问:
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>```

答:
jdbc:h2:~/test","sa","password" OR jdbc:h2:file:~/test;USER=sa;PASSWORD=password

try any of these connection strings.

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)


来源: stackexchange

问:
Cannot get ElasticSearch to map all fields as text
I am trying to map all fields as text. Based on the docs, this should work, but it doesn't:

```<code>PUT my_type
{
  "mappings": {
    "my_type": {
      "dynamic_templates": [
        {
          "longs_as_strings": {
            "match_mapping_type": "*",
            "match":   "*",
            "mapping": {
              "type": "text"
            }
          }
        }
      ]
    }
  }
}

PUT my_type/my_type/1
{
  "intfield": 5
}

GET my_type/_search
</code>```

Results in:

```<code>{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "my_type",
        "_type": "my_type",
        "_id": "1",
        "_score": 1,
        "_source": {
          "intfield": 5
        }
      }
    ]
  }
}
</code>```

答:
This is the solution that ended up working:</p>

```<code>{
    "mappings": {
        "my_record": {
            "dynamic_templates": [{
                "longs_as_strings": {
                    "match_mapping_type": "*",
                    "match": "*",
                    "mapping": {
                        "type": "text"
                    }
                }
            }]
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to map all fields as text. Based on the docs, this should work, but it doesn't:

PUT my_type
{
  "mappings": {
    "my_type": {
      "dynamic_templates": [
        {
          "longs_as_strings": {
            "match_mapping_type": "*",
            "match":   "*",
            "mapping": {
              "type": "text"
            }
          }
        }
      ]
    }
  }
}

PUT my_type/my_type/1
{
  "intfield": 5
}

GET my_type/_search

Results in:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "my_type",
        "_type": "my_type",
        "_id": "1",
        "_score": 1,
        "_source": {
          "intfield": 5
        }
      }
    ]
  }
}

Body:
This is the solution that ended up working:

{
    "mappings": {
        "my_record": {
            "dynamic_templates": [{
                "longs_as_strings": {
                    "match_mapping_type": "*",
                    "match": "*",
                    "mapping": {
                        "type": "text"
                    }
                }
            }]
        }
    }
}


问:
How to install NodeJS LTS on Windows as a local user (without admin rights)
I'm using Windows as a simple user (I don't have any admin rights) and want to install NodeJS LTS.

On the download site I have the choice to download only the binary node.exe (which don't includes npm) or the node.msi installer which requires the admin rights to execute.

How can I manually install node.exe and also be able to use npm?

答:
The nodejs version of 6.11 LTS and later seems to be easier to install, because npm is already included.

Download the node.js LTS binary for Windows and extract it to your
desired location

Add the path of the nodejs folder to the PATH environment variable:
(Shortcut winkey+R and enter: rundll32 sysdm.cpl,EditEnvironmentVariables)

Open a new command window (winkey+R and type cmd)

Type node -v and npm -v to verify the installation

ContentLicense: CC BY-SA 4.0


问:
Passing PHP GET into a jQuery function
I'm using a bit of jquery code which uses li items to select which tab is displayed. the "tabs" are just divs. This is the jQuery code:

```<code>$(document).ready(function() {

            //When page loads...
            $(".tab_content").hide(); //Hide all content
            $("ul.tabs li:first").addClass("active").show(); //Activate first tab
            $(".tab_content:first").show(); //Show first tab content

            //On Click Event
            $("ul.tabs li").click(function() {

                $("ul.tabs li").removeClass("active"); //Remove any "active" class
                $(this).addClass("active"); //Add "active" class to selected tab
                $(".tab_content").hide(); //Hide all tab content

                var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
                $(activeTab).fadeIn(); //Fade in the active ID content
                return false;
            });
        });
</code>```

Where it says li:first and adds the active class to it, i'm trying to figure out how i can change which "tab" gets displayed first depending on a PHP GET result: <?php $tab = $_GET['tab']; ?>

"tab" will be a number 1,2,3 or 4. ie. tab 1, tab 2, etc...so how can i use this PHP variable with jQuery to choose which tab to make Active?

Thanks

答:
What about something like this (assuming the 'tab' GET parameter is an index):</p>

```<code>$("ul.tabs li:nth-child(<?= $_GET['tab'] ?>)").addClass("active").show(); //Activate first tab
$(".tab_content:nth-child(<?= $_GET['tab'] ?>)").show(); //Show first tab content
</code>```

ContentLicense: CC BY-SA 2.5

Title: Passing PHP GET into a jQuery function

Body:
I'm using a bit of jquery code which uses li items to select which tab is displayed. the "tabs" are just divs. This is the jQuery code:

$(document).ready(function() {

            //When page loads...
            $(".tab_content").hide(); //Hide all content
            $("ul.tabs li:first").addClass("active").show(); //Activate first tab
            $(".tab_content:first").show(); //Show first tab content

            //On Click Event
            $("ul.tabs li").click(function() {

                $("ul.tabs li").removeClass("active"); //Remove any "active" class
                $(this).addClass("active"); //Add "active" class to selected tab
                $(".tab_content").hide(); //Hide all tab content

                var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
                $(activeTab).fadeIn(); //Fade in the active ID content
                return false;
            });
        });

Where it says li:first and adds the active class to it, i'm trying to figure out how i can change which "tab" gets displayed first depending on a PHP GET result: <?php $tab = $_GET['tab']; ?>

"tab" will be a number 1,2,3 or 4. ie. tab 1, tab 2, etc...so how can i use this PHP variable with jQuery to choose which tab to make Active?

Thanks

Body:
What about something like this (assuming the 'tab' GET parameter is an index):

$("ul.tabs li:nth-child(<?= $_GET['tab'] ?>)").addClass("active").show(); //Activate first tab
$(".tab_content:nth-child(<?= $_GET['tab'] ?>)").show(); //Show first tab content


问:
How can I distinguish whether Switch,Checkbox Value is changed by user or programmatically (including by retention)?
```<code>setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // How to check whether the checkbox/switch has been checked
                // by user or it has been checked programatically ?

                if (isNotSetByUser())
                    return;
                handleSetbyUser();
            }
        });
</code>```

How to implement method isNotSetByUser()?

答:
The accepted answer could be simplified a bit to not maintain a reference to the original checkbox. This makes it so we can use the SilentSwitchCompat (or SilentCheckboxCompat if you prefer) directly in the XML. I also made it so you can set the OnCheckedChangeListener to null if you desire to do so.

```<code>public class SilentSwitchCompat extends SwitchCompat {
  private OnCheckedChangeListener listener = null;

  public SilentSwitchCompat(Context context) {
    super(context);
  }

  public SilentSwitchCompat(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
    super.setOnCheckedChangeListener(listener);
    this.listener = listener;
  }

  /**
   * Check the {@link SilentSwitchCompat}, without calling the {@code onCheckChangeListener}.
   *
   * @param checked whether this {@link SilentSwitchCompat} should be checked or not.
   */
  public void silentlySetChecked(boolean checked) {
    OnCheckedChangeListener tmpListener = listener;
    setOnCheckedChangeListener(null);
    setChecked(checked);
    setOnCheckedChangeListener(tmpListener);
  }
}
</code>```

You can then use this directly in your XML like so (Note: you will need the whole package name):

```<code><com.my.package.name.SilentCheckBox
      android:id="@+id/my_check_box"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textOff="@string/disabled"
      android:textOn="@string/enabled"/>
</code>```

Then you can check the box silently by calling:

```<code>SilentCheckBox mySilentCheckBox = (SilentCheckBox) findViewById(R.id.my_check_box)
mySilentCheckBox.silentlySetChecked(someBoolean)
</code>```

Body:
setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // How to check whether the checkbox/switch has been checked
                // by user or it has been checked programatically ?

                if (isNotSetByUser())
                    return;
                handleSetbyUser();
            }
        });

