问:
send all values from ng repeat in a form
Well I'm generating a ng-repat but I need change data and send all this for edit in back end my problem is when I want to do this, can't obtain values of the form inside ng-repeat

The picture is the form that have, in html looks:

```<code> <form name="FormTablesPackageCreation">
                    <table class="table table-striped ta  ble-bordered">
                        <thead>
                        <tr>
                            <th>Estado</th>
                            <th>Especie</th>
                            <th>Tipo</th>
                            <th>Dimension</th>
                            <th>ubicacion</th>
                            <th>largo</th>
                            <th>Ancho</th>
                            <th>Espesor</th>
                            <th>Cantidad</th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="packageList in dataListTables">
                                <input class="form-control" type="hidden" ng-value="packageList.id_table"  name="id_table[{{$index}}]" id="id_table[{{$index}}]">
                                <input class="form-control" type="hidden" ng-value="packageList.id_package" name="id_package[{{$index}}]" id="id_package[{{$index}}]">
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.estado" ng-model="vm.estado" name="estado[{{$index}}]" id="estado[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.especie" name="especie[{{$index}}]" id="especie[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.ubicacion" name="ubicacion[{{$index}}]" id="ubicacion[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.dimension" name="dimension[{{$index}}]" id="dimension[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.tipo" value="{{packageList.tipo}}" name="tipo[{{$index}}]" id="tipo[{{$index}}]" readonly>
                                </td>

                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.humedad" value="{{packageList.humedad}}" name="humedad[{{$index}}]" id="humedad[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.disponible" value="{{packageList.disponible}}" name="disponible[{{$index}}]" id="disponible[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.largo" name="largo[{{$index}}]" id="largo[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.ancho" name="ancho[{{$index}}]" id="ancho[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.espesor" name="espesor[{{$index}}]" id="espesor[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-model="packageList.cantidad" ng-value="packageList.cantidad" ng-change=""  name="cantidad[{{$index}}]" id="cantidad[{{$index}}]" required>
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>Cantidad de tablas</td>
                                <td>
                                    <input class="form-control" type="text" ng-model="vm.total" ng-value="dataListTables | sumByColumn: 'cantidad'" name="total" id="total" readonly>
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>Cantidad de tablas nuevo paquete</td>
                                <td>
                                    <input class="form-control" type="text" ng-model="vm.Referencial" ng-value="sumNewCan(dataListTables | sumByColumn: 'cantidad')" readonly>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div>
                        <br>
                        <button class="btn btn-primary btn-lg" ng-click="crearPaquete()">Crear nuevo Paquetes</button>
                    </div>
                </form>
</code>```

how I'm trying to obtain of values:

```<code>$scope.crearPaquete = function ()
{
    var vm = this;
    $scope.seleccionadorEspecies = false;
    $scope.creadorPaquetes = false;
    $scope.verificacionPaquetes = true;

    for (var i = 0; i < FormTablesPackageCreation.cantidad.length; i++)
    {
        console.log(FormTablesPackageCreation.id_table[i].value);
        console.log(FormTablesPackageCreation.id_package[i].value);
        console.log(FormTablesPackageCreation.cantidad[i].value);
    }
};
</code>```

I need obtain data of the ng-repeat, Try another way but do not work yet.

答:
Its very simple.
Add ng-model in input tag like this

```<code><input class="form-control" type="text" ng-value="packageList.humedad" value="{{packageList.humedad}}" ng-model ="packageList.humedad" name="humedad[{{$index}}]" id="humedad[{{$index}}]" readonly>
</code>```

You can get the updated value in the controller like $scope.dataListTables. hope it will help you.

Body:
Well I'm generating a ng-repat but I need change data and send all this for edit in back end my problem is when I want to do this, can't obtain values of the form inside ng-repeat

The picture is the form that have, in html looks:

 <form name="FormTablesPackageCreation">

                            Estado
                            Especie
                            Tipo
                            Dimension
                            ubicacion
                            largo
                            Ancho
                            Espesor
                            Cantidad

                                <input class="form-control" type="hidden" ng-value="packageList.id_table"  name="id_table[{{$index}}]" id="id_table[{{$index}}]">
                                <input class="form-control" type="hidden" ng-value="packageList.id_package" name="id_package[{{$index}}]" id="id_package[{{$index}}]">

                                    <input class="form-control" type="text" ng-value="packageList.estado" ng-model="vm.estado" name="estado[{{$index}}]" id="estado[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.especie" name="especie[{{$index}}]" id="especie[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.ubicacion" name="ubicacion[{{$index}}]" id="ubicacion[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.dimension" name="dimension[{{$index}}]" id="dimension[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.tipo" value="{{packageList.tipo}}" name="tipo[{{$index}}]" id="tipo[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.humedad" value="{{packageList.humedad}}" name="humedad[{{$index}}]" id="humedad[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.disponible" value="{{packageList.disponible}}" name="disponible[{{$index}}]" id="disponible[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.largo" name="largo[{{$index}}]" id="largo[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.ancho" name="ancho[{{$index}}]" id="ancho[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.espesor" name="espesor[{{$index}}]" id="espesor[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-model="packageList.cantidad" ng-value="packageList.cantidad" ng-change=""  name="cantidad[{{$index}}]" id="cantidad[{{$index}}]" required>

                                Cantidad de tablas

                                    <input class="form-control" type="text" ng-model="vm.total" ng-value="dataListTables | sumByColumn: 'cantidad'" name="total" id="total" readonly>

                                Cantidad de tablas nuevo paquete

                                    <input class="form-control" type="text" ng-model="vm.Referencial" ng-value="sumNewCan(dataListTables | sumByColumn: 'cantidad')" readonly>

                        <button class="btn btn-primary btn-lg" ng-click="crearPaquete()">Crear nuevo Paquetes</button>

                </form>

how I'm trying to obtain of values:

$scope.crearPaquete = function ()
{
    var vm = this;
    $scope.seleccionadorEspecies = false;
    $scope.creadorPaquetes = false;
    $scope.verificacionPaquetes = true;

    for (var i = 0; i < FormTablesPackageCreation.cantidad.length; i++)
    {
        console.log(FormTablesPackageCreation.id_table[i].value);
        console.log(FormTablesPackageCreation.id_package[i].value);
        console.log(FormTablesPackageCreation.cantidad[i].value);
    }
};

I need obtain data of the ng-repeat, Try another way but do not work yet.

Body:
Its very simple.
Add ng-model in input tag like this

<input class="form-control" type="text" ng-value="packageList.humedad" value="{{packageList.humedad}}" ng-model ="packageList.humedad" name="humedad[{{$index}}]" id="humedad[{{$index}}]" readonly>

You can get the updated value in the controller like $scope.dataListTables. hope it will help you.


来源: stackexchange

问:
How to find the Sass file for a particular HTML page in ionic?
As per the ionic tutorial Ionic Framework Tutorial

The styles should be added in the Sass file for the page.
I am unable to find the Sass file for the HTML pages in the template folder.

答:
Whenever you create a new page you need at least 2 files: a .ts file to define the page and its logic and an .html file to define what it show (otherwise called the template). If you want, you may also create a third .scss file wherin you can specify how the data defined in the template are styled.

All these 2 or 3 files are usually stored on the same folder for each page.

If you manually created a page (you created the .ts and html files) then just create another new .scss file in the same directory with them and with the same filename.

Alternatevely you can use the CLI to generate pages for you automatically by typing in the terminal:

ionic generate page MyNewPage

or its shorthand which also works (handy if you use it a lot)

