问:
org.h2.jdbc.JdbcSQLException: Table "PACCHETTIVISITETURISTICHE" not found; SQL statement:
I'm implementing a piece of code for a project using eclipse.
One of the features I'm asked to do is to find out if there are two values in a database table (created with h2).
All this must be implemented by using DAO classes and a Manager class that passes between the main and the DAO classes.
My problem is that by doing this, an exception is always raised that tells me that the "packet list" table was not found.
But this can not be because:

I checked it in the database and there is the table

The database was properly connected with eclipse

If I implement all the function in the main the table is recognized!

These are the classes:

```<code>import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DaoPacchetti {

public static boolean Ricerca(String citta, String periodo ) throws SQLException{
    boolean verifica=false;
    PreparedStatement stat=null;
    ResultSet rs=null;
    Connection con=null;

    con= DBManager.getConnection();
    stat=con.prepareStatement("SELECT * FROM pacchettivisiteturistiche "
            +  " WHERE citta=? AND disponibilitaSottoscrizione=?");
    stat.setString(1, citta);
    stat.setString(2, periodo);
    rs=stat.executeQuery();
    if(rs.next()){
        verifica=true;
    }

    //rs.close();
    //stat.close();
    con.close();
    return verifica;

    }
}
</code>```

Manager Class:

```<code>import dao.DaoPacchetti;
//import dao.DAOException;
import java.sql.SQLException;

public class GestorePacchetti {

private static GestorePacchetti istance;

public static GestorePacchetti getIstance() {
    if (istance == null)
        istance = new GestorePacchetti();
    return istance;
}

public  boolean RicercaPacchetto(String citta,String periodo){
    boolean trovato=false;
    try{
    trovato=DaoPacchetti.Ricerca(citta, periodo);
    return trovato;
    }
    catch(SQLException e){
        System.err.println("errore nella ricerca del pacchetto");
        e.printStackTrace();
    }

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

Main class:

```<code>import pacchetti.GestorePacchetti;
import java.util.Scanner;

public class Terminale {

public static void main(String[] args) {

    boolean trovato;
    String citta;
    String codice_pacchetto;
    String data;
    String nPartecipantistringa;
    int nPartecipanti;

    GestorePacchetti g=  GestorePacchetti.getIstance();

System.out.println("immetti la città e la data per la ricerca del pacchetto
delle visite turistiche");

    Scanner input = new Scanner(System.in);

    do{
        System.out.println("immetti prima la citta");
        citta = input.nextLine();
        System.out.println("ora immetti la data");
        data=input.nextLine();

        trovato=g.RicercaPacchetto(citta, data);

        if(trovato==false)
        System.out.println("Reinserire i parametri per favore");
    }while(trovato==false);

    System.out.println("Trovato!!");

}

}
</code>```

I also write the main function that contains the entire function without invoking other classes (here the table is recognized):

```<code>import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws Exception{

    boolean trovato;
    String citta;
    String codice_pacchetto;
    String data;
    String nPartecipantistringa;
    int nPartecipanti;

    GestoreVisiteTuristiche g= new GestoreVisiteTuristiche();

    System.out.println("immetti la città e la data per la ricerca del
    pacchetto delle visite turistiche");

    Scanner input = new Scanner(System.in);

        System.out.println("immetti prima la citta");
        citta = input.nextLine();
        System.out.println("ora immetti la data");
        data=input.nextLine();

        Connection con=null;
        PreparedStatement stat=null;
        ResultSet rs=null;

        try{

        con=DBManager.getConnection();
        stat=con.prepareStatement("SELECT * FROM PacchettiVisiteTuristiche P
"
                +  "WHERE ?=P.citta AND ?=P.disponibilitaSottoscrizione");
        stat.setString(1, citta);
        stat.setString(2, data);
        rs=stat.executeQuery();

        if(rs.next()){
            System.out.println("trovato!!");
            citta=rs.getString("citta");
            data=rs.getString("disponibilitaSottoscrizione");
            System.out.println(citta+" "+data);
        }
        else{
            System.out.println("errore, nessuna corrispondenza");
        }

        rs.close();
        stat.close();
        }
        catch(Exception e){System.out.println("errore");}
        finally {
            if (con != null) {
        try {
            con.close();
        } catch (SQLException e){}
        }
        }

}
}
</code>```

DBManager Class:

```<code>import java.sql.Connection;

public class DBManager {
protected static Connection conn;

final protected static ConnectionFactory CONNECTION_FACTORY=new
H2ConnectionFactory();

public static Connection getConnection(){
    if (conn == null) {
        try {
            conn = CONNECTION_FACTORY.createConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    return conn;

}
}
</code>```

ConnectionFactory :

```<code>public interface ConnectionFactory {
java.sql.Connection createConnection() throws Exception;
}

import java.sql.DriverManager;

public class H2ConnectionFactory implements ConnectionFactory {

protected final static String DB_PATH= "./test";
protected final static String CONNECTION_STRING = "jdbc:h2:" + DB_PATH ;

@Override
public java.sql.Connection createConnection() throws Exception {
    Class.forName("org.h2.Driver");
    return DriverManager.getConnection(CONNECTION_STRING, "sa", "12345");
}
}
</code>```

This is the exception raised:

```<code>org.h2.jdbc.JdbcSQLException: Table "PACCHETTIVISITETURISTICHE" not found;
SQL statement:
SELECT * FROM pacchettivisiteturistiche  WHERE citta=? AND
disponibilitaSottoscrizione=? [42102-195]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.command.Parser.readTableOrView(Parser.java:5506)
at org.h2.command.Parser.readTableFilter(Parser.java:1260)
at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1940)
at org.h2.command.Parser.parseSelectSimple(Parser.java:2089)
at org.h2.command.Parser.parseSelectSub(Parser.java:1934)
at org.h2.command.Parser.parseSelectUnion(Parser.java:1749)
at org.h2.command.Parser.parseSelect(Parser.java:1737)
at org.h2.command.Parser.parsePrepared(Parser.java:448)
at org.h2.command.Parser.parse(Parser.java:320)
at org.h2.command.Parser.parse(Parser.java:292)
at org.h2.command.Parser.prepareCommand(Parser.java:257)
at org.h2.engine.Session.prepareLocal(Session.java:573)
at org.h2.engine.Session.prepareCommand(Session.java:514)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1204)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:73)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:288)
at dao.DaoPacchetti.Ricerca(DaoPacchetti.java:22)
at pacchetti.GestorePacchetti.RicercaPacchetto(GestorePacchetti.java:21)
at ui.Terminale.main(Terminale.java:30)
</code>```

答:
Okay, but i am not sure that the error is here because in the main class where the function works i use the same DBManager class.
This is my DBManager Class:

```<code>import java.sql.Connection;