How to implement method isNotSetByUser()?

Body:
The accepted answer could be simplified a bit to not maintain a reference to the original checkbox. This makes it so we can use the SilentSwitchCompat (or SilentCheckboxCompat if you prefer) directly in the XML. I also made it so you can set the OnCheckedChangeListener to null if you desire to do so.

public class SilentSwitchCompat extends SwitchCompat {
  private OnCheckedChangeListener listener = null;

  public SilentSwitchCompat(Context context) {
    super(context);
  }

  public SilentSwitchCompat(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
    super.setOnCheckedChangeListener(listener);
    this.listener = listener;
  }

  /**
   * Check the {@link SilentSwitchCompat}, without calling the {@code onCheckChangeListener}.
   *
   * @param checked whether this {@link SilentSwitchCompat} should be checked or not.
   */
  public void silentlySetChecked(boolean checked) {
    OnCheckedChangeListener tmpListener = listener;
    setOnCheckedChangeListener(null);
    setChecked(checked);
    setOnCheckedChangeListener(tmpListener);
  }
}

You can then use this directly in your XML like so (Note: you will need the whole package name):

<com.my.package.name.SilentCheckBox
      android:id="@+id/my_check_box"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textOff="@string/disabled"
      android:textOn="@string/enabled"/>

Then you can check the box silently by calling:

SilentCheckBox mySilentCheckBox = (SilentCheckBox) findViewById(R.id.my_check_box)
mySilentCheckBox.silentlySetChecked(someBoolean)


问:
"no viable alternative postgresql" error message
```<code>  select c_bpartner.name , c_bpartner.c_bpartner_id
  from c_bpartner
  where name in (select ad_org.name
  from ad_org
  where name='orgnamehere'
   )
 where isvendor='Y'
</code>```

Im getting error no viable alternative at input "select". The error is on the select in the sub query.

答:
Remove the last where isvendor='Y' and remplace it with AND isvendor='Y'

```<code>      select c_b.name , c_b.c_bpartner_id
      from c_bpartner c_b
      where c_b.isvendor='Y' AND
             c_b.name in (select a_o.name
                      from ad_org a_o
                      where a_o.name='orgnamehere'
                      )
</code>```

Body:
  select c_bpartner.name , c_bpartner.c_bpartner_id
  from c_bpartner
  where name in (select ad_org.name
  from ad_org
  where name='orgnamehere'
   )
 where isvendor='Y'

Im getting error no viable alternative at input "select". The error is on the select in the sub query.

Body:
Remove the last where isvendor='Y' and remplace it with AND isvendor='Y'

      select c_b.name , c_b.c_bpartner_id
      from c_bpartner c_b
      where c_b.isvendor='Y' AND
             c_b.name in (select a_o.name
                      from ad_org a_o
                      where a_o.name='orgnamehere'
                      )


问:
Spring Security - when to clear SecurityContextHolder
I have a controller and I'm returning user info from that controller:

```<code>@RequestMapping(method = RequestMethod.GET)
Object getUserInfo() {
    return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
</code>```

I have created custom token based authentication using OncePerRequestFilter:

```<code>package gbyf;

import gbyf.token.Token;
import gbyf.token.TokenRepository;
import gbyf.user.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final TokenRepository tokenRepository;

    TokenAuthenticationFilter(TokenRepository tokenRepository) {
        this.tokenRepository = tokenRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String tokenString = request.getHeader("token");

        if(tokenString == null) {
            // user is not authenticated, continue to filter
            chain.doFilter(request, response);
            return;
        }

        Token token = tokenRepository.findTokenByTokenValue(tokenString);

        if(token == null) {
            System.out.println("=====doFilterInternal()==== token is null, not authenticated");
        } else {

            System.out.println("=====doFilterInternal()==== token is NOT null");
            User user = token.getUser();

            if(user != null) {
                Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
                System.out.println("=====doFilterInternal()==== authenticated user");
            }
        }

        super.doFilter(request, response, chain);
    }

}
</code>```

When I sent correct token parameter that found in database, it correctly authenticates the user. But with another wrong token request, server still sends old user authentication principals. Shouldn't SecurityContextHolder flush the authentication detail after request is done.

What can be the problem?

答:
Are you using browser to call the API? If so, then I think session is being created for your user and being tracked via cookies. Try to use stateless session creation policy:</p>

```<code>@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
</code>```

Body:
I have a controller and I'm returning user info from that controller:

@RequestMapping(method = RequestMethod.GET)
Object getUserInfo() {
    return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

I have created custom token based authentication using OncePerRequestFilter:

package gbyf;

import gbyf.token.Token;
import gbyf.token.TokenRepository;
import gbyf.user.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final TokenRepository tokenRepository;

    TokenAuthenticationFilter(TokenRepository tokenRepository) {
        this.tokenRepository = tokenRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String tokenString = request.getHeader("token");

        if(tokenString == null) {
            // user is not authenticated, continue to filter
            chain.doFilter(request, response);
            return;
        }

        Token token = tokenRepository.findTokenByTokenValue(tokenString);

        if(token == null) {
            System.out.println("=====doFilterInternal()==== token is null, not authenticated");
        } else {

            System.out.println("=====doFilterInternal()==== token is NOT null");
            User user = token.getUser();

            if(user != null) {
                Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
                System.out.println("=====doFilterInternal()==== authenticated user");
            }
        }

        super.doFilter(request, response, chain);
    }

}

When I sent correct token parameter that found in database, it correctly authenticates the user. But with another wrong token request, server still sends old user authentication principals. Shouldn't SecurityContextHolder flush the authentication detail after request is done.

What can be the problem?

Body:
Are you using browser to call the API? If so, then I think session is being created for your user and being tracked via cookies. Try to use stateless session creation policy:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}


问:
Integrate a function of three variables C++
I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.

I have a function !

```<code>double integrand(double r, double phi, double theta)
</code>```

That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".

Algorithmically speaking what I wanted to do was :

```<code>double firstIntegral(double r, double phi) {
    double result = integrationFunction(integrand,lower_bound,upper_bound);
    return result;
}
</code>```

And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.

How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?

答:
You can use functors</p>

