问:
CalendarApp Event ID
Using Google Apps Script, I am trying to create an Event in CalendarApp and store a Link to the event in a spreadsheet.

To create a link to the event I need to get the event ID, however using event.getID() in Google Apps Script returns the incorrect event ID.

Format for the link should be:

```<code>https://calendar.google.com/calendar/event?eid={eventID}=%7BAmerica/Chicago%7D
</code>```

Event ID should look something like:

tmFmbHZydmU1aDBDZGhlYmMwaWdqcW1wZGMgdDY1HT6yhuHI5YXJwYW5lMHV2OTYzamtAZw

getID() is returning this:

065cvve58nriutnkuses332fkf@google.com

```<code>var event = CalendarApp.getCalendarById(calID).createAllDayEvent(eventName, new Date (eventDate));
var eventID = event.getId();
var eventLink = "https://www.google.com/calendar/event?eid=" + eventID + "&ctz={America/Chicago}";
Logger.log(eventLink);
</code>```

Why is GAS returning the ID in this format?

答:
According to this documentation,

getId()

Gets the ID of the calendar. The ID for a user's default calendar is
  their email address.

You must have a specific id for your event.

You may check this links too:

FormResponse.getId() returns the wrong value right after the response is submitted

The id of a FormResponse when a response is submitted is different when you list all FormResponses

Based from this link, the IDs are not always the same, they are equal, apparently assigned a temporary ID until they are synchronized.

Title: CalendarApp Event ID

Body:
Using Google Apps Script, I am trying to create an Event in CalendarApp and store a Link to the event in a spreadsheet.

To create a link to the event I need to get the event ID, however using event.getID() in Google Apps Script returns the incorrect event ID.

Format for the link should be:

https://calendar.google.com/calendar/event?eid={eventID}=%7BAmerica/Chicago%7D

Event ID should look something like:

tmFmbHZydmU1aDBDZGhlYmMwaWdqcW1wZGMgdDY1HT6yhuHI5YXJwYW5lMHV2OTYzamtAZw

getID() is returning this:

065cvve58nriutnkuses332fkf@google.com

var event = CalendarApp.getCalendarById(calID).createAllDayEvent(eventName, new Date (eventDate));
var eventID = event.getId();
var eventLink = "https://www.google.com/calendar/event?eid=" + eventID + "&ctz={America/Chicago}";
Logger.log(eventLink);

Why is GAS returning the ID in this format?


来源: stackexchange

问:
how to send navigations params to mapStatetoProps method
I want to put navigation params to mapStatetoProps method

I try to avoid redux for my navigation to keep it simple, but if the only way is to use redux then I'll use it.

here is my code

```<code>class GameScreen extends React.Component {
  static navigationOptions = ({navigation}) => ({
    title: navigation.state.params.id,
  });

  render() {
    return (
      <View style={{flex:1, backgroundColor: '#005662'}}>
        <Text>ID</Text>
        <Text>{this.props.game.id}</Text>
        <Text>TITLE</Text>
        <Text>{this.props.game.title}</Text>
        </View>
    );
  }
}

function mapStateToProps(state, props) {
  return {
    game: state.games.find(item => item.id === /* how to put value from navigation.state.params.id to here */)
  }
}

export default connect(mapStateToProps)(GameScreen);
</code>```

答:
You can integrate React Navigation with Redux and have the current navigation state in your store.

Then you can easily access that data in your state inside of mapStateToProps.

```<code>function mapStateToProps(state, props) {
  return {
    game: state.games.find(item => item.id === state.nav...
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to put navigation params to mapStatetoProps method

I try to avoid redux for my navigation to keep it simple, but if the only way is to use redux then I'll use it.

here is my code

class GameScreen extends React.Component {
  static navigationOptions = ({navigation}) => ({
    title: navigation.state.params.id,
  });

  render() {
    return (
      <View style={{flex:1, backgroundColor: '#005662'}}>
        <Text>ID</Text>
        <Text>{this.props.game.id}</Text>
        <Text>TITLE</Text>
        <Text>{this.props.game.title}</Text>
        </View>
    );
  }
}

function mapStateToProps(state, props) {
  return {
    game: state.games.find(item => item.id === /* how to put value from navigation.state.params.id to here */)
  }
}

export default connect(mapStateToProps)(GameScreen);

Body:
You can integrate React Navigation with Redux and have the current navigation state in your store.

Then you can easily access that data in your state inside of mapStateToProps.

function mapStateToProps(state, props) {
  return {
    game: state.games.find(item => item.id === state.nav...
  }
}


问:
CSS center content in relative wrapper
I am making a personal website with a parallax background which takes 100% of the screen size, however when I change the screen size to the minimum size the text goes out of the div, I use a padding-top percentage. I do know quite a bit of css but I don't want to fiddle around and mess everything up, I've looked everywhere but no answer came close to my problem. Basically I just want to vertically and horizontally center my content even when I resize my screen.

Here's my CSS:

```<code>.wrapper {
    width: 100%;
    /* whatever width you want */
    display: inline-block;
    position: relative;
}
.wrapper:after {
    padding-top: 52.50%;
    /* 16:9 ratio */
    display: block;
    content: '';
}
.main {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    /* fill parent */
    background-image: url('/storage/images/background.jpeg');
    /* let's see it! */
    color: white;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
.text {
    margin-top: 15%;
    text-align:center;
}
</code>```

And my HTML:

```<code><div class="row">
    <div class="wrapper">
        <div class="main">
            <div class=text>
                <img src="/storage/images/image.jpg" style="border-radius:100%; width:150px; height:auto;">
                <h1>My name</h1>
            </div>
        </div>
    </div>
</div>
</code>```

答:
Use :

```<code>.main {
  text-align: center;<-----------------------
  //More code..........
}

.text {
  max-width: 150px;
  text-align: center;
  display: inline-block;
  margin-top: 15%;
}

.text img {
  border-radius:100%;
  width:70%;
  height:auto;
}

.text h1 {
  margin: 0;
  padding: 0;
}
</code>```

.wrapper {
  width: 100%;
  /* whatever width you want */
  display: inline-block;
  position: relative;
}
.wrapper:after {
  padding-top: 52.50%;
  /* 16:9 ratio */
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  /* fill parent */
  background-image: url('http://justcuteanimals.com/wp-content/uploads/2016/10/baby-bear-pictures-cute-animal-pics.jpg');
  /* let's see it! */
  color: white;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
}
.text {
  max-width: 150px;
  text-align: center;
  display: inline-block;
  margin-top: 15%;
}

.text img {
  border-radius:100%;
  width:70%;
  height:auto;
}

.text h1 {
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div class="wrapper">
        <div class="main">
            <div class=text>
                <img src="http://justcuteanimals.com/wp-content/uploads/2016/10/baby-bear-pictures-cute-animal-pics.jpg">
                <h1>My name</h1>
            </div>
        </div>
    </div>
</div></code>```

Title: CSS center content in relative wrapper

Body:
I am making a personal website with a parallax background which takes 100% of the screen size, however when I change the screen size to the minimum size the text goes out of the div, I use a padding-top percentage. I do know quite a bit of css but I don't want to fiddle around and mess everything up, I've looked everywhere but no answer came close to my problem. Basically I just want to vertically and horizontally center my content even when I resize my screen.

Here's my CSS:

.wrapper {
    width: 100%;
    /* whatever width you want */
    display: inline-block;
    position: relative;
}
.wrapper:after {
    padding-top: 52.50%;
    /* 16:9 ratio */
    display: block;
    content: '';
}
.main {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    /* fill parent */
    background-image: url('/storage/images/background.jpeg');
    /* let's see it! */
    color: white;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
.text {
    margin-top: 15%;
    text-align:center;
}

And my HTML:

My name

Body:
Use :

.main {
  text-align: center;<-----------------------
  //More code..........
}

.text {
  max-width: 150px;
  text-align: center;
  display: inline-block;
  margin-top: 15%;
}

.text img {
  border-radius:100%;
  width:70%;
  height:auto;
}

.text h1 {
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100%;
  /* whatever width you want */
  display: inline-block;
  position: relative;
}
.wrapper:after {
  padding-top: 52.50%;
  /* 16:9 ratio */
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  /* fill parent */
  background-image: url('http://justcuteanimals.com/wp-content/uploads/2016/10/baby-bear-pictures-cute-animal-pics.jpg');
  /* let's see it! */
  color: white;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
}
.text {
  max-width: 150px;
  text-align: center;
  display: inline-block;
  margin-top: 15%;
}

.text img {
  border-radius:100%;
  width:70%;
  height:auto;
}

.text h1 {
  margin: 0;
  padding: 0;
}

<div class="row">
    <div class="wrapper">
        <div class="main">
            <div class=text>
                <img src="http://justcuteanimals.com/wp-content/uploads/2016/10/baby-bear-pictures-cute-animal-pics.jpg">
                <h1>My name</h1>
            </div>
        </div>
    </div>
</div>


问:
F# Inline Function Specialization
My current project involves lexing and parsing script code, and as such I'm using fslex and fsyacc.  Fslex LexBuffers can come in either LexBuffer<char> and LexBuffer<byte> varieties, and I'd like to have the option to use both.

In order to user both, I need a lexeme function of type ^buf -> string.  Thus far, my attempts at specialization have looked like:

```<code>let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: char array) =
  new System.String(lexbuf.Lexeme)

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: byte array) =
  System.Text.Encoding.UTF8.GetString(lexbuf.Lexeme)
</code>```

I'm getting a type error stating that the function body should be of type ^buf -> string, but the inferred type is just string.  Clearly, I'm doing something (majorly?) wrong.

Is what I'm attempting even possible in F#?  If so, can someone point me to the proper path?

Thanks!

答:
Functions and members marked as inline cannot be overloaded, so your original strategy won't work. You need to write different code for both of the declarations, so you need to use overloading (if you want to write this without boxing and dynamic type tests).

If you're using standard F# tools, then the type you'll get as a buffer will always be LexBuffer<'T> and you want to have two overloads based on the type argument. In this case, you don't need the static member constraints at all and can write just:

```<code>type Utils =
  static member lexeme(buf:LexBuffer<char>) =
    new System.String(buf.Lexeme)
  static member lexeme(buf:LexBuffer<byte>) =
    System.Text.Encoding.UTF8.GetString(buf.Lexeme)
</code>```

ContentLicense: CC BY-SA 2.5

Title: F# Inline Function Specialization

Body:
My current project involves lexing and parsing script code, and as such I'm using fslex and fsyacc.  Fslex LexBuffers can come in either LexBuffer<char> and LexBuffer<byte> varieties, and I'd like to have the option to use both.

In order to user both, I need a lexeme function of type ^buf -> string.  Thus far, my attempts at specialization have looked like:

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: char array) =
  new System.String(lexbuf.Lexeme)

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: byte array) =
  System.Text.Encoding.UTF8.GetString(lexbuf.Lexeme)

