问:
Azure Storage Emulator 400 Bad Request (redux)
In VisualStudio 2017 and 2015 when I attempt CreateIfNotExists() with CloudBlobClient "UseDevelopmentStorage=true" I am getting a 400 Bad Request. When I change the connection to point to a live Azure storage account, it works

```<code>open Microsoft.WindowsAzure
open Microsoft.WindowsAzure.Storage
open Microsoft.WindowsAzure.Storage.Blob
let storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://127.0.0.1;")
    //let storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true")  //also tried formatting the connection string this way
    //let storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://127.0.0.1:10000;") //also tried this
let blobClient = storageAccount.CreateCloudBlobClient()
let container = blobClient.GetContainerReference("contactinput")
container.CreateIfNotExists()
|> ignore
</code>```

Previous questions on this topic were resolved by

1) improper container name, usually capital letters

(that is not the case here, especially since it works pointing to live Azure storage)

2) issue with local development storage not starting properly

(that is not the case here, as I can connect to local storage through the Microsoft Storage Explorer and even inside Visual Studio through the Server Explorer)

3) incompatibility between emulator, SDK, and storage DLL

(recommended solution is "get latest")

This is my set-up:

Azure .NET SDK v2.9

Windows Azure Storage Emulator 5.1.0.0

Microsoft.WindowsAzure.Storage DLL  8.3.0

As best I can tell these are all current, except there is an SDK v2.9.6. I'm having trouble finding a link to download this version of the SDK, all the online links seem to point me to a full VS2017 install.

It's unlikely such a minor SDK revision would be the source of my problem anyway. Any other suggestions as to what my problem could be?

答:
Personally I use

```<code>CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount
</code>```

to set up development account because it makes sure everything is set up correctly, also be sure that every container is lowercase, I was getting a 400 bad request error because I was sending out a request for "testContainer", the error stopped showing up when I used "testcontainer" instead.

Body:
In VisualStudio 2017 and 2015 when I attempt CreateIfNotExists() with CloudBlobClient "UseDevelopmentStorage=true" I am getting a 400 Bad Request. When I change the connection to point to a live Azure storage account, it works

open Microsoft.WindowsAzure
open Microsoft.WindowsAzure.Storage
open Microsoft.WindowsAzure.Storage.Blob
let storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://127.0.0.1;")
    //let storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true")  //also tried formatting the connection string this way
    //let storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://127.0.0.1:10000;") //also tried this
let blobClient = storageAccount.CreateCloudBlobClient()
let container = blobClient.GetContainerReference("contactinput")
container.CreateIfNotExists()
|> ignore

Previous questions on this topic were resolved by

1) improper container name, usually capital letters

(that is not the case here, especially since it works pointing to live Azure storage)

2) issue with local development storage not starting properly

(that is not the case here, as I can connect to local storage through the Microsoft Storage Explorer and even inside Visual Studio through the Server Explorer)

3) incompatibility between emulator, SDK, and storage DLL

(recommended solution is "get latest")

This is my set-up:

Azure .NET SDK v2.9

Windows Azure Storage Emulator 5.1.0.0

Microsoft.WindowsAzure.Storage DLL  8.3.0

As best I can tell these are all current, except there is an SDK v2.9.6. I'm having trouble finding a link to download this version of the SDK, all the online links seem to point me to a full VS2017 install.

It's unlikely such a minor SDK revision would be the source of my problem anyway. Any other suggestions as to what my problem could be?

Body:
Personally I use

CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount

to set up development account because it makes sure everything is set up correctly, also be sure that every container is lowercase, I was getting a 400 bad request error because I was sending out a request for "testContainer", the error stopped showing up when I used "testcontainer" instead.


来源: stackexchange

问:
imagepng under a Windows 2012 R2 Server
So the Situation is, that I have to automatically convert .jpg-files to .png-files, when a User uploads via POST.

The problem is: I just can't save the converted Image-Object I created with PHP... I'm running a Windows 2012 R2 Server, with Apache 2.4 and PHP 5.5.38.

According to the PHP-Manual I just need to give the function a path to a file:

```<code>$input = 'test.jpg';
$output = 'test.png';
$inputfile = imagecreatefromjpeg(realpath($input));
imagepng($inputfile,$output,9);
</code>```

The output path can be an existing or non-existing file, right?
For the directory wherein the code is executed, the windows permissions are set to Full Access for everyone - so the problem shouldn't be there...

I'm pretty sure, it's just a dumb mistake I oversee :D
Thanks in advance!

答:
Nevermind guys, just saw the right answer in the PHP manual comments...

Blockquote
  Be careful when using a variable for the file name.
  PHP behavior with $filename differs when switching to PHP5.4 : PHP5.3 will use $filename='' the same way as $filename=NULL (e.g. no warning)

ContentLicense: CC BY-SA 3.0

Title: imagepng under a Windows 2012 R2 Server

Body:
So the Situation is, that I have to automatically convert .jpg-files to .png-files, when a User uploads via POST.

The problem is: I just can't save the converted Image-Object I created with PHP... I'm running a Windows 2012 R2 Server, with Apache 2.4 and PHP 5.5.38.

According to the PHP-Manual I just need to give the function a path to a file:

$input = 'test.jpg';
$output = 'test.png';
$inputfile = imagecreatefromjpeg(realpath($input));
imagepng($inputfile,$output,9);

The output path can be an existing or non-existing file, right?
For the directory wherein the code is executed, the windows permissions are set to Full Access for everyone - so the problem shouldn't be there...

I'm pretty sure, it's just a dumb mistake I oversee :D
Thanks in advance!


问:
Count from two tables and display the counts in the same table in MYSQL
I have two tables with a primary key and a column(name color)

```<code>Table1
|Color|
|red  |
|green|
|blue |

Table2
|Color|
|red  |
|red  |
|green|
</code>```

I tried

```<code>SELECT  (
        SELECT COUNT(*)
        FROM   table1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   table2
    ) AS count2
</code>```

but this gives

```<code>count1|count2|
 3    |3     |
</code>```

How can i get an output grouped with the color like,

```<code>|Color|count1| count2
|red  | 1    |2
|green| 1    |1
|blue |1     |0
</code>```

答:
Hi sri simply you can use union and group by</p>

```<code>select id,color, sum(coun_t) as counts from (
    (SELECT id,color,count(*) as coun_t FROM `table1` group by color)
          union
    (SELECT id,color,count(*) as coun_t FROM `table2` group by color)
 ) as p group by color order by id asc
</code>```

Body:
I have two tables with a primary key and a column(name color)

Table1
|Color|
|red  |
|green|
|blue |

Table2
|Color|
|red  |
|red  |
|green|

I tried

SELECT  (
        SELECT COUNT(*)
        FROM   table1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   table2
    ) AS count2

but this gives

count1|count2|
 3    |3     |

How can i get an output grouped with the color like,

|Color|count1| count2
|red  | 1    |2
|green| 1    |1
|blue |1     |0

Body:
Hi sri simply you can use union and group by

select id,color, sum(coun_t) as counts from (
    (SELECT id,color,count(*) as coun_t FROM `table1` group by color)
          union
    (SELECT id,color,count(*) as coun_t FROM `table2` group by color)
 ) as p group by color order by id asc


问:
Why session is invalid in the Spring controller and what is the best way for REST implementation with spring MVC?
Now I am making project with REST API for the smart flat. I am using Spring, Spring, Hibernate, MySql.
For now I have created entity for user and I faced with such exception when I try retrieve the user by my API:

Could not write JSON: could not initialize proxy - no Session;

I have found the solution how to prevent this exception by next links

JsonMappingException: could not initialize proxy - no Session

What does @Proxy(lazy = false) do?

@Proxy(lazy = false) - has solved my problem, but I realy don't understand why session is closed in the spring controller when i try to get the user?

When I persist the user - no such exception! Nevertheless that the same service is used for persisting and getting objects. How can it be?

Logic of my application is started from web.xml. I am using

org.springframework.web.servlet.DispatcherServlet

This servlet maps requests and transfer to my controller. I am using spring json message converter

org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

Configuration for spring's dispatcherServlet is

```<code> <mvc:annotation-driven/>
<context:component-scan base-package="com.smartcore.controllers.mysql"/>

    <!-- Configure to plugin JSON as request and response in method handler -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>
    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
</code>```

My Entity is simple and doesn't have any relations with othe entities

```<code>@Entity
@Table(name = "User")
//@Proxy(lazy = false)
public class UserMySql {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;

    @Column(name = "email")
    private String eMail;

    @Column(name = "login")
    private String login;

    @Column(name = "password")
    private String password;

    public UserMySql() {}

    public UserMySql(String name, String surname, String login, String password, String eMail) {
        this.name = name;
        this.surname = surname;
        this.login = login;
        this.password = password;
        this.eMail = eMail;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String geteMail() {
        return eMail;
    }

    public void seteMail(String eMail) {
        this.eMail = eMail;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("UserMySql [id=");
        sb.append(id);
        sb.append(", name=");
        sb.append(name);
        sb.append(", surname=");
        sb.append(surname);
        sb.append(", eMail=");
        sb.append(eMail);
        sb.append(", login=");
        sb.append(login);
        sb.append(", password=");
        sb.append(password);
        sb.append("]");
        return sb.toString();
    }
</code>```

Code for Controller

```<code>@RestController
public class MySqlUserAccountController {

    private UserMySqlService userMySqlService;

    @Autowired
    public MySqlUserAccountController( UserMySqlService userMySqlService) {
        this.userMySqlService = userMySqlService;
    };

    @GetMapping("/user/{userId}")
    public @ResponseBody UserMySql findUserById(@PathVariable("userId") Long userId) {
        return userMySqlService.getUserById(userId);
    }

    @PostMapping("/user/add")
    public void addUser(@RequestBody UserMySql user){
        userMySqlService.save(user);
    }

}
</code>```