ionic g p MyNewPage

ContentLicense: CC BY-SA 3.0


问:
Am getting Caused by: java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey this exception
basically my pom structure dependencies would look like

```<code><dependencies>
     <!-- Spring -->

     <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.4.Final</version>
    </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${org.springframework-version}</version>
   <exclusions>
    <!-- Exclude Commons Logging in favor of SLF4j -->
    <exclusion>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     </exclusion>
   </exclusions>
  </dependency>
  <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework-version}</version>
  </dependency>

   <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

  <dependency>
   <groupId>org.springframework.webflow</groupId>
   <artifactId>spring-webflow</artifactId>
   <version>${org.springwebflow-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.webflow</groupId>
   <artifactId>spring-js</artifactId>
   <version>${org.springjs-version}</version>
  </dependency>

  <!-- Database, JPA -->
  <dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
   <version>${hsqldb.version}</version>

  </dependency>

    <!-- MySQL database driver -->
   <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.connector-version}</version>
   </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate-version}</version>
  </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-envers</artifactId>
   <version>${hibernate-envers-version}</version>
  </dependency>
  <!-- Servlet -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>${servlet-api-version}</version>
   <scope>provided</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>${jsp-version}</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.3.Final</version>
</dependency>

  </dependencies>
</code>```

and am trying the example of ehCache second level  example  and my project structure looks like

and i have declared my root context.xml as

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

    <!-- Root Context: defines shared resources visible to all other web components -->
    <import resource="classpath*:/META-INF/mvc-config/servlet-context.xml"/>
    <!-- <import resource="classpath*:/META-INF/security-config/spring-security.xml"/> -->
</beans>
</code>```

And my servlet-contextt.xml is

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

    <!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Enables Transaction Annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <context:annotation-config></context:annotation-config>

    <!-- Get AppData properties file -->
    <beans:bean id="appProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location" value="classpath:META-INF/application.properties" />
    </beans:bean>

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/, file:/${appDataPath}/" />

     <!-- Definition for view resolver -->
          <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <beans:property name="prefix" value="/WEB-INF/views/"/>
           <beans:property name="suffix" value=".jsp"/>
          </beans:bean>

    <!-- DataSource Bean -->
    <beans:bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="${DB.DRIVER}" />
        <beans:property name="url"
            value="${DB.URL}" />
        <beans:property name="username" value="${DB.UNAME}" />
        <beans:property name="password" value="${DB.PASS}"/>
    </beans:bean>

    <!-- SessionFactory Bean -->
    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="packagesToScan" value="com.darshan" />
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
                <beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
                <beans:prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</beans:prop>
                <beans:prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</beans:prop>
                <beans:prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</beans:prop>
                <beans:prop key="hibernate.hbm2ddl.auto">${hibernate.UPDATE_CREATE}</beans:prop>
                <beans:prop key="hbm2ddl.auto">${hbm2ddl.auto}</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

    <!-- TransactionManager -->

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

    <beans:bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:META-INF/validation" />
        <beans:property name="defaultEncoding" value="UTF-8" />
    </beans:bean>

    <context:component-scan base-package="com.darshan.mn" />

</beans:beans>
</code>```

Application.properties look like

```<code>#-- Contains the application configuration data --#
#--- Base file path for storing the files & images ---#
appDataPath=E:/eSchool/appData

#--- Database Props ---#
DB.DRIVER=com.mysql.jdbc.Driver
DB.URL=jdbc:mysql://localhost:3306/interview_preparation
DB.UNAME=root
DB.PASS=tiger

#--- File Upload: 10MB---#
maxFileUploadSize=100000000

#--- Java Mail Props ---#
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.mailgun.org
mail.smtp.port=587
mail.debug=false

#--- MailGun API Props ---#
mailGunUname=postmaster@sandbox187ce31a22334db2b4b17e499b407de6.mailgun.org
mailGunPass=cdf6e6fe99fe01efe669939c6c8c6301

#--- HibernateConfig ---#
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.UPDATE_CREATE=update
hbm2ddl.auto=update
hibernate.hbm2ddl.auto=create
hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
net.sf.ehcache.configurationResourceName=ehcache.xml
</code>```

my model class looks like

```<code>package com.darshan.mn.model;

import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE,region="departmentList")
public class Department
{

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String departmentName;

    @OneToMany(mappedBy="department")
    @Fetch(FetchMode.JOIN)
    @BatchSize(size=1)
    Set<Employee> employees;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
    public Set<Employee> getEmployees() {
        return employees;
    }
    public void setEmployees(Set<Employee> employees) {
        this.employees = employees;
    }

}
</code>```

am trying with all googled solution but no luck :-(

please help me

答:
We will need the full stack trace to answer completely. But globally the thing calling JoinColumn.foreignKey() expects a different JPA version than what you currently have in your classpath.

You can check which one you use by doing System.out.println(getClass().getResource("/javax/persistence/JoinColumn.class"));

Body:
basically my pom structure dependencies would look like

<dependencies>

     <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.4.Final</version>
    </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${org.springframework-version}</version>
   <exclusions>

    <exclusion>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     </exclusion>
   </exclusions>
  </dependency>
  <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework-version}</version>
  </dependency>

   <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

  <dependency>
   <groupId>org.springframework.webflow</groupId>
   <artifactId>spring-webflow</artifactId>
   <version>${org.springwebflow-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.webflow</groupId>
   <artifactId>spring-js</artifactId>
   <version>${org.springjs-version}</version>
  </dependency>

  <dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
   <version>${hsqldb.version}</version>

  </dependency>

   <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.connector-version}</version>
   </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate-version}</version>
  </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-envers</artifactId>
   <version>${hibernate-envers-version}</version>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>${servlet-api-version}</version>
   <scope>provided</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>${jsp-version}</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.3.Final</version>
</dependency>

  </dependencies>

and am trying the example of ehCache second level  example  and my project structure looks like

and i have declared my root context.xml as

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

    <import resource="classpath*:/META-INF/mvc-config/servlet-context.xml"/>

</beans>

And my servlet-contextt.xml is

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

    <annotation-driven />

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <context:annotation-config></context:annotation-config>

    <beans:bean id="appProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location" value="classpath:META-INF/application.properties" />
    </beans:bean>

    <resources mapping="/resources/**" location="/resources/, file:/${appDataPath}/" />

          <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <beans:property name="prefix" value="/WEB-INF/views/"/>
           <beans:property name="suffix" value=".jsp"/>
          </beans:bean>

    <beans:bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="${DB.DRIVER}" />
        <beans:property name="url"
            value="${DB.URL}" />
        <beans:property name="username" value="${DB.UNAME}" />
        <beans:property name="password" value="${DB.PASS}"/>
    </beans:bean>

    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="packagesToScan" value="com.darshan" />
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
                <beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
                <beans:prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</beans:prop>
                <beans:prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</beans:prop>
                <beans:prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</beans:prop>
                <beans:prop key="hibernate.hbm2ddl.auto">${hibernate.UPDATE_CREATE}</beans:prop>
                <beans:prop key="hbm2ddl.auto">${hbm2ddl.auto}</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

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

    <beans:bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:META-INF/validation" />
        <beans:property name="defaultEncoding" value="UTF-8" />
    </beans:bean>

    <context:component-scan base-package="com.darshan.mn" />

</beans:beans>

Application.properties look like

#-- Contains the application configuration data --#
#--- Base file path for storing the files & images ---#
appDataPath=E:/eSchool/appData