I'm getting a type error stating that the function body should be of type ^buf -> string, but the inferred type is just string.  Clearly, I'm doing something (majorly?) wrong.

Is what I'm attempting even possible in F#?  If so, can someone point me to the proper path?

Thanks!

Body:
Functions and members marked as inline cannot be overloaded, so your original strategy won't work. You need to write different code for both of the declarations, so you need to use overloading (if you want to write this without boxing and dynamic type tests).

If you're using standard F# tools, then the type you'll get as a buffer will always be LexBuffer<'T> and you want to have two overloads based on the type argument. In this case, you don't need the static member constraints at all and can write just:

type Utils =
  static member lexeme(buf:LexBuffer<char>) =
    new System.String(buf.Lexeme)
  static member lexeme(buf:LexBuffer<byte>) =
    System.Text.Encoding.UTF8.GetString(buf.Lexeme)


问:
update a table with an array just with one query
I have a table like this:

I receive an array like this:

```<code> $data = array(
   array('m_id'=>1,'d_id'=>101,'available'=>0),
   array('m_id'=>1,'d_id'=>102,'available'=>1),
   array('m_id'=>1,'d_id'=>103,'available'=>1),
   array('m_id'=>1,'d_id'=>104,'available'=>0),
   array('m_id'=>1,'d_id'=>105,'available'=>0)
 );
</code>```

My question is how I can update the table just with one query like this:

```<code>  $query = "UPDATE tbl_name SET available='".$data[0]['available']."'" WHERE conditon1";
</code>```

I mean update table once instead of 5 query.

答: Possible duplicate of this one. In a nutshell - you need to use either CASE conditional or INSERT ... ON DUPLICATE KEY UPDATE construct.

Body:
I have a table like this:

I receive an array like this:

 $data = array(
   array('m_id'=>1,'d_id'=>101,'available'=>0),
   array('m_id'=>1,'d_id'=>102,'available'=>1),
   array('m_id'=>1,'d_id'=>103,'available'=>1),
   array('m_id'=>1,'d_id'=>104,'available'=>0),
   array('m_id'=>1,'d_id'=>105,'available'=>0)
 );

My question is how I can update the table just with one query like this:

  $query = "UPDATE tbl_name SET available='".$data[0]['available']."'" WHERE conditon1";

I mean update table once instead of 5 query.


问:
How I See my Result in Select from Where MYSQL using PHP?
I have this code, i try to call my data from table database mysql , but didn't see any result. always go to else , not go to the process. what would i do?

<?php
require('connectDB.php');
                 $nama = $_GET['nama'];
                 echo $nama;
                    $query = "SELECT * FROM pesan
                    WHERE nama = '%" . mysqli_real_escape_string($connection, $nama) . "%'

                    ";
              $results = mysqli_query($connection, $query);
              $baris = mysqli_num_rows($results);

              if (!$results) {
               die('Invalid query: ' . mysql_error());
              }

              if ( $baris > 0) {
               while($row = mysqli_fetch_assoc($results)) {
               ?>

Nama Mobil : <?php echo $row['mobil'] ?>

ID Pembelian : <?php echo $row['id']; ?>

Nama anda : <?php echo $row['nama']; ?>

Alamat : <?php echo $row['alamat']; ?>

Tanggal Masuk : <?php echo $row['tgl_masuk']; ?>

              <?php
               }
              }else{
               echo "error";
              }
              ?>```
</div>
</div>
</p>

<p>What wrong with my code?
Thanks!</p>

<p>im sorry , this is my ConnectDB.php , i include in my html. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
    die("Database Connection Failed" . mysqli_error());
}

// $db = new PDO ('mysql:host=localhost;dbname=db_login;charset=utf8mb4','root','');
?></code>```

答:
Your connection check and result check is incorrect.

```<code>$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
    die("Database Connection Failed" . mysqli_connect_error());
}
</code>```

Also

```<code>$results = mysqli_query($connection, $query);
$baris = mysqli_num_rows($results);

if (!$results) {
   die('Invalid query: ' . mysqli_error($connection));
 }
</code>```

Body:
I have this code, i try to call my data from table database mysql , but didn't see any result. always go to else , not go to the process. what would i do?

<?php
require('connectDB.php');
                 $nama = $_GET['nama'];
                 echo $nama;
                    $query = "SELECT * FROM pesan
                    WHERE nama = '%" . mysqli_real_escape_string($connection, $nama) . "%'

                    ";
              $results = mysqli_query($connection, $query);
              $baris = mysqli_num_rows($results);

              if (!$results) {
               die('Invalid query: ' . mysql_error());
              }

              if ( $baris > 0) {
               while($row = mysqli_fetch_assoc($results)) {
               ?>

Nama Mobil : <?php echo $row['mobil'] ?>

ID Pembelian : <?php echo $row['id']; ?>

Nama anda : <?php echo $row['nama']; ?>

Alamat : <?php echo $row['alamat']; ?>

Tanggal Masuk : <?php echo $row['tgl_masuk']; ?>

              <?php
               }
              }else{
               echo "error";
              }
              ?>