I am using Spring data and it was used native methot of JpaRepository getOne(id) to retrieve user.

```<code>return this.userRepo.getOne(id);
</code>```

Also I have found the solution to use

org.springframework.orm.hibernate5.support.OpenSessionInViewFilter

But configuring filter and adding bean session has not helped.

web.xml added

```<code><servlet-mapping>
    <servlet-name>dispServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    <!-- Replace with hibernate3, hibernate4 or hibernate5 depending on the
        hibernate version one uses -->
</filter>
</code>```

application-context.xml added

```<code><bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.smartcore.entities.mysqldb"/>
          <property name="hibernateProperties">
         <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
</code>```

What is best way for implementation? and if use @Proxy(lazy = false)- that lead to live link to my object from any object contains it, can it lead to the increasing memory consumption?

In previous answers I have not found reason why session was invalidated in the controller. Could you please describe in more details what is trhe reason?

Update

I still has not solved problem with lazy loading. I found solution described here

http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/

But in my case it doesnt't work and I don't understand why ?

```<code>web.xml config

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>dispServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="com.smartcore.controllers.mysql" />
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.smartcore.mappers.json.HibernateAwareObjectMapper" />
                </property>
             </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>
</code>```

HibernateAwareObject

```<code>public class HibernateAwareObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 5371945173448137189L;

    public HibernateAwareObjectMapper() {

        this.registerModule(new Hibernate5Module());

    }

}
</code>```

In the log I don't see that my custom object will be called. It looks like something with configuration.