```<code>#include <iostream>

struct MyFunctorMultiply
{
    double m_coeff;

    MyFunctorMultiply(double coeff)
    {
        m_coeff  = coeff;
    }

    double operator()(double value)
    {
        return m_coeff * value;
    }
};

struct MyFunctorAdd
{
    double m_a;

    MyFunctorAdd(double a)
    {
        m_a  = a;
    }

    double operator()(double value)
    {
        return m_a + value;
    }
};

template<class t_functor>
double calculate(t_functor functor, double value, double other_param)
{

    return functor(value) - other_param;
}

int main()
{
    MyFunctorMultiply multiply2(2.);
    MyFunctorAdd      add3(3.);

    double result_a  = calculate(multiply2, 4, 1); // should obtain 4 * 2 - 1 = 7
    double result_b  = calculate(add3, 5, 6);      // should obtain 5 + 3 - 6 = 2

    std::cout << result_a << std::endl;
    std::cout << result_b << std::endl;
}
</code>```

Body:
I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.

I have a function !

double integrand(double r, double phi, double theta)

That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".

Algorithmically speaking what I wanted to do was :

double firstIntegral(double r, double phi) {
    double result = integrationFunction(integrand,lower_bound,upper_bound);
    return result;
}

And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.

How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?

Body:
You can use functors

#include <iostream>

struct MyFunctorMultiply
{
    double m_coeff;

    MyFunctorMultiply(double coeff)
    {
        m_coeff  = coeff;
    }

    double operator()(double value)
    {
        return m_coeff * value;
    }
};

struct MyFunctorAdd
{
    double m_a;

    MyFunctorAdd(double a)
    {
        m_a  = a;
    }

    double operator()(double value)
    {
        return m_a + value;
    }
};

template<class t_functor>
double calculate(t_functor functor, double value, double other_param)
{

    return functor(value) - other_param;
}

int main()
{
    MyFunctorMultiply multiply2(2.);
    MyFunctorAdd      add3(3.);

    double result_a  = calculate(multiply2, 4, 1); // should obtain 4 * 2 - 1 = 7
    double result_b  = calculate(add3, 5, 6);      // should obtain 5 + 3 - 6 = 2

    std::cout << result_a << std::endl;
    std::cout << result_b << std::endl;
}


问:
How to list all timers of another form
I want to make a procedure that stops all timers of any given form. Though when building it says

"components' is not a member of 'System.Windows.Forms.Form".

Here is the code:

```<code>Public Sub _Timers_Stop(frm As Form)
        For Each itm As Object In frm.components.components
           If TypeOf (itm) Is Timer Then
               itm.stop()
           End If
        Next
End Sub
</code>```

答:
You could use reflection for this:</p>

```<code>Public Sub StopTimers(Form As Form)
    For Each Item In Form.GetType.GetFields(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public).Where(Function(x) TypeOf x.GetValue(Form) Is Timer)
        Dim Timer As Timer
        Timer = Item.GetValue(Form)
        Timer.Stop()
    Next
End Sub
</code>```

Title: How to list all timers of another form

Body:
I want to make a procedure that stops all timers of any given form. Though when building it says

"components' is not a member of 'System.Windows.Forms.Form".

Here is the code:

Public Sub _Timers_Stop(frm As Form)
        For Each itm As Object In frm.components.components
           If TypeOf (itm) Is Timer Then
               itm.stop()
           End If
        Next
End Sub

Body:
You could use reflection for this:

Public Sub StopTimers(Form As Form)
    For Each Item In Form.GetType.GetFields(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public).Where(Function(x) TypeOf x.GetValue(Form) Is Timer)
        Dim Timer As Timer
        Timer = Item.GetValue(Form)
        Timer.Stop()
    Next
End Sub


问:
Swap file returns to original size after reboot
I am trying to increase swapfile size on my raspberry pi 3.
I'm following this guide here on DigitalOcean.

After successfully increasing the file and setting it up using mkswap and swpon commands everything works fine. I even tried filling my ram with random data to see if it is going to use the new swap space and it works perfectly.

However after I reboot my raspberry, swap file returns to the previous (default) size of 100MB.
Is there any way to make this change permanent?

I'm running Raspberry pi 3 on Raspbian Jessie.

答:
Suppose you have got to the point where swapon -s returns

```<code># sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        4194300    0          -1
</code>```

Now to make this change permanent you need to add a record about your new swapfile in fstab.

You need to add the following line:

```<code>/swapfile       none       swap         sw        0      0
</code>```

The meaning of the fstab fields is as follows:

```<code>#1.source   2.mountpoint  3.fstype  4.options   5.freq  6.order
</code>```

Body:
Suppose you have got to the point where swapon -s returns

# sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        4194300    0          -1

Now to make this change permanent you need to add a record about your new swapfile in fstab.

You need to add the following line:

/swapfile       none       swap         sw        0      0

The meaning of the fstab fields is as follows:

#1.source   2.mountpoint  3.fstype  4.options   5.freq  6.order


问:
Is there a way to automatically strip leading space from Apache commons-cli option value?
Consider the following example:

```<code>import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class ApacheCommonsCliWhitespaceTest {

  public static void main(String[] args) throws ParseException {
    Options options = new Options();
    Option option = new Option("t", "test", true, "test description");
    options.addOption(option);

    CommandLineParser parser = new DefaultParser();

    String[] parameters = new String[1];

    parameters[0] = "-t ping";
    CommandLine result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");

    parameters[0] = "-test ping";
    result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");
  }
}
</code>```

The result will be

```<code>* ping*
* ping*
</code>```

Is there really no way to remove the leading space automatically? I would have expected that to be a common use case.

答:
Not sure if it feasible to adjust this in your case, but it seems Commons CLI wants the format -arg=value, so the following results in *ping*:

```<code>    parameters[0] = "-test=ping";
    result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");
</code>```

See also the Usage guide (although the samples are not consistent, sometimes they use "--test", which does not work for me with version 1.4.)

Body:
Consider the following example:

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class ApacheCommonsCliWhitespaceTest {

  public static void main(String[] args) throws ParseException {
    Options options = new Options();
    Option option = new Option("t", "test", true, "test description");
    options.addOption(option);

    CommandLineParser parser = new DefaultParser();

    String[] parameters = new String[1];

    parameters[0] = "-t ping";
    CommandLine result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");

    parameters[0] = "-test ping";
    result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");
  }
}

The result will be

* ping*
* ping*

Is there really no way to remove the leading space automatically? I would have expected that to be a common use case.

Body:
Not sure if it feasible to adjust this in your case, but it seems Commons CLI wants the format -arg=value, so the following results in *ping*:

    parameters[0] = "-test=ping";
    result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");

See also the Usage guide (although the samples are not consistent, sometimes they use "--test", which does not work for me with version 1.4.)


问:
Moving Code logic from Autofac.integration.mvc to Autofac.integration.webapi
We are creating the ContainerManger which will be used by Application Engine while resolving the dependency in WebAPI. We have below mention code for fetching the current scope,considering autofac integration MVC framework

```<code>  /// <summary>
    /// Get current scope
    /// </summary>
    /// <returns>Scope</returns>
    public virtual ILifetimeScope Scope()
    {
        try
        {
            if (HttpContext.Current != null)
                return AutofacDependencyResolver.Current.RequestLifetimeScope;

            //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
            return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
        }
        catch (Exception)
        {
            //we can get an exception here if RequestLifetimeScope is already disposed
            //for example, requested in or after "Application_EndRequest" handler
            //but note that usually it should never happen

            //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
            return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
        }
    }
</code>```