What wrong with my code?
Thanks!

im sorry , this is my ConnectDB.php , i include in my html.

<?php
$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
    die("Database Connection Failed" . mysqli_error());
}

// $db = new PDO ('mysql:host=localhost;dbname=db_login;charset=utf8mb4','root','');
?>

Body:
Your connection check and result check is incorrect.

$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
    die("Database Connection Failed" . mysqli_connect_error());
}

Also

$results = mysqli_query($connection, $query);
$baris = mysqli_num_rows($results);

if (!$results) {
   die('Invalid query: ' . mysqli_error($connection));
 }


问:
how to restrict number of instances of a class in C++ or JAVA?
The question was asked to me in an interview, i tried to think could not answer it, i want a piece of Code either in C++ or JAVA that restricts number of instance ( objects ) of a class.</p>

答:
Yes we can restrict instances of class upto some specific limit. It is just an enhancement to Singleton Design Pattern

By making our constructor private and then creating a visible constructor method, we can limit the number of instance creations (like we do in singleton design pattern) or recycle instances or other construction-related tasks.

Doing new x() never returns null, but using the factory pattern, you can return null.

Here is the Java implementation for the same :

```<code>public class LimitObjectCreationTest {

        public static void main(String[] args) {

        LimitClass obj;
        int i=1;
        while(i<=20)
        {
            obj = LimitClass.getLimInstance();
            i++;
        }
      }
}

class LimitClass {

    /**
     * count of alive instances in JVM
     */
    public static int objCount = 0;

    /**
     * private constructor
     * increases the objCount static variable on every object creation
     */
    private LimitClass(){
        objCount++;
        System.out.println("instance " + objCount + " created");
    }

    /**
     * static factory method to return LimitClass instance
     * @return instance of LimitClass if not reached to threshold, else returns null
     */
    public static synchronized LimitClass getLimInstance() {
        if(objCount < 3 ){
            return new LimitClass();
        }
        System.out.println("Instance Limit reached. Can not create new Object");
        System.gc();
        return null;
    }

    /**
     * decreases the objCount static variable when JVM runs garbage collection
     * and destroys unused instances
     */
    @Override
    public void finalize()
    {
        System.out.println("Instance destroyed");
         objCount--;
    }
}
</code>```

Output

```<code>instance 1 created
instance 2 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
instance 3 created
Instance destroyed
instance 2 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
instance 3 created
Instance destroyed
instance 3 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
Instance destroyed
instance 1 created
instance 2 created
</code>```

output may vary based on your allocated JVM memory.

Reference : http://codepumpkin.com/use-private-constructor-java/

Body:
Yes we can restrict instances of class upto some specific limit. It is just an enhancement to Singleton Design Pattern

By making our constructor private and then creating a visible constructor method, we can limit the number of instance creations (like we do in singleton design pattern) or recycle instances or other construction-related tasks.

Doing new x() never returns null, but using the factory pattern, you can return null.

Here is the Java implementation for the same :

public class LimitObjectCreationTest {

        public static void main(String[] args) {

        LimitClass obj;
        int i=1;
        while(i<=20)
        {
            obj = LimitClass.getLimInstance();
            i++;
        }
      }
}

class LimitClass {

    /**
     * count of alive instances in JVM
     */
    public static int objCount = 0;

    /**
     * private constructor
     * increases the objCount static variable on every object creation
     */
    private LimitClass(){
        objCount++;
        System.out.println("instance " + objCount + " created");
    }

    /**
     * static factory method to return LimitClass instance
     * @return instance of LimitClass if not reached to threshold, else returns null
     */
    public static synchronized LimitClass getLimInstance() {
        if(objCount < 3 ){
            return new LimitClass();
        }
        System.out.println("Instance Limit reached. Can not create new Object");
        System.gc();
        return null;
    }

    /**
     * decreases the objCount static variable when JVM runs garbage collection
     * and destroys unused instances
     */
    @Override
    public void finalize()
    {
        System.out.println("Instance destroyed");
         objCount--;
    }
}

Output

instance 1 created
instance 2 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
instance 3 created
Instance destroyed
instance 2 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
instance 3 created
Instance destroyed
instance 3 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
Instance destroyed
instance 1 created
instance 2 created

output may vary based on your allocated JVM memory.

Reference : http://codepumpkin.com/use-private-constructor-java/


答:
In pure MySQL, you could use a CASE expression in the UPDATE to handle this:

```<code>UPDATE tbl_name
SET available = CASE WHEN d_id = 101 THEN 0
                     WHEN d_id = 102 THEN 1
                     WHEN d_id = 103 THEN 1
                     WHEN d_id = 104 THEN 0
                     WHEN d_id = 105 THEN 0 END
WHERE d_id IN (101, 102, 103, 104, 105)
</code>```

If, on the other hand, you wanted to iterate over your array of arrays and then issue UPDATE statements, you could try the following:

```<code>foreach ($data as $entry) {
    $query = "UPDATE tbl_name SET available=".$entry['available']." WHERE d_id=".$entry['d_id'];
    // execute $query ...
}
</code>```

Title: update a table with an array just with one query

Body:
In pure MySQL, you could use a CASE expression in the UPDATE to handle this:

UPDATE tbl_name
SET available = CASE WHEN d_id = 101 THEN 0
                     WHEN d_id = 102 THEN 1
                     WHEN d_id = 103 THEN 1
                     WHEN d_id = 104 THEN 0
                     WHEN d_id = 105 THEN 0 END
WHERE d_id IN (101, 102, 103, 104, 105)

If, on the other hand, you wanted to iterate over your array of arrays and then issue UPDATE statements, you could try the following:

foreach ($data as $entry) {
    $query = "UPDATE tbl_name SET available=".$entry['available']." WHERE d_id=".$entry['d_id'];
    // execute $query ...
}


问:
WPF trigger on datagrid to hide/show columns according to bindings
I have a data grid like this:

```<code><DataGrid AutoGenerateColumns="False" CanUserDeleteRows="True"
          HorizontalScrollBarVisibility="Hidden" Margin="10,10,10,10"
          VerticalScrollBarVisibility="Visible"
          CanUserAddRows="False" ItemsSource="{Binding ListGestores}"
          ToolTip="Selecione uma linha e pressione DELETE para remover uma unidade.">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding TB_UNIDADE.DS_NOME_UNIDADE}" CanUserResize="False" Header="Setor" IsReadOnly="True" x:Name=""/>
        <DataGridTextColumn Binding="{Binding TB_UNIDADE.TB_UNIDADE2.DS_NOME_UNIDADE}" CanUserResize="False" Header="Unidade" IsReadOnly="True" x:Name=""/>
        <DataGridTextColumn Binding="{Binding TB_CONTATOS.DS_NOME}" CanUserResize="False" Header="Gestor" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>
</code>```

The problem is that i need to verify if the 2 column binding is null, and if it is null, i need to Hide it, and Change the Header of the column 1.

I know that i can do that with Triggers, but how exactly???
I started with:

```<code><DataGrid.Triggers>
    <DataTrigger Binding="{Binding TB_UNIDADE.TB_UNIDADE2}" Value="{x:Null}">
        <Setter Property="" Value="" />
    </DataTrigger>
</DataGrid.Triggers>
</code>```

But i don't know what setter or whatever to put !

Help me =]

答:
Example:

With the following ViewModel:

```<code>public class ViewModel : INotifyPropertyChanged
{
    public String Data1 { get; set; }
    public String Data2 { get; set; }
    public String Data3 { get; set; }
}
</code>```

You can use following sample XAML:

```<code><Grid.Resources>
    <local:DataGridColumnVisibilityConverter x:Key="DataGridColumnVisibilityConverter" />
</Grid.Resources>
<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Data1}"
                            Visibility="{Binding, Converter={StaticResource DataGridColumnVisibilityConverter}, ConverterParameter=Data1}" />
        <DataGridTextColumn Binding="{Binding Data2}"
                            Visibility="{Binding, Converter={StaticResource DataGridColumnVisibilityConverter}, ConverterParameter=Data2}" />
        <DataGridTextColumn Binding="{Binding Data3}"
                            Visibility="{Binding, Converter={StaticResource DataGridColumnVisibilityConverter}, ConverterParameter=Data3}" />
    </DataGrid.Columns>
</DataGrid>
</code>```

