问:
delete all files in a folder with php

Possible Duplicate:

  how to delete a folder with contents using PHP

hi,

is it possible to delete all children within a parent directory and then delete the the parent directory in php?

Edited:

When i use scan dir why does the first 2 elements of the array show '.', '..'?:

```<code>> Array ( [0] => . [1] => .. [2] => evga-nvidia-graphics-card4d0fe6868d2f8.jpg [3] => image4d0eaafb920a0.png [4] => image4d0eab086a106.png )
</code>```

many thanks

答:
The first elements in your array (. and  ..) are references to the directory itself (.) and to its parent directory (..). Every non-root directory in your filesystem will have both of them. They are usually ignored by hand in this kind of scripts.

If you use a DirectoryIterator you can tell if the current element you're iterating over is either . or .. with the isDot() function.

Title: delete all files in a folder with php

Body:
Possible Duplicate:

  how to delete a folder with contents using PHP

hi,

is it possible to delete all children within a parent directory and then delete the the parent directory in php?

Edited:

When i use scan dir why does the first 2 elements of the array show '.', '..'?:

> Array ( [0] => . [1] => .. [2] => evga-nvidia-graphics-card4d0fe6868d2f8.jpg [3] => image4d0eaafb920a0.png [4] => image4d0eab086a106.png )

many thanks


来源: stackexchange

问:
public MWNumericArray(int rows, int columns, double[] realData) - How should I format my Double[]?
I wish to create a MWNumericArray with 6 columns and 3000 rows. Each column should contain the measured values of a signal - meaning I have 6 signals with 3000 values each.

My question is: Should my double[] realData be the first values of the six signals, the second values of the six signals, and so on until value no. 3000?

An example using numbers for clarification:

Lets say signal one always have the value 1, signal two always have the value 2 and so on.
Should realData then be 123456123456123456 and so on, with a total length of 3000*6?

Thank you very much!

答: According to Here, your interpretation is correct, it will have 3000*6 elements with each element corresponding to a position in the row.</p>

ContentLicense: CC BY-SA 3.0


问:
SSL proxy for two applications on same domain (one application without context path)
I have 2 applications running on separate tomcat on the same server machine

application 1 : www.example.com

application 2 : www.example.com/app

I have made the configuration and SSL works for application 1 but not for application 2.

When I try to go to https:www.example.com/app , i get a page not found exception

httpd.conf

```<code>ServerName example.com

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

SSLEngine               On

SSLCertificateFile      /etc/ssl/certs/mydomain_com_with_chain.crt
SSLCertificateKeyFile   /etc/ssl/private/mydomain_com.key

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app
</code>```

The server.xml configuration is correct with the connector having proxy parameters

```<code> <Connector port="8081"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               acceptCount="100"
               disableUploadTimeout="true"
               scheme="https"
               proxyName="example.com"
               proxyPort="443"
               secure="true"/>
</code>```

Can someone please point out the problem here . I suspect it is because application 1 does not have a context path. However, I cannot have a context path for my application 1.
Any suggestions highly appreciated.

答:
I believe the problem is in your proxypass

You have

```<code>ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app
</code>```

Should be

```<code>ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       https://www.example.com/

ProxyPass               /app       http://myserver:8081/app
ProxyPassReverse        /app       https://www.example.com/app
</code>```

Unless you have a port offset, there is no reason to call port 8082

Apache ProxyPass Doc

Body:
I have 2 applications running on separate tomcat on the same server machine

application 1 : www.example.com

application 2 : www.example.com/app

I have made the configuration and SSL works for application 1 but not for application 2.

When I try to go to https:www.example.com/app , i get a page not found exception

httpd.conf

ServerName example.com

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

SSLEngine               On

SSLCertificateFile      /etc/ssl/certs/mydomain_com_with_chain.crt
SSLCertificateKeyFile   /etc/ssl/private/mydomain_com.key

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app

The server.xml configuration is correct with the connector having proxy parameters

 <Connector port="8081"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               acceptCount="100"
               disableUploadTimeout="true"
               scheme="https"
               proxyName="example.com"
               proxyPort="443"
               secure="true"/>

Can someone please point out the problem here . I suspect it is because application 1 does not have a context path. However, I cannot have a context path for my application 1.
Any suggestions highly appreciated.

Body:
I believe the problem is in your proxypass

You have

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app

Should be

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       https://www.example.com/

ProxyPass               /app       http://myserver:8081/app
ProxyPassReverse        /app       https://www.example.com/app

Unless you have a port offset, there is no reason to call port 8082

Apache ProxyPass Doc


问:
google plus shared url not rendering
I am sharing URL to google plus using PlusShare.Builder but its not rendering.

Its render successfully when i simply copy paste URL in google plus, but in android side its not working.

this is my URL

Plz guide me with my code.. is there anything missing in my code.

```<code>private void shareToGooglePlus(String urlToShare){
        PlusShare.Builder builder = new PlusShare.Builder(getActivity());

        // Set call-to-action metadata.
        builder.addCallToAction(
                "CREATE_ITEM", /** call-to-action button label */
                Uri.parse("http://plus.google.com/pages/create"), /** call-to-action url (for desktop use) */
                "/pages/create" /** call to action deep-link ID (for mobile use), 512 characters or fewer */);

        // Set the content url (for desktop use).
        builder.setContentUrl(Uri.parse("https://plus.google.com/share?url="+ urlToShare));
        // Set the share text.
        builder.addStream(Uri.parse(urlToShare));
        builder.setText(urlToShare);

        startActivityForResult(builder.getIntent(), 0);
    }
</code>```

答:
Have you tried

```<code>Intent shareIntent = new PlusShare.Builder(this)
        .setText("CREATE_ITEM")
        .setType("text/plain")
        .setContentUrl(Uri.parse("https://plus.google.com/share?url="+ urlToShare)
        .setContentDeepLinkId(Uri.parse("/pages/create"))
        .getIntent();

startActivityForResult(shareIntent, 0);
</code>```

Check the source just in case you don't have something configured correctly: https://developers.google.com/+/mobile/android/share/deep-link

And IDK if addCallToAction can still be of use because according to the docs https://developers.google.com/android/reference/com/google/android/gms/plus/PlusShare.Builder#addCallToAction(java.lang.String,%20android.net.Uri,%20java.lang.String) it requires a signed-in PlusClient in the builder, but it is not available anymore in the updated play services: https://stackoverflow.com/a/31654018/6248510

Hope it helps

Title: google plus shared url not rendering

Body:
I am sharing URL to google plus using PlusShare.Builder but its not rendering.

Its render successfully when i simply copy paste URL in google plus, but in android side its not working.

this is my URL

Plz guide me with my code.. is there anything missing in my code.

private void shareToGooglePlus(String urlToShare){
        PlusShare.Builder builder = new PlusShare.Builder(getActivity());

        // Set call-to-action metadata.
        builder.addCallToAction(
                "CREATE_ITEM", /** call-to-action button label */
                Uri.parse("http://plus.google.com/pages/create"), /** call-to-action url (for desktop use) */
                "/pages/create" /** call to action deep-link ID (for mobile use), 512 characters or fewer */);

        // Set the content url (for desktop use).
        builder.setContentUrl(Uri.parse("https://plus.google.com/share?url="+ urlToShare));
        // Set the share text.
        builder.addStream(Uri.parse(urlToShare));
        builder.setText(urlToShare);

        startActivityForResult(builder.getIntent(), 0);
    }

Body:
Have you tried