wanted to convert it to autofac integration WebAPI framework so that same logic can be used in webapi. if you check the above code you will find AutofacDependencyResolver from autoface.integration.mvc is being used. As WebAPI is Stateless httpContext will be not available for REST API.

Can any body suggest what is the right thing to do for getting the Current Scope in the WebAPI when scope is not provided while resolving the dependency in Web API based service.

Any guidance or sample would be appreciated.

答:
I think it's :

if (HttpContext.Current != null)
                    return GlobalConfiguration.Configuration.DependencyResolver.GetRequestLifetimeScope();

Body:
We are creating the ContainerManger which will be used by Application Engine while resolving the dependency in WebAPI. We have below mention code for fetching the current scope,considering autofac integration MVC framework

  ///
    /// Get current scope
    ///
    /// <returns>Scope</returns>
    public virtual ILifetimeScope Scope()
    {
        try
        {
            if (HttpContext.Current != null)
                return AutofacDependencyResolver.Current.RequestLifetimeScope;

            //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
            return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
        }
        catch (Exception)
        {
            //we can get an exception here if RequestLifetimeScope is already disposed
            //for example, requested in or after "Application_EndRequest" handler
            //but note that usually it should never happen

            //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
            return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
        }
    }

wanted to convert it to autofac integration WebAPI framework so that same logic can be used in webapi. if you check the above code you will find AutofacDependencyResolver from autoface.integration.mvc is being used. As WebAPI is Stateless httpContext will be not available for REST API.

Can any body suggest what is the right thing to do for getting the Current Scope in the WebAPI when scope is not provided while resolving the dependency in Web API based service.

Any guidance or sample would be appreciated.


问:
Image upload using retrofit2 Put method
I am new to retrofit2. I want upload image through api service as a file. I have tried with postman by selecting a file and found its working. But through mobile how can I upload the image file.

Here is the Header section of Api

```<code>--header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
</code>```

In the body section I am having, "picture", "name", "email" and "phone"

I am trying like,

i have created a class with body parameters
UpdateRequest Class

```<code>    public class UpdateRequest {
        @SerializedName("picture")
        MultipartBody.Part picture;
        @SerializedName("name")
        public String name;
        @SerializedName("email")
        public String email;
        @SerializedName("phone")
        public String phone;

//Also Generated Getters and Setters for the parameters

    }
</code>```

Api Interface function

```<code>public interface MediaUploadApiInterface {

    @Headers({
            "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
    })
    @PUT("api/employee")
        Call<UpdateResponse> updateDetails(@Body UpdateRequest request, @Header("X-TOKEN") String token);

}
</code>```

Now How can i bind the details and send.

Please Help me..

答:
You have to create Multipart Request like below.

```<code>File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "picture");

RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "your_name");
RequestBody email = RequestBody.create(MediaType.parse("text/plain"), "your_email");
RequestBody phone = RequestBody.create(MediaType.parse("text/plain"), "your_phone");

HasMap<String,RequestBody> map = new HasMap<>();
map.put("name",name);
map.put("email",email);
map.put("phone",phone);

postImage(map, picture)
</code>```

Interface is like below.

```<code>@Multipart
    @PUT("/")
    Call<ResponseBody> postImage(@PartMap Map<String, RequestBody> map, @Part MultipartBody.Part image);
}
</code>```

Also, don't forget to add @Multipart in your interface.

Title: Image upload using retrofit2 Put method

Body:
I am new to retrofit2. I want upload image through api service as a file. I have tried with postman by selecting a file and found its working. But through mobile how can I upload the image file.

Here is the Header section of Api

--header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \

In the body section I am having, "picture", "name", "email" and "phone"

I am trying like,

i have created a class with body parameters
UpdateRequest Class

    public class UpdateRequest {
        @SerializedName("picture")
        MultipartBody.Part picture;
        @SerializedName("name")
        public String name;
        @SerializedName("email")
        public String email;
        @SerializedName("phone")
        public String phone;

//Also Generated Getters and Setters for the parameters

    }

Api Interface function

public interface MediaUploadApiInterface {

    @Headers({
            "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
    })
    @PUT("api/employee")
        Call<UpdateResponse> updateDetails(@Body UpdateRequest request, @Header("X-TOKEN") String token);

}

Now How can i bind the details and send.

Please Help me..

Body:
You have to create Multipart Request like below.

File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "picture");

RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "your_name");
RequestBody email = RequestBody.create(MediaType.parse("text/plain"), "your_email");
RequestBody phone = RequestBody.create(MediaType.parse("text/plain"), "your_phone");

HasMap<String,RequestBody> map = new HasMap<>();
map.put("name",name);
map.put("email",email);
map.put("phone",phone);

postImage(map, picture)

Interface is like below.

@Multipart
    @PUT("/")
    Call<ResponseBody> postImage(@PartMap Map<String, RequestBody> map, @Part MultipartBody.Part image);
}

Also, don't forget to add @Multipart in your interface.


问:
Square Up API Edge Browser Issue
I'm facing an issue right now with the SquareUp API. I'm using this function to render the form paymentForm.build(); and everything works ok on all browers but on Edge Browser version 9 the form isn't rendering.

When you open the developer tools the form renders. Is there any kind of workaround to solve this issue in Edge browser?

Thanks!

答: If anyone else is facing this issue the answser is simple. It was as simple as adding the minimum height for the fields used by the iframe in SquareUp. Some browsers sometimes fails to render the form in the DOM, so adding a minimum height we assure that the fields are visible to the users until we wait for the iframe response.</p>

Title: Square Up API Edge Browser Issue


问:
How to fill all rows in a column with data from other columns?
I have a dataset called 'names' as shown below. The 'expected.entry.in.this.col' column is currently empty, but below I have shown how it should look. How can I write the logic?

Basically I think I'll need to run a loop through every row and for each row, use an 'if' condition to check the format and then enter the data into 'expected.entry.in.this.col' appropriately. How would I go about doing this? (a bit unfamiliar with R syntax for these kind of tasks).

names

EDIT: row 3 is a mistake and should read williams.harry

答:
This is a solution with a "lookup table" and withoutif's

```<code>mydf <- data.frame(
  first= c("John", "Michael", "Harry", "Stephen", "Simon", "Rachael", "Paul"),
  last = c("Smith", "Johnson", "Williams", "Jones", "Adams", "Moore", "Taylor"),
  format = c("first.last", "firstlast", "last.first", "f.last", "flast", "f_last", "f_last"),
  expected = c("", "", "", "", "", "", ""),
  stringsAsFactors = FALSE
  )
library(dplyr)

firstList <- c("first.last", "firstlast", "f.last", "flast", "f_last")

#if in the format is in firstList, then do this
mydf[mydf$format %in% firstList, ]$expected <- paste0(
  mydf[mydf$format %in% firstList, ]$first, ".",
  mydf[mydf$format %in% firstList, ]$last)

mydf[ !(mydf$format %in% firstList), ]$expected <- paste0(
  mydf[ !(mydf$format %in% firstList), ]$last, ".",
  mydf[ !(mydf$format %in% firstList), ]$first)
)
</code>```