#--- Database Props ---#
DB.DRIVER=com.mysql.jdbc.Driver
DB.URL=jdbc:mysql://localhost:3306/interview_preparation
DB.UNAME=root
DB.PASS=tiger

#--- File Upload: 10MB---#
maxFileUploadSize=100000000

#--- Java Mail Props ---#
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.mailgun.org
mail.smtp.port=587
mail.debug=false

#--- MailGun API Props ---#
mailGunUname=postmaster@sandbox187ce31a22334db2b4b17e499b407de6.mailgun.org
mailGunPass=cdf6e6fe99fe01efe669939c6c8c6301

#--- HibernateConfig ---#
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.UPDATE_CREATE=update
hbm2ddl.auto=update
hibernate.hbm2ddl.auto=create
hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
net.sf.ehcache.configurationResourceName=ehcache.xml

my model class looks like

package com.darshan.mn.model;

import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE,region="departmentList")
public class Department
{

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String departmentName;

    @OneToMany(mappedBy="department")
    @Fetch(FetchMode.JOIN)
    @BatchSize(size=1)
    Set<Employee> employees;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
    public Set<Employee> getEmployees() {
        return employees;
    }
    public void setEmployees(Set<Employee> employees) {
        this.employees = employees;
    }

}

am trying with all googled solution but no luck :-(

please help me


问:
Using regex to restrict input in textbox

/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...

on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario

```<code>function ValidatePhone(phone) {
            var expr = /^\+?(?:\d\s?){11,13}$/;
            return expr.test(phone);
        }

var countofPlus = 0;

    $("#phone").on("keypress", function (evt) {
        if (evt.key == "+")
        {
            countofPlus = countofPlus + 1;
            if (countofPlus > 1 || this.value.length >= 1) {
                return false;
            }
            else return true;
        }
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    });
$("#phone").on("keyup", function (evt) {
        debugger;
        if (evt.key == "+") {
            countofPlus--;
            return true;
        }

    });
</code>```

答:
Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:

// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  var state = {
    value: input.value,
    start: input.selectionStart,
    end: input.selectionEnd,
    pattern: RegExp('^' + input.dataset.filter + '$')
  };

  input.addEventListener('input', function(event) {
    if (state.pattern.test(input.value)) {
      state.value = input.value;
    } else {
      input.value = state.value;
      input.setSelectionRange(state.start, state.end);
    }
  });

  input.addEventListener('keydown', function(event) {
    state.start = input.selectionStart;
    state.end = input.selectionEnd;
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'></code>```

Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.

Also, I modified the given regex to \+?\d{0,13} so it allows for incomplete input. Use HTML5 form validation to validate the final result.

Body:
/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...

on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario

function ValidatePhone(phone) {
            var expr = /^\+?(?:\d\s?){11,13}$/;
            return expr.test(phone);
        }

var countofPlus = 0;

    $("#phone").on("keypress", function (evt) {
        if (evt.key == "+")
        {
            countofPlus = countofPlus + 1;
            if (countofPlus > 1 || this.value.length >= 1) {
                return false;
            }
            else return true;
        }
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    });
$("#phone").on("keyup", function (evt) {
        debugger;
        if (evt.key == "+") {
            countofPlus--;
            return true;
        }

    });

Body:
Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:

// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  var state = {
    value: input.value,
    start: input.selectionStart,
    end: input.selectionEnd,
    pattern: RegExp('^' + input.dataset.filter + '$')
  };

  input.addEventListener('input', function(event) {
    if (state.pattern.test(input.value)) {
      state.value = input.value;
    } else {
      input.value = state.value;
      input.setSelectionRange(state.start, state.end);
    }
  });

  input.addEventListener('keydown', function(event) {
    state.start = input.selectionStart;
    state.end = input.selectionEnd;
  });
}

<input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'>

Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.

Also, I modified the given regex to \+?\d{0,13} so it allows for incomplete input. Use HTML5 form validation to validate the final result.


问:
How to Align Bootstrap thumbnails horizontally
I know this is a silly question but Can someone please tell me how can I arrange Bootstrap thumbnails horizontally?

Currently the thumbnails are placed vertically (one below the other).

This is my code snippet for the two thumbnails.

```<code><div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="photos/square.png" alt="...">
                <div class="caption">
                    <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
                    <p>...</p>
                    <p><a href="#" class="btn btn-primary btn-ok" role="button">Read More</a></p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="photos/square.png" alt="...">
                <div class="caption">
                    <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
                    <p>...</p>
                    <p><a href="#" class="btn btn-primary btn-ok" role="button">Read More</a></p>
                </div>
            </div>
        </div>
    </div>
</code>```

And here's s screenshot how it is placed.

答:
Remove the second row div and the closing div above it and they will be beside each other.</p>

```<code><div class="row"> creates a new row
</code>```

Body:
I know this is a silly question but Can someone please tell me how can I arrange Bootstrap thumbnails horizontally?

Currently the thumbnails are placed vertically (one below the other).

This is my code snippet for the two thumbnails.

Software Name

...

Read More

Software Name

...

Read More

And here's s screenshot how it is placed.

Body:
Remove the second row div and the closing div above it and they will be beside each other.

<div class="row"> creates a new row


问:
Xcode 9 : Module compiled with Swift 3.1 cannot be imported in Swift 4.0
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

```<code>@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0
</code>```

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !

答: Doing a "clean build folder" and restarting Xcode 9 cleaned up the error for me. Also the error didn't stop the app from running on my device or the simulator. </p>

Body:
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !


问:
REST API URL pattern design
I am currently developing a REST API.

I am developing an API that returns products associated with a user, and an API that returns products associated with a product.

I can not be sure how to configure the URLpattern to be correct.

What I think is ambiguous is that in the case of the URL returning the product list through the product, the products are repeatedly listed.

Please advise me of a good URL pattern.

I am considering the options below.

1.

```<code>/domain/v1/relatedProducts/users/{userId}

/domain/v1/relatedProducts/products/{productId}
</code>```

2.

```<code>/domain/v1/user/{userId}/relatedProducts

/domain/v1/products/{productId}/relatedProducts
</code>```

3.
Please advise other URL patterns.

答:
the products are related to a user, so you should select user first, then list all products. so it should be like

```<code>/domain/v1/users/{userId}/products
</code>```

notice that i used users not user and products not relatedProducts

```<code>/domain/v1/users/{userId}/products/{productId}
</code>```

also note, there is no thing wrong with v1 you can keep it or remove it, some of major companies use the version part.

you can follow some best Practices to URL pattern

Use nouns but no verbs

Use plural nouns

Use sub-resources for relations

you can find more helpful details at restapitutorial Resource Naming

Title: REST API URL pattern design

Body:
I am currently developing a REST API.

I am developing an API that returns products associated with a user, and an API that returns products associated with a product.

I can not be sure how to configure the URLpattern to be correct.

What I think is ambiguous is that in the case of the URL returning the product list through the product, the products are repeatedly listed.

Please advise me of a good URL pattern.

I am considering the options below.

1.

/domain/v1/relatedProducts/users/{userId}

/domain/v1/relatedProducts/products/{productId}

2.

/domain/v1/user/{userId}/relatedProducts

/domain/v1/products/{productId}/relatedProducts

3.
Please advise other URL patterns.

Body:
the products are related to a user, so you should select user first, then list all products. so it should be like

/domain/v1/users/{userId}/products

notice that i used users not user and products not relatedProducts

/domain/v1/users/{userId}/products/{productId}

also note, there is no thing wrong with v1 you can keep it or remove it, some of major companies use the version part.

