问:
How to write HQL JOIN query for multiple table's selected Columns using Constructor In The Select Clause
I'm writing  HQL JOIN query for multiple table's selected Columns using Constructor() In The Select Clause

I have following Entities:

Entity 1: NotificationObject.java

```<code>@Entity
@Table(name="notification_object")
public class NotificationObject implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue( strategy=GenerationType.IDENTITY )
    @Column( columnDefinition="INT(10) UNSIGNED" )
    private Integer id;

    @Column( name="entity_type_id", columnDefinition="TINYINT UNSIGNED", nullable=false )
    private Short entityTypeId;

    @Column( name="entity_id", columnDefinition="INT(10) UNSIGNED", nullable=false )
    private Integer entityId;

    @DateTimeFormat( pattern="yyyy-MM-dd" )
    @Temporal( TemporalType.TIMESTAMP )
    @CreationTimestamp
    @Column( name="created_on"/*, nullable=false*/ )
    private Date createdOn;

    @OneToMany( mappedBy = "notificationObject" )
    private Set<Notification> notifications = new LinkedHashSet<>();

    public NotificationObject() {}
    public NotificationObject(Short entityTypeId, Integer entityId) {
        this.entityTypeId = entityTypeId;
        this.entityId = entityId;
    }

    // Getters and Setters
}
</code>```

Entity 2: NotificationChange.java

```<code>@Entity
@Table(name="notification_change")
public class NotificationChange implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(columnDefinition="INT(10) UNSIGNED")
    private Integer id;

    @ManyToOne( fetch=FetchType.LAZY )
    @JoinColumn(
            name="notification_object_id", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_change_notification_object_noti_object_id")
    )
    private NotificationObject notificationObject;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(
            name="actor_id", columnDefinition="INT(10) UNSIGNED", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_change_user_user_id")
    )
    private User actor;

    public NotificationChange() {}
    public NotificationChange( User actor ) {
        this.actor = actor;
    }

    // Getters and Setters
}
</code>```

Entity 3: Notification.java

```<code>@Entity
@Table(name="notification")
public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue( strategy=GenerationType.IDENTITY )
    @Column( columnDefinition="INT(10) UNSIGNED" )
    private Integer id;

    @ManyToOne( fetch=FetchType.LAZY )
    @JoinColumn(
            name="notification_object_id", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_notification_object_notification_object_id")
    )
    private NotificationObject notificationObject;

    @ManyToOne( fetch=FetchType.LAZY )
    @JoinColumn(
            name="notifier_id", columnDefinition="INT(10) UNSIGNED", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_user_user_id")
    )
    private User notifier;

    @Column( name="is_seen", nullable=false )
    private boolean isSeen;

    @Column( name="is_viewed", nullable=false )
    private boolean isViewed;

    public Notification() {}
    public Notification( User notifier, boolean isSeen, boolean isViewed ) {
        this.notifier = notifier;
        this.isSeen = isSeen;
        this.isViewed = isViewed;
    }

    // Getters and Setters
}
</code>```

Entity 4: User.java

```<code>@Entity
@Table(name="user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

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

    // Extra fields

    @OneToOne(cascade=CascadeType.MERGE)
    @JoinColumn(name="emp_id", columnDefinition="INT(10) UNSIGNED")
    private Employee employee;

    @OneToMany( mappedBy="notifier" )
    private Set<Notification> notifications = new LinkedHashSet<>();

    public User() {}
    public User(String user_id) {
        this.user_id = user_id;
    }

    // Getters and Setters
}
</code>```

Entity 5: Employee.java

```<code>@Entity
@Table(name="employee")
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    public Employee() { }
    public Employee( String emp_id ) {
        this.emp_id = emp_id;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="emp_id")
    private String emp_id;

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

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

    // Extra fields

    @OneToOne(mappedBy="employee")
    @JsonBackReference
    private User user;

    // Getters and Setters
}
</code>```

DTO 1: Notify.java

```<code>public class Notify {
    private Integer notificationObjectId, notificationId, notifierId, actorId, entityId;
    private Short entityTypeId;
    private String notifierName, actorName, message, notificationLink;
    private Date createdOn;
    private boolean isSeen, isViewed;

    public Notify() {}
    public Notify ( Integer notificationObjectId, Integer notificationId, Integer notifierId, Integer actorId,
            Integer entityId, Short entityTypeId, String notifierName, String actorName, String message,
            String notificationLink, Date createdOn, boolean isSeen, boolean isViewed ) {
        // Set Values Here
    }
    public Notify (Integer notificationObjectId, Integer notificationId, Integer notifierId, String notifierName,
            Integer actorId, String actorName, Integer entityId, Short entityTypeId,
            Date createdOn, boolean isSeen, boolean isViewed ) {
        // Or Here
    }

    // Getters and Setters
}
</code>```

I'm weak at JOINs.

I want to write HQL JOIN query for entity's selected field to form Constructor() In The Select Clause of Notify.java DTO.

What I have tried:

Query 1

```<code>final String GET_NOTIFICATIONS_FOR_USER =
"select new support.dto.Notify ( no.id, n.id, Integer.parseInt( n.notifier.user_id ), "
+ "concat ( n.notifier.employee.first_name, ' ', n.notifier.employee.last_name ), "
+ "Integer.parseInt( nc.actor.user_id ), concat( nc.actor.employee.first_name, ' ', nc.actor.employee.last_name ), "
+ "no.entityId, no.entityTypeId, no.createdOn, n.isSeen, n.isViewed ) "
+ "from Notification n, NotificationObject no, NotificationChange nc, User u, Employee e "
+ "where n.notifier.user_id = :notifierId";
</code>```

Query 2

```<code>final String GET_NOTIFICATIONS_FOR_USER =
"select new support.dto.Notify ( no.id, n.id, Integer.parseInt( n.notifier.user_id ), "
+ "concat ( n.notifier.employee.first_name, ' ', n.notifier.employee.first_name ), "
+ "Integer.parseInt( nc.actor.user_id ), concat( nc.actor.employee.first_name, ' ', nc.actor.employee.last_name ), "
+ "no.entityId, no.entityTypeId, no.createdOn, n.isSeen, n.isViewed ) "
+ "from NotificationChange nc inner join nc.notificationObject no "
+ "inner join no.notifications n "
+ "where n.notifier.user_id = :notifierId";
</code>```

I'm getting following Exception

java.lang.NullPointerException
      at org.hibernate.internal.util.ReflectHelper.getConstructor(ReflectHelper.java:309)
      at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:174)
      at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:144)
      at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1091)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2328)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2194)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1476)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:573)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
      at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
      at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
      at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
      at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:115)
      at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:76)
      at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
      at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:298)
      at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
      at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1821)
      at support.DAO.MasterDaoImpl.getNotifications(MasterDaoImpl.java:115)
      at support.service.MasterServiceImpl.getNotifications(MasterServiceImpl.java:158)
      at support.service.MasterServiceImpl$$FastClassBySpringCGLIB$$a355463b.invoke()
      at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
      at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
      at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
      at support.service.MasterServiceImpl$$EnhancerBySpringCGLIB$$8c2728e2.getNotifications()
      at support.controller.WebSocketController.hello(WebSocketController.java:91)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:601)
      at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:185)
      at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:104)
      at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMatch(AbstractMethodMessageHandler.java:447)
      at org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:443)
      at org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:82)
      at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessageInternal(AbstractMethodMessageHandler.java:408)
      at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessage(AbstractMethodMessageHandler.java:346)
      at org.springframework.messaging.support.ExecutorSubscribableChannel$SendTask.run(ExecutorSubscribableChannel.java:135)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
      at java.lang.Thread.run(Thread.java:722)

答:
The error tells you that Hibernate couldn't locate the Notify  constructor.

More, you are not allowed to add Integer.parseInt in your HQL query. Use the expected type from the ResultSet and do the casting inside the constructor from the incoming parameter.

Body:
I'm writing  HQL JOIN query for multiple table's selected Columns using Constructor() In The Select Clause

I have following Entities:

Entity 1: NotificationObject.java

@Entity
@Table(name="notification_object")
public class NotificationObject implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue( strategy=GenerationType.IDENTITY )
    @Column( columnDefinition="INT(10) UNSIGNED" )
    private Integer id;

    @Column( name="entity_type_id", columnDefinition="TINYINT UNSIGNED", nullable=false )
    private Short entityTypeId;

    @Column( name="entity_id", columnDefinition="INT(10) UNSIGNED", nullable=false )
    private Integer entityId;

    @DateTimeFormat( pattern="yyyy-MM-dd" )
    @Temporal( TemporalType.TIMESTAMP )
    @CreationTimestamp
    @Column( name="created_on"/*, nullable=false*/ )
    private Date createdOn;

    @OneToMany( mappedBy = "notificationObject" )
    private Set<Notification> notifications = new LinkedHashSet<>();

    public NotificationObject() {}
    public NotificationObject(Short entityTypeId, Integer entityId) {
        this.entityTypeId = entityTypeId;
        this.entityId = entityId;
    }

    // Getters and Setters
}

Entity 2: NotificationChange.java

@Entity
@Table(name="notification_change")
public class NotificationChange implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(columnDefinition="INT(10) UNSIGNED")
    private Integer id;

    @ManyToOne( fetch=FetchType.LAZY )
    @JoinColumn(
            name="notification_object_id", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_change_notification_object_noti_object_id")
    )
    private NotificationObject notificationObject;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(
            name="actor_id", columnDefinition="INT(10) UNSIGNED", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_change_user_user_id")
    )
    private User actor;

    public NotificationChange() {}
    public NotificationChange( User actor ) {
        this.actor = actor;
    }

    // Getters and Setters
}