Body:
This is a solution with a "lookup table" and withoutif's

mydf <- data.frame(
  first= c("John", "Michael", "Harry", "Stephen", "Simon", "Rachael", "Paul"),
  last = c("Smith", "Johnson", "Williams", "Jones", "Adams", "Moore", "Taylor"),
  format = c("first.last", "firstlast", "last.first", "f.last", "flast", "f_last", "f_last"),
  expected = c("", "", "", "", "", "", ""),
  stringsAsFactors = FALSE
  )
library(dplyr)

firstList <- c("first.last", "firstlast", "f.last", "flast", "f_last")

#if in the format is in firstList, then do this
mydf[mydf$format %in% firstList, ]$expected <- paste0(
  mydf[mydf$format %in% firstList, ]$first, ".",
  mydf[mydf$format %in% firstList, ]$last)

mydf[ !(mydf$format %in% firstList), ]$expected <- paste0(
  mydf[ !(mydf$format %in% firstList), ]$last, ".",
  mydf[ !(mydf$format %in% firstList), ]$first)
)


问:
Get documents from Watson Discovery Service when doing a histogram
I am currently doing a using the histogram feature in Watson discovery, but I need to documents for each slice, so I can then do work on them again. ( such as looking at average sentiment )

This is my query, which breaks down my data into 15 mins chunks

filter(enriched_tweet.concepts.text:"'Hockey'").histogram(extracted_metadata.utc_timestamp,interval:900000)

but the response only tells me how many documents are in each "slice".

```<code>{
"matching_results": 444530,
"aggregations": [
    {
        "type": "filter",
        "match": "enriched_tweet.concepts.text:\"'Hockey'\"",
        "matching_results": 69556,
        "aggregations": [
            {
                "type": "histogram",
                "field": "utc_timestamp",
                "interval": 900000,
                "results": [
                    {
                        "key": 1498227300000,
                        "matching_results": 180
                    },
                    {
                        "key": 1498228200000,
                        "matching_results": 258
                    },
</code>```

Extension to the answer below

So, you can perform actions on the data in the buckets even though you don't seem them in your results, for example, the following will work:

```<code>filter(enriched_tweet.concepts.text:"'Hockey'").histogram(utc_timestamp,interval:900000).sum(followers)
</code>```

What I want is an array of docs for each slice, so I can then go over them and so sums on them to work out the sentiment of a 15 min interval for example.

答: You can run a sum aggregation nested under your histogram aggregation which can sum a field within the histogram buckets. See https://www.ibm.com/watson/developercloud/doc/discovery/query-reference.html#aggregations for more about aggregations.</p>

Body:
I am currently doing a using the histogram feature in Watson discovery, but I need to documents for each slice, so I can then do work on them again. ( such as looking at average sentiment )

This is my query, which breaks down my data into 15 mins chunks

filter(enriched_tweet.concepts.text:"'Hockey'").histogram(extracted_metadata.utc_timestamp,interval:900000)

but the response only tells me how many documents are in each "slice".

{
"matching_results": 444530,
"aggregations": [
    {
        "type": "filter",
        "match": "enriched_tweet.concepts.text:\"'Hockey'\"",
        "matching_results": 69556,
        "aggregations": [
            {
                "type": "histogram",
                "field": "utc_timestamp",
                "interval": 900000,
                "results": [
                    {
                        "key": 1498227300000,
                        "matching_results": 180
                    },
                    {
                        "key": 1498228200000,
                        "matching_results": 258
                    },

Extension to the answer below

So, you can perform actions on the data in the buckets even though you don't seem them in your results, for example, the following will work:

filter(enriched_tweet.concepts.text:"'Hockey'").histogram(utc_timestamp,interval:900000).sum(followers)

What I want is an array of docs for each slice, so I can then go over them and so sums on them to work out the sentiment of a 15 min interval for example.


问:
Is this the right way to get string resources from within a Fragment?
Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

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

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}
</code>```

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

```<code>public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}
</code>```

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.

答: The second approach is more complicated and adds no value over the first approach. Use the first approach.</p>

Body:
Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.


问:
Applying CSS to Label and Input Elements Using Values in jQuery
Edit :
I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Yii I cannot remove it.

Using jQuery I am attempting to add and remove styling to an input and label within my HTML. I get no response when I am trying this, I believe it is due to the abnormal for="" and/or val= values of the elements generated by Yii.

Can't seem to get it working with the if else statement. When removed it applies the CSS.

It should do as follows; select Yes, with the value "Yes", and the second label and input appear.

I have created a CodePen for this as I am having issues with JSFiddle.
https://codepen.io/CallumRocks/pen/rwrrvE

I have also included the relevant code below.

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}</code>```

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

```

答:
You don't have to remove the ?. Simply escape it in jQuery using \\:

```<code>$('#event_Do_you_require_any_accessibility_assistance\\?')
</code>```

Reference

Example:

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance\\?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}</code>```

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

```

Body:
Edit :
I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Yii I cannot remove it.

Using jQuery I am attempting to add and remove styling to an input and label within my HTML. I get no response when I am trying this, I believe it is due to the abnormal for="" and/or val= values of the elements generated by Yii.

Can't seem to get it working with the if else statement. When removed it applies the CSS.

It should do as follows; select Yes, with the value "Yes", and the second label and input appear.

I have created a CodePen for this as I am having issues with JSFiddle.
https://codepen.io/CallumRocks/pen/rwrrvE

I have also included the relevant code below.

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});

label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

Body:
You don't have to remove the ?. Simply escape it in jQuery using \\:

$('#event_Do_you_require_any_accessibility_assistance\\?')

Reference

Example:

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance\\?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});

label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="form-group">
  <label class="required-label required" for="event_Do you require any accessibility assistance?">Do you require any accessibility assistance? <span class="required">*</span></label>
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>
</div>

<div class="form-group">
  <label for="event_Please specify">Please specify</label>
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">
</div>


问:
Swift Delegation: unexpectedly found nil while unwrapping an Optional value

Edit: Please note the question below discusses using delegation between
  2 viewcontrollers that are also implemented in a UITabBarController.

I've done a fair bit of searching here and on YouTube, but haven't seen my issue replicated elsewhere. I'll keep it to the point.

I have 2 view controllers that I coded myself -not generated by XCode-; TabOneController, and TabTwoController

below are the coding for both...

```<code>import UIKit

class TabOneController: UIViewController{

    private let instanceOfTabOneView = TabOneView()

    var vc1Delegate: fromOneToTwo!

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabOneView.buildTheVu())
                view.backgroundColor = UIColor.white

        runThisOnce()

        }

    func runThisOnce(){

        vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")

    }

}

protocol fromOneToTwo{

    func passTheValue(heroNameIs: String)

}
</code>```

as for tab 2...

```<code>import UIKit

class TabTwoController: UIViewController, fromOneToTwo{

    private let instanceOfTabTwoView = TabTwoView()

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabTwoView.buildTheVu())

        assignDelegateToSelf()

    }

    func assignDelegateToSelf(){

        let instanceTabOne = TabOneController()
            instanceTabOne.vc1Delegate = self

    }

    func passTheValue(heroNameIs:String){

        instanceOfTabTwoView.txtFld.text = heroNameIs

    }

}
</code>```

I'm getting the following error at runtime -the app builds successfully-...

fatal error: unexpectedly found nil while unwrapping an Optional value

on the following line...

```<code>vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
</code>```

When I comment out the above line, the app builds and runs successfully, but of course the app doesn't execute the delegation.

I kinda understand what the compiler is trying to tell me, that the

```<code>vc1Delegate
</code>```

hasn't been instantiated -I guess-. But I searched under every rock, and can't seem to find how to get around this.

I'd appreciate any help or guidance. Sorry if my code seems immature, I'm new to Swift and programming in general. Thank you.

答:
In a UITabBarController, the first tab is instantiating by default. The view controller initialization executes the loadView and finds a nil because the second tab did not initialize yet; this is normal behavior. My suggestion is making the delegate weak optional with the ? suffix and run the delegate code elsewhere. Also, always capitalize the first letter in class and protocol names.

```<code>weak var vc1Delegate: FromOneToTwo?
</code>```

If this structure is mandatory, try with a custom notification observer instead.

Body:
Edit: Please note the question below discusses using delegation between
  2 viewcontrollers that are also implemented in a UITabBarController.

I've done a fair bit of searching here and on YouTube, but haven't seen my issue replicated elsewhere. I'll keep it to the point.

I have 2 view controllers that I coded myself -not generated by XCode-; TabOneController, and TabTwoController

below are the coding for both...

import UIKit

class TabOneController: UIViewController{

    private let instanceOfTabOneView = TabOneView()

    var vc1Delegate: fromOneToTwo!

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabOneView.buildTheVu())
                view.backgroundColor = UIColor.white

        runThisOnce()

        }

    func runThisOnce(){

        vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")

    }

}

protocol fromOneToTwo{

    func passTheValue(heroNameIs: String)

}

as for tab 2...

import UIKit

class TabTwoController: UIViewController, fromOneToTwo{

    private let instanceOfTabTwoView = TabTwoView()

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabTwoView.buildTheVu())

        assignDelegateToSelf()

    }

    func assignDelegateToSelf(){

        let instanceTabOne = TabOneController()
            instanceTabOne.vc1Delegate = self

    }

    func passTheValue(heroNameIs:String){

        instanceOfTabTwoView.txtFld.text = heroNameIs

    }

}

I'm getting the following error at runtime -the app builds successfully-...

fatal error: unexpectedly found nil while unwrapping an Optional value

on the following line...

vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")

When I comment out the above line, the app builds and runs successfully, but of course the app doesn't execute the delegation.

I kinda understand what the compiler is trying to tell me, that the

vc1Delegate

hasn't been instantiated -I guess-. But I searched under every rock, and can't seem to find how to get around this.

I'd appreciate any help or guidance. Sorry if my code seems immature, I'm new to Swift and programming in general. Thank you.

Body:
In a UITabBarController, the first tab is instantiating by default. The view controller initialization executes the loadView and finds a nil because the second tab did not initialize yet; this is normal behavior. My suggestion is making the delegate weak optional with the ? suffix and run the delegate code elsewhere. Also, always capitalize the first letter in class and protocol names.

weak var vc1Delegate: FromOneToTwo?

If this structure is mandatory, try with a custom notification observer instead.


问:
Defining ostream operator<< for typedef defined in the class
Could anyone provide me a hint how to implement correctly operator<< for MyType in provided code example?

```<code>#include <iostream>
#include <map>