you can follow some best Practices to URL pattern

Use nouns but no verbs

Use plural nouns

Use sub-resources for relations

you can find more helpful details at restapitutorial Resource Naming


问:
How to Learn MS SQL Server 2005?
I would like to start learning SQL Server 2005 on my own.  Can anyone recommend good books or websites that will be a good start for me?</p>

答: Learning SQL on SQL Server 2005 is a good book for beginners. It covers SQL syntax and server administration tasks.</p>

OwnerDisplayName: Craig G

ContentLicense: CC BY-SA 2.5

Title: How to Learn MS SQL Server 2005?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Daniel Auger


问:
insert into an array if value is not found
I have an array built like this:

```<code>test[0].age = "15-24"; test[0].value= "5";

test[1].age = "45-54"; test[1].value= "10";
</code>```

etc

I have another array built like this:

```<code>ageRange[0] = "1-14";

ageRange[1] = "15-24";
</code>```

etc

The ageRange has all age ranges - and the test array only has some of them.

I want to rebuild the test array to include all ages of the ageRange array and if they aren't already in the array, assign them a value of 0. What is the best way of doing this? Also - they need to be sequentially added.

答:
```<code>ageRange.forEach((age, i) => {
let agePresent = test.filter((obj) => obj.age === age).length;
if (!agePresent) {
var objt = ({val : 0, age : age});
test.splice(i,0,objt);
}
});
</code>```

I ended up getting some help and came up with this solution, which was easier for me to wrap my head around although more or less the same as user1960808's solution. I appreciate the help @user1960808 and @Nina Scholz both of your solutions also worked great and were interesting ways to tackle the problem.

edit:mods feel free to mark any of these as the answer as they are all valid

Body:
I have an array built like this:

test[0].age = "15-24"; test[0].value= "5";

test[1].age = "45-54"; test[1].value= "10";

etc

I have another array built like this:

ageRange[0] = "1-14";

ageRange[1] = "15-24";

etc

The ageRange has all age ranges - and the test array only has some of them.

I want to rebuild the test array to include all ages of the ageRange array and if they aren't already in the array, assign them a value of 0. What is the best way of doing this? Also - they need to be sequentially added.

Body:
ageRange.forEach((age, i) => {
let agePresent = test.filter((obj) => obj.age === age).length;
if (!agePresent) {
var objt = ({val : 0, age : age});
test.splice(i,0,objt);
}
});

I ended up getting some help and came up with this solution, which was easier for me to wrap my head around although more or less the same as user1960808's solution. I appreciate the help @user1960808 and @Nina Scholz both of your solutions also worked great and were interesting ways to tackle the problem.

edit:mods feel free to mark any of these as the answer as they are all valid


问:
How to run only the test cases added in a test suite and not all the test cases available in the class?
I have written a Test Suite.

myTestsuite.py

```<code>import unittest
from myTestCase2 import MyTestCase2
from prime_num_validation import Prime_Num_Validation

def my_test_suite():
    suite = unittest.TestSuite()
    suite.addTest(MyTestCase2('test_greaterCheck2'))
    #To add only test case: test_greaterCheck2 from the MyTestCase2 class
    suite.addTest(Prime_Num_Validation('test_prime_check'))
    #To add only test case: test_prime_check from the MyTestCase2 class
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(my_test_suite())
</code>```

Now when I run this using command line with: python -m unittest -v myTestsuite, It runs all the test cases from the MyTestCase2 class, which actually has 3 TC's, but we added only one out of 3 in our suite.

How should we avoid invoking all test case and executing only those which are present in the suite.

When I run this using Pycharm editor,
it again executes all the test cases from MyTestCase2.

答:
You can have the marker on top of your unit test, something call xfail that will skip the test.

for example,

Below example skip test_function3()

```<code>import sys

def test_function1():

def test_function2():

@pytest.mark.skipif(sys.version_info < (3,3),
                    reason="requires python3.3")
def test_function3():
</code>```

For reference please go through this site, you will find more information py.test skipif

the link I provided above has example of using xfail marker also.

You can use the xfail marker or create your own custom marker also. xfail is to indicate that you expect a test to fail.

You can run xfail test using following command.

```<code>pytest --runxfail
</code>```

As with skipif you can also mark your expectation of a failure on a particular
platform:

Example

```<code>import pytest
xfail = pytest.mark.xfail

@xfail
def test_func1():
    assert 0

@xfail(run=False)
def test_func2():
    assert 0
</code>```

Body:
I have written a Test Suite.

myTestsuite.py

import unittest
from myTestCase2 import MyTestCase2
from prime_num_validation import Prime_Num_Validation

def my_test_suite():
    suite = unittest.TestSuite()
    suite.addTest(MyTestCase2('test_greaterCheck2'))
    #To add only test case: test_greaterCheck2 from the MyTestCase2 class
    suite.addTest(Prime_Num_Validation('test_prime_check'))
    #To add only test case: test_prime_check from the MyTestCase2 class
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(my_test_suite())

Now when I run this using command line with: python -m unittest -v myTestsuite, It runs all the test cases from the MyTestCase2 class, which actually has 3 TC's, but we added only one out of 3 in our suite.

How should we avoid invoking all test case and executing only those which are present in the suite.

When I run this using Pycharm editor,
it again executes all the test cases from MyTestCase2.

Body:
You can have the marker on top of your unit test, something call xfail that will skip the test.

for example,

Below example skip test_function3()

import sys

def test_function1():

def test_function2():

@pytest.mark.skipif(sys.version_info < (3,3),
                    reason="requires python3.3")
def test_function3():

For reference please go through this site, you will find more information py.test skipif

the link I provided above has example of using xfail marker also.

You can use the xfail marker or create your own custom marker also. xfail is to indicate that you expect a test to fail.

You can run xfail test using following command.

pytest --runxfail

As with skipif you can also mark your expectation of a failure on a particular
platform:

Example

import pytest
xfail = pytest.mark.xfail

@xfail
def test_func1():
    assert 0

@xfail(run=False)
def test_func2():
    assert 0


问:
Not able to add custom dimensions at different levels in measurement protocol google analytics
I want to have some more dimensions so that the data for the user is more human readable.
I have set values such as
 { v: '1',
     tid: 'UA-XXXXX-1',
     cid: '55555',
     t: 'event',
     ec: 'GA',
     ea: 'GA_Recharge',
     el: 'Recharge_NameofUer',
     ev: '30' }

which provides me a three layered dimension but I want to add some more dimensions how could i achieve that.

答:
Seems like you are tracking events through the measurement protocol. Events have by default 3 dimensions:

Event Category (ec)

Event Action (ea)

Event Label (el)

If you want to add more the first idea is to create customDimensions. You can have up to 20 custom dimensions (200 for GA360 clients).

You need to setup them on the interface first. You haven't given much information about your use case but I'll guess you want to set them with Hit Scope Level. Give each one a descriptive name on the UI and take note of their indexes.

Then you can use them in the measurement protocol with the parameter cdX, like this:

Custom Dimension 1 (cd1)

Custom Dimension 2(cd2)

...

Custom Dimension 20 (cd20)

You can later create custom reports that mix these dimensions with the Event(Category|Action|Label) for easy reporting.


问:
How to get values from mapping table in grails?
I have created one domain class in grails which have mapping to vehicleList as per mentioned in code. Now I want to get list of vehicles with family id = 1. I can get this using familyInstance.vehicleList.