And converter:

```<code>public class DataGridColumnVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ViewModel viewModel = (ViewModel)value;

        switch (parameter.ToString().ToLower())
        {
            case "data1":
                return (!String.IsNullOrEmpty(viewModel.Data1)) ? Visibility.Visible : Visibility.Collapsed;
            case "data2":
                return (!String.IsNullOrEmpty(viewModel.Data2)) ? Visibility.Visible : Visibility.Collapsed;
            case "data3":
                return (!String.IsNullOrEmpty(viewModel.Data3)) ? Visibility.Visible : Visibility.Collapsed;
        }

        return Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
I have a data grid like this:

<DataGrid AutoGenerateColumns="False" CanUserDeleteRows="True"
          HorizontalScrollBarVisibility="Hidden" Margin="10,10,10,10"
          VerticalScrollBarVisibility="Visible"
          CanUserAddRows="False" ItemsSource="{Binding ListGestores}"
          ToolTip="Selecione uma linha e pressione DELETE para remover uma unidade.">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding TB_UNIDADE.DS_NOME_UNIDADE}" CanUserResize="False" Header="Setor" IsReadOnly="True" x:Name=""/>
        <DataGridTextColumn Binding="{Binding TB_UNIDADE.TB_UNIDADE2.DS_NOME_UNIDADE}" CanUserResize="False" Header="Unidade" IsReadOnly="True" x:Name=""/>
        <DataGridTextColumn Binding="{Binding TB_CONTATOS.DS_NOME}" CanUserResize="False" Header="Gestor" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

The problem is that i need to verify if the 2 column binding is null, and if it is null, i need to Hide it, and Change the Header of the column 1.

I know that i can do that with Triggers, but how exactly???
I started with:

<DataGrid.Triggers>
    <DataTrigger Binding="{Binding TB_UNIDADE.TB_UNIDADE2}" Value="{x:Null}">
        <Setter Property="" Value="" />
    </DataTrigger>
</DataGrid.Triggers>

But i don't know what setter or whatever to put !

Help me =]

Body:
Example:

With the following ViewModel:

public class ViewModel : INotifyPropertyChanged
{
    public String Data1 { get; set; }
    public String Data2 { get; set; }
    public String Data3 { get; set; }
}

You can use following sample XAML:

<Grid.Resources>
    <local:DataGridColumnVisibilityConverter x:Key="DataGridColumnVisibilityConverter" />
</Grid.Resources>
<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Data1}"
                            Visibility="{Binding, Converter={StaticResource DataGridColumnVisibilityConverter}, ConverterParameter=Data1}" />
        <DataGridTextColumn Binding="{Binding Data2}"
                            Visibility="{Binding, Converter={StaticResource DataGridColumnVisibilityConverter}, ConverterParameter=Data2}" />
        <DataGridTextColumn Binding="{Binding Data3}"
                            Visibility="{Binding, Converter={StaticResource DataGridColumnVisibilityConverter}, ConverterParameter=Data3}" />
    </DataGrid.Columns>
</DataGrid>

And converter:

public class DataGridColumnVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ViewModel viewModel = (ViewModel)value;

        switch (parameter.ToString().ToLower())
        {
            case "data1":
                return (!String.IsNullOrEmpty(viewModel.Data1)) ? Visibility.Visible : Visibility.Collapsed;
            case "data2":
                return (!String.IsNullOrEmpty(viewModel.Data2)) ? Visibility.Visible : Visibility.Collapsed;
            case "data3":
                return (!String.IsNullOrEmpty(viewModel.Data3)) ? Visibility.Visible : Visibility.Collapsed;
        }

        return Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


问:
navigator is deprecated and has been removed even i don't use navigator
I don't use Navigator in my codes. But I am getting this error.

```<code>"dependencies": {
    "react": "16.0.0-alpha.12",
    "react-native": "0.45.1",
    "react-native-deprecated-custom-components": "^0.1.0",
    "react-native-router-redux": "^0.2.2",
    "react-redux": "^5.0.5",
    "redux": "^3.7.0"
},
"devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.0.0",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12"
}
</code>```

Anyone can help me?

答:
Navigation experimental(Previously Navigator) has been removed from React Native and moved to a separate package react-native-deprecated-custom-components. It has been deprecated and not recommended. To fix your old code you can perform following steps

Install package react-native-deprecated-custom-components

npm install react-native-deprecated-custom-components --save

Import NavigationExperimental(Previously Navigator)

import NavigationExperimental from 'react-native-deprecated-custom-comreponents';

Replace Navigator with NavigationExperimental.Navigator

Body:
I don't use Navigator in my codes. But I am getting this error.

"dependencies": {
    "react": "16.0.0-alpha.12",
    "react-native": "0.45.1",
    "react-native-deprecated-custom-components": "^0.1.0",
    "react-native-router-redux": "^0.2.2",
    "react-redux": "^5.0.5",
    "redux": "^3.7.0"
},
"devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.0.0",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12"
}

Anyone can help me?


问:
Fatal error in PHP function prepared statement
I am using prepared statement for login. The compiler is giving a fatal error in the store result function. It is not saving the row in the result that I want to show. I saw solutions but they are not working.</p>

```<code>if($_SERVER["REQUEST_METHOD"]=="POST"){
    $sql = "SELECT * FROM login where email=? and password=?";
    $stmt= $conn->prepare($sql);

    $stmt->bind_param("ss", $_POST["email"],$_POST["password"]);
    $stmt->execute();

    //$res=$result->num_rows;
    $res=store_result();
    $row = mysqli_fetch_assoc($res);

    if ($stmt->num_rows>0) {

        // output data of each row

      while($row['admin_role']==1)
      {
        $_SESSION["email"]=$email;
        $_SESSION["id"]=$row['user_id'];
        header('Location: index.html');
        exit;
      }
     } else {
       echo "0 results";
     }
 }

?>
</code>```

答:
According to the docs here and the error message you are getting the function name should be mysqli_store_result and not store_result.

You will also need to provide your connection variable which looking at your code above appears to be $conn so it would be:

```<code>mysqli_store_result($conn)
</code>```

Alternatively I believe you could call it as a class method directly using your $conn variable as below:

```<code>$conn->store_result()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using prepared statement for login. The compiler is giving a fatal error in the store result function. It is not saving the row in the result that I want to show. I saw solutions but they are not working.

if($_SERVER["REQUEST_METHOD"]=="POST"){
    $sql = "SELECT * FROM login where email=? and password=?";
    $stmt= $conn->prepare($sql);

    $stmt->bind_param("ss", $_POST["email"],$_POST["password"]);
    $stmt->execute();

    //$res=$result->num_rows;
    $res=store_result();
    $row = mysqli_fetch_assoc($res);

    if ($stmt->num_rows>0) {

        // output data of each row

      while($row['admin_role']==1)
      {
        $_SESSION["email"]=$email;
        $_SESSION["id"]=$row['user_id'];
        header('Location: index.html');
        exit;
      }
     } else {
       echo "0 results";
     }
 }

?>

Body:
According to the docs here and the error message you are getting the function name should be mysqli_store_result and not store_result.

You will also need to provide your connection variable which looking at your code above appears to be $conn so it would be:

mysqli_store_result($conn)

Alternatively I believe you could call it as a class method directly using your $conn variable as below:

$conn->store_result()


问:
Public Scala constructor fields not public in Java
The question is quite simple. When I declare a Scala field directly in a constructor, like this:

```<code>class Vector2D(val x: Float, val y: Float) {

}
</code>```

The fields x and y are not public in Java. For example:

```<code>public class JavaMain {
    public static void main(String[] args) {
        Vector2D vec = new Vector2D(1, 2);
        System.out.println(vec.x); //Won't compile.
    }
}
</code>```