template <typename T>
class A {
public:
    typedef std::map<unsigned int, T> MyType;
    MyType data;

    void show();
};

template <typename T>
std::ostream& operator<<(std::ostream& stream, typename A<T>::MyType const& mm)
{
    return stream << mm.size() << "\n";
}

//template <typename T>
//std::ostream& operator<<(std::ostream& stream, std::map<unsigned int, T> const& mm)
//{
//  return stream << mm.size() << "\n";
//}

template <typename T>
void A<T>::show() {std::cout << data;}

int main() {
    A<double> a;

    a.show();

    return 0;
}
</code>```

Above code does not compile. But when I change definition of operator<< to commented out one, everything works correctly. This is just a (not) working example of a more complicated problem and in reality MyType is much much more nasty. In that simple example I just could easily copy-paste exact definition of MyType from a 'A' class but in more complicated case, when this typedef is depending on antoher typedef... it would be nice just to refer to it. Is there any solution to this problem?

Edit:

Output error from compiler (in general as if operator<< was not defined at all, so when both definitions for operator<< from example are commented out compiler prints same error).

```<code>g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++14 -MMD -MP -MF"src/ostreamTest.d" -MT"src/ostreamTest.o" -o "src/ostreamTest.o" "../src/ostreamTest.cpp"
../src/ostreamTest.cpp:27:31: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'MyType' (aka 'map<unsigned int, double>'))
    void A<T>::show() {std::cout << data;}
                       ~~~~~~~~~ ^  ~~~~
</code>```

答:
So I was cooking this as an answer

```<code>#include <iostream>
#include <map>

template <typename T>
class A{
public:

    using MyType = std::map<unsigned int, T>;
    MyType data;

    void show();

    friend std::ostream& operator<<(std::ostream& stream, const MyType& mm){
        return stream << mm.size() << "\n";
    }
};

template <typename T>
void A<T>::show(){
    std::cout << data;
}