But I want to know is there any other way I can get this. I tried to apply criteria but for both createCriteria and withCriteria showing me error arrayIndexOutOfBound error in projections where I have mentioned property("vehicleList"). Applying basic MySql query I can directly get data from mapping table but If I want to get those data using criteria how to do that.

```<code>class Family {

    String name

    Integer noOfVehicle

    List vehicleList

    static hasMany = [vehicleList: String]

    static constraints = {
    }
}

class FamilyController {

 def edit(Family familyInstance) {

        def fi = familyInstance
        println "familyInstance ::: " + familyInstance

        //Try 1
        def familyCriteria = Family.createCriteria()
        def vehicleList = familyCriteria.list{
            createAlias('vehicleList','vlist')
            projections {
                property('vehicleList')
            }
            eq('id',familyInstance.id)
        }
        println "vehicleList ::: " + vehicleList

        //Try 2
        def vehicleList1 = familyInstance.vehicleList
        println "vehicleList1 ::: " + vehicleList1

        //Try 3
        def vehicleList2 = Family.withCriteria{
            createAlias('vehicleList','vlist')
            projections{
                property('vehicleList')
            }
            eq('id',familyInstance.id)
        }
        println "vehicleList2 ::: ===------>>>>>" + vehicleList2
        respond familyInstance
    }
}
</code>```

Database structure:

Error with projections

答:
Remove your createAlias statement

```<code>Family.createCriteria().list{
    projections {
        property('vehicleList')
    }
    eq('id', familyInstance.id)
}
</code>```

works

Body:
I have created one domain class in grails which have mapping to vehicleList as per mentioned in code. Now I want to get list of vehicles with family id = 1. I can get this using familyInstance.vehicleList.

But I want to know is there any other way I can get this. I tried to apply criteria but for both createCriteria and withCriteria showing me error arrayIndexOutOfBound error in projections where I have mentioned property("vehicleList"). Applying basic MySql query I can directly get data from mapping table but If I want to get those data using criteria how to do that.

class Family {

    String name

    Integer noOfVehicle

    List vehicleList

    static hasMany = [vehicleList: String]

    static constraints = {
    }
}

class FamilyController {

 def edit(Family familyInstance) {

        def fi = familyInstance
        println "familyInstance ::: " + familyInstance

        //Try 1
        def familyCriteria = Family.createCriteria()
        def vehicleList = familyCriteria.list{
            createAlias('vehicleList','vlist')
            projections {
                property('vehicleList')
            }
            eq('id',familyInstance.id)
        }
        println "vehicleList ::: " + vehicleList

        //Try 2
        def vehicleList1 = familyInstance.vehicleList
        println "vehicleList1 ::: " + vehicleList1

        //Try 3
        def vehicleList2 = Family.withCriteria{
            createAlias('vehicleList','vlist')
            projections{
                property('vehicleList')
            }
            eq('id',familyInstance.id)
        }
        println "vehicleList2 ::: ===------>>>>>" + vehicleList2
        respond familyInstance
    }
}

Database structure:

Error with projections

Body:
Remove your createAlias statement

Family.createCriteria().list{
    projections {
        property('vehicleList')
    }
    eq('id', familyInstance.id)
}

works


问:
Singleton serialization in Kotlin
I'm wondering if it's possible in Kotlin to deserialize (restore property values) of a declared object, without having to manually assign the properties or resorting to reflection. The following snippet further explains:

```<code>object Foo: Serializable {
    var propOne: String = ""
    // ...

    fun persist() {
        serialize(this)
        // no problem with serialization
    }

    fun restore(bytes: ByteArray) {

        val fooObj: Foo = deserialize(bytes) as Foo
        // It seems Kotlin allows us to use singleton as type!

        // obvioulsly either of the following is wrong:
        // this = fooObj
        // Foo = fooObj

        // ... is there a way to 'recover' the singleton (object) other than
        //     manual assignment of properties (or reflection) ???
    }
}
</code>```

答: There is no way to reassign the global reference to a singleton with a new instance.  At most you can write out the properties during serialization, and then on deserialization directly read the properties and mutate the state in the original object.  It will require custom code for you to assign the properties into the object either by direct assignment or reflection.  It would be better if you make your own singleton mechanism that holds an instance that you can swap out to be another instance that you deserialize.</p>

Title: Singleton serialization in Kotlin

Body:
I'm wondering if it's possible in Kotlin to deserialize (restore property values) of a declared object, without having to manually assign the properties or resorting to reflection. The following snippet further explains:

object Foo: Serializable {
    var propOne: String = ""
    // ...

    fun persist() {
        serialize(this)
        // no problem with serialization
    }

    fun restore(bytes: ByteArray) {

        val fooObj: Foo = deserialize(bytes) as Foo
        // It seems Kotlin allows us to use singleton as type!

        // obvioulsly either of the following is wrong:
        // this = fooObj
        // Foo = fooObj

        // ... is there a way to 'recover' the singleton (object) other than
        //     manual assignment of properties (or reflection) ???
    }
}


问:
Asp.net Unit test model data annotation DataType.EmailAddress?
How do I test DataType.EmailAddress?

I have a Customer model with an Email property with the following data annotations to validate:

```<code>[StringLength(100)]
[DataType(DataType.EmailAddress, ErrorMessage = "Email must be a valid email address")]
[Display(Name = "Email")]
[Required(ErrorMessage = "Email is required")]
public string email { get; set; }
</code>```

I am writing unit tests to test validations. I have figured out how to test required and string length.

Here's my method that catches other errors, but doesn't handle the DataType validations:

```<code>private List<ValidationResult> ValidateModel<T>(T model)
{
    var context = new ValidationContext(model, null, null);
    var result = new List<ValidationResult>();
    var valid = Validator.TryValidateObject(model, context, result, true);

    return result;
}
</code>```

I call it in a test method:

```<code>[TestMethod]
public void Invalid_email_addresses_throw_errors()
{
    var model = new Models.Customer();

    model.email = "";
    var results = ValidateModel(model);
    Assert.IsTrue(results.Any(v => v.ErrorMessage == "Email is required"));
}
</code>```

How do I test DataType.EmailAddress - passing in an invalid value and receiving the an error as a result?

答:
Use the [EmailAddress] DataTypeAttribute.

EmailAddressAttribute is derived from DataTypeAttribute and overrides the IsValid method which is what checks that the value is in fact a valid email.

Using

```<code>[DataType(DataType.EmailAddress, ErrorMessage = "Email must be a valid email address")]
</code>```

does not do anything for email validation.

If you inspect the source code for DataTypeAttribute you will realize that it is primarily a base attribute used to create custom and targeted validation attribute.

The DataTypeAttribute in the original question is being used incorrectly.
There is no other solution than to use the EmailAddressAttribute as demonstrated below in the following unit test.

```<code>[TestClass]
public class UnitTestExample {
    [TestMethod]
    public void Invalid_email_addresses_throw_errors() {
        //Arrange
        var badEmail = "1234_)(";
        var subject = new Customer { email = badEmail };

        //Act
        var results = ValidateModel(subject);

        //Assert
        Assert.IsTrue(results.Count > 0);
        Assert.IsTrue(results.Any(v => v.MemberNames.Contains("email")));
    }

    public class Customer {

        [StringLength(100)]
        [Display(Name = "Email")]
        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage = "Email must be a valid email address")]
        public string email { get; set; }

    }

    private List<ValidationResult> ValidateModel<T>(T model) {
        var context = new ValidationContext(model, null, null);
        var result = new List<ValidationResult>();
        var valid = Validator.TryValidateObject(model, context, result, true);

        return result;
    }
}
</code>```