2017-11-17 13:58:50 DEBUG DispatcherServlet:891 - DispatcherServlet
  with name 'dispServlet' processing GET request for
  [/Smart_Core_Control/user/3] 2017-11-17 13:58:50 DEBUG
  RequestMappingHandlerMapping:313 - Looking up handler method for path
  /user/3 2017-11-17 13:58:50 DEBUG RequestMappingHandlerMapping:320 -
  Returning handler method [public
  com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]
  2017-11-17 13:58:50 DEBUG DefaultListableBeanFactory:255 - Returning
  cached instance of singleton bean 'mySqlUserAccountController'
  2017-11-17 13:58:50 DEBUG DispatcherServlet:979 - Last-Modified value
  for [/Smart_Core_Control/user/3] is: -1 2017-11-17 13:58:50 DEBUG
  TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:354
  - Adding transactional method 'getOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' 2017-11-17
  13:58:50 DEBUG DefaultListableBeanFactory:255 - Returning cached
  instance of singleton bean 'transactionManager' 2017-11-17 13:58:50
  DEBUG JpaTransactionManager:368 - Creating new transaction with name
  [org.springframework.data.jpa.repository.support.SimpleJpaRepository.getOne]:
  PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' 2017-11-17
  13:58:50 DEBUG JpaTransactionManager:391 - Opened new EntityManager
  [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0}
  updates=ExecutableList{size=0} deletions=ExecutableList{size=0}
  orphanRemovals=ExecutableList{size=0}
  collectionCreations=ExecutableList{size=0}
  collectionRemovals=ExecutableList{size=0}
  collectionUpdates=ExecutableList{size=0}
  collectionQueuedOps=ExecutableList{size=0}
  unresolvedInsertDependencies=null])] for JPA transaction 2017-11-17
  13:58:50 DEBUG DriverManagerDataSource:143 - Creating new JDBC
  DriverManager Connection to [jdbc:mysql://localhost:3306/core_data]
  Fri Nov 17 13:58:50 EET 2017 WARN: Establishing SSL connection without
  server's identity verification is not recommended. According to MySQL
  5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance
  with existing applications not using SSL the verifyServerCertificate
  property is set to 'false'. You need either to explicitly disable SSL
  by setting useSSL=false, or set useSSL=true and provide truststore for
  server certificate verification. 2017-11-17 13:58:50 DEBUG
  DataSourceUtils:176 - Setting JDBC Connection
  [com.mysql.cj.jdbc.ConnectionImpl@29154676] read-only 2017-11-17
  13:58:50 DEBUG TransactionImpl:55 - begin 2017-11-17 13:58:50 DEBUG
  JpaTransactionManager:423 - Exposing JPA transaction as JDBC
  transaction
  [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@34dcedf7]
  2017-11-17 13:58:50 DEBUG JpaTransactionManager:739 - Initiating
  transaction commit 2017-11-17 13:58:50 DEBUG JpaTransactionManager:531
  - Committing JPA transaction on EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0}
  updates=ExecutableList{size=0} deletions=ExecutableList{size=0}
  orphanRemovals=ExecutableList{size=0}
  collectionCreations=ExecutableList{size=0}
  collectionRemovals=ExecutableList{size=0}
  collectionUpdates=ExecutableList{size=0}
  collectionQueuedOps=ExecutableList{size=0}
  unresolvedInsertDependencies=null])] 2017-11-17 13:58:50 DEBUG
  TransactionImpl:66 - committing 2017-11-17 13:58:50 DEBUG
  DataSourceUtils:233 - Resetting read-only flag of JDBC Connection
  [com.mysql.cj.jdbc.ConnectionImpl@29154676] 2017-11-17 13:58:50 DEBUG
  JpaTransactionManager:622 - Closing JPA EntityManager
  [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0}
  updates=ExecutableList{size=0} deletions=ExecutableList{size=0}
  orphanRemovals=ExecutableList{size=0}
  collectionCreations=ExecutableList{size=0}
  collectionRemovals=ExecutableList{size=0}
  collectionUpdates=ExecutableList{size=0}
  collectionQueuedOps=ExecutableList{size=0}
  unresolvedInsertDependencies=null])] after transaction 2017-11-17
  13:58:50 DEBUG EntityManagerFactoryUtils:419 - Closing JPA
  EntityManager 2017-11-17 13:58:50 DEBUG
  ExceptionHandlerExceptionResolver:137 - Resolving exception from
  handler [public com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 DEBUG
  ResponseStatusExceptionResolver:137 - Resolving exception from handler
  [public com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 DEBUG
  DefaultHandlerExceptionResolver:137 - Resolving exception from handler
  [public com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 WARN
  DefaultHandlerExceptionResolver:380 - Failed to write HTTP message:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 DEBUG
  DispatcherServlet:1076 - Null ModelAndView returned to
  DispatcherServlet with name 'dispServlet': assuming HandlerAdapter
  completed request handling 2017-11-17 13:58:50 DEBUG
  DispatcherServlet:1004 - Successfully completed request

What can be wrong?

答:
You are returning an object via @Responsebody, userObject which you are returning is proxy object as you using is `LAZY' fetch. In controller layer there is no longer active transaction to fetch the properties of entity object.

You can either do EAGER fetching for of object or make declare child properties as Transient.

Body:
Now I am making project with REST API for the smart flat. I am using Spring, Spring, Hibernate, MySql.
For now I have created entity for user and I faced with such exception when I try retrieve the user by my API:

Could not write JSON: could not initialize proxy - no Session;

I have found the solution how to prevent this exception by next links

JsonMappingException: could not initialize proxy - no Session

What does @Proxy(lazy = false) do?

@Proxy(lazy = false) - has solved my problem, but I realy don't understand why session is closed in the spring controller when i try to get the user?

When I persist the user - no such exception! Nevertheless that the same service is used for persisting and getting objects. How can it be?

Logic of my application is started from web.xml. I am using

org.springframework.web.servlet.DispatcherServlet

This servlet maps requests and transfer to my controller. I am using spring json message converter

org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

Configuration for spring's dispatcherServlet is

 <mvc:annotation-driven/>
<context:component-scan base-package="com.smartcore.controllers.mysql"/>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>

My Entity is simple and doesn't have any relations with othe entities

@Entity
@Table(name = "User")
//@Proxy(lazy = false)
public class UserMySql {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;

    @Column(name = "email")
    private String eMail;

    @Column(name = "login")
    private String login;

    @Column(name = "password")
    private String password;

    public UserMySql() {}

    public UserMySql(String name, String surname, String login, String password, String eMail) {
        this.name = name;
        this.surname = surname;
        this.login = login;
        this.password = password;
        this.eMail = eMail;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String geteMail() {
        return eMail;
    }

    public void seteMail(String eMail) {
        this.eMail = eMail;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("UserMySql [id=");
        sb.append(id);
        sb.append(", name=");
        sb.append(name);
        sb.append(", surname=");
        sb.append(surname);
        sb.append(", eMail=");
        sb.append(eMail);
        sb.append(", login=");
        sb.append(login);
        sb.append(", password=");
        sb.append(password);
        sb.append("]");
        return sb.toString();
    }

Code for Controller

@RestController
public class MySqlUserAccountController {

    private UserMySqlService userMySqlService;

    @Autowired
    public MySqlUserAccountController( UserMySqlService userMySqlService) {
        this.userMySqlService = userMySqlService;
    };

    @GetMapping("/user/{userId}")
    public @ResponseBody UserMySql findUserById(@PathVariable("userId") Long userId) {
        return userMySqlService.getUserById(userId);
    }

    @PostMapping("/user/add")
    public void addUser(@RequestBody UserMySql user){
        userMySqlService.save(user);
    }

}

I am using Spring data and it was used native methot of JpaRepository getOne(id) to retrieve user.

return this.userRepo.getOne(id);

Also I have found the solution to use

org.springframework.orm.hibernate5.support.OpenSessionInViewFilter

But configuring filter and adding bean session has not helped.

web.xml added

<servlet-mapping>
    <servlet-name>dispServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>

</filter>

application-context.xml added

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.smartcore.entities.mysqldb"/>
          <property name="hibernateProperties">
         <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

What is best way for implementation? and if use @Proxy(lazy = false)- that lead to live link to my object from any object contains it, can it lead to the increasing memory consumption?

In previous answers I have not found reason why session was invalidated in the controller. Could you please describe in more details what is trhe reason?

Update

I still has not solved problem with lazy loading. I found solution described here

http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/

But in my case it doesnt't work and I don't understand why ?

web.xml config

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <servlet>
        <servlet-name>dispServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="com.smartcore.controllers.mysql" />
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.smartcore.mappers.json.HibernateAwareObjectMapper" />
                </property>
             </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>

HibernateAwareObject

public class HibernateAwareObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 5371945173448137189L;

    public HibernateAwareObjectMapper() {

        this.registerModule(new Hibernate5Module());

    }

}

In the log I don't see that my custom object will be called. It looks like something with configuration.

2017-11-17 13:58:50 DEBUG DispatcherServlet:891 - DispatcherServlet
  with name 'dispServlet' processing GET request for
  [/Smart_Core_Control/user/3] 2017-11-17 13:58:50 DEBUG
  RequestMappingHandlerMapping:313 - Looking up handler method for path
  /user/3 2017-11-17 13:58:50 DEBUG RequestMappingHandlerMapping:320 -
  Returning handler method [public
  com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]
  2017-11-17 13:58:50 DEBUG DefaultListableBeanFactory:255 - Returning
  cached instance of singleton bean 'mySqlUserAccountController'
  2017-11-17 13:58:50 DEBUG DispatcherServlet:979 - Last-Modified value
  for [/Smart_Core_Control/user/3] is: -1 2017-11-17 13:58:50 DEBUG
  TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:354
  - Adding transactional method 'getOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' 2017-11-17
  13:58:50 DEBUG DefaultListableBeanFactory:255 - Returning cached
  instance of singleton bean 'transactionManager' 2017-11-17 13:58:50
  DEBUG JpaTransactionManager:368 - Creating new transaction with name
  [org.springframework.data.jpa.repository.support.SimpleJpaRepository.getOne]:
  PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' 2017-11-17
  13:58:50 DEBUG JpaTransactionManager:391 - Opened new EntityManager
  [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0}
  updates=ExecutableList{size=0} deletions=ExecutableList{size=0}
  orphanRemovals=ExecutableList{size=0}
  collectionCreations=ExecutableList{size=0}
  collectionRemovals=ExecutableList{size=0}
  collectionUpdates=ExecutableList{size=0}
  collectionQueuedOps=ExecutableList{size=0}
  unresolvedInsertDependencies=null])] for JPA transaction 2017-11-17
  13:58:50 DEBUG DriverManagerDataSource:143 - Creating new JDBC
  DriverManager Connection to [jdbc:mysql://localhost:3306/core_data]
  Fri Nov 17 13:58:50 EET 2017 WARN: Establishing SSL connection without
  server's identity verification is not recommended. According to MySQL
  5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance
  with existing applications not using SSL the verifyServerCertificate
  property is set to 'false'. You need either to explicitly disable SSL
  by setting useSSL=false, or set useSSL=true and provide truststore for
  server certificate verification. 2017-11-17 13:58:50 DEBUG
  DataSourceUtils:176 - Setting JDBC Connection
  [com.mysql.cj.jdbc.ConnectionImpl@29154676] read-only 2017-11-17
  13:58:50 DEBUG TransactionImpl:55 - begin 2017-11-17 13:58:50 DEBUG
  JpaTransactionManager:423 - Exposing JPA transaction as JDBC
  transaction
  [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@34dcedf7]
  2017-11-17 13:58:50 DEBUG JpaTransactionManager:739 - Initiating
  transaction commit 2017-11-17 13:58:50 DEBUG JpaTransactionManager:531
  - Committing JPA transaction on EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0}
  updates=ExecutableList{size=0} deletions=ExecutableList{size=0}
  orphanRemovals=ExecutableList{size=0}
  collectionCreations=ExecutableList{size=0}
  collectionRemovals=ExecutableList{size=0}
  collectionUpdates=ExecutableList{size=0}
  collectionQueuedOps=ExecutableList{size=0}
  unresolvedInsertDependencies=null])] 2017-11-17 13:58:50 DEBUG
  TransactionImpl:66 - committing 2017-11-17 13:58:50 DEBUG
  DataSourceUtils:233 - Resetting read-only flag of JDBC Connection
  [com.mysql.cj.jdbc.ConnectionImpl@29154676] 2017-11-17 13:58:50 DEBUG
  JpaTransactionManager:622 - Closing JPA EntityManager
  [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0}
  updates=ExecutableList{size=0} deletions=ExecutableList{size=0}
  orphanRemovals=ExecutableList{size=0}
  collectionCreations=ExecutableList{size=0}
  collectionRemovals=ExecutableList{size=0}
  collectionUpdates=ExecutableList{size=0}
  collectionQueuedOps=ExecutableList{size=0}
  unresolvedInsertDependencies=null])] after transaction 2017-11-17
  13:58:50 DEBUG EntityManagerFactoryUtils:419 - Closing JPA
  EntityManager 2017-11-17 13:58:50 DEBUG
  ExceptionHandlerExceptionResolver:137 - Resolving exception from
  handler [public com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 DEBUG
  ResponseStatusExceptionResolver:137 - Resolving exception from handler
  [public com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 DEBUG
  DefaultHandlerExceptionResolver:137 - Resolving exception from handler
  [public com.smartcore.entities.mysqldb.UserMySql
  com.smartcore.controllers.mysql.MySqlUserAccountController.findUserById(java.lang.Long)]:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 WARN
  DefaultHandlerExceptionResolver:380 - Failed to write HTTP message:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: could not initialize proxy - no Session; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  could not initialize proxy - no Session 2017-11-17 13:58:50 DEBUG
  DispatcherServlet:1076 - Null ModelAndView returned to
  DispatcherServlet with name 'dispServlet': assuming HandlerAdapter
  completed request handling 2017-11-17 13:58:50 DEBUG
  DispatcherServlet:1004 - Successfully completed request

What can be wrong?


问:
Decode Xml to mxGraph .Net
I want to execute an operation that is an inversion of what i do when forming xmlString in mxGraph().

```<code>mxGraph graph = new mxGraph();
        Object parent = graph.GetDefaultParent();

        graph.Model.BeginUpdate();
        try
        {
            Object v1 = graph.InsertVertex(parent, null, "Hello,", 20, 20, 80, 30);
            Object v2 = graph.InsertVertex(parent, null, "World!", 200, 150, 80, 30);
            Object e1 = graph.InsertEdge(parent, null, "Edge", v1, v2);
        }
        finally
        {
            graph.Model.EndUpdate();
        }

        mxCodec codec = new mxCodec();
        Xml = mxUtils.GetXml(codec.Encode(graph.Model));
        var xmlString = mxUtils.GetXml(xml);
</code>```

I'm trying to execute inverse operation.

```<code>        XmlDocument doc = mxUtils.ParseXml(xmlString);

        mxGraph graphNew = new mxGraph();

        var decoder = new mxCodec(doc);

        decoder.Decode(doc, graphNew.Model);

        Object parentNew = graphNew.GetDefaultParent();
</code>```

But the object "parentNew" has no children.

答:
I just encountered this myself and was able to solve it.

```<code>decoder.Decode(doc, graphNew.Model);
</code>```

should be:

```<code>decoder.Decode(doc.DocumentElement, graphNew.getModel());
</code>```

In addition to doc.DocumentElement, you also need to use graphNew.getModel(), not just graphNew.model.

As per this documentation

Also, you do not need to create a new graph. Insert your existing graph into the second parameter of Decode.

Title: Decode Xml to mxGraph .Net

Body:
I want to execute an operation that is an inversion of what i do when forming xmlString in mxGraph().

mxGraph graph = new mxGraph();
        Object parent = graph.GetDefaultParent();

        graph.Model.BeginUpdate();
        try
        {
            Object v1 = graph.InsertVertex(parent, null, "Hello,", 20, 20, 80, 30);
            Object v2 = graph.InsertVertex(parent, null, "World!", 200, 150, 80, 30);
            Object e1 = graph.InsertEdge(parent, null, "Edge", v1, v2);
        }
        finally
        {
            graph.Model.EndUpdate();
        }

        mxCodec codec = new mxCodec();
        Xml = mxUtils.GetXml(codec.Encode(graph.Model));
        var xmlString = mxUtils.GetXml(xml);

I'm trying to execute inverse operation.

        XmlDocument doc = mxUtils.ParseXml(xmlString);

        mxGraph graphNew = new mxGraph();

        var decoder = new mxCodec(doc);

        decoder.Decode(doc, graphNew.Model);

        Object parentNew = graphNew.GetDefaultParent();

But the object "parentNew" has no children.

Body:
I just encountered this myself and was able to solve it.

decoder.Decode(doc, graphNew.Model);

should be:

decoder.Decode(doc.DocumentElement, graphNew.getModel());

In addition to doc.DocumentElement, you also need to use graphNew.getModel(), not just graphNew.model.

As per this documentation

Also, you do not need to create a new graph. Insert your existing graph into the second parameter of Decode.

ContentLicense: CC BY-SA 4.0


问:
git branch lost in a directory and cannot pull
I have a project repository on GitLab. It has two directories Test and Actility

I have two branches on this project : master and lme-dev.

When I use the command git branch in the folder containing the two directories, it shows :

```<code>* lme-dev
  master
</code>```

When I use the command git branch in the folder Actility, it only shows one branch :

```<code>* master
</code>```

When I use the command git pull in the folder Actility, it prompts :

GitLab: The project you were looking for could not be found. fatal:
  Could not read from remote repository.

Please make sure you have the correct access rights and the repository
  exists.

I know I have already committed changes in this folder. On GitLab I can see the directory in the project... How is that possible that for the same project, I have access to one directory and not the other one ?

答: You have an extra .git sub-folder in your Actility folder. Just remove it or move it elsewhere outside of the repository.</p>

Body:
I have a project repository on GitLab. It has two directories Test and Actility

I have two branches on this project : master and lme-dev.

When I use the command git branch in the folder containing the two directories, it shows :

* lme-dev
  master

When I use the command git branch in the folder Actility, it only shows one branch :

* master

When I use the command git pull in the folder Actility, it prompts :

GitLab: The project you were looking for could not be found. fatal:
  Could not read from remote repository.

Please make sure you have the correct access rights and the repository
  exists.

I know I have already committed changes in this folder. On GitLab I can see the directory in the project... How is that possible that for the same project, I have access to one directory and not the other one ?


问:
Get linkedin Access Token with JavaScript SDK
I am working on that application allow user to connect to linkedin (using javascript). I want to store access token that I got from IN.ENV.auth.oauth_token because I will use it to post to user's timeline.

But when I use this access token to post to Linkedin, I got "Invalid access token" error.
Did I use correct access token? How's the correct way to get Access token?

Here's my code:

```<code>$("#linkedin-connect").on('click',function(e){
    e.preventDefault();
    IN.UI.Authorize().place();
    IN.Event.on(IN, "auth", OnLinkedInAuth);
    return false;
});

function OnLinkedInAuth() {
    console.debug("oauth token:" + IN.ENV.auth.oauth_token);
}
</code>```

JSFiddle Example

答:
this event IN.Event.on(IN, "auth", OnLinkedInAuth); should pass some data to your function OnLikedInAuth as in shown in the documentation of the sdk.

```<code><script type="text/javascript" src="//platform.linkedin.com/in.js">
    api_key: YOUR_API_KEY_HERE
    authorize: true
    onLoad: onLinkedInLoad
</script>

<script type="text/javascript">

// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
    IN.Event.on(IN, "auth", getProfileData);
}

// Handle the successful return from the API call
function onSuccess(data) {
    console.log(data);
}

// Handle an error response from the API call
function onError(error) {
    console.log(error);
}

// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
    IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
</code>```

As that example (available in docs) the getProfileData (similar to your OnLinkedInAuth) returns a Promise and when it's resolved will give you some data that you need to read. In that object you will find the token that you can store (LocalStorage) and use

Body:
I am working on that application allow user to connect to linkedin (using javascript). I want to store access token that I got from IN.ENV.auth.oauth_token because I will use it to post to user's timeline.

But when I use this access token to post to Linkedin, I got "Invalid access token" error.
Did I use correct access token? How's the correct way to get Access token?

Here's my code:

$("#linkedin-connect").on('click',function(e){
    e.preventDefault();
    IN.UI.Authorize().place();
    IN.Event.on(IN, "auth", OnLinkedInAuth);
    return false;
});

function OnLinkedInAuth() {
    console.debug("oauth token:" + IN.ENV.auth.oauth_token);
}

JSFiddle Example

Body:
this event IN.Event.on(IN, "auth", OnLinkedInAuth); should pass some data to your function OnLikedInAuth as in shown in the documentation of the sdk.

<script type="text/javascript" src="//platform.linkedin.com/in.js">
    api_key: YOUR_API_KEY_HERE
    authorize: true
    onLoad: onLinkedInLoad
</script>

<script type="text/javascript">

// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
    IN.Event.on(IN, "auth", getProfileData);
}

// Handle the successful return from the API call
function onSuccess(data) {
    console.log(data);
}

// Handle an error response from the API call
function onError(error) {
    console.log(error);
}

// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
    IN.API.Raw("/people/~").result(onSuccess).error(onError);
}

As that example (available in docs) the getProfileData (similar to your OnLinkedInAuth) returns a Promise and when it's resolved will give you some data that you need to read. In that object you will find the token that you can store (LocalStorage) and use


问:
How to simulate a touch event in Android?
How to simulate a touch event with Android while giving the X and Y coordinates manually?</p>

答:
Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.</p>

```<code># This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# Connects to the current device
device = MonkeyRunner.waitForConnection()

# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2

for i in range(1, 250):
    # Every so often inject a touch to spice things up!
    if i % 9 == 0:
        device.touch(x2, y, 'DOWN_AND_UP')
        MonkeyRunner.sleep(pause)
    # Swipe right
    device.drag(start, end, duration, steps)
    MonkeyRunner.sleep(pause)
    # Swipe left
    device.drag(end, start, duration, steps)
    MonkeyRunner.sleep(pause)
</code>```

Body:
Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.

# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# Connects to the current device
device = MonkeyRunner.waitForConnection()

# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2

for i in range(1, 250):
    # Every so often inject a touch to spice things up!
    if i % 9 == 0:
        device.touch(x2, y, 'DOWN_AND_UP')
        MonkeyRunner.sleep(pause)
    # Swipe right
    device.drag(start, end, duration, steps)
    MonkeyRunner.sleep(pause)
    # Swipe left
    device.drag(end, start, duration, steps)
    MonkeyRunner.sleep(pause)

ContentLicense: CC BY-SA 2.5


问:
what does (<typeof className>this.constructor) mean in typescript?
when I see sourceCode of jQTree(https://github.com/mbraak/jqTree) , which is write in Typescript; I saw this:

export default class SimpleWidget{
    protected static defaults = {};
    public options:any
    protected $el : JQuery

    constructor(el:Element,options:any){
        this.$el = $(el);
        console.log(typeof SimpleWidget)
        let defaults = (<typeof SimpleWidget>this.constructor).defaults;
        console.log(defaults)
        this.options = $.extend({},defaults,options);
    }
}```

what does (this.constructor) mean? How can It get the static after Assertion?

答:
This class will compile to a constructor function, with the static property attached directly to it:

```<code>function SimpleWidget(el, options) { ... }

SimpleWidget.defaults = {};
</code>```

Child classes would define their own defaults:

```<code>class DerivedWidget extends SimpleWidget {
  protected static defaults = { prop: 'derived default' };
}
</code>```

which would compile to:

```<code>DerivedWidget.defaults = { prop: 'derived default' };
</code>```

So the parent will want to access the child's static defaults, which it wouldn't get it if accessed SimpleWidget.defaults. But it can access this.constructor.defaults, which is dynamic.

Body:
when I see sourceCode of jQTree(https://github.com/mbraak/jqTree) , which is write in Typescript; I saw this:

export default class SimpleWidget{
    protected static defaults = {};
    public options:any
    protected $el : JQuery

    constructor(el:Element,options:any){
        this.$el = $(el);
        console.log(typeof SimpleWidget)
        let defaults = (<typeof SimpleWidget>this.constructor).defaults;
        console.log(defaults)
        this.options = $.extend({},defaults,options);
    }
}

what does (this.constructor) mean? How can It get the static after Assertion?

Body:
This class will compile to a constructor function, with the static property attached directly to it:

function SimpleWidget(el, options) { ... }

SimpleWidget.defaults = {};

Child classes would define their own defaults:

class DerivedWidget extends SimpleWidget {
  protected static defaults = { prop: 'derived default' };
}

which would compile to:

DerivedWidget.defaults = { prop: 'derived default' };

So the parent will want to access the child's static defaults, which it wouldn't get it if accessed SimpleWidget.defaults. But it can access this.constructor.defaults, which is dynamic.


问:
How to solve this "Synchronize on a new "Object" instead. "
I am getting the warning in sonar at line synchronized (new Integer(count)) as
Synchronize on a new "Object" instead.  </p>

```<code>public class PRMDataTransferHelper {

    /** static variable to keep count */
    private static int count = 0;

    private static void done() {

        synchronized (new Integer(count)) {
            count--;

            if (0 == count) {
                cleanUp();
            }
        }

        return;
    }

}
</code>```

答:
There are two problems here:

As Sonar states, you shouldn't synchronize on a primitive wrapper (i.e. Integer, Long, Boolean, etc.) since these can be created by autoboxing, and Sonar assumes that this is risky. It is risky because a lock object used in a synchronized statement should be constant among all threads that are to be synchronized. Any dynamic object that may be re-used in the program logic can easily lead to failed synchronization. Therefore, it is best practise to instantiate Object and create a special lock object that is used for synchronization only.

You are using new Integer(count), i.e. whenever the synchronized block is entered, a new instance of integer is created. This means that each thread will see its own version of a lock object, and thus the block will not be synchronized between threads at all. In order to achieve synchronization, you need to re-use a lock object shared by all threads.

In your case, having a static variable such as

```<code>private static Object lock=new Object();
</code>```

and using this one in synchronized(lock) would ensure that all threads are indeed synchronized at the beginning of the block.

Body:
I am getting the warning in sonar at line synchronized (new Integer(count)) as
Synchronize on a new "Object" instead.

public class PRMDataTransferHelper {

    /** static variable to keep count */
    private static int count = 0;

    private static void done() {

        synchronized (new Integer(count)) {
            count--;

            if (0 == count) {
                cleanUp();
            }
        }

        return;
    }

}

Body:
There are two problems here:

As Sonar states, you shouldn't synchronize on a primitive wrapper (i.e. Integer, Long, Boolean, etc.) since these can be created by autoboxing, and Sonar assumes that this is risky. It is risky because a lock object used in a synchronized statement should be constant among all threads that are to be synchronized. Any dynamic object that may be re-used in the program logic can easily lead to failed synchronization. Therefore, it is best practise to instantiate Object and create a special lock object that is used for synchronization only.

You are using new Integer(count), i.e. whenever the synchronized block is entered, a new instance of integer is created. This means that each thread will see its own version of a lock object, and thus the block will not be synchronized between threads at all. In order to achieve synchronization, you need to re-use a lock object shared by all threads.

In your case, having a static variable such as

private static Object lock=new Object();

and using this one in synchronized(lock) would ensure that all threads are indeed synchronized at the beginning of the block.


问:
How can view depends on primary key constraint in postgres
Sometimes while bulk data loading it's recommended to temporary drop constraints and indexes on table. But when I am doing this I faced with some problems with dependency. My simplified example:

```<code>CREATE TABLE public.t_place_type
(
  id serial NOT NULL,
  c_name character varying(100),
  CONSTRAINT pk_t_place_type PRIMARY KEY (id)
);

CREATE TABLE public.t_place
(
  id serial NOT NULL,
  c_name character varying(50),
  id_place_type integer,
  CONSTRAINT pk_t_place PRIMARY KEY (id),
  CONSTRAINT fk_t_place_t_place_type FOREIGN KEY (id_place_type)
      REFERENCES public.t_place_type (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

CREATE OR REPLACE VIEW public.v_place AS
 SELECT p.id,
    p.c_name,
    pt.c_name AS c_place_type
   FROM t_place p
     LEFT JOIN t_place_type pt ON pt.id = p.id_place_type
  GROUP BY p.id, pt.id, p.c_name;
</code>```

My script:

```<code>ALTER TABLE public.t_place DROP CONSTRAINT fk_t_place_t_place_type;
ALTER TABLE public.t_place DROP CONSTRAINT pk_t_place;
ALTER TABLE public.t_place_type DROP CONSTRAINT pk_t_place_type;
</code>```

When I run it I am getting error:

ERROR:  cannot drop constraint pk_t_place_type on table t_place_type
  because other objects depend on it
  DETAIL:  view v_place depends on constraint pk_t_place_type on table
  t_place_type

It's strange to me that view can depends on some constraint. AFAIK postgres does not cache execution plan for a view.

When I change my view this way:

```<code>CREATE OR REPLACE VIEW public.v_place AS
 SELECT p.id,
    p.c_name AS c_name,
    pt.c_name AS c_place_type
   FROM t_place p
     LEFT JOIN t_place_type pt ON pt.id = p.id_place_type;
</code>```

the dependency is gone and my script executes successfully.

So my question is: What is the reason for this dependency between view and constraint.

EDIT

Here https://www.postgresql.org/docs/9.5/static/sql-select.html#SQL-GROUPBY postgres docs say:

When GROUP BY is present, or any aggregate functions are present, it
  is not valid for the SELECT list expressions to refer to ungrouped
  columns except within aggregate functions or when the ungrouped column
  is functionally dependent on the grouped columns, since there would
  otherwise be more than one possible value to return for an ungrouped
  column. A functional dependency exists if the grouped columns (or a
  subset thereof) are the primary key of the table containing the
  ungrouped column.

Is this a reason for such behavior? Even though I have no ungrouped columns in my view?

答:
Your query from view will not work if you drop PK on public.t_place_type.

It will produce this error:

```<code>ERROR:  column "pt.c_name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3:     pt.c_name AS c_place_type
            ^
</code>```

That is because, from your documentation citation, A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

Postgres knows that PK represents unique row, so once you group by it you might as well group by all columns from that table and get the same result.

Those give the same result, with is ungrouped rows:

```<code>SELECT * FROM public.t_place;
SELECT * FROM public.t_place GROUP BY id;
SELECT * FROM public.t_place GROUP BY id, c_name;
SELECT * FROM public.t_place GROUP BY id, c_name, id_place_type;
SELECT * FROM public.t_place GROUP BY id, id_place_type;
</code>```

And you are using this dependency while selecting pt.c_name AS c_place_type, because you grouped that table by primary key pt.id, with is non existent PK once you drop it, so grouping by it makes pt.c_name both not used in aggregate and not used in group by. And that is why Postgres complains about view dependency - its query will not work anymore once you drop this PK.

You can try it yourself with modified example from your question:

```<code>CREATE TABLE public.t_place_type
(
  id serial NOT NULL,
  c_name character varying(100)
);

CREATE TABLE public.t_place
(
  id serial NOT NULL,
  c_name character varying(50),
  id_place_type integer,
  CONSTRAINT pk_t_place PRIMARY KEY (id)
);

 SELECT p.id,
    p.c_name,
    pt.c_name AS c_place_type
   FROM t_place p
     LEFT JOIN t_place_type pt ON pt.id = p.id_place_type
  GROUP BY p.id, pt.id, p.c_name;

/* RESULT:
ERROR:  column "pt.c_name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3:     pt.c_name AS c_place_type
            ^
*/
</code>```

Body:
Sometimes while bulk data loading it's recommended to temporary drop constraints and indexes on table. But when I am doing this I faced with some problems with dependency. My simplified example:

CREATE TABLE public.t_place_type
(
  id serial NOT NULL,
  c_name character varying(100),
  CONSTRAINT pk_t_place_type PRIMARY KEY (id)
);

CREATE TABLE public.t_place
(
  id serial NOT NULL,
  c_name character varying(50),
  id_place_type integer,
  CONSTRAINT pk_t_place PRIMARY KEY (id),
  CONSTRAINT fk_t_place_t_place_type FOREIGN KEY (id_place_type)
      REFERENCES public.t_place_type (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

CREATE OR REPLACE VIEW public.v_place AS
 SELECT p.id,
    p.c_name,
    pt.c_name AS c_place_type
   FROM t_place p
     LEFT JOIN t_place_type pt ON pt.id = p.id_place_type
  GROUP BY p.id, pt.id, p.c_name;

My script:

ALTER TABLE public.t_place DROP CONSTRAINT fk_t_place_t_place_type;
ALTER TABLE public.t_place DROP CONSTRAINT pk_t_place;
ALTER TABLE public.t_place_type DROP CONSTRAINT pk_t_place_type;

When I run it I am getting error:

ERROR:  cannot drop constraint pk_t_place_type on table t_place_type
  because other objects depend on it
  DETAIL:  view v_place depends on constraint pk_t_place_type on table
  t_place_type

It's strange to me that view can depends on some constraint. AFAIK postgres does not cache execution plan for a view.

When I change my view this way:

CREATE OR REPLACE VIEW public.v_place AS
 SELECT p.id,
    p.c_name AS c_name,
    pt.c_name AS c_place_type
   FROM t_place p
     LEFT JOIN t_place_type pt ON pt.id = p.id_place_type;

the dependency is gone and my script executes successfully.

So my question is: What is the reason for this dependency between view and constraint.

EDIT

Here https://www.postgresql.org/docs/9.5/static/sql-select.html#SQL-GROUPBY postgres docs say:

When GROUP BY is present, or any aggregate functions are present, it
  is not valid for the SELECT list expressions to refer to ungrouped
  columns except within aggregate functions or when the ungrouped column
  is functionally dependent on the grouped columns, since there would
  otherwise be more than one possible value to return for an ungrouped
  column. A functional dependency exists if the grouped columns (or a
  subset thereof) are the primary key of the table containing the
  ungrouped column.

Is this a reason for such behavior? Even though I have no ungrouped columns in my view?

Body:
Your query from view will not work if you drop PK on public.t_place_type.

It will produce this error:

ERROR:  column "pt.c_name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3:     pt.c_name AS c_place_type
            ^

That is because, from your documentation citation, A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

Postgres knows that PK represents unique row, so once you group by it you might as well group by all columns from that table and get the same result.

Those give the same result, with is ungrouped rows:

SELECT * FROM public.t_place;
SELECT * FROM public.t_place GROUP BY id;
SELECT * FROM public.t_place GROUP BY id, c_name;
SELECT * FROM public.t_place GROUP BY id, c_name, id_place_type;
SELECT * FROM public.t_place GROUP BY id, id_place_type;

And you are using this dependency while selecting pt.c_name AS c_place_type, because you grouped that table by primary key pt.id, with is non existent PK once you drop it, so grouping by it makes pt.c_name both not used in aggregate and not used in group by. And that is why Postgres complains about view dependency - its query will not work anymore once you drop this PK.

You can try it yourself with modified example from your question:

CREATE TABLE public.t_place_type
(
  id serial NOT NULL,
  c_name character varying(100)
);

CREATE TABLE public.t_place
(
  id serial NOT NULL,
  c_name character varying(50),
  id_place_type integer,
  CONSTRAINT pk_t_place PRIMARY KEY (id)
);

 SELECT p.id,
    p.c_name,
    pt.c_name AS c_place_type
   FROM t_place p
     LEFT JOIN t_place_type pt ON pt.id = p.id_place_type
  GROUP BY p.id, pt.id, p.c_name;

/* RESULT:
ERROR:  column "pt.c_name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3:     pt.c_name AS c_place_type
            ^
*/


问:
IBOutlets and IBactions require ! in the end
I tried to start and go from Obj-C to Swift today and I was reading the documentation. I tried to create an easy IBOutlet in Swift and it constantly gave me those errors.

View Controller has no initialiser

required init(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented") }

IBOutletproperty has non-optional type 'UILabel'

and that constantly pops up with this code:

@IBOutlet var outputLabel : UILabel

but when I add an ! mark, it's running without errors like so

@IBOutlet var outputLabel : UILabel!

Same thing happens for IBActions...

答: When views or view controllers are initialized from an interface builder file, their outlets cannot be connected yet. They will only be connected after initialization, so they need to be optional. When any other code in the class is called after initialization, though, these outlets are guaranteed to be connected. This is why IBOutlets are always declared as implicitly unwrapped optionals.</p>


问:
Heroku Upload - Could not find a version that satisfies the requirement anaconda-client==1.4.0
I'm trying to push a Django app onto Heroku, but am getting the following error upon running git push heroku master:

```<code>Counting objects: 80, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (74/74), done.
Writing objects: 100% (80/80), 990.21 KiB | 0 bytes/s, done.
Total 80 (delta 20), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote:  !     The latest version of Python 2 is python-2.7.14 (you are using
python-2.7.12, which is unsupported).
remote:  !     We recommend upgrading by specifying the latest version
(python-2.7.14).
remote:        Learn More: https://devcenter.heroku.com/articles/python-
runtimes
remote: -----> Installing python-2.7.12
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote:        Collecting alabaster==0.7.7 (from -r
/tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 1))
remote:          Downloading alabaster-0.7.7-py2.py3-none-any.whl
remote:        Collecting anaconda-client==1.4.0 (from -r
/tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2))
remote:          Could not find a version that satisfies the requirement
anaconda-client==1.4.0 (from -r
/tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2)) (from
versions: 1.1.1, 1.2.2)
remote:        No matching distribution found for anaconda-client==1.4.0 (from
-r /tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2))
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to demo-freshstart.
</code>```

Seems like it has something to do with Anaconda, but I see Anaconda pretty early on in my requirements.txt, so thinking it could just be the first thing it's getting caught up on for some other reason.

答: According to PyPI, there's no such thing as anaconda-client version 1.4.0: the highest version is 1.2.2.</p>

Body:
I'm trying to push a Django app onto Heroku, but am getting the following error upon running git push heroku master:

Counting objects: 80, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (74/74), done.
Writing objects: 100% (80/80), 990.21 KiB | 0 bytes/s, done.
Total 80 (delta 20), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote:  !     The latest version of Python 2 is python-2.7.14 (you are using
python-2.7.12, which is unsupported).
remote:  !     We recommend upgrading by specifying the latest version
(python-2.7.14).
remote:        Learn More: https://devcenter.heroku.com/articles/python-
runtimes
remote: -----> Installing python-2.7.12
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote:        Collecting alabaster==0.7.7 (from -r
/tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 1))
remote:          Downloading alabaster-0.7.7-py2.py3-none-any.whl
remote:        Collecting anaconda-client==1.4.0 (from -r
/tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2))
remote:          Could not find a version that satisfies the requirement
anaconda-client==1.4.0 (from -r
/tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2)) (from
versions: 1.1.1, 1.2.2)
remote:        No matching distribution found for anaconda-client==1.4.0 (from
-r /tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2))
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to demo-freshstart.

Seems like it has something to do with Anaconda, but I see Anaconda pretty early on in my requirements.txt, so thinking it could just be the first thing it's getting caught up on for some other reason.


问:
Stuck with my query
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

```<code>select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;
</code>```

Where am I making the mistake?

Thanks in advance!

答:
```<code>select
      name
    , sal
    , max_sal - sal as diff
from (
     select
          e.ename
        , e.sal
        , max(salary) over() as max_sal
     from emp e
     ) d
</code>```

I suggest using max(salary) over() analytic (or window) function which places the maximum salary on every row of the subquery, then it is a simple subtraction to calculate the difference. No group by clause is required in this form of aggregate.

Title: Stuck with my query

Body:
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;

Where am I making the mistake?

Thanks in advance!

Body:
select
      name
    , sal
    , max_sal - sal as diff
from (
     select
          e.ename
        , e.sal
        , max(salary) over() as max_sal
     from emp e
     ) d

I suggest using max(salary) over() analytic (or window) function which places the maximum salary on every row of the subquery, then it is a simple subtraction to calculate the difference. No group by clause is required in this form of aggregate.


问:
How to change the order of words with alphabetic order
I got a dataset with a list of keywords (1 keyword / row).

I m looking for a way to create a new column (ALPHABETICAL) based on the KEYWORD column. The value of the ALPHABETICAL column should be auto generated based on the keyword, but words should be ordered alphabetically.

Like this :

```<code> | KEYWORD            | ALPHABETICAL       |
 | house blue         | blue house         |
 | blue house         | blue house         |
 | my blue house      | blue house my      |
 | this house is blue | blue house is this |
 | sky orange         | orange sky         |
 | orange sky         | orange sky         |
 | the orange sky     | orange sky the     |
</code>```

Thanks for your help!

答:
One solution with dplyr + stringr

```<code>library(dplyr)
library(stringr)
KEYWORDS  <- c('house blue','blue house','my blue house','this house is blue','sky orange','orange sky','the orange sky')

ALPHABETICAL <- KEYWORDS %>% str_split(., ' ') %>% lapply(., 'sort') %>%  lapply(., 'paste', collapse=' ') %>% unlist(.)
</code>```

The last line uses str_split() to split the KEYWORDS into a list of vectors; sort is then applied to each list element; the vectors are concatenated using paste, and finally the list is broken into a vector.

The result is

```<code>> cbind(KEYWORDS, ALPHABETICAL)
     KEYWORDS             ALPHABETICAL
[1,] "house blue"         "blue house"
[2,] "blue house"         "blue house"
[3,] "my blue house"      "blue house my"
[4,] "this house is blue" "blue house is this"
[5,] "sky orange"         "orange sky"
[6,] "orange sky"         "orange sky"
[7,] "the orange sky"     "orange sky the"
</code>```

Body:
I got a dataset with a list of keywords (1 keyword / row).

I m looking for a way to create a new column (ALPHABETICAL) based on the KEYWORD column. The value of the ALPHABETICAL column should be auto generated based on the keyword, but words should be ordered alphabetically.

Like this :

 | KEYWORD            | ALPHABETICAL       |
 | house blue         | blue house         |
 | blue house         | blue house         |
 | my blue house      | blue house my      |
 | this house is blue | blue house is this |
 | sky orange         | orange sky         |
 | orange sky         | orange sky         |
 | the orange sky     | orange sky the     |

Thanks for your help!

Body:
One solution with dplyr + stringr

library(dplyr)
library(stringr)
KEYWORDS  <- c('house blue','blue house','my blue house','this house is blue','sky orange','orange sky','the orange sky')

ALPHABETICAL <- KEYWORDS %>% str_split(., ' ') %>% lapply(., 'sort') %>%  lapply(., 'paste', collapse=' ') %>% unlist(.)

The last line uses str_split() to split the KEYWORDS into a list of vectors; sort is then applied to each list element; the vectors are concatenated using paste, and finally the list is broken into a vector.

The result is

> cbind(KEYWORDS, ALPHABETICAL)
     KEYWORDS             ALPHABETICAL
[1,] "house blue"         "blue house"
[2,] "blue house"         "blue house"
[3,] "my blue house"      "blue house my"
[4,] "this house is blue" "blue house is this"
[5,] "sky orange"         "orange sky"
[6,] "orange sky"         "orange sky"
[7,] "the orange sky"     "orange sky the"


答:
```<code>select e.ename,
       e.sal sal_of_others,
      (select max(sal) from emp where ename = e.ename ) - e.sal sal_diff
  from emp e
</code>```

Title: Stuck with my query


问:
(mongoDB) find with empty or null values
how to make a mongodb collection find (db.collection.find) with empty values?

currently i have:

```<code>function test(s) {
    if (!s) {
        return null;
    } else {
        return s;
    }
}

var content = {
    date: {
        from: '2017-10-15',
        to: '2017-11-15'
    },

    'name': 'some text', //this can be null or empty
    'text': 'some other text' //this can be null or empty
}

col.find({
    "date": {
        $gte: new Date(content.date.from),
        $lte: new Date(content.date.to)
    },

    "name": {
        $ne: {
            $type: null
        },

        $eq: test(content.name)
    },

    "text": {
        $ne: {
            $type: null
        },

        $eq: test(content.text)
    },
}).toArray((err, items) => {
    console.log(items)
});
</code>```

but it returns an empty array, because "name" or "text" is null / an empty string,
i want that it query only the values that have something specified or ignore it (like content.name is something in it or its empty)

how do i get it? i already searched ... but didnt found something

thanks!

( already testet mongoDB : multi value field search ignoring null fields)

Versions:
Node: 8.9.0
(npm) mongodb: 2.2.33
mongodb: 3.4

答:
```<code>col.find({
    $and: [
        {
            $and: [
                {
                    "date": {
                        $gte: new Date(content.date.from)
                    }
                },
                {
                    "date": {
                        $lte: new Date(content.date.to)
                    }
                },
            ]
        },
        {
            $or: [
                { 'name': null },
                { 'name': content.name }
            ]
        },
        {
            $or: [
                { 'text': null },
                { 'text': content.text }
            ]
        }
    ]
})
</code>```

Edited:

```<code>col.find({
    $and: [
        {
            $and: [
                {
                    "date": {
                        $gte: new Date(content.date.from)
                    }
                },
                {
                    "date": {
                        $lte: new Date(content.date.to)
                    }
                },
            ]
        },
        {
            $or: [
                { 'name': null },
                { 'name':'' }
                { 'name': content.name }
            ]
        },
        {
            $or: [
                { 'text': null },
                { 'text': '' },
                { 'text': content.text }
            ]
        }
    ]
})
</code>```

null and empty is different, you need to add one more condition for empty string in query.

Logical Query Operators

Body:
how to make a mongodb collection find (db.collection.find) with empty values?

currently i have:

function test(s) {
    if (!s) {
        return null;
    } else {
        return s;
    }
}

var content = {
    date: {
        from: '2017-10-15',
        to: '2017-11-15'
    },

    'name': 'some text', //this can be null or empty
    'text': 'some other text' //this can be null or empty
}

col.find({
    "date": {
        $gte: new Date(content.date.from),
        $lte: new Date(content.date.to)
    },

    "name": {
        $ne: {
            $type: null
        },

        $eq: test(content.name)
    },

    "text": {
        $ne: {
            $type: null
        },

        $eq: test(content.text)
    },
}).toArray((err, items) => {
    console.log(items)
});

but it returns an empty array, because "name" or "text" is null / an empty string,
i want that it query only the values that have something specified or ignore it (like content.name is something in it or its empty)

how do i get it? i already searched ... but didnt found something

thanks!

( already testet mongoDB : multi value field search ignoring null fields)

Versions:
Node: 8.9.0
(npm) mongodb: 2.2.33
mongodb: 3.4

Body:
col.find({
    $and: [
        {
            $and: [
                {
                    "date": {
                        $gte: new Date(content.date.from)
                    }
                },
                {
                    "date": {
                        $lte: new Date(content.date.to)
                    }
                },
            ]
        },
        {
            $or: [
                { 'name': null },
                { 'name': content.name }
            ]
        },
        {
            $or: [
                { 'text': null },
                { 'text': content.text }
            ]
        }
    ]
})

Edited:

col.find({
    $and: [
        {
            $and: [
                {
                    "date": {
                        $gte: new Date(content.date.from)
                    }
                },
                {
                    "date": {
                        $lte: new Date(content.date.to)
                    }
                },
            ]
        },
        {
            $or: [
                { 'name': null },
                { 'name':'' }
                { 'name': content.name }
            ]
        },
        {
            $or: [
                { 'text': null },
                { 'text': '' },
                { 'text': content.text }
            ]
        }
    ]
})

null and empty is different, you need to add one more condition for empty string in query.

Logical Query Operators


问:
How can i bulk delete using knexjs(MySQL). I have entries in an array which matches a single field
let i have database structure like this.

```<code>sr no.       name         age
 1.         hemant          25
 2.          amit           23
 3.         vikash          24
</code>```

and i have array like following:

```<code>arr=['hemant','amit'];
</code>```

答:
You can use whereIn statement:

```<code>var arr = ['hemant', 'amit'];

knex('table')
  .whereIn('name', arr)
  .del();
</code>```

Body:
let i have database structure like this.

sr no.       name         age
 1.         hemant          25
 2.          amit           23
 3.         vikash          24

and i have array like following:

arr=['hemant','amit'];

Body:
You can use whereIn statement:

var arr = ['hemant', 'amit'];

knex('table')
  .whereIn('name', arr)
  .del();


问:
Aggregation query operator excluding values with repeated key MongoDB
I have implemented a system where are two type of Prices:

Prices specific for determinated Clients (clientId, productId)

Prices that are common for many Clients (feeId, productId)

My schema is flexible, that is that there are prices that have clientId (1) and prices that has feeId (2). But all of them must have a productId.

There could be only one Price with the same productId and the same clientId.

```<code>var schema = new Schema({
    feeId: {type: Schema.Types.ObjectId, ref: 'Fee'},
    clientId: {type: Schema.Types.ObjectId, ref: 'Client'},
    productId: {type: Schema.Types.ObjectId, ref: 'Product', required:true},
    price: {type: Number, required: true}
});
</code>```

My goal is to obtain the prices for a specific client and product family, and the query should return the prices of the client (price matching clientId), in case it has, and the prices of the products that belongs to that family (price with feeId and without clientId, matching familyId).

Right now i have this:

```<code>  Price.aggregate([
    {
      $lookup:
        {
          'from': 'products',
          'localField': 'productId',
          'foreignField': '_id',
          'as': 'product'
        }
    },
    {
      $unwind: '$product'
    },
    {
      $match: {
        $and: [
          {
            "product.family": new mongoose.Types.ObjectId(req.params.familyId)
          },
          {
            $or: [
              {"clientId": new mongoose.Types.ObjectId(req.params.clientId)},
              {"feeId": {$exists: true, $ne: null}}
            ]
          }

        ]
      }
    },
  ])
</code>```

With that query I obtain the following results:

```<code>    {
  "title": "Precio",
  "body": [
    {
      "_id": "5a0974c7347eff02c784e5bd",
      "price": 8,
      "productId": "5a0970f9347eff02c784e5b1",
      "clientId": "59f350dfb8634f659680299e",
      "product": {
        "_id": "5a0970f9347eff02c784e5b1",
        "erpId": "12345",
        "name": "Entrecot Entero",
        "description": "Pieza entera",
        "weight": null,
        "photoURL": "https://okelan.s3.amazonaws.com/x14-FILETES-ENTRECOT-250gr_PREMIUM-e1491499466438-n6oowu8z2p0d877vgp4eioezbckou4u636uwvc35mo.jpg.pagespeed.ic.l38ZGRUwf6.jpg",
        "familyId": "59e721e8b8634f65967eabf4"
      },
      "client": {
        "_id": "59f350dfb8634f659680299e",
        "contactName": "Pablo 2",
        "NIF": "12345678Z",
        "email": "pablogm.grao@gmail.com",
        "password": "$2a$10$gXn.G/q4ar3wbjSyBCu0XOVud0HL5l3d.2WXNab4cCfB3uToncQLm",
        "orders": [],
        "erpId": "14123",
        "IBAN": "ES6621000418401234567891",
        "photoURL": "https://okelan.s3.amazonaws.com/logo.png",
        "company": "Cárnicas Paco",
        "deliveryMode": "Prueba",
        "paymentMode": "Prueba",
        "active": true,
        "feeId": "59e78d76b8634f65967ec1b3",
        "phone": "620859192",
        "fee": "59e78d76b8634f65967ec1b3",
        "shippingAddresses": [
          {
            "province": "Asturias",
            "city": "Grado",
            "postalCode": 33820,
            "street": "Calle Asturias, 14 3°DCHA",
            "_id": "5a097de74c468c17af16d18e"
          },
          {
            "province": "adfasd",
            "city": "adsfasd",
            "postalCode": 23423,
            "street": "asdfasd",
            "_id": "5a097de74c468c17af16d18d"
          }
        ],
        "billingAddress": {
          "province": "adfasd",
          "city": "adsfasd",
          "postalCode": 23423,
          "street": "asdfasd"
        }
      }
    },
    {
      "_id": "5a0c0d91e5127378570f13b0",
      "price": 14,
      "productId": "5a09ac68e640a63e0520301f",
      "clientId": "59f350dfb8634f659680299e",
      "product": {
        "_id": "5a09ac68e640a63e0520301f",
        "erpId": "2355",
        "name": "Prueba",
        "description": "25",
        "weight": 25,
        "photoURL": "https://okelan.s3.amazonaws.com/camera.jpg",
        "familyId": "59e721e8b8634f65967eabf4"
      },
      "client": {
        "_id": "59f350dfb8634f659680299e",
        "contactName": "Pablo 2",
        "NIF": "12345678Z",
        "email": "pablogm.grao@gmail.com",
        "password": "$2a$10$gXn.G/q4ar3wbjSyBCu0XOVud0HL5l3d.2WXNab4cCfB3uToncQLm",
        "orders": [],
        "erpId": "14123",
        "IBAN": "ES6621000418401234567891",
        "photoURL": "https://okelan.s3.amazonaws.com/logo.png",
        "company": "Cárnicas Paco",
        "deliveryMode": "Prueba",
        "paymentMode": "Prueba",
        "active": true,
        "feeId": "59e78d76b8634f65967ec1b3",
        "phone": "620859192",
        "fee": "59e78d76b8634f65967ec1b3",
        "shippingAddresses": [
          {
            "province": "Asturias",
            "city": "Grado",
            "postalCode": 33820,
            "street": "Calle Asturias, 14 3°DCHA",
            "_id": "5a097de74c468c17af16d18e"
          },
          {
            "province": "adfasd",
            "city": "adsfasd",
            "postalCode": 23423,
            "street": "asdfasd",
            "_id": "5a097de74c468c17af16d18d"
          }
        ],
        "billingAddress": {
          "province": "adfasd",
          "city": "adsfasd",
          "postalCode": 23423,
          "street": "asdfasd"
        }
      }
    }
  ]
}
</code>```

Here you can find some source documents: https://pastebin.com/qBDqKa5y

Could be possible to do it in just one query with an aggregation operator?

Thanks to @dnickless for the final solution:

```<code>  Price.aggregate([
{
  $lookup:
    {
      'from': 'products',
      'localField': 'productId',
      'foreignField': '_id',
      'as': 'product'
    }
},
{
  $unwind: '$product'
},
{
  $lookup:
    {
      'from': 'clients',
      'localField': 'clientId',
      'foreignField': '_id',
      'as': 'client'
    }
},
{
  $unwind: '$client'
},
{
  $match: {
    $and: [
      {
        "product.familyId": new mongoose.Types.ObjectId(req.params.familyId)
      },
      {
        $or: [
          {"clientId": new mongoose.Types.ObjectId(req.params.clientId)},
          {"feeId": new mongoose.Types.ObjectId(req.body.feeId)}
        ]
      }
    ]
  }
},
{
  $sort:
    {
      "clientId":
        -1
    }
},
{
  $group: {

    _id: {
      "productId":
        "$productId"
    }
    ,
    "doc":
      {
        $first: "$$ROOT"
      }
  }
},
{
  $project: { // restore target structure
    "_id": "$doc._id", // you may or may not need this field
    "price": "$doc.price",
    "productId": "$_id.productId",
    "clientId": "$doc.clientId",
    "feeId": "$doc.feeId",
    "promoPrice": "$doc.promoPrice"
  }
},
{
  $lookup:
    {
      'from': 'products',
      'localField': 'productId',
      'foreignField': '_id',
      'as': 'product'
    }
},
{
  $unwind: '$product'
},
{
  $lookup:
    {
      'from': 'clients',
      'localField': 'clientId',
      'foreignField': '_id',
      'as': 'client'
    }
},
{
  $unwind: '$client'
}
</code>```

])