public class DBManager {
protected static Connection conn;

final protected static ConnectionFactory CONNECTION_FACTORY=new
H2ConnectionFactory();

public static Connection getConnection(){
    if (conn == null) {
        try {
            conn = CONNECTION_FACTORY.createConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    return conn;

}
}
</code>```

This is the interface and class of the ConnectorFactory:

```<code>public interface ConnectionFactory {
java.sql.Connection createConnection() throws Exception;
}

import java.sql.DriverManager;

public class H2ConnectionFactory implements ConnectionFactory {

protected final static String DB_PATH= "./test";
protected final static String CONNECTION_STRING = "jdbc:h2:" + DB_PATH ;

@Override
public java.sql.Connection createConnection() throws Exception {
    Class.forName("org.h2.Driver");
    return DriverManager.getConnection(CONNECTION_STRING, "sa", "12345");
}
}
</code>```

Body:
I'm implementing a piece of code for a project using eclipse.
One of the features I'm asked to do is to find out if there are two values in a database table (created with h2).
All this must be implemented by using DAO classes and a Manager class that passes between the main and the DAO classes.
My problem is that by doing this, an exception is always raised that tells me that the "packet list" table was not found.
But this can not be because:

I checked it in the database and there is the table

The database was properly connected with eclipse

If I implement all the function in the main the table is recognized!

These are the classes:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DaoPacchetti {

public static boolean Ricerca(String citta, String periodo ) throws SQLException{
    boolean verifica=false;
    PreparedStatement stat=null;
    ResultSet rs=null;
    Connection con=null;

    con= DBManager.getConnection();
    stat=con.prepareStatement("SELECT * FROM pacchettivisiteturistiche "
            +  " WHERE citta=? AND disponibilitaSottoscrizione=?");
    stat.setString(1, citta);
    stat.setString(2, periodo);
    rs=stat.executeQuery();
    if(rs.next()){
        verifica=true;
    }

    //rs.close();
    //stat.close();
    con.close();
    return verifica;

    }
}

Manager Class:

import dao.DaoPacchetti;
//import dao.DAOException;
import java.sql.SQLException;

public class GestorePacchetti {

private static GestorePacchetti istance;

public static GestorePacchetti getIstance() {
    if (istance == null)
        istance = new GestorePacchetti();
    return istance;
}

public  boolean RicercaPacchetto(String citta,String periodo){
    boolean trovato=false;
    try{
    trovato=DaoPacchetti.Ricerca(citta, periodo);
    return trovato;
    }
    catch(SQLException e){
        System.err.println("errore nella ricerca del pacchetto");
        e.printStackTrace();
    }

    return trovato;
}
}

Main class:

import pacchetti.GestorePacchetti;
import java.util.Scanner;

public class Terminale {

public static void main(String[] args) {

    boolean trovato;
    String citta;
    String codice_pacchetto;
    String data;
    String nPartecipantistringa;
    int nPartecipanti;

    GestorePacchetti g=  GestorePacchetti.getIstance();

System.out.println("immetti la città e la data per la ricerca del pacchetto
delle visite turistiche");

    Scanner input = new Scanner(System.in);

    do{
        System.out.println("immetti prima la citta");
        citta = input.nextLine();
        System.out.println("ora immetti la data");
        data=input.nextLine();

        trovato=g.RicercaPacchetto(citta, data);

        if(trovato==false)
        System.out.println("Reinserire i parametri per favore");
    }while(trovato==false);

    System.out.println("Trovato!!");

}

}

I also write the main function that contains the entire function without invoking other classes (here the table is recognized):

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws Exception{

    boolean trovato;
    String citta;
    String codice_pacchetto;
    String data;
    String nPartecipantistringa;
    int nPartecipanti;

    GestoreVisiteTuristiche g= new GestoreVisiteTuristiche();

    System.out.println("immetti la città e la data per la ricerca del
    pacchetto delle visite turistiche");

    Scanner input = new Scanner(System.in);

        System.out.println("immetti prima la citta");
        citta = input.nextLine();
        System.out.println("ora immetti la data");
        data=input.nextLine();

        Connection con=null;
        PreparedStatement stat=null;
        ResultSet rs=null;

        try{

        con=DBManager.getConnection();
        stat=con.prepareStatement("SELECT * FROM PacchettiVisiteTuristiche P
"
                +  "WHERE ?=P.citta AND ?=P.disponibilitaSottoscrizione");
        stat.setString(1, citta);
        stat.setString(2, data);
        rs=stat.executeQuery();

        if(rs.next()){
            System.out.println("trovato!!");
            citta=rs.getString("citta");
            data=rs.getString("disponibilitaSottoscrizione");
            System.out.println(citta+" "+data);
        }
        else{
            System.out.println("errore, nessuna corrispondenza");
        }

        rs.close();
        stat.close();
        }
        catch(Exception e){System.out.println("errore");}
        finally {
            if (con != null) {
        try {
            con.close();
        } catch (SQLException e){}
        }
        }

}
}

DBManager Class:

import java.sql.Connection;

public class DBManager {
protected static Connection conn;

final protected static ConnectionFactory CONNECTION_FACTORY=new
H2ConnectionFactory();

public static Connection getConnection(){
    if (conn == null) {
        try {
            conn = CONNECTION_FACTORY.createConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    return conn;

}
}

ConnectionFactory :

public interface ConnectionFactory {
java.sql.Connection createConnection() throws Exception;
}

import java.sql.DriverManager;

public class H2ConnectionFactory implements ConnectionFactory {

protected final static String DB_PATH= "./test";
protected final static String CONNECTION_STRING = "jdbc:h2:" + DB_PATH ;

@Override
public java.sql.Connection createConnection() throws Exception {
    Class.forName("org.h2.Driver");
    return DriverManager.getConnection(CONNECTION_STRING, "sa", "12345");
}
}

This is the exception raised:

org.h2.jdbc.JdbcSQLException: Table "PACCHETTIVISITETURISTICHE" not found;
SQL statement:
SELECT * FROM pacchettivisiteturistiche  WHERE citta=? AND
disponibilitaSottoscrizione=? [42102-195]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.command.Parser.readTableOrView(Parser.java:5506)
at org.h2.command.Parser.readTableFilter(Parser.java:1260)
at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1940)
at org.h2.command.Parser.parseSelectSimple(Parser.java:2089)
at org.h2.command.Parser.parseSelectSub(Parser.java:1934)
at org.h2.command.Parser.parseSelectUnion(Parser.java:1749)
at org.h2.command.Parser.parseSelect(Parser.java:1737)
at org.h2.command.Parser.parsePrepared(Parser.java:448)
at org.h2.command.Parser.parse(Parser.java:320)
at org.h2.command.Parser.parse(Parser.java:292)
at org.h2.command.Parser.prepareCommand(Parser.java:257)
at org.h2.engine.Session.prepareLocal(Session.java:573)
at org.h2.engine.Session.prepareCommand(Session.java:514)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1204)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:73)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:288)
at dao.DaoPacchetti.Ricerca(DaoPacchetti.java:22)
at pacchetti.GestorePacchetti.RicercaPacchetto(GestorePacchetti.java:21)
at ui.Terminale.main(Terminale.java:30)

Body:
Okay, but i am not sure that the error is here because in the main class where the function works i use the same DBManager class.
This is my DBManager Class:

import java.sql.Connection;

public class DBManager {
protected static Connection conn;

final protected static ConnectionFactory CONNECTION_FACTORY=new
H2ConnectionFactory();

public static Connection getConnection(){
    if (conn == null) {
        try {
            conn = CONNECTION_FACTORY.createConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    return conn;

}
}

This is the interface and class of the ConnectorFactory:

public interface ConnectionFactory {
java.sql.Connection createConnection() throws Exception;
}

import java.sql.DriverManager;

public class H2ConnectionFactory implements ConnectionFactory {

protected final static String DB_PATH= "./test";
protected final static String CONNECTION_STRING = "jdbc:h2:" + DB_PATH ;

@Override
public java.sql.Connection createConnection() throws Exception {
    Class.forName("org.h2.Driver");
    return DriverManager.getConnection(CONNECTION_STRING, "sa", "12345");
}
}


来源: stackexchange

问:
Installing open Cart using XAMPP
I'm getting this error when I try installing open Cart on my system.

Fatal error:

Call to undefined function openssl_random_pseudo_bytes_() in C:\xampp\htdocs\shop\system\library\session.php on line 33

答:
Edit php.ini file - changing ;extension=php_openssl.dll to extension=php_openssl.dll .

OR

Your php installation either does not have openssl enabled, or you could be running a version of php < 5.3.

To enable openssl, you must re-compile and install php with the "–with-openssl" flag. See php installation documentation

OR

Your version of PHP wasn't compiled with the openssl module. If you are building from source, add the module like so:

```<code>cd /path/to/php-5.4/
./configure --with-openssl
</code>```

ContentLicense: CC BY-SA 3.0

Title: Installing open Cart using XAMPP

Body:
Edit php.ini file - changing ;extension=php_openssl.dll to extension=php_openssl.dll .

OR

Your php installation either does not have openssl enabled, or you could be running a version of php < 5.3.

To enable openssl, you must re-compile and install php with the "–with-openssl" flag. See php installation documentation

OR

Your version of PHP wasn't compiled with the openssl module. If you are building from source, add the module like so:

cd /path/to/php-5.4/
./configure --with-openssl


问:
R: expr' did not evaluate to an object of length 'n'
```<code>require(OptionPricing)
c=BS_EC(K=54, r = 0.07, sigma = 0.3, T = 5/12, S0 = 50)
c[1]
y <- function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)-2.846575)
</code>```

This is done in matlab using fzero, I have implemented this in Python using lambda. Want to do same in R.

so far tried following:

```<code>> uniroot(y,c(-1,1))
Error in uniroot(y, c(-1, 1)) :
  f() values at end points not of opposite sign
In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
  the condition has length > 1 and only the first element will be used
</code>```

and

```<code>> f <- Vectorize(function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)-2.846575))
> curve(f)
Error in curve(f) : 'expr' did not evaluate to an object of length 'n'
</code>```

Also plot(); but no luck!

Please share an idea.

Thank you.

答:
The problem is BS_EC gives back a vector (price,delta,gamma) as result.
In order to apply a range of input you have to consider just one result at time.
For example for price add [1]

```<code> f <- Vectorize(function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)[1]-2.846575))
 curve(f)