int main()
{
    A<double> a;
    std::cout << a;
    return 0;
}
</code>```

But there's a build error quite known that occurs when compiling :

error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

This error often means that the type deduction could not do its job properly (non-deductible context) (cf. Why is template type deduction not working and ostream lvalue error)

Therefore I think that, for the moment, you should find another way around this problem, such way I can't think of for the moment.

Body:
Could anyone provide me a hint how to implement correctly operator<< for MyType in provided code example?

#include <iostream>
#include <map>

template <typename T>
class A {
public:
    typedef std::map<unsigned int, T> MyType;
    MyType data;

    void show();
};

template <typename T>
std::ostream& operator<<(std::ostream& stream, typename A<T>::MyType const& mm)
{
    return stream << mm.size() << "\n";
}

//template <typename T>
//std::ostream& operator<<(std::ostream& stream, std::map<unsigned int, T> const& mm)
//{
//  return stream << mm.size() << "\n";
//}

template <typename T>
void A<T>::show() {std::cout << data;}

int main() {
    A<double> a;

    a.show();

    return 0;
}

Above code does not compile. But when I change definition of operator<< to commented out one, everything works correctly. This is just a (not) working example of a more complicated problem and in reality MyType is much much more nasty. In that simple example I just could easily copy-paste exact definition of MyType from a 'A' class but in more complicated case, when this typedef is depending on antoher typedef... it would be nice just to refer to it. Is there any solution to this problem?

Edit:

Output error from compiler (in general as if operator<< was not defined at all, so when both definitions for operator<< from example are commented out compiler prints same error).

g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++14 -MMD -MP -MF"src/ostreamTest.d" -MT"src/ostreamTest.o" -o "src/ostreamTest.o" "../src/ostreamTest.cpp"
../src/ostreamTest.cpp:27:31: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'MyType' (aka 'map<unsigned int, double>'))
    void A<T>::show() {std::cout << data;}
                       ~~~~~~~~~ ^  ~~~~

Body:
So I was cooking this as an answer

#include <iostream>
#include <map>

template <typename T>
class A{
public:

    using MyType = std::map<unsigned int, T>;
    MyType data;

    void show();

    friend std::ostream& operator<<(std::ostream& stream, const MyType& mm){
        return stream << mm.size() << "\n";
    }
};

template <typename T>
void A<T>::show(){
    std::cout << data;
}

int main()
{
    A<double> a;
    std::cout << a;
    return 0;
}

But there's a build error quite known that occurs when compiling :

error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

This error often means that the type deduction could not do its job properly (non-deductible context) (cf. Why is template type deduction not working and ostream lvalue error)

Therefore I think that, for the moment, you should find another way around this problem, such way I can't think of for the moment.


问:
How to import js file in typescript?
I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';

@Component({
  selector: 'page-success',
  templateUrl: 'success.html'
})

export class SuccessPage {
  constructor(public navCtrl: NavController, public navParms: NavParams) {

let centerPos =  new atlan.maps.UTMK(953933.75, 1952050.75);

 }
}
</code>```

This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!

答: In your file ../../pages/mobile.js, you must export your atlan object (if you can edit this file of course), then, you import it the same way you do with everything.

Title: How to import js file in typescript?

Body:
I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';

@Component({
  selector: 'page-success',
  templateUrl: 'success.html'
})

export class SuccessPage {
  constructor(public navCtrl: NavController, public navParms: NavParams) {

let centerPos =  new atlan.maps.UTMK(953933.75, 1952050.75);

 }
}

This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!


问:
Heroku 500 internal server error, TypeError (no implicit conversion of Symbol into Integer):
first time posting.
Im trying to make mailgun send me an email for new subscribers
but when i filled the form it gives me 500 internal server error and TypeError.

Error log

Completed 500 Internal Server Error in 13ms (ActiveRecord: 4.9ms)
  TypeError (no implicit conversion of Symbol into Integer):

  app/controllers/contacts_controller.rb:9:in []'
  app/controllers/contacts_controller.rb:9:increate'

Is there something wrong with my ContactsController?

```<code>class ContactsController < ApplicationController
 def new
@contact = Contact.new
end

def create
 @contact = Contact.new(contact_params)
 if @contact.save
  name = params[:contact][:name]
  email = params[:contact][:email]
  body = params[:contact][:comments]
  ContactMailer.contact_email(name, email, body).deliver
   flash[:success] = "Message sent."
   redirect_to new_contact_path
 else
   flash[:danger] = @contact.errors.full_messages.join(", ")
   redirect_to new_contact_path
 end
end

 private
    def contact_params
     params.require(:contact).permit(:name, :email, :comments)
    end
end
</code>```

contact_email.html.erb

```<code>   <!DOCTYPE html>
   <html>
     <head></head>
     <body>
       <p>You have received a message from the site's contact form, from
       <%= "#{ @name }, #{ @email }." %></p>
       <p><%= @body %></p>
     </body>

   </html>
</code>```

The weird thing is that if i run my codes in development via cloud9 server it runs fine but in production via heroku server it gives me an error after trying to submit the contact us form fully filled out.
Also im learning how to code by following this website.
The issue is with lesson 78.

答:
name, email, body - have to be string.

```<code>inspect it by
name.class
email.class
body.class
</code>```

ActionMailer can work only with basic types(like string), but in you code someone in name, email, body is a symbol class.

Body:
first time posting.
Im trying to make mailgun send me an email for new subscribers
but when i filled the form it gives me 500 internal server error and TypeError.

Error log

Completed 500 Internal Server Error in 13ms (ActiveRecord: 4.9ms)
  TypeError (no implicit conversion of Symbol into Integer):

  app/controllers/contacts_controller.rb:9:in []'
  app/controllers/contacts_controller.rb:9:increate'

Is there something wrong with my ContactsController?

class ContactsController < ApplicationController
 def new
@contact = Contact.new
end

def create
 @contact = Contact.new(contact_params)
 if @contact.save
  name = params[:contact][:name]
  email = params[:contact][:email]
  body = params[:contact][:comments]
  ContactMailer.contact_email(name, email, body).deliver
   flash[:success] = "Message sent."
   redirect_to new_contact_path
 else
   flash[:danger] = @contact.errors.full_messages.join(", ")
   redirect_to new_contact_path
 end
end

 private
    def contact_params
     params.require(:contact).permit(:name, :email, :comments)
    end
end

contact_email.html.erb

   <!DOCTYPE html>

You have received a message from the site's contact form, from
       <%= "#{ @name }, #{ @email }." %>

<%= @body %>

The weird thing is that if i run my codes in development via cloud9 server it runs fine but in production via heroku server it gives me an error after trying to submit the contact us form fully filled out.
Also im learning how to code by following this website.
The issue is with lesson 78.

Body:
name, email, body - have to be string.

inspect it by
name.class
email.class
body.class

ActionMailer can work only with basic types(like string), but in you code someone in name, email, body is a symbol class.


问:
I am new to MVC or you can say new to OOPS. Can anyone tell me what is the meaning of both the lines?
.Where(m=> m.Depatment.Name =="")

.Where(m => m.JobTitle.Name == "Administrator")

答:
Where is from LINQ (System.Linq), which is short for "Language-Integrated Query". LINQ provides a set of methods that allow you build dynamic queries on basically any object structure. ORMs like Entity Framework support LINQ, and use it to build actual SQL queries behind the scenes, but you can use LINQ anywhere, really, not just for database access.

The parameter to something like Where is a lambda expression. The type is actually Func<TSource, bool>, which simply means it's a function that takes a generic type and returns a bool. In a lambda, the left side of the => is the parameter(s) to the lambda, while the right side is the return value of the lambda. So, both of these have a parameter, m, and include an expression that evaluates to a boolean. The actual value that's passed to the parameter is obviously the entity type you're working with, i.e. the object you're querying. In practical terms, any objects where the expression evaluates to true will be returned, while any that evaluate to false will be excluded. The result will be an IEnumerable<TSource>, where TSource is your entity type. In other words, it's going to return a list of all the entities that match.

Based on that, the first expression will return any entities where the related Department's Name property is an empty string. The second expression, meanwhile, will return all the entities where the related JobTile's Name property is equal to "Administrator".


问:
Register .net MVC3 ControllerContext into windsor container
With ASP.NET MVC3 what would be the best way to register the requests ControllerContext into castle windsor container? Ultimately I'd like to be able to say

```<code>container.Resolve<ControllerContext>();
</code>```

and have the requests controller context returned.

More detail