Body:
How do I test DataType.EmailAddress?

I have a Customer model with an Email property with the following data annotations to validate:

[StringLength(100)]
[DataType(DataType.EmailAddress, ErrorMessage = "Email must be a valid email address")]
[Display(Name = "Email")]
[Required(ErrorMessage = "Email is required")]
public string email { get; set; }

I am writing unit tests to test validations. I have figured out how to test required and string length.

Here's my method that catches other errors, but doesn't handle the DataType validations:

private List<ValidationResult> ValidateModel<T>(T model)
{
    var context = new ValidationContext(model, null, null);
    var result = new List<ValidationResult>();
    var valid = Validator.TryValidateObject(model, context, result, true);

    return result;
}

I call it in a test method:

[TestMethod]
public void Invalid_email_addresses_throw_errors()
{
    var model = new Models.Customer();

    model.email = "";
    var results = ValidateModel(model);
    Assert.IsTrue(results.Any(v => v.ErrorMessage == "Email is required"));
}

How do I test DataType.EmailAddress - passing in an invalid value and receiving the an error as a result?

Body:
Use the [EmailAddress] DataTypeAttribute.

EmailAddressAttribute is derived from DataTypeAttribute and overrides the IsValid method which is what checks that the value is in fact a valid email.

Using

[DataType(DataType.EmailAddress, ErrorMessage = "Email must be a valid email address")]

does not do anything for email validation.

If you inspect the source code for DataTypeAttribute you will realize that it is primarily a base attribute used to create custom and targeted validation attribute.

The DataTypeAttribute in the original question is being used incorrectly.
There is no other solution than to use the EmailAddressAttribute as demonstrated below in the following unit test.

[TestClass]
public class UnitTestExample {
    [TestMethod]
    public void Invalid_email_addresses_throw_errors() {
        //Arrange
        var badEmail = "1234_)(";
        var subject = new Customer { email = badEmail };

        //Act
        var results = ValidateModel(subject);

        //Assert
        Assert.IsTrue(results.Count > 0);
        Assert.IsTrue(results.Any(v => v.MemberNames.Contains("email")));
    }

    public class Customer {

        [StringLength(100)]
        [Display(Name = "Email")]
        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage = "Email must be a valid email address")]
        public string email { get; set; }

    }

    private List<ValidationResult> ValidateModel<T>(T model) {
        var context = new ValidationContext(model, null, null);
        var result = new List<ValidationResult>();
        var valid = Validator.TryValidateObject(model, context, result, true);

        return result;
    }
}


问:
Add / Update / Find .bashrc or .bash_profile in CentOS 6 for Laravel new command to work
currently I am unable to run Laravel new command to create new project.

I get the following error:

```<code>bash: laravel: Command not found
</code>```

I need to add the path:

```<code>$HOME/.composer/vendor/bin
</code>```

But I have never worked with CentOS, I have done once in Ubuntu but I cant find any article on how to proceed with .bashrc in CentOS.

I did ran this command in Terminal:

```<code>export PATH="$PATH:~/.composer/vendor/bin"
</code>```

Then I tried :

```<code>source ~/.bashrc
</code>```

Both of the above command ran and no error was thrown and no output. I am not sure if those command even work for CentOS 6.

I tried : Laravel new blog after above steps and same output Laravel not found. What am I doing wrong or how do I fix this issue ?

Updated - File content

```<code># .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi
</code>```

答:
You have used double-quotes to expand ~ representing the home directory path which obviously won't happen.

POSIX defines Double-Quotes as:

Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters dollar sign, backquote, and backslash

so do either do below without quotes

```<code>export PATH=$PATH:~/.composer/vendor/bin
</code>```

(or) use the environment variable $HOME for the same

```<code>export PATH="$PATH:$HOME/.composer/vendor/bin"
</code>```

Body:
currently I am unable to run Laravel new command to create new project.

I get the following error:

bash: laravel: Command not found

I need to add the path:

$HOME/.composer/vendor/bin

But I have never worked with CentOS, I have done once in Ubuntu but I cant find any article on how to proceed with .bashrc in CentOS.

I did ran this command in Terminal:

export PATH="$PATH:~/.composer/vendor/bin"

Then I tried :

source ~/.bashrc

Both of the above command ran and no error was thrown and no output. I am not sure if those command even work for CentOS 6.

I tried : Laravel new blog after above steps and same output Laravel not found. What am I doing wrong or how do I fix this issue ?

Updated - File content

# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

Body:
You have used double-quotes to expand ~ representing the home directory path which obviously won't happen.

POSIX defines Double-Quotes as:

Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters dollar sign, backquote, and backslash

so do either do below without quotes

export PATH=$PATH:~/.composer/vendor/bin

(or) use the environment variable $HOME for the same

export PATH="$PATH:$HOME/.composer/vendor/bin"


问:
Re-assign a variable in a function with computation expression
Based on the question How can I re-assign a variable in a function in Haskell?, there is a haskell solution to change the total congo elephant count Congo 0 in a function:

main' :: StateT Congo IO ()
main' =
  do
    printElephant
    function 2
    printElephant

-- run program:
main :: IO ()
main = Congo 0 & runStateT main' & void
-- outputs:
0
2
```

After reading the Computation Expression series, I still don't know how to write a CE builder for this problem correctly. How can I re-assign a variable in a function with F#'s CE?

答:
F# has a first-class support for imperative programming constructs. You just need to mark your let bindings as mutable. There is no need for computation expressions in this case:

```<code>let mutable elephant = 0
printfn "Elephant = %d" elephant
elephant <- 2
printfn "Elephant = %d" elephant
</code>```

Body:
Based on the question How can I re-assign a variable in a function in Haskell?, there is a haskell solution to change the total congo elephant count Congo 0 in a function:

main' :: StateT Congo IO ()
main' =
  do
    printElephant
    function 2
    printElephant

-- run program:
main :: IO ()
main = Congo 0 & runStateT main' & void
-- outputs:
0
2

After reading the Computation Expression series, I still don't know how to write a CE builder for this problem correctly. How can I re-assign a variable in a function with F#'s CE?

Body:
F# has a first-class support for imperative programming constructs. You just need to mark your let bindings as mutable. There is no need for computation expressions in this case:

let mutable elephant = 0
printfn "Elephant = %d" elephant
elephant <- 2
printfn "Elephant = %d" elephant


问:
How to find key trees/features from a trained random forest?
I am using Scikit-Learn Random Forest Classifier and trying to extract the meaningful trees/features in order to better understand the prediction results.

I found this method which seems relevant in the documention (http://scikit-learn.org/dev/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.get_params), but couldn't find an example how to use it.

I am also hoping to visualize those trees if possible, any relevant code would be great.

Thank you!

答:
Here is how I visualize the tree:

First make the model after you have done all of the preprocessing, splitting, etc:

```<code># max number of trees = 100
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 100, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
</code>```

Make predictions:

```<code># Predicting the Test set results
y_pred = classifier.predict(X_test)
</code>```

Then make the plot of importances.  The variable dataset is the name of the original dataframe.

```<code># get importances from RF
importances = classifier.feature_importances_

# then sort them descending
indices = np.argsort(importances)

# get the features from the original data set
features = dataset.columns[0:26]