Entity 3: Notification.java

@Entity
@Table(name="notification")
public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue( strategy=GenerationType.IDENTITY )
    @Column( columnDefinition="INT(10) UNSIGNED" )
    private Integer id;

    @ManyToOne( fetch=FetchType.LAZY )
    @JoinColumn(
            name="notification_object_id", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_notification_object_notification_object_id")
    )
    private NotificationObject notificationObject;

    @ManyToOne( fetch=FetchType.LAZY )
    @JoinColumn(
            name="notifier_id", columnDefinition="INT(10) UNSIGNED", nullable=false,
            foreignKey=@ForeignKey(name="fk_notification_user_user_id")
    )
    private User notifier;

    @Column( name="is_seen", nullable=false )
    private boolean isSeen;

    @Column( name="is_viewed", nullable=false )
    private boolean isViewed;

    public Notification() {}
    public Notification( User notifier, boolean isSeen, boolean isViewed ) {
        this.notifier = notifier;
        this.isSeen = isSeen;
        this.isViewed = isViewed;
    }

    // Getters and Setters
}

Entity 4: User.java

@Entity
@Table(name="user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

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

    // Extra fields

    @OneToOne(cascade=CascadeType.MERGE)
    @JoinColumn(name="emp_id", columnDefinition="INT(10) UNSIGNED")
    private Employee employee;

    @OneToMany( mappedBy="notifier" )
    private Set<Notification> notifications = new LinkedHashSet<>();

    public User() {}
    public User(String user_id) {
        this.user_id = user_id;
    }

    // Getters and Setters
}

Entity 5: Employee.java

@Entity
@Table(name="employee")
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    public Employee() { }
    public Employee( String emp_id ) {
        this.emp_id = emp_id;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="emp_id")
    private String emp_id;

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

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

    // Extra fields

    @OneToOne(mappedBy="employee")
    @JsonBackReference
    private User user;

    // Getters and Setters
}

DTO 1: Notify.java

public class Notify {
    private Integer notificationObjectId, notificationId, notifierId, actorId, entityId;
    private Short entityTypeId;
    private String notifierName, actorName, message, notificationLink;
    private Date createdOn;
    private boolean isSeen, isViewed;

    public Notify() {}
    public Notify ( Integer notificationObjectId, Integer notificationId, Integer notifierId, Integer actorId,
            Integer entityId, Short entityTypeId, String notifierName, String actorName, String message,
            String notificationLink, Date createdOn, boolean isSeen, boolean isViewed ) {
        // Set Values Here
    }
    public Notify (Integer notificationObjectId, Integer notificationId, Integer notifierId, String notifierName,
            Integer actorId, String actorName, Integer entityId, Short entityTypeId,
            Date createdOn, boolean isSeen, boolean isViewed ) {
        // Or Here
    }

    // Getters and Setters
}

I'm weak at JOINs.

I want to write HQL JOIN query for entity's selected field to form Constructor() In The Select Clause of Notify.java DTO.

What I have tried:

Query 1

final String GET_NOTIFICATIONS_FOR_USER =
"select new support.dto.Notify ( no.id, n.id, Integer.parseInt( n.notifier.user_id ), "
+ "concat ( n.notifier.employee.first_name, ' ', n.notifier.employee.last_name ), "
+ "Integer.parseInt( nc.actor.user_id ), concat( nc.actor.employee.first_name, ' ', nc.actor.employee.last_name ), "
+ "no.entityId, no.entityTypeId, no.createdOn, n.isSeen, n.isViewed ) "
+ "from Notification n, NotificationObject no, NotificationChange nc, User u, Employee e "
+ "where n.notifier.user_id = :notifierId";

Query 2

final String GET_NOTIFICATIONS_FOR_USER =
"select new support.dto.Notify ( no.id, n.id, Integer.parseInt( n.notifier.user_id ), "
+ "concat ( n.notifier.employee.first_name, ' ', n.notifier.employee.first_name ), "
+ "Integer.parseInt( nc.actor.user_id ), concat( nc.actor.employee.first_name, ' ', nc.actor.employee.last_name ), "
+ "no.entityId, no.entityTypeId, no.createdOn, n.isSeen, n.isViewed ) "
+ "from NotificationChange nc inner join nc.notificationObject no "
+ "inner join no.notifications n "
+ "where n.notifier.user_id = :notifierId";

I'm getting following Exception

java.lang.NullPointerException
      at org.hibernate.internal.util.ReflectHelper.getConstructor(ReflectHelper.java:309)
      at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:174)
      at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:144)
      at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1091)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2328)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2194)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1476)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:573)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
      at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
      at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
      at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
      at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
      at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:115)
      at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:76)
      at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
      at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:298)
      at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
      at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1821)
      at support.DAO.MasterDaoImpl.getNotifications(MasterDaoImpl.java:115)
      at support.service.MasterServiceImpl.getNotifications(MasterServiceImpl.java:158)
      at support.service.MasterServiceImpl$$FastClassBySpringCGLIB$$a355463b.invoke()
      at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
      at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
      at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
      at support.service.MasterServiceImpl$$EnhancerBySpringCGLIB$$8c2728e2.getNotifications()
      at support.controller.WebSocketController.hello(WebSocketController.java:91)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:601)
      at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:185)
      at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:104)
      at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMatch(AbstractMethodMessageHandler.java:447)
      at org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:443)
      at org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:82)
      at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessageInternal(AbstractMethodMessageHandler.java:408)
      at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessage(AbstractMethodMessageHandler.java:346)
      at org.springframework.messaging.support.ExecutorSubscribableChannel$SendTask.run(ExecutorSubscribableChannel.java:135)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
      at java.lang.Thread.run(Thread.java:722)


来源: stackexchange

问:
If I can use SQLite 3 to organize data in python, why should I use classes?
I am going to create a project for my university called Criminal Record System in which I will manage criminal's data and history. Now I stumbled upon the term class. Going through some videos and articles I realized that it is used to save data. So I am confused that if we can use sqlite 3 then why are using classes to organize data.</p>

答:
Database scope is to store data. You use Classes to better organize your data in your program.

Think of the database as a warehouse where you store your library and your books. When you need to get some of these books you retrieve them (read from database) and use a Class to organize them when you use it at 'home' (in your program).
Without database when the program is closed you lose all your books. Without classes you have all your books in a mess.

So there is no a 'better' or 'worse'. One does not exclude the other.

You can read this: https://python.swaroopch.com/oop.html

ContentLicense: CC BY-SA 3.0


问:
Extend a class from different puppet module
I need to extend a class from a different Puppet module. Is it possible to do this? If yes, what would be the syntax?</p>

答:
In Puppet, it is possible for a class a::b to inherit class a via the inherits keyword. This allows class a::b to "extend" class a.

Note that Puppet recommends that you should rarely if ever need to do this. In particular, most of what can be achieved by inheritance can also be achieved by just including the base class by using the include function. For more information, see the documentation here.

If you do choose to use inheritance, class a is automatically declared first; class a becomes the parent scope of class a::b, so it receives copies of all variables and resource defaults; and the code in class a::b has permission to override resource attributes that are set in class a.

Using this pattern, it is also possible for class a::b to use a variable from class a as a default for one of its class parameters. This led to the "params pattern" where a params.pp file is used to set class defaults.

The following simple code example illustrates all of these features:

```<code>class a {
  File {
    mode => '0755',
  }
  file { '/tmp/foo':
    ensure => absent,
  }
  $x = 'I, Foo'
}

class a::b (
  $y = $a::x  # default from class a.
) inherits a {

  # Override /tmp/foo's ensure
  # and content attributes.

  File['/tmp/foo'] {
    ensure  => file,
    content => $y,
  }

  # Both /tmp/foo and /tmp/bar
  # will receive the default file
  # mode of 0755.

  file { '/tmp/bar':
    ensure => file,
  }
}
</code>```

And using Rspec to express the catalog's expected end-state:

```<code>describe 'a::b' do
  it 'overrides ensure attribute' do
    is_expected.to contain_file('/tmp/foo').with({
      'ensure'  => 'file',
    })
  end
  it 'inherits content from $x' do
    is_expected.to contain_file('/tmp/foo').with({
      'content' => "I, Foo",
    })
  end
  it 'file defaults inherited' do
    is_expected.to contain_file('/tmp/foo').with({
      'mode' => '0755',
    })
    is_expected.to contain_file('/tmp/bar').with({
      'mode' => '0755',
    })
  end
end
</code>```

Tests pass:

```<code>a::b
  overrides ensure attribute
  inherits content from $x
  file defaults inherited

Finished in 0.15328 seconds (files took 1.2 seconds to load)
3 examples, 0 failures
</code>```

A note about "plusignment".

As also described in the documentation, it is possible, when overriding a resource attribute that is an array, to add to that array instead of replacing using the +> "plusignment" operator. It is a rarely used feature, but should be mentioned in this context. See the link above for a code example.

Body:
In Puppet, it is possible for a class a::b to inherit class a via the inherits keyword. This allows class a::b to "extend" class a.

Note that Puppet recommends that you should rarely if ever need to do this. In particular, most of what can be achieved by inheritance can also be achieved by just including the base class by using the include function. For more information, see the documentation here.

If you do choose to use inheritance, class a is automatically declared first; class a becomes the parent scope of class a::b, so it receives copies of all variables and resource defaults; and the code in class a::b has permission to override resource attributes that are set in class a.