Intent shareIntent = new PlusShare.Builder(this)
        .setText("CREATE_ITEM")
        .setType("text/plain")
        .setContentUrl(Uri.parse("https://plus.google.com/share?url="+ urlToShare)
        .setContentDeepLinkId(Uri.parse("/pages/create"))
        .getIntent();

startActivityForResult(shareIntent, 0);

Check the source just in case you don't have something configured correctly: https://developers.google.com/+/mobile/android/share/deep-link

And IDK if addCallToAction can still be of use because according to the docs https://developers.google.com/android/reference/com/google/android/gms/plus/PlusShare.Builder#addCallToAction(java.lang.String,%20android.net.Uri,%20java.lang.String) it requires a signed-in PlusClient in the builder, but it is not available anymore in the updated play services: https://stackoverflow.com/a/31654018/6248510

Hope it helps


问:
How to get the percentage of apt get output through regex?
Can someone please help me with a regular expression to get the percentage from the below bash output through regex?

```<code>Get:11 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libvlc$

Get:12 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-freefont-ttf$

40% [12 fonts-freefont-ttf 855 kB/4,140 kB 21%]
</code>```

I just need to get the 40% from the above example..

Thanks.

答:
Using grep and -p :

```<code>grep -oP '^\d+%\s'
</code>```

Body:
Can someone please help me with a regular expression to get the percentage from the below bash output through regex?

Get:11 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libvlc$

Get:12 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-freefont-ttf$

40% [12 fonts-freefont-ttf 855 kB/4,140 kB 21%]

I just need to get the 40% from the above example..

Thanks.

Body:
Using grep and -p :

grep -oP '^\d+%\s'


问:
AngularFire push function
I am using angularfire as below:

```<code> this.afDB.list('/items/' + this.itemID).push({displayName: item.name});
</code>```

The structure then looks like this where the itemID is qoieke

```<code>items:
    - qoieke:
            - Leow9dnfwoierjhwelo
                                - displayName: "Something"
</code>```

What I don't understand is how do I avoid getting the "Leow9dnfwoierjhwelo" as automatically generated id?

So, I want to have structure like below:

```<code>items:
    - qoieke:
           - displayName: "Something"
</code>```

Thanks!

答:
Calling push generates a so-called push ID. To not generate that, don't call push. Instead call set() (to replace the current values at the location with whatever you pass in) or update() (to only modify the properties you pass in).

In your case an update() seems to do what you want:

```<code>this.afDB.list('/items/' + this.itemID).update({displayName: item.name});
</code>```

Title: AngularFire push function

Body:
I am using angularfire as below:

 this.afDB.list('/items/' + this.itemID).push({displayName: item.name});

The structure then looks like this where the itemID is qoieke

items:
    - qoieke:
            - Leow9dnfwoierjhwelo
                                - displayName: "Something"

What I don't understand is how do I avoid getting the "Leow9dnfwoierjhwelo" as automatically generated id?

So, I want to have structure like below:

items:
    - qoieke:
           - displayName: "Something"

Thanks!

Body:
Calling push generates a so-called push ID. To not generate that, don't call push. Instead call set() (to replace the current values at the location with whatever you pass in) or update() (to only modify the properties you pass in).

In your case an update() seems to do what you want:

this.afDB.list('/items/' + this.itemID).update({displayName: item.name});


问:
How do I modify my simple Python code, to take into account HTTP headers?
```<code>def URLRequest(url, params, method="POST"):
    r  = urllib2.urlopen(url, data=urllib.urlencode(params))
    return r
</code>```

In this method, I send a POST request to a certain URL.  What if I want to do headers as well? I want to send a dictionary of additional headers (in addition to standard headers).

答:
```<code>def URLPost(url, params, method="POST", headers = {}):
    req = urllib2.Request(url)
    for k, v in headers.items():
        req.add_header(k, v)
    r  = urllib2.urlopen(req, data=urllib.urlencode(params))
    return r
</code>```

ContentLicense: CC BY-SA 2.5

Body:
def URLRequest(url, params, method="POST"):
    r  = urllib2.urlopen(url, data=urllib.urlencode(params))
    return r

In this method, I send a POST request to a certain URL.  What if I want to do headers as well? I want to send a dictionary of additional headers (in addition to standard headers).


问:
Shape issue with keras `fit_generator()`
I am having a seemingly simple issue with the shape of the numpy arrays returned from a custom generator function I am using within keras's fit_generator function.

The generator function is similar to this:

```<code>def data_generator(full_data, encoder):
    for s in full_data:
        in1_X = encoder.encode(s[:,0])
        in2_X = encoder.encode(s[:,1])
        out1_y = encoder.encode(s[:,2])
        out2_y = encoder.encode(s[:,3])
        X = [in1_X, in2_X]
        y = [out1_y, out2_y]
        yield (X,y)
</code>```

I can get the shape returned from in1_X by using a for loop and printing the shape, which simply returns (60,)

However, when calling this using the fit_generator() function, it fails:

```<code>train_data_gen = data_generator(full_data, encoder)

main_in = Input(shape=(seq_len,), name='main_input')

# ...
# define model
# ...

joint_model.fit_generator(train_data_gen, steps_per_epoch=2000, epochs=2)
</code>```

from which the output is this:

```<code>Error when checking input:
expected main_input to have shape (None, 60) but got array with shape (60, 1)
</code>```

How can I get this to not change the numpy array from shape (60,) to shape (60, 1)?  Has anyone else had this issue?

答:
We found a response to this issue. Please check the explanation and comments at the following PR: https://github.com/fchollet/keras/issues/4641
Providing a 2D array solved the issue for us.</p>

Body:
I am having a seemingly simple issue with the shape of the numpy arrays returned from a custom generator function I am using within keras's fit_generator function.

The generator function is similar to this:

def data_generator(full_data, encoder):
    for s in full_data:
        in1_X = encoder.encode(s[:,0])
        in2_X = encoder.encode(s[:,1])
        out1_y = encoder.encode(s[:,2])
        out2_y = encoder.encode(s[:,3])
        X = [in1_X, in2_X]
        y = [out1_y, out2_y]
        yield (X,y)

I can get the shape returned from in1_X by using a for loop and printing the shape, which simply returns (60,)

However, when calling this using the fit_generator() function, it fails:

train_data_gen = data_generator(full_data, encoder)

main_in = Input(shape=(seq_len,), name='main_input')

# ...
# define model
# ...

joint_model.fit_generator(train_data_gen, steps_per_epoch=2000, epochs=2)

from which the output is this:

Error when checking input:
expected main_input to have shape (None, 60) but got array with shape (60, 1)

How can I get this to not change the numpy array from shape (60,) to shape (60, 1)?  Has anyone else had this issue?


问:
Spring Boot JPA repositories custom query
http://spring.io/guides/gs/accessing-data-jpa/

Referred the above link to define a custom query.

We have a developed a Spring boot web service CRUD application but we are facing the following exception when we add a custom query.

```<code> org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeController': Unsatisfied dependency expressed through field 'EmployeeService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:naat org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
</code>```

This was the repository interface that I have defined. Defined a custom query.

```<code>package com.example.rest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.rest.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findByName(String employeeName);}
</code>```

This is my service interface

```<code>package com.example.rest.service;
import java.util.List;
import com.example.rest.model.Employee;
public interface EmployeeService {

Employee save(Employee employee);
Employee getById(Long employeeId);
void delete(Long employeeId);
List<Employee> findAll();
Employee findByName(String employeeName); }
</code>```

This is my Service Implementation class

```<code>package com.example.rest.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.rest.model.Employee;
import com.example.rest.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
EmployeeRepository employeeRepository;

@Override
public Employee save(Employee employee) {
    // TODO Auto-generated method stub
    return employeeRepository.save(employee);
}

@Override
public Employee getById(Long employeeId) {
    // TODO Auto-generated method stub
    return employeeRepository.getOne(employeeId);
}

@Override
public void delete(Long employeeId) {
    // TODO Auto-generated method stub
    employeeRepository.delete(employeeId);
}

@Override
public List<Employee> findAll() {
    // TODO Auto-generated method stub
    return employeeRepository.findAll();
}

@Override
public Employee findByName(String employeeName) {
    // TODO Auto-generated method stub
    return employeeRepository.findByName(employeeName);
}}
</code>```

Without custom query my application works fine.
Let me know where I have made a mistake.

I have added the model class

```<code>package com.example.rest.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="testF")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable=false, unique=true)
private Long employeeId;

@Column(nullable=false, unique=true)
private String employeeName;

@Column(nullable=false)
private String emailId;

@Column(nullable=false)
private Long salary;

public Employee() {
}

public Employee(Long employeeId, String employeeName, String emailId, Long salary) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.emailId = emailId;
this.salary = salary;
}

public Long getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public Long getSalary() {
return salary;
}

public void setSalary(Long salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", emailId=" + emailId
+ ", salary=" + salary + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employeeId == null) ? 0 : employeeId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (employeeId == null) {
if (other.employeeId != null)
return false;
} else if (!employeeId.equals(other.employeeId))
return false;
return true;
}}
</code>```

答:
Your model doesn't have name property, you have employeeName, so your query should look like this:

```<code>Employee findByEmployeeName(String employeeName);
</code>```

Please see reference for more info on how to build Spring Data queries. In short, when you want to create a query you have to specify full field name how it is written in your Entity.

Body:
http://spring.io/guides/gs/accessing-data-jpa/

Referred the above link to define a custom query.

We have a developed a Spring boot web service CRUD application but we are facing the following exception when we add a custom query.

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeController': Unsatisfied dependency expressed through field 'EmployeeService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:naat org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]

This was the repository interface that I have defined. Defined a custom query.

package com.example.rest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.rest.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findByName(String employeeName);}

This is my service interface

package com.example.rest.service;
import java.util.List;
import com.example.rest.model.Employee;
public interface EmployeeService {

Employee save(Employee employee);
Employee getById(Long employeeId);
void delete(Long employeeId);
List<Employee> findAll();
Employee findByName(String employeeName); }