答:
Ok, based on what I think I've understood about your issue, here is something that should work together with some explanations:</p>

```<code>Price.aggregate([{
    $match: { // keep this as your first stage as it will leverage an index on "clientId" (there should be one!) and limit the number of documents to process by the following stages nicely
        $or: [ // we want to consider all prices that
            { "clientId": new mongoose.Types.ObjectId(req.params.clientId) }, // are either for the chose client
            { "clientId": null } // or null - so valid for all clients
        ]
    }
}, {
    $sort: {
        "clientId": -1 // nulls will be at the end of our list so we can use $first later in the next stage in to pick the right price that should take precedence
    }
}, {
    $group: {
        _id: { "productId": "$productId" }, // look at all products individually
        "doc": { // take the first document per "productId" that hit the $group stage (the preceding $sort stage is needed for this to do the right thing)

            $first: "$$ROOT"
        }
    }
}, {
    $project: { // restore target structure
        "_id": "$doc._id", // you may or may not need this field
        "price": "$doc.price",
        "productId": "$_id.productId",
        "clientId": "$doc.clientId",
    }
} /* here you may want to include the $lookup stage if  you need the product information */ ])
</code>```

Body:
I have implemented a system where are two type of Prices:

Prices specific for determinated Clients (clientId, productId)

Prices that are common for many Clients (feeId, productId)