Using this pattern, it is also possible for class a::b to use a variable from class a as a default for one of its class parameters. This led to the "params pattern" where a params.pp file is used to set class defaults.

The following simple code example illustrates all of these features:

class a {
  File {
    mode => '0755',
  }
  file { '/tmp/foo':
    ensure => absent,
  }
  $x = 'I, Foo'
}

class a::b (
  $y = $a::x  # default from class a.
) inherits a {

  # Override /tmp/foo's ensure
  # and content attributes.

  File['/tmp/foo'] {
    ensure  => file,
    content => $y,
  }

  # Both /tmp/foo and /tmp/bar
  # will receive the default file
  # mode of 0755.

  file { '/tmp/bar':
    ensure => file,
  }
}

And using Rspec to express the catalog's expected end-state:

describe 'a::b' do
  it 'overrides ensure attribute' do
    is_expected.to contain_file('/tmp/foo').with({
      'ensure'  => 'file',
    })
  end
  it 'inherits content from $x' do
    is_expected.to contain_file('/tmp/foo').with({
      'content' => "I, Foo",
    })
  end
  it 'file defaults inherited' do
    is_expected.to contain_file('/tmp/foo').with({
      'mode' => '0755',
    })
    is_expected.to contain_file('/tmp/bar').with({
      'mode' => '0755',
    })
  end
end

Tests pass:

a::b
  overrides ensure attribute
  inherits content from $x
  file defaults inherited

Finished in 0.15328 seconds (files took 1.2 seconds to load)
3 examples, 0 failures

A note about "plusignment".

As also described in the documentation, it is possible, when overriding a resource attribute that is an array, to add to that array instead of replacing using the +> "plusignment" operator. It is a rarely used feature, but should be mentioned in this context. See the link above for a code example.


问:
Error with passing data over Intent
I'm trying to pass an ID from one class to another using intent after watching a youtube tutorial. However, it always passes over the default value of -1 rather than the value I want.

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String homeTeam = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);

            Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext()){
                itemID = data.getInt(0);
            }
            if(itemID > -1){
                //Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
                editScreenIntent.putExtra("MatchId", itemID);
                editScreenIntent.putExtra("homeTeam",homeTeam);
                startActivity(editScreenIntent);
            }
            else{
                toastMessage("No ID associated with that name");
            }
        }
    });
}
</code>```

The class it goes to:

```<code> //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);
</code>```

In his tutorial, it works fine but when I try it after I edit a match, in my log it comes up with MatchId = -1 when it shouldn't be.

I'll include the method in the database also:

```<code>public void updateName(String newName, int id, String oldName){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
            " = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
            " AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
    Log.d(TAG, "updateName: query: " + query);
    Log.d(TAG, "updateName: Setting name to " + newName);
    db.execSQL(query);
}
</code>```

答:
In the Recieving Activity Change the code

```<code> //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);
</code>```

You should use MatchId instaed of matchID. Java is Case Sensitive.

Title: Error with passing data over Intent

Body:
I'm trying to pass an ID from one class to another using intent after watching a youtube tutorial. However, it always passes over the default value of -1 rather than the value I want.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String homeTeam = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);

            Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext()){
                itemID = data.getInt(0);
            }
            if(itemID > -1){
                //Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
                editScreenIntent.putExtra("MatchId", itemID);
                editScreenIntent.putExtra("homeTeam",homeTeam);
                startActivity(editScreenIntent);
            }
            else{
                toastMessage("No ID associated with that name");
            }
        }
    });
}

The class it goes to:

 //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);

In his tutorial, it works fine but when I try it after I edit a match, in my log it comes up with MatchId = -1 when it shouldn't be.

I'll include the method in the database also:

public void updateName(String newName, int id, String oldName){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
            " = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
            " AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
    Log.d(TAG, "updateName: query: " + query);
    Log.d(TAG, "updateName: Setting name to " + newName);
    db.execSQL(query);
}

Body:
In the Recieving Activity Change the code

 //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);

You should use MatchId instaed of matchID. Java is Case Sensitive.


问:
Integrating Mobile Money to Symfony
I have a Symfony application which I will like to integrate mobile money into. The problem is I cannot add PHP code to twig files and I am a complete newbie to this kind of challenge. The code reads:

<?php

require_once '/path/to/monetbil-php/monetbil.php';

// Setup Monetbil arguments
Monetbil::setAmount(500);
Monetbil::setCurrency('XAF');
Monetbil::setLocale('en'); // Display language fr or en
Monetbil::setPhone('');
Monetbil::setCountry('');
Monetbil::setItem_ref('2536');
Monetbil::setPayment_ref('d4be3535f9cb5a7aff1f84fa94e6f040');
Monetbil::setUser(12);
Monetbil::setFirst_name('KAMDEM');
Monetbil::setLast_name('Jean');
Monetbil::setEmail('jean.kamdem@email.com');

// Start a payment
// You will be redirected to the payment page
Monetbil::startPayment();
```

I am looking at adding this to App/Resources/Views/members/dashboard.html.twig

答: Twig is only ment to render your output. Put your (php) logic in your controller and/or create your own service. From your controller you will also render your Twig template with the variables you need but only to render the output that you want to show to the users. </p>

ContentLicense: CC BY-SA 4.0

Title: Integrating Mobile Money to Symfony

Body:
I have a Symfony application which I will like to integrate mobile money into. The problem is I cannot add PHP code to twig files and I am a complete newbie to this kind of challenge. The code reads:

<?php

require_once '/path/to/monetbil-php/monetbil.php';

// Setup Monetbil arguments
Monetbil::setAmount(500);
Monetbil::setCurrency('XAF');
Monetbil::setLocale('en'); // Display language fr or en
Monetbil::setPhone('');
Monetbil::setCountry('');
Monetbil::setItem_ref('2536');
Monetbil::setPayment_ref('d4be3535f9cb5a7aff1f84fa94e6f040');
Monetbil::setUser(12);
Monetbil::setFirst_name('KAMDEM');
Monetbil::setLast_name('Jean');
Monetbil::setEmail('jean.kamdem@email.com');

// Start a payment
// You will be redirected to the payment page
Monetbil::startPayment();

I am looking at adding this to App/Resources/Views/members/dashboard.html.twig


问:
Why is it advised to NOT use the RPM Packager tag?
There is a note in http://fedoraproject.org/wiki/How_to_create_an_RPM_package#Other_tags, which states:

```<code>Do NOT use these tags

Packager
Vendor
Copyright
</code>```

With no explanation given.  Packager is quite commonly seen, so, when I am creating a new spec file to distribute software, why should I not include that tag (or any of the named tags)?

答:
Copyright has been deprecated in 2000. Rpmbuild refuse to accept it since 2005. It was poorly named initially and should have been named License from the very start. Nowadays everyone uses License tag.

Vendor is usually set by build system (Koji, Copr, OBS) so you should not override it. I.e. every package in Fedora has Vendor set to "Fedora Project".

The same for Packager. But this one is a little bit relaxed. E.g., Koji set it, but Copr not.

Body:
There is a note in http://fedoraproject.org/wiki/How_to_create_an_RPM_package#Other_tags, which states:

Do NOT use these tags

Packager
Vendor
Copyright

With no explanation given.  Packager is quite commonly seen, so, when I am creating a new spec file to distribute software, why should I not include that tag (or any of the named tags)?


问:
Error when running watchman
When I run react-native start, I am getting the following message

Error: A non-recoverable condition has triggered.  Watchman needs your help!
The triggering condition was at timestamp=1489123194: inotify-add-watch(/var/www/html/eventManager/android/app/src/main/res/mipmap-mdpi) -> The user limit on the total number of inotify watches was reached; increase the fs.inotify.max_user_watches sysctl
All requests will continue to fail with this message until you resolve
the underlying problem.  You will find more information on fixing this at
https://facebook.github.io/watchman/docs/troubleshooting.html#poison-inotify-add-watch

```<code>at ChildProcess.<anonymous> (/var/www/html/bookLister/node_modules/fb-watchman/index.js:207:21)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:852:16)
at Socket.<anonymous> (internal/child_process.js:323:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:492:12)
</code>```

答:
Just run these commands in terminal:

```<code>echo 256 | sudo tee -a /proc/sys/fs/inotify/max_user_instances
echo 32768 | sudo tee -a /proc/sys/fs/inotify/max_queued_events
echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches
watchman shutdown-server
</code>```

Other Way make Script in package.json

```<code>"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "flow": "flow",
    "flow-stop": "flow stop",
    "watch-need-help": "echo 256 | sudo tee -a /proc/sys/fs/inotify/max_user_instances && echo 32768 | sudo tee -a /proc/sys/fs/inotify/max_queued_events && echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches && watchman shutdown-server"
  },
</code>```

Run following command on Terminal in project directory

```<code>npm run watch-need-help
</code>```

Title: Error when running watchman

Body:
When I run react-native start, I am getting the following message

Error: A non-recoverable condition has triggered.  Watchman needs your help!
The triggering condition was at timestamp=1489123194: inotify-add-watch(/var/www/html/eventManager/android/app/src/main/res/mipmap-mdpi) -> The user limit on the total number of inotify watches was reached; increase the fs.inotify.max_user_watches sysctl
All requests will continue to fail with this message until you resolve
the underlying problem.  You will find more information on fixing this at
https://facebook.github.io/watchman/docs/troubleshooting.html#poison-inotify-add-watch

at ChildProcess.<anonymous> (/var/www/html/bookLister/node_modules/fb-watchman/index.js:207:21)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:852:16)
at Socket.<anonymous> (internal/child_process.js:323:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:492:12)