However, in Scala this will compile:

```<code>object ScalaMain {
    def main(args: Array[String]) = {
        var vec = new Vector2D(1, 2);
        println(vec.x);
    }
}
</code>```

Why does this not compile in Java? Is there a workaround or correct approach?

If you are wondering these classes are in the same project and same package. I am using Scala IDE.

Another interesting thing, is that the IDE will put a red underline under the incorrect code but fails to display an error icon next to the file with the error like it normally would.

答:
you can access scala class members from java with paranthesis like member_variable().

If you print the scala compiled class, you will see accessors defined as def x() and def y().

```<code>$ scalac -print Vector2d.scala
[[syntax trees at end of                   cleanup]] // Vector2d.scala
package <empty> {
  class Vector2D extends Object {
    <paramaccessor> private[this] val x: Float = _;
    <stable> <accessor> <paramaccessor> def x(): Float = Vector2D.this.x;
    <paramaccessor> private[this] val y: Float = _;
    <stable> <accessor> <paramaccessor> def y(): Float = Vector2D.this.y;
    def <init>(x: Float, y: Float): Vector2D = {
      Vector2D.this.x = x;
      Vector2D.this.y = y;
      Vector2D.super.<init>();
      ()
    }
  }
}
</code>```

So from java code, call the accessors x() or y().

```<code>public class JavaMain {

    public static void main(String[] args) {
        Vector2D vec = new Vector2D(1, 2);
        System.out.println(vec.x());
    }
}
</code>```

Also see

Accessing Scala instance variables from Java in Eclipse

Body:
The question is quite simple. When I declare a Scala field directly in a constructor, like this:

class Vector2D(val x: Float, val y: Float) {

}

The fields x and y are not public in Java. For example:

public class JavaMain {
    public static void main(String[] args) {
        Vector2D vec = new Vector2D(1, 2);
        System.out.println(vec.x); //Won't compile.
    }
}

However, in Scala this will compile:

object ScalaMain {
    def main(args: Array[String]) = {
        var vec = new Vector2D(1, 2);
        println(vec.x);
    }
}

Why does this not compile in Java? Is there a workaround or correct approach?

If you are wondering these classes are in the same project and same package. I am using Scala IDE.

Another interesting thing, is that the IDE will put a red underline under the incorrect code but fails to display an error icon next to the file with the error like it normally would.

Body:
you can access scala class members from java with paranthesis like member_variable().

If you print the scala compiled class, you will see accessors defined as def x() and def y().

$ scalac -print Vector2d.scala
[[syntax trees at end of                   cleanup]] // Vector2d.scala
package <empty> {
  class Vector2D extends Object {
    <paramaccessor> private[this] val x: Float = _;
    <stable> <accessor> <paramaccessor> def x(): Float = Vector2D.this.x;
    <paramaccessor> private[this] val y: Float = _;
    <stable> <accessor> <paramaccessor> def y(): Float = Vector2D.this.y;
    def <init>(x: Float, y: Float): Vector2D = {
      Vector2D.this.x = x;
      Vector2D.this.y = y;
      Vector2D.super.<init>();
      ()
    }
  }
}

So from java code, call the accessors x() or y().

public class JavaMain {

    public static void main(String[] args) {
        Vector2D vec = new Vector2D(1, 2);
        System.out.println(vec.x());
    }
}

Also see

Accessing Scala instance variables from Java in Eclipse


问:
invalid group function in sql
```<code>select * from details where sal=max(sal);
</code>```

I use this but I get error..What is the mistake in this query .I know

select Max(sal) from table;

select * from details where sal=max(sal);

are correct queries but I need to know what is the mistake in my query.

答:
You intend to compare each row's salary against the maximum value in that table.  Then use a subquery to determine that maximum salary:

```<code>SELECT *
FROM details
WHERE sal = (SELECT MAX(sal) FROM details)
</code>```

This query would return all records having the max salary, which could be more than one in the case of a tie.  If you are certain that there be only a single record having the maximum salary, then the following would also work:

```<code>SELECT *
FROM details
ORDER BY sal DESC
LIMIT 1
</code>```

Title: invalid group function in sql

Body:
select * from details where sal=max(sal);

I use this but I get error..What is the mistake in this query .I know

select Max(sal) from table;

select * from details where sal=max(sal);

are correct queries but I need to know what is the mistake in my query.

Body:
You intend to compare each row's salary against the maximum value in that table.  Then use a subquery to determine that maximum salary:

SELECT *
FROM details
WHERE sal = (SELECT MAX(sal) FROM details)

This query would return all records having the max salary, which could be more than one in the case of a tie.  If you are certain that there be only a single record having the maximum salary, then the following would also work:

SELECT *
FROM details
ORDER BY sal DESC
LIMIT 1


问:
Flink JDBCInputFormat cannot find method 'setRowTypeInfo'
I want to use flink-jdbc to get data from mysql。
I have seen an example on Apache flink website

```<code>// Read data from a relational database using the JDBC input format
DataSet<Tuple2<String, Integer> dbData =
    env.createInput(
      JDBCInputFormat.buildJDBCInputFormat()
                     .setDrivername("org.apache.derby.jdbc.EmbeddedDriver")
                     .setDBUrl("jdbc:derby:memory:persons")
                     .setQuery("select name, age from persons")
                     .setRowTypeInfo(new RowTypeInfo(BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO))
                     .finish()
    );
</code>```

But when i try to write a demo， i can't find the method 'setRowTypeInfo'.
It was like this

```<code>import org.apache.flink.api.common.typeinfo.BasicTypeInfo
import org.apache.flink.api.java.ExecutionEnvironment
import org.apache.flink.api.java.io.jdbc.JDBCInputFormat
import org.apache.flink.api.scala._

/**
  * Created by lulijun on 17/7/7.
  */
object FlinkJDBC {

  def main(args:Array[String]): Unit = {

    val env = ExecutionEnvironment.createLocalEnvironment()

    val dbData = env.createInput(
      JDBCInputFormat.buildJDBCInputFormat
        .setDrivername("com.mysql.jdbc.Driver")
        .setDBUrl("XXX")
        .setUsername("xxx")
        .setPassword("XXX")
        .setQuery("select name, age from persons")
        .setRowTypeInfo(new Nothing(BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO))
        .finish)

    dbData.print()

    env.execute()
  }

}
</code>```

The "setRowTypeInfo" method is always red, and the IDEA prompts
"cannot resolve symbol setRowTypeInfo"

The jar version of flink-jdbc i used is 1.0.0.

```<code><dependencies>
    <!-- Use this dependency if you are using the DataSet API -->
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-scala_2.10</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-clients_2.10</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-jdbc</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
    </dependency>
</dependencies>
</code>```

I have searched a lot, and most of the people use the method exactly like the official document, but on one mentioned this problem.
I doubt whether I used the wrong version of flink-jdbc, but I cannot get any information about the right way to use flink-jdbc.
If you know the problem, please teach me.Thank you.

答:
I changed the flink-jdbc version from 1.0.0 to 1.3.0 and the problem solved.
But when I search flink-jdbc on maven websit
https://mvnrepository.com/search?q=flink-jdbc, I can't get the right information in the first few pages, It makes me thought the version of flink-jdbc do not need to be matched with other flink jars.
But the truth is flink-jdbc/1.1.3 use class RowTypeInfo of package api.table, but flink-jdbc/1.3.0 use class RowTypeInfo of package api.java.They have close ties with each other.
We must make sure the version is matched.</p>

Body:
I want to use flink-jdbc to get data from mysql。
I have seen an example on Apache flink website

// Read data from a relational database using the JDBC input format
DataSet<Tuple2<String, Integer> dbData =
    env.createInput(
      JDBCInputFormat.buildJDBCInputFormat()
                     .setDrivername("org.apache.derby.jdbc.EmbeddedDriver")
                     .setDBUrl("jdbc:derby:memory:persons")
                     .setQuery("select name, age from persons")
                     .setRowTypeInfo(new RowTypeInfo(BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO))
                     .finish()
    );

