问:
How to autowire a class which is in another project
I have two java projects as epService and epEntity (factory classes for db access). And there is another Spring project as epWeb which contains controllers and this is a Rest API.
Now, I want to autowire a class which is inside epEntity to the spring project epWeb.
I have successfully autowired classes within that epWeb project but I was unable to autowire a class from another project
Anyone have a suggestion for doing that, please let me know.
If this is an irrelevant question for stackoverflow, please delete this.

The class where I autowire
public class Mapper {

```<code>@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
@Autowired
private AppointmentFactory af;
@Autowired
private AppointmentController ac;
}
</code>```

mvc-dispatcher-servlet.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:component-scan base-package="com.mobios.ep.web.controllers" />
    <!-- <context:component-scan base-package="com.mobios.ep.services" />
    <context:component-scan base-package="com.ombios.ep.entity.factory" /> -->
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="maxUploadSize" value="1048576"/>
    </bean>
</beans>
</code>```

答:
My sugestion is to create an spring-config.xml file in both projects for own spring beans configurations (you used the name mvc-dispatcher-servlet.xml) and on web.xml to map both files for contextConfigLocation, so both projects will be in same spring context.

Also you can use a specified pattern for spring config files and to use a regex for contextConfigLocation.

web.xml fragment:

```<code>  <context-param>
    <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:view-spring-config.xml
        classpath:service-spring-config.xml
      </param-value>
  </context-param>
</code>```

or

```<code>  <context-param>
    <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:*-spring-config.xml
      </param-value>
  </context-param>
</code>```

Body:
I have two java projects as epService and epEntity (factory classes for db access). And there is another Spring project as epWeb which contains controllers and this is a Rest API.
Now, I want to autowire a class which is inside epEntity to the spring project epWeb.
I have successfully autowired classes within that epWeb project but I was unable to autowire a class from another project
Anyone have a suggestion for doing that, please let me know.
If this is an irrelevant question for stackoverflow, please delete this.

The class where I autowire
public class Mapper {

@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
@Autowired
private AppointmentFactory af;
@Autowired
private AppointmentController ac;
}

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:component-scan base-package="com.mobios.ep.web.controllers" />

    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="maxUploadSize" value="1048576"/>
    </bean>
</beans>

Body:
My sugestion is to create an spring-config.xml file in both projects for own spring beans configurations (you used the name mvc-dispatcher-servlet.xml) and on web.xml to map both files for contextConfigLocation, so both projects will be in same spring context.

Also you can use a specified pattern for spring config files and to use a regex for contextConfigLocation.

web.xml fragment:

  <context-param>
    <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:view-spring-config.xml
        classpath:service-spring-config.xml
      </param-value>
  </context-param>

or

  <context-param>
    <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:*-spring-config.xml
      </param-value>
  </context-param>


来源: stackexchange

问:
How do I compose the UriTemplate for a WCF function to set a property?
I would like to be able to set a property on an object via my CRUD interface by using a URL such as:

http://example.com/service/object?property=value

To that end I tried the following, which is invalid.

```<code>    [WebInvoke(Method = "POST", UriTemplate = "device/{deviceID}?{propName}={propValue}")]
    [OperationContract]
    void SetDeviceProperty(string DeviceID, string propName, string propValue);

    [WebInvoke(Method = "GET", UriTemplate = "device/{deviceID}?{propName}")]
    [OperationContract]
    string GetDeviceProperty(string DeviceID, string propName);
</code>```

The closest example I could find was something like

```<code>propertyName={proeprtyName},propertyValue={propertyValue}
</code>```

...but that would make for some ugly URLs.  I'd like to keep it as simple as the object path followed by ?name=value

答:
For the POST part it looks like it's unnecessary to create such UriTemplate you can just do it like this:

```<code>    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "sendTransaction")]
    SomeResponse RequestMethod(SomeRequest req);
</code>```

Where SomeResponse is a class for Response and SomeRequest is the request.

For the GET part I don't think you can make it more elegant, your choice would be to make it all POST. Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I would like to be able to set a property on an object via my CRUD interface by using a URL such as:

http://example.com/service/object?property=value

To that end I tried the following, which is invalid.

    [WebInvoke(Method = "POST", UriTemplate = "device/{deviceID}?{propName}={propValue}")]
    [OperationContract]
    void SetDeviceProperty(string DeviceID, string propName, string propValue);

    [WebInvoke(Method = "GET", UriTemplate = "device/{deviceID}?{propName}")]
    [OperationContract]
    string GetDeviceProperty(string DeviceID, string propName);

The closest example I could find was something like

propertyName={proeprtyName},propertyValue={propertyValue}

...but that would make for some ugly URLs.  I'd like to keep it as simple as the object path followed by ?name=value

Body:
For the POST part it looks like it's unnecessary to create such UriTemplate you can just do it like this:

    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "sendTransaction")]
    SomeResponse RequestMethod(SomeRequest req);

Where SomeResponse is a class for Response and SomeRequest is the request.

For the GET part I don't think you can make it more elegant, your choice would be to make it all POST. Hope this helps.


问:
Should open method in Linux device driver return a file descriptor?
I'm studying Linux Device Driver programming 3rd edition and I have some questions about the open method, here's the "scull_open" method used in that book:

```<code>int scull_open(struct inode *inode, struct file *filp){
    struct scull_dev *dev; /* device information */

    dev = container_of(inode->i_cdev, struct scull_dev, cdev);
    filp->private_data = dev; /* for other methods */
    /* now trim to 0 the length of the device if open was write-only */
    if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
            if (down_interruptible(&dev->sem))
                    return -ERESTARTSYS;
            scull_trim(dev); /* ignore errors */
            up(&dev->sem);
    }
    return 0;          /* success */
}
</code>```

And my questions are:

Shouldn't this function returns a file descriptor to the device just opened?

Isn't the "*filp" local to this function, then why we copy the contents of dev to it?

How we could use later in read and write methods?

could someone writes to my a typical "non-fatty" implementation of open method?

ssize_t scull_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos){
   struct scull_dev *dev = filp->private_data;
   ...}

答:
Shouldn't this function returns a file descriptor to the device just opened ?
In linux device driver, open() returns either 0 or negative error code. File descriptor is internally managed by kernel.

Isn't the "*filp" local to this function, then why we copy the contents of dev to it ?
filp represents opened file and a pointer to it is passed to driver by kernel. Sometimes this filp is used sometimes it is not needed by driver. Copy contents of dev is required so that when some other function let us say read() is called driver can retrieve some device specific data.

How we could use later in read and write methods ?
One of the most common way to use filp in read/write() is to acquire lock. When device is opened driver will create a lock. Now when a read/write occurs same lock will be used to prevent data buffer from corruption in case multiple process are accessing same device.

could someone writes to my a typical "non-fatty" implementation of open method ?
As you are just studying please enjoy exploring more. An implementation can be found here

Body:
I'm studying Linux Device Driver programming 3rd edition and I have some questions about the open method, here's the "scull_open" method used in that book:

int scull_open(struct inode *inode, struct file *filp){
    struct scull_dev *dev; /* device information */

    dev = container_of(inode->i_cdev, struct scull_dev, cdev);
    filp->private_data = dev; /* for other methods */
    /* now trim to 0 the length of the device if open was write-only */
    if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
            if (down_interruptible(&dev->sem))
                    return -ERESTARTSYS;
            scull_trim(dev); /* ignore errors */
            up(&dev->sem);
    }
    return 0;          /* success */
}

And my questions are:

Shouldn't this function returns a file descriptor to the device just opened?

Isn't the "*filp" local to this function, then why we copy the contents of dev to it?

How we could use later in read and write methods?

could someone writes to my a typical "non-fatty" implementation of open method?

ssize_t scull_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos){
   struct scull_dev *dev = filp->private_data;
   ...}


问:
C# : The best solution to parse the xml file?
I can write this employee object's information into the XML file. Look like this.

Employee's class

```<code>class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;
        string _text;
        public Employee(int id, string firstName, string lastName, int salary,string text)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
            this._text = text;
        }
        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
        public string Text { get { return _text; } }
    }