Body:
Just run these commands in terminal:

echo 256 | sudo tee -a /proc/sys/fs/inotify/max_user_instances
echo 32768 | sudo tee -a /proc/sys/fs/inotify/max_queued_events
echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches
watchman shutdown-server

Other Way make Script in package.json

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "flow": "flow",
    "flow-stop": "flow stop",
    "watch-need-help": "echo 256 | sudo tee -a /proc/sys/fs/inotify/max_user_instances && echo 32768 | sudo tee -a /proc/sys/fs/inotify/max_queued_events && echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches && watchman shutdown-server"
  },

Run following command on Terminal in project directory

npm run watch-need-help


问:
Angular 2/4 pushing in array inside an object
I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

```<code>export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}
</code>```

Each time some one types a comment I want to add it to the comment array something like this

```<code>  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})
</code>```

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved.
Please let me know how can I push comment values

答:
This example creates a new RecordItem which we can subsequently push items into, initialising an empty recordName and comment array.

```<code>export class Comment {
  comment: string
}

export class RecordItem {
  recordName: string;
  comments: Comment[]

  constructor(recordName: string, comments: Comment[]) {
    this.recordName = recordName;
    this.comments = comments;
  }
}

const recordItem = new RecordItem('', []);

recordItem.comments.push({ comment: 'Hey!!' });
</code>```

Body:
I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}

Each time some one types a comment I want to add it to the comment array something like this

  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved.
Please let me know how can I push comment values

Body:
This example creates a new RecordItem which we can subsequently push items into, initialising an empty recordName and comment array.

export class Comment {
  comment: string
}

export class RecordItem {
  recordName: string;
  comments: Comment[]

  constructor(recordName: string, comments: Comment[]) {
    this.recordName = recordName;
    this.comments = comments;
  }
}

const recordItem = new RecordItem('', []);

recordItem.comments.push({ comment: 'Hey!!' });


问:
Use Field Code as File Name in Mail Merge
I want to separate my mail merge into separate PDF files (this part is working). But the file names are being saved as a counter i.e. numbers.

```<code>Sub AllSectionsToSubDoc()

    Dim x               As Long
    Dim Sections        As Long
    Dim Doc             As Document

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Doc = ActiveDocument
    Sections = Doc.Sections.Count
    For x = Sections - 1 To 1 Step -1
        Doc.Sections(x).Range.Copy
        Documents.Add
        ActiveDocument.Range.Paste
        ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
        ActiveDocument.Close False
    Next x

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub
</code>```

I want to extend this code so that it saves the files with file names which are NOT numbers, but are taken from one of the field codes that I specify.

For example if I specify field code «First_Name» as the file name in my VBA code, and there are 3 names - (John, Peter, Samuel) 3 files should be saved in my destination folder as John.pdf, Peter.pdf, Samuel.pdf

答:
Get the value from the data source, Split between commas, loop through the returned array and save each document individually.

Something like this (I haven't been able to test it).

```<code>Dim Value As String
Dim Names As Variant
Dim idx As Long

Value = Doc.DataSource.DataFields("First_Name").Value
Names = Split(Value, ",")

For idx = LBound(Names) To UBound(Names)
    ActiveDocument.SaveAs Doc.Path & "\" & Names(idx) & ".pdf"
Next
</code>```

In the event where the value is a single name (no comma), the Split() function will return an array with a single element.

Body:
I want to separate my mail merge into separate PDF files (this part is working). But the file names are being saved as a counter i.e. numbers.

Sub AllSectionsToSubDoc()

    Dim x               As Long
    Dim Sections        As Long
    Dim Doc             As Document

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Doc = ActiveDocument
    Sections = Doc.Sections.Count
    For x = Sections - 1 To 1 Step -1
        Doc.Sections(x).Range.Copy
        Documents.Add
        ActiveDocument.Range.Paste
        ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
        ActiveDocument.Close False
    Next x

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

I want to extend this code so that it saves the files with file names which are NOT numbers, but are taken from one of the field codes that I specify.

For example if I specify field code «First_Name» as the file name in my VBA code, and there are 3 names - (John, Peter, Samuel) 3 files should be saved in my destination folder as John.pdf, Peter.pdf, Samuel.pdf

Body:
Get the value from the data source, Split between commas, loop through the returned array and save each document individually.

Something like this (I haven't been able to test it).

Dim Value As String
Dim Names As Variant
Dim idx As Long

Value = Doc.DataSource.DataFields("First_Name").Value
Names = Split(Value, ",")

For idx = LBound(Names) To UBound(Names)
    ActiveDocument.SaveAs Doc.Path & "\" & Names(idx) & ".pdf"
Next

In the event where the value is a single name (no comma), the Split() function will return an array with a single element.


问:
Scrapy to extract data from javascript script
I'm trying to extract the odds of games from an espn website. The 'moneyLine' odds are buried in a script that I just can't figure out how to access. Ideally I would have the odds in rows for each game. I've managed to extract team names and scores in rows, I would like odds to go with it.

```<code>scrapy shell
fetch('http://www.espn.com/nfl/schedule/_/week/1')
response.xpath("//script[contains(., 'moneyLine')]/text()")
</code>```

This is the output

```<code>[<Selector xpath="//script[contains(., 'moneyLine')]/text()" data='\n\t\t\tvar espn = espn || {};\n\n\t\t\t// Build '>]
</code>```

Here is a sample from firefox inspector window, I can see the 'moneyLine' items, just can't isolate them

答: Your data is in

Body:
I'm trying to extract the odds of games from an espn website. The 'moneyLine' odds are buried in a script that I just can't figure out how to access. Ideally I would have the odds in rows for each game. I've managed to extract team names and scores in rows, I would like odds to go with it.

scrapy shell
fetch('http://www.espn.com/nfl/schedule/_/week/1')
response.xpath("//script[contains(., 'moneyLine')]/text()")

This is the output

[<Selector xpath="//script[contains(., 'moneyLine')]/text()" data='\n\t\t\tvar espn = espn || {};\n\n\t\t\t// Build '>]

Here is a sample from firefox inspector window, I can see the 'moneyLine' items, just can't isolate them

Body:
Your data is in <script> between data: and queue: in JSON format.

You can use standard string functions (ie. find(), slicing) to cut off this part.

And then you can use module json to convert to python dictionary.

And then you have to only find where moneyLine is in this dictionary.

scrapy shell 'http://www.espn.com/nfl/schedule/_/week/1'

# get `<script>` as text
items = response.xpath("//script[contains(., 'moneyLine')]/text()")
txt = items.extract_first()

# find start and end of data
#(I found this manually checking txt)
start = txt.find('data:') + 6 # manually found how many add to get correct JSON string
end = txt.find('queue:') - 6  # manually found how many substract to get correct JSON string

json_string = txt[start:end]

# convert to python dictionary
import json
data = json.loads(json_string)

# example data
#(I found this manually using `data.keys(), data['sports'][0].keys(), etc.)
data['sports'][0]['leagues'][0]['events'][0]['odds']['home']['moneyLine']


问:
Exit nightwatch cucumber process with exit code 0?
Is it possible to exit nightwatch-cucumber with an exit code of 0 even when the tests fail?

Reason being, with the breaking changes you can no longer generate a cucumber report in a step, meaning you have to wait for the tests to finish, pass or fail, to generate the report.

The problem is that teamcity sees test failures and will not progress to the next step, due to the tests failing with an exit code not equal to 0, thus not generating the cucumber report.

答: I suggest to run cucumber report generation from NPM instead a separate Teamcity task. See the nightwatch-cucumber docs regarding this topic.


问:
Connecting to Windows Network Share Drive from NodeJS inside Docker Container
Been banging my head with this, and would appreciate any help! I did search, and found a few potential solutions, but all were a no go for me.

I have a nodejs application developed in windows, and is now running in a docker container (using the node:latest image). The application needs to connect to a shared windows network drive to perform read/writes, but it doesn't seem to be working when the application runs inside the docker container (It works fine when it is run on my windows machine outside of docker).

The network drive shared folder looks something like this. Shared to everyone:

\\myserver\test

The Nodejs code (not quite but gives you an idea of how I am accessing file):

```<code>let fileLocation = "\\myserver\test\file.pdf"
let readStream = fs.createReadStream(fileLocation)

// When the stream is done being read, end the response
readStream.on('close', () =>
{
    // End response
    response.status('200').end()

    // Remove the file
    fs.unlinkSync(fileLocation)
})

// Stream chunks to response
readStream.pipe(response)
</code>```

This works fine when run in nodejs on windows, but I keep getting a "ENOENT: no such file or directory" error when run inside the nodejs docker container. I'm not sure if this is a linux OS (which the node image is based on) or a docker permission/priviledge issue. The file does exist.

This is the command I'm using to test when I'm running the container

```<code>docker run --rm -it -p 8080:8080 myapplication:latest
</code>```

New to docker, but Any help is appreciated!

答:
Try mounting the volume using docker run -v (see documentation).

I'm hoping it will work on your Windows network share drive.

Update

Syntax of volume mounting in Windows is:
docker run -v c:/Users:/data alpine

Where c:/Users is the Windows directory on the host machine you'd like to mount (equivalent to C:\Users in Windows syntax), and data is the name of the mounted directory inside the running container.

Body:
Been banging my head with this, and would appreciate any help! I did search, and found a few potential solutions, but all were a no go for me.

I have a nodejs application developed in windows, and is now running in a docker container (using the node:latest image). The application needs to connect to a shared windows network drive to perform read/writes, but it doesn't seem to be working when the application runs inside the docker container (It works fine when it is run on my windows machine outside of docker).

The network drive shared folder looks something like this. Shared to everyone:

\\myserver\test

The Nodejs code (not quite but gives you an idea of how I am accessing file):

let fileLocation = "\\myserver\test\file.pdf"
let readStream = fs.createReadStream(fileLocation)

// When the stream is done being read, end the response
readStream.on('close', () =>
{
    // End response
    response.status('200').end()

    // Remove the file
    fs.unlinkSync(fileLocation)
})

// Stream chunks to response
readStream.pipe(response)

This works fine when run in nodejs on windows, but I keep getting a "ENOENT: no such file or directory" error when run inside the nodejs docker container. I'm not sure if this is a linux OS (which the node image is based on) or a docker permission/priviledge issue. The file does exist.

This is the command I'm using to test when I'm running the container

docker run --rm -it -p 8080:8080 myapplication:latest

New to docker, but Any help is appreciated!


问:
Force BottomSheet to hide when user is dragging
I am trying to force my BottomSheet to hide even when user is dragging.

For the discussion let's say that my app only contains two views :

- Button

- BottomSheet

At the beginning the BottomSheet is expanded. When I click the button I want the BottomSheet to completely hide, no matter if the user is dragging. I thought I would just have to set the BottomSheet's state to collapsed or hidden, but this only works if the user is not dragging the BottomSheet. If he's dragging, then nothing happens and the BottomSheet remains visible.

Here is what I've tried :

- set peekHeight to 0

- set state to hidden

- set state to collapsed

But none of this worked.

Any idea ?

答:
```<code> @Override
public void onBackPressed() {
    if (mBottomSheetBehavior.isHideable()) {
        super.onBackPressed();
    }else {
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
    }
}
</code>```


答:
If you're using a framework like Symfony, you shouldn't use require_once (except some exceptions). Read about autoloading and dependency injections (Symfony.com has excellent articles).

For some reason, the monetbil-php library doesn't use composer. I don't know why, but I can imagine three reasons: they don't know what it is (hello developers, it's  2017!), they hate other developers or the library hasn't been updated for years. Despite the recent commits, it looks like a very outdated library (why still supporting PHP 5.2? That's from the dark ages!). Sorry for this slightly offtopic rant, back to the question.