# plot them with a horizontal bar chart
plt.figure(1)
plt.title('Feature Importances')
plt.barh(range(len(indices)), importances[indices], color='b', align='center')
plt.yticks(range(len(indices)), features[indices])
plt.xlabel('Relative Importance')
</code>```

This yields a plot as below:

Body:
Here is how I visualize the tree:

First make the model after you have done all of the preprocessing, splitting, etc:

# max number of trees = 100
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 100, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)

Make predictions:

# Predicting the Test set results
y_pred = classifier.predict(X_test)

Then make the plot of importances.  The variable dataset is the name of the original dataframe.

# get importances from RF
importances = classifier.feature_importances_

# then sort them descending
indices = np.argsort(importances)

# get the features from the original data set
features = dataset.columns[0:26]

# plot them with a horizontal bar chart
plt.figure(1)
plt.title('Feature Importances')
plt.barh(range(len(indices)), importances[indices], color='b', align='center')
plt.yticks(range(len(indices)), features[indices])
plt.xlabel('Relative Importance')

This yields a plot as below:


问:
How to find the css version?
How do I find the version of CSS that I am using?</p>

答:
In my opinion you should use object detection instead - check the MDC to understand the principle.

On Internet Explorer you might find compatMode and documentMode useful.

ContentLicense: CC BY-SA 4.0

Title: How to find the css version?


问:
Netezza stored procedure error
I am my trying to convert an oracle procedure of something like below to Netezza and facing some issues when executed, no compilation errors. The procedure was executed successfully in Oracle. About the task, it is batch process without expecting to return or take input parameters and loop through the a table to prepare an SQL statement dynamically. Logic is built well as there is no issue in Oracle.

```<code>CREATE OR REPLACE PROCEDURE proc1 ()
   RETURNS CHARACTER VARYING (ANY) EXECUTE AS OWNER  LANGUAGE NZPLSQL AS
BEGIN_PROC

DECLARE

lv_sql varchar(4000);
lv1 varchar(4000);
lv2 varchar(4000);
lv3 varchar(4000);
lv4 varchar(4000);
lv5 varchar(4000);
lv_value varchar(1000);
lv_str_cnt integer;
lv_ret_string VARCHAR(1000);

BEGIN
    FOR c1 IN (SELECT * from test)
    LOOP
            IF lv_str_cnt = 0 THEN
              lv_ret_string := '''' || c1.col1 || '''';
            ELSE IF  lv_str_cnt IS NULL THEN
              lv_ret_string := NULL;
            ELSE
                lv_ret_string := '''' || c1.col2 || '''';
            END IF;
            .............
            .............

        lv_sql := lv_sql || lv1 || lv2 || lv3 || lv4;

        EXECUTE IMMEDIATE lv_sql;

     END LOOP;

END;
END_PROC;
</code>```

I get the following error when the procedure is executed
"Syntax error, unexpected WORD at or near Varchar2"

Varchar2 is an Oracle datatype and I can confirm it is modified to Varchar of Netezza in my procedure in all the places. I searched on google to find good examples of creating a procedure but unfortunately I could not get desired help.

Also there is particular block code which I want to create as function and re-use it. Unfortunately stuck up with function syntax too.

Appreciate your help

答:
I felt it is time to return back with answer to my own question.</p>

```<code>CREATE OR REPLACE PROCEDURE proc1 ()
   RETURNS CHARACTER VARYING (ANY) EXECUTE AS OWNER  LANGUAGE NZPLSQL AS
BEGIN_PROC

DECLARE
c1      RECORD;
v_sql   text;

lv_sql varchar(4000);
lv1 varchar(4000);
lv2 varchar(4000);
lv3 varchar(4000);
lv4 varchar(4000);
lv5 varchar(4000);
lv_value varchar(1000);
lv_str_cnt integer;
lv_ret_string VARCHAR(1000);

BEGIN
    v_sql := 'SELECT * from test;';

    FOR c1 IN EXECUTE v_sql
    LOOP
            IF lv_str_cnt = 0 THEN
              lv_ret_string := '''' || c1.col1 || '''';
            ELSE IF  lv_str_cnt IS NULL THEN
              lv_ret_string := NULL;
            ELSE
                lv_ret_string := '''' || c1.col2 || '''';
            END IF;
            .............
            .............

        lv_sql := lv_sql || lv1 || lv2 || lv3 || lv4;

        EXECUTE IMMEDIATE lv_sql;

     END LOOP;

END;
END_PROC;
</code>```

Title: Netezza stored procedure error

Body:
I am my trying to convert an oracle procedure of something like below to Netezza and facing some issues when executed, no compilation errors. The procedure was executed successfully in Oracle. About the task, it is batch process without expecting to return or take input parameters and loop through the a table to prepare an SQL statement dynamically. Logic is built well as there is no issue in Oracle.

CREATE OR REPLACE PROCEDURE proc1 ()
   RETURNS CHARACTER VARYING (ANY) EXECUTE AS OWNER  LANGUAGE NZPLSQL AS
BEGIN_PROC

DECLARE

lv_sql varchar(4000);
lv1 varchar(4000);
lv2 varchar(4000);
lv3 varchar(4000);
lv4 varchar(4000);
lv5 varchar(4000);
lv_value varchar(1000);
lv_str_cnt integer;
lv_ret_string VARCHAR(1000);

BEGIN
    FOR c1 IN (SELECT * from test)
    LOOP
            IF lv_str_cnt = 0 THEN
              lv_ret_string := '''' || c1.col1 || '''';
            ELSE IF  lv_str_cnt IS NULL THEN
              lv_ret_string := NULL;
            ELSE
                lv_ret_string := '''' || c1.col2 || '''';
            END IF;
            .............
            .............

        lv_sql := lv_sql || lv1 || lv2 || lv3 || lv4;

        EXECUTE IMMEDIATE lv_sql;

     END LOOP;

END;
END_PROC;

I get the following error when the procedure is executed
"Syntax error, unexpected WORD at or near Varchar2"

Varchar2 is an Oracle datatype and I can confirm it is modified to Varchar of Netezza in my procedure in all the places. I searched on google to find good examples of creating a procedure but unfortunately I could not get desired help.

Also there is particular block code which I want to create as function and re-use it. Unfortunately stuck up with function syntax too.

Appreciate your help

Body:
I felt it is time to return back with answer to my own question.

CREATE OR REPLACE PROCEDURE proc1 ()
   RETURNS CHARACTER VARYING (ANY) EXECUTE AS OWNER  LANGUAGE NZPLSQL AS
BEGIN_PROC

DECLARE
c1      RECORD;
v_sql   text;

lv_sql varchar(4000);
lv1 varchar(4000);
lv2 varchar(4000);
lv3 varchar(4000);
lv4 varchar(4000);
lv5 varchar(4000);
lv_value varchar(1000);
lv_str_cnt integer;
lv_ret_string VARCHAR(1000);

BEGIN
    v_sql := 'SELECT * from test;';

    FOR c1 IN EXECUTE v_sql
    LOOP
            IF lv_str_cnt = 0 THEN
              lv_ret_string := '''' || c1.col1 || '''';
            ELSE IF  lv_str_cnt IS NULL THEN
              lv_ret_string := NULL;
            ELSE
                lv_ret_string := '''' || c1.col2 || '''';
            END IF;
            .............
            .............

        lv_sql := lv_sql || lv1 || lv2 || lv3 || lv4;

        EXECUTE IMMEDIATE lv_sql;

     END LOOP;

END;
END_PROC;


问:
jQuery - When looping out additional data from database, looped button doesnt work
Initially, I'm looping out 10 comments from the database. Then, with the SHOWMORE button I'm looping out 4 more comments each time clicked. However, as from the 14th comment, the looped button, CONSENT THIS doesnt work(sort of a vote button)

ideas.php

```<code><?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
?>
<div class = 'comments'>
    <?php