</code>```

Writen Xml.

```<code><Employees>
    <Employee Text="text1">
        <ID>1</ID>
        <FirstName>David</FirstName>
        <LastName>Smith</LastName>
        <Salary>10000</Salary>
    </Employee>
    <Employee Text="text2">
           <ID>3</ID>
           <FirstName>Mark</FirstName>
           <LastName>Drinkwater</LastName>
           <Salary>30000</Salary>
    </Employee>
<Employees>
</code>```

Then I want to parse xml back into Employee object, What's the best solution?

答:
Personally, I'd use LINQ to XML:

```<code>XDocument doc = XDocument.Load("employees.xml");
var employees = doc.Root.Elements("Employee")
                        .Select(e => new Employee(
                                       (int) e.Attribute("ID"),
                                       (string) e.Attribute("FirstName"),
                                       (string) e.Attribute("LastName"),
                                       (int) e.Attribute("Salary"))
                        .ToList();
</code>```

Note that this isn't currently performing any validation that the attributes exist. If you need more complicated validation and construction, you could change the query to something like:

```<code>XDocument doc = XDocument.Load("employees.xml");
var employees = doc.Root.Elements("Employee")
                        .Select(Employee.FromXElement)
                        .ToList();
</code>```

where Employee.FromXElement would be a static method which knows the details of how to create an Employee from an XElement. You might then want an instance method of ToXElement to perform the reverse operation. I've used this pattern before and had great success with it.

While you can certainly use XML serialization, I find this tends to be less flexible than "custom" serialization, in terms of the output it can produce, the input it can accept, and allowing you to cope with an evolving set of data in the type.  As Darin's shown, it also puts various requirements on the type which may not fit in with the rest of your design - such as your pleasantly-immutable current type.

On the other hand, the built-in XML serialization will cope better at things like referential integrity.

ContentLicense: CC BY-SA 2.5

Body:
I can write this employee object's information into the XML file. Look like this.

Employee's class

class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;
        string _text;
        public Employee(int id, string firstName, string lastName, int salary,string text)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
            this._text = text;
        }
        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
        public string Text { get { return _text; } }
    }

Writen Xml.

<Employees>
    <Employee Text="text1">
        <ID>1</ID>
        <FirstName>David</FirstName>
        <LastName>Smith</LastName>
        <Salary>10000</Salary>
    </Employee>
    <Employee Text="text2">
           <ID>3</ID>
           <FirstName>Mark</FirstName>
           <LastName>Drinkwater</LastName>
           <Salary>30000</Salary>
    </Employee>
<Employees>

Then I want to parse xml back into Employee object, What's the best solution?

Body:
Personally, I'd use LINQ to XML:

XDocument doc = XDocument.Load("employees.xml");
var employees = doc.Root.Elements("Employee")
                        .Select(e => new Employee(
                                       (int) e.Attribute("ID"),
                                       (string) e.Attribute("FirstName"),
                                       (string) e.Attribute("LastName"),
                                       (int) e.Attribute("Salary"))
                        .ToList();

Note that this isn't currently performing any validation that the attributes exist. If you need more complicated validation and construction, you could change the query to something like:

XDocument doc = XDocument.Load("employees.xml");
var employees = doc.Root.Elements("Employee")
                        .Select(Employee.FromXElement)
                        .ToList();

where Employee.FromXElement would be a static method which knows the details of how to create an Employee from an XElement. You might then want an instance method of ToXElement to perform the reverse operation. I've used this pattern before and had great success with it.

While you can certainly use XML serialization, I find this tends to be less flexible than "custom" serialization, in terms of the output it can produce, the input it can accept, and allowing you to cope with an evolving set of data in the type.  As Darin's shown, it also puts various requirements on the type which may not fit in with the rest of your design - such as your pleasantly-immutable current type.

On the other hand, the built-in XML serialization will cope better at things like referential integrity.


问:
Regarding sub-topics in chronicle queue

I'm looking to write messages to a single queue.  I'd like to use the sub-topics functionality, so that tailers can pick and choose either to read all of the sub-topics under one topic, or pick specific sub-topics to read from.

The documentation mentions that sub-topics are supported in a directory under the main topic, so in order to read from a subtopic, do we just create a new queue and point it to the sub-topic path?

```<code>    SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary("Topic").build();
    SingleChronicleQueue queue2 = SingleChronicleQueueBuilder.binary("Topic/SubTopic").build();

    ExcerptAppender appender = queue.acquireAppender();
    ExcerptAppender appender2 = queue2.acquireAppender();

    appender.writeText("aaa");
    appender2.writeText("bbb");
</code>```

This will just output aaa, but i want it to output but aaa and bbb

答:
There is no real concept of hierarchy in Chronicle-Queue; there is a one-to-one mapping between file-system directory and queue.

If you wish to filter certain records, you will need to do that when reading the records out of the queue. It will be up to your application to decide how to detect messages that should be filtered.

The documentation you refer to appears to have been copied from concepts that exist in Chronicle-Engine.

Title: Regarding sub-topics in chronicle queue

Body:
I'm looking to write messages to a single queue.  I'd like to use the sub-topics functionality, so that tailers can pick and choose either to read all of the sub-topics under one topic, or pick specific sub-topics to read from.

The documentation mentions that sub-topics are supported in a directory under the main topic, so in order to read from a subtopic, do we just create a new queue and point it to the sub-topic path?

    SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary("Topic").build();
    SingleChronicleQueue queue2 = SingleChronicleQueueBuilder.binary("Topic/SubTopic").build();

    ExcerptAppender appender = queue.acquireAppender();
    ExcerptAppender appender2 = queue2.acquireAppender();

    appender.writeText("aaa");
    appender2.writeText("bbb");

This will just output aaa, but i want it to output but aaa and bbb


问:
How to add tooltip on each select option with bootstrap-select
I am trying to add tooltip to each select option with bootstrap-select. While I inspecting it seems the select-js converting the select tag to ul. I have no idea this is the reason for my code is not working.

html

```<code><div class="form-group">
    <label  for="email">Network : </label>
    <select  id="basic" class="selectpicker form-control" >
        <option value="0" data-toggle="tooltip" title="Finding your IMEI number">One</option>
        <option value="1" data-toggle="tooltip" title="Next title" >Two</option>
        <option value="2" >Three</option>
        <option  value="3">Four</option>
        <option value="4">Five</option>
        <option value="5">Six</option>
    </select>
</div>
</code>```

js

```<code><script>
$(document).ready(function () {
  var mySelect = $('#first-disabled2');

  $('#special').on('click', function () {
    mySelect.find('option:selected').attr('disabled', 'disabled');
    mySelect.selectpicker('refresh');
  });

  var $basic2 = $('#basic2').selectpicker({
    liveSearch: true,
    maxOptions: 1
  });
});
</script>

<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</code>```

答:
Check this working code here please take this as reference. </p>

```<code>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
  });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="container" style="margin-top:80px;">
            <div class="row">
                <div class="col-sm-4"></div>
                <div class="col-sm-4">
                    <select name="opts" id="opts" class="form-control" multiple>
                        <option value="1" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 1">option 1</option>
                        <option value="2" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 2">option 2</option>
                        <option value="3" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 3">option 3</option>
                        <option value="4" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 4">option 4</option>
                        <option value="5" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 5">option 5</option>
                        <option value="6" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 6">option 6</option>
                    </select>
                    <div id="tooltip_container"></div>
                </div>
                <div class="col-sm-4"></div>
            </div>