For now, copy the files to your project, give the file a namespace and use it in your project. I've opened an issue here because I think the developers should add a composer file if they want their users to use their library in a framework like Symfony.

The PHP code should be in your controller* since you can't use PHP in Twig and even if you could, you shouldn't. Monetbil defines business logic, so it shouldn't be in a template.

To use it in your controller:

```<code>/**
 * Pay the bill
 *
 * @Route("/pay/{id}", name="payment")
 * @Method("POST")
 * @param Request $request
 * @param Order $product
 *
 * @return JsonResponse
 * @throws \Exception
 */
public function payAction(Request $request, Order $product)
{
     Monetbil::setAmount(500);
     //..
     Monetbil::startPayment();
}
</code>```

According to the comment, startPayment() will redirect, so there's nothing to return to the Twig template.

(*) Business logic in your template is considered as a bad practice, but you should prevent putting too many business logic in a controller too. If you have this example working, try to read about services so you can define the business logic in a framework-agnostic way. It makes maintaining your application (unit tests, Symfony updates, maybe switch to another framework?) easier.

Title: Integrating Mobile Money to Symfony

Body:
If you're using a framework like Symfony, you shouldn't use require_once (except some exceptions). Read about autoloading and dependency injections (Symfony.com has excellent articles).

For some reason, the monetbil-php library doesn't use composer. I don't know why, but I can imagine three reasons: they don't know what it is (hello developers, it's  2017!), they hate other developers or the library hasn't been updated for years. Despite the recent commits, it looks like a very outdated library (why still supporting PHP 5.2? That's from the dark ages!). Sorry for this slightly offtopic rant, back to the question.

For now, copy the files to your project, give the file a namespace and use it in your project. I've opened an issue here because I think the developers should add a composer file if they want their users to use their library in a framework like Symfony.

The PHP code should be in your controller* since you can't use PHP in Twig and even if you could, you shouldn't. Monetbil defines business logic, so it shouldn't be in a template.

To use it in your controller:

/**
 * Pay the bill
 *
 * @Route("/pay/{id}", name="payment")
 * @Method("POST")
 * @param Request $request
 * @param Order $product
 *
 * @return JsonResponse
 * @throws \Exception
 */
public function payAction(Request $request, Order $product)
{
     Monetbil::setAmount(500);
     //..
     Monetbil::startPayment();
}

According to the comment, startPayment() will redirect, so there's nothing to return to the Twig template.

(*) Business logic in your template is considered as a bad practice, but you should prevent putting too many business logic in a controller too. If you have this example working, try to read about services so you can define the business logic in a framework-agnostic way. It makes maintaining your application (unit tests, Symfony updates, maybe switch to another framework?) easier.


问:
Find free tag numbers in SQL: How to find multiple numbers in a row for SQL query
I am trying to find free tag numbers in a SQL Server database. I have done this by declaring all possible tag numbers, and when a tag number is taken, it has a bit column that is set to 1. In other words, free tag numbers have BIT = 0.

```<code>SELECT TOP(\*NUMBERS*) TAG
FROM \*DATABASE*
WHERE BIT = 0
</code>```

*NUMBERS* is how many tags I need. The problem is after some tag numbers are deleted, and I am trying to get e.g. 5 tag numbers i a row (e.g. 10, 11, 12, 13, 14, 15) I might get a spread of values (e.g. 5, 8, 10, 11, 12). I want to be able to reuse deleted tag numbers, but I want every numbers to be in a row.

