问:
AWS EC2 LAMP Vhosts all point to same folder
I would like to have multiple domains going to the same EC2 instance. All will have same IP. I have setup multiple vhost files as domain1.com and domain2.com. I do not have anything special in any htaccess files or in the vhost files. I have the domains through GoDaddy, they are pointed to the EC2 IP. The issue I have is that both domain 1 and 2 go to the same folder and show the same index.html in the browser.

As per https://help.ubuntu.com/lts/serverguide/httpd.html I see that httpd.conf does not exist anymore and I do not see anything in apache2.conf for ghosts.

(As you can see the commented out things I have tried)

* NOT using rout 53, I do not want to use this, unless I have too*

vhost files:

(domain 1)

```<code>#SSLStaplingCache shmcb:/tmp/stapling_cache(128000)
SSLStaplingCache shmcb:${APACHE_RUN_DIR}/ssl_stapling_cache(128000)
<VirtualHost *:80>
    ServerAdmin me@localhost
    ServerName domain1.com
    ServerAlias www.domain1.com
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/html>
    Options Indexes FollowSymLinks

    AllowOverride All
    Require all granted
</Directory>

SSLUseStapling on
RewriteEngine on
#RewriteRule domain1.com\/$ http://domain1.com [NC]
RewriteCond %{SERVER_NAME} =domain1.com [OR]
RewriteCond %{SERVER_NAME} =domain1.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

</VirtualHost>
</code>```

(domain 2)

```<code><VirtualHost *:80>
ServerAdmin me@gmail.com
ServerName domain2.com
ServerAlias www.domain2.com
DocumentRoot /var/www/html/domain2.com
#    ServerPath "/domain2.com/"
#    RewriteEngine On
#    RewriteRule "^(/domain2.com/.*)" "/html/domain2.com$1"
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/html/domain2.com>
  Options Indexes FollowSymLinks

 AllowOverride All
 Require all granted
</Directory>
#RewriteEngine on
#RewriteRule domain2.com\/$ http://domain2.com/index.php [NC]
</VirtualHost>
</code>```

default-ssl.conf file:

```<code><IfModule mod_ssl.c>
    <VirtualHost _default_:443>
            ServerAdmin me8@gmail.com
            ServerName domain1.com

            DocumentRoot /var/www/html/domain1.com
</code>```

*********** EDIT ****************

```<code>apache2 -v
Server version: Apache/2.4.18 (Ubuntu)
Server built:   2017-09-18T15:09:02
sudo apachectl configtest
Syntax OK
</code>```

I have completed "sudo a2ensite" command on vhost files and restarted apache after them

******* EDIT ****************

in hosts:

```<code>127.0.0.1 localhost
127.0.1.1 domain1.com
127.0.1.2 domain2.com
</code>```

答:
You should provide more details:
What Instance/LAMP are you using?
Are you configuring vhost correctly?

For Bitnami stacks, for example, you should add the correct add the following line to the end of /opt/bitnami/apache2/conf/bitnami/bitnami-apps-vhosts.conf:
Include "/path to your configuration file.conf”

restart apache:
$sudo /opt/bitnami/ctlscript.sh restart apache

For plain Ubuntu,(after having apache installed) you should include your configuration file as below:
/etc/apache2/sites-available/example.com.conf

ensure to enable your virtual host file:
$sudo a2ensite example.com.conf

restart apache:
$sudo service apache2 restart

Body:
I would like to have multiple domains going to the same EC2 instance. All will have same IP. I have setup multiple vhost files as domain1.com and domain2.com. I do not have anything special in any htaccess files or in the vhost files. I have the domains through GoDaddy, they are pointed to the EC2 IP. The issue I have is that both domain 1 and 2 go to the same folder and show the same index.html in the browser.

As per https://help.ubuntu.com/lts/serverguide/httpd.html I see that httpd.conf does not exist anymore and I do not see anything in apache2.conf for ghosts.

(As you can see the commented out things I have tried)

* NOT using rout 53, I do not want to use this, unless I have too*

vhost files:

(domain 1)

#SSLStaplingCache shmcb:/tmp/stapling_cache(128000)
SSLStaplingCache shmcb:${APACHE_RUN_DIR}/ssl_stapling_cache(128000)
<VirtualHost *:80>
    ServerAdmin me@localhost
    ServerName domain1.com
    ServerAlias www.domain1.com
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/html>
    Options Indexes FollowSymLinks

    AllowOverride All
    Require all granted
</Directory>

SSLUseStapling on
RewriteEngine on
#RewriteRule domain1.com\/$ http://domain1.com [NC]
RewriteCond %{SERVER_NAME} =domain1.com [OR]
RewriteCond %{SERVER_NAME} =domain1.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

</VirtualHost>

(domain 2)

<VirtualHost *:80>
ServerAdmin me@gmail.com
ServerName domain2.com
ServerAlias www.domain2.com
DocumentRoot /var/www/html/domain2.com
#    ServerPath "/domain2.com/"
#    RewriteEngine On
#    RewriteRule "^(/domain2.com/.*)" "/html/domain2.com$1"
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/html/domain2.com>
  Options Indexes FollowSymLinks

 AllowOverride All
 Require all granted
</Directory>
#RewriteEngine on
#RewriteRule domain2.com\/$ http://domain2.com/index.php [NC]
</VirtualHost>

default-ssl.conf file:

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
            ServerAdmin me8@gmail.com
            ServerName domain1.com

            DocumentRoot /var/www/html/domain1.com

*********** EDIT ****************

apache2 -v
Server version: Apache/2.4.18 (Ubuntu)
Server built:   2017-09-18T15:09:02
sudo apachectl configtest
Syntax OK

I have completed "sudo a2ensite" command on vhost files and restarted apache after them

******* EDIT ****************

in hosts:

127.0.0.1 localhost
127.0.1.1 domain1.com
127.0.1.2 domain2.com


来源: stackexchange

问:
Incorrect usage of stategy pattern?
Is the following an incorrect usage of the strategy

```<code>interface FilterStrategy {
  public void filter();
}

class OldProductsStrategy implements FilterStrategy {
  public filter();
}

class NewProductsStrategy implements FilterStrategy {
  public filter();
}

class ProductsFilterStrategy {
  public getFilter(a) {
   if(a) {
     return new NewProductsStrategy();
   } else {
     return new OldProductsStrategy();
   }
}

class Client {
  new ProductsFilterStrategy().getFilter(true).filter();
}
</code>```

Is delegating the selection of the strategy implementation part of the strategy pattern?

答: The usage is fine. But technically  the class which is responsible of creating different instances is a factory. Not part of the strategy pattern.</p>

ContentLicense: CC BY-SA 3.0

Title: Incorrect usage of stategy pattern?

Body:
Is the following an incorrect usage of the strategy

interface FilterStrategy {
  public void filter();
}

class OldProductsStrategy implements FilterStrategy {
  public filter();
}

class NewProductsStrategy implements FilterStrategy {
  public filter();
}