</code>```

Body:
I am trying to add tooltip to each select option with bootstrap-select. While I inspecting it seems the select-js converting the select tag to ul. I have no idea this is the reason for my code is not working.

html

    Network :
    <select  id="basic" class="selectpicker form-control" >
        <option value="0" data-toggle="tooltip" title="Finding your IMEI number">One</option>
        <option value="1" data-toggle="tooltip" title="Next title" >Two</option>
        <option value="2" >Three</option>
        <option  value="3">Four</option>
        <option value="4">Five</option>
        <option value="5">Six</option>
    </select>

js

Body:
Check this working code here please take this as reference.

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
  });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="container" style="margin-top:80px;">
            <div class="row">
                <div class="col-sm-4"></div>
                <div class="col-sm-4">
                    <select name="opts" id="opts" class="form-control" multiple>
                        <option value="1" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 1">option 1</option>
                        <option value="2" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 2">option 2</option>
                        <option value="3" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 3">option 3</option>
                        <option value="4" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 4">option 4</option>
                        <option value="5" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 5">option 5</option>
                        <option value="6" data-toggle="tooltip" data-container="#tooltip_container" title="tooltip 6">option 6</option>
                    </select>
                    <div id="tooltip_container"></div>
                </div>
                <div class="col-sm-4"></div>
            </div>


问:
How to redisplay mysql records without reloading/refresing the current page using php?
So here's the scenario:

The code below display all the user accounts.

```<code><table border="3px" align="center" cellspacing="3px" cellpadding="3px">
<tr>
<td>Username</td>
<td>Password</td>
<td><a href="" onclick='return popup_link()'>Add</a></td>
</tr>
<?php
include("connection.php");
$query=mysql_query("select * from tbl_users");
while($row=mysql_fetch_array($query)){
?>
<tr>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['password']; ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</code>```

Then I have a popup page wherein it can add user account into the database table user account without reloading the page itself.

```<code><form id="form">
<h3>Add Record</h3>
<label>Username:</label>
<br/>
<input type="text" id="username" placeholder="Userusername"/>
<br/>
<br/>
<label>Password:</label>
<br/>
<input type="password" id="password" placeholder="Password"/>
<br/>
<br/>
<input type="button" id="submit" value="Submit"/>
</form>

<?php
// Establishing connection with server by passing "server_name", "user_id", "password"
$connection = mysql_connect("localhost", "root", "");
// Selecting Database by passing "database_name" and above connection variable
$db = mysql_select_db("smsi_inventory", $connection);

//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];

//Insert query
$query = mysql_query("insert into tbl_users(username, password) values ('$username2','$password2')");
if($query){
echo "Record Saved succesfully";
}

//connection closed
mysql_close($connection);
?>
</code>```

However, I'm having a hard time displaying the records of the newly added accounts without reloading/refreshing the page. Is there a way I can display the newly added accounts using php?

Your help is highly appreciated. Thank you!

答:
Try this

mysql is deprecated you have to use mysqli

A few days back I implement this code. I am sharing you the sample, you have to implement in your code This code is working for me.

You have to submit the data to the database and display that data in the table without refresh the page. right?

You have to use the ajax and in the success function, you have to use the tr: last and reset the table.

```<code><?php
ob_start();
session_start();
include('connection.php');
$sql = "SELECT * FROM test1";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<form method="post" id="register" autocomplete="off">
  <input type="text" name="fname" id="fname" placeholder="Firstname">
  <input type="text" name="lname" id="lname" placeholder="Lastname">
  <input type="email" name="email" id="email" placeholder="Email">
  <input type="submit" name="submit" value="submit" >
</form>
<table border="1" style="margin-top: 25px;" id="myTable">
<tr>
    <th>Id</th>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
  </tr>
 <?php
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
  echo "<tr>
                <td>".$row['id']."</td>
                <td>".$row['fname']."</td>
                <td>".$row['lname']."</td>
                <td>".$row['email']."</td>
            </tr>";
    }
} else {
    echo "0 results";
}
$conn->close();
 ?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

    $('#register').submit(function(e){
    e.preventDefault(); // Prevent Default Submission

            var fname = $("#fname").val();
            var lname = $("#lname").val();
            var email = $("#email").val();
            var dataString = 'fname='+ fname + '&lname='+ lname + '&email='+ email;
            $.ajax(
            {
                url:'process.php',
                type:'POST',
                data:dataString,
                success:function(data)
                {
                    $('#myTable tr:last').after('<tr><td></td><td>' +fname +'</td><td>'+lname+'</td><td>'+email+'</td></tr>');
                    $("#register")[0].reset();
                },
            });
        });