How could I solve this in best practice (in SQL or C#)?

答:
Sorry, not tested, but this query should give you the first tag of a sequence of NUMBERS free tags. The Idea should be clear...</p>

```<code>SELECT TOP (1) TAG FROM *DATABASE* D WHERE BIT = 0 AND *NUMBERS* = (SELECT
COUNT(*) FROM *DATABSE*  WHERE BIT = 0 AND TAG >= D.TAG AND TAG < D.TAG + *NUMBERS*)
</code>```

Body:
I am trying to find free tag numbers in a SQL Server database. I have done this by declaring all possible tag numbers, and when a tag number is taken, it has a bit column that is set to 1. In other words, free tag numbers have BIT = 0.

SELECT TOP(\*NUMBERS*) TAG
FROM \*DATABASE*
WHERE BIT = 0

*NUMBERS* is how many tags I need. The problem is after some tag numbers are deleted, and I am trying to get e.g. 5 tag numbers i a row (e.g. 10, 11, 12, 13, 14, 15) I might get a spread of values (e.g. 5, 8, 10, 11, 12). I want to be able to reuse deleted tag numbers, but I want every numbers to be in a row.

How could I solve this in best practice (in SQL or C#)?

Body:
Sorry, not tested, but this query should give you the first tag of a sequence of NUMBERS free tags. The Idea should be clear...

SELECT TOP (1) TAG FROM *DATABASE* D WHERE BIT = 0 AND *NUMBERS* = (SELECT
COUNT(*) FROM *DATABSE*  WHERE BIT = 0 AND TAG >= D.TAG AND TAG < D.TAG + *NUMBERS*)


问:
How to fetch data in Angular
can someone help me with getting number from http response in Angular 5 ? I don't now how to do it, I was searching at internet but Angular grow very fast so it doesn't help me. Thanks for any help !

My code:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../entities/User';

@Injectable()
export class UserService {

  private usersurl: 'http://localhost:8080/api/users';

  user: User;
  id: number;

  constructor(private http: HttpClient) {}

  isLoggedIn() {
    return this.user != null;
  }

  isAdmin() {
    return this.user.isAdmin;
  }

  unLoggin() {
    this.user = null;
  }

  login(username: string, password: string) {
    this.id = null;
    this.http.get<number>(`${this.usersurl}/verify?username=${username}&password=${password}`).subscribe(id => this.id = id);
    alert(this.id);
    if (this.id != null) {
      return true;
    } else {
      return false;
    }
  }

}
</code>```

It alert [object Object]
localhost:8080/api/users/verify returns for example 8 only 8 no json formated 8

答:
When you make a HTTP request it returns a observable object which you subscribe to. If you want to manipulate the data and only return the id you can use the map function.

```<code>function getUserID() {

    return this.http.get('this.usersurl + '/verify?username=' + username +
    '&password=' + password').map(val => val.id)
}

this.getUserID.subscribe((data) => {
    console.log(data); // should return the id (number).
});
</code>```

So the above returns only the id (number) of the val object.

Title: How to fetch data in Angular

Body:
can someone help me with getting number from http response in Angular 5 ? I don't now how to do it, I was searching at internet but Angular grow very fast so it doesn't help me. Thanks for any help !

My code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../entities/User';

@Injectable()
export class UserService {

  private usersurl: 'http://localhost:8080/api/users';

  user: User;
  id: number;

  constructor(private http: HttpClient) {}

  isLoggedIn() {
    return this.user != null;
  }

  isAdmin() {
    return this.user.isAdmin;
  }

  unLoggin() {
    this.user = null;
  }

  login(username: string, password: string) {
    this.id = null;
    this.http.get<number>(`${this.usersurl}/verify?username=${username}&password=${password}`).subscribe(id => this.id = id);
    alert(this.id);
    if (this.id != null) {
      return true;
    } else {
      return false;
    }
  }

}

It alert [object Object]
localhost:8080/api/users/verify returns for example 8 only 8 no json formated 8

Body:
When you make a HTTP request it returns a observable object which you subscribe to. If you want to manipulate the data and only return the id you can use the map function.

function getUserID() {

    return this.http.get('this.usersurl + '/verify?username=' + username +
    '&password=' + password').map(val => val.id)
}

this.getUserID.subscribe((data) => {
    console.log(data); // should return the id (number).
});

So the above returns only the id (number) of the val object.


问:
running a mysql query inside a loop of another without a sync error
If I have code like this (irrelevant things like initialising the connection and handle omitted):

```<code>MYSQL_RES *res;
MYSQL_ROW row;
mysql_query(mysql, "some select query");
res = mysql_use_result(mysql);
while (row = mysql_fetch_row(res)) {
    MYSQL_RES *res2;
    MYSQL_ROW row2;
    mysql_query(mysql, "some other select query using an id from the first");
    res2 = mysql_use_result(mysql);
    /* ... */
    mysql_free_result(res2);
}
mysql_free_result(res);
</code>```

Whenever I run the second mysql_query (in the loop), I get the error

```<code>mysql: 2014: Commands out of sync; you can't run this command now
</code>```

How can I run another select query while fetching rows from one select query?

答:
I sent an email to the MySQL mailing list. Basically, to be able to do this, I need to have two independent MySQL connections. Thanks, Shawn Green (from Oracle).

The mysql object you are using for your connection can only have one active query or result on it at a time. To have two sets of results working, you need a second independent connection to the MySQL server

ContentLicense: CC BY-SA 2.5

Body:
If I have code like this (irrelevant things like initialising the connection and handle omitted):

MYSQL_RES *res;
MYSQL_ROW row;
mysql_query(mysql, "some select query");
res = mysql_use_result(mysql);
while (row = mysql_fetch_row(res)) {
    MYSQL_RES *res2;
    MYSQL_ROW row2;
    mysql_query(mysql, "some other select query using an id from the first");
    res2 = mysql_use_result(mysql);
    /* ... */
    mysql_free_result(res2);
}
mysql_free_result(res);

Whenever I run the second mysql_query (in the loop), I get the error

mysql: 2014: Commands out of sync; you can't run this command now

How can I run another select query while fetching rows from one select query?


问:
How to find time intervals with no data points in InfluxDB
I have a bunch of IoT sensors that upload second by second data to InfluxDB.  Since their network is unreliable, sometimes they do not report data.

I'm trying to figure out how to determine time periods in InfluxDB for which there is no data, and am encountering some wacky behavior with subqueries.

What I've tried so far:

Count the number of points each second, for example:

```<code>select count(power)
from energy
where time < '2017-05-14T00:05:10Z'
  and time >= '2017-05-14T00:04:30Z'
group by time(1s);
</code>```

This looks promising, as it returns a result for each second in the interval and the count of data points:

```<code>...
1494720297000000000 1
1494720298000000000 1
1494720299000000000 0
1494720300000000000 0
...
</code>```

Now I want only the time periods where there are 0 points, however when I try this, only time ranges with non-zero numbers of points are reported:

```<code>select "points"
from
    (select count(power) as "points"
     from energy
     where time < '2017-05-14T00:05:10Z'
       and time >= '2017-05-14T00:04:30Z'
     group by time(1s));
</code>```

Returns:

```<code>...
1494720297000000000 1
1494720298000000000 1
</code>```

No data after 1494720298000000000 is returned, even though the subquery does return rows.

Any help would be appreciated in crafting a query or approach to identify only the areas of time where there is no data.

答:
add fill(none) after your query

Example-select count(power)from energy where time < '2017-05-14T00:05:10Z' and time >= '2017-05-14T00:04:30Z' group by time(1s) fill(none)

Body:
I have a bunch of IoT sensors that upload second by second data to InfluxDB.  Since their network is unreliable, sometimes they do not report data.

I'm trying to figure out how to determine time periods in InfluxDB for which there is no data, and am encountering some wacky behavior with subqueries.

What I've tried so far:

Count the number of points each second, for example:

select count(power)
from energy
where time < '2017-05-14T00:05:10Z'
  and time >= '2017-05-14T00:04:30Z'
group by time(1s);

This looks promising, as it returns a result for each second in the interval and the count of data points:

...
1494720297000000000 1
1494720298000000000 1
1494720299000000000 0
1494720300000000000 0
...

Now I want only the time periods where there are 0 points, however when I try this, only time ranges with non-zero numbers of points are reported:

select "points"
from
    (select count(power) as "points"
     from energy
     where time < '2017-05-14T00:05:10Z'
       and time >= '2017-05-14T00:04:30Z'
     group by time(1s));

Returns:

...
1494720297000000000 1
1494720298000000000 1

No data after 1494720298000000000 is returned, even though the subquery does return rows.

Any help would be appreciated in crafting a query or approach to identify only the areas of time where there is no data.


问:
How to import multiple pages into Excel from ESPN
I need to import data from ESPN Fantasy Football into Excel. This includes multiple pages and a web query does not work. The URL is http://games.espn.com/ffl/tools/projections?startIndex=0. When you click next, the URL becomes http://games.espn.com/ffl/tools/projections?startIndex=40 and 80 and so on. Basically, the startIndex increments to multiples of 40 when you click on the next page.

This is the code I've user so far modifying the code provided by @Dee and it seems to adding a new worksheet but has no data in it.

```<code> Private Const URL_TEMPLATE As String =
"URL;http://games.espn.com/ffl/tools/projections?startIndex={0}"
Private Const NUMBER_OF_PAGES As Byte = 7

Sub test()
    Dim page As Byte
    Dim queryTableObject As QueryTable
    Dim url As String

    For page = 1 To NUMBER_OF_PAGES
        url = VBA.Strings.Replace(URL_TEMPLATE, "{0}", page * 40)
        Set queryTableObject = ActiveSheet.QueryTables.Add(Connection:=url, Destination:=ThisWorkbook.Worksheets.Add.[a1])
        queryTableObject.WebSelectionType = xlSpecifiedTables
        queryTableObject.WebTables = "14"
        queryTableObject.Refresh
    Next page

End Sub
</code>```

The end result should be pulling all the columns from each page into a tab in one Excel sheet. Is there a way to do this? Please assist.

Thanks,
J

答:
The Id of the table is not 14 but playertable_0. If you need to paste all the data to one single sheet try to use the following modified code. Number of pages is here determined just by guessing. You will have to add some more code to prove if e.g. the Next element is present on the page and do it in do-loop or just simply guess the number of pages. HTH

```<code>Option Explicit

Private Const URL_TEMPLATE As String = _
 "URL;http://games.espn.com/ffl/tools/projections?startIndex={0}"
Private Const NUMBER_OF_PAGES As Byte = 20
Private Const TableId As String = "playertable_0"

Sub test()
    Dim page As Byte
    Dim queryTableObject As QueryTable
    Dim url As String
    Dim ws As Worksheet
    Dim target As Range
    Dim lastRow As Long

    Set ws = ThisWorkbook.Worksheets.Add
    Set target = ws.[a1]
    lastRow = 1

    For page = 0 To NUMBER_OF_PAGES
        url = VBA.Strings.Replace(URL_TEMPLATE, "{0}", page * 40)

        Set queryTableObject = ActiveSheet.QueryTables.Add( _
            Connection:=url, _
            Destination:=target)

        With queryTableObject
            .BackgroundQuery = False ' Run the query synchronously
                                     ' to be able to compute the last row
            .WebSelectionType = xlSpecifiedTables
            .WebTables = TableId
            .Refresh
        End With

        lastRow = ws.Cells.Find( _
            what:="*", _
            SearchDirection:=xlPrevious, _
            SearchOrder:=xlByRows) _
            .Row

        Set target = ws.Cells(lastRow + 1, 1)
        target.Select
    Next page
End Sub
</code>```

Body:
I need to import data from ESPN Fantasy Football into Excel. This includes multiple pages and a web query does not work. The URL is http://games.espn.com/ffl/tools/projections?startIndex=0. When you click next, the URL becomes http://games.espn.com/ffl/tools/projections?startIndex=40 and 80 and so on. Basically, the startIndex increments to multiples of 40 when you click on the next page.

This is the code I've user so far modifying the code provided by @Dee and it seems to adding a new worksheet but has no data in it.

 Private Const URL_TEMPLATE As String =
"URL;http://games.espn.com/ffl/tools/projections?startIndex={0}"
Private Const NUMBER_OF_PAGES As Byte = 7

Sub test()
    Dim page As Byte
    Dim queryTableObject As QueryTable
    Dim url As String

    For page = 1 To NUMBER_OF_PAGES
        url = VBA.Strings.Replace(URL_TEMPLATE, "{0}", page * 40)
        Set queryTableObject = ActiveSheet.QueryTables.Add(Connection:=url, Destination:=ThisWorkbook.Worksheets.Add.[a1])
        queryTableObject.WebSelectionType = xlSpecifiedTables
        queryTableObject.WebTables = "14"
        queryTableObject.Refresh
    Next page

End Sub

The end result should be pulling all the columns from each page into a tab in one Excel sheet. Is there a way to do this? Please assist.

Thanks,
J

Body:
The Id of the table is not 14 but playertable_0. If you need to paste all the data to one single sheet try to use the following modified code. Number of pages is here determined just by guessing. You will have to add some more code to prove if e.g. the Next element is present on the page and do it in do-loop or just simply guess the number of pages. HTH

Option Explicit

Private Const URL_TEMPLATE As String = _
 "URL;http://games.espn.com/ffl/tools/projections?startIndex={0}"
Private Const NUMBER_OF_PAGES As Byte = 20
Private Const TableId As String = "playertable_0"

Sub test()
    Dim page As Byte
    Dim queryTableObject As QueryTable
    Dim url As String
    Dim ws As Worksheet
    Dim target As Range
    Dim lastRow As Long

    Set ws = ThisWorkbook.Worksheets.Add
    Set target = ws.[a1]
    lastRow = 1

    For page = 0 To NUMBER_OF_PAGES
        url = VBA.Strings.Replace(URL_TEMPLATE, "{0}", page * 40)

        Set queryTableObject = ActiveSheet.QueryTables.Add( _
            Connection:=url, _
            Destination:=target)

        With queryTableObject
            .BackgroundQuery = False ' Run the query synchronously
                                     ' to be able to compute the last row
            .WebSelectionType = xlSpecifiedTables
            .WebTables = TableId
            .Refresh
        End With

        lastRow = ws.Cells.Find( _
            what:="*", _
            SearchDirection:=xlPrevious, _
            SearchOrder:=xlByRows) _
            .Row

        Set target = ws.Cells(lastRow + 1, 1)
        target.Select
    Next page
End Sub


问:
Adding columns with two data types in SQL Server
I need to achieve the output like this can anyone please help me. Thanks in advance

答:
You could use left() & right() function if your data format will always in specified format

```<code>select LEFT(names, 1) [name], SUM(cast(right(names, 2) as int)) [sum] from <table>
group by LEFT(names, 1)
</code>```

Body:
You could use left() & right() function if your data format will always in specified format

select LEFT(names, 1) [name], SUM(cast(right(names, 2) as int)) [sum] from <table>
group by LEFT(names, 1)


问:
Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON
I've got a cascading drop-drown using mvc. Something like, if you select a country in the first-dropdown, the states of that country in the second one should be populated accordingly.

At the moment, all seems fine and I'm getting Json response (saw it using F12 tools), and it looks something like  [{ "stateId":"01", "StateName": "arizona" } , { "stateId" : "02", "StateName":"California" }, etc..] ..

I'd like to know how to populate my second-dropdown with this data. My second drop-down's id is "StateID". Any help would be greatly appreciated.

Below is the code used to produce the JSON Response from the server:

[HttpPost]
public JsonResult GetStates(string CountryID)
{
    using (mdb)
    {
        var statesResults = from q in mdb.GetStates(CountryID)
                        select new Models.StatesDTO
                        {
                            StateID = q.StateID,
                            StateName = q.StateName
                        };

        locations.statesList = stateResults.ToList();
    }

    JsonResult result = new JsonResult();

    result.Data = locations.statesList;

    return result;
}
```
<p>Below is the client-side HTML, my razor-code and  my script. I want to write some code inside "<code>success</code>:" so that it populates the States <code>dropdown</code> with the JSON data.</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
    $(function () {
        $("select#CountryID").change(function (evt) {

            if ($("select#CountryID").val() != "-1") {

                $.ajax({
                    url: "/Home/GetStates",
                    type: 'POST',
                    data: { CountryID: $("select#CountryID").val() },
                    success: function () { alert("Data retrieval successful"); },
                    error: function (xhr) { alert("Something seems Wrong"); }
                });
            }
        });
    });
</script>
</code>```

答:
You should consider using some client-side view engine that binds a model (in your case JSON returned from API) to template (HTML code for SELECT). Angular and React might be to complex for this use case, but JQuery view engine enables you to easily load JSON model into template using MVC-like approach:

```<code><script type="text/javascript">
    $(function () {
        $("select#CountryID").change(function (evt) {

            if ($("select#CountryID").val() != "-1") {

                $.ajax({
                    url: "/Home/GetStates",
                    type: 'POST',
                    data: { CountryID: $("select#CountryID").val() },
                    success: function (response) {
                             $("#stateID").empty();
                             $("#stateID").view(response);
                    },
                    error: function (xhr) { alert("Something seems Wrong"); }
                });
            }
        });
    });
</script>
</code>```

It is much cleaner that generating raw HTML in JavaScript. See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

Body:
I've got a cascading drop-drown using mvc. Something like, if you select a country in the first-dropdown, the states of that country in the second one should be populated accordingly.

At the moment, all seems fine and I'm getting Json response (saw it using F12 tools), and it looks something like  [{ "stateId":"01", "StateName": "arizona" } , { "stateId" : "02", "StateName":"California" }, etc..] ..

I'd like to know how to populate my second-dropdown with this data. My second drop-down's id is "StateID". Any help would be greatly appreciated.

Below is the code used to produce the JSON Response from the server:

[HttpPost]
public JsonResult GetStates(string CountryID)
{
    using (mdb)
    {
        var statesResults = from q in mdb.GetStates(CountryID)
                        select new Models.StatesDTO
                        {
                            StateID = q.StateID,
                            StateName = q.StateName
                        };

        locations.statesList = stateResults.ToList();
    }

    JsonResult result = new JsonResult();

    result.Data = locations.statesList;

    return result;
}

Below is the client-side HTML, my razor-code and  my script. I want to write some code inside "success:" so that it populates the States dropdown with the JSON data.

Body:
You should consider using some client-side view engine that binds a model (in your case JSON returned from API) to template (HTML code for SELECT). Angular and React might be to complex for this use case, but JQuery view engine enables you to easily load JSON model into template using MVC-like approach:

<script type="text/javascript">
    $(function () {
        $("select#CountryID").change(function (evt) {

            if ($("select#CountryID").val() != "-1") {

                $.ajax({
                    url: "/Home/GetStates",
                    type: 'POST',
                    data: { CountryID: $("select#CountryID").val() },
                    success: function (response) {
                             $("#stateID").empty();
                             $("#stateID").view(response);
                    },
                    error: function (xhr) { alert("Something seems Wrong"); }
                });
            }
        });
    });
</script>

It is much cleaner that generating raw HTML in JavaScript. See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown


问:
After IF statment is fired as True, from inside this code move to the Else part of the IF statement
I am curious to know one thing. Is it possible in .NET (or in any language that you might have faced to execute this scenario:

Pseudo code below:

```<code>if(statement)
  //do something
  //Because you calculated or read something else, **drop|go|navigate** to else part
  //(not necessarily error or exception)
  //rest of if-true code continues, but is not executed because you moved to else
else
 //do something in else part, code continues here and is executed till the end normally
end-if
</code>```

Before you down vote me, I know this is a perfect try-throw-catch solvable implementation and this is how I address it for now.

Inside the if I don't need to throw an exception because in terms of logic and BI there is absolutely no exception.

I need to know if it is supported in .NET or any other language through the if declaration without throwing an exception or implementing it with try-catch.

With the simplest words I can find... my question is: Is it possible to execute the Else part of an if condition even if the if(true) is fired? Can I change my mind inside the if(true)?

答:
In some programming languages you can, using LABELS and GOTO

But understanding the problem would help finding a good solution. It seems an IF/ELSE is not what you want, why not using 2 ifs ? If you want to just go straight to the second option... Maybe close inside a function/method, and call whenever you need. Explain the problem better and maybe we can get a solution better :P

Body:
I am curious to know one thing. Is it possible in .NET (or in any language that you might have faced to execute this scenario:

Pseudo code below:

if(statement)
  //do something
  //Because you calculated or read something else, **drop|go|navigate** to else part
  //(not necessarily error or exception)
  //rest of if-true code continues, but is not executed because you moved to else
else
 //do something in else part, code continues here and is executed till the end normally
end-if

Before you down vote me, I know this is a perfect try-throw-catch solvable implementation and this is how I address it for now.

Inside the if I don't need to throw an exception because in terms of logic and BI there is absolutely no exception.

I need to know if it is supported in .NET or any other language through the if declaration without throwing an exception or implementing it with try-catch.

With the simplest words I can find... my question is: Is it possible to execute the Else part of an if condition even if the if(true) is fired? Can I change my mind inside the if(true)?


问:
Writing a big text file fast
How can I write a big text file very fast on Android?

I made some tests using a PrintWriter, a BufferedWriter and a FileWriter, but there are no significative time difference, and writing takes about three times the time of reading.

答:
Android, just like every single other device with a storage unit, has limited writing speed.

The only thing you can do to speed up file writing and reading is get a better storage unit (which isn't as easy on an Android device as you can't just screw it open and replace the unit).

So when it comes to file reading and writing, you're limited by hardware.

Title: Writing a big text file fast


问:
Lightbox2 next arrow disappears after the first image of the group
I have 3 pics that I want to link them in my photo gallery. So when I click one of the image, it should have the next and previous arrow that allow the user to go to another image. My codes with lightbox2 is as below.

```<code><a href="my/path/images/image1.jpg" data-lightbox="roadtrip" data-title="My caption">
<img src="my/path/thumbnails/thumb1.jpg" alt="Surfing"/>
</a>
<a href="my/path/images/image2.jpg" data-lightbox="roadtrip" data-title="My caption">
<img src="my/path/thumbnails/thumb2.jpg" alt="Lifeguard Stand"/>
</a>
<a href="my/path/images/image3.jpg" data-lightbox="roadtrip" data-title="My caption">
<img src="my/path/thumbnails/thumb3.jpg" alt="Hot Air Balloons"/>
</a>
</code>```

So now when I run the code, in the first image there will be an next arrow that links to the second image. However, when the user is in the second image, there is only previous arrow but no next arrow. But I want both arrows to appear.

If anyone knows how to solve the issue, please let me know. Appreciated!!

答:
Ok so I found the answer by myself and below is the answer for many people who may have encountered the same problems.

Just change the width of .lb-nav a.lb-prev in the lightbox.css and it should work. I change it from 64% to 50% and then the next arrow appears.

I don't have time digging into what's the essential cause is, but this solution does work. If anyone knows what exactly happens there, please feel free to leave a comment or answer. Appreciated!

Body:
I have 3 pics that I want to link them in my photo gallery. So when I click one of the image, it should have the next and previous arrow that allow the user to go to another image. My codes with lightbox2 is as below.

So now when I run the code, in the first image there will be an next arrow that links to the second image. However, when the user is in the second image, there is only previous arrow but no next arrow. But I want both arrows to appear.

If anyone knows how to solve the issue, please let me know. Appreciated!!


问:
Android 2.2: Reboot device programmatically
I would like to know if there is a way to reboot the device through code. Ive tried:

```<code>Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);
</code>```

And added permissions for REBOOT but it still doesnt work.

Thanks

答:
If the phone is rooted, it's actually very simple:

```<code>try {
    Runtime.getRuntime().exec("su");
    Runtime.getRuntime().exec("reboot");
} catch (IOException e) {
}
</code>```

The first command will ask for superuser permission. The second, will reboot the phone.
There is no need for extra permissions in the manifest file since the actual rebooting is handled by the executed comamand, not the app.

Body:
I would like to know if there is a way to reboot the device through code. Ive tried:

Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);

And added permissions for REBOOT but it still doesnt work.

Thanks

Body:
If the phone is rooted, it's actually very simple:

try {
    Runtime.getRuntime().exec("su");
    Runtime.getRuntime().exec("reboot");
} catch (IOException e) {
}

The first command will ask for superuser permission. The second, will reboot the phone.
There is no need for extra permissions in the manifest file since the actual rebooting is handled by the executed comamand, not the app.


问:
SWI Prolog - Recursion with lists
I am new to ProLog and I am having some troubles understanding recursion over lists.

I am stuck on this exercise. Basically given the vocabulary I need to convert a list of Italian numbers to English numbers.

This is my KB.

```<code>tran(uno, one).
tran(due, two).
tran(tre, three).
tran(quattro, four).
tran(cinque, five).
tran(sei, six).
tran(sette, seven).
tran(otto, eight).
tran(nove, nine).

listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).
</code>```

This program should give the translated list (in reverse order). However, it only outputs true when I pass:

```<code>?- listran(X, [uno, due, tre]).
</code>```

I've tried to trace it and seems that at the end removes?? all elements from my translated list. This is the trace output.

```<code>[trace]  ?- listran(X,[uno,due,tre]).
   Call: (8) listran(_5566, [uno, due, tre]) ? creep
   Call: (9) tran(uno, _5820) ? creep
   Exit: (9) tran(uno, one) ? creep
   Call: (9) listran([one|_5566], [due, tre]) ? creep
   Call: (10) tran(due, _5826) ? creep
   Exit: (10) tran(due, two) ? creep
   Call: (10) listran([two, one|_5566], [tre]) ? creep
   Call: (11) tran(tre, _5832) ? creep
   Exit: (11) tran(tre, three) ? creep
   Call: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (10) listran([two, one|_5566], [tre]) ? creep
   Exit: (9) listran([one|_5566], [due, tre]) ? creep
   Exit: (8) listran(_5566, [uno, due, tre]) ? creep
true.
</code>```

Can someone help me understanding this little problem?

Thank you in advance.

答:
An interesting (and "prologish") way is to use DCG :</p>

```<code>tran(uno) --> [one].
tran(due) --> [two].
tran(tre) --> [three].
tran(quattro) --> [four].
tran(cinque) --> [five].
tran(sei) -->  [six].
tran(sette) -->  [seven].
tran(otto) -->  [eight].
tran(nove) --> [nine].

listran(In,Out) :-
    phrase(trans(In), Out).

trans([]) --> [].

trans([H|T]) --> tran(H), trans(T).
</code>```

Title: SWI Prolog - Recursion with lists

Body:
I am new to ProLog and I am having some troubles understanding recursion over lists.

I am stuck on this exercise. Basically given the vocabulary I need to convert a list of Italian numbers to English numbers.

This is my KB.

tran(uno, one).
tran(due, two).
tran(tre, three).
tran(quattro, four).
tran(cinque, five).
tran(sei, six).
tran(sette, seven).
tran(otto, eight).
tran(nove, nine).

listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).

This program should give the translated list (in reverse order). However, it only outputs true when I pass:

?- listran(X, [uno, due, tre]).

I've tried to trace it and seems that at the end removes?? all elements from my translated list. This is the trace output.

[trace]  ?- listran(X,[uno,due,tre]).
   Call: (8) listran(_5566, [uno, due, tre]) ? creep
   Call: (9) tran(uno, _5820) ? creep
   Exit: (9) tran(uno, one) ? creep
   Call: (9) listran([one|_5566], [due, tre]) ? creep
   Call: (10) tran(due, _5826) ? creep
   Exit: (10) tran(due, two) ? creep
   Call: (10) listran([two, one|_5566], [tre]) ? creep
   Call: (11) tran(tre, _5832) ? creep
   Exit: (11) tran(tre, three) ? creep
   Call: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (10) listran([two, one|_5566], [tre]) ? creep
   Exit: (9) listran([one|_5566], [due, tre]) ? creep
   Exit: (8) listran(_5566, [uno, due, tre]) ? creep
true.

Can someone help me understanding this little problem?

Thank you in advance.

Body:
An interesting (and "prologish") way is to use DCG :

tran(uno) --> [one].
tran(due) --> [two].
tran(tre) --> [three].
tran(quattro) --> [four].
tran(cinque) --> [five].
tran(sei) -->  [six].
tran(sette) -->  [seven].
tran(otto) -->  [eight].
tran(nove) --> [nine].

listran(In,Out) :-
    phrase(trans(In), Out).

trans([]) --> [].

trans([H|T]) --> tran(H), trans(T).


问:
Django Queryset get list for the day of a particular type, unique foreignkey id using Postgres database
I am trying to find a query to get a list of latest attendance for a particular day, with unique employee that has checked in (CHECKIN = 1)

Below is my model, records and what I am trying to accomplish.

My model has 2 models:

```<code>class Employee(models.Model):
    fullname = models.CharField(max_length=30, blank=False)

class Attendance(models.Model):
    CHECKIN = 1
    CHECKOUT = 2
    ATTENDANCE_TYPE_CHOICES = (
        (CHECKIN, "Check In"),
        (CHECKOUT, "Check Out"),
    )
    employee = models.ForeignKey(Employee)
    activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
    timestamp = models.DateTimeField(auto_now_add=True)
</code>```

Assuming I have the records below:

```<code>Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift"}

Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30",
"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":8, "employee": 1,"activity_type": 2, timestamp: "2017-12-06 08:08"}
</code>```

I am interest so that it output this 2 record only based on the activity type 1 for CHECKIN and for the date 2017-12-05 and that employee id must be unique and latest:

```<code>{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"
"id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30"}
</code>```

I am using Postgres 9.4

How can I produce the intended result with Django queryset ?

答:
Filter attendance by activity_type, order by employee_id and -timestamp then use distinct on employee_id

```<code>Attendance.objects.filter(activity_type=Attendance.CHECKIN).order_by('employee_id','-timestamp').distinct('employee_id')
</code>```

Body:
I am trying to find a query to get a list of latest attendance for a particular day, with unique employee that has checked in (CHECKIN = 1)

Below is my model, records and what I am trying to accomplish.

My model has 2 models:

class Employee(models.Model):
    fullname = models.CharField(max_length=30, blank=False)

class Attendance(models.Model):
    CHECKIN = 1
    CHECKOUT = 2
    ATTENDANCE_TYPE_CHOICES = (
        (CHECKIN, "Check In"),
        (CHECKOUT, "Check Out"),
    )
    employee = models.ForeignKey(Employee)
    activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
    timestamp = models.DateTimeField(auto_now_add=True)

Assuming I have the records below:

Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift"}

Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30",
"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":8, "employee": 1,"activity_type": 2, timestamp: "2017-12-06 08:08"}

I am interest so that it output this 2 record only based on the activity type 1 for CHECKIN and for the date 2017-12-05 and that employee id must be unique and latest:

{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"
"id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30"}

I am using Postgres 9.4

How can I produce the intended result with Django queryset ?

Body:
Filter attendance by activity_type, order by employee_id and -timestamp then use distinct on employee_id

Attendance.objects.filter(activity_type=Attendance.CHECKIN).order_by('employee_id','-timestamp').distinct('employee_id')


问:
Google apps reinstall after uninstall
Hello everyone and thank you in advance,
I have an estar Gemini tablet, in which I have flashed the firmware, and installed kingroot. I need to uninstall every app that it has (except the apps needed). For some reason the GooglePlayStore, PlayMovies&TV and GoogleMaps simply reappear whenever I uninstall them. Only these 3 apps. Is there something I can do?</p>

答:
You can find the apks of system apps in the /system/app folder and the /custpack/app folder, as well as the protected apps' apks in the /system/priv-app folder(Source).

My advice would be to navigate to those directories with a file explorer (the free version of ES File Explorer will do), delete the apks of the aforementioned apps and uninstall them using a system app uninstaller (this app is a good choice).

Title: Google apps reinstall after uninstall