</code>```

The same is true for the optimization, you have to decide what parameter you want to consider
Again give back just the price with [1] and you are done

```<code> y <- function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)[1]-2.846575)
uniroot(y,c(-1,1))
</code>```

Body:
require(OptionPricing)
c=BS_EC(K=54, r = 0.07, sigma = 0.3, T = 5/12, S0 = 50)
c[1]
y <- function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)-2.846575)

This is done in matlab using fzero, I have implemented this in Python using lambda. Want to do same in R.

so far tried following:

> uniroot(y,c(-1,1))
Error in uniroot(y, c(-1, 1)) :
  f() values at end points not of opposite sign
In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
  the condition has length > 1 and only the first element will be used

and

> f <- Vectorize(function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)-2.846575))
> curve(f)
Error in curve(f) : 'expr' did not evaluate to an object of length 'n'

Also plot(); but no luck!

Please share an idea.

Thank you.

Body:
The problem is BS_EC gives back a vector (price,delta,gamma) as result.
In order to apply a range of input you have to consider just one result at time.
For example for price add [1]

 f <- Vectorize(function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)[1]-2.846575))
 curve(f)

The same is true for the optimization, you have to decide what parameter you want to consider
Again give back just the price with [1] and you are done

 y <- function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)[1]-2.846575)
uniroot(y,c(-1,1))


问:
Error establishing database connection in WordPress install
I am working with a managed server from 1&1 and I am trying to manually install WordPress with no luck. I went and downloaded the WP core files, uploaded them via FTP and then went into mySQL and created the database and username/password etc. and assigned the privileges. When I try to install wordpress via "www.example.com/wp-admin/install.php", I continuously receive the error:

Error establishing a database connection

I tried everything and triple checked my user,password, etc.

Here is my credentials (Password is hidden):

答: Try use 127.0.0.1 instead of localhost as the db host. Had the same issue and this fixed it for me. </p>


问:
Chaining aggreggation procedures
I have the following code:

```<code>myData_agg = myData.groupby("Customer")["PurchAmount"].sum()
myData_agg.loc[myData_agg>=100,]
</code>```

Can I write this code in one procedure?
Thanks!

答:
Option one:

Chain them with [] and a lambda expression:

```<code>myData.groupby("Customer")["PurchAmount"].sum()[lambda x: x >= 100]
</code>```

Option two:

Use the compress method:

```<code>myData.groupby("Customer")["PurchAmount"].sum().compress(lambda x: x >= 100)
</code>```

Option three:

Use pipe:

```<code>myData.groupby("Customer")["PurchAmount"].sum().pipe(lambda x: x[x >= 100])
</code>```

Title: Chaining aggreggation procedures

Body:
I have the following code:

myData_agg = myData.groupby("Customer")["PurchAmount"].sum()
myData_agg.loc[myData_agg>=100,]

Can I write this code in one procedure?
Thanks!

Body:
Option one:

Chain them with [] and a lambda expression:

myData.groupby("Customer")["PurchAmount"].sum()[lambda x: x >= 100]

Option two:

Use the compress method:

myData.groupby("Customer")["PurchAmount"].sum().compress(lambda x: x >= 100)

Option three:

Use pipe:

myData.groupby("Customer")["PurchAmount"].sum().pipe(lambda x: x[x >= 100])


问:
swf to Illustrator friendly format (vector)
So I'm making a drawing app that uses flash. I want to be able to export my drawing into an illustrator friendly format.

I'm thinking I will need to record the shapes drawn with a "history" and then export those either via text/xml/bytearray.

Have any fellow overflowers heard of tool to make my life easier? Thanks!

答:
I use this online tool http://iiistudio.com/convert2svg/

It works the best and save the result in SVG format you can directly open with Adobe Illustrator, and it's made in flash application. You can download the swf file and it could work locally without server backend anyway as I guessed it has php or js!

As I tried to import the swf file I exported from Toon Boom Harmony to Adobe Flash, it's into the stage but the vector curves are zig-zagged not what I want. Ans I also tried print the swf to PDF with variety of virtual PDF printer such as Foxit PDF printer, PDF Factory Pro and the results is bad as well, not the original shapes at all.

results are so different in PDF, Flash and swf2svg:
https://i.stack.imgur.com/7bJnf.jpg

ContentLicense: CC BY-SA 2.5


问:
SSIS Sort large data from Heterogeneous sources - Alternatives
I am looking for alternatives to sort ~2 million records on SSIS.

Data sourced from Heterogeneous sources (SQL, Oracle, DB2) after applying multiple  transformation, there is an Union All to combine data and then needs to be sorted by three fields.

This is because data needs to be sorted by certain fields before we sent to external vendor

These are the solutions I already tried :

Buffer size (100 MB) and Max rows tuning (50K rows)

Applied sort at each source (Just for the sake of my mind !)

Set Validate external metadata property to False (for Sort Trans)

tried script task (C# sorting)

None of these significantly improved performance.

Is there any other alternatives ?

Update :
This is string sort on Three different fields which belongs to three different DB tables (SQL, Oracle, DB2). I can't sort until data set is combined.

Tried loading output to a single table and used Order by with appropriate indexing  - This gives an unexpected result as SQL Order by behaves differently than Sort Transformation Here is the explanation

答:
Use a MERGE transformation instead of UNION ALL:

Instead of using a UNION ALL to combine data sets first and then sorting the resulting large combined dataset, you are better to sort each smaller set first and then use a MERGE transformation. The result of the MERGE transformation will be already sorted.


问:
Using voice to give commnands to a plot, is it possible?
I will go straight to the point.

I have a plot with a 3D figure represented by points, what I would like to do is give matlab a voice command that make a function starts.

Specifically I would like to say for example "rotate", matlab should recognize this vocal command and make the actual figure in the plot to rotate.

Is this possible or I should give up? Because Im going crazy trying.

Thanks in advance.

答:
Sure, you can do that. Here are the rough steps:

Start by recording a very large number of samples of yourself saying "ROTATE", and whatever other commands you'd like to give to the plot.

Then use the deep learning functionality from Neural Network Toolbox to train a network on those voice samples, and classify each of them into the appropriate command (you'll need a computer with a decent GPU).

Use Data Acquisition Toolbox to connect your sound card, and listen to sounds coming in from your microphone.

Connect the audio stream from Data Acquisition Toolbox to the inputs of the network generated in step 2.

When the network successfully classifies a portion of the audio stream into one of your commands, execute the appropriate command to rotate, or otherwise modify your plot.

Once you've done all that, apply to MathWorks for a job as an Application Engineer. It would make a nice demo to show to customers.

By the way, all of the above might sound facetious, but is quite serious - this is the sort of thing that MATLAB actually makes pretty easy, and if you know what you're doing I would think it's only maybe a week's work. And I do think that if you showed it in a MathWorks interview, there would be a good chance it might land you a job there.

Edit: Or, you could get MATLAB to just make a call to Google's Cloud Speech API and then do something based on the word it returns. Google are probably better than either of us at neural networks :)

Edit 2: Or, if you're comfortable with a six-hour delay in your command, you could get MATLAB to send an email to GoTranscript, where a real human will transcribe your voice for you, and then MATLAB could read the response email :/


问:
how to include 2 joins into a union statement
I want to merge plan and actual data into 1 view using Union.
For this I use two inner joins to make the rows match - then I use a union statement. Currently I do this in 3 steps - now I want to merge all this into 1 step.

Example

create vPlan2

```<code>Select
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan] as 'invoice'
from vPlan a
inner join vActuals b on a.step = b.step
group by
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan]
</code>```

create vActuals2

```<code>Select
    a.step,
    b.[planned user],
    a.[actual user],
    a.[invoice actuals] as 'invoice'
from vActuals a
inner join vPlan b on a.step = b.step
group by
    a.step,
    a.[actual user],
    b.[planned user],
    a.[invoice actuals]
</code>```

create vplanandactuals

```<code>select
    'Plan' as type,
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
from vPlan2 a
group by
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
Union
select
    'Actuals',
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]
from vActuals2 b
group by
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]
</code>```

答:
Similar to @texastonie's answer, but replacing the group by with select distinct:

```<code>Select Distinct
   'Plan' as type,
   vPlan.step,
   vPlan.[planned user],
   vPlan.[invoice plan] as 'invoice',
   vActuals.[actual user]
from vPlan
inner join vActuals
  on vPlan.step = vActuals.step
union
Select Distinct
    'Actuals' as type,
    vActuals.step,
    vPlan.[planned user],
    vActuals.[invoice actuals] as 'invoice',
    vActuals.[actual user]
from vActuals
inner join vPlan
  on vActuals.step = vPlan.step