My schema is flexible, that is that there are prices that have clientId (1) and prices that has feeId (2). But all of them must have a productId.

There could be only one Price with the same productId and the same clientId.

var schema = new Schema({
    feeId: {type: Schema.Types.ObjectId, ref: 'Fee'},
    clientId: {type: Schema.Types.ObjectId, ref: 'Client'},
    productId: {type: Schema.Types.ObjectId, ref: 'Product', required:true},
    price: {type: Number, required: true}
});

My goal is to obtain the prices for a specific client and product family, and the query should return the prices of the client (price matching clientId), in case it has, and the prices of the products that belongs to that family (price with feeId and without clientId, matching familyId).

Right now i have this:

  Price.aggregate([
    {
      $lookup:
        {
          'from': 'products',
          'localField': 'productId',
          'foreignField': '_id',
          'as': 'product'
        }
    },
    {
      $unwind: '$product'
    },
    {
      $match: {
        $and: [
          {
            "product.family": new mongoose.Types.ObjectId(req.params.familyId)
          },
          {
            $or: [
              {"clientId": new mongoose.Types.ObjectId(req.params.clientId)},
              {"feeId": {$exists: true, $ne: null}}
            ]
          }

        ]
      }
    },
  ])

With that query I obtain the following results:

    {
  "title": "Precio",
  "body": [
    {
      "_id": "5a0974c7347eff02c784e5bd",
      "price": 8,
      "productId": "5a0970f9347eff02c784e5b1",
      "clientId": "59f350dfb8634f659680299e",
      "product": {
        "_id": "5a0970f9347eff02c784e5b1",
        "erpId": "12345",
        "name": "Entrecot Entero",
        "description": "Pieza entera",
        "weight": null,
        "photoURL": "https://okelan.s3.amazonaws.com/x14-FILETES-ENTRECOT-250gr_PREMIUM-e1491499466438-n6oowu8z2p0d877vgp4eioezbckou4u636uwvc35mo.jpg.pagespeed.ic.l38ZGRUwf6.jpg",
        "familyId": "59e721e8b8634f65967eabf4"
      },
      "client": {
        "_id": "59f350dfb8634f659680299e",
        "contactName": "Pablo 2",
        "NIF": "12345678Z",
        "email": "pablogm.grao@gmail.com",
        "password": "$2a$10$gXn.G/q4ar3wbjSyBCu0XOVud0HL5l3d.2WXNab4cCfB3uToncQLm",
        "orders": [],
        "erpId": "14123",
        "IBAN": "ES6621000418401234567891",
        "photoURL": "https://okelan.s3.amazonaws.com/logo.png",
        "company": "Cárnicas Paco",
        "deliveryMode": "Prueba",
        "paymentMode": "Prueba",
        "active": true,
        "feeId": "59e78d76b8634f65967ec1b3",
        "phone": "620859192",
        "fee": "59e78d76b8634f65967ec1b3",
        "shippingAddresses": [
          {
            "province": "Asturias",
            "city": "Grado",
            "postalCode": 33820,
            "street": "Calle Asturias, 14 3°DCHA",
            "_id": "5a097de74c468c17af16d18e"
          },
          {
            "province": "adfasd",
            "city": "adsfasd",
            "postalCode": 23423,
            "street": "asdfasd",
            "_id": "5a097de74c468c17af16d18d"
          }
        ],
        "billingAddress": {
          "province": "adfasd",
          "city": "adsfasd",
          "postalCode": 23423,
          "street": "asdfasd"
        }
      }
    },
    {
      "_id": "5a0c0d91e5127378570f13b0",
      "price": 14,
      "productId": "5a09ac68e640a63e0520301f",
      "clientId": "59f350dfb8634f659680299e",
      "product": {
        "_id": "5a09ac68e640a63e0520301f",
        "erpId": "2355",
        "name": "Prueba",
        "description": "25",
        "weight": 25,
        "photoURL": "https://okelan.s3.amazonaws.com/camera.jpg",
        "familyId": "59e721e8b8634f65967eabf4"
      },
      "client": {
        "_id": "59f350dfb8634f659680299e",
        "contactName": "Pablo 2",
        "NIF": "12345678Z",
        "email": "pablogm.grao@gmail.com",
        "password": "$2a$10$gXn.G/q4ar3wbjSyBCu0XOVud0HL5l3d.2WXNab4cCfB3uToncQLm",
        "orders": [],
        "erpId": "14123",
        "IBAN": "ES6621000418401234567891",
        "photoURL": "https://okelan.s3.amazonaws.com/logo.png",
        "company": "Cárnicas Paco",
        "deliveryMode": "Prueba",
        "paymentMode": "Prueba",
        "active": true,
        "feeId": "59e78d76b8634f65967ec1b3",
        "phone": "620859192",
        "fee": "59e78d76b8634f65967ec1b3",
        "shippingAddresses": [
          {
            "province": "Asturias",
            "city": "Grado",
            "postalCode": 33820,
            "street": "Calle Asturias, 14 3°DCHA",
            "_id": "5a097de74c468c17af16d18e"
          },
          {
            "province": "adfasd",
            "city": "adsfasd",
            "postalCode": 23423,
            "street": "asdfasd",
            "_id": "5a097de74c468c17af16d18d"
          }
        ],
        "billingAddress": {
          "province": "adfasd",
          "city": "adsfasd",
          "postalCode": 23423,
          "street": "asdfasd"
        }
      }
    }
  ]
}