This is my Service Implementation class

package com.example.rest.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.rest.model.Employee;
import com.example.rest.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
EmployeeRepository employeeRepository;

@Override
public Employee save(Employee employee) {
    // TODO Auto-generated method stub
    return employeeRepository.save(employee);
}

@Override
public Employee getById(Long employeeId) {
    // TODO Auto-generated method stub
    return employeeRepository.getOne(employeeId);
}

@Override
public void delete(Long employeeId) {
    // TODO Auto-generated method stub
    employeeRepository.delete(employeeId);
}

@Override
public List<Employee> findAll() {
    // TODO Auto-generated method stub
    return employeeRepository.findAll();
}

@Override
public Employee findByName(String employeeName) {
    // TODO Auto-generated method stub
    return employeeRepository.findByName(employeeName);
}}

Without custom query my application works fine.
Let me know where I have made a mistake.

I have added the model class

package com.example.rest.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="testF")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable=false, unique=true)
private Long employeeId;

@Column(nullable=false, unique=true)
private String employeeName;

@Column(nullable=false)
private String emailId;

@Column(nullable=false)
private Long salary;

public Employee() {
}

public Employee(Long employeeId, String employeeName, String emailId, Long salary) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.emailId = emailId;
this.salary = salary;
}

public Long getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public Long getSalary() {
return salary;
}

public void setSalary(Long salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", emailId=" + emailId
+ ", salary=" + salary + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employeeId == null) ? 0 : employeeId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (employeeId == null) {
if (other.employeeId != null)
return false;
} else if (!employeeId.equals(other.employeeId))
return false;
return true;
}}

Body:
Your model doesn't have name property, you have employeeName, so your query should look like this:

Employee findByEmployeeName(String employeeName);

Please see reference for more info on how to build Spring Data queries. In short, when you want to create a query you have to specify full field name how it is written in your Entity.


问:
How do you merge two different SQL Server 2012 database tables in single stored procedure?
```<code>MERGE [160.80.3.220].[sample].[dbo].[Products] AS TARGET
USING UpdatedProducts AS SOURCE ON (TARGET.ProductID = SOURCE.ProductID)

-- When records are matched, update
-- the records if there is any change
WHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName
              OR TARGET.Rate <> SOURCE.Rate THEN
    UPDATE
        SET TARGET.ProductName = SOURCE.ProductName,
            TARGET.Rate = SOURCE.Rate

-- When no records are matched, insert
-- the incoming records from source
-- table to target table
WHEN NOT MATCHED BY TARGET THEN
    INSERT (ProductID, ProductName, Rate)
    VALUES (SOURCE.ProductID, SOURCE.ProductName, SOURCE.Rate)

-- When there is a row that exists in target table and
-- same record does not exist in source table
-- then delete this record from target table
WHEN NOT MATCHED BY SOURCE THEN
    DELETE

-- $action specifies a column of type nvarchar(10)
-- in the OUTPUT clause that returns one of three
-- values for each row: 'INSERT', 'UPDATE', or 'DELETE',
-- according to the action that was performed on that row
OUTPUT $action,
       DELETED.ProductID AS TargetProductID,
       DELETED.ProductName AS TargetProductName,
       DELETED.Rate AS TargetRate,
       INSERTED.ProductID AS SourceProductID,
       INSERTED.ProductName AS SourceProductName,
       INSERTED.Rate AS SourceRate;

SELECT @@ROWCOUNT;
GO
</code>```

答:
Since:

target_table cannot be a remote table. target_table cannot have any
  rules defined on it.

What you could do is first insert all the data from your linked server to your current server database table using four-part query, then do Merge.

OR:

using source table as remote table because remote table is supported in USING. So what you could do alternatively is:

first Change connection to [160.80.3.220].[sample]

then:

```<code>MERGE [dbo].[Products] AS TARGET

USING [linked server instance].[database].[schema].UpdatedProducts AS SOURCE
</code>```

Body:
Since:

target_table cannot be a remote table. target_table cannot have any
  rules defined on it.

What you could do is first insert all the data from your linked server to your current server database table using four-part query, then do Merge.

OR:

using source table as remote table because remote table is supported in USING. So what you could do alternatively is:

first Change connection to [160.80.3.220].[sample]

then:

MERGE [dbo].[Products] AS TARGET

USING [linked server instance].[database].[schema].UpdatedProducts AS SOURCE


问:
matlab rgb values dilemma
When i wrote these commands

```<code>out = ones(size(ben))
imshow(out)
</code>```

the output is a white picture but i expect almost dark picture because the rgb values are 1,1,1. when i give 255,255,255 it also gives a white picture. Isn't this a dilemma ?

答:
Try out = ones(size(ben), 'uint8');

ones() by default creates an array of doubles.  When imshow() gets an array of doubles it assumes that the pixel values range between 0 and 1, and assigns the white color to anything greater than 1.  However, if you pass an array of uint8 to imshow() it will assume the range to be between 0 and 255.

You can also try using imagesc(); instead of imshow(), but you may need to do colormap gray after wards to get a grayscale image.

Another alternative is to rescale the image before display:

```<code>imshow(out / max(out(:)));
</code>```

Title: matlab rgb values dilemma

Body:
When i wrote these commands

out = ones(size(ben))
imshow(out)

the output is a white picture but i expect almost dark picture because the rgb values are 1,1,1. when i give 255,255,255 it also gives a white picture. Isn't this a dilemma ?

Body:
Try out = ones(size(ben), 'uint8');

ones() by default creates an array of doubles.  When imshow() gets an array of doubles it assumes that the pixel values range between 0 and 1, and assigns the white color to anything greater than 1.  However, if you pass an array of uint8 to imshow() it will assume the range to be between 0 and 255.

You can also try using imagesc(); instead of imshow(), but you may need to do colormap gray after wards to get a grayscale image.

Another alternative is to rescale the image before display:

imshow(out / max(out(:)));


问:
Monitor Chrome Network traffic (XHR packets)
I have a webapp to test. I got a test working with protractorJS that is clicking different buttons.
Some buttons do trigger a POST request, and the webapp is waiting for an answer from that point on. The answer can take up to 30 or 40 seconds to come in. If I look into the Chrome Developer tools, I see that the webapp sends GET packets to get the status every 2 seconds. The status can be waiting, failed or successful.

My Question is now:
How can I watch the network traffic and filter them that I know at which point the successful or failed status packet comes in?
I found PhantomJS Network Monitoring.

Basically I want to call a function after I clicked the button automatically with protractor, and this function should look into every packet that is coming in and should stop when it reads that the status is successful. If it takes more than 60 or 70 seconds the function should time out.

答:
After clicking the button which triggers POST method you should start listening in a loop another endpoint (GET) every n seconds (you wrote that app does it every 2 seconds).

If status is waiting - keep going, if it's failed - raise an exception and fail the test, if it successful - pass the test or do whatever you want.

The loop will prevent you from timeout.

You need to consider whether you need to protect yourself from the infinite loop if e.g. worker which processes the task stops working. Then GET method may return waiting, the loop won't finish and the test won't stop.


问:
How to create a JavaScript wrapper that can access a function and it's objects?
I have the following code that must be intact and cannot be modified.

```<code>        function newUser(username, email, callback) {
            var xhr = new XMLHttpRequest();
            var response;
            var success = (!!Math.round(Math.random()));

            if (!success){
                response = JSON.stringify({
                    success: success,
                    error: "Oups, something went wrong!"
                });
            } else {
                response = JSON.stringify({
                    success: success,
                    user: {
                        username: username,
                        email: email
                    }
                });
            }

            xhr.open("POST", "/echo/json/");
            xhr.onload = function () {
                    if (xhr.status === 200) {
                        callback(JSON.parse(xhr.responseText));
                }
            }
            xhr.send("json=" + response);
        };
</code>```

First I would like to call a function (newUser) on Click and then I would like to display and alert when the AJAX request within that function is successful. So far I have something similar to

```<code>            var el = document.getElementById("myButton");
            el.onclick = addUser;

               if (success){
                    alert (‘successful’);
                    }
</code>```

Since I can't modify the addUser function I figured that I need to add some sort of JavaScript wrapper to access it. Maybe I'm overthinking it but I can't get it to work.

答:
Not entirely sure I understand your question, but let me try to help.  Specify a handler function:

```<code>function onSuccess(result){
   alert (‘successful’)
}
</code>```

Then call newUser:

```<code>el.onclick = addUser("userName", "userEmal", onSuccess);
</code>```

onSuccess will be invoked in case of a 200 response, per the source code you provided.

ContentLicense: CC BY-SA 4.0