;
</code>```

Body:
I want to merge plan and actual data into 1 view using Union.
For this I use two inner joins to make the rows match - then I use a union statement. Currently I do this in 3 steps - now I want to merge all this into 1 step.

Example

create vPlan2

Select
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan] as 'invoice'
from vPlan a
inner join vActuals b on a.step = b.step
group by
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan]

create vActuals2

Select
    a.step,
    b.[planned user],
    a.[actual user],
    a.[invoice actuals] as 'invoice'
from vActuals a
inner join vPlan b on a.step = b.step
group by
    a.step,
    a.[actual user],
    b.[planned user],
    a.[invoice actuals]

create vplanandactuals

select
    'Plan' as type,
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
from vPlan2 a
group by
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
Union
select
    'Actuals',
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]
from vActuals2 b
group by
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]

Body:
Similar to @texastonie's answer, but replacing the group by with select distinct:

Select Distinct
   'Plan' as type,
   vPlan.step,
   vPlan.[planned user],
   vPlan.[invoice plan] as 'invoice',
   vActuals.[actual user]
from vPlan
inner join vActuals
  on vPlan.step = vActuals.step
union
Select Distinct
    'Actuals' as type,
    vActuals.step,
    vPlan.[planned user],
    vActuals.[invoice actuals] as 'invoice',
    vActuals.[actual user]
from vActuals
inner join vPlan
  on vActuals.step = vPlan.step
;


问:
How to convert a number to Q format
I am working with XMC1300 MCU series from Infineon. For my application I need to find out the square root of some data.

Following are the math lib api provided by Infineon

```<code>int16_t XMC_MATH_CORDIC_Q15_Sqrt(int16_t x)
int32_t XMC_MATH_CORDIC_Q31_Sqrt(int32_t x)
</code>```

These two API accept and returns data format Q15 and Q31 i.e. It could only represent [-1,1] range.

Suppose I wanted to find out the square root of

```<code>144
200
1000
34567
50000
</code>```

How can I change these numbers in range [-1, 1].

What needs to be done for the normalization of Input and Output.

Regards,
Tinchu

答:
I usually just develop formulas to convert from machine to engineering units.  In this case the input and output would be expected to be Q15.  Below I use _eu to designate engineering units, _mu to designate machine units and sqrt() to designate the actual square root.  The formula for square root:

```<code>output_eu = sqrt(input_eu)
</code>```

Conversions for input and output:

```<code>output_mu = (2^15)*output_eu
input_mu = (2^15)*input_eu
</code>```

To get the equivalent calculation in machine units, substitute:

```<code>output_mu/(2^15) = sqrt(input_mu/(2^15))
output_mu = sqrt((2^15)*input_mu)
</code>```

It's best to right shift the input in order to optimize precision, so in the case of 144, the number could be left shifted by 7 bits:  144*(2^7) = 18432

So the input is basically Q7.

In other words:

```<code>output_mu = sqrt((2^15)*((2^7)*input_eu))
          = (2^11)*sqrt(input_eu)
</code>```

So basically the output here is Q11 and could be shifted right 11 bits to get to the result in engineering units.

So if you were to execute this in code, lets say value 144 is loaded into variable x and we want to put result in variable y:

```<code>y = x << 7;
y = XMC_MATH_CORDIC_Q15_Sqrt(y);
y >>= 11;
</code>```

Walking through the math:

```<code>1) y = (144*(2^7)) = 18432
2) y = sqrt((2^15)*18432) = 24576
3) y = 24576/(2^11) = 12
</code>```

Title: How to convert a number to Q format

Body:
I am working with XMC1300 MCU series from Infineon. For my application I need to find out the square root of some data.

Following are the math lib api provided by Infineon

int16_t XMC_MATH_CORDIC_Q15_Sqrt(int16_t x)
int32_t XMC_MATH_CORDIC_Q31_Sqrt(int32_t x)

These two API accept and returns data format Q15 and Q31 i.e. It could only represent [-1,1] range.

Suppose I wanted to find out the square root of

144
200
1000
34567
50000

How can I change these numbers in range [-1, 1].

What needs to be done for the normalization of Input and Output.

Regards,
Tinchu

Body:
I usually just develop formulas to convert from machine to engineering units.  In this case the input and output would be expected to be Q15.  Below I use _eu to designate engineering units, _mu to designate machine units and sqrt() to designate the actual square root.  The formula for square root:

output_eu = sqrt(input_eu)

Conversions for input and output:

output_mu = (2^15)*output_eu
input_mu = (2^15)*input_eu

To get the equivalent calculation in machine units, substitute:

output_mu/(2^15) = sqrt(input_mu/(2^15))
output_mu = sqrt((2^15)*input_mu)

It's best to right shift the input in order to optimize precision, so in the case of 144, the number could be left shifted by 7 bits:  144*(2^7) = 18432

So the input is basically Q7.

In other words:

output_mu = sqrt((2^15)*((2^7)*input_eu))
          = (2^11)*sqrt(input_eu)

So basically the output here is Q11 and could be shifted right 11 bits to get to the result in engineering units.

So if you were to execute this in code, lets say value 144 is loaded into variable x and we want to put result in variable y:

y = x << 7;
y = XMC_MATH_CORDIC_Q15_Sqrt(y);
y >>= 11;

Walking through the math:

1) y = (144*(2^7)) = 18432
2) y = sqrt((2^15)*18432) = 24576
3) y = 24576/(2^11) = 12


问:
Jquery Datepicker : Never show the day selection "ui-datepicker-calendar"
I need a datepicker to never show the day section.

I want to thus destroy/remove this element : "ui-datepicker-calendar"

It must never show. I want to only use the date and year selection.

The best place it seems is to look at "beforeShow"

```<code>$("#datepicker").datepicker({ dateFormat: 'dd/mm/yy', beforeShow: myFunction});

function myFunction(input,inst)
{
    alert(inst);
    $(".ui-datepicker-calendar").remove();
   //$(".ui-datepicker-calendar").destroy(); //this causes infinite loop
}
</code>```

It this possible?
http://jsfiddle.net/UEnqL/9/

I have tried "destroy", "hide" it just comes back on the next click.

答:
```<code>$("#datepicker").focus(function(){
    $(".ui-datepicker-calendar").remove()
})
</code>```

Use the above code to remove the "ui-datepicker-calendar" section.

Body:
I need a datepicker to never show the day section.

I want to thus destroy/remove this element : "ui-datepicker-calendar"

It must never show. I want to only use the date and year selection.

The best place it seems is to look at "beforeShow"

$("#datepicker").datepicker({ dateFormat: 'dd/mm/yy', beforeShow: myFunction});

function myFunction(input,inst)
{
    alert(inst);
    $(".ui-datepicker-calendar").remove();
   //$(".ui-datepicker-calendar").destroy(); //this causes infinite loop
}

It this possible?
http://jsfiddle.net/UEnqL/9/

I have tried "destroy", "hide" it just comes back on the next click.

Body:
$("#datepicker").focus(function(){
    $(".ui-datepicker-calendar").remove()
})

Use the above code to remove the "ui-datepicker-calendar" section.


问:
Get substing of a column in Oracle 11g
I have a column with a long text, and i need to find an specific string inside of it.

for example:
the column contains this: "Hello mi number is C.C. 2313"

and i need to extract "C.C. 2313"

Im using an Oracle 11g Database.

答:
Variable separators are tricky in Oracle.  Here is one method:

```<code>select substr(col, length(regexp_substr(col, '.*(cc|[cC][.][cC][.]')) + 1)
</code>```

Oh, the above removes the separator.  You want it, so that is easier:

```<code>select regexp_substr(col, 'cc|[cC][.][cC][.].*')
</code>```

Title: Get substing of a column in Oracle 11g

Body:
Variable separators are tricky in Oracle.  Here is one method:

select substr(col, length(regexp_substr(col, '.*(cc|[cC][.][cC][.]')) + 1)

Oh, the above removes the separator.  You want it, so that is easier:

select regexp_substr(col, 'cc|[cC][.][cC][.].*')


问:
Reading between certain lines
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!</p>

```<code># DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

答:
To be honest, the "best" solution depends on your file.  For example:

if the file is immense, slurping it all in via <> or $_ might not be wise, whereas if it's "small", that would be fine.

does the file have as regular a structure as the the sample shown?  In that snippet the blocks occur on a repeating schedule: Stats1 blocks are at lines 3, 19, 35, ..., 3+16n and ending at "7+16n".  So it might be as simple as reading the file in and only printing the lines if the line number is between 3 and 7 modulo 16.

On the optimistic assumption that the file is well-structured, it might be as simple as this:

```<code>open(IN, "inp.txt") or die;
while (my $line = <IN>)
{
  chomp $line;
  if ( ($. % 16 >= 3) &&
       ($. % 16 <= 7)    )
  {
     print "$line\n";
  }
}
close(IN);
</code>```

Title: Reading between certain lines

Body:
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!

# DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Body:
To be honest, the "best" solution depends on your file.  For example:

if the file is immense, slurping it all in via <> or $_ might not be wise, whereas if it's "small", that would be fine.

does the file have as regular a structure as the the sample shown?  In that snippet the blocks occur on a repeating schedule: Stats1 blocks are at lines 3, 19, 35, ..., 3+16n and ending at "7+16n".  So it might be as simple as reading the file in and only printing the lines if the line number is between 3 and 7 modulo 16.

On the optimistic assumption that the file is well-structured, it might be as simple as this:

open(IN, "inp.txt") or die;
while (my $line = <IN>)
{
  chomp $line;
  if ( ($. % 16 >= 3) &&
       ($. % 16 <= 7)    )
  {
     print "$line\n";
  }
}
close(IN);


问:
Is there a shorter way to make a unit converter program in C?
i am making a unit convert program, but my code is too long and just go on forever, here is the first part of my code :