The vast majority of my actions are just going to do some validation, authentication, etc.. before sending a message to nservicebus to actually do the work.  To avoid having to copy/paste these 20/30 lines of code all over the place I have put them into a handler class which my controllers take a dependency on in the constructor, the actions then call this class which leaves my actions containing just one line of code.

One of the child classes that makes up the handler needs to know about the route that was taken, I could just pass the controller to the handler and then onto this class but it seems a bit messy.  It would be nice if there was a way to get Windsor registered to provide it for me.

答:
I don't think you can register the ControllerContext without some very ugly hacks, and IMHO it's not a good idea anyway. The ControllerContext belongs to the controller, it's not meant to be shared around.

However, if you only need the routing information, you can register it like this (UNTESTED!):

```<code>container.Register(Component.For<HttpContextBase>()
                    .UsingFactoryMethod(() => new HttpContextBaseWrapper(HttpContext.Current))
                    .LifeStyle.PerWebRequest,
                   Component.For<RouteData>()
                    .UsingFactoryMethod(k => RouteTable.Routes.GetRouteData(k.Resolve<HttpContextBase>()))
                    .LifeStyle.PerWebRequest);
</code>```

Also see ASP.NET MVC & Windsor.Castle: working with HttpContext-dependent services for more details.

I don't know concretely what you're trying to achieve but I'd look into doing it with filters or custom ActionResults instead.

Body:
With ASP.NET MVC3 what would be the best way to register the requests ControllerContext into castle windsor container? Ultimately I'd like to be able to say

container.Resolve<ControllerContext>();

and have the requests controller context returned.

More detail

The vast majority of my actions are just going to do some validation, authentication, etc.. before sending a message to nservicebus to actually do the work.  To avoid having to copy/paste these 20/30 lines of code all over the place I have put them into a handler class which my controllers take a dependency on in the constructor, the actions then call this class which leaves my actions containing just one line of code.

One of the child classes that makes up the handler needs to know about the route that was taken, I could just pass the controller to the handler and then onto this class but it seems a bit messy.  It would be nice if there was a way to get Windsor registered to provide it for me.

Body:
I don't think you can register the ControllerContext without some very ugly hacks, and IMHO it's not a good idea anyway. The ControllerContext belongs to the controller, it's not meant to be shared around.

However, if you only need the routing information, you can register it like this (UNTESTED!):

container.Register(Component.For<HttpContextBase>()
                    .UsingFactoryMethod(() => new HttpContextBaseWrapper(HttpContext.Current))
                    .LifeStyle.PerWebRequest,
                   Component.For<RouteData>()
                    .UsingFactoryMethod(k => RouteTable.Routes.GetRouteData(k.Resolve<HttpContextBase>()))
                    .LifeStyle.PerWebRequest);

Also see ASP.NET MVC & Windsor.Castle: working with HttpContext-dependent services for more details.

I don't know concretely what you're trying to achieve but I'd look into doing it with filters or custom ActionResults instead.


问:
Update one property of an entity in google cloud datastore python
How do I update only one property of an entity in the google cloud datastore, without remove all other properties?

```<code>key = client.key('employee', ID)
employee_to_deactivate = datastore.Entity(key)
employee_to_deactivate.update({
    'active':False,
})
</code>```

this updates the active property to False, but removes all the other properties.

答: You cannot update specific properties of an entity. All writes (inserts, updates) must include all properties that should be persisted. Whenever you need to do an update, you need to first retrieve the existing entity as a whole, then update one or more properties by setting new values and update the entity. </p>

Body:
How do I update only one property of an entity in the google cloud datastore, without remove all other properties?

key = client.key('employee', ID)
employee_to_deactivate = datastore.Entity(key)
employee_to_deactivate.update({
    'active':False,
})

this updates the active property to False, but removes all the other properties.


问:
Single Prediction when using Batch Normalization
I have a CNN that is learning pretty well on a dataset I created. I added Batch Normalization to this network to try to improve the performances.

But ..  when I try to make a prediction on a single image I always end up with the same result (whatever the image). I think it is because I need batches to actually do batch normalization.

So is it possible to do a prediction on a single image with a CNN using BN ?
I thought about deleting BN layers once my network is done training, is it the way to go ?

Thank you :)

答:
I found the exact answer and the problem I face here : https://r2rt.com/implementing-batch-normalization-in-tensorflow.html
in the "Making predictions with the model" it is explained that when using BN, during training time you need to estimate the population mean and population variance on your training set so you don't have to use batch when doing testing (which would be "cheating") :)</p>


问:
What is the best way of using response of first call as request payload for second call in Node.js without using promises?
I am trying to make 2 /POST calls in Node.js. I want to use some fields of response of first call as payload for second call. The implementation i am aware of is as folllows:

```<code>function abc(reqObject, callback){
  request(reqObject, function(err,res)){
    if(err)
    {
      callback(err, null);
    }
    else
    {
      <use this res for second req>
      request(reqObject, function(err,res)){
       <err,res handling here>
      }
    }
  }
}
</code>```

What is the most appropriate way(without messing up with callbacks) to achieve this without using promises and async modules? I am trying to do this using only request module.

答:
You are doing almost everything right. Only the braces are not in the right position. </p>

```<code>function abc(reqObject, callback){
 request(reqObject, function(err,res){
   if(err)
  {
  callback(err, null);
}
else
{
  // <use this res for second req>
  request(reqObject, function(err,res){
  //  <err,res handling here>
 });
}
});
}
</code>```

Body:
I am trying to make 2 /POST calls in Node.js. I want to use some fields of response of first call as payload for second call. The implementation i am aware of is as folllows:

function abc(reqObject, callback){
  request(reqObject, function(err,res)){
    if(err)
    {
      callback(err, null);
    }
    else
    {
      <use this res for second req>
      request(reqObject, function(err,res)){
       <err,res handling here>
      }
    }
  }
}

What is the most appropriate way(without messing up with callbacks) to achieve this without using promises and async modules? I am trying to do this using only request module.

Body:
You are doing almost everything right. Only the braces are not in the right position.

function abc(reqObject, callback){
 request(reqObject, function(err,res){
   if(err)
  {
  callback(err, null);
}
else
{
  // <use this res for second req>
  request(reqObject, function(err,res){
  //  <err,res handling here>
 });
}
});
}


问:
android: Set ToggleButton background back to default
I changed the background for a ToggleButton and wish to reset it back to its default state.

Changed the background:

```<code>btn.setBackgroundColor(Color.parseColor("#FF2929"));
</code>```

Tried changing it back:

```<code>btn.setBackgroundResource(0);                                  //Just text, no button
btn.setBackgroundColor(android.R.drawable.btn_default);        //Normal button not toggle
</code>```

答:
you are setting a drawable in Color, use btn.setBackgroundResource(android.R.drawable.btn_default).
This should set something in your button.

Body:
I changed the background for a ToggleButton and wish to reset it back to its default state.

Changed the background:

btn.setBackgroundColor(Color.parseColor("#FF2929"));

Tried changing it back:

btn.setBackgroundResource(0);                                  //Just text, no button
btn.setBackgroundColor(android.R.drawable.btn_default);        //Normal button not toggle