Body:
I have the following code that must be intact and cannot be modified.

        function newUser(username, email, callback) {
            var xhr = new XMLHttpRequest();
            var response;
            var success = (!!Math.round(Math.random()));

            if (!success){
                response = JSON.stringify({
                    success: success,
                    error: "Oups, something went wrong!"
                });
            } else {
                response = JSON.stringify({
                    success: success,
                    user: {
                        username: username,
                        email: email
                    }
                });
            }

            xhr.open("POST", "/echo/json/");
            xhr.onload = function () {
                    if (xhr.status === 200) {
                        callback(JSON.parse(xhr.responseText));
                }
            }
            xhr.send("json=" + response);
        };

First I would like to call a function (newUser) on Click and then I would like to display and alert when the AJAX request within that function is successful. So far I have something similar to

            var el = document.getElementById("myButton");
            el.onclick = addUser;

               if (success){
                    alert (‘successful’);
                    }

Since I can't modify the addUser function I figured that I need to add some sort of JavaScript wrapper to access it. Maybe I'm overthinking it but I can't get it to work.

Body:
Not entirely sure I understand your question, but let me try to help.  Specify a handler function:

function onSuccess(result){
   alert (‘successful’)
}

Then call newUser:

el.onclick = addUser("userName", "userEmal", onSuccess);

onSuccess will be invoked in case of a 200 response, per the source code you provided.


问:
Is it better to return a json object with relations or without?
I know that it probably depends a lot on the situation but..
If I have like two different controllers. Cotroller A is a parent to controller B.

If call my end point "/api/a/". It would return every A and each of their children.

Is it any efficent? Or would it be better to just returns all As from endpoint "api/a" without their children and make it seperately to get it from endpoint like "api/b/[A's id]"

I probably messed up a lot with this question.

But maybe someone could give me some kind of direction which should I follow @_ @

答:
The answer really depends.  How often will A include data from B?  How large is B?

If the answer is that A will need data B almost all the time, and that B is not very large then I probably wouldn't have a controller for B at all.  In every request to A I would include and return B with it.

If the answer is A will almost never need B, and B is fairly large then in my A object I would include a BUrl property that has the url to B and then when I desire B I can go get it.

Finally another option would be to just have an optional parameter that will include B on request. ?includeb=true

It really depends on the situation.  I favor fewer controllers and including data where practical.  It's less maintenance and overhead.


问:
Can't set headers on my WKWebView POST request
I want to do a POST request to my WKWebView but the headers doesn't get set when I monitor the requests with Charles so the request fails. What is wrong here?

```<code>NSString *post = [NSString stringWithFormat: @"email=%@&password=%@", email, password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *contentLength = [NSString stringWithFormat:@"%d", postData.length];

NSURL *url = [NSURL URLWithString:@"http://materik.me/endpoint"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[webview loadRequest:request];
</code>```

And this is what Charles says the request is like:

```<code>POST /endpoint HTTP/1.1
Host: materik.me
Content-Type: application/x-www-form-urlencoded
Origin: null
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (iPhone; CPU OS 8_0 like Mac OS X)
Content-Length: 0
Accept-Language: en-us
Accept-Encoding: gzip, deflate
</code>```

So, as you can see, Content-Length is 0, Accept is not application/json and no request body were sent.

Thanks for any help.

答:
As the OP stated, I have also confirmed in Charles that the body is 0 bytes after webView.load(request).

There's a workaround for this WKWebView bug, we will initiate a POST request using URLSession convert the data returned by the server to String and instead of loading the url we will use loadHTMLString which will:

Set the webpage contents and base URL.

and the content is our converted string:

```<code>var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
request.httpMethod = "POST"
let params = "do=something&andAgain=something"
request.httpBody = params.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
        if data != nil {
            if let returnString = String(data: data!, encoding: .utf8) {
                self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
            }
        }
}
task.resume()
</code>```

Body:
I want to do a POST request to my WKWebView but the headers doesn't get set when I monitor the requests with Charles so the request fails. What is wrong here?