But when i try to write a demo， i can't find the method 'setRowTypeInfo'.
It was like this

import org.apache.flink.api.common.typeinfo.BasicTypeInfo
import org.apache.flink.api.java.ExecutionEnvironment
import org.apache.flink.api.java.io.jdbc.JDBCInputFormat
import org.apache.flink.api.scala._

/**
  * Created by lulijun on 17/7/7.
  */
object FlinkJDBC {

  def main(args:Array[String]): Unit = {

    val env = ExecutionEnvironment.createLocalEnvironment()

    val dbData = env.createInput(
      JDBCInputFormat.buildJDBCInputFormat
        .setDrivername("com.mysql.jdbc.Driver")
        .setDBUrl("XXX")
        .setUsername("xxx")
        .setPassword("XXX")
        .setQuery("select name, age from persons")
        .setRowTypeInfo(new Nothing(BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO))
        .finish)

    dbData.print()

    env.execute()
  }

}

The "setRowTypeInfo" method is always red, and the IDEA prompts
"cannot resolve symbol setRowTypeInfo"

The jar version of flink-jdbc i used is 1.0.0.

<dependencies>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-scala_2.10</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-clients_2.10</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-jdbc</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
    </dependency>
</dependencies>

I have searched a lot, and most of the people use the method exactly like the official document, but on one mentioned this problem.
I doubt whether I used the wrong version of flink-jdbc, but I cannot get any information about the right way to use flink-jdbc.
If you know the problem, please teach me.Thank you.


问:
Difficulty with apps with a forced landscape orientation
I have two apps, both of which force the user to use the iPhone in landscape mode, in order to have a wider screen, instead of a taller one.

One of the things I have found is that my first view will look fine, but all other views come up with their subviews (UIButtons, UIPicker, UIViews) squeezed to one side or clipped (depending on whether the elements were set to move, resize or stay in the same position as the view size changed).  All my views are designed in IB in the landscape orientation.  My underlying UIWindow, and everything I can think of has been laid out in landscape orientation. Even my plist file has the UIInterfaceOrientationLandscapeRight flag set.

Now, if I load all my views at the same time as my rootview controller, then I have no problems.  But if I have views loaded later, they get clipped or squeezed.

The only way to get around the problem was to add the following line in my code that flips in a new view:

```<code>[coming.view setFrame:CGRectMake(0, 0, 480, 300)];
</code>```

Anyone know why I need to do this? Is it just that the iPhone assumes that loaded views are 300x480 unless a transform gets applied to them?

Thanks.

ps. This is what the view looks like if I don't call setFrame, as described above:

alt text http://files.me.com/mahboud/ljhvun

All viewcontrollers that get loaded after the first one will have their screen similarly squeezed down.  For some reason the first viewcontroller doesn't have this issue.

答:
A simple way I fixed this was to have my root view controller subclass UINavigationController, and implement shouldAutorotateToInterfaceOrientation to handle landscape view ie,

```<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
            (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
</code>```

Every view controller that is pushed to the navigation controller seems to appear in landscape too.

Body:
I have two apps, both of which force the user to use the iPhone in landscape mode, in order to have a wider screen, instead of a taller one.

One of the things I have found is that my first view will look fine, but all other views come up with their subviews (UIButtons, UIPicker, UIViews) squeezed to one side or clipped (depending on whether the elements were set to move, resize or stay in the same position as the view size changed).  All my views are designed in IB in the landscape orientation.  My underlying UIWindow, and everything I can think of has been laid out in landscape orientation. Even my plist file has the UIInterfaceOrientationLandscapeRight flag set.

Now, if I load all my views at the same time as my rootview controller, then I have no problems.  But if I have views loaded later, they get clipped or squeezed.

The only way to get around the problem was to add the following line in my code that flips in a new view:

[coming.view setFrame:CGRectMake(0, 0, 480, 300)];

Anyone know why I need to do this? Is it just that the iPhone assumes that loaded views are 300x480 unless a transform gets applied to them?

Thanks.

ps. This is what the view looks like if I don't call setFrame, as described above:

alt text http://files.me.com/mahboud/ljhvun

All viewcontrollers that get loaded after the first one will have their screen similarly squeezed down.  For some reason the first viewcontroller doesn't have this issue.

Body:
A simple way I fixed this was to have my root view controller subclass UINavigationController, and implement shouldAutorotateToInterfaceOrientation to handle landscape view ie,

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
            (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}

Every view controller that is pushed to the navigation controller seems to appear in landscape too.


问:
PHP/SimpleXML - Arrays generated differently for single child and multiple children
I'm using SimpleXML to parse an XML feed of property listings from different realtors. The relevant section of the XML feed looks something like this:

```<code><branch name="Trustee Realtors">
    <properties>
        <property>
            <reference>1</reference>
            <price>275000</price>
            <bedrooms>3</bedrooms>
        </property>
        <property>
            <reference>2</reference>
            <price>350000</price>
            <bedrooms>4</bedrooms>
        </property>
        <property>
            <reference>3</reference>
            <price>128500</price>
            <bedrooms>4</bedrooms>
        </property>
    </properties>
</branch>
<branch name="Quick-E-Realty Inc">
    <properties>
        <property>
            <reference>4</reference>
            <price>180995</price>
            <bedrooms>3</bedrooms>
        </property>
    </properties>
</branch>
</code>```

and is then converted to an array like this:

```<code>$xml = file_get_contents($filename);
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);
$xml_array = array($xml->getName() => $xml_array);
</code>```

The issue I'm having is that when the array is created the data for the single listing is in a different position in the array to the multiple listings - I'm not sure exactly how to explain this, but if I var_dump() the array for the multiple items it looks like this:

```<code>array(3) {
    [0]=>
    array(3) {
        ["reference"]=>
        string(4) "0001"
        ["price"]=>
        string(6) "275000"
        ["bedrooms"]=>
        int(3)
    }
    [1]=>
    array(3) {
        ["reference"]=>
        string(4) "0002"
        ["price"]=>
        string(6) "350000"
        ["bedrooms"]=>
        int(4)
    }
    [2]=>
    array(3) {
    ["reference"]=>
        string(4) "0003"
        ["price"]=>
        string(6) "128500"
        ["bedrooms"]=>
        int(2)
    }
}
</code>```

If I var_dump() the array for the single listing it looks like this:

```<code>array(3) {
    ["reference"]=>
    string(4) "0004"
    ["price"]=>
    string(6) "180995"
    ["bedrooms"]=>
    int(3)
}
</code>```

But what I need it to look like is this:

```<code>array(1) {
    [0]=>
    array(3) {
        ["reference"]=>
        string(4) "0004"
        ["price"]=>
        string(6) "180995"
        ["bedrooms"]=>
        int(3)
    }
}
</code>```

Each of these arrays represents the property listings from a single realtor. I'm not sure whether this is just the way that SimpleXML or the json functions work but what I need is for the same format to be used (the array containing the property listing to be the value of the [0] key).

Thanks in advance!