class ProductsFilterStrategy {
  public getFilter(a) {
   if(a) {
     return new NewProductsStrategy();
   } else {
     return new OldProductsStrategy();
   }
}

class Client {
  new ProductsFilterStrategy().getFilter(true).filter();
}

Is delegating the selection of the strategy implementation part of the strategy pattern?


问:
Why is vertical-align: middle not working on my span or div?
I'm trying to vertically center a span or div element within another div element. However when I put vertical-align: middle, nothing happens. I've tried changing the display properties of both elements, and nothing seems to work.

This is what I'm currently doing in my webpage:

.main {
  height: 72px;
  vertical-align: middle;
  border: 1px solid black;
  padding: 2px;
}

.inner {
  vertical-align: middle;
  border: 1px solid red;
}

.second {
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="inner">
    This box should be centered in the larger box
    <div class="second">Another box in here</div>
  </div>
</div></code>```

Here is a jsfiddle of the implementation showing that it doesn't work: http://jsfiddle.net/gZXWC/

答:
I used this to align everything in the center of the wrapper div in case it helps anyone - I found it simplest:

div.wrapper {
  /* --- This works --- */
  display: flex;
  /* Align Vertically */
  align-items: center;
  /* Align Horizontally */
  justify-content: center;
  /* --- ---------- ----- */
  width: 100%;
  height:100px;
  background-color: blue;
}
div.inner {
  width: 50px;
  height: 50px;
  background-color: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="inner">
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to vertically center a span or div element within another div element. However when I put vertical-align: middle, nothing happens. I've tried changing the display properties of both elements, and nothing seems to work.

This is what I'm currently doing in my webpage:

.main {
  height: 72px;
  vertical-align: middle;
  border: 1px solid black;
  padding: 2px;
}

.inner {
  vertical-align: middle;
  border: 1px solid red;
}

.second {
  border: 1px solid blue;
}

    This box should be centered in the larger box

Another box in here

Here is a jsfiddle of the implementation showing that it doesn't work: http://jsfiddle.net/gZXWC/

Body:
I used this to align everything in the center of the wrapper div in case it helps anyone - I found it simplest:

div.wrapper {
  /* --- This works --- */
  display: flex;
  /* Align Vertically */
  align-items: center;
  /* Align Horizontally */
  justify-content: center;
  /* --- ---------- ----- */
  width: 100%;
  height:100px;
  background-color: blue;
}
div.inner {
  width: 50px;
  height: 50px;
  background-color: orange;
}

<div class="wrapper">
  <div class="inner">
  </div>
</div>


问:
Getting Chrome to accept self-signed localhost certificate
I have created a self-signed SSL certificate for the localhost CN. Firefox accepts this certificate after initially complaining about it, as expected. Chrome and IE, however, refuse to accept it, even after adding the certificate to the system certificate store under Trusted Roots. Even though the certificate is listed as correctly installed when I click "View certificate information" in Chrome's HTTPS popup, it still insists the certificate cannot be trusted.

What am I supposed to do to get Chrome to accept the certificate and stop complaining about it?

答: Assuming you're on Mac OSX, you can also just open the URL in question in Safari; say; https://localhost:8080/css/app.css, allow the cert. Re-start Chrome, and it will work.        </p>


问:
Orafce install in postgresql 9.5
I am new to programmer world so i want to learn so many things, and about what i want to ask, can i install orafce in postgresql? I mean all the tutorial always show use BigSql but iam using from enterprise DB. I am already try take orafce.dll from bigsql but it can't read because not specified procedure.

ERROR:  could not load library "C:/Program Files/PostgreSQL/9.5/lib/orafce.dll": The specified procedure could not be found.

and i already try from other source but still got some error

```<code>ERROR:  could not find function "plvlex_tokens" in file "C:/Program Files/PostgreSQL/9.5/lib/orafce.dll"
</code>```

答: It was a bug in Orafce windows build. Should be fixed by last build.</p>

Title: Orafce install in postgresql 9.5

Body:
I am new to programmer world so i want to learn so many things, and about what i want to ask, can i install orafce in postgresql? I mean all the tutorial always show use BigSql but iam using from enterprise DB. I am already try take orafce.dll from bigsql but it can't read because not specified procedure.

ERROR:  could not load library "C:/Program Files/PostgreSQL/9.5/lib/orafce.dll": The specified procedure could not be found.

and i already try from other source but still got some error

ERROR:  could not find function "plvlex_tokens" in file "C:/Program Files/PostgreSQL/9.5/lib/orafce.dll"


问:
Tell a web programmer how to write a very very simple GUI program
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

```<code>if(a>5 || b>3) { final = 4; }
else if ...
</code>```

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?

答: For windows you can consider C#, The visual studio express editions are fee. All you need are a couple of text boxes and buttons etc. And if you know java, doing a bit of Dot Netting should be very trivial. I am also a java guy and i do a bit of c# for personal utils etc because they are so similar.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

if(a>5 || b>3) { final = 4; }
else if ...

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?


问:
How to split a string and get only segament after the question mark
how do you split a string and get the sentence only after the question mark. For example say you have the line : hello?myNameIs...

 how could you only get what's after the question mark

 many thanks

答:
try this one</p>

```<code>String sArray[]  = src.split(Pattern.quote("?"));
</code>```

Body:
try this one

String sArray[]  = src.split(Pattern.quote("?"));


问:
best way to concatenate scope results
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

```<code>scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')
</code>```

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

```<code>def self.with_something_data_first
  has_something + has_no_something
end
</code>```

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

```<code>Model.with_something_data_first.order(:created_at).reverse_order.limit(20)
</code>```

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

答:
The problem with that is when you concatenate the two scopes, you get an array, not an Active Record anymore, so you can't use order. Don't know if it's the best approach, but you can make a new query from the ids in the order you got. That would be something like:

```<code>def self.with_something_data_first
  YourModel.find((has_something + has_no_something).map{|o| o.id})
end
</code>```

Like this, you can apply an order method on that, since you're gonna have an Active Record Relation, and it respect the order of the objects you established before. Hope this helps!

Title: best way to concatenate scope results

Body:
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

def self.with_something_data_first
  has_something + has_no_something
end

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

Model.with_something_data_first.order(:created_at).reverse_order.limit(20)

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

Body:
The problem with that is when you concatenate the two scopes, you get an array, not an Active Record anymore, so you can't use order. Don't know if it's the best approach, but you can make a new query from the ids in the order you got. That would be something like:

def self.with_something_data_first
  YourModel.find((has_something + has_no_something).map{|o| o.id})
end

Like this, you can apply an order method on that, since you're gonna have an Active Record Relation, and it respect the order of the objects you established before. Hope this helps!


问:
angular using @output to sent data from child to parent component
I have some data that I am passing from my child to parent component and I want it to check if its empty or it has some value inside automatically.

this is in my login.compunent.ts - child ts

```<code>@Output() update=new EventEmitter<string>();
userEmail = "a@b.com";
authUser(loginForm) {
      this.update.emit(userEmail);
      this.router.navigate(['/home']);
  }
</code>```

this is in my app.compunent.ts - parent ts

```<code>  emailData:string;

  onUpdate(userEmail:string){
    console.log("userEmail")
    if(userEmail !== ''){
      this.emailData = userEmail
      console.log(userEmail)
    }
  }
</code>```

this is in my app.compunent.html - parernt html

```<code>{{emailData}}
<router-outlet (update)="onUpdate($event)"></router-outlet>
</code>```

答:
I'm not sure I understand you completely but if you want to pass data from your child to your parent "automatically" I believe you have to implement a two-way bindable property.

You do that like this

child.ts

```<code>export class SomeComponent  {
  ...
     @Input() something;
     // it's important to name it with the 'Change' suffix
     @Output() somethingChange = new EventEmitter();
  ...
</code>```

parent.html

```<code><some-component [(something)] = "someFieldYouWantToTwoWayBindTo"></some-component>
</code>```

now whenever you update something from your child the field someFieldYouWantToTwoWayBindTo will also be updated

Now if you want to check what's in something and only filter certain cases then implement a setter for someFieldYouWantToTwoWayBindTo

parent.ts

```<code>_someFieldYouWantToTwoWayBindTo
set someFieldYouWantToTwoWayBindTo(value) {
    if(value !== '')
      this._someFieldYouWantToTwoWayBindTo = value;

}
</code>```

Body:
I have some data that I am passing from my child to parent component and I want it to check if its empty or it has some value inside automatically.

this is in my login.compunent.ts - child ts

@Output() update=new EventEmitter<string>();
userEmail = "a@b.com";
authUser(loginForm) {
      this.update.emit(userEmail);
      this.router.navigate(['/home']);
  }

this is in my app.compunent.ts - parent ts

  emailData:string;

  onUpdate(userEmail:string){
    console.log("userEmail")
    if(userEmail !== ''){
      this.emailData = userEmail
      console.log(userEmail)
    }
  }

this is in my app.compunent.html - parernt html

{{emailData}}
<router-outlet (update)="onUpdate($event)"></router-outlet>

Body:
I'm not sure I understand you completely but if you want to pass data from your child to your parent "automatically" I believe you have to implement a two-way bindable property.

You do that like this

child.ts

export class SomeComponent  {
  ...
     @Input() something;
     // it's important to name it with the 'Change' suffix
     @Output() somethingChange = new EventEmitter();
  ...

parent.html

<some-component [(something)] = "someFieldYouWantToTwoWayBindTo"></some-component>

now whenever you update something from your child the field someFieldYouWantToTwoWayBindTo will also be updated

Now if you want to check what's in something and only filter certain cases then implement a setter for someFieldYouWantToTwoWayBindTo

parent.ts

_someFieldYouWantToTwoWayBindTo
set someFieldYouWantToTwoWayBindTo(value) {
    if(value !== '')
      this._someFieldYouWantToTwoWayBindTo = value;

}


问:
Adding New Table Entity Framwork Code First Approach
That solution does not work in .net core 2 tied to SQL Server 2016.  Original Question: Trying to jump into entity framework, using the "Code First Approach".   I have my new class setup “NewTable” shown below.    I can’t figure out what in the Program Manger Console I need to type to get this table created in my Default Connection String (pointing to a local instance of Sql Server 2016).   The database is working and the user in this .net core 2 web app can register his/her name then log in using that new created account.   Thanks in advance!!

Default Connection String:

"ConnectionStrings": {
  "DefaultConnection" "Server=localhost\RCDSE_Dev;Database=Some Database;User ID=sa;Password=SomePass;"
},

```<code>[Table("NewTable")]
public class NewTable
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Database generated key
    [Key] //Primary Key
    public long Id { get; set; }

    [Required]
    public string Manager { get; set; }
}

public class NewTableContext : DbContext
{
    public DbSet<NewTable> NewTables{ get; set; }
}
</code>```

答: I figured this out.  Will post a detailed step by step guide for others in the next couple of days.   There are specific things that need to be done in .net core 2 project file that were NOT COVERED in any of the referenced examples by users here.   Thanks for all the help..it got me somewhat pointed in a direction, to find the right direction...lol.</p>

Body:
That solution does not work in .net core 2 tied to SQL Server 2016.  Original Question: Trying to jump into entity framework, using the "Code First Approach".   I have my new class setup “NewTable” shown below.    I can’t figure out what in the Program Manger Console I need to type to get this table created in my Default Connection String (pointing to a local instance of Sql Server 2016).   The database is working and the user in this .net core 2 web app can register his/her name then log in using that new created account.   Thanks in advance!!

Default Connection String:

"ConnectionStrings": {
  "DefaultConnection" "Server=localhost\RCDSE_Dev;Database=Some Database;User ID=sa;Password=SomePass;"
},

[Table("NewTable")]
public class NewTable
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Database generated key
    [Key] //Primary Key
    public long Id { get; set; }

    [Required]
    public string Manager { get; set; }
}

public class NewTableContext : DbContext
{
    public DbSet<NewTable> NewTables{ get; set; }
}


问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
You can add one line:

```<code>studlistGrouped.values().forEach(list -> list.sort(Comparator.comparing(Student::getId)));
</code>```

Or you can write your own collector.

I know which one I would choose.

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
You can add one line:

studlistGrouped.values().forEach(list -> list.sort(Comparator.comparing(Student::getId)));

Or you can write your own collector.

I know which one I would choose.


问:
creating a listener that merge all finder windows
I want that every time I open a new folder it will automatically merge with the others finder's windows that are already opened. Basically one folder with n tabs.
I already use the command Finder> Window > Merge All Windows but I wish it was automatic.

All I can do is create an automation for merging the windows but it isn't automatic

```<code>tell application "Finder"
    activate
    tell application "System Events"
        tell process "Finder"
            click menu item "Merge All Windows" of menu "Window" of menu bar 1
        end tell
    end tell
end tell
</code>```

答: In addition to "Open folders in tabs instead of new windows" you might need to set View->Show tab bar, it does help for some cases, but still not always</p>

Body:
I want that every time I open a new folder it will automatically merge with the others finder's windows that are already opened. Basically one folder with n tabs.
I already use the command Finder> Window > Merge All Windows but I wish it was automatic.

All I can do is create an automation for merging the windows but it isn't automatic

tell application "Finder"
    activate
    tell application "System Events"
        tell process "Finder"
            click menu item "Merge All Windows" of menu "Window" of menu bar 1
        end tell
    end tell
end tell


问:
Finding filenames with specific string in a shell script
I am trying to write a bash script to do a batch processing of some fMRI data. My problem is that I am not able to get the filenames that match a specific pattern within the directory of interest.

My scripts looks like this

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

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=$find `$inputpath` -name *mprage

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'
</code>```

The only output that I get is the following error message

```<code>-name: command not found
</code>```

I am definetely not familiar with shell scripting so I am sorry if the question may sound trivial.
Any help will be much appreciated.

Antonio

EDIT:: SOLVED

Exploring the suggestions I found the correct way to make it running with no errors

```<code>anatomical_scans=$(find $input_path -name "*mprage*")
</code>```

Thanks

答:
try changing the line

anatomical_scans=$find$inputpath-name *mprage

to

```<code>anatomical_scans=$(find "${inputpath}" -name "*mprage")
</code>```

Body:
I am trying to write a bash script to do a batch processing of some fMRI data. My problem is that I am not able to get the filenames that match a specific pattern within the directory of interest.

My scripts looks like this

#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=$find `$inputpath` -name *mprage

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'

The only output that I get is the following error message

-name: command not found

I am definetely not familiar with shell scripting so I am sorry if the question may sound trivial.
Any help will be much appreciated.

Antonio

EDIT:: SOLVED

Exploring the suggestions I found the correct way to make it running with no errors

anatomical_scans=$(find $input_path -name "*mprage*")

Thanks

Body:
try changing the line

anatomical_scans=$find$inputpath-name *mprage

to

anatomical_scans=$(find "${inputpath}" -name "*mprage")


问:
Are there any ways to convert a symmetric weight matrix into undirected weighted graph without looping?
From a particular dataset I obtained the pandas dataframe object and calculated the correlations between columns of this df.

The next step is to move from this correlation matrix to a weighted graph, where weights are taken from this matrix.

Since I have about 100 datasets that are big enough, I would prefer not to use looping for this purpose (or do it in a smart way).

The main problem with the command "stack()" is that the graph becomes directed, it includes both edges [(x,y):weight0] and [(y,x):weight0]. I would like to get rid of those duplicates. Here is my code so far:

```<code>import pandas as pd
import numpy as np
import networkx as nx

df1 = df1.corr()
links = df1.stack().reset_index()
links.columns = ['var1', 'var2','value']
links = links.loc[(links['var1'] != links['var2'])]
G = nx.from_pandas_dataframe(links, 'var1', 'var2', 'value')
</code>```

答:
You can go more directly from the correlation dataframe (which is really just a square numpy array with the trim of a) to networkx:

```<code>correlation_matrix = df1.corr().values
G = nx.from_numpy_matrix(correlation_matrix,create_using=nx.DiGraph())
</code>```

if you want to make the diagonal 0 before making the graph insert the following code between the two lines above, noting that np.fill_diagonal works in-place:

```<code>import numpy as np
np.fill_diagonal(correlation_matrix, 0)
</code>```

Body:
From a particular dataset I obtained the pandas dataframe object and calculated the correlations between columns of this df.

The next step is to move from this correlation matrix to a weighted graph, where weights are taken from this matrix.

Since I have about 100 datasets that are big enough, I would prefer not to use looping for this purpose (or do it in a smart way).

The main problem with the command "stack()" is that the graph becomes directed, it includes both edges [(x,y):weight0] and [(y,x):weight0]. I would like to get rid of those duplicates. Here is my code so far:

import pandas as pd
import numpy as np
import networkx as nx

df1 = df1.corr()
links = df1.stack().reset_index()
links.columns = ['var1', 'var2','value']
links = links.loc[(links['var1'] != links['var2'])]
G = nx.from_pandas_dataframe(links, 'var1', 'var2', 'value')

Body:
You can go more directly from the correlation dataframe (which is really just a square numpy array with the trim of a) to networkx:

correlation_matrix = df1.corr().values
G = nx.from_numpy_matrix(correlation_matrix,create_using=nx.DiGraph())

if you want to make the diagonal 0 before making the graph insert the following code between the two lines above, noting that np.fill_diagonal works in-place:

import numpy as np
np.fill_diagonal(correlation_matrix, 0)


问:
How to update firebase-query after user login
Using polymer and firebase I have some data that is only accessible by logged users. But, when the user login in the application the data isn't automatically updated.

An easily workaround is force the page reload with location.reload(). But, I'm trying to discover how to update these values without having to reload the entire application. Any ideas?

Expected outcome:

When user logins all fibase-document and firebase-query updates the synced data.

Actual outcome:

These elements doesn't update and the user has to reload the page

Example:

Element: app-auth.html

```<code><firebase-app
  id="firebaseApp"
  auth-domain="app.firebaseapp.com"
  database-url="https://app.firebaseio.com"
  storage-bucket="app.appspot.com"
  api-key="api"
  messaging-sender-id="id"
 ></firebase-app>

<firebase-auth id="auth"
  signed-in="{{isUserLogged}}"
  user="{{user}}"
  on-error="_onAuthError"
  log
></firebase-auth>

login(credentials) {
    if (credentials.provider === 'email') {
      this.$.auth.signInWithEmailAndPassword(credentials.params.email, credentials.params.password)
        .catch(e => {
          if (e.code === 'auth/user-not-found') {
            this.$.auth.createUserWithEmailAndPassword(credentials.params.email, credentials.params.password)
              .then(this._successfulLogin());
          }
        })
        .then(this._successfulLogin());
      this.password = null;

    } else {
      this.$.auth.signInWithPopup(credentials.provider);
    }
  }
</code>```

app-contents.html:

```<code>   <firebase-query
        data="{{contents}}"
        path="/contents"
    ></firebase-query>

    <div class="card">
        <h1>Contents:</h1>
        <template is="dom-repeat" items="[[contents]]" as="content">
            <app-content-preview="[[content]]"></app-content-preview>
        </template>
    </div>
</template>
</code>```

The contents element shows questionnaires the user has to answer in order to complete the goal of the app. But, the questionnaires can only be accessed by logged users. I would like to, when user logins in the app-auth, process his identity and update the firebase-query that shows the questionnaires he has to answer

答:
Actually should read the data at query (due to your firebase datababase rule. (if you allow read for all, but write on logged in ) something like in database rules;

```<code>"rules": {
    ".read": true,
    ".write": "auth != null"
     }
</code>```

But in case let says read need also auth !=null than, lets change your code like:

```<code> <firebase-query
        data="{{contents}}"
        path="{{pathContents}}"
    ></firebase-query>
</code>```

and define an observer like

```<code>static get observers() {
        return ['_isUserLogged(user)']

   _isUserLogged(user) {
      if (user) {
        this.set('pathContents', 'contents');
      }
   }
</code>```

this observer will check user is exist or not. And if exist than the path will be defined as contents than query element will fire again automatically.
Hope this will work :)

Another js options is;

```<code>_isUserLogged(user) {
          if (user) {
            var db = firebase.database();
            db.ref('contents').on('value', snapshot=>{
             if (snapshot.exists()) {  //To check that you have a data
                 this.set('contents', snapshot.val() );
             }
            })
          }
       }
</code>```

Please not: if you read database with above code, than you do not need firebase-query element. So, delete it.

Body:
Using polymer and firebase I have some data that is only accessible by logged users. But, when the user login in the application the data isn't automatically updated.

An easily workaround is force the page reload with location.reload(). But, I'm trying to discover how to update these values without having to reload the entire application. Any ideas?

Expected outcome:

When user logins all fibase-document and firebase-query updates the synced data.

Actual outcome:

These elements doesn't update and the user has to reload the page

Example:

Element: app-auth.html

<firebase-app
  id="firebaseApp"
  auth-domain="app.firebaseapp.com"
  database-url="https://app.firebaseio.com"
  storage-bucket="app.appspot.com"
  api-key="api"
  messaging-sender-id="id"
 ></firebase-app>

<firebase-auth id="auth"
  signed-in="{{isUserLogged}}"
  user="{{user}}"
  on-error="_onAuthError"
  log
></firebase-auth>

login(credentials) {
    if (credentials.provider === 'email') {
      this.$.auth.signInWithEmailAndPassword(credentials.params.email, credentials.params.password)
        .catch(e => {
          if (e.code === 'auth/user-not-found') {
            this.$.auth.createUserWithEmailAndPassword(credentials.params.email, credentials.params.password)
              .then(this._successfulLogin());
          }
        })
        .then(this._successfulLogin());
      this.password = null;

    } else {
      this.$.auth.signInWithPopup(credentials.provider);
    }
  }

app-contents.html:

   <firebase-query
        data="{{contents}}"
        path="/contents"
    ></firebase-query>

Contents:

        <template is="dom-repeat" items="[[contents]]" as="content">
            <app-content-preview="[[content]]"></app-content-preview>
        </template>

</template>

The contents element shows questionnaires the user has to answer in order to complete the goal of the app. But, the questionnaires can only be accessed by logged users. I would like to, when user logins in the app-auth, process his identity and update the firebase-query that shows the questionnaires he has to answer

Body:
Actually should read the data at query (due to your firebase datababase rule. (if you allow read for all, but write on logged in ) something like in database rules;

"rules": {
    ".read": true,
    ".write": "auth != null"
     }

But in case let says read need also auth !=null than, lets change your code like:

 <firebase-query
        data="{{contents}}"
        path="{{pathContents}}"
    ></firebase-query>

and define an observer like

static get observers() {
        return ['_isUserLogged(user)']

   _isUserLogged(user) {
      if (user) {
        this.set('pathContents', 'contents');
      }
   }

this observer will check user is exist or not. And if exist than the path will be defined as contents than query element will fire again automatically.
Hope this will work :)

Another js options is;

_isUserLogged(user) {
          if (user) {
            var db = firebase.database();
            db.ref('contents').on('value', snapshot=>{
             if (snapshot.exists()) {  //To check that you have a data
                 this.set('contents', snapshot.val() );
             }
            })
          }
       }

Please not: if you read database with above code, than you do not need firebase-query element. So, delete it.


问:
Tkinter name "X" is not defined error.
I am trying to take a more object oriented approach by using classes, but I seem to be getting the following error.

Traceback (most recent call last):   File "./Main.py", line 17, in

      Main = Menu(root)   File "./Main.py", line 11, in init
      self.F1.pack(fill=X) NameError: global name 'X' is not defined

Here is the code I am trying to compile, I have broken it down to a simple snippet to show the error I am getting:

```<code>#!/usr/bin/python

import Tkinter as tk # Python 2 import

class Menu:
    def __init__(self, parent):
        self.root = parent
        self.root.geometry("800x400")
        self.root.title("Image Compression")
        self.F1 = tk.Frame(self.root, bg="black")
        self.F1.pack(fill=X)

if __name__ == "__main__":
    root = tk.Tk()
    Main = Menu(root)
    root.mainloop()
</code>```

答:
Your

```<code>self.F1.pack(fill=X)
</code>```

should be

```<code>self.F1.pack(fill=tk.X)
</code>```

and you should also add expand=True to make the fill actually work.
Tkinter.X and Tkinter.Y and Tkinter.BOTH are constants (strings) that are defined in the Tkinter module. Without the Tkinter., you are trying to access X as a variable.
Your line should read

```<code>self.F1.pack(fill=tk.X, expand=True)
</code>```

to do what you want it to do.

Oh, one more afterthought... You may be thinking, "Hey! I've seen .pack(fill=X) working before!" This is true when there is a

```<code>from Tkinter import *
</code>```

statement above the reference. Then, in that instance, X would be found as coming from Tkinter but without needing the leading Tkinter.. That's the topic of namespace, which is beyond the scope of this answer.

Title: Tkinter name "X" is not defined error.

Body:
I am trying to take a more object oriented approach by using classes, but I seem to be getting the following error.

Traceback (most recent call last):   File "./Main.py", line 17, in

      Main = Menu(root)   File "./Main.py", line 11, in init
      self.F1.pack(fill=X) NameError: global name 'X' is not defined

Here is the code I am trying to compile, I have broken it down to a simple snippet to show the error I am getting:

#!/usr/bin/python

import Tkinter as tk # Python 2 import

class Menu:
    def __init__(self, parent):
        self.root = parent
        self.root.geometry("800x400")
        self.root.title("Image Compression")
        self.F1 = tk.Frame(self.root, bg="black")
        self.F1.pack(fill=X)

if __name__ == "__main__":
    root = tk.Tk()
    Main = Menu(root)
    root.mainloop()

Body:
Your

self.F1.pack(fill=X)

should be

self.F1.pack(fill=tk.X)

and you should also add expand=True to make the fill actually work.
Tkinter.X and Tkinter.Y and Tkinter.BOTH are constants (strings) that are defined in the Tkinter module. Without the Tkinter., you are trying to access X as a variable.
Your line should read

self.F1.pack(fill=tk.X, expand=True)

to do what you want it to do.

Oh, one more afterthought... You may be thinking, "Hey! I've seen .pack(fill=X) working before!" This is true when there is a

from Tkinter import *

statement above the reference. Then, in that instance, X would be found as coming from Tkinter but without needing the leading Tkinter.. That's the topic of namespace, which is beyond the scope of this answer.


问:
R -- mean function of column section
I am trying to include a mean calculation as part of a larger code. The idea is to calculate the mean from a series of values within a column, but not all the column.

For example, from column_x (10 entries) in yFile, calculate the mean of the last 4 values:

```<code>column_x
1
5
8
3
0
3
3
7
9
9

Result = 7
</code>```

This is what I've got:

```<code>avg_subx <- mean(yFile$column_x, 7:10, trim = 0, na.rm = FALSE)
</code>```

But for some reason, the result I am getting back is not the correct value.
Could you help me finding out where I'm going wrong?

Thanks!

答:
have you tried with tail function? With tail you can select the last n values of a data frame or a vector.

example:

```<code>avg_subx <- mean(tail(yFile$column_x,4))
</code>```

In this case you're selecting the las 4 values.

Hope this can help you!

Title: R -- mean function of column section

Body:
I am trying to include a mean calculation as part of a larger code. The idea is to calculate the mean from a series of values within a column, but not all the column.

For example, from column_x (10 entries) in yFile, calculate the mean of the last 4 values:

column_x
1
5
8
3
0
3
3
7
9
9

Result = 7

This is what I've got:

avg_subx <- mean(yFile$column_x, 7:10, trim = 0, na.rm = FALSE)

But for some reason, the result I am getting back is not the correct value.
Could you help me finding out where I'm going wrong?

Thanks!

Body:
have you tried with tail function? With tail you can select the last n values of a data frame or a vector.

example:

avg_subx <- mean(tail(yFile$column_x,4))

In this case you're selecting the las 4 values.

Hope this can help you!


问:
Reactstrap Card component throws error
The issue is with the reactstrap cards: https://reactstrap.github.io/components/card/

Using reactstrap components like Card, etc is not working.

Component: Version I

```<code>import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;
</code>```

Output: *It works fine without any errors.

But when I try to use the rest of the components from reactstrap. It throws errors on console.

Component: Version II

```<code>import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                    <CardBody>
                        <CardTitle>Card title</CardTitle>
                        <CardSubtitle>Card subtitle</CardSubtitle>
                        <CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
                        <Button>Button</Button>
                    </CardBody>
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;
</code>```

Output:

package.json

```<code>{
  "name": "client",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-transition-group": "^2.2.1",
    "reactstrap": "^4.8.0",
    "redux": "^3.7.2",
    "redux-promise": "^0.5.3"
  }
}
</code>```

I am not able to debug this issue. Please help! TIA.

答:
This looks like a typo here:

```<code>renderMovies() {
        return _.map(this.props.movies, movie => {
</code>```

Missing )

Try

```<code>_.map(this.props.movies, movie) => {
</code>```

If that doesn't do it, put console.log() after everything to see where it becomes undefined.

This type of error usually results from something not being exported correctly or something being null/undefined due to data missing, etc.

This is a good opportunity for me to recommend using ES Lint, so you can gain extra help 24/7 from the passive display of errors. Check it out if you aren't using it. It's absolutely worth looking into and using.

I won't recommend any specific linting configs in here. That is out of scope of this help. ES Lint will underline code errors such as the missing ) with a red underline, so you will experience less of this kind of thing :)

Title: Reactstrap Card component throws error

Body:
The issue is with the reactstrap cards: https://reactstrap.github.io/components/card/

Using reactstrap components like Card, etc is not working.

Component: Version I

import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;

Output: *It works fine without any errors.

But when I try to use the rest of the components from reactstrap. It throws errors on console.

Component: Version II

import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                    <CardBody>
                        <CardTitle>Card title</CardTitle>
                        <CardSubtitle>Card subtitle</CardSubtitle>
                        <CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
                        <Button>Button</Button>
                    </CardBody>
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;

Output:

package.json

{
  "name": "client",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-transition-group": "^2.2.1",
    "reactstrap": "^4.8.0",
    "redux": "^3.7.2",
    "redux-promise": "^0.5.3"
  }
}

I am not able to debug this issue. Please help! TIA.

Body:
This looks like a typo here:

renderMovies() {
        return _.map(this.props.movies, movie => {

Missing )

Try

_.map(this.props.movies, movie) => {

If that doesn't do it, put console.log() after everything to see where it becomes undefined.

This type of error usually results from something not being exported correctly or something being null/undefined due to data missing, etc.

This is a good opportunity for me to recommend using ES Lint, so you can gain extra help 24/7 from the passive display of errors. Check it out if you aren't using it. It's absolutely worth looking into and using.

I won't recommend any specific linting configs in here. That is out of scope of this help. ES Lint will underline code errors such as the missing ) with a red underline, so you will experience less of this kind of thing :)


问:
Oracle: export a table with blobs to an .sql file that can be imported again
I have a table "Images" with two fields:

Name VARCHAR2

Data BLOB

I would like to export that table to a .sql file which I could import on another system. I tried to do so using the "Database unload" assistant of Oracle SQL Developer. However the generated file does just have the content for the names in it but not the data. Thus after importing I would end up with all the names but the data field would be null everywhere.

I'd really prefer it just to be one file (I saw some examples that included dumping the data to one file per field on the fs...)

Is it possible to generate such a script with SQL Developer? or is there any other way/tool to do so?

答:
This is definitely possible in SQL developer.

First you need to export the table in the source location choosing
appropriate table(s).

Tools > Database Export

Select output format as loader  rather than insert , excel which we
normally use.

Following these steps would create sqlldr control files and data files and also the create table ddl if you chose the option.You can use them to import(sqlldr) data in the destination.

This is a better solution and is portable in terms of extraction and distribution . It gives the flexibility of delivering components to be deployed through code repositories.

Here is a link that explains it step by step.

Exporting Multiple BLOBs with Oracle SQL Developer


问:
Encryption Algorithm
I am creating an application which uses a steganography algorithm. Now I can encrypt and decrypt text. But I want my application to ask for password after encrypting the text into the image, so that whenever someone will decrypt the image it would ask for the password for authentication. Is this even possible? If yes, how?</p>

答:
Decrypt the text with a symmetric cypher like AES. To get the encryption key use a password based key derivation function (such as PBKDF2) on the password the user entered.

Then hide the encrypted text in your image using steganography.

Title: Encryption Algorithm


问:
Decode JSON Data on Swift 4 returns nil
I'm trying to decode my json data with below function. I had different Json format at first and It was working but whenI change json format, It started not to work. I try to do changes also in Structure code but nothing worked. What Am I missing? (Code is for first Json format so It needs to be work on second format too)

First JSON:

```<code>{
"status": 200,
"results": [
    {
        "group_matched": false,
        "distance_mi": 4,
        "content_hash": "1rT2lirUapfrYIYxSR2u0GtmRSLPsVki9kFj4ugs8JIq6",
        "common_friends": [],
        "common_likes": [],
        "common_friend_count": 0,
        "common_like_count": 0,
        "connection_count": 0,
        "_id": "5a2805ba779f34267d32d8b0",
        "bio": "",
            "birth_date": "1997-12-09T16:28:29.761Z",
            "name": "John",
        },
</code>```

Second JSON:

```<code>{
    "meta": {
        "status": 200
    },
    "data": {
        "results": [
            {
                "type": "user",
                "user": {
                    "_id": "545001b33bf179416a30bf7f",
                    "bio": "Ä°nstagram:",
                    "birth_date": "1992-12-09T17:12:49.957Z",
                    "name": "",
                    "photos": [
                        {
                            "id": "2eb1beec-6180-4d58-90fd-5f076da96af9",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "89d2bc07-d244-457b-b610-26ecd4e9e86d",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "0fcafc7e-d6e7-4cc5-891a-735971d6a5b2",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "g",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "bac74531-09e7-4c5b-ac6c-cab36c4be587",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "3c216244-946a-4c58-8670-cc12c05801cb",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "-8672-488d-8b7e-f30b4560c56b",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        }
                    ],
                    "gender": 1,
</code>```

Struct Code:

```<code>    struct Photo: Codable{
    var url: String?
    var processedFiles: [processedFiles]?
}
struct User: Codable{
    var group_matched: Bool?
    var distance_mi: Int?
    var common_friend_count: Int?
    var name:String?
    var profile_picture: String?
    var instagram_id: String?
    var photos: [Photo]?
}
class Results : Codable {
    var results: [User] = []
    static let sharedResults = Results()
    private init() { }
    var type: String?

    func populateData(sender: Results){
        print(sender)
        results += sender.results
    }
}
</code>```

Decode Code:

```<code> let jsonData = JSON(data: response.data!)
                let jsonData2 = try? JSONSerialization.data(withJSONObject: jsonData["data"].object)
                print(JSON(data: jsonData2!))

                let decoder = JSONDecoder()
                var response_class = Results.sharedResults
                response_class = try decoder.decode(Results.self, from: jsonData2!)
                Results.sharedResults.populateData(sender: response_class)
</code>```

EDIT: I edit second JSON, It now has array of array. How Can I implement decoder keys for that second array?

答:
In this case I would write a custom initializer with nestedContainer to include the user dictionary into the parent object

```<code>let jsonString = """
{
    "meta": {
        "status": 200
    },
    "data": {
        "results": [
        {
            "type": "user",
            "user": {
                "_id": "545001b33bf179416a30bf7f",
                "bio": "Ä°nstagram:hello",
                "birth_date": "1992-12-09T17:12:49.957Z",
                "name": "Hello"
            },

            "group_matched": false,
            "distance_mi": 4
        }
      ]
    }
}
"""
</code>```

```<code>struct Root : Decodable {
    let meta : [String:Int]
    let data : Result
}

struct Result : Decodable {
    let results : [User]
}

struct User : Decodable {

    let type : String
    let groupMatched : Bool
    let distanceMi : Int

    let id, bio, birthDate, name : String

    private enum CodingKeys : String, CodingKey {
        case type, user, groupMatched = "group_matched", distanceMi = "distance_mi"
    }

    private enum UserKeys: String, CodingKey {
        case id = "_id", bio, birthDate = "birth_date", name
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        type = try container.decode(String.self, forKey: .type)
        groupMatched = try container.decode(Bool.self, forKey: .groupMatched)
        distanceMi = try container.decode(Int.self, forKey: .distanceMi)

        let userInfo = try container.nestedContainer(keyedBy: UserKeys.self, forKey: .user)
        id = try userInfo.decode(String.self, forKey: .id)
        bio = try userInfo.decode(String.self, forKey: .bio)
        birthDate = try userInfo.decode(String.self, forKey: .birthDate)
        name = try userInfo.decode(String.self, forKey: .name)
    }
}
</code>```

```<code>do {
     let data = Data(jsonString.utf8)
     let decoder = JSONDecoder()
     let root = try decoder.decode(Root.self, from: data)
     print(root)
} catch {
     print("error: ", error)
}
</code>```

Title: Decode JSON Data on Swift 4 returns nil

Body:
I'm trying to decode my json data with below function. I had different Json format at first and It was working but whenI change json format, It started not to work. I try to do changes also in Structure code but nothing worked. What Am I missing? (Code is for first Json format so It needs to be work on second format too)

First JSON:

{
"status": 200,
"results": [
    {
        "group_matched": false,
        "distance_mi": 4,
        "content_hash": "1rT2lirUapfrYIYxSR2u0GtmRSLPsVki9kFj4ugs8JIq6",
        "common_friends": [],
        "common_likes": [],
        "common_friend_count": 0,
        "common_like_count": 0,
        "connection_count": 0,
        "_id": "5a2805ba779f34267d32d8b0",
        "bio": "",
            "birth_date": "1997-12-09T16:28:29.761Z",
            "name": "John",
        },

Second JSON:

{
    "meta": {
        "status": 200
    },
    "data": {
        "results": [
            {
                "type": "user",
                "user": {
                    "_id": "545001b33bf179416a30bf7f",
                    "bio": "Ä°nstagram:",
                    "birth_date": "1992-12-09T17:12:49.957Z",
                    "name": "",
                    "photos": [
                        {
                            "id": "2eb1beec-6180-4d58-90fd-5f076da96af9",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "89d2bc07-d244-457b-b610-26ecd4e9e86d",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "0fcafc7e-d6e7-4cc5-891a-735971d6a5b2",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "g",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "bac74531-09e7-4c5b-ac6c-cab36c4be587",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "3c216244-946a-4c58-8670-cc12c05801cb",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        },
                        {
                            "id": "-8672-488d-8b7e-f30b4560c56b",
                            "url": "",
                            "processedFiles": [
                                {
                                    "url": "",
                                    "height": 640,
                                    "width": 640
                                },
                                {
                                    "url": "",
                                    "height": 320,
                                    "width": 320
                                },
                                {
                                    "url": "",
                                    "height": 172,
                                    "width": 172
                                },
                                {
                                    "url": "",
                                    "height": 84,
                                    "width": 84
                                }
                            ]
                        }
                    ],
                    "gender": 1,

Struct Code:

    struct Photo: Codable{
    var url: String?
    var processedFiles: [processedFiles]?
}
struct User: Codable{
    var group_matched: Bool?
    var distance_mi: Int?
    var common_friend_count: Int?
    var name:String?
    var profile_picture: String?
    var instagram_id: String?
    var photos: [Photo]?
}
class Results : Codable {
    var results: [User] = []
    static let sharedResults = Results()
    private init() { }
    var type: String?

    func populateData(sender: Results){
        print(sender)
        results += sender.results
    }
}

Decode Code:

 let jsonData = JSON(data: response.data!)
                let jsonData2 = try? JSONSerialization.data(withJSONObject: jsonData["data"].object)
                print(JSON(data: jsonData2!))

                let decoder = JSONDecoder()
                var response_class = Results.sharedResults
                response_class = try decoder.decode(Results.self, from: jsonData2!)
                Results.sharedResults.populateData(sender: response_class)

EDIT: I edit second JSON, It now has array of array. How Can I implement decoder keys for that second array?

Body:
In this case I would write a custom initializer with nestedContainer to include the user dictionary into the parent object

let jsonString = """
{
    "meta": {
        "status": 200
    },
    "data": {
        "results": [
        {
            "type": "user",
            "user": {
                "_id": "545001b33bf179416a30bf7f",
                "bio": "Ä°nstagram:hello",
                "birth_date": "1992-12-09T17:12:49.957Z",
                "name": "Hello"
            },

            "group_matched": false,
            "distance_mi": 4
        }
      ]
    }
}
"""

struct Root : Decodable {
    let meta : [String:Int]
    let data : Result
}

struct Result : Decodable {
    let results : [User]
}

struct User : Decodable {

    let type : String
    let groupMatched : Bool
    let distanceMi : Int

    let id, bio, birthDate, name : String

    private enum CodingKeys : String, CodingKey {
        case type, user, groupMatched = "group_matched", distanceMi = "distance_mi"
    }

    private enum UserKeys: String, CodingKey {
        case id = "_id", bio, birthDate = "birth_date", name
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        type = try container.decode(String.self, forKey: .type)
        groupMatched = try container.decode(Bool.self, forKey: .groupMatched)
        distanceMi = try container.decode(Int.self, forKey: .distanceMi)

        let userInfo = try container.nestedContainer(keyedBy: UserKeys.self, forKey: .user)
        id = try userInfo.decode(String.self, forKey: .id)
        bio = try userInfo.decode(String.self, forKey: .bio)
        birthDate = try userInfo.decode(String.self, forKey: .birthDate)
        name = try userInfo.decode(String.self, forKey: .name)
    }
}

do {
     let data = Data(jsonString.utf8)
     let decoder = JSONDecoder()
     let root = try decoder.decode(Root.self, from: data)
     print(root)
} catch {
     print("error: ", error)
}


问:
React-Native FlatList performance problems with large list
My code gets Json data to an array lists the data using a FlatList. It looks like a phonebook photo and text in a row.

Here is My code:

```<code>  renderItem = ({ item }) =>
    (
    <ListItem
      title={item.username}
      avatar={{ uri: item.photo }}
    />
    )

  render() {
    console.log(this.state.myData);
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.myData}
          renderItem={this.renderItem}
        />
      </View>
    );
  }
</code>```

Its works and I get the output, but the performance is slow. Rendering takes approximately 10 seconds which is annoying to the user. What should  I do to make it faster?

答:
Here are some improvements you can do to optimize your flatlist:

Pagination

You can paginate your data in your backend and refetch it when your scroll gets closer to the end. onEndReached and onEndReachedThreshold can help you.

Update your React Native version to 49 or latest

Fiber 16 has amazing performance improvement which makes everything runs faster and smoother

Use PureComponent for render item

PureComponent improves the rendering and memory usage of your component, creating render items as pure gives you a better performance experience

Define getItemLayout prop

It improves item rendering since React will previously know its layout definition

Hope it helps

Body:
My code gets Json data to an array lists the data using a FlatList. It looks like a phonebook photo and text in a row.

Here is My code:

  renderItem = ({ item }) =>
    (
    <ListItem
      title={item.username}
      avatar={{ uri: item.photo }}
    />
    )

  render() {
    console.log(this.state.myData);
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.myData}
          renderItem={this.renderItem}
        />
      </View>
    );
  }

Its works and I get the output, but the performance is slow. Rendering takes approximately 10 seconds which is annoying to the user. What should  I do to make it faster?


问:
mySQL query -- if value in string
I have a string of IDs separated with comma

```<code>$myIDs = 22,23,45,895;
</code>```

How do I write a query to return records for values that correspond to the IDs in my string?
This does not seem to be right:

```<code>SELECT *
FROM t1
WHERE itemID IN ($myIDs)
</code>```

I guess I'm trying PHP array function here, hah? Is there something like this in mySQL?

Appreciate any suggestions. Thanks.

答:
I think you're missing quotes, ie, the exact query should look like this before evaluation

```<code>SELECT *
FROM t1
WHERE itemID IN ('22','23','45','895');
</code>```

Hence all you've got to do to fix this is:-

```<code>$myIDs = array(22,23,45,895);
$myIDs_string = "'".implode("','",$myIDs)."'";
</code>```

then in whatever PHP/SQL library/framework you select, use PHP to execute the following php query:-

```<code>SELECT *
FROM t1
WHERE itemID IN ($myIDs_string);
</code>```

Hope this helps.

Title: mySQL query -- if value in string

Body:
I have a string of IDs separated with comma

$myIDs = 22,23,45,895;

How do I write a query to return records for values that correspond to the IDs in my string?
This does not seem to be right:

SELECT *
FROM t1
WHERE itemID IN ($myIDs)

I guess I'm trying PHP array function here, hah? Is there something like this in mySQL?

Appreciate any suggestions. Thanks.

Body:
I think you're missing quotes, ie, the exact query should look like this before evaluation

SELECT *
FROM t1
WHERE itemID IN ('22','23','45','895');

Hence all you've got to do to fix this is:-

$myIDs = array(22,23,45,895);
$myIDs_string = "'".implode("','",$myIDs)."'";

then in whatever PHP/SQL library/framework you select, use PHP to execute the following php query:-

SELECT *
FROM t1
WHERE itemID IN ($myIDs_string);

Hope this helps.


问:
Not matched rows in B join with some row in A
Example data:

```<code>Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A
</code>```

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

```<code>x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1
</code>```

答:
I can't think of a really elegant way to accomplish this.  The following is somewhat brute force, but it gets the job done:</p>

```<code>select t1.x, t1.y,
       (case when t1.y is null then unmatched.cnt else matched.cnt end) as cnt
from table1 t1 outer apply
     (select count(*) as cnt
      from table2 t2
      where t2.y = t1.y
     ) matched cross join
     (select count(*) as cnt
      from table2 t2
      where not exists (select 1 from table1 t1 where t1.y = t2.y)
    ) unmatched;
</code>```

Body:
Example data:

Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1

Body:
I can't think of a really elegant way to accomplish this.  The following is somewhat brute force, but it gets the job done:

select t1.x, t1.y,
       (case when t1.y is null then unmatched.cnt else matched.cnt end) as cnt
from table1 t1 outer apply
     (select count(*) as cnt
      from table2 t2
      where t2.y = t1.y
     ) matched cross join
     (select count(*) as cnt
      from table2 t2
      where not exists (select 1 from table1 t1 where t1.y = t2.y)
    ) unmatched;


问:
Is the YQL console page down for everyone (again)?
Is anyone able to browse to the YQL console at https://developer.yahoo.com/yql/console today?

It worked yesterday but now I only get a page that says "The requested page was not found" like this screenshot

My existing scripts continue to work, and the sample console works at the main YQL page.

The same "page was not found" error also appears for anything in the ../yql/... directory like the FAQ or tutorial.

Also - before anyone suggests this is off topic, please note that I am posting this here because Yahoo/Oath says YQL support questions can only be posted here with the yql tag, so I'm just doing the only thing that I can do about this.  (source)

答:
Yes, the console is down (since Nov. 30 at least), confirmed by YDN tweet:

We are aware that the YQL Console is offline. We are investigating the issue. In the meantime, you can still continue to use YQL via our APIs. You can find the documentation here: https://developer.yahoo.com/yql/guide

source: https://twitter.com/ydn/status/936763870974173185


问:
SQL array flattening: Why doesn't CROSS JOIN UNNEST join every nested value with every row?
This question isn't about solving a particular problem, it's about understanding what's actually happening behind the scenes in a common SQL idiom used to flatten arrays.  There's some magic behind the scenes and I want to peek behind the curtain of syntactic sugar and see what's going on.

Let's consider the following table t1 :

Now let's assume we have a function called FLATTEN that takes a column of type array and unpacks each of the arrays in that column so that we're left with one row for each value in each array -- if we run SELECT FLATTEN(numbers_array) AS flattened_numbers FROM t1, we'd expect the following, which we'll call t2

In SQL, the CROSS JOIN combines rows from two tables by combining each row from the first table with each row from the second table. So if we run SELECT id, flattened.flattened_numbers from t1 CROSS JOIN flattened, we get

Now flatten is just an imaginary function, and as you can see it's not very useful to combine it with a CROSS JOIN, because each of the original values of the id column gets mixed with flattened_numbers from each of the original rows.  Everything gets mixed up because we don't have a WHERE clause that selects only the rows of the CROSS JOIN that we want.

The pattern people actually use to flatten arrays looks like this:
SELECT id, flattened_numbers FROM t1 CROSS JOIN UNNEST(sequences.some_numbers) AS flattened_numbers, which produces

But I don't understand why the CROSS JOIN UNNEST pattern actually works.  Because the CROSS JOIN doesn't include a WHERE clause, I would expect it behave just like the FLATTEN function I outlined above, where every unnested value gets combined with every row from t1.

Can someone 'unpack' what's actually going on in the CROSS JOIN UNNEST pattern that ensures that each row is only joined with it's own nested values (and not with the nested values from other rows)?

答:
The best way to think about this is by looking at what happens on a row-by-row basis. Setting up some input data, we have:

```<code>WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
)
...
</code>```

(I'm using a third element for the second row to make things more interesting). If we just select from it, we get output that looks like this:

```<code>WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
)
SELECT * FROM t1;
+----+---------------+
| id | numbers_array |
+----+---------------+
| 1  | [0, 1]        |
| 2  | [2, 4, 5]     |
+----+---------------+
</code>```

Now let's talk about unnesting. The UNNEST function takes an array and returns a value table of the array's element type. Whereas most BigQuery tables are SQL tables defined as a collection of columns, a value table has rows of some value type. For numbers_array, UNNEST(numbers_array) returns a value table whose value type is INT64, since numbers_array is an array with an element type of INT64. This value table contains all of the elements in numbers_array for the current row from t1.

For the row with an id of 1, the contents of the value table returned by UNNEST(numbers_array) are:

```<code>+-----+
| f0_ |
+-----+
| 0   |
| 1   |
+-----+
</code>```

This is the same as what we get with the following query:

```<code>SELECT * FROM UNNEST([0, 1]);
</code>```

UNNEST([0, 1]) in this case means "create a value table from the INT64 values 0 and 1".

Similarly, for the row with an id of 2, the contents of the value table returned by UNNEST(numbers_array) are:

```<code>+-----+
| f0_ |
+-----+
| 2   |
| 4   |
| 5   |
+-----+
</code>```

Now let's talk about how CROSS JOIN fits into the picture. In most cases, you use CROSS JOIN between two uncorrelated tables. In other words, the contents of the table on the right of the CROSS JOIN are not defined by the current contents of the table on the left.

In the case of arrays and UNNEST, however, the contents of the value table produced by UNNEST(numbers_array) change depending on the current row of t1. When we join the two tables, we get the cross product of the current row from t1 with all of the rows from UNNEST(numbers_array). For example:

```<code>WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
)
SELECT id, number
FROM t1
CROSS JOIN UNNEST(numbers_array) AS number;
+----+--------+
| id | number |
+----+--------+
| 1  | 0      |
| 1  | 1      |
| 2  | 2      |
| 2  | 4      |
| 2  | 5      |
+----+--------+
</code>```

numbers_array has two elements in the first row and three elements in the second, so we get 2 + 3 = 5 rows in the result of the query.

To answer the question about how this differs from flattening the numbers_array and then performing a CROSS JOIN, let's look at the results of this query:

```<code>WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
), t2 AS (
  SELECT number
  FROM t1
  CROSS JOIN UNNEST(numbers_array) AS number
)
SELECT number
FROM t2;
+--------+
| number |
+--------+
| 0      |
| 1      |
| 2      |
| 4      |
| 5      |
+--------+
</code>```

In this case, t2 is is a SQL table with a column named number with those values. If we perform a CROSS JOIN between t1 and t2, we get a true cross product of all rows:

```<code>WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
), t2 AS (
  SELECT number
  FROM t1
  CROSS JOIN UNNEST(numbers_array) AS number
)
SELECT id, numbers_array, number
FROM t1
CROSS JOIN t2;
+----+---------------+--------+
| id | numbers_array | number |
+----+---------------+--------+
| 1  | [0, 1]        | 0      |
| 1  | [0, 1]        | 1      |
| 1  | [0, 1]        | 2      |
| 1  | [0, 1]        | 4      |
| 1  | [0, 1]        | 5      |
| 2  | [2, 4, 5]     | 0      |
| 2  | [2, 4, 5]     | 1      |
| 2  | [2, 4, 5]     | 2      |
| 2  | [2, 4, 5]     | 4      |
| 2  | [2, 4, 5]     | 5      |
+----+---------------+--------+
</code>```

So what's the difference between this and the previous query with CROSS JOIN UNNEST(numbers_array)? In this case, the contents of t2 don't change for each row from t1. For the first row in t1, there are five rows in t2. For the second row in t1, there are five rows in t2. As a result, the CROSS JOIN between the two of them returns 5 + 5 = 10 rows in total.

Body:
The best way to think about this is by looking at what happens on a row-by-row basis. Setting up some input data, we have:

WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
)
...

(I'm using a third element for the second row to make things more interesting). If we just select from it, we get output that looks like this:

WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
)
SELECT * FROM t1;
+----+---------------+
| id | numbers_array |
+----+---------------+
| 1  | [0, 1]        |
| 2  | [2, 4, 5]     |
+----+---------------+

Now let's talk about unnesting. The UNNEST function takes an array and returns a value table of the array's element type. Whereas most BigQuery tables are SQL tables defined as a collection of columns, a value table has rows of some value type. For numbers_array, UNNEST(numbers_array) returns a value table whose value type is INT64, since numbers_array is an array with an element type of INT64. This value table contains all of the elements in numbers_array for the current row from t1.

For the row with an id of 1, the contents of the value table returned by UNNEST(numbers_array) are:

+-----+
| f0_ |
+-----+
| 0   |
| 1   |
+-----+

This is the same as what we get with the following query:

SELECT * FROM UNNEST([0, 1]);

UNNEST([0, 1]) in this case means "create a value table from the INT64 values 0 and 1".

Similarly, for the row with an id of 2, the contents of the value table returned by UNNEST(numbers_array) are:

+-----+
| f0_ |
+-----+
| 2   |
| 4   |
| 5   |
+-----+

Now let's talk about how CROSS JOIN fits into the picture. In most cases, you use CROSS JOIN between two uncorrelated tables. In other words, the contents of the table on the right of the CROSS JOIN are not defined by the current contents of the table on the left.

In the case of arrays and UNNEST, however, the contents of the value table produced by UNNEST(numbers_array) change depending on the current row of t1. When we join the two tables, we get the cross product of the current row from t1 with all of the rows from UNNEST(numbers_array). For example:

WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
)
SELECT id, number
FROM t1
CROSS JOIN UNNEST(numbers_array) AS number;
+----+--------+
| id | number |
+----+--------+
| 1  | 0      |
| 1  | 1      |
| 2  | 2      |
| 2  | 4      |
| 2  | 5      |
+----+--------+

numbers_array has two elements in the first row and three elements in the second, so we get 2 + 3 = 5 rows in the result of the query.

To answer the question about how this differs from flattening the numbers_array and then performing a CROSS JOIN, let's look at the results of this query:

WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
), t2 AS (
  SELECT number
  FROM t1
  CROSS JOIN UNNEST(numbers_array) AS number
)
SELECT number
FROM t2;
+--------+
| number |
+--------+
| 0      |
| 1      |
| 2      |
| 4      |
| 5      |
+--------+

In this case, t2 is is a SQL table with a column named number with those values. If we perform a CROSS JOIN between t1 and t2, we get a true cross product of all rows:

WITH t1 AS (
  SELECT 1 AS id, [0, 1] AS numbers_array UNION ALL
  SELECT 2, [2, 4, 5]
), t2 AS (
  SELECT number
  FROM t1
  CROSS JOIN UNNEST(numbers_array) AS number
)
SELECT id, numbers_array, number
FROM t1
CROSS JOIN t2;
+----+---------------+--------+
| id | numbers_array | number |
+----+---------------+--------+
| 1  | [0, 1]        | 0      |
| 1  | [0, 1]        | 1      |
| 1  | [0, 1]        | 2      |
| 1  | [0, 1]        | 4      |
| 1  | [0, 1]        | 5      |
| 2  | [2, 4, 5]     | 0      |
| 2  | [2, 4, 5]     | 1      |
| 2  | [2, 4, 5]     | 2      |
| 2  | [2, 4, 5]     | 4      |
| 2  | [2, 4, 5]     | 5      |
+----+---------------+--------+

So what's the difference between this and the previous query with CROSS JOIN UNNEST(numbers_array)? In this case, the contents of t2 don't change for each row from t1. For the first row in t1, there are five rows in t2. For the second row in t1, there are five rows in t2. As a result, the CROSS JOIN between the two of them returns 5 + 5 = 10 rows in total.