NSString *post = [NSString stringWithFormat: @"email=%@&password=%@", email, password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *contentLength = [NSString stringWithFormat:@"%d", postData.length];

NSURL *url = [NSURL URLWithString:@"http://materik.me/endpoint"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[webview loadRequest:request];

And this is what Charles says the request is like:

POST /endpoint HTTP/1.1
Host: materik.me
Content-Type: application/x-www-form-urlencoded
Origin: null
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (iPhone; CPU OS 8_0 like Mac OS X)
Content-Length: 0
Accept-Language: en-us
Accept-Encoding: gzip, deflate

So, as you can see, Content-Length is 0, Accept is not application/json and no request body were sent.

Thanks for any help.

Body:
As the OP stated, I have also confirmed in Charles that the body is 0 bytes after webView.load(request).

There's a workaround for this WKWebView bug, we will initiate a POST request using URLSession convert the data returned by the server to String and instead of loading the url we will use loadHTMLString which will:

Set the webpage contents and base URL.

and the content is our converted string:

var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
request.httpMethod = "POST"
let params = "do=something&andAgain=something"
request.httpBody = params.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
        if data != nil {
            if let returnString = String(data: data!, encoding: .utf8) {
                self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
            }
        }
}
task.resume()


问:
Make a UITableView "sticky to the bottom"
Say you have a table view T which shows messages,

```<code>T[ message d
T[ message c
T[ message b
T[ most recent message down bottom
</code>```

Say there are 100 messages, with the bottom 4 visible in the example.

So the table view height is 700 say.  You have a typical text entry underneath...

```<code>T[ message d
T[ message c
T[ message b
T[ most recent message down bottom
[enter snapped chat message!] [send]
</code>```

When the keyboard appears, the new height of the visible table view is 400 say.

Of course, that will "cut off the bottom" of the messages - the most recent two will no longer be visible.

```<code>T[ message d
T[ message c
[enter snapped chat message!] [send]
[           iOS keyboard        ]
[           iOS keyboard        ]
</code>```

(So, messages A and B are now "under" the keyboard.)

Naturally what you do is just scroll the table after the keyboard appears, for example.  No problem doing it in an ad-hoc manner.

However, it would be really natural if one could subclass UITableView in such a way that, as the size of the visible area changed, the table view knew to keep the "bottom point" identical.

So, as the bottom of the table moves up and down (due to keyboard appearing - or whatever cause), the table would scroll actually based on the movement of the "base" of the table.

(Apart from anything else this would solve the "match the animation timing" nuisance.)

Could this be achieved elegantly and if so how - indeed this would seem so natural these days, perhaps it's built-in to UITableView as a flag and I just don't know?

once again the question here is

How to modify UITableView so that it moves its own scroll position, as, the view size changes...

(so as to keep the "bottom point the same")

Note that it's trivial to just scroll the table "manually" as it were from the outside.

答:
Section headers stick to the top, so maybe something like this:

1. Make the most recent message a section header view instead of a table cell

2. Mirror the table view vertically:

tableView.transform = CGAffineTransformMakeScale(1, -1);

3. Mirror vertically the section header and table cells

4. Reverse the order of your messages

Is that what you were looking for?

Body:
Say you have a table view T which shows messages,

T[ message d
T[ message c
T[ message b
T[ most recent message down bottom

Say there are 100 messages, with the bottom 4 visible in the example.

So the table view height is 700 say.  You have a typical text entry underneath...

T[ message d
T[ message c
T[ message b
T[ most recent message down bottom
[enter snapped chat message!] [send]

When the keyboard appears, the new height of the visible table view is 400 say.

Of course, that will "cut off the bottom" of the messages - the most recent two will no longer be visible.

T[ message d
T[ message c
[enter snapped chat message!] [send]
[           iOS keyboard        ]
[           iOS keyboard        ]

(So, messages A and B are now "under" the keyboard.)

Naturally what you do is just scroll the table after the keyboard appears, for example.  No problem doing it in an ad-hoc manner.

However, it would be really natural if one could subclass UITableView in such a way that, as the size of the visible area changed, the table view knew to keep the "bottom point" identical.

So, as the bottom of the table moves up and down (due to keyboard appearing - or whatever cause), the table would scroll actually based on the movement of the "base" of the table.

(Apart from anything else this would solve the "match the animation timing" nuisance.)

Could this be achieved elegantly and if so how - indeed this would seem so natural these days, perhaps it's built-in to UITableView as a flag and I just don't know?

once again the question here is

How to modify UITableView so that it moves its own scroll position, as, the view size changes...

(so as to keep the "bottom point the same")

Note that it's trivial to just scroll the table "manually" as it were from the outside.


问:
ER_NOT_SUPPORTED_AUTH_MODE - MySQL server

Failed at Connecting Node.js Server to MySQL-Database

I had MariaDB" installed on a "Node.js Server", but decided that I wanted to use a SQL Database instead. I uninstalled, and completely removed "MariaDB", after which, I proceeded to install the "Community Ed." "MySQL Database". After going through the entire *'MySQL Setup Process'**, I made several attempts to connect to the database via a JavaScript document that implemented the de facto code snippet for a JS DB Connection — my DB-connection document is posted as a code snippet bellow — shown in the code snippet bellow. Disappointingly, the JS/SQL connection failed at each attempt.

Here is the Failed Connection Error Message that I received:

```<code>
"ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication
protocol requested by server. Consider upgrading MariaDB client."

</code>```

JS/SQL Connection Snippet that I am using:

```<code>
    var mysql = require('mysql');

    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '********',
        database : 'foobarDb'
    });

</code>```

答:
I figure that some MySQL versions have the authentication for the establishment of a connection a bit messed up. All I had to do was add the line "insecureAuth" : true to the CreateConnection(...) credentials.

```<code>var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '********',
  database : 'vod_bill_database',
  insecureAuth : true
});
</code>```

The error is gone now, and the client is successfully connecting.

Body:
Failed at Connecting Node.js Server to MySQL-Database

I had MariaDB" installed on a "Node.js Server", but decided that I wanted to use a SQL Database instead. I uninstalled, and completely removed "MariaDB", after which, I proceeded to install the "Community Ed." "MySQL Database". After going through the entire *'MySQL Setup Process'**, I made several attempts to connect to the database via a JavaScript document that implemented the de facto code snippet for a JS DB Connection — my DB-connection document is posted as a code snippet bellow — shown in the code snippet bellow. Disappointingly, the JS/SQL connection failed at each attempt.

Here is the Failed Connection Error Message that I received:

"ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication
protocol requested by server. Consider upgrading MariaDB client."

JS/SQL Connection Snippet that I am using:

    var mysql = require('mysql');

    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '********',
        database : 'foobarDb'
    });

Body:
I figure that some MySQL versions have the authentication for the establishment of a connection a bit messed up. All I had to do was add the line "insecureAuth" : true to the CreateConnection(...) credentials.

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '********',
  database : 'vod_bill_database',
  insecureAuth : true
});

The error is gone now, and the client is successfully connecting.


问:
Performance tests
How to make performance tests on Java? Such as time of execution, a track of using memory, a track of operations per second and may be there are another helpful tests. How to realize this tests without an influence to the real application work (without this test)? I mean that I could be confident that my application would be work with the same performance on average without those tests.

Note: I need to attach a specific tool to my test class. I know that there is many different tools to test a huge amount of VM parameters of an application. I need to write a test class with distinct test parameters which values I can handle as I want. It would be good if API supported graphical GUI for some those parameters.

答:
I am under the assumption that your servers are hosted on the linux env. Jconsole and Visualvm are indeed helpful to monitor your memory and performance. Just as a work around you can also use sar, top and mpstat commands to get your required values.
You will have to install the sar package on your linux server by command sudo apt-get install sysstat. You can refer "http://www.thegeekstuff.com/2011/03/sar-examples/?utm_source=feedburner" to learn more on the commnads.
You don't need admin access to configure any of these commnds..</p>

Title: Performance tests


问:
How can I left align latex equations in R Markdown?
I'm having some difficulty left aligning equations in R Markdown (i.e. putting the equation on the far left side of page, and aligning subsequent lines). I've generally determined that I want to set the [fleqn] option in the amsmath package to left align all equations, but putting the following in my YAML header gives an error

'Option clash for package amsmath'

```<code>---
author: "ME"
date: "February 26, 2015"
header-includes:
  - \usepackage[fleqn]{amsmath}
output: pdf_document
---
</code>```

A section from my document:

```<code>$$
\begin{aligned}
Bias(\hat{\theta})  &= E(\hat{\theta}) - \theta \\
                    &= E(2 \bar{X} -1) - \theta \\
                    &= \frac{2}{n}\sum_{i=1}^n E(X_i) -1 -\theta \\
                    &= 2E(X) - 1 - \theta \\
                    &= 2 \cdot \frac{\theta+1}{2} - 1 - \theta \\
                    &= 0 \\
\end{aligned}
$$
</code>```

Thanks

答:
This question has already been asked here: R Markdown Math Equation Allignment

The below works for me:

```<code>$\begin{aligned}
Bias(\hat{\theta})  &= E(\hat{\theta}) - \theta \\
                    &= E(2 \bar{X} -1) - \theta \\
                    &= \frac{2}{n}\sum_{i=1}^n E(X_i) -1 -\theta \\
                    &= 2E(X) - 1 - \theta \\
                    &= 2 \cdot \frac{\theta+1}{2} - 1 - \theta \\
                    &= 0 \\
\end{aligned}$
</code>```

Body:
I'm having some difficulty left aligning equations in R Markdown (i.e. putting the equation on the far left side of page, and aligning subsequent lines). I've generally determined that I want to set the [fleqn] option in the amsmath package to left align all equations, but putting the following in my YAML header gives an error

'Option clash for package amsmath'

---
author: "ME"
date: "February 26, 2015"
header-includes:
  - \usepackage[fleqn]{amsmath}
output: pdf_document
---

A section from my document:

$$
\begin{aligned}
Bias(\hat{\theta})  &= E(\hat{\theta}) - \theta \\
                    &= E(2 \bar{X} -1) - \theta \\
                    &= \frac{2}{n}\sum_{i=1}^n E(X_i) -1 -\theta \\
                    &= 2E(X) - 1 - \theta \\
                    &= 2 \cdot \frac{\theta+1}{2} - 1 - \theta \\
                    &= 0 \\
\end{aligned}
$$

Thanks

Body:
This question has already been asked here: R Markdown Math Equation Allignment

The below works for me:

$\begin{aligned}
Bias(\hat{\theta})  &= E(\hat{\theta}) - \theta \\
                    &= E(2 \bar{X} -1) - \theta \\
                    &= \frac{2}{n}\sum_{i=1}^n E(X_i) -1 -\theta \\
                    &= 2E(X) - 1 - \theta \\
                    &= 2 \cdot \frac{\theta+1}{2} - 1 - \theta \\
                    &= 0 \\
\end{aligned}$


问:
fetching parameter in a link php codeigniter
Say I have this url

```<code>http://localhost/newtkt/index.php/welcome/gettkt/PfIfiETYXzUpYRJf6RPvyncN4PgdN3
</code>```

and a controller function

```<code>public function gettkt()
{
  //mydata
}
</code>```

how can i retrieve the parameter PfIfiETYXzUpYRJf6RPvyncN4PgdN3 that comes with the url and make it a variable in my controller function gettkt() so that i can use the parameter within the function like gettkt(thisparameter). I hope I've structured my question in the best way possible. thank you.

答:
You can do two things

Method 01

```<code>public function gettkt($parm)
{
    echo $parm; # Prints PfIfiETYXzUpYRJf6RPvyncN4PgdN3
}
</code>```

Method 02

Use URI Class in CodeIgniter

```<code>$parm = $this->uri->segment(n); # Number point your parameter
$parm = $this->uri->segment(3); # Prints PfIfiETYXzUpYRJf6RPvyncN4PgdN3
</code>```

Body:
Say I have this url

http://localhost/newtkt/index.php/welcome/gettkt/PfIfiETYXzUpYRJf6RPvyncN4PgdN3

and a controller function

public function gettkt()
{
  //mydata
}

how can i retrieve the parameter PfIfiETYXzUpYRJf6RPvyncN4PgdN3 that comes with the url and make it a variable in my controller function gettkt() so that i can use the parameter within the function like gettkt(thisparameter). I hope I've structured my question in the best way possible. thank you.

Body:
You can do two things

Method 01

public function gettkt($parm)
{
    echo $parm; # Prints PfIfiETYXzUpYRJf6RPvyncN4PgdN3
}

Method 02

Use URI Class in CodeIgniter

$parm = $this->uri->segment(n); # Number point your parameter
$parm = $this->uri->segment(3); # Prints PfIfiETYXzUpYRJf6RPvyncN4PgdN3


问:
Ionic docker Failed to open the browser
I'm using ionic with docker and when i try to execute the command ionic serve that execute the app on the browser i have this error :

```<code>root@00209e483f93:/var/www/espaceproold# ionic serve
[INFO] Starting app-scripts server: --port 8100 --p 8100 --livereload-port 35729 --r 35729 --address 0.0.0.0 - Ctrl+C to
       cancel

[13:54:41]  watch started ...
[13:54:41]  build dev started ...
[13:54:41]  clean started ...
[13:54:41]  clean finished in 7 ms
[13:54:41]  copy started ...
[13:54:41]  transpile started ...
[13:54:45]  transpile finished in 3.50 s
[13:54:45]  preprocess started ...
[13:54:45]  deeplinks started ...
[13:54:45]  deeplinks finished in 47 ms
[13:54:45]  preprocess finished in 49 ms
[13:54:45]  webpack started ...
[13:54:45]  copy finished in 4.10 s
[13:54:55]  webpack finished in 10.18 s
[13:54:55]  sass started ...
[13:54:57]  sass finished in 1.55 s
[13:54:57]  postprocess started ...
[13:54:57]  postprocess finished in 18 ms
[13:54:57]  lint started ...
[13:54:57]  build dev finished in 15.37 s
[13:54:57]  watch ready in 15.48 s
[13:54:57]  dev server running: http://localhost:8100/

[13:54:57]  Failed to open the browser: Command failed: xdg-open "http://localhost:8100" /bin/sh: 1: xdg-open: not found
[13:55:00]  lint finished in 3.41 s
</code>```

docker file :

```<code>FROM ubuntu:16.04
MAINTAINER ""
# Install apt packages
RUN apt-get update && apt-get install -y git lib32stdc++6 lib32z1 curl openjdk-8-jdk-headless sendemail libio-socket-ssl-perl libnet-ssleay-perl && apt-get clean && rm -rf /var/lib/apt/lists/*
# Install android SDK, tools and platforms
RUN cd /opt && curl https://dl.google.com/android/android-sdk_r24.4.1-linux.tgz -o android-sdk.tgz && tar xzf android-sdk.tgz && rm android-sdk.tgz
ENV ANDROID_HOME /opt/android-sdk-linux
RUN echo 'y' | /opt/android-sdk-linux/tools/android update sdk -u -a -t platform-tools,build-tools-23.0.3,android-23,extra-android-support,extra-google-m2repository,extra-android-m2repository
# accept the license agreements of the SDK components
RUN export ANDROID_LICENSES="$ANDROID_HOME/licenses" && \
    [ -d $ANDROID_LICENSES ] || mkdir $ANDROID_LICENSES && \
    [ -f $ANDROID_LICENSES/android-sdk-license ] || echo 8933bad161af4178b1185d1a37fbf41ea5269c55 > $ANDROID_LICENSES/android-sdk-license && \
    [ -f $ANDROID_LICENSES/android-sdk-preview-license ] || echo 84831b9409646a918e30573bab4c9c91346d8abd > $ANDROID_LICENSES/android-sdk-preview-license && \
    [ -f $ANDROID_LICENSES/intel-android-extra-license ] || echo d975f751698a77b662f1254ddbeed3901e976f5a > $ANDROID_LICENSES/intel-android-extra-license && \
    unset ANDROID_LICENSES
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y -q \
    nodejs \
    gradle \
    && apt-get -y autoclean \
    && rm -rf /var/lib/apt/lists/*
# Install npm packages
RUN npm install -g ionic
RUN npm install -g cordova
# Setup environment
ENV ANDROID_HOME /opt/android-sdk-linux
ENV PATH ${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools
EXPOSE 8100 35729
</code>```

Is there anything wrong with my dockerfile? Or what is the issue?
thanks in advance !

答:
From ionic documentation, you should run ionic with this option:

```<code>--nobrowser,-b    |    Disable launching a browser
</code>```

This will prevent ionic serve to try launching a browser to display your site.

Moreover, you certainly don't want in production to enable live-reload. you can use --nolivereload then. It's ok to keep live-reload if you are on a development mode.

Title: Ionic docker Failed to open the browser

Body:
I'm using ionic with docker and when i try to execute the command ionic serve that execute the app on the browser i have this error :

root@00209e483f93:/var/www/espaceproold# ionic serve
[INFO] Starting app-scripts server: --port 8100 --p 8100 --livereload-port 35729 --r 35729 --address 0.0.0.0 - Ctrl+C to
       cancel

[13:54:41]  watch started ...
[13:54:41]  build dev started ...
[13:54:41]  clean started ...
[13:54:41]  clean finished in 7 ms
[13:54:41]  copy started ...
[13:54:41]  transpile started ...
[13:54:45]  transpile finished in 3.50 s
[13:54:45]  preprocess started ...
[13:54:45]  deeplinks started ...
[13:54:45]  deeplinks finished in 47 ms
[13:54:45]  preprocess finished in 49 ms
[13:54:45]  webpack started ...
[13:54:45]  copy finished in 4.10 s
[13:54:55]  webpack finished in 10.18 s
[13:54:55]  sass started ...
[13:54:57]  sass finished in 1.55 s
[13:54:57]  postprocess started ...
[13:54:57]  postprocess finished in 18 ms
[13:54:57]  lint started ...
[13:54:57]  build dev finished in 15.37 s
[13:54:57]  watch ready in 15.48 s
[13:54:57]  dev server running: http://localhost:8100/

[13:54:57]  Failed to open the browser: Command failed: xdg-open "http://localhost:8100" /bin/sh: 1: xdg-open: not found
[13:55:00]  lint finished in 3.41 s

docker file :

FROM ubuntu:16.04
MAINTAINER ""
# Install apt packages
RUN apt-get update && apt-get install -y git lib32stdc++6 lib32z1 curl openjdk-8-jdk-headless sendemail libio-socket-ssl-perl libnet-ssleay-perl && apt-get clean && rm -rf /var/lib/apt/lists/*
# Install android SDK, tools and platforms
RUN cd /opt && curl https://dl.google.com/android/android-sdk_r24.4.1-linux.tgz -o android-sdk.tgz && tar xzf android-sdk.tgz && rm android-sdk.tgz
ENV ANDROID_HOME /opt/android-sdk-linux
RUN echo 'y' | /opt/android-sdk-linux/tools/android update sdk -u -a -t platform-tools,build-tools-23.0.3,android-23,extra-android-support,extra-google-m2repository,extra-android-m2repository
# accept the license agreements of the SDK components
RUN export ANDROID_LICENSES="$ANDROID_HOME/licenses" && \
    [ -d $ANDROID_LICENSES ] || mkdir $ANDROID_LICENSES && \
    [ -f $ANDROID_LICENSES/android-sdk-license ] || echo 8933bad161af4178b1185d1a37fbf41ea5269c55 > $ANDROID_LICENSES/android-sdk-license && \
    [ -f $ANDROID_LICENSES/android-sdk-preview-license ] || echo 84831b9409646a918e30573bab4c9c91346d8abd > $ANDROID_LICENSES/android-sdk-preview-license && \
    [ -f $ANDROID_LICENSES/intel-android-extra-license ] || echo d975f751698a77b662f1254ddbeed3901e976f5a > $ANDROID_LICENSES/intel-android-extra-license && \
    unset ANDROID_LICENSES
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y -q \
    nodejs \
    gradle \
    && apt-get -y autoclean \
    && rm -rf /var/lib/apt/lists/*
# Install npm packages
RUN npm install -g ionic
RUN npm install -g cordova
# Setup environment
ENV ANDROID_HOME /opt/android-sdk-linux
ENV PATH ${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools
EXPOSE 8100 35729

Is there anything wrong with my dockerfile? Or what is the issue?
thanks in advance !

Body:
From ionic documentation, you should run ionic with this option:

--nobrowser,-b    |    Disable launching a browser

This will prevent ionic serve to try launching a browser to display your site.

Moreover, you certainly don't want in production to enable live-reload. you can use --nolivereload then. It's ok to keep live-reload if you are on a development mode.


问:
How to share the library resources which are included in "base feature" module
I have the following structure of android project

application module

base feature module

feature module

a local library project

remote libraries

When I try to include the local library project in base feature module with
api or implementation, the feature either not compiling because of not found resources or throwing the same errors at runtime.
And now I am wondering is there a point which I misunderstood. The documentation says the base feature module is intended to share the common code and the resources, but it seems it doesn't cover the library cases.

The runtime resource not found errors are thrown when I try to include the same library also in the feature module.

答:
When referecing resources from base module in your feature modules you need to use the full packageName qualifier.

This is because in instant apps they will belong to another name space.

Hence:

R.id.resource will point to resources of your feature module
com.yourdomain.appbase.R.id.resource will reference resources of your base module


问:
How can I json.parse a javascript string?
I'm trying to parse a string that is created from data I get from html.

```<code>    var string = ''
    string += '\n\n\n';
    string += $('#tickmarks').data('hello'+mode);
    string += '\n';
    checks.forEach(function(check){
        if($(check).is(':checked')){
            string += $(check).parent().text();
            string += '\n\n';
        }
    });
    string += $('#tickmarks').data('goodbye'+mode);

    string += '\n';

    string += $('.name').val();
    $('textarea').val(JSON.parse(string));
</code>```

I get errors, when I try to pass characters into this string. Apparently a string in JSON should have quotes, I have tried adding them like this:

```<code>string += '"'
string += "foo"
string += '"'
</code>```

and this:

```<code>string += '"'
string += "foo"
string += '"'
</code>```

and this:

```<code>string += "'"
string += "foo"
string += "'"
</code>```

答:
Quotes are not necessary.
For example this string is easily parseable without additional quotes in it:

```<code>> JSON.parse('\n\n{}');
< Object {}
</code>```

However, if you want to have JSON representation of some jQuery objects, I suggest building a Object from your jQuery selection and then using JSON.stringify()

```<code>    var data = {
       {tickmarks:$('#tickmarks').data('hello'+mode)}
    };
    checks.forEach(function(check){
        if($(check).is(':checked')){
                data[$(check).parent().text()] = $(check).parent().text();
            }
        });
    JSON.stringify(data);
</code>```

PS. In your code you should try to print the concatenated string and verify that it follows the rules for parsing string (see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Examples)

Body:
I'm trying to parse a string that is created from data I get from html.

    var string = ''
    string += '\n\n\n';
    string += $('#tickmarks').data('hello'+mode);
    string += '\n';
    checks.forEach(function(check){
        if($(check).is(':checked')){
            string += $(check).parent().text();
            string += '\n\n';
        }
    });
    string += $('#tickmarks').data('goodbye'+mode);

    string += '\n';

    string += $('.name').val();
    $('textarea').val(JSON.parse(string));

I get errors, when I try to pass characters into this string. Apparently a string in JSON should have quotes, I have tried adding them like this:

string += '"'
string += "foo"
string += '"'

and this:

string += '"'
string += "foo"
string += '"'

and this:

string += "'"
string += "foo"
string += "'"

Body:
Quotes are not necessary.
For example this string is easily parseable without additional quotes in it:

> JSON.parse('\n\n{}');
< Object {}

However, if you want to have JSON representation of some jQuery objects, I suggest building a Object from your jQuery selection and then using JSON.stringify()

    var data = {
       {tickmarks:$('#tickmarks').data('hello'+mode)}
    };
    checks.forEach(function(check){
        if($(check).is(':checked')){
                data[$(check).parent().text()] = $(check).parent().text();
            }
        });
    JSON.stringify(data);

PS. In your code you should try to print the concatenated string and verify that it follows the rules for parsing string (see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Examples)


问:
Dropdown only works in chrome
I had to hack in a drop down menu to an element in an ecommerce site where the show/hide couldn't be done with css due to html structure.

I came up with this code but it only works in chrome.  In IE & Firefox the dropdown instantly dissapears when the cursor leaves the blue and goes over the red.  Why is this and how should I fix it?

$("#button").hover(
  function() {
    $("#mainmenu").show();
  },
  function() {
    if (!$("#mainmenu").is(":hover")) {
      $("#mainmenu").hide();
    }
  }
);

$("#mainmenu").hover(
  function() {

  },
  function() {
      $("#mainmenu").hide();

  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button{
  width: 300px;
  height: 30px;
  background-color: blue;
}
#mainmenu{
  width: 300px;
  height: 600px;
  background-color: red;
  position: absolute;
  display: none;
}</code>```

```

答:
Add $("#mainmenu").show(); inside the first callback function of the $("#mainmenu").hover():

$("#button").hover(
  function() {
    $("#mainmenu").show();
  },
  function() {
    if (!$("#mainmenu").is(":hover")) {
      $("#mainmenu").hide();
    }
  }
);

$("#mainmenu").hover(
  function() {
    $("#mainmenu").show();
  },
  function() {
    $("#mainmenu").hide();

  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button {
  width: 300px;
  height: 30px;
  background-color: blue;
}

#mainmenu {
  width: 300px;
  height: 600px;
  background-color: red;
  position: absolute;
  display: none;
}</code>```

```

Title: Dropdown only works in chrome

Body:
I had to hack in a drop down menu to an element in an ecommerce site where the show/hide couldn't be done with css due to html structure.

I came up with this code but it only works in chrome.  In IE & Firefox the dropdown instantly dissapears when the cursor leaves the blue and goes over the red.  Why is this and how should I fix it?

$("#button").hover(
  function() {
    $("#mainmenu").show();
  },
  function() {
    if (!$("#mainmenu").is(":hover")) {
      $("#mainmenu").hide();
    }
  }
);

$("#mainmenu").hover(
  function() {

  },
  function() {
      $("#mainmenu").hide();

  }
);

#button{
  width: 300px;
  height: 30px;
  background-color: blue;
}
#mainmenu{
  width: 300px;
  height: 600px;
  background-color: red;
  position: absolute;
  display: none;
}

Body:
Add $("#mainmenu").show(); inside the first callback function of the $("#mainmenu").hover():

$("#button").hover(
  function() {
    $("#mainmenu").show();
  },
  function() {
    if (!$("#mainmenu").is(":hover")) {
      $("#mainmenu").hide();
    }
  }
);

$("#mainmenu").hover(
  function() {
    $("#mainmenu").show();
  },
  function() {
    $("#mainmenu").hide();

  }
);

#button {
  width: 300px;
  height: 30px;
  background-color: blue;
}

#mainmenu {
  width: 300px;
  height: 600px;
  background-color: red;
  position: absolute;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button"></div>
<div id="mainmenu"></div>


问:
Uncaught TypeError: $ is not a function Is anybody know what is wrong?

Uncaught TypeError: $ is not a function

Here is the "custom-isotope-portfolio.js" file. Does anybody know what is wrong?

This is a wordpess site. Looks like there is a problem in theme

enter image description here

if (!$) $ = jQuery;

// Isotope for Portfolio

$(document).ready(function() {
 ('.vivaco-grid[id^="gridwrapper_"]').each( function() {
  var $div = $(this),
   token = $div.data('token'),
   settingObj = window['vsc_grid_' + token],
   $container = null,
   $optionSets = null,
   grid_gutter_width = settingObj.gutter_width;

  if (typeof settingObj === 'undefined') {
   $container = $(".grid_portfolio");
   $optionSets = $('#gridwrapper_portfolio #options .option-set');

  }else {
   $container = $(".grid_"+settingObj.id+"");
   $optionSets = $('#gridwrapper_'+settingObj.id+'  #options .option-set');

  }

  colWidth = function () {
   var w = $container.width(),
    columnNum = 1,
    columnWidth = 0;

   vals = settingObj.vals

   // apply default settings
   if (vals.grid_manager != 1) {
    if (w > 1440) {
     columnNum  = 4;

    } else if (w > 1365) {
     columnNum  = 3;

    } else if (w > 1279) {
     columnNum  = 3;

    } else if (w > 1023) {
     columnNum  = 3;

    } else if (w > 767) {
     columnNum  = 2;

    } else if (w > 479) {
     columnNum  = 2;

    }

   }else { // apply custom settings
    if (w > 1440) {
     columnNum  = vals.grid_very_wide;

    } else if (w > 1365) {
     columnNum  = vals.grid_wide;

    } else if (w > 1279) {
     columnNum  = vals.grid_normal;

    } else if (w > 1023) {
     columnNum  = vals.grid_small;

    } else if (w > 767) {
     columnNum  = vals.grid_tablet;

    } else if (w > 479) {
     columnNum  = vals.grid_phone;

    }
   }

   columnWidth = Math.floor(w/columnNum);

   $container.find('.grid-item').each(function() {
    var $item = $(this),
     gwidth = 0;

    if (vals.grid_manager == 1) {
     gwidth = grid_gutter_width;

    }

    $item.css({'margin': Math.floor(gwidth/2)});

    if ($item.hasClass('item-wide')) {
     if (w < 480) {
      $item.css({
       'width' : ((columnWidth)-gwidth) + 'px',
       'height' : Math.round(((columnWidth)-gwidth) * 0.7777777) + 'px'
      });

      $item.find('img').css({
       'width' : ((columnWidth)-gwidth) + 'px',
       'height' : '100%'
      });

     }else {
      $item.css({
       'width' : ((columnWidth*2)-gwidth) + 'px',
       'height' : Math.round(((columnWidth*2)-gwidth) * 0.7777777) + 'px'
      });

      $item.find('img').css({
       'width' : ((columnWidth*2)-gwidth) + 'px',
       'height' : '100%'
      });

     }
    }

    if ($item.hasClass('item-small')) {
     $item.css({
      'width' : ((columnWidth)-gwidth) + 'px',
      'height' : Math.round(((columnWidth)-gwidth) * 0.7777777) + 'px'
     });

     $item.find('img').css({
      'width' : ((columnWidth)-gwidth) + 'px',
      'height' : '100%'
     });

    }

    if ($item.hasClass('item-long')) {
     if (w < 480) {
      $item.css({
       'width' : ((columnWidth)-gwidth) + 'px',
       'height' : Math.round(((columnWidth)-gwidth) * 0.7777777/2) + 'px'
      });

      $item.find('img').css({
       'width' : ((columnWidth)-gwidth) + 'px',
       'height' : '100%'
      });

     }else {
      $item.css({
       'width' : ((columnWidth*2)-gwidth) + 'px',
       'height' : Math.round(((columnWidth)-gwidth) * 0.7777777) + 'px'
      });

      $item.find('img').css({
       'width' : ((columnWidth*2)-gwidth) + 'px',
       'height' : '100%'
      });

     }
    }

    if ($item.hasClass('item-high')) {
     $item.css({
      'width' : ((columnWidth)-gwidth) + 'px',
      'height' : Math.round(((columnWidth*2)-gwidth) * 0.7777777) +'px'
     });

     $item.find('img').css({
      'width' : ((columnWidth)-gwidth) + 'px',
      'height' : '100%'
     });

    }
   });

   return columnWidth;
  }

  // Isotope Call
  gridIsotope = function () {
   $container.isotope({
    layoutMode : 'masonry',
    itemSelector: '.grid-item',
    animationEngine: 'jquery',
    resizable: false,
    masonry: { columnWidth: colWidth(), gutter: 35, isFitWidth: true }
   });
  };
  gridIsotope();
  $(window).smartresize(gridIsotope);

  // Portfolio Filtering
  $optionLinks = $optionSets.find('a');

  $optionLinks.click(function() {
   var $this = $(this);
   var $optionSet = $this.parents('.option-set');

   // don't proceed if already selected
   if ( $this.hasClass('selected') ) return false;

   $optionSet.find('.selected').removeClass('selected');
   $this.addClass('selected');

   // make option object dynamically, i.e. { filter: '.my-filter-class' }
   var options = {},
    key = $optionSet.attr('data-option-key'),
    value = $this.attr('data-option-value');

   // parse 'false' as false boolean
   value = value === 'false' ? false : value;
   options[ key ] = value;

   if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
    changeLayoutMode( $this, options ); // changes in layout modes need extra logic

   } else {
    $container.isotope( options ); // otherwise, apply new options

   }

   return false;
  });
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答: you do not have jquery loaded. try loading it through a cdn</p>


问:
Redshift FULL OUTER JOIN doesn't output NULL
We have a 'numbers' table that holds 0-10000 values in its single value 'n'.
We have tableX that has calculated_at datetime and a term.
We are trying to fill the holes where in tableX doesnt have matches in the given dates. HOWEVER, this doesn't seem to yield NULL or 0 for the non-matching... </p>

```<code>select term
     , avg(total::float)
     , date_trunc('day', series.date) as date1
     , date_trunc('day', calculated_at) as date2
from (select
        (current_timestamp - interval '1 day' * numbers.n)::date as date
      from numbers) as series
full outer join terms
   on series.date = date_trunc('day', calculated_at)
where series.date BETWEEN '2017-07-01' AND '2017-07-30'
AND (term in ('term111') or term is null)
group by term
       , date_trunc('day', series.date)
       , date_trunc('day', calculated_at)
 order by date_trunc('day', series.date) asc
</code>```

答:
The full outer join is fine.  The problem is the filters.  These are really tricky with a full outer join.  I would recommend:

```<code>select t.term, avg(total::float),
       date_trunc('day', series.date) as date1,
       date_trunc('day', calculated_at) as date2
from (select (current_timestamp - interval '1 day' * numbers.n)::date as date
      from numbers
      where (current_timestamp - interval '1 day' * numbers.n)::date BETWEEN '2017-07-01' AND '2017-07-30'
     ) series full outer join
     (select t.*
      from terms
      where term = 'term111'
     ) t
     on series.date = date_trunc('day', t.calculated_at)
group by t.term, date_trunc('day', series.date), date_trunc('day', calculated_at)
 order by date_trunc('day', series.date) asc;
</code>```

My guess though is that a left join would do what you want.  I doubt a full outer join is what you really intend.  If you have doubts, ask another question and provide sample data and desired results.

Body:
We have a 'numbers' table that holds 0-10000 values in its single value 'n'.
We have tableX that has calculated_at datetime and a term.
We are trying to fill the holes where in tableX doesnt have matches in the given dates. HOWEVER, this doesn't seem to yield NULL or 0 for the non-matching...

select term
     , avg(total::float)
     , date_trunc('day', series.date) as date1
     , date_trunc('day', calculated_at) as date2
from (select
        (current_timestamp - interval '1 day' * numbers.n)::date as date
      from numbers) as series
full outer join terms
   on series.date = date_trunc('day', calculated_at)
where series.date BETWEEN '2017-07-01' AND '2017-07-30'
AND (term in ('term111') or term is null)
group by term
       , date_trunc('day', series.date)
       , date_trunc('day', calculated_at)
 order by date_trunc('day', series.date) asc

Body:
The full outer join is fine.  The problem is the filters.  These are really tricky with a full outer join.  I would recommend:

select t.term, avg(total::float),
       date_trunc('day', series.date) as date1,
       date_trunc('day', calculated_at) as date2
from (select (current_timestamp - interval '1 day' * numbers.n)::date as date
      from numbers
      where (current_timestamp - interval '1 day' * numbers.n)::date BETWEEN '2017-07-01' AND '2017-07-30'
     ) series full outer join
     (select t.*
      from terms
      where term = 'term111'
     ) t
     on series.date = date_trunc('day', t.calculated_at)
group by t.term, date_trunc('day', series.date), date_trunc('day', calculated_at)
 order by date_trunc('day', series.date) asc;

My guess though is that a left join would do what you want.  I doubt a full outer join is what you really intend.  If you have doubts, ask another question and provide sample data and desired results.


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

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

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

    void show();
};

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

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

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

int main() {
    A<double> a;

    a.show();

    return 0;
}
</code>```

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

Edit:

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

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

答:
Problem is the non-deduced context (thanks PasserBy for the link), which disallows us to find a direct solution.

A workaround might be moving the typedef out of the class, such as this:

```<code>template <typename T>
using A_MyType = std::map<unsigned int, T>;

template <typename T>
class A
{
public:
    typedef A_MyType<T> MyType;
    MyType data;

    void show();
};

template <typename T>
std::ostream& operator<<(std::ostream& stream, A_MyType<T> const& mm)
{
    return stream << mm.size() << std::endl;
}
</code>```

Sure, this works fine for the std::map, if it works for your more complex class – impossible to say without knowing more details...

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

#include <iostream>
#include <map>

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

    void show();
};

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

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

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

int main() {
    A<double> a;

    a.show();

    return 0;
}

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

Edit:

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

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

Body:
Problem is the non-deduced context (thanks PasserBy for the link), which disallows us to find a direct solution.

A workaround might be moving the typedef out of the class, such as this:

template <typename T>
using A_MyType = std::map<unsigned int, T>;

template <typename T>
class A
{
public:
    typedef A_MyType<T> MyType;
    MyType data;

    void show();
};

template <typename T>
std::ostream& operator<<(std::ostream& stream, A_MyType<T> const& mm)
{
    return stream << mm.size() << std::endl;
}

Sure, this works fine for the std::map, if it works for your more complex class – impossible to say without knowing more details...


答:
I removed this bit from $("#button").hover():

```<code>  function() {
    if (!$("#mainmenu").is(":hover")) {
      $("#mainmenu").hide();
    }
</code>```

This works for me in IE as you intended it to:

$("#button").hover(
  function() {
    $("#mainmenu").show();
  }
);

$("#mainmenu").hover(
  function() {

  },
  function() {
      $("#mainmenu").hide();

  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button{
  width: 300px;
  height: 30px;
  background-color: blue;
}
#mainmenu{
  width: 300px;
  height: 600px;
  background-color: red;
  position: absolute;
  display: none;
}</code>```

```

Title: Dropdown only works in chrome

Body:
I removed this bit from $("#button").hover():

  function() {
    if (!$("#mainmenu").is(":hover")) {
      $("#mainmenu").hide();
    }

This works for me in IE as you intended it to:

$("#button").hover(
  function() {
    $("#mainmenu").show();
  }
);

$("#mainmenu").hover(
  function() {

  },
  function() {
      $("#mainmenu").hide();

  }
);

#button{
  width: 300px;
  height: 30px;
  background-color: blue;
}
#mainmenu{
  width: 300px;
  height: 600px;
  background-color: red;
  position: absolute;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button"></div>
<div id="mainmenu"></div>