</script>
</body>
</html>
</code>```

Body:
So here's the scenario:

The code below display all the user accounts.

Username
Password
Add

<?php
include("connection.php");
$query=mysql_query("select * from tbl_users");
while($row=mysql_fetch_array($query)){
?>

<?php echo $row['username']; ?>
<?php echo $row['password']; ?>

<?php
}
?>

Then I have a popup page wherein it can add user account into the database table user account without reloading the page itself.

<form id="form">

Add Record

Username:

<input type="text" id="username" placeholder="Userusername"/>

Password:

<input type="password" id="password" placeholder="Password"/>

<input type="button" id="submit" value="Submit"/>
</form>

<?php
// Establishing connection with server by passing "server_name", "user_id", "password"
$connection = mysql_connect("localhost", "root", "");
// Selecting Database by passing "database_name" and above connection variable
$db = mysql_select_db("smsi_inventory", $connection);

//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];

//Insert query
$query = mysql_query("insert into tbl_users(username, password) values ('$username2','$password2')");
if($query){
echo "Record Saved succesfully";
}

//connection closed
mysql_close($connection);
?>

However, I'm having a hard time displaying the records of the newly added accounts without reloading/refreshing the page. Is there a way I can display the newly added accounts using php?

Your help is highly appreciated. Thank you!

Body:
Try this

mysql is deprecated you have to use mysqli

A few days back I implement this code. I am sharing you the sample, you have to implement in your code This code is working for me.

You have to submit the data to the database and display that data in the table without refresh the page. right?

You have to use the ajax and in the success function, you have to use the tr: last and reset the table.

<?php
ob_start();
session_start();
include('connection.php');
$sql = "SELECT * FROM test1";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<form method="post" id="register" autocomplete="off">
  <input type="text" name="fname" id="fname" placeholder="Firstname">
  <input type="text" name="lname" id="lname" placeholder="Lastname">
  <input type="email" name="email" id="email" placeholder="Email">
  <input type="submit" name="submit" value="submit" >
</form>
<table border="1" style="margin-top: 25px;" id="myTable">
<tr>
    <th>Id</th>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
  </tr>
 <?php
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
  echo "<tr>
                <td>".$row['id']."</td>
                <td>".$row['fname']."</td>
                <td>".$row['lname']."</td>
                <td>".$row['email']."</td>
            </tr>";
    }
} else {
    echo "0 results";
}
$conn->close();
 ?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

    $('#register').submit(function(e){
    e.preventDefault(); // Prevent Default Submission

            var fname = $("#fname").val();
            var lname = $("#lname").val();
            var email = $("#email").val();
            var dataString = 'fname='+ fname + '&lname='+ lname + '&email='+ email;
            $.ajax(
            {
                url:'process.php',
                type:'POST',
                data:dataString,
                success:function(data)
                {
                    $('#myTable tr:last').after('<tr><td></td><td>' +fname +'</td><td>'+lname+'</td><td>'+email+'</td></tr>');
                    $("#register")[0].reset();
                },
            });
        });
</script>
</body>
</html>


问:
Camera2 Api..java.lang.IllegalArgumentException: Surface had no valid native Surface
I was trying so long for Camera2 api integration to my app.Its working fine for capturing image at first.But when i snap second time the preview was not coming.I tested it in genymotion nexus 5 emulator.Tried with all examples.Preview was not coming for snapping at second time.Getting this error also.    java.lang.IllegalArgumentException: Surface had no valid native Surface...

and i followed this 2 codes
http://inducesmile.com/android/android-camera2-api-example-tutorial/?cid=519
Github-Camera2Master.Please help anyone to resolve this error and give some links for more detailed explanation about camera 2 api

```<code>package com.example.cameraapi;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AndroidCameraApi extends AppCompatActivity {
    private static final String TAG = "AndroidCameraApi";
    private Button takePictureButton;
    private TextureView textureView;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    private String cameraId;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession cameraCaptureSessions;
    protected CaptureRequest captureRequest;
    protected CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;
    private File file;
    private static final int REQUEST_CAMERA_PERMISSION = 200;
    private boolean mFlashSupported;
    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        textureView = (TextureView) findViewById(R.id.textureView);
        assert textureView != null;
        textureView.setSurfaceTextureListener(textureListener);
        takePictureButton = (Button) findViewById(R.id.btn_takepicture);
        assert takePictureButton != null;
        takePictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });
    }
    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //open your camera here
            openCamera();
        }
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            // Transform you image captured size according to the surface width and height
        }
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }
    };
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            //This is called when the camera is open
            Log.e(TAG, "onOpened");
            cameraDevice = camera;
            createCameraPreview();
        }
        @Override
        public void onDisconnected(CameraDevice camera) {
            cameraDevice.close();
        }
        @Override
        public void onError(CameraDevice camera, int error) {
            if(cameraDevice!=null)
            cameraDevice.close();
            cameraDevice = null;
        }
    };
    final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
        @Override
        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
//            Toast.makeText(AndroidCameraApi.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
            createCameraPreview();
        }
    };
    protected void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    protected void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    protected void takePicture() {
        if(null == cameraDevice) {
            Log.e(TAG, "cameraDevice is null");
            return;
        }
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
            Size[] jpegSizes = null;
            if (characteristics != null) {
                jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
            }
            int width = 640;
            int height = 480;
            if (jpegSizes != null && 0 < jpegSizes.length) {
                width = jpegSizes[0].getWidth();
                height = jpegSizes[0].getHeight();
            }
            ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
            List<Surface> outputSurfaces = new ArrayList<Surface>(2);
            outputSurfaces.add(reader.getSurface());
            outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
            final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(reader.getSurface());
            captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            // Orientation
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
            final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
            ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image = null;
                    try {
                        image = reader.acquireLatestImage();
                        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                        byte[] bytes = new byte[buffer.capacity()];
                        buffer.get(bytes);
                        save(bytes);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (image != null) {
                            image.close();
                        }
                    }
                }
                private void save(byte[] bytes) throws IOException {
                    OutputStream output = null;
                    try {
                        output = new FileOutputStream(file);
                        output.write(bytes);
                    } finally {
                        if (null != output) {
                            output.close();
                        }
                    }
                }
            };
            reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
            final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                    super.onCaptureCompleted(session, request, result);