答:
In order to solve this problem, you should select using xpath (as other mention), but in my opinion this is not a very familiar tool to most web-developers. I created a very small composer enabled package, which solves this problem. Credit to the symfony package CssSelector (https://symfony.com/doc/current/components/css_selector.html) which rewrites CSS selectors to xpath selectors. My package is just a thin wrapper that actually deals with what you in the most common cases will do with XML using PHP. You can find it here: https://github.com/diversen/simple-query-selector

```<code>use diversen\querySelector;

// Load simple XML document
$xml = simplexml_load_file('test2.xml');

// Get all branches as DOM elements
$elems = querySelector::getElementsAsDOM($xml, 'branch');

foreach($elems as $elem) {
    // Get attribute name
    echo $elem->attributes()->name . "\n";
    // Get properties as array
    $props = querySelector::getElementsAsAry($elem, 'property');
    print_r($props); // You will get the array structure you expect
}
</code>```

You could also (if you don't care about the branch name) just do:

```<code>$elems = querySelector::getElementsAsAry($xml, 'property');
</code>```

Body:
I'm using SimpleXML to parse an XML feed of property listings from different realtors. The relevant section of the XML feed looks something like this:

<branch name="Trustee Realtors">
    <properties>
        <property>
            <reference>1</reference>
            <price>275000</price>
            <bedrooms>3</bedrooms>
        </property>
        <property>
            <reference>2</reference>
            <price>350000</price>
            <bedrooms>4</bedrooms>
        </property>
        <property>
            <reference>3</reference>
            <price>128500</price>
            <bedrooms>4</bedrooms>
        </property>
    </properties>
</branch>
<branch name="Quick-E-Realty Inc">
    <properties>
        <property>
            <reference>4</reference>
            <price>180995</price>
            <bedrooms>3</bedrooms>
        </property>
    </properties>
</branch>

and is then converted to an array like this:

$xml = file_get_contents($filename);
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);
$xml_array = array($xml->getName() => $xml_array);

The issue I'm having is that when the array is created the data for the single listing is in a different position in the array to the multiple listings - I'm not sure exactly how to explain this, but if I var_dump() the array for the multiple items it looks like this:

array(3) {
    [0]=>
    array(3) {
        ["reference"]=>
        string(4) "0001"
        ["price"]=>
        string(6) "275000"
        ["bedrooms"]=>
        int(3)
    }
    [1]=>
    array(3) {
        ["reference"]=>
        string(4) "0002"
        ["price"]=>
        string(6) "350000"
        ["bedrooms"]=>
        int(4)
    }
    [2]=>
    array(3) {
    ["reference"]=>
        string(4) "0003"
        ["price"]=>
        string(6) "128500"
        ["bedrooms"]=>
        int(2)
    }
}

If I var_dump() the array for the single listing it looks like this:

array(3) {
    ["reference"]=>
    string(4) "0004"
    ["price"]=>
    string(6) "180995"
    ["bedrooms"]=>
    int(3)
}

But what I need it to look like is this:

array(1) {
    [0]=>
    array(3) {
        ["reference"]=>
        string(4) "0004"
        ["price"]=>
        string(6) "180995"
        ["bedrooms"]=>
        int(3)
    }
}

Each of these arrays represents the property listings from a single realtor. I'm not sure whether this is just the way that SimpleXML or the json functions work but what I need is for the same format to be used (the array containing the property listing to be the value of the [0] key).

Thanks in advance!

Body:
In order to solve this problem, you should select using xpath (as other mention), but in my opinion this is not a very familiar tool to most web-developers. I created a very small composer enabled package, which solves this problem. Credit to the symfony package CssSelector (https://symfony.com/doc/current/components/css_selector.html) which rewrites CSS selectors to xpath selectors. My package is just a thin wrapper that actually deals with what you in the most common cases will do with XML using PHP. You can find it here: https://github.com/diversen/simple-query-selector

use diversen\querySelector;

// Load simple XML document
$xml = simplexml_load_file('test2.xml');

// Get all branches as DOM elements
$elems = querySelector::getElementsAsDOM($xml, 'branch');

foreach($elems as $elem) {
    // Get attribute name
    echo $elem->attributes()->name . "\n";
    // Get properties as array
    $props = querySelector::getElementsAsAry($elem, 'property');
    print_r($props); // You will get the array structure you expect
}

You could also (if you don't care about the branch name) just do:

$elems = querySelector::getElementsAsAry($xml, 'property');


问:
spring data compose @query query dynamically
I have situation in which I have to compose a JPQL query in some method, then  pass this query to spring data query method to be used as the query in @Query annotation

```<code>@Query(value = ":DyanamicQuery")
List<PrizeInsuranceConfiguration> filterConfigurPrizeInsurance(String DyanamicQuery);
</code>```

or at least the conditions part

```<code>@Query(value = "SELECT c FROM PrizeInsuranceConfiguration c WHERE  :DyanamicConditions")
List<PrizeInsuranceConfiguration> filterConfigurPrizeInsurance(String DyanamicConditions);
</code>```

答:
Do, you can do that. There are two reasons why not:

sql  injection (spring data work with prepared statements);

(result of first reasone) spring data create query tree and bind all params

But if you need dynamic query you can use Specifications, Query by Example or Querydsl.

Body:
I have situation in which I have to compose a JPQL query in some method, then  pass this query to spring data query method to be used as the query in @Query annotation

@Query(value = ":DyanamicQuery")
List<PrizeInsuranceConfiguration> filterConfigurPrizeInsurance(String DyanamicQuery);

or at least the conditions part

@Query(value = "SELECT c FROM PrizeInsuranceConfiguration c WHERE  :DyanamicConditions")
List<PrizeInsuranceConfiguration> filterConfigurPrizeInsurance(String DyanamicConditions);


问:
SpringData MongoDB cannot determine IsNewStrategy during Auditing
I am trying to enable Auditing using Annotations. My domain class has @Id field that is populated while constructing the object. I have added a java.util.Date field for lastModified and annotated it with @LastModifiedDate.

@Document
public class Book {
    @Id
    private String name;
    private String isbn;
    @LastModifiedDate
    private Date lastModified;

    public Book(String name) {
        this.name = name;
    }
}
```

<p>I have enabled auditing in the Spring Configuration XML using <code><mongo:auditing/>.</code></p>

<p>When I try to save an instance of my object, I get the following error:</p>

<pre class="lang-java prettyprint-override"><code>Book book1 = new Book("ABCD");
mongoOps.save(book1);
</code>```

java.lang.IllegalArgumentException: Unsupported entity com.pankaj.Book! Could not determine IsNewStrategy.

I do not want to use the Auditable interface nor extend my domain classes from AbstractAuditable. I only want to use the Annotations.
Since I am not interested in the @CreatedBy and the @LastModifiedBy, I am not implementing the AuditAware interface as well.

I just want the @LastModifiedDate to work for my domain classes. What am I missing?

I am using version 1.7.0 of SpringData MongoDB.

答:
I had the same issue when using annotations only configuration.

When you put @EnableMongoAuditing on a configuration class, Spring will create a MappingContext bean.

Then you have to make sure the same mappingContext is being used in the MongoTemplate.

```<code>@Configuration
@EnableMongoAuditing
@EnableMongoRepositories(value = "my.repositories.package", mongoTemplateRef = "myMongoTemplate")
class MongoConfig {

    @Autowired
    //Autowiring the MongoMappingContext will supply the same MongoMappingContext as the one used in auditing
    MongoMappingContext mongoMappingContext;

    @Bean
    MongoTemplate myMongoTemplate() {

        String databaseName = "mydbname";
        MongoDbFactory factory = new SimpleMongoDbFactory(mongoClient, databaseName);
        MongoConverter converter = new MappingMongoConverter(factory, mongoMappingContext);
        MongoTemplate mongoTemplate =  new MongoTemplate(factory, converter);
        return mongoTemplate;
    }
}
</code>```

Body:
I am trying to enable Auditing using Annotations. My domain class has @Id field that is populated while constructing the object. I have added a java.util.Date field for lastModified and annotated it with @LastModifiedDate.

@Document
public class Book {
    @Id
    private String name;
    private String isbn;
    @LastModifiedDate
    private Date lastModified;

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

I have enabled auditing in the Spring Configuration XML using <mongo:auditing/>.

When I try to save an instance of my object, I get the following error:

Book book1 = new Book("ABCD");
mongoOps.save(book1);

java.lang.IllegalArgumentException: Unsupported entity com.pankaj.Book! Could not determine IsNewStrategy.

I do not want to use the Auditable interface nor extend my domain classes from AbstractAuditable. I only want to use the Annotations.
Since I am not interested in the @CreatedBy and the @LastModifiedBy, I am not implementing the AuditAware interface as well.

I just want the @LastModifiedDate to work for my domain classes. What am I missing?

I am using version 1.7.0 of SpringData MongoDB.

Body:
I had the same issue when using annotations only configuration.

When you put @EnableMongoAuditing on a configuration class, Spring will create a MappingContext bean.

Then you have to make sure the same mappingContext is being used in the MongoTemplate.

@Configuration
@EnableMongoAuditing
@EnableMongoRepositories(value = "my.repositories.package", mongoTemplateRef = "myMongoTemplate")
class MongoConfig {

    @Autowired
    //Autowiring the MongoMappingContext will supply the same MongoMappingContext as the one used in auditing
    MongoMappingContext mongoMappingContext;

    @Bean
    MongoTemplate myMongoTemplate() {

        String databaseName = "mydbname";
        MongoDbFactory factory = new SimpleMongoDbFactory(mongoClient, databaseName);
        MongoConverter converter = new MappingMongoConverter(factory, mongoMappingContext);
        MongoTemplate mongoTemplate =  new MongoTemplate(factory, converter);
        return mongoTemplate;
    }
}


问:
libprotoc compiling protoc files but not other protoc included in it (google grpc assistant annotations.pb.h no file or directory error)
I am trying to generate Google Assistant library in C++.
I have compiled the embedded_assistant.proto file using protoc compiler and obtained the embedded_assistant.grpc.pb.h and embedded_assistant.grpc.pb.cc files for library.
I created a client file ea_main.cc and included these files in it.

When i try to compile ea_main.cc using g++ compiler I get this error.

```<code>car@ubuntu:~/grpc/examples/cpp/embedded_assistant$ g++ -I./ ea_main.cc -o OUT_CPP_TEST -std=c++11
In file included from embedded_assistant.grpc.pb.h:22:0,
                 from ea_main.cc:9:
embedded_assistant.pb.h:33:39: fatal error: google/api/annotations.pb.h: No such file or directory
compilation terminated.
</code>```

In the embedded_assistant.proto file there is another proto file included in it as

```<code>import "google/api/annotations.proto";
import "google/rpc/status.proto";
</code>```

It seems that the protoc didnt compiled or generated headers for these .proto files. When looked in google/api/ they ere not there.

So thats why the g++ compiler is giving errors for the missing annotations.pb.h file.

Why the protoc didnt compiled the proto included in embedded_assistant.proto
?How can I get these files??
Is something wrong?

答:
I got the solution i.e. include other required protos while compiling like:-</p>

```<code>protoc --proto_path=protos --cpp_out=. protos/embedded_assistant.proto protos/google/api/annotations.proto protos/google/api/http.proto protos/google/rpc/status.proto
</code>```

Body:
I am trying to generate Google Assistant library in C++.
I have compiled the embedded_assistant.proto file using protoc compiler and obtained the embedded_assistant.grpc.pb.h and embedded_assistant.grpc.pb.cc files for library.
I created a client file ea_main.cc and included these files in it.

When i try to compile ea_main.cc using g++ compiler I get this error.

car@ubuntu:~/grpc/examples/cpp/embedded_assistant$ g++ -I./ ea_main.cc -o OUT_CPP_TEST -std=c++11
In file included from embedded_assistant.grpc.pb.h:22:0,
                 from ea_main.cc:9:
embedded_assistant.pb.h:33:39: fatal error: google/api/annotations.pb.h: No such file or directory
compilation terminated.

In the embedded_assistant.proto file there is another proto file included in it as

import "google/api/annotations.proto";
import "google/rpc/status.proto";

It seems that the protoc didnt compiled or generated headers for these .proto files. When looked in google/api/ they ere not there.

So thats why the g++ compiler is giving errors for the missing annotations.pb.h file.

Why the protoc didnt compiled the proto included in embedded_assistant.proto
?How can I get these files??
Is something wrong?

Body:
I got the solution i.e. include other required protos while compiling like:-

protoc --proto_path=protos --cpp_out=. protos/embedded_assistant.proto protos/google/api/annotations.proto protos/google/api/http.proto protos/google/rpc/status.proto


问:
How to: Google marker url open in a new tab
I want to make my map marker opening the map in the new tab. Dou you have any advices?

```<code>var map = $that.data('googleMap');

                            google.maps.event.addListener(marker, 'click',
function() {
                                infowindow.open(map, marker);
                            });
                        } else if(params.url) {
                            google.maps.event.addListener(marker, 'click',
function() {
                                document.location = params.url;
                            });
                        }
</code>```

In footer.tpl I have this:

```<code>$("#mapContact").addMarker({
      coords: [49.004674, 14.770050],
      icon: '/themes/organie4/img/dorado/contact/location-pin.png',
      url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
    });
</code>```

Thank you!

答:
Sure. Here it is.

jquery.googlemap.js

```<code>var map = $that.data('googleMap');

    marker.addListener('click', function() {
    if (this.url) {
           window.open(this.url, '_blank')
          // Or like this if you want a new tab : window.open(this.url, '_blank');
                   } else {
                                infowindow.open(map, this);
                            }
                        });
</code>```

footer.tpl

```<code>var marker = new google.maps.Marker({
        position: {lat: 49.004674, lng: 14.770050},
        map: map,
        icon: '/themes/organie4/img/dorado/contact/location-pin.png',
        url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
  });
</code>```

When I change footer.tpl my page "Contact" throw 500 (Internal Server Error)

Body:
I want to make my map marker opening the map in the new tab. Dou you have any advices?

var map = $that.data('googleMap');

                            google.maps.event.addListener(marker, 'click',
function() {
                                infowindow.open(map, marker);
                            });
                        } else if(params.url) {
                            google.maps.event.addListener(marker, 'click',
function() {
                                document.location = params.url;
                            });
                        }

In footer.tpl I have this:

$("#mapContact").addMarker({
      coords: [49.004674, 14.770050],
      icon: '/themes/organie4/img/dorado/contact/location-pin.png',
      url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
    });

Thank you!

Body:
Sure. Here it is.

jquery.googlemap.js

var map = $that.data('googleMap');

    marker.addListener('click', function() {
    if (this.url) {
           window.open(this.url, '_blank')
          // Or like this if you want a new tab : window.open(this.url, '_blank');
                   } else {
                                infowindow.open(map, this);
                            }
                        });

footer.tpl

var marker = new google.maps.Marker({
        position: {lat: 49.004674, lng: 14.770050},
        map: map,
        icon: '/themes/organie4/img/dorado/contact/location-pin.png',
        url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
  });

When I change footer.tpl my page "Contact" throw 500 (Internal Server Error)


问:
How to get the resultant array from a Mongoid::Criteria without an "each" block
Our application uses ajax very heavily and as a result of this we have statements like var items = #{@items.to_json} in all our views. Now @items is being set in the controller as @items=Item.all. The problem is that @items is a Mongoid::Criteria and it doesn't have a .to_json method. So, it's throwing up an error while rendering the view. Is there an easy way to convert this criteria object into an array without using code like @items.collect {|i| i}

答:
Use the #entries method in criteria to do request:

```<code>@items = Item.all.entries
</code>```

Body:
Use the #entries method in criteria to do request:

@items = Item.all.entries


答:
When Scala compiles this down to class files, the x and y variables are made accessible through methods of the same name.  So in Java, you would access this variable by calling x().

Note that in Scala, the use of brackets when calling methods is generally optional, which is why it looks like you are accessing the variable directly.

Title: Public Scala constructor fields not public in Java

Body:
The question is quite simple. When I declare a Scala field directly in a constructor, like this:

class Vector2D(val x: Float, val y: Float) {

}

The fields x and y are not public in Java. For example:

public class JavaMain {
    public static void main(String[] args) {
        Vector2D vec = new Vector2D(1, 2);
        System.out.println(vec.x); //Won't compile.
    }
}

However, in Scala this will compile:

object ScalaMain {
    def main(args: Array[String]) = {
        var vec = new Vector2D(1, 2);
        println(vec.x);
    }
}

Why does this not compile in Java? Is there a workaround or correct approach?

If you are wondering these classes are in the same project and same package. I am using Scala IDE.

Another interesting thing, is that the IDE will put a red underline under the incorrect code but fails to display an error icon next to the file with the error like it normally would.