while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>

    <?php echo$show['post'];?><br>
   <span class = 'counter'><?php echo$show['consents'];?></span> <span>Consents</span>

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>' >Consent This</button>
     <?php } ?>

<?php }
?>
</div>
<?php
     $more = "SELECT * FROM ideas_1";
     $more1 = mysqli_query($conn, $more);
     if (mysqli_num_rows($more1)>10) {
     ?>
     <button id = 'showmore'>Show more</button>
     <?php }?>
<script>

    var voterid = "<?php echo $id;?>"
    var commentCount = 10;

$(document).ready(function () {
   $('.consents').click(function(){
    var postid = $(this).data('postid');
    var consents = $(this).data('consents');
    var posterid = $(this).data('posterid');
    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });

  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
  $("#showmore").click(function(){
    commentCount = commentCount + 4;
    $('.comments').load("load-ideas.php", {
        commentNewCount: commentCount
        });
    });
}
  );
</script>
</code>```

load-ideas.php

```<code><?php
include ('header.php');
if (isset($_SESSION['id'])){
    $id = $_SESSION['id'];
} else {
    header("Location: index.php");
}
include('dbh.php');
$commentNewCount = $_POST['commentNewCount'];

$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT $commentNewCount";
$done = mysqli_query($conn, $postshow);

while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>
   <div class = 'comments'>
    <?php echo$show['post'];?><br>
   <span class = 'counter'><?php echo$show['consents'];?></span> <span>Consents</span>

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>'>Consent This</button>
     <?php } ?>

   </div>

<?php }
?>

<script>
    $(document).ready(function(){
         $('.consents').click(function(){
    var postid = $(this).data('postid');
    var consents = $(this).data('consents');
    var posterid = $(this).data('posterid');
    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });

});
</script>
</code>```

What am I doing wrong?

答:
Since you populate your document dynamically with more .consents buttons -
 you need to dynamically delegate your click to those elements by using the jQuery .on() method with delegated events

$(staticParent).on(eventName, dynamicChild, callbackFn)

or in your case:

```<code>$(document /*or rather a static parent selector*/ ).on("click", ".consents", function) {
</code>```

same goes for any other element that is dynamically generated.

Also don't use fetch_assoc, rather use prepared statements with PDO

Additionally don't trust input values without sanitization filtering using filter_input, filter_var etc.

Body:
Initially, I'm looping out 10 comments from the database. Then, with the SHOWMORE button I'm looping out 4 more comments each time clicked. However, as from the 14th comment, the looped button, CONSENT THIS doesnt work(sort of a vote button)

ideas.php

<?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
?>

    <?php
while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>

    <?php echo$show['post'];?>

   <?php echo$show['consents'];?> Consents

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>' >Consent This</button>
     <?php } ?>

<?php }
?>

<?php
     $more = "SELECT * FROM ideas_1";
     $more1 = mysqli_query($conn, $more);
     if (mysqli_num_rows($more1)>10) {
     ?>
     <button id = 'showmore'>Show more</button>
     <?php }?>

load-ideas.php

<?php
include ('header.php');
if (isset($_SESSION['id'])){
    $id = $_SESSION['id'];
} else {
    header("Location: index.php");
}
include('dbh.php');
$commentNewCount = $_POST['commentNewCount'];

$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT $commentNewCount";
$done = mysqli_query($conn, $postshow);

while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>

    <?php echo$show['post'];?>

   <?php echo$show['consents'];?> Consents

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>'>Consent This</button>
     <?php } ?>

<?php }
?>

What am I doing wrong?

Body:
Since you populate your document dynamically with more .consents buttons -
 you need to dynamically delegate your click to those elements by using the jQuery .on() method with delegated events

$(staticParent).on(eventName, dynamicChild, callbackFn)

or in your case:

$(document /*or rather a static parent selector*/ ).on("click", ".consents", function) {

same goes for any other element that is dynamically generated.

Also don't use fetch_assoc, rather use prepared statements with PDO

Additionally don't trust input values without sanitization filtering using filter_input, filter_var etc.


问:
How to set App Version on Facebook Analytic SDK using JavaScript?
I'm using Ionic to develop application on mobile. Now I'm using Facebook SDK analytic for web to tracking events on my application. But I cannot find method to set app version as below:

Does anyone has experience about this?

答:
App Version is currently supported only for Native Apps using Android SDK or iOS SDK. By supported I meant, SDK extracts the version automatically from the manifest accordingly.

At this point let me advice to send the version string as custom param, something like this:

```<code>function logEvent(name) {
  FB.AppEvents.logEvent(name, null, {version: currVersion});
}
</code>```

Body:
App Version is currently supported only for Native Apps using Android SDK or iOS SDK. By supported I meant, SDK extracts the version automatically from the manifest accordingly.

At this point let me advice to send the version string as custom param, something like this:

function logEvent(name) {
  FB.AppEvents.logEvent(name, null, {version: currVersion});
}


问:
Partial Specialization of Operator()
One of my classes declares a templated function:

```<code>template<class A, class B>
A do_something(const std::vector<B> &data)
</code>```

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

```<code>template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector<B> &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector<B> data;
}
</code>```

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

```<code>fatal error C1001: An internal error has occurred in the compiler.
</code>```

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

答:
Not a solution to your problem (there are a couple already there), but some of the things that are wrong in your code:

You are missing a struct or class keyword in the template class declaration:

```<code>template <typename A, typename B> struct do_something_implementation {
//                                ^^^^^^
</code>```

Inside the class definition, member functions must not use a qualified name, regardless of whether the class is a template or not:

```<code>class A {
   void A::foo() {} // Error, should be: void foo() {}
};
</code>```

Member template specializations cannot appear inside the class definition, but at the namespace level:

```<code>class B {
   template <typename T> void foo( T );
};
template <> void B::foo<int>( int ) {}
template <> void B::foo<double>( double ) {}
</code>```

Plus on your case, the member function is not a template, but rather a non-templated member function (the template is the containing class, not the function itself). What your code is effectively trying to do is defining other class' member functions inside the general template, kind of trying to do.

Overall there was enough errors to make parsing the code almost impossible for the compiler to identify what you were trying to do and provide a good error message, but still, it should have provided any error message pointing to the first line that you copied instead of chocking to death.

Title: Partial Specialization of Operator()

Body:
One of my classes declares a templated function:

template<class A, class B>
A do_something(const std::vector &data)

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector data;
}

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

fatal error C1001: An internal error has occurred in the compiler.

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

Body:
Not a solution to your problem (there are a couple already there), but some of the things that are wrong in your code:

You are missing a struct or class keyword in the template class declaration:

template <typename A, typename B> struct do_something_implementation {
//                                ^^^^^^

Inside the class definition, member functions must not use a qualified name, regardless of whether the class is a template or not:

class A {
   void A::foo() {} // Error, should be: void foo() {}
};

Member template specializations cannot appear inside the class definition, but at the namespace level:

class B {
   template <typename T> void foo( T );
};
template <> void B::foo<int>( int ) {}
template <> void B::foo<double>( double ) {}

Plus on your case, the member function is not a template, but rather a non-templated member function (the template is the containing class, not the function itself). What your code is effectively trying to do is defining other class' member functions inside the general template, kind of trying to do.

Overall there was enough errors to make parsing the code almost impossible for the compiler to identify what you were trying to do and provide a good error message, but still, it should have provided any error message pointing to the first line that you copied instead of chocking to death.