```<code>int measure;
int from;
int to;
float input;
float output;

printf("Choose measurement :\n1 : Length\n2 : Area\n3 : Temparture\n");
measure = getch();

switch(measure){
    case '1' :
        printf("\nYou want to change from :\n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        from = getch();
        printf("\nTo : \n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        to = getch();

        printf("Enter number : ");   scanf("%f", &input);

        switch(from){
            case '1' :
                switch(to){
                    case '1' : output = input;                printf("%f mm = %f mm", input, output);   break;
                    case '2' : output = input/10;             printf("%f mm = %f cm", input, output);   break;
                    case '3' : output = input/1000;           printf("%f mm = %f dm", input, output);   break;
                    case '4' : output = input/10000;          printf("%f mm = %f m", input, output);   break;
                    case '5' : output = input/100000;         printf("%f mm = %f dcm", input, output);   break;
                    case '6' : output = input/1000000;        printf("%f mm = %f hm", input, output);   break;
                    case '7' : output = input/10000000;       printf("%f mm = %f km", input, output);   break;
                }
                break;

            case '2' :
                 switch(to){
                    case '1' : output = input*10;           printf("%f cm = %f mm", input, output);   break;
                    case '2' : output = input;              printf("%f cm = %f cm", input, output);   break;
                    case '3' : output = input/10;           printf("%f cm = %f dm", input, output);   break;
                    case '4' : output = input/100;          printf("%f cm = %f m", input, output);   break;
                    case '5' : output = input/1000;         printf("%f cm = %f dcm", input, output);   break;
                    case '6' : output = input/10000;        printf("%f cm = %f hm", input, output);   break;
                    case '7' : output = input/100000;       printf("%f cm = %f km", input, output);   break;
                }
                break;
</code>```

and it will go on case 3,4,5, ... until the kilometer, not including the area and the temparture measurement, and other thing i want to add

Is there any shorter way to do this ? Thanks :)

答:
Yes you can remove a lot of this duplication.  Try and see where things repeat unnecessarily and see where they differ.  If you think you can handle the difference programmatically, then you should try it and you may have simplified it a bit further.

I would also recommend you check the inputs the user gives you so you don't suffer from a buffer over/underflow.

Edit: removed fromMeter; dividing by toMeter is the same thing.

```<code>int fromIdx, toIdx;
char measure, from, to;
float input, output;
char *unit[] = {"mm", "cm", "dm", "m", "dcm", "hm", "km"};
float toMeter[] = {0.001, 0.01, 0.1, 1, 10, 100, 1000};

printf("Choose measurement :\n1 : Length\n2 : Area\n3 : Temparture\n");
scanf("%c", &measure);

switch(measure){
    case '1' :
        printf("\nYou want to change from :\n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        scanf(" %c", &from);
        if(from < '1' || from > '7') {
            // invalid choice
            return;
        }
        fromIdx = from - '1';

        printf("\nTo : \n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        scanf(" %c", &to);
        if(to < '1' || to > '7') {
            // invalid choice
            return;
        }
        toIdx = to - '1';

        printf("Enter number : ");   scanf(" %f", &input);
        output = input * toMeter[fromIdx] / toMeter[toIdx];

        printf("%f %s = %f %s\n", input, unit[fromIdx], output, unit[toIdx]);
        break;
}
</code>```

Body:
i am making a unit convert program, but my code is too long and just go on forever, here is the first part of my code :

int measure;
int from;
int to;
float input;
float output;

printf("Choose measurement :\n1 : Length\n2 : Area\n3 : Temparture\n");
measure = getch();