//                    Toast.makeText(AndroidCameraApi.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
                    createCameraPreview();
                }
            };
            cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(CameraCaptureSession session) {
                    try {
                        session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onConfigureFailed(CameraCaptureSession session) {
                }
            }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    protected void createCameraPreview() {
        try {
            SurfaceTexture texture = textureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
            Surface surface = new Surface(texture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);
            cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(AndroidCameraApi.this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void openCamera() {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        Log.e(TAG, "is camera open");
        try {
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
            // Add permission for camera and let user grant the permission
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(AndroidCameraApi.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
                return;
            }
            manager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "openCamera X");
    }
    protected void updatePreview() {
        if(null == cameraDevice) {
            Log.e(TAG, "updatePreview error, return");
        }
        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        try {
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void closeCamera() {
        if (null != cameraDevice) {
            cameraDevice.close();
            cameraDevice = null;
        }
        if (null != imageReader) {
            imageReader.close();
            imageReader = null;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(AndroidCameraApi.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        startBackgroundThread();
        if (textureView.isAvailable()) {
            openCamera();
        } else {
            textureView.setSurfaceTextureListener(textureListener);
        }
    }
    @Override
    protected void onPause() {
        Log.e(TAG, "onPause");
        //closeCamera();
        stopBackgroundThread();
        super.onPause();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >
    <TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/take_picture" />
</RelativeLayout>
</code>```

I got error like below when i start to capture more images.not more after second image itself.

```<code>09-30 07:36:43.199 6252-6305/com.example.cameraapi E/Legacy-CameraDevice-JNI: LegacyCameraDevice_nativeGetSurfaceId: Could not retrieve native Surface from surface.
09-30 07:36:43.199 6252-6305/com.example.cameraapi E/AndroidRuntime: FATAL EXCEPTION: Thread-275
                                                                     Process: com.example.cameraapi, PID: 6252
                                                                     java.lang.IllegalArgumentException: Surface had no valid native Surface.
                                                                         at android.hardware.camera2.legacy.LegacyCameraDevice.nativeGetSurfaceId(Native Method)
                                                                         at android.hardware.camera2.legacy.LegacyCameraDevice.getSurfaceId(LegacyCameraDevice.java:658)
                                                                         at android.hardware.camera2.legacy.LegacyCameraDevice.containsSurfaceId(LegacyCameraDevice.java:678)
                                                                         at android.hardware.camera2.legacy.RequestThreadManager$2.onPictureTaken(RequestThreadManager.java:220)
                                                                         at android.hardware.Camera$EventHandler.handleMessage(Camera.java:1092)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.hardware.camera2.legacy.CameraDeviceUserShim$CameraLooper.run(CameraDeviceUserShim.java:136)
                                                                         at java.lang.Thread.run(Thread.java:818)
09-30 07:36:43.373 6252-6252/com.example.cameraapi E/AndroidCameraApi: onPause
09-30 07:36:43.463 6252-6292/com.example.cameraapi E/Surface: getSlotFromBufferLocked: unknown buffer: 0xe05090e0
09-30 07:36:43.475 6252-6292/com.example.cameraapi D/OpenGLRenderer: endAllStagingAnimators on 0xe8b85100 (RippleDrawable) with handle 0xdf9d43d0
09-30 07:36:47.201 6252-6313/com.example.cameraapi E/RequestThread-0: Hit timeout for jpeg callback!
09-30 07:36:47.202 6252-6313/com.example.cameraapi I/CameraDeviceState: Legacy camera service transitioning to state IDLE
09-30 07:36:47.203 6252-6252/com.example.cameraapi W/MessageQueue: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                   java.lang.IllegalStateException: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                       at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
                                                                       at android.os.Handler.enqueueMessage(Handler.java:631)
                                                                       at android.os.Handler.sendMessageAtTime(Handler.java:600)
                                                                       at android.os.Handler.sendMessageDelayed(Handler.java:570)
                                                                       at android.os.Handler.post(Handler.java:326)
                                                                       at android.hardware.camera2.dispatch.HandlerDispatcher.dispatch(HandlerDispatcher.java:61)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.dispatch.DuckTypingDispatcher.dispatch(DuckTypingDispatcher.java:53)
                                                                       at android.hardware.camera2.dispatch.ArgumentReplacingDispatcher.dispatch(ArgumentReplacingDispatcher.java:74)
                                                                       at android.hardware.camera2.dispatch.BroadcastDispatcher.dispatch(BroadcastDispatcher.java:54)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.impl.CallbackProxies$DeviceCaptureCallbackProxy.onCaptureCompleted(CallbackProxies.java:121)
                                                                       at android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks$4.run(CameraDeviceImpl.java:1828)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-30 07:36:47.204 6252-6252/com.example.cameraapi W/MessageQueue: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                   java.lang.IllegalStateException: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                       at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
                                                                       at android.os.Handler.enqueueMessage(Handler.java:631)
                                                                       at android.os.Handler.sendMessageAtTime(Handler.java:600)
                                                                       at android.os.Handler.sendMessageDelayed(Handler.java:570)
                                                                       at android.os.Handler.post(Handler.java:326)
                                                                       at android.hardware.camera2.dispatch.HandlerDispatcher.dispatch(HandlerDispatcher.java:61)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.dispatch.DuckTypingDispatcher.dispatch(DuckTypingDispatcher.java:53)
                                                                       at android.hardware.camera2.dispatch.ArgumentReplacingDispatcher.dispatch(ArgumentReplacingDispatcher.java:74)
                                                                       at android.hardware.camera2.dispatch.BroadcastDispatcher.dispatch(BroadcastDispatcher.java:54)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.impl.CallbackProxies$DeviceCaptureCallbackProxy.onCaptureSequenceCompleted(CallbackProxies.java:133)
                                                                       at android.hardware.camera2.impl.CameraDeviceImpl$10.run(CameraDeviceImpl.java:1588)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

                                                                   [ 09-30 07:36:48.448  6252: 6257 D/         ]
                                                                   HostConnection::get() New Host Connection established 0xe9952950, tid 6257
</code>```

答:
A little bit late, but i did have the same problem for the same app but after i read what @Clocker said i realised he was absolutely right. We all tend to forget, the 2nd time around when the app runs(ie when it is brought back into the foreground) onPause() does get called, after onResume(), and hence it kills the thread... So all later camera setup operations fail, especially the Surface. So just use a bit of logic to only allow onPause() to run partially.

```<code>@Override
    public void onPause() {
        if(onResume_just_ran){super.onPause(); return;}

        super.onPause();
        closeCamera();
        stopBackgroundThread();
    }
</code>```

So the boolean onResume_just_ran will be set to true in the onResume(). Now it wont run the stopBackgroundThread(). This worked fine for me!
ALSO, remember to put that boolean back to false somewhere in the program, so it runs the bottom part of the code when it really goes into onPause() while exiting, as in my program it happened somewhere else.

Body:
I was trying so long for Camera2 api integration to my app.Its working fine for capturing image at first.But when i snap second time the preview was not coming.I tested it in genymotion nexus 5 emulator.Tried with all examples.Preview was not coming for snapping at second time.Getting this error also.    java.lang.IllegalArgumentException: Surface had no valid native Surface...

and i followed this 2 codes
http://inducesmile.com/android/android-camera2-api-example-tutorial/?cid=519
Github-Camera2Master.Please help anyone to resolve this error and give some links for more detailed explanation about camera 2 api

package com.example.cameraapi;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AndroidCameraApi extends AppCompatActivity {
    private static final String TAG = "AndroidCameraApi";
    private Button takePictureButton;
    private TextureView textureView;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    private String cameraId;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession cameraCaptureSessions;
    protected CaptureRequest captureRequest;
    protected CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;
    private File file;
    private static final int REQUEST_CAMERA_PERMISSION = 200;
    private boolean mFlashSupported;
    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        textureView = (TextureView) findViewById(R.id.textureView);
        assert textureView != null;
        textureView.setSurfaceTextureListener(textureListener);
        takePictureButton = (Button) findViewById(R.id.btn_takepicture);
        assert takePictureButton != null;
        takePictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });
    }
    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //open your camera here
            openCamera();
        }
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            // Transform you image captured size according to the surface width and height
        }
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }
    };
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            //This is called when the camera is open
            Log.e(TAG, "onOpened");
            cameraDevice = camera;
            createCameraPreview();
        }
        @Override
        public void onDisconnected(CameraDevice camera) {
            cameraDevice.close();
        }
        @Override
        public void onError(CameraDevice camera, int error) {
            if(cameraDevice!=null)
            cameraDevice.close();
            cameraDevice = null;
        }
    };
    final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
        @Override
        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
//            Toast.makeText(AndroidCameraApi.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
            createCameraPreview();
        }
    };
    protected void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    protected void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    protected void takePicture() {
        if(null == cameraDevice) {
            Log.e(TAG, "cameraDevice is null");
            return;
        }
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
            Size[] jpegSizes = null;
            if (characteristics != null) {
                jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
            }
            int width = 640;
            int height = 480;
            if (jpegSizes != null && 0 < jpegSizes.length) {
                width = jpegSizes[0].getWidth();
                height = jpegSizes[0].getHeight();
            }
            ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
            List<Surface> outputSurfaces = new ArrayList<Surface>(2);
            outputSurfaces.add(reader.getSurface());
            outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
            final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(reader.getSurface());
            captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            // Orientation
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
            final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
            ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image = null;
                    try {
                        image = reader.acquireLatestImage();
                        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                        byte[] bytes = new byte[buffer.capacity()];
                        buffer.get(bytes);
                        save(bytes);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (image != null) {
                            image.close();
                        }
                    }
                }
                private void save(byte[] bytes) throws IOException {
                    OutputStream output = null;
                    try {
                        output = new FileOutputStream(file);
                        output.write(bytes);
                    } finally {
                        if (null != output) {
                            output.close();
                        }
                    }
                }
            };
            reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
            final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                    super.onCaptureCompleted(session, request, result);
//                    Toast.makeText(AndroidCameraApi.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
                    createCameraPreview();
                }
            };
            cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(CameraCaptureSession session) {
                    try {
                        session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onConfigureFailed(CameraCaptureSession session) {
                }
            }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    protected void createCameraPreview() {
        try {
            SurfaceTexture texture = textureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
            Surface surface = new Surface(texture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);
            cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(AndroidCameraApi.this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void openCamera() {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        Log.e(TAG, "is camera open");
        try {
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
            // Add permission for camera and let user grant the permission
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(AndroidCameraApi.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
                return;
            }
            manager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "openCamera X");
    }
    protected void updatePreview() {
        if(null == cameraDevice) {
            Log.e(TAG, "updatePreview error, return");
        }
        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        try {
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void closeCamera() {
        if (null != cameraDevice) {
            cameraDevice.close();
            cameraDevice = null;
        }
        if (null != imageReader) {
            imageReader.close();
            imageReader = null;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(AndroidCameraApi.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        startBackgroundThread();
        if (textureView.isAvailable()) {
            openCamera();
        } else {
            textureView.setSurfaceTextureListener(textureListener);
        }
    }
    @Override
    protected void onPause() {
        Log.e(TAG, "onPause");
        //closeCamera();
        stopBackgroundThread();
        super.onPause();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >
    <TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/take_picture" />
</RelativeLayout>

I got error like below when i start to capture more images.not more after second image itself.

09-30 07:36:43.199 6252-6305/com.example.cameraapi E/Legacy-CameraDevice-JNI: LegacyCameraDevice_nativeGetSurfaceId: Could not retrieve native Surface from surface.
09-30 07:36:43.199 6252-6305/com.example.cameraapi E/AndroidRuntime: FATAL EXCEPTION: Thread-275
                                                                     Process: com.example.cameraapi, PID: 6252
                                                                     java.lang.IllegalArgumentException: Surface had no valid native Surface.
                                                                         at android.hardware.camera2.legacy.LegacyCameraDevice.nativeGetSurfaceId(Native Method)
                                                                         at android.hardware.camera2.legacy.LegacyCameraDevice.getSurfaceId(LegacyCameraDevice.java:658)
                                                                         at android.hardware.camera2.legacy.LegacyCameraDevice.containsSurfaceId(LegacyCameraDevice.java:678)
                                                                         at android.hardware.camera2.legacy.RequestThreadManager$2.onPictureTaken(RequestThreadManager.java:220)
                                                                         at android.hardware.Camera$EventHandler.handleMessage(Camera.java:1092)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.hardware.camera2.legacy.CameraDeviceUserShim$CameraLooper.run(CameraDeviceUserShim.java:136)
                                                                         at java.lang.Thread.run(Thread.java:818)
09-30 07:36:43.373 6252-6252/com.example.cameraapi E/AndroidCameraApi: onPause
09-30 07:36:43.463 6252-6292/com.example.cameraapi E/Surface: getSlotFromBufferLocked: unknown buffer: 0xe05090e0
09-30 07:36:43.475 6252-6292/com.example.cameraapi D/OpenGLRenderer: endAllStagingAnimators on 0xe8b85100 (RippleDrawable) with handle 0xdf9d43d0
09-30 07:36:47.201 6252-6313/com.example.cameraapi E/RequestThread-0: Hit timeout for jpeg callback!
09-30 07:36:47.202 6252-6313/com.example.cameraapi I/CameraDeviceState: Legacy camera service transitioning to state IDLE
09-30 07:36:47.203 6252-6252/com.example.cameraapi W/MessageQueue: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                   java.lang.IllegalStateException: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                       at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
                                                                       at android.os.Handler.enqueueMessage(Handler.java:631)
                                                                       at android.os.Handler.sendMessageAtTime(Handler.java:600)
                                                                       at android.os.Handler.sendMessageDelayed(Handler.java:570)
                                                                       at android.os.Handler.post(Handler.java:326)
                                                                       at android.hardware.camera2.dispatch.HandlerDispatcher.dispatch(HandlerDispatcher.java:61)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.dispatch.DuckTypingDispatcher.dispatch(DuckTypingDispatcher.java:53)
                                                                       at android.hardware.camera2.dispatch.ArgumentReplacingDispatcher.dispatch(ArgumentReplacingDispatcher.java:74)
                                                                       at android.hardware.camera2.dispatch.BroadcastDispatcher.dispatch(BroadcastDispatcher.java:54)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.impl.CallbackProxies$DeviceCaptureCallbackProxy.onCaptureCompleted(CallbackProxies.java:121)
                                                                       at android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks$4.run(CameraDeviceImpl.java:1828)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-30 07:36:47.204 6252-6252/com.example.cameraapi W/MessageQueue: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                   java.lang.IllegalStateException: Handler (android.os.Handler) {ef17f10} sending message to a Handler on a dead thread
                                                                       at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
                                                                       at android.os.Handler.enqueueMessage(Handler.java:631)
                                                                       at android.os.Handler.sendMessageAtTime(Handler.java:600)
                                                                       at android.os.Handler.sendMessageDelayed(Handler.java:570)
                                                                       at android.os.Handler.post(Handler.java:326)
                                                                       at android.hardware.camera2.dispatch.HandlerDispatcher.dispatch(HandlerDispatcher.java:61)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.dispatch.DuckTypingDispatcher.dispatch(DuckTypingDispatcher.java:53)
                                                                       at android.hardware.camera2.dispatch.ArgumentReplacingDispatcher.dispatch(ArgumentReplacingDispatcher.java:74)
                                                                       at android.hardware.camera2.dispatch.BroadcastDispatcher.dispatch(BroadcastDispatcher.java:54)
                                                                       at android.hardware.camera2.dispatch.MethodNameInvoker.invoke(MethodNameInvoker.java:88)
                                                                       at android.hardware.camera2.impl.CallbackProxies$DeviceCaptureCallbackProxy.onCaptureSequenceCompleted(CallbackProxies.java:133)
                                                                       at android.hardware.camera2.impl.CameraDeviceImpl$10.run(CameraDeviceImpl.java:1588)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

                                                                   [ 09-30 07:36:48.448  6252: 6257 D/         ]
                                                                   HostConnection::get() New Host Connection established 0xe9952950, tid 6257

Body:
A little bit late, but i did have the same problem for the same app but after i read what @Clocker said i realised he was absolutely right. We all tend to forget, the 2nd time around when the app runs(ie when it is brought back into the foreground) onPause() does get called, after onResume(), and hence it kills the thread... So all later camera setup operations fail, especially the Surface. So just use a bit of logic to only allow onPause() to run partially.

@Override
    public void onPause() {
        if(onResume_just_ran){super.onPause(); return;}

        super.onPause();
        closeCamera();
        stopBackgroundThread();
    }

So the boolean onResume_just_ran will be set to true in the onResume(). Now it wont run the stopBackgroundThread(). This worked fine for me!
ALSO, remember to put that boolean back to false somewhere in the program, so it runs the bottom part of the code when it really goes into onPause() while exiting, as in my program it happened somewhere else.


问:
Removing character strings in date in R
$ date "20141013T000000", "20141209T000000", "20150225T000000", "20141209T000000"

I have this "date" variable in R dataframe. I want to clean this variable and remove "T000000" such that "20141013T000000" shows only "20141013" so I can then convert my date variable into it's proper date format.

Thank you very much.

答:
You don't need to remove that, you can just do the date-conversion directly and specify the existing format:</p>

```<code>as.Date("20141013T000000", "%Y%m%dT000000")
# [1] "2014-10-13"
</code>```

Title: Removing character strings in date in R

Body:
You don't need to remove that, you can just do the date-conversion directly and specify the existing format:

as.Date("20141013T000000", "%Y%m%dT000000")
# [1] "2014-10-13"


问:
Zend Studio 7.2.1 does not automatically create @return in PHPDoc block
I recently upgraded from Zend Studio for Eclipse 6.1.2 to 7.2.1.

Directly above a PHP method which contains a return, when I type /** and hit ENTER as to let Zend Studio automatically generate the PHPDoc block, Zend Studio 7.2.1 creates the PHPDoc block successfully however it does not put an @return in the block. Zend Studio 6.2.1 did this perfectly.

I spent a lot of time playing around the with (extensive) preferences in Zend Studio 7.2.1 to no avail. Any ideas? Thanks!

答:
This is a known bug in PDT. It is fixed in PDT SVN. The resolution of the bug is, typing "/** ENTER" right before a function statement doesn't trigger the correct code template.

Until you upgrade to the latest PDT (or perhaps until ZS9 is released) you can use "Source -> Generate Element Comment" menu or "SHIFT + CTRL + J" shortcut, it'll do the trick.

Same bug and workaround applies for Zend Studio 8 branch.

PDT Bug Report: https://bugs.eclipse.org/bugs/show_bug.cgi?id=322321

Zend Studio Discussion: http://forums.zend.com/viewtopic.php?f=79&p=25271


问:
How to pass compile time parameter for Yocto project?
I am new to Yocto build environment. I have a C code which has some code as below:

```<code>#include <stdio.h>
int main ()
{
    printf("HELLO WORLD\n");

#ifdef MYDEF
    printf("MYDEF is defined\n");
#endif

    return 0;
}
</code>```

I want to pass a flag/parameter MYDEF in local.conf file. I tried following defines but they didn't work. Any thoughts on what am I doing wrong and what possibly can fix it?

```<code>MYDEF = 'y'
MYDEF ?= 'y'
MYDEF ??= 'y'
CFLAGS = "-DMYDEF"
TARGET_CFLAGS = "-DMYDEF"
BUILD_CFLAGS = "-DMYDEF"
</code>```

Thanks.

答:
I was able to create a example recipe with compiling Your sample code:

```<code>LICENSE = "CLOSED"

SRC_URI = "file://hello_test.cpp"
S = "${WORKDIR}"

inherit native

MYDEF = "y"

do_compile (){
  ${CC} -DMYDEF -o hello_test ${S}/hello_test.cpp
}

do_install () {
    install -d ${D}${bindir}
    install ${B}/hello_test ${D}/${bindir}
}
</code>```

And the proof of execution hello_test binary:

```<code>$ ./hello_test
HELLO WORLD
MYDEF is defined
</code>```

Body:
I am new to Yocto build environment. I have a C code which has some code as below:

#include <stdio.h>
int main ()
{
    printf("HELLO WORLD\n");

#ifdef MYDEF
    printf("MYDEF is defined\n");
#endif

    return 0;
}

I want to pass a flag/parameter MYDEF in local.conf file. I tried following defines but they didn't work. Any thoughts on what am I doing wrong and what possibly can fix it?

MYDEF = 'y'
MYDEF ?= 'y'
MYDEF ??= 'y'
CFLAGS = "-DMYDEF"
TARGET_CFLAGS = "-DMYDEF"
BUILD_CFLAGS = "-DMYDEF"

Thanks.

Body:
I was able to create a example recipe with compiling Your sample code:

LICENSE = "CLOSED"

SRC_URI = "file://hello_test.cpp"
S = "${WORKDIR}"

inherit native

MYDEF = "y"

do_compile (){
  ${CC} -DMYDEF -o hello_test ${S}/hello_test.cpp
}

do_install () {
    install -d ${D}${bindir}
    install ${B}/hello_test ${D}/${bindir}
}

And the proof of execution hello_test binary:

$ ./hello_test
HELLO WORLD
MYDEF is defined


问:
Index(match()) or lookup to return first non null / empty value
I'm using an index(match()) function to return a value based on the name of a column header. However, I've recently learned that a column header can appear 4 times in my data. However, there would only ever be one populated, the others would always be empty.

Whilst I could do a nested if =(isblank(...)# do stuff) I wondered if there was a more sophisticated way to tell GSheets to return the first non null / empty value, kind of like the SQL coalesque() function.

Is there?

Current formula looks like this:

```<code>=index('Form Responses 1'!$A$2:$DY,match($A2,'Form Responses 1'!$A$2:$A,0),match(I$1,'Form Responses 1'!$A$1:$DY$1,0))
</code>```

However, this piece is the problem piece:

```<code>match(I$1,'Form Responses 1'!$A$1:$DY$1,0)
</code>```

This is because I$1 appears 4 times in range Form Responses 1'!$A$1:$DY$1. The one that I want is the one that does not return a empty cell when nested in index() function.

答:
I've made a more simple case when all the data is on single sheet.

The formula is:

=QUERY(TRANSPOSE({A1:E1;FILTER(A2:E8,A2:A8 = 2)}),
"select Col2 where Col2 is not null and Col1 = 'foo' limit 1")

number 2 is criteria by row ($A2 in your sample)

text foo is criteria by column ( replace it with " & I$1 & " )

How it works

{A1:E1; filter } is to get headers and desired row in one array

TRANSPOSE is to use query

where Col2 is not null is to get rid of empty cells

limit 1 is like select first 1

Body:
I'm using an index(match()) function to return a value based on the name of a column header. However, I've recently learned that a column header can appear 4 times in my data. However, there would only ever be one populated, the others would always be empty.

Whilst I could do a nested if =(isblank(...)# do stuff) I wondered if there was a more sophisticated way to tell GSheets to return the first non null / empty value, kind of like the SQL coalesque() function.

Is there?

Current formula looks like this:

=index('Form Responses 1'!$A$2:$DY,match($A2,'Form Responses 1'!$A$2:$A,0),match(I$1,'Form Responses 1'!$A$1:$DY$1,0))

However, this piece is the problem piece:

match(I$1,'Form Responses 1'!$A$1:$DY$1,0)

This is because I$1 appears 4 times in range Form Responses 1'!$A$1:$DY$1. The one that I want is the one that does not return a empty cell when nested in index() function.


问:
Giving PopupMenu a shadow in API 21+
This has been posted many times, but none of the existing solution appears to work with API 21+. The default popup's background color is exactly the same as the default background color for the layouts.

This is what it looks like (The popup is over a gridview but it has no obvious 'boundary' which looks a little off)

Something like this is ideal,i.e, with a proper material design shadow. There's a solution for accomplishing this with the toolbar popup menu. Not with a 'normal' PopupMenu.

This old question is trying to accomplish the same, however the given solution now no longer works:

```<code><style name="AppTheme" parent="android:Theme.Holo.Light">
<item name="android:popupMenuStyle">@style/popupMenuStyle</item>
</style>
<style name="popupMenuStyle" parent="@android:style/Widget.PopupMenu">
<item name="android:popupBackground">@color/bgPopumMenu</item>
</style>
</code>```

And neither does setting a custom context wrapper:

```<code> Context wrapper = new ContextThemeWrapper(getContext(), R.style.PopupMenu);
 PopupMenu popup = new PopupMenu(wrapper, anchorView);
</code>```

So, I'm unable to even change the background color of the popupmenu, let alone have a proper material design shadow.

How to give PopupMenu a shadow? Or how do I at least use a custom background drawable (using which I could put in a 9 patch shadow)

答:
You need a separate style for Lollipop+.

Create another resource: res/values-v21/styles.xml.

Add there Your popup style and specify needed elevation:

```<code><style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">@android:color/white</item>
    <item name="android:popupElevation">20dp</item>
</style>
</code>```

That's it.

Title: Giving PopupMenu a shadow in API 21+

Body:
This has been posted many times, but none of the existing solution appears to work with API 21+. The default popup's background color is exactly the same as the default background color for the layouts.

This is what it looks like (The popup is over a gridview but it has no obvious 'boundary' which looks a little off)

Something like this is ideal,i.e, with a proper material design shadow. There's a solution for accomplishing this with the toolbar popup menu. Not with a 'normal' PopupMenu.

This old question is trying to accomplish the same, however the given solution now no longer works:

And neither does setting a custom context wrapper:

 Context wrapper = new ContextThemeWrapper(getContext(), R.style.PopupMenu);
 PopupMenu popup = new PopupMenu(wrapper, anchorView);

So, I'm unable to even change the background color of the popupmenu, let alone have a proper material design shadow.

How to give PopupMenu a shadow? Or how do I at least use a custom background drawable (using which I could put in a 9 patch shadow)

Body:
You need a separate style for Lollipop+.

Create another resource: res/values-v21/styles.xml.

Add there Your popup style and specify needed elevation:

<style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">@android:color/white</item>
    <item name="android:popupElevation">20dp</item>
</style>

That's it.


问:
My page scrolls horizontally on mobile
I just found out that my website is scrolling horizontally on mobile. However, I am not able to find out why this is happening.

The containers and body seem to have the correct width when I check it in my browser.

Any idea?

https://www.urban-zweirad.de

Cheers,
Mark

答:
it seems line number 204 from _pages.scss is creating issue

```<code>.teaser {
    padding: 0!important;
}
</code>```

try removing this.

Title: My page scrolls horizontally on mobile

Body:
it seems line number 204 from _pages.scss is creating issue

.teaser {
    padding: 0!important;
}

try removing this.