Here you can find some source documents: https://pastebin.com/qBDqKa5y

Could be possible to do it in just one query with an aggregation operator?

Thanks to @dnickless for the final solution:

  Price.aggregate([
{
  $lookup:
    {
      'from': 'products',
      'localField': 'productId',
      'foreignField': '_id',
      'as': 'product'
    }
},
{
  $unwind: '$product'
},
{
  $lookup:
    {
      'from': 'clients',
      'localField': 'clientId',
      'foreignField': '_id',
      'as': 'client'
    }
},
{
  $unwind: '$client'
},
{
  $match: {
    $and: [
      {
        "product.familyId": new mongoose.Types.ObjectId(req.params.familyId)
      },
      {
        $or: [
          {"clientId": new mongoose.Types.ObjectId(req.params.clientId)},
          {"feeId": new mongoose.Types.ObjectId(req.body.feeId)}
        ]
      }
    ]
  }
},
{
  $sort:
    {
      "clientId":
        -1
    }
},
{
  $group: {

    _id: {
      "productId":
        "$productId"
    }
    ,
    "doc":
      {
        $first: "$$ROOT"
      }
  }
},
{
  $project: { // restore target structure
    "_id": "$doc._id", // you may or may not need this field
    "price": "$doc.price",
    "productId": "$_id.productId",
    "clientId": "$doc.clientId",
    "feeId": "$doc.feeId",
    "promoPrice": "$doc.promoPrice"
  }
},
{
  $lookup:
    {
      'from': 'products',
      'localField': 'productId',
      'foreignField': '_id',
      'as': 'product'
    }
},
{
  $unwind: '$product'
},
{
  $lookup:
    {
      'from': 'clients',
      'localField': 'clientId',
      'foreignField': '_id',
      'as': 'client'
    }
},
{
  $unwind: '$client'
}

])

Body:
Ok, based on what I think I've understood about your issue, here is something that should work together with some explanations:

Price.aggregate([{
    $match: { // keep this as your first stage as it will leverage an index on "clientId" (there should be one!) and limit the number of documents to process by the following stages nicely
        $or: [ // we want to consider all prices that
            { "clientId": new mongoose.Types.ObjectId(req.params.clientId) }, // are either for the chose client
            { "clientId": null } // or null - so valid for all clients
        ]
    }
}, {
    $sort: {
        "clientId": -1 // nulls will be at the end of our list so we can use $first later in the next stage in to pick the right price that should take precedence
    }
}, {
    $group: {
        _id: { "productId": "$productId" }, // look at all products individually
        "doc": { // take the first document per "productId" that hit the $group stage (the preceding $sort stage is needed for this to do the right thing)

            $first: "$$ROOT"
        }
    }
}, {
    $project: { // restore target structure
        "_id": "$doc._id", // you may or may not need this field
        "price": "$doc.price",
        "productId": "$_id.productId",
        "clientId": "$doc.clientId",
    }
} /* here you may want to include the $lookup stage if  you need the product information */ ])