switch(measure){
    case '1' :
        printf("\nYou want to change from :\n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        from = getch();
        printf("\nTo : \n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        to = getch();

        printf("Enter number : ");   scanf("%f", &input);

        switch(from){
            case '1' :
                switch(to){
                    case '1' : output = input;                printf("%f mm = %f mm", input, output);   break;
                    case '2' : output = input/10;             printf("%f mm = %f cm", input, output);   break;
                    case '3' : output = input/1000;           printf("%f mm = %f dm", input, output);   break;
                    case '4' : output = input/10000;          printf("%f mm = %f m", input, output);   break;
                    case '5' : output = input/100000;         printf("%f mm = %f dcm", input, output);   break;
                    case '6' : output = input/1000000;        printf("%f mm = %f hm", input, output);   break;
                    case '7' : output = input/10000000;       printf("%f mm = %f km", input, output);   break;
                }
                break;

            case '2' :
                 switch(to){
                    case '1' : output = input*10;           printf("%f cm = %f mm", input, output);   break;
                    case '2' : output = input;              printf("%f cm = %f cm", input, output);   break;
                    case '3' : output = input/10;           printf("%f cm = %f dm", input, output);   break;
                    case '4' : output = input/100;          printf("%f cm = %f m", input, output);   break;
                    case '5' : output = input/1000;         printf("%f cm = %f dcm", input, output);   break;
                    case '6' : output = input/10000;        printf("%f cm = %f hm", input, output);   break;
                    case '7' : output = input/100000;       printf("%f cm = %f km", input, output);   break;
                }
                break;

and it will go on case 3,4,5, ... until the kilometer, not including the area and the temparture measurement, and other thing i want to add

Is there any shorter way to do this ? Thanks :)

Body:
Yes you can remove a lot of this duplication.  Try and see where things repeat unnecessarily and see where they differ.  If you think you can handle the difference programmatically, then you should try it and you may have simplified it a bit further.

I would also recommend you check the inputs the user gives you so you don't suffer from a buffer over/underflow.

Edit: removed fromMeter; dividing by toMeter is the same thing.

int fromIdx, toIdx;
char measure, from, to;
float input, output;
char *unit[] = {"mm", "cm", "dm", "m", "dcm", "hm", "km"};
float toMeter[] = {0.001, 0.01, 0.1, 1, 10, 100, 1000};

printf("Choose measurement :\n1 : Length\n2 : Area\n3 : Temparture\n");
scanf("%c", &measure);

switch(measure){
    case '1' :
        printf("\nYou want to change from :\n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        scanf(" %c", &from);
        if(from < '1' || from > '7') {
            // invalid choice
            return;
        }
        fromIdx = from - '1';

        printf("\nTo : \n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        scanf(" %c", &to);
        if(to < '1' || to > '7') {
            // invalid choice
            return;
        }
        toIdx = to - '1';

        printf("Enter number : ");   scanf(" %f", &input);
        output = input * toMeter[fromIdx] / toMeter[toIdx];

        printf("%f %s = %f %s\n", input, unit[fromIdx], output, unit[toIdx]);
        break;
}


答:
This should help

The below is sample of how you can make it work.

My suggestion, would be to have a trigger on the table, to insert the part of the string as a separate column in the table

    WITH data AS
        (SELECT 'Hello mi number is C.C. 2313' column_Value
        FROM dual
        UNION
        SELECT 'Hello mi number is c.c. 2414' column_Value
        FROM dual
        UNION
        SELECT 'Hello mi number is cc 2515' column_Value
        FROM dual
        )
    SELECT 1,
        SUBSTR(column_value, instr(column_value,'cc') + 2)
    FROM data
    WHERE column_value LIKE '%cc%'
    UNION
    SELECT 2,
        SUBSTR(column_value, instr(column_value,'c.c.',1) + 4)
    FROM data
    WHERE column_value LIKE '%c.c.%'
    UNION
    SELECT 3,
        SUBSTR(column_value, instr(column_value, 'C.C.') + 4)
    FROM data
    WHERE column_value LIKE '%C.C.%'
    ;

Title: Get substing of a column in Oracle 11g

Body:
I have a column with a long text, and i need to find an specific string inside of it.

for example:
the column contains this: "Hello mi number is C.C. 2313"

and i need to extract "C.C. 2313"

Im using an Oracle 11g Database.


问:
How do I correctly clone a JavaScript object?
I have an object x. I'd like to copy it as object y, such that changes to y do not modify x. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted properties. This isn't a problem, since I'm copying one of my own literal-constructed objects.

How do I correctly clone a JavaScript object?

答:
OK, imagine you have this object below and you want to clone it:

```<code>let obj = {a:1, b:2, c:3}; //ES6
</code>```

or

```<code>var obj = {a:1, b:2, c:3}; //ES5
</code>```

the answer is mainly depeneds on which ECMAscript you using, in ES6+, you can simply use Object.assign to do the clone:

```<code>let cloned = Object.assign({}, obj); //new {a:1, b:2, c:3};
</code>```

or using spread operator like this:

```<code>let cloned = {...obj}; //new {a:1, b:2, c:3};
</code>```

But if you using ES5, you can use few methods, but the JSON.stringify, just make sure you not using for a big chunk of data to copy, but it could be one line handy way in many cases, something like this:

```<code>let cloned = JSON.parse(JSON.stringify(obj));
//new {a:1, b:2, c:3};, can be handy, but avoid using on big chunk of data over and over
</code>```

ContentLicense: CC BY-SA 4.0

Body:
OK, imagine you have this object below and you want to clone it:

let obj = {a:1, b:2, c:3}; //ES6

or

var obj = {a:1, b:2, c:3}; //ES5

the answer is mainly depeneds on which ECMAscript you using, in ES6+, you can simply use Object.assign to do the clone:

let cloned = Object.assign({}, obj); //new {a:1, b:2, c:3};

or using spread operator like this:

let cloned = {...obj}; //new {a:1, b:2, c:3};

But if you using ES5, you can use few methods, but the JSON.stringify, just make sure you not using for a big chunk of data to copy, but it could be one line handy way in many cases, something like this:

let cloned = JSON.parse(JSON.stringify(obj));
//new {a:1, b:2, c:3};, can be handy, but avoid using on big chunk of data over and over


问:
No resource identifier found for attribute 'text color' in package 'android' --- When building
I am new and now using Android Studio. I have created single page design using XML but when i run the code using the emulator this message appears:

Information:Gradle tasks [:app:assembleDebug]
  C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\src\main\res\layout\activity_main.xml
  Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android'

C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\build\intermediates\res\merged\debug\layout\activity_main.xml

Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android' Error:Execution failed for
  task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt Information:BUILD FAILED Information:Total time: 1 mins 25.346 secs Information:5 errors Information:0 warnings Information:See complete output in console

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Please help.

答:
There is no specific "fontColor" attribute of TextView, that is why it is giving you that error.

Add

```<code>android:textColor="#FFFFFF"
</code>```

and then clean your project and rebuild.

Body:
I am new and now using Android Studio. I have created single page design using XML but when i run the code using the emulator this message appears:

Information:Gradle tasks [:app:assembleDebug]
  C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\src\main\res\layout\activity_main.xml
  Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android'

C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\build\intermediates\res\merged\debug\layout\activity_main.xml

Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android' Error:Execution failed for
  task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt Information:BUILD FAILED Information:Total time: 1 mins 25.346 secs Information:5 errors Information:0 warnings Information:See complete output in console

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Please help.

Body:
There is no specific "fontColor" attribute of TextView, that is why it is giving you that error.

Add

android:textColor="#FFFFFF"

and then clean your project and rebuild.


问:
How to calculate number of business days in Golang
I have this so far to count the number of days using http://golang.org/pkg/time/ but I don't know how to exclude weekends and only count business days.</p>

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    f := time.Date(2015, time.August, 21, 24, 0, 0, 0, time.UTC)
    diff := f.Sub(t)

    // convert diff to days
    days := int(diff.Hours() / 24)

    fmt.Printf("days  %d\n", days)
}
</code>```

答:
Realizing that we are calculating an integral and remembering that integrals are usually calculated using primitive functions, which can be taken to be the integral from some fixed time, we can write the following code.

The function primitive() gives the number of workdays since 3 January 2000, chosen to be a Monday to simplify the formula. The number of workdays between two dates is then given by the difference of primitive() for the two days.

```<code>package main

import (
    "fmt"
    "time"
)

type Date struct {
    year int
    month time.Month
    day int
}

func date2unix(d Date, loc *time.Location) int64 {
    return time.Date(d.year, d.month, d.day, 0, 0, 0, 0, loc).Unix()
}

func primitive(d Date, loc *time.Location) int64 {
    // 3 January 2000 was a Monday
    base := Date{2000, time.January, 3}
    seconds := date2unix(d, loc) - date2unix(base, loc)
    weeks := seconds / (7*24*60*60)
    seconds_into_week := seconds % (7*24*60*60)
    workdays := seconds_into_week / (24*60*60)
    if workdays > 5 {
        workdays = 5
    }

    return 5*weeks + workdays
}

func DayCountExcludingWeekends(from, to Date, loc *time.Location) int {
    return int(primitive(to, loc) - primitive(from, loc))
}

func main() {
    loc, err := time.LoadLocation("Europe/Stockholm")
    if err != nil {
        panic(err)
    }

    f := Date{2017, 6, 28}
    t := Date{2017, 7,  6}

    fmt.Println(DayCountExcludingWeekends(f, t, loc))
}
</code>```

https://play.golang.org/p/_wxw8-PyMO

https://goplay.space/#wWU0Stv5zO

Body:
I have this so far to count the number of days using http://golang.org/pkg/time/ but I don't know how to exclude weekends and only count business days.

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    f := time.Date(2015, time.August, 21, 24, 0, 0, 0, time.UTC)
    diff := f.Sub(t)

    // convert diff to days
    days := int(diff.Hours() / 24)

    fmt.Printf("days  %d\n", days)
}

Body:
Realizing that we are calculating an integral and remembering that integrals are usually calculated using primitive functions, which can be taken to be the integral from some fixed time, we can write the following code.

The function primitive() gives the number of workdays since 3 January 2000, chosen to be a Monday to simplify the formula. The number of workdays between two dates is then given by the difference of primitive() for the two days.

package main

import (
    "fmt"
    "time"
)

type Date struct {
    year int
    month time.Month
    day int
}

func date2unix(d Date, loc *time.Location) int64 {
    return time.Date(d.year, d.month, d.day, 0, 0, 0, 0, loc).Unix()
}

func primitive(d Date, loc *time.Location) int64 {
    // 3 January 2000 was a Monday
    base := Date{2000, time.January, 3}
    seconds := date2unix(d, loc) - date2unix(base, loc)
    weeks := seconds / (7*24*60*60)
    seconds_into_week := seconds % (7*24*60*60)
    workdays := seconds_into_week / (24*60*60)
    if workdays > 5 {
        workdays = 5
    }

    return 5*weeks + workdays
}

func DayCountExcludingWeekends(from, to Date, loc *time.Location) int {
    return int(primitive(to, loc) - primitive(from, loc))
}

func main() {
    loc, err := time.LoadLocation("Europe/Stockholm")
    if err != nil {
        panic(err)
    }

    f := Date{2017, 6, 28}
    t := Date{2017, 7,  6}

    fmt.Println(DayCountExcludingWeekends(f, t, loc))
}

https://play.golang.org/p/_wxw8-PyMO

https://goplay.space/#wWU0Stv5zO


问:
d3.each() index doesn't begin at 0
My question is very similar to this. The solution there was that there was a
 messing things up. There are no <divs> in mine.

I have this CoffeeScript code:

```<code>data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )
</code>```

With the desired console output being:

```<code>0 0
1 1
2 2
3 3
4 4
</code>```

The actual console output is:

```<code>1 1
2 2
3 3
4 4
</code>```

I can get the desired output with this code:

```<code>data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .each((d, i) =>
    console.log(i, d)
  ).enter()
   .each((d, i) =>
    console.log(i, d)
  )
</code>```

But it just feels wrong to have two .each() calls.

答:
d3.each() does begin at index 0. What you're seeing in your code is the expected behaviour, given what you have in your code.

The issue here is simple: there is a  element in the page, of course. Your data array has 5 elements, and one of them is being bound to the .

Let's show this. Have a look at the size of the "enter" selection:

data = [0, 1, 2, 3, 4]
var foo = d3.select("body")
  .data(data)
  .enter();

console.log("Size of enter selection: " + foo.size())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

We can also show that the first element in the array was bound to the :

data = [0, 1, 2, 3, 4]
var foo = d3.select("body")
  .data(data)
  .enter();

console.log("Data of body: " + d3.select("body").data())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

Yet another way for showing this is using the third argument (technically speaking, parameter), which is the current group:

```<code>data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .enter()
  .each((d, i, p) =>
  //           ^---- this is the third argument
    console.log(p)
  )
</code>```

Here I cannot provide a working Stack snippet, because it crashes if we try to log a D3 selection. But the result will be this:

```<code>[undefined × 1, EnterNode, EnterNode, EnterNode, EnterNode]
</code>```

That undefined is the "update" selection (the body), and the 4 EnterNodes are the "enter" selection. And that brings us to the explanation of why each() behaves that way in your code.

If you have a look at the source code...

```<code>function(callback) {

    for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
        for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
            if (node = group[i]) callback.call(node, node.__data__, i, group);
        }
    }

    return this;
}
</code>```

You're gonna see that it works comparing the nodes to the group, and your group contains both the "update" selection and the "enter" selection. The update selection corresponds to index 0 and the enter selection corresponds to indices 1, 2, 3, and 4.

Solution:

This is what you want, pay attention to selectAll and null:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .selectAll(null)
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

Thus, as you can see, selecting null assure us that our "enter" selection  always have all the elements in the data array.

Bonus: select and selectAll behave differently. Most people think that the only difference is that the former selects only 1 element and the latter selects all the elements. But there are more subtle differences. Have a look at this table:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

Title: d3.each() index doesn't begin at 0

Body:
My question is very similar to this. The solution there was that there was a
 messing things up. There are no <divs> in mine.

I have this CoffeeScript code:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )

With the desired console output being:

0 0
1 1
2 2
3 3
4 4

The actual console output is:

1 1
2 2
3 3
4 4

I can get the desired output with this code:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .each((d, i) =>
    console.log(i, d)
  ).enter()
   .each((d, i) =>
    console.log(i, d)
  )

But it just feels wrong to have two .each() calls.

Body:
d3.each() does begin at index 0. What you're seeing in your code is the expected behaviour, given what you have in your code.

The issue here is simple: there is a <body> element in the page, of course. Your data array has 5 elements, and one of them is being bound to the <body>.

Let's show this. Have a look at the size of the "enter" selection:

data = [0, 1, 2, 3, 4]
var foo = d3.select("body")
  .data(data)
  .enter();

console.log("Size of enter selection: " + foo.size())

<script src="https://d3js.org/d3.v4.js"></script>

We can also show that the first element in the array was bound to the <body>:

data = [0, 1, 2, 3, 4]
var foo = d3.select("body")
  .data(data)
  .enter();

console.log("Data of body: " + d3.select("body").data())

<script src="https://d3js.org/d3.v4.js"></script>

Yet another way for showing this is using the third argument (technically speaking, parameter), which is the current group:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .enter()
  .each((d, i, p) =>
  //           ^---- this is the third argument
    console.log(p)
  )

Here I cannot provide a working Stack snippet, because it crashes if we try to log a D3 selection. But the result will be this:

[undefined × 1, EnterNode, EnterNode, EnterNode, EnterNode]

That undefined is the "update" selection (the body), and the 4 EnterNodes are the "enter" selection. And that brings us to the explanation of why each() behaves that way in your code.

If you have a look at the source code...

function(callback) {

    for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
        for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
            if (node = group[i]) callback.call(node, node.__data__, i, group);
        }
    }

    return this;
}

You're gonna see that it works comparing the nodes to the group, and your group contains both the "update" selection and the "enter" selection. The update selection corresponds to index 0 and the enter selection corresponds to indices 1, 2, 3, and 4.

Solution:

This is what you want, pay attention to selectAll and null:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .selectAll(null)
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )

<script src="https://d3js.org/d3.v4.js"></script>

Thus, as you can see, selecting null assure us that our "enter" selection  always have all the elements in the data array.

Bonus: select and selectAll behave differently. Most people think that the only difference is that the former selects only 1 element and the latter selects all the elements. But there are more subtle differences. Have a look at this table:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data


问:
How to send form data with a POST request?
I want to view and scrape job listings on the https://www.akzonobel.com/nl/careers/vacatures/ website. The country has to be "The Netherlands" and the Job level is "Entry level".

I'm using httparty to send a POST request but it keeps returning the initial 10 job listings. The correct response should be 3 job listings.

This is the code I'm using:

```<code>require 'httparty'
require 'nokogiri'

@base_url = 'https://www.akzonobel.com'

url = "#{@base_url}/careers/vacatures/"

data = {
  'ctl00$contentLeft$ctl01$ddlCountryExt' => 'NLD',
  'ctl00$contentLeft$ctl01$ddlJobLevelExt' => 'ENTRY_LEVEL'
}

response = HTTParty.post("#{@base_url}/nl/careers/vacatures/", :body => data)

html = Nokogiri::HTML(response)

jobs = html.xpath('//h3//a')

jobs.each do |job|
  puts job.text
end

puts jobs.size
</code>```

Which returns:

```<code>Regional Demand Planner Nordeuropa (m,w)
Forecast Analyst - TiO2 Spend Area
PS Regional Manager APAC
Production leader
Engineering Administrator - Temporary
Procurement Manager EMEA
Business Analyst, Americas
HR Business Partner Supply Chain and R&D
AS Regional Manager
Business Information Manager
10
</code>```

How can I send the form data needed to the site to get the correct response?

Update:

I've tried the following:

```<code>require 'httparty'
require 'nokogiri'

@base_url = 'https://www.akzonobel.com'

url = "#{@base_url}/careers/vacatures/"

data = {
  'ctl00$contentLeft$ctl01$ddlCountryExt' => 'NLD',
  'ctl00$contentLeft$ctl01$ddlJobLevelExt' => 'ENTRY_LEVEL',
  'ctl00$contentLeft$ctl01$ddlContinentExt' => 1,
  'ctl00$contentLeft$ctl01$ddlRegionEx' => 4,
  'ctl00$contentLeft$ctl01$ddlJobFamilyEx' => 45,
  'ctl00$contentLeft$ctl01$ddlBusinessUnitExt' => 22,
  'ctl00$contentLeft$ctl01$ddlJobLevelExt' => 1,
  'ctl00$contentLeft$ctl01$ddlCountryExt' => 1,
}

response = HTTParty.post("#{@base_url}/nl/careers/vacatures/", :body => data)

html = Nokogiri::HTML(response)

jobs = html.xpath('//h3//a')

jobs.each do |job|
  puts job.text
end

puts jobs.size
</code>```

Unfortunately the result is exactly the same.

Update 2:

Here's the updated code:

```<code>require 'httparty'
require 'nokogiri'

@base_url = 'https://www.akzonobel.com'

url = "#{@base_url}/careers/vacatures/"

data = {
  'contentLeft_ctl01_ddlContinentExt' => 'C_EUROPE',
  'contentLeft_ctl01_ddlCountryExt' => 'NLD',
  'contentLeft_ctl01_ddlRegionExt' => 'Gelderland',
  'contentLeft_ctl01_ddlRegionExt' => 'Limburg',
  'contentLeft_ctl01_ddlRegionExt' => 'North Holland',
  'contentLeft_ctl01_ddlRegionExt' => 'South Holland',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'General Management',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Integrated Supply Chain',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Sales & Marketing',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'RD&I',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Support',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Other',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl2_General Management',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Manufacturing',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'HSE',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Engineering',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Procurement',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Distribution & Logistics',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Sales',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Marketing',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl2_RD&I',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Finance',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'IM',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'HR',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Legal, IP & Compliance',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Facilities',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl2_Other',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80200000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80300000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81900000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81100000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '82000000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81200000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80700000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80400000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80500000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80800000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80900000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '82100000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '82200000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81010000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81020000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81030000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81040000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81300000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81410000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81420000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81430000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81600000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81700000',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl3_Other',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000100',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000200',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000300',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000900',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000010',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000013',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000020',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000022',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000026',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000033',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000038',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000041',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000054',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000055',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000056',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000061',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000063',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000100',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000300',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000900',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000901',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '51000000',
  'contentLeft_ctl01_ddlJobLevelExt' => 'ENTRY_LEVEL'
}

response = HTTParty.post("#{@base_url}/nl/careers/vacatures/", :body => data)

html = Nokogiri::HTML(response)

jobs = html.xpath('//h3//a')

jobs.each do |job|
  puts job.text
end

puts jobs.size
</code>```

Giving me the exact same result as before.

答:
I think the problem can be solved by changing this piece of code to a loop that only outputs job.text 3 times.

so change this,

```<code>jobs.each do |job|
  puts job.text
end
</code>```

to this,

```<code>for (i=0; i < 3; i++) {
 puts job.text
}
</code>```

Body:
I want to view and scrape job listings on the https://www.akzonobel.com/nl/careers/vacatures/ website. The country has to be "The Netherlands" and the Job level is "Entry level".

I'm using httparty to send a POST request but it keeps returning the initial 10 job listings. The correct response should be 3 job listings.

This is the code I'm using:

require 'httparty'
require 'nokogiri'

@base_url = 'https://www.akzonobel.com'

url = "#{@base_url}/careers/vacatures/"

data = {
  'ctl00$contentLeft$ctl01$ddlCountryExt' => 'NLD',
  'ctl00$contentLeft$ctl01$ddlJobLevelExt' => 'ENTRY_LEVEL'
}

response = HTTParty.post("#{@base_url}/nl/careers/vacatures/", :body => data)

html = Nokogiri::HTML(response)

jobs = html.xpath('//h3//a')

jobs.each do |job|
  puts job.text
end

puts jobs.size

Which returns:

Regional Demand Planner Nordeuropa (m,w)
Forecast Analyst - TiO2 Spend Area
PS Regional Manager APAC
Production leader
Engineering Administrator - Temporary
Procurement Manager EMEA
Business Analyst, Americas
HR Business Partner Supply Chain and R&D
AS Regional Manager
Business Information Manager
10

How can I send the form data needed to the site to get the correct response?

Update:

I've tried the following:

require 'httparty'
require 'nokogiri'

@base_url = 'https://www.akzonobel.com'

url = "#{@base_url}/careers/vacatures/"

data = {
  'ctl00$contentLeft$ctl01$ddlCountryExt' => 'NLD',
  'ctl00$contentLeft$ctl01$ddlJobLevelExt' => 'ENTRY_LEVEL',
  'ctl00$contentLeft$ctl01$ddlContinentExt' => 1,
  'ctl00$contentLeft$ctl01$ddlRegionEx' => 4,
  'ctl00$contentLeft$ctl01$ddlJobFamilyEx' => 45,
  'ctl00$contentLeft$ctl01$ddlBusinessUnitExt' => 22,
  'ctl00$contentLeft$ctl01$ddlJobLevelExt' => 1,
  'ctl00$contentLeft$ctl01$ddlCountryExt' => 1,
}

response = HTTParty.post("#{@base_url}/nl/careers/vacatures/", :body => data)

html = Nokogiri::HTML(response)

jobs = html.xpath('//h3//a')

jobs.each do |job|
  puts job.text
end

puts jobs.size

Unfortunately the result is exactly the same.

Update 2:

Here's the updated code:

require 'httparty'
require 'nokogiri'

@base_url = 'https://www.akzonobel.com'

url = "#{@base_url}/careers/vacatures/"

data = {
  'contentLeft_ctl01_ddlContinentExt' => 'C_EUROPE',
  'contentLeft_ctl01_ddlCountryExt' => 'NLD',
  'contentLeft_ctl01_ddlRegionExt' => 'Gelderland',
  'contentLeft_ctl01_ddlRegionExt' => 'Limburg',
  'contentLeft_ctl01_ddlRegionExt' => 'North Holland',
  'contentLeft_ctl01_ddlRegionExt' => 'South Holland',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'General Management',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Integrated Supply Chain',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Sales & Marketing',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'RD&I',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Support',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Other',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl2_General Management',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Manufacturing',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'HSE',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Engineering',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Procurement',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Distribution & Logistics',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Sales',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Marketing',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl2_RD&I',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Finance',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'IM',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'HR',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Legal, IP & Compliance',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Facilities',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl2_Other',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80200000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80300000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81900000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81100000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '82000000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81200000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80700000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80400000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80500000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80800000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '80900000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '82100000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '82200000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81010000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81020000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81030000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81040000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81300000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81410000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81420000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81430000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81600000',
  'contentLeft_ctl01_ddlJobFamilyExt' => '81700000',
  'contentLeft_ctl01_ddlJobFamilyExt' => 'Lvl3_Other',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000100',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000200',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000300',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '52000900',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000010',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000013',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000020',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000022',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000026',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000033',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000038',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000041',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000054',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000055',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000056',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000061',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000063',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000100',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000300',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000900',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '53000901',
  'contentLeft_ctl01_ddlBusinessUnitExt' => '51000000',
  'contentLeft_ctl01_ddlJobLevelExt' => 'ENTRY_LEVEL'
}

response = HTTParty.post("#{@base_url}/nl/careers/vacatures/", :body => data)

html = Nokogiri::HTML(response)

jobs = html.xpath('//h3//a')

jobs.each do |job|
  puts job.text
end

puts jobs.size

Giving me the exact same result as before.

Body:
I think the problem can be solved by changing this piece of code to a loop that only outputs job.text 3 times.

so change this,

jobs.each do |job|
  puts job.text
end

to this,

for (i=0; i < 3; i++) {
 puts job.text
}


问:
do I need multiple tables or single?
I developing a tool which may got more than a million data to fill in.

current i have designed single table with 36 coloumns. my question is do I need to divide these into multiple tables or single??

If single what is the advantage and disadvantage

if multiple then what is the advantage and disadvantage

and what will be the engine to use for speed...

my concern is a large database which will have atleast 50000 queries perday..

any help??

答:
Yes, you should normalize your database.  A general rule of thumb is that if a column that isn't a foreign key contains duplicate values, the table should be normalized.

Normalization involves splitting your database into tables, and helps to:

Avoid modification anomolies.

Minimize impact of changes to the data structure.

Make the data model more informative.

There is plenty of information about normalization on Wikipedia.

If you have a serious amount of data and don't normalize, you will eventually come to a point where you will need to redesign your database, and this is incredibly hard to do retrospectively, as it will involve not only changing any code that accesses the database, but also migrating all existing data to the new design.

There are cases where it might be better to avoid normalization for performance reasons, but you should have a good understanding of normalization before making this decision.

Title: do I need multiple tables or single?


问:
How to write the curl command to imitate get method?
```<code>cd /var/www/html/phplearn
</code>```

For the http post request and response.

vim send_local_post.php

```<code><form action=http://127.0.0.1/phplearn/do_post.php method=post>
user:  <input type=text name=userName size=12/>
key:    <input type=text name=PS size=12/>
<input type=submit value=login>
</form>
</code>```

vim  do_post.php

```<code><?php
$userName = $_POST["userName"];
$PS = $_POST["PS"];
echo "the name is:  ".$userName."\n";
echo "key word is:  ".$PS."\n";
?>
</code>```

Let's imitate post method with curl in console.

```<code>curl -X POST -d "userName=user&PS=key"  127.0.0.1/phplearn/do_post.php
</code>```

The output in console is as below:

For the http get request and response.

vim send_local.get.php

```<code><form action=http://127.0.0.1/phplearn/do_get.php method=get>
user:  <input type=text name=userName size=12/>
key:   <input type=text name=PS size=12/>
<input type=submit value=login>
</form>
</code>```

vim  do_get.php

```<code><?php
$userName = $_GET["userName"];
$PS = $_GET["PS"];
echo "the name is:  ".$userName."\n";
echo "key word is:  ".$PS."\n";
?>
</code>```

Let's imitate get method with curl in console.

```<code>curl  http://127.0.0.1/phplearn/do_get.php?userName=user&PS=key
</code>```

The output in console is as below:

Why the key value can't displayed on the console such as post method?

答:
This is because of the ampersand. When bash hits the ampersand it triggers a background process, and cuts off the remaining text.

This is also why you see [1] 14975 because it's spinning off a new process, and running it in the background.

To fix this, simply enclose your url in quotes:

```<code>curl "http://127.0.0.1/phplearn/do_get.php?userName=user&PS=key"
</code>```

Body:
cd /var/www/html/phplearn

For the http post request and response.

vim send_local_post.php

<form action=http://127.0.0.1/phplearn/do_post.php method=post>
user:  <input type=text name=userName size=12/>
key:    <input type=text name=PS size=12/>
<input type=submit value=login>
</form>

vim  do_post.php

<?php
$userName = $_POST["userName"];
$PS = $_POST["PS"];
echo "the name is:  ".$userName."\n";
echo "key word is:  ".$PS."\n";
?>

Let's imitate post method with curl in console.

curl -X POST -d "userName=user&PS=key"  127.0.0.1/phplearn/do_post.php

The output in console is as below:

For the http get request and response.

vim send_local.get.php

<form action=http://127.0.0.1/phplearn/do_get.php method=get>
user:  <input type=text name=userName size=12/>
key:   <input type=text name=PS size=12/>
<input type=submit value=login>
</form>

vim  do_get.php

<?php
$userName = $_GET["userName"];
$PS = $_GET["PS"];
echo "the name is:  ".$userName."\n";
echo "key word is:  ".$PS."\n";
?>

Let's imitate get method with curl in console.

curl  http://127.0.0.1/phplearn/do_get.php?userName=user&PS=key

The output in console is as below:

Why the key value can't displayed on the console such as post method?

Body:
This is because of the ampersand. When bash hits the ampersand it triggers a background process, and cuts off the remaining text.

This is also why you see [1] 14975 because it's spinning off a new process, and running it in the background.

To fix this, simply enclose your url in quotes:

curl "http://127.0.0.1/phplearn/do_get.php?userName=user&PS=key"


问:
Inheriting into Base Class Namespace
I have a Class A that has some protected members that I want my base Class B to access. I also want Class B to be in the namespace under Class A. Is this possible?

```<code>Namespace BLL
   Public Class A
      Protected varA As Integer
      Protected varB As String
   End Class
End Namespace

Namespace BLL.A
   Public Class B
      Inherits A
      Public Sub setA()
         varA = 3
         varB = "test"
      End Sub
   End Class
End Namespace
</code>```

I then want to be able to access Class B like so:

```<code>BLL.A.B.setA()
</code>```

When I do this I am getting an error "'A' is ambiguous in the namespace BLL". What am I doing wrong?

答:
A isn't a namespace, it's a class. You'll have to put B inside of class A.

```<code>Namespace BLL
    Public Class A
        Protected varA As Integer
        Protected varB As String
    End Class
End Namespace

Namespace BLL
    Partial Public Class A
        Public Class B
            Inherits A
            Public Sub setA()
                varA = 3
                varB = "test"
            End Sub
        End Class
    End Class
End Namespace
</code>```

Which I do not recommend of doing. The framework rarely have classes inside of class, especially public ones. But, I'm just one random person on the internet :)

If you really want namespace, I would rename class A something like CarBase and put the other classes in a namespace called Car.

Title: Inheriting into Base Class Namespace

Body:
I have a Class A that has some protected members that I want my base Class B to access. I also want Class B to be in the namespace under Class A. Is this possible?

Namespace BLL
   Public Class A
      Protected varA As Integer
      Protected varB As String
   End Class
End Namespace

Namespace BLL.A
   Public Class B
      Inherits A
      Public Sub setA()
         varA = 3
         varB = "test"
      End Sub
   End Class
End Namespace

I then want to be able to access Class B like so:

BLL.A.B.setA()

When I do this I am getting an error "'A' is ambiguous in the namespace BLL". What am I doing wrong?

Body:
A isn't a namespace, it's a class. You'll have to put B inside of class A.

Namespace BLL
    Public Class A
        Protected varA As Integer
        Protected varB As String
    End Class
End Namespace

Namespace BLL
    Partial Public Class A
        Public Class B
            Inherits A
            Public Sub setA()
                varA = 3
                varB = "test"
            End Sub
        End Class
    End Class
End Namespace

Which I do not recommend of doing. The framework rarely have classes inside of class, especially public ones. But, I'm just one random person on the internet :)

If you really want namespace, I would rename class A something like CarBase and put the other classes in a namespace called Car.