问:
org.hibernate.exception.ConstraintViolationException on add product
So when I wanted to add a product to the database from the frontend form and the following error occurs :

```<code>Nov 30, 2017 8:28:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: NULL not allowed for column "ID"; SQL statement:
insert into Product (id, category_id, price, productDescription, productname, quantity) values (null, ?, ?, ?, ?, ?) [23502-196]
Nov 30, 2017 8:28:54 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/project1_frontend] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: NULL not allowed for column "ID"; SQL statement:
insert into Product (id, category_id, price, productDescription, productname, quantity) values (null, ?, ?, ?, ?, ?) [23502-196]] with root cause
org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID"; SQL statement:
insert into Product (id, category_id, price, productDescription, productname, quantity) values (null, ?, ?, ?, ?, ?) [23502-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.table.Column.validateConvertUpdateSequence(Column.java:345)
    at org.h2.table.Table.validateConvertUpdateSequence(Table.java:797)
    at org.h2.command.dml.Insert.insertRows(Insert.java:151)
    at org.h2.command.dml.Insert.update(Insert.java:114)
    at org.h2.command.CommandContainer.update(CommandContainer.java:101)
    at org.h2.command.Command.executeUpdate(Command.java:260)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:164)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:150)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy43.executeUpdate(Unknown Source)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:55)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2757)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3268)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:78)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:304)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:128)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:615)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:608)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:604)
    at com.niit.dao.ProductDaoImpl.saveOrUpdateProduct(ProductDaoImpl.java:45)
    at com.niit.services.ProductServiceImpl.saveOrUpdateProduct(ProductServiceImpl.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy38.saveOrUpdateProduct(Unknown Source)
    at com.niit.controllers.ProductController.saveorUpdateProduct(ProductController.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:500)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

The Product class :

```<code>package com.niit.product;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Min;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO) //Automatically generate value for Id using sequence
private int id; //product.setId(0)

@NotEmpty(message="Product name is mandatory")
private String productname;//product.setProductName("pen")
@NotEmpty(message="Product description cannot be blank")
private String productDescription;

private int quantity;
@Min(value=10,message="Minimum price is 10")
private double price;
@ManyToOne
private Category category;//product.setCategory().setId(1)
@Transient
private MultipartFile image; //image will not get persisted in the table
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getProductname() {
    return productname;
}
public void setProductname(String productname) {
    this.productname = productname;
}
public int getQuantity() {
    return quantity;
}
public void setQuantity(int quantity) {
    this.quantity = quantity;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getProductDescription() {
    return productDescription;
}
public void setProductDescription(String productDescription) {
    this.productDescription = productDescription;
}
public Category getCategory() {
    return category;
}
public void setCategory(Category category) {
    this.category = category;
}
public MultipartFile getImage() {
    return image;
}
public void setImage(MultipartFile image) {
    this.image = image;
}

}
</code>```

The Category class for which the id is PK and acts as category_id or FK for the Product class:

```<code>package com.niit.product;

import java.util.List;

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

@Entity
public class Category {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String categoryname;
@OneToMany(mappedBy="category")
private List<Product> products;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getCategoryname() {
    return categoryname;
}
public void setCategoryname(String categoryname) {
    this.categoryname = categoryname;
}

}
</code>```

Here is my ProductController :

```<code>package com.niit.controllers;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.niit.product.Category;
import com.niit.product.Product;
import com.niit.services.ProductService;
@Controller
public class ProductController {
    @Autowired
private ProductService productService;
    @RequestMapping(value="/all/getallproducts")
public ModelAndView getAllProducts(){
    List<Product> products=productService.getAllProducts();
    //productlist - logical view name [productlist.jsp]
    //products - model attribute [use this attribute in jsp]
    //products - List<Product> data
    return new ModelAndView("productlist","productsAttr",products);
    //JSTL and EL
}
    // all/viewproduct/1  [id=1]
    @RequestMapping(value="/all/viewproduct/{id}")
    public ModelAndView getProduct(@PathVariable int id){
        Product product=productService.getProduct(id);
        return new ModelAndView("viewproduct","product",product);
    }
    @RequestMapping(value="/admin/deleteproduct/{id}")
    public String deleteProduct(HttpServletRequest request,@PathVariable int id){
        String rootDirectory=request.getServletContext().getRealPath("/");
        Path path=Paths.get(rootDirectory + "/WEB-INF/resources/images/"+id+".png");
        if(Files.exists(path)){
            try {
                Files.delete(path);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        productService.deleteProduct(id);
        return "redirect:/all/getallproducts";
    }
    @RequestMapping(value="/admin/getproductform")
    public String getProductForm(@RequestParam(required=false)int id,Model model){
        if(id==0)//add product
        model.addAttribute("product",new Product());//1
        else{ //edit product
            Product product=productService.getProduct(id);//select * from product where id=?
            model.addAttribute("product",product);
        }
        //SELECT * from Category
        List<Category> categoriesList=productService.getAllCategories();
        model.addAttribute("categories",categoriesList);
        return "productform";
    }
    @RequestMapping(value="/admin/saveorupdateproduct")
    public String saveorUpdateProduct(HttpServletRequest request,@Valid @ModelAttribute(name="product")  Product product,BindingResult result,Model model) {//3
        if(result.hasErrors()){//constraint violation
            List<Category> categories=productService.getAllCategories();
            model.addAttribute("categories",categories);
            return "productform";
        }
        System.out.println(product.getProductname());

        productService.saveOrUpdateProduct(product); //insert and update
        String rootDirectory=request.getServletContext().getRealPath("/");
        System.out.println(rootDirectory);
        Path path=Paths.get(rootDirectory + "/WEB-INF/resources/images/"+product.getId()+".png");
        MultipartFile prodImage=product.getImage();//uploaded image [jpeg,gif,..]
        try {
            prodImage.transferTo(new File(path.toString()));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//transfer the image to the file named productid.png
        return "redirect:/all/getallproducts";
    }

}
</code>```

Shouldn't the AUTO generated strategy automatically generate id for product class as we add more products via the frontend dynamically?(Instead of encountering a null value for another entry of product) I'm new to hibernate and any help would be appreciated!

Here is my product table at backend H2

答:
Follow Auto Generation issue and following this link if its throwing violation exception then its because you already have entries in Product table with these ID values.

I think you are doing development so delete entries from database and start from scratch with generation type as Table. May be Generation type Auto does not work with H2.

Body:
So when I wanted to add a product to the database from the frontend form and the following error occurs :

Nov 30, 2017 8:28:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: NULL not allowed for column "ID"; SQL statement:
insert into Product (id, category_id, price, productDescription, productname, quantity) values (null, ?, ?, ?, ?, ?) [23502-196]
Nov 30, 2017 8:28:54 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/project1_frontend] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: NULL not allowed for column "ID"; SQL statement:
insert into Product (id, category_id, price, productDescription, productname, quantity) values (null, ?, ?, ?, ?, ?) [23502-196]] with root cause
org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID"; SQL statement:
insert into Product (id, category_id, price, productDescription, productname, quantity) values (null, ?, ?, ?, ?, ?) [23502-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.table.Column.validateConvertUpdateSequence(Column.java:345)
    at org.h2.table.Table.validateConvertUpdateSequence(Table.java:797)
    at org.h2.command.dml.Insert.insertRows(Insert.java:151)
    at org.h2.command.dml.Insert.update(Insert.java:114)
    at org.h2.command.CommandContainer.update(CommandContainer.java:101)
    at org.h2.command.Command.executeUpdate(Command.java:260)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:164)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:150)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy43.executeUpdate(Unknown Source)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:55)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2757)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3268)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:78)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:304)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:128)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:615)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:608)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:604)
    at com.niit.dao.ProductDaoImpl.saveOrUpdateProduct(ProductDaoImpl.java:45)
    at com.niit.services.ProductServiceImpl.saveOrUpdateProduct(ProductServiceImpl.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy38.saveOrUpdateProduct(Unknown Source)
    at com.niit.controllers.ProductController.saveorUpdateProduct(ProductController.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:500)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

The Product class :

package com.niit.product;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Min;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO) //Automatically generate value for Id using sequence
private int id; //product.setId(0)

@NotEmpty(message="Product name is mandatory")
private String productname;//product.setProductName("pen")
@NotEmpty(message="Product description cannot be blank")
private String productDescription;

private int quantity;
@Min(value=10,message="Minimum price is 10")
private double price;
@ManyToOne
private Category category;//product.setCategory().setId(1)
@Transient
private MultipartFile image; //image will not get persisted in the table
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getProductname() {
    return productname;
}
public void setProductname(String productname) {
    this.productname = productname;
}
public int getQuantity() {
    return quantity;
}
public void setQuantity(int quantity) {
    this.quantity = quantity;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getProductDescription() {
    return productDescription;
}
public void setProductDescription(String productDescription) {
    this.productDescription = productDescription;
}
public Category getCategory() {
    return category;
}
public void setCategory(Category category) {
    this.category = category;
}
public MultipartFile getImage() {
    return image;
}
public void setImage(MultipartFile image) {
    this.image = image;
}

}

The Category class for which the id is PK and acts as category_id or FK for the Product class:

package com.niit.product;

import java.util.List;

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

@Entity
public class Category {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String categoryname;
@OneToMany(mappedBy="category")
private List<Product> products;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getCategoryname() {
    return categoryname;
}
public void setCategoryname(String categoryname) {
    this.categoryname = categoryname;
}

}

Here is my ProductController :

package com.niit.controllers;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.niit.product.Category;
import com.niit.product.Product;
import com.niit.services.ProductService;
@Controller
public class ProductController {
    @Autowired
private ProductService productService;
    @RequestMapping(value="/all/getallproducts")
public ModelAndView getAllProducts(){
    List<Product> products=productService.getAllProducts();
    //productlist - logical view name [productlist.jsp]
    //products - model attribute [use this attribute in jsp]
    //products - List<Product> data
    return new ModelAndView("productlist","productsAttr",products);
    //JSTL and EL
}
    // all/viewproduct/1  [id=1]
    @RequestMapping(value="/all/viewproduct/{id}")
    public ModelAndView getProduct(@PathVariable int id){
        Product product=productService.getProduct(id);
        return new ModelAndView("viewproduct","product",product);
    }
    @RequestMapping(value="/admin/deleteproduct/{id}")
    public String deleteProduct(HttpServletRequest request,@PathVariable int id){
        String rootDirectory=request.getServletContext().getRealPath("/");
        Path path=Paths.get(rootDirectory + "/WEB-INF/resources/images/"+id+".png");
        if(Files.exists(path)){
            try {
                Files.delete(path);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        productService.deleteProduct(id);
        return "redirect:/all/getallproducts";
    }
    @RequestMapping(value="/admin/getproductform")
    public String getProductForm(@RequestParam(required=false)int id,Model model){
        if(id==0)//add product
        model.addAttribute("product",new Product());//1
        else{ //edit product
            Product product=productService.getProduct(id);//select * from product where id=?
            model.addAttribute("product",product);
        }
        //SELECT * from Category
        List<Category> categoriesList=productService.getAllCategories();
        model.addAttribute("categories",categoriesList);
        return "productform";
    }
    @RequestMapping(value="/admin/saveorupdateproduct")
    public String saveorUpdateProduct(HttpServletRequest request,@Valid @ModelAttribute(name="product")  Product product,BindingResult result,Model model) {//3
        if(result.hasErrors()){//constraint violation
            List<Category> categories=productService.getAllCategories();
            model.addAttribute("categories",categories);
            return "productform";
        }
        System.out.println(product.getProductname());

        productService.saveOrUpdateProduct(product); //insert and update
        String rootDirectory=request.getServletContext().getRealPath("/");
        System.out.println(rootDirectory);
        Path path=Paths.get(rootDirectory + "/WEB-INF/resources/images/"+product.getId()+".png");
        MultipartFile prodImage=product.getImage();//uploaded image [jpeg,gif,..]
        try {
            prodImage.transferTo(new File(path.toString()));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//transfer the image to the file named productid.png
        return "redirect:/all/getallproducts";
    }

}

Shouldn't the AUTO generated strategy automatically generate id for product class as we add more products via the frontend dynamically?(Instead of encountering a null value for another entry of product) I'm new to hibernate and any help would be appreciated!

Here is my product table at backend H2


来源: stackexchange

问:
How to enable ECMAScript "use strict" globally?
I have a project with literally hundreds of JavaScript source files. I am wondering what is the best way to enable the strict mode for the project? I understand the consequences of this action and I am only looking for advice regarding the deployement of this feature. Placing "use strict" in every file does not seem fun.</p>

答:
Well, I'm not clear on the context your javascript files will be used in, however say the context is a dynamic web application where various page files, javascript files, style sheets, etc, etc, are loaded when needed, then I would just create a single javascript file with only "use strict" within it. Then, include that file in your head tags, preceding all other javascript files and make sure that if you will be inserting javascript files dynamically into the head of the document of a given web application that you append them after your "use strict" .js file.

That way you won't have to go through each of your .js files and modify them individually.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Speed Up Xcopy in Batch
So I'm trying to copy a backup of the data from my app. I wrote the batch script below to do this, but the script takes forever to run.

I start the batch script at 1am, and it is still running at 8:30am. This seems weird to me because when I copy the backup of my app manually in Windows File Explorer, it copies in 7-15 minutes depending on network traffic.

I REM the %backupcmd% "C:\Program Files\App\App Server\Data\Backups" "%drive%\" line. That was the original line of batch script I used to backup the data, and it worked efficiently up till a month ago.

So I tried the xcopy command with /d, so it would only copy source files that have been changed on or after that date (the current date), and the backups I'm copying are made at 12:01am every night and the copy backup script starts at 1am.

Any advice as to how to speed up my xcopy would be appreciated. If you think I should use powershell for this task too, I'm open to that option as well.

```<code>@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set yyyy=%ldt:~0,4%
set mm=%ldt:~4,2%
set dd=%ldt:~6,2%

:: variables
set drive=Z:\RootSoft\App\Data Backups
set backupcmd=xcopy /s /c /d /e /h /i /r /y /f /z

echo ### Backing up Backup...
REM %backupcmd% "C:\Program Files\App\App Server\Data\Backups" "%drive%\"
xcopy "C:\Program Files\App\App Server\Data\Backups" "Z:\RootSoft\App\Data Backups" /D:%mm%-%dd%-%yyyy% /s /c /e /h /i /r /y /f /z

:: use below syntax to backup other directories...
:: %backupcmd% "...source directory..." "%drive%\...destination dir..."

echo Backup Complete!
echo %errorlevel%
pause
</code>```

答:
netsh interface tcp show global

netsh int tcp set heuristics disabled

netsh int tcp set global autotuninglevel=disabled

netsh int ip set global taskoffload=disabled

Title: Speed Up Xcopy in Batch

Body:
So I'm trying to copy a backup of the data from my app. I wrote the batch script below to do this, but the script takes forever to run.

I start the batch script at 1am, and it is still running at 8:30am. This seems weird to me because when I copy the backup of my app manually in Windows File Explorer, it copies in 7-15 minutes depending on network traffic.

I REM the %backupcmd% "C:\Program Files\App\App Server\Data\Backups" "%drive%\" line. That was the original line of batch script I used to backup the data, and it worked efficiently up till a month ago.

So I tried the xcopy command with /d, so it would only copy source files that have been changed on or after that date (the current date), and the backups I'm copying are made at 12:01am every night and the copy backup script starts at 1am.

Any advice as to how to speed up my xcopy would be appreciated. If you think I should use powershell for this task too, I'm open to that option as well.

@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set yyyy=%ldt:~0,4%
set mm=%ldt:~4,2%
set dd=%ldt:~6,2%

:: variables
set drive=Z:\RootSoft\App\Data Backups
set backupcmd=xcopy /s /c /d /e /h /i /r /y /f /z

echo ### Backing up Backup...
REM %backupcmd% "C:\Program Files\App\App Server\Data\Backups" "%drive%\"
xcopy "C:\Program Files\App\App Server\Data\Backups" "Z:\RootSoft\App\Data Backups" /D:%mm%-%dd%-%yyyy% /s /c /e /h /i /r /y /f /z

:: use below syntax to backup other directories...
:: %backupcmd% "...source directory..." "%drive%\...destination dir..."

echo Backup Complete!
echo %errorlevel%
pause


问:
I can't set labels in Django forms fields
This is my model:

```<code>class CalEvents(models.Model):

    user = models.ForeignKey(User)
    activity_name = models.CharField(max_length=256, unique=False, blank=True)
    activity_type = models.CharField(max_length=30, unique=False, blank=True)
    activity_code = models.CharField(max_length=30, unique=False, blank=True)

    def __str__(self):
        return "Activity: '{}' - @{}".format(self.activity_name, self.user.username)
</code>```

This is my forms.py (with my attempted solutions to define the labels):

```<code>from django.forms import ModelForm
from gCalData.models import CalEvents
from accounts.models import User

class CalEventsForm(ModelForm):
    class Meta:
        model = CalEvents
        fields = ['activity_name','activity_type','activity_code']
        labels = {"actiity_name": "Activity name",
                    "activity_type": "Activity type",
                    "activity_code": "Activity code"}

    def __init__(self, *args, **kwargs):
        super(CalEventsForm, self).__init__(*args, **kwargs)
        self.fields['activity_name'].label = "Activity name"
        self.fields['activity_type'].label = "Activity type"
        self.fields['activity_code'].label = "Activity code"
</code>```

This is the part of my template where I put the form:

```<code><tr>
  <form method="POST">
    {% csrf_token %}
  {% for field in form %}
    <td>{{ field }}</td>
  {% endfor %}
  <td><input type="submit" name="new_record" class="btn btn-primary" value="Add Activity"></td>
  </form>
</tr>
</code>```

What am I doing wrong?

答:
Try adding {{ field.label_tag }} (the html wrapping you decide):

```<code>{% for field in form %}
   {{ field.label_tag }}
    <td>{{ field }}</td>
  {% endfor %}
</code>```

Edit

You may also add the error tags:

```<code>{% for error in field.errors %}
 <div class="alert alert-danger" role="alert">{{ error|escape }}</div>
{% endfor %}
</code>```

Body:
This is my model:

class CalEvents(models.Model):

    user = models.ForeignKey(User)
    activity_name = models.CharField(max_length=256, unique=False, blank=True)
    activity_type = models.CharField(max_length=30, unique=False, blank=True)
    activity_code = models.CharField(max_length=30, unique=False, blank=True)

    def __str__(self):
        return "Activity: '{}' - @{}".format(self.activity_name, self.user.username)

This is my forms.py (with my attempted solutions to define the labels):

from django.forms import ModelForm
from gCalData.models import CalEvents
from accounts.models import User

class CalEventsForm(ModelForm):
    class Meta:
        model = CalEvents
        fields = ['activity_name','activity_type','activity_code']
        labels = {"actiity_name": "Activity name",
                    "activity_type": "Activity type",
                    "activity_code": "Activity code"}

    def __init__(self, *args, **kwargs):
        super(CalEventsForm, self).__init__(*args, **kwargs)
        self.fields['activity_name'].label = "Activity name"
        self.fields['activity_type'].label = "Activity type"
        self.fields['activity_code'].label = "Activity code"

This is the part of my template where I put the form:

  <form method="POST">
    {% csrf_token %}
  {% for field in form %}
    {{ field }}
  {% endfor %}
  <input type="submit" name="new_record" class="btn btn-primary" value="Add Activity">
  </form>

What am I doing wrong?

Body:
Try adding {{ field.label_tag }} (the html wrapping you decide):

{% for field in form %}
   {{ field.label_tag }}
    <td>{{ field }}</td>
  {% endfor %}

Edit

You may also add the error tags:

{% for error in field.errors %}
 <div class="alert alert-danger" role="alert">{{ error|escape }}</div>
{% endfor %}


问:
implement vlookup like function in javascript
I have an object in my React component's state that looks like this:

```<code>const elementPositions =  {
  "0": 180.2,
  "1": 350.8666666666667,
  "2": 521.5333333333333,
  "3": 692.2,
  "4": 862.8666666666667,
  "5": 1033.5333333333333,
  "6": 1204.2
}
</code>```

I have scroll listener that returns a scroll position value, let's say const scrollY = 466 in this instance.

I need to create a function that returns the corresponding index for the scroll position - i.e. 466 would return 1 since it is greater than 350 but less than 521. What's the best way to achieve this? I was thinking something along the lines of this but am not sure it's the best approach:

```<code>const values = Object.values(elementPositions)
values.push(scrollY)
values.sort((a, b) => {return a-b})
const newIndex = values.indexOf(scrollY) - 1
</code>```

Body:
I have an object in my React component's state that looks like this:

const elementPositions =  {
  "0": 180.2,
  "1": 350.8666666666667,
  "2": 521.5333333333333,
  "3": 692.2,
  "4": 862.8666666666667,
  "5": 1033.5333333333333,
  "6": 1204.2
}

I have scroll listener that returns a scroll position value, let's say const scrollY = 466 in this instance.

I need to create a function that returns the corresponding index for the scroll position - i.e. 466 would return 1 since it is greater than 350 but less than 521. What's the best way to achieve this? I was thinking something along the lines of this but am not sure it's the best approach:

const values = Object.values(elementPositions)
values.push(scrollY)
values.sort((a, b) => {return a-b})
const newIndex = values.indexOf(scrollY) - 1

Body:
Your numbers seem to be increments of about 170, so you should be able to do it with arithmetic in constant time (no sorting, loops, etc).

const elementPositions =  {
  "0": 180.2,
  "1": 350.8666666666667,
  "2": 521.5333333333333,
  "3": 692.2,
  "4": 862.8666666666667,
  "5": 1033.5333333333333,
  "6": 1204.2
};

function getPos(x) {
  return elementPositions[Math.floor((x-180.2) / 170.66666666666)] || 0;
}

// test
for (const n of [0,10,180,181,350,351,466,521,522,692,693,862,863,1033,1034,1204,1205]) {
  console.log(n, getPos(n));
}


问:
Set marker size based on coordinate values, not pixels, in plotly R
This post - Set marker size in plotly - unfortunately did not help with what I was looking for, and is the only post on the topic I could find. Per the plotly documentation on the size parameter for scatter plots:

"size (number or array of numbers greater than or equal to 0), default: 6, Sets the marker size (in px)"

the (in px) is a problem for me. I'd like to create a plot where the marker sizes are based on the coordinate values, not pixels, that way I can increase the size of a graph (by full screening it, for example) and the points increase in size as well. An example of my code currently:

```<code>library(plotly)
mydf <- data.frame(x = rep(1:20, times = 20), y = rep(1:20, each = 20),
                   thesize = 10)
plot_ly(mydf) %>%
  add_trace(x = ~x, y = ~y, type = 'scatter', mode = 'markers',
            marker = list(symbol = 'hexagon', size = ~thesize, opacity = 0.6))
</code>```

If you create this plot in R, and then make the plot either larger or smaller by dragging the Rstudio viewer window, or in some other way, you'll notice that the markers stay exactly the same size (10 pixels), which is frustrating. I would love it if I could have these markers have diameter == 1 (on the x axis), rather than be set to a number of pixels. Is this possible?

Any help is super appreciated!!!

答:
Let's start with a plot with a defined axis range.

```<code>p <- plot_ly() %>% layout(xaxis = list(range = c(1, 5)))
</code>```

Now add a JavaScript eventlistener which captures any changes in the plot's layout

```<code>javascript <- "
var myPlot = document.getElementsByClassName('plotly')[0];

function resize(eventdata) {
  // magic happens here
}

myPlot.on('plotly_relayout', function(eventdata) {
  resize(eventdata);
});
"
p <- htmlwidgets::prependContent(p,
                                 onStaticRenderComplete(javascript))
p
</code>```

The event passes eventdata from where we can get the new axis range.

```<code>eventdata['xaxis.range[1]']
</code>```

Since we don't know the size of the plot in advance, we determine it via the size of the axis line

```<code>var plot_width = Plotly.d3.select('.xlines-above').node().getBBox()['width'];
</code>```

We need to call the event once manually to make sure that plot is correctly initialized

Initial plot

Zoom in

Complete R code

```<code>library("plotly")
library("htmlwidgets")

p <- plot_ly() %>%
  add_trace(x = c(1.5, 3, 4.2),
            y = c(-2, 1, 2),
            type = 'scatter',
            mode = 'lines+markers',
            showlegend = F) %>%
  add_trace(x = c(2, 3, 4.2),
            y = c(2, 0, -1),
            type = 'scatter',
            mode = 'lines+markers',
            showlegend = F) %>%
  add_trace(x = c(1.5, 3, 4.2),
            y = c(1, 0.5, 1),
            type = 'scatter',
            mode = 'markers',
            showlegend = F) %>%
  layout(xaxis = list(range = c(1, 5)))
javascript <- "
marker_size = 0.5; // x-axis units
var myPlot = document.getElementsByClassName('plotly')[0];

function resize(eventdata) {
  var xaxis_stop = 5;
  var xaxis_start = 1;
  var plot_width = Plotly.d3.select('.xlines-above').node().getBBox()['width'];
  if (eventdata['xaxis.range[1]'] !== undefined) {
    var update = {'marker.size': marker_size * plot_width / (eventdata['xaxis.range[1]'] - eventdata['xaxis.range[0]'])};
  } else {
    var update = {'marker.size': marker_size * plot_width / (xaxis_stop - xaxis_start)};
  }
  Plotly.restyle(myPlot, update, 2);
}
resize({eventdata: {}});

myPlot.on('plotly_relayout', function(eventdata) {
  resize(eventdata);
});
"
p <- htmlwidgets::prependContent(p,
                                 onStaticRenderComplete(javascript))
p
</code>```

Interactive JavaScript example

You could start with a defined height/width for your graph and a defined axis range, this way you would know how many pixels is one axis unit.

The size of your markers would be initially in the size you want.

Whenever a user changes the axis range, a plotly_relayout event will be triggered and you can retrieve the new ranges from the eventdata in xaxis.range[1] (start) and xaxis.range[1] (end)

Based on the new ranges you can relayout your marker sizes.

var plot_width = 500;
var plot_height = 500;
var margin_l = 100;
var margin_r = 100;
marker_size = 0.5; // x-axis units
xaxis_start = 1;
xaxis_stop = 5;

var trace1 = {
  x: [1.5, 2, 3, 4],
  y: [10, 15, 13, 17],
  mode: "markers",
  marker: {
    size: marker_size *
      (plot_width - margin_l - margin_r) /
      (xaxis_stop - xaxis_start)
  },
  showlegend: false
};

var trace2 = {
  x: [2, 3, 4, 4.5],
  y: [16, 5, 11, 10],
  mode: "lines"
};

var trace3 = {
  x: [1.5, 2, 3, 4],
  y: [12, 9, 15, 12],
  mode: "lines+markers",
  showlegend: false
};

var data = [trace1, trace2, trace3];

var layout = {
  width: plot_width,
  height: plot_height,
  margin: {
    l: margin_l,
    r: margin_r
  },
  xaxis: {
    range: [1, 5]
  },
  showlegend: false
};

Plotly.newPlot("myDiv", data, layout);

var refplot = document.getElementById("myDiv");
refplot.on("plotly_relayout", function(eventdata) {
  if (eventdata["xaxis.range[1]"] !== undefined) {
    var update = {
      "marker.size": marker_size *
        (plot_width - margin_l - margin_r) /
        (eventdata["xaxis.range[1]"] - eventdata["xaxis.range[0]"])
    };
  } else {
    var update = {
      "marker.size": marker_size *
        (plot_width - margin_l - margin_r) /
        (xaxis_stop - xaxis_start)
    };
  }
  Plotly.restyle("myDiv", update, 0);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<body>
  <div id="myDiv"></div>
</body></code>```

Body:
This post - Set marker size in plotly - unfortunately did not help with what I was looking for, and is the only post on the topic I could find. Per the plotly documentation on the size parameter for scatter plots:

"size (number or array of numbers greater than or equal to 0), default: 6, Sets the marker size (in px)"

the (in px) is a problem for me. I'd like to create a plot where the marker sizes are based on the coordinate values, not pixels, that way I can increase the size of a graph (by full screening it, for example) and the points increase in size as well. An example of my code currently:

library(plotly)
mydf <- data.frame(x = rep(1:20, times = 20), y = rep(1:20, each = 20),
                   thesize = 10)
plot_ly(mydf) %>%
  add_trace(x = ~x, y = ~y, type = 'scatter', mode = 'markers',
            marker = list(symbol = 'hexagon', size = ~thesize, opacity = 0.6))

If you create this plot in R, and then make the plot either larger or smaller by dragging the Rstudio viewer window, or in some other way, you'll notice that the markers stay exactly the same size (10 pixels), which is frustrating. I would love it if I could have these markers have diameter == 1 (on the x axis), rather than be set to a number of pixels. Is this possible?

Any help is super appreciated!!!

Body:
Let's start with a plot with a defined axis range.

p <- plot_ly() %>% layout(xaxis = list(range = c(1, 5)))

Now add a JavaScript eventlistener which captures any changes in the plot's layout

javascript <- "
var myPlot = document.getElementsByClassName('plotly')[0];

function resize(eventdata) {
  // magic happens here
}

myPlot.on('plotly_relayout', function(eventdata) {
  resize(eventdata);
});
"
p <- htmlwidgets::prependContent(p,
                                 onStaticRenderComplete(javascript))
p

The event passes eventdata from where we can get the new axis range.

eventdata['xaxis.range[1]']

Since we don't know the size of the plot in advance, we determine it via the size of the axis line

var plot_width = Plotly.d3.select('.xlines-above').node().getBBox()['width'];

We need to call the event once manually to make sure that plot is correctly initialized

Initial plot

Zoom in

Complete R code

library("plotly")
library("htmlwidgets")

p <- plot_ly() %>%
  add_trace(x = c(1.5, 3, 4.2),
            y = c(-2, 1, 2),
            type = 'scatter',
            mode = 'lines+markers',
            showlegend = F) %>%
  add_trace(x = c(2, 3, 4.2),
            y = c(2, 0, -1),
            type = 'scatter',
            mode = 'lines+markers',
            showlegend = F) %>%
  add_trace(x = c(1.5, 3, 4.2),
            y = c(1, 0.5, 1),
            type = 'scatter',
            mode = 'markers',
            showlegend = F) %>%
  layout(xaxis = list(range = c(1, 5)))
javascript <- "
marker_size = 0.5; // x-axis units
var myPlot = document.getElementsByClassName('plotly')[0];

function resize(eventdata) {
  var xaxis_stop = 5;
  var xaxis_start = 1;
  var plot_width = Plotly.d3.select('.xlines-above').node().getBBox()['width'];
  if (eventdata['xaxis.range[1]'] !== undefined) {
    var update = {'marker.size': marker_size * plot_width / (eventdata['xaxis.range[1]'] - eventdata['xaxis.range[0]'])};
  } else {
    var update = {'marker.size': marker_size * plot_width / (xaxis_stop - xaxis_start)};
  }
  Plotly.restyle(myPlot, update, 2);
}
resize({eventdata: {}});

myPlot.on('plotly_relayout', function(eventdata) {
  resize(eventdata);
});
"
p <- htmlwidgets::prependContent(p,
                                 onStaticRenderComplete(javascript))
p

Interactive JavaScript example

You could start with a defined height/width for your graph and a defined axis range, this way you would know how many pixels is one axis unit.

The size of your markers would be initially in the size you want.

Whenever a user changes the axis range, a plotly_relayout event will be triggered and you can retrieve the new ranges from the eventdata in xaxis.range[1] (start) and xaxis.range[1] (end)

Based on the new ranges you can relayout your marker sizes.

var plot_width = 500;
var plot_height = 500;
var margin_l = 100;
var margin_r = 100;
marker_size = 0.5; // x-axis units
xaxis_start = 1;
xaxis_stop = 5;

var trace1 = {
  x: [1.5, 2, 3, 4],
  y: [10, 15, 13, 17],
  mode: "markers",
  marker: {
    size: marker_size *
      (plot_width - margin_l - margin_r) /
      (xaxis_stop - xaxis_start)
  },
  showlegend: false
};

var trace2 = {
  x: [2, 3, 4, 4.5],
  y: [16, 5, 11, 10],
  mode: "lines"
};

var trace3 = {
  x: [1.5, 2, 3, 4],
  y: [12, 9, 15, 12],
  mode: "lines+markers",
  showlegend: false
};

var data = [trace1, trace2, trace3];

var layout = {
  width: plot_width,
  height: plot_height,
  margin: {
    l: margin_l,
    r: margin_r
  },
  xaxis: {
    range: [1, 5]
  },
  showlegend: false
};

Plotly.newPlot("myDiv", data, layout);

var refplot = document.getElementById("myDiv");
refplot.on("plotly_relayout", function(eventdata) {
  if (eventdata["xaxis.range[1]"] !== undefined) {
    var update = {
      "marker.size": marker_size *
        (plot_width - margin_l - margin_r) /
        (eventdata["xaxis.range[1]"] - eventdata["xaxis.range[0]"])
    };
  } else {
    var update = {
      "marker.size": marker_size *
        (plot_width - margin_l - margin_r) /
        (xaxis_stop - xaxis_start)
    };
  }
  Plotly.restyle("myDiv", update, 0);
});

<head>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<body>
  <div id="myDiv"></div>
</body>


问:
How to override Ionic2 sass variable just in one page?
I tried to override sass variable in variables.css like this

but it's not what I want.

It seems to change the styles of all tabs.

答:
Currently you cannot change sass variables in one page. That's just not how sass works. Sass is meant to be used as a global setting.

There is a work around to change let's say for example the background of a loading container.

You can do this for most.

If you open developer tools and select inspect element on the loading wrapper it gives the class .loading-wrapper as shown in image link below.

css class for loading shown in inspect element

In your app.css

```<code> .loadingCss {

  .loading-wrapper {
    color: #f4f4f4;
    background: #2979ff;
  }
}
</code>```

in your component ts add the class to your loading create instance

```<code>    //initialize a loading overlay
let working = this.loadingCtrl.create({
  content: 'Working...',
  spinner: 'dots',
  cssClass: 'loadingCss'
});
</code>```

Now you can create multiple instances of loading and have separate classes for loading and add them to your instance and the css will take effect.

Final result is shown in the below image link.

Loading overlays with custom css on two pages

I hope this helps

Body:
Currently you cannot change sass variables in one page. That's just not how sass works. Sass is meant to be used as a global setting.

There is a work around to change let's say for example the background of a loading container.

You can do this for most.

If you open developer tools and select inspect element on the loading wrapper it gives the class .loading-wrapper as shown in image link below.

css class for loading shown in inspect element

In your app.css

 .loadingCss {

  .loading-wrapper {
    color: #f4f4f4;
    background: #2979ff;
  }
}

in your component ts add the class to your loading create instance

    //initialize a loading overlay
let working = this.loadingCtrl.create({
  content: 'Working...',
  spinner: 'dots',
  cssClass: 'loadingCss'
});

Now you can create multiple instances of loading and have separate classes for loading and add them to your instance and the css will take effect.

Final result is shown in the below image link.

Loading overlays with custom css on two pages

I hope this helps


问:
Jupyter notebook table style changes when saved as html
I'm using jupyter notebook version 5.2.2 with python

When I display a DataFrame in the notebook the table style looks really nice. Especially the alternating grey and white row colors. When I save the notebook as html the nice style disappears.

Is there any way to keep the style that appears in the notebook itself?

答: Unfortunately, there is no way to achieve this. I have run into this problem before. When you convert the notebook to HTML you lose that styling. </p>


问:
Access control configuration Logic Apps via ARM templates
Is it possible to deploy the accessControl section of a Logic App via an ARM template ?
I used the LogicAppTemplateCreator from GitHub (https://github.com/jeffhollan/LogicAppTemplateCreator) to retrieve the ARM definition of the Logic and I tried to add the accessControl section but because it is not inside the definition of the Logic app itself, my ARM template is not valid.
Then, what is the best option to automatize the configuration of Logic Apps access controls?
Thanks.</p>

答:
Yes, access control is part of the logic app resource definition, and can be included in the template. See the following for details
https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-securing-a-logic-app

The relevant section you want included as part of your logic app resource template is below

```<code>{
    "name:" "myLogicAppWithAccessControl"
    "type": "Microsoft.Logic/workflows"
    "properties": {
        "definition": { <your logic app definition> },
        "accessControl": {
            "triggers": {
                "allowedCallerIpAddresses": [
                    {
                        "addressRange": "192.168.12.0/23"
                    },
                    {
                        "addressRange": "2001:0db8::/64"
                    }
                ]
            }
        }
    }
}
</code>```

Body:
Yes, access control is part of the logic app resource definition, and can be included in the template. See the following for details
https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-securing-a-logic-app

The relevant section you want included as part of your logic app resource template is below

{
    "name:" "myLogicAppWithAccessControl"
    "type": "Microsoft.Logic/workflows"
    "properties": {
        "definition": { <your logic app definition> },
        "accessControl": {
            "triggers": {
                "allowedCallerIpAddresses": [
                    {
                        "addressRange": "192.168.12.0/23"
                    },
                    {
                        "addressRange": "2001:0db8::/64"
                    }
                ]
            }
        }
    }
}


问:
Trying to assign groups in R, but it is filling in NA values and missing others that belong in the group
So I have a dataset in R (Framingham Heart Study data), and I am trying to assign BMI groups "underweight," "normal," "overweight," and "obese."

It has over 11,000 observations and 38 variables/columns, so it would be kind of hard to post some of the data here (I hope this won't be too much trouble to answer without it).

The dataset is called frm and I am trying to subset in the following way:

```<code>frm$BMIGRP <- NA  #Creating new variable (this part works and creates a BMIGRP column with all NA values)
frm$BMIGRP[which(as.numeric(frm$BMI) < 18.5)] <- "underweight"
</code>```

However, there are NA values in the data set BMI variable (indicated with a ".", which I have also tried changing to NA).

When I try to subset this way for each group, it is assigning only some of the underweight values to "underweight" and is assigning a lot of NA / "." values to underweight as well. It then tells me there are only 10 "normal" weight subjects and about 11000 in the obese category which is just not true because I can view the data set.

If done correctly, this should create the four groups with several hundred to several thousand observations in each category. But I am only getting 10 normal, 71 underweight, and ~11,000 obese.

I'm just not sure where I'm going wrong with this or if there is a different way I can create a new variable and assign it in the same kind of way. Any help is very much appreciated.

I should also mention that this is the code that my professor gave us as an example in our lab session, and I am basically copying and pasting it with the appropriate replacements for my data set.

This is my first question on this website so I apologize if it is incomplete or if I need to give more information. Thanks!

答:
Reading your code, it seems the column is not numeric.

This should work:

```<code>frm$BMI <- as.numeric(frm$BMI)
frm$BMIGRP[frm$BMI < 18.5] <- "underweight"
</code>```

Body:
So I have a dataset in R (Framingham Heart Study data), and I am trying to assign BMI groups "underweight," "normal," "overweight," and "obese."

It has over 11,000 observations and 38 variables/columns, so it would be kind of hard to post some of the data here (I hope this won't be too much trouble to answer without it).

The dataset is called frm and I am trying to subset in the following way:

frm$BMIGRP <- NA  #Creating new variable (this part works and creates a BMIGRP column with all NA values)
frm$BMIGRP[which(as.numeric(frm$BMI) < 18.5)] <- "underweight"

However, there are NA values in the data set BMI variable (indicated with a ".", which I have also tried changing to NA).

When I try to subset this way for each group, it is assigning only some of the underweight values to "underweight" and is assigning a lot of NA / "." values to underweight as well. It then tells me there are only 10 "normal" weight subjects and about 11000 in the obese category which is just not true because I can view the data set.

If done correctly, this should create the four groups with several hundred to several thousand observations in each category. But I am only getting 10 normal, 71 underweight, and ~11,000 obese.

I'm just not sure where I'm going wrong with this or if there is a different way I can create a new variable and assign it in the same kind of way. Any help is very much appreciated.

I should also mention that this is the code that my professor gave us as an example in our lab session, and I am basically copying and pasting it with the appropriate replacements for my data set.

This is my first question on this website so I apologize if it is incomplete or if I need to give more information. Thanks!

Body:
Reading your code, it seems the column is not numeric.

This should work:

frm$BMI <- as.numeric(frm$BMI)
frm$BMIGRP[frm$BMI < 18.5] <- "underweight"


问:
Constructor uses the mock object, how do I test a method in isolation?
I have a class that looks like this:

```<code>class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}
</code>```

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

```<code>MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));
</code>```

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

答:
As suggested by others, you can roll your own mock or you can set a number of expectations on the dependency.

For example, you can verify that your method was called:

```<code>var mock = new Mock<IDependency>();
var subject = new MyClass(mock.Object);

subject.Clear();

mock.Verify( dep => dep.Reset(), Times.AtMost(2));
</code>```

However it's worth pointing out that work within the constructor is a known code smell, and this smell is exacerbated when you try to write tests.

The fact that your constructor needs to call this method on the dependency suggests that this object knows too much information about the implementation details of the dependency.  This violates the Open Closed Principle and closes you off from scenarios where you don't want the Reset method from being called when it's initialized.

Also consider that any class or test that uses the MyClass concrete object as an dummy parameter will need a Mock initialized or you'll get a NullReferenceException.  This adds considerable overhead to writing your tests and adds a level of fragility that equates to long term maintenance and false negatives in your tests.  The only way around this is to make everything an interface which although effective isn't the best long term strategy either.

As per http://googletesting.blogspot.com/2009/07/separation-anxiety.html, the use of a Factory would reduce some of this coupling and open you up to better reuse of this object.

Body:
I have a class that looks like this:

class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

Body:
As suggested by others, you can roll your own mock or you can set a number of expectations on the dependency.

For example, you can verify that your method was called:

var mock = new Mock<IDependency>();
var subject = new MyClass(mock.Object);

subject.Clear();

mock.Verify( dep => dep.Reset(), Times.AtMost(2));

However it's worth pointing out that work within the constructor is a known code smell, and this smell is exacerbated when you try to write tests.

The fact that your constructor needs to call this method on the dependency suggests that this object knows too much information about the implementation details of the dependency.  This violates the Open Closed Principle and closes you off from scenarios where you don't want the Reset method from being called when it's initialized.

Also consider that any class or test that uses the MyClass concrete object as an dummy parameter will need a Mock initialized or you'll get a NullReferenceException.  This adds considerable overhead to writing your tests and adds a level of fragility that equates to long term maintenance and false negatives in your tests.  The only way around this is to make everything an interface which although effective isn't the best long term strategy either.

As per http://googletesting.blogspot.com/2009/07/separation-anxiety.html, the use of a Factory would reduce some of this coupling and open you up to better reuse of this object.


问:
Lodash | Search object for key
I am trying to search an object that I have for a key that matches an input name. This is so I can assign values.

<input type="text" name="first_name"/>

```<code>const inputs = document.querySelectorAll('inputs');
const obj = {
    first_name: "Bob",
    last_name: "Marley"
};
</code>```

I want to match the key first_name onto a input which has the name first_name.

I have got as far as:

```<code>_.forEach(inputs, (input) => {
    const value = _.filter(obj, input.name);
    input.value = value;
});
</code>```

However, I keep getting undefined so I don't believe the filter is the right function to use. However, I have had a look at the documentation and not really seen anything that comes close. I have tried to convert to an array but had no hope there either as all of the keys went to the index number.

答:
I think _.get(obj, input.name) is what you are looking for.

Here the docs:

```<code>_.get(object, path, [defaultValue])
</code>```

Gets the value at path of object. If the resolved value is undefined,
  the defaultValue is returned in its place.

Example:

```<code>const obj = {'a':1, 'b':{'c': 2}}
_.get(obj, 'a')   // returns 1
_.get(obj, 'b.c') // returns 2
</code>```

Title: Lodash | Search object for key

Body:
I am trying to search an object that I have for a key that matches an input name. This is so I can assign values.

<input type="text" name="first_name"/>

const inputs = document.querySelectorAll('inputs');
const obj = {
    first_name: "Bob",
    last_name: "Marley"
};

I want to match the key first_name onto a input which has the name first_name.

I have got as far as:

_.forEach(inputs, (input) => {
    const value = _.filter(obj, input.name);
    input.value = value;
});

However, I keep getting undefined so I don't believe the filter is the right function to use. However, I have had a look at the documentation and not really seen anything that comes close. I have tried to convert to an array but had no hope there either as all of the keys went to the index number.

Body:
I think _.get(obj, input.name) is what you are looking for.

Here the docs:

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined,
  the defaultValue is returned in its place.

Example:

const obj = {'a':1, 'b':{'c': 2}}
_.get(obj, 'a')   // returns 1
_.get(obj, 'b.c') // returns 2


问:
pandas group by and assign a group id then ungroup
I have a large data set in the following format:

```<code>id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook
</code>```

I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.

```<code>id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1
</code>```

I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.

```<code>x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)
</code>```

答:
You can use sklearn.preprocessing.LabelEncoder method:</p>

```<code>In [79]: from sklearn.preprocessing import LabelEncoder

In [80]: le = LabelEncoder()

In [81]: df['groupId'] = le.fit_transform(df['socialmedia'])+1

In [82]: df
Out[82]:
    id socialmedia  groupId
0    1    facebook        1
1    2    facebook        1
2    3      google        2
3    4      google        2
4    5      google        2
5    6     twitter        4
6    7      google        2
7    8     twitter        4
8    9    snapchat        3
9   10     twitter        4
10  11    facebook        1
</code>```

Body:
I have a large data set in the following format:

id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook

I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.

id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1

I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.

x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)

Body:
You can use sklearn.preprocessing.LabelEncoder method:

In [79]: from sklearn.preprocessing import LabelEncoder

In [80]: le = LabelEncoder()

In [81]: df['groupId'] = le.fit_transform(df['socialmedia'])+1

In [82]: df
Out[82]:
    id socialmedia  groupId
0    1    facebook        1
1    2    facebook        1
2    3      google        2
3    4      google        2
4    5      google        2
5    6     twitter        4
6    7      google        2
7    8     twitter        4
8    9    snapchat        3
9   10     twitter        4
10  11    facebook        1


问:
Emulating static constructors for templated classes

I would like to have a templated class with a static data member, and initialize it by emulating a "static constructor." For a non-templated class, this has already been answered (see static constructors in C++? I need to initialize private static objects and What is a static constructor?). However, none of the answers seem to work for a templated class.

The following is an example that tries to adapt the "static constructor" idiom from the previous answers to a templated class. (Note that the example is simply initializing an int and could be written without such constructors; however, I require a general solution.)

```<code>#include <iostream>

struct Foo
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Foo..." << std::endl;
            x = 1;
        }
    } initializer;
};
int Foo::x;
Foo::init Foo::initializer;

template<int N>
struct Bar
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Bar..." << std::endl;
            x = N;
        }
    } initializer;
};

template<int N>
int Bar<N>::x;
template<int N>
typename Bar<N>::init Bar<N>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}
</code>```

This outputs:

```<code>Initializing Foo...
1
0
</code>```

But I expected it to output:

```<code>Initializing Foo...
Initializing Bar...
1
1
</code>```

Is this an example of the "static initialization order fiasco?"

答:
No, it is not static initialization order fiasco. It is simply a result of the fact that every member of a template class is a template on it's own, and as such is not instantiated until used.

Your code never uses init member, so init is never instantiated.

However, your problem is easily solved:

```<code>#include <iostream>

template<int N>
struct Bar
{
    static int x;
};

template<int N>
int Bar<N>::x= N;

int main()
{
    std::cout << Bar<1>::x << std::endl;
    return 0;
}
</code>```

This gives you what you want in a simpler way.

Body:
I would like to have a templated class with a static data member, and initialize it by emulating a "static constructor." For a non-templated class, this has already been answered (see static constructors in C++? I need to initialize private static objects and What is a static constructor?). However, none of the answers seem to work for a templated class.

The following is an example that tries to adapt the "static constructor" idiom from the previous answers to a templated class. (Note that the example is simply initializing an int and could be written without such constructors; however, I require a general solution.)

#include <iostream>

struct Foo
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Foo..." << std::endl;
            x = 1;
        }
    } initializer;
};
int Foo::x;
Foo::init Foo::initializer;

template<int N>
struct Bar
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Bar..." << std::endl;
            x = N;
        }
    } initializer;
};

template<int N>
int Bar<N>::x;
template<int N>
typename Bar<N>::init Bar<N>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}

This outputs:

Initializing Foo...
1
0

But I expected it to output:

Initializing Foo...
Initializing Bar...
1
1

Is this an example of the "static initialization order fiasco?"

Body:
No, it is not static initialization order fiasco. It is simply a result of the fact that every member of a template class is a template on it's own, and as such is not instantiated until used.

Your code never uses init member, so init is never instantiated.

However, your problem is easily solved:

#include <iostream>

template<int N>
struct Bar
{
    static int x;
};

template<int N>
int Bar<N>::x= N;

int main()
{
    std::cout << Bar<1>::x << std::endl;
    return 0;
}

This gives you what you want in a simpler way.


问:
Create an array of integers property in Objective-C
I'm having troubles creating a property of an array of integers in Objective-C.
I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solution.

myclass.h

```<code>@interface myClass : NSObject {

@private int doubleDigits[10];
}

@property int doubleDigits;
@end
</code>```

myclass.m

```<code>@implementation myClass

    @synthesize doubleDigits;
    -(id) init {

        self = [super init];

        int doubleDigits[10] = {1,2,3,4,5,6,7,8,9,10};

        return self;
    }

    @end
</code>```

When I build and run, I get the following error:

error: type of property 'doubleDigits'
  does not match type of ivar
  'doubleDigits'

答:
This should work:</p>

```<code>@interface MyClass
{
    int _doubleDigits[10];
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having troubles creating a property of an array of integers in Objective-C.
I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solution.

myclass.h

@interface myClass : NSObject {

@private int doubleDigits[10];
}

@property int doubleDigits;
@end

myclass.m

@implementation myClass

    @synthesize doubleDigits;
    -(id) init {

        self = [super init];

        int doubleDigits[10] = {1,2,3,4,5,6,7,8,9,10};

        return self;
    }

    @end

When I build and run, I get the following error:

error: type of property 'doubleDigits'
  does not match type of ivar
  'doubleDigits'

Body:
This should work:

@interface MyClass
{
    int _doubleDigits[10];
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

OwnerDisplayName: s-bug


问:
How to access this.state from a function inside componentDidMount in React Native?
this.state is undefined when I try to use it inside a function within componentDidMount.  this is referring to the component within componentDidMount, but not when it is called from the nested function.  I have tried binding this to to the function but have not had any luck.  I am using React Native, but I believe this applies to React in general.  Here is componentDidMount:

componentDidMount(){
    console.log(this.state); //is state of the Component
    //this.state.foos is an array
    var foosRef = firebase.database().ref('foos');
    foosRef.on('child_added', function(child){
      console.log(this.state); //is undefined
      this.setState((prevState) => {
        return {foos: prevState.push(child) }
      })

    }).bind(this)

  }
```

<p>I currently have the following in my constructor:</p>

```this.componentDidMount.bind(this);
```

<p>I also tried binding <code>this</code> at the end of the callback, instead of after <code>.on</code> but that does not work either.</p>

<p>The error is:</p>

```TypeError: prevState.push is not a function. (In 'prevState.push(child)', prevState.push is undefined)
```

<p><code>state</code> is not a property of <code>this</code>.</p>

<p>I know you shouldn't mutate <code>prevState</code>, but I was previously doing</p>

```this.state.foos.push(child)
```

and haven't looked up the syntax for adding an element as a copy of the original.

答:
the problem is the context of 'this' within your handler function is not your component's definition.  You can solve this in one of three ways:

before calling foosRef.on, add

let my = this;
```</li>
</ol>

<p>then reference "my" inside your inline handler function instead of "this".</p>

<p>OR,
2. move your inline handler function to a standalone member of your component class, e.g.:</p>

<pre class="lang-js prettyprint-override"><code>function foosRefOnHandler(child){
  console.log(this.state); //is undefined
  this.setState((prevState) => {
    return {foos: prevState.push(child) }
  }
</code>```

then, you would have to change your foosRef.on call to bind that method:

foosRef.on('child_added', this.foosRefOnHandler.bind(this));
```

<p>OR,
3. using an inline arrow function instead of handler, e.g.:</p>

<pre class="lang-js prettyprint-override"><code>foosRef.on('child_added', (child) => {
  console.log(this.state); //is undefined
  this.setState((prevState) => {
    return {foos: prevState.push(child) }
  })

})
</code>```

Body:
this.state is undefined when I try to use it inside a function within componentDidMount.  this is referring to the component within componentDidMount, but not when it is called from the nested function.  I have tried binding this to to the function but have not had any luck.  I am using React Native, but I believe this applies to React in general.  Here is componentDidMount:

componentDidMount(){
    console.log(this.state); //is state of the Component
    //this.state.foos is an array
    var foosRef = firebase.database().ref('foos');
    foosRef.on('child_added', function(child){
      console.log(this.state); //is undefined
      this.setState((prevState) => {
        return {foos: prevState.push(child) }
      })

    }).bind(this)

  }

I currently have the following in my constructor:

this.componentDidMount.bind(this);

I also tried binding this at the end of the callback, instead of after .on but that does not work either.

The error is:

TypeError: prevState.push is not a function. (In 'prevState.push(child)', prevState.push is undefined)

state is not a property of this.

I know you shouldn't mutate prevState, but I was previously doing

this.state.foos.push(child)

and haven't looked up the syntax for adding an element as a copy of the original.

Body:
the problem is the context of 'this' within your handler function is not your component's definition.  You can solve this in one of three ways:

before calling foosRef.on, add

let my = this;

then reference "my" inside your inline handler function instead of "this".

OR,
2. move your inline handler function to a standalone member of your component class, e.g.:

function foosRefOnHandler(child){
  console.log(this.state); //is undefined
  this.setState((prevState) => {
    return {foos: prevState.push(child) }
  }

then, you would have to change your foosRef.on call to bind that method:

foosRef.on('child_added', this.foosRefOnHandler.bind(this));

OR,
3. using an inline arrow function instead of handler, e.g.:

foosRef.on('child_added', (child) => {
  console.log(this.state); //is undefined
  this.setState((prevState) => {
    return {foos: prevState.push(child) }
  })

})


问:
Possible to do double hashing with React Router HashRouter?
Im trying to make this

```<code><Route
    exact
    path={"/" + myPath + "/:product"}
    render={(props) => {
        return (
            <ProductInFocus
                productFocus={this.props.productFocus}
                state={this.props.productFocusState}
                match={props.match}
            />
        )
    }}
/>
</code>```

where myPath is something like root/mobiles/ or root/clothes or to whatever category the product belongs.

Right now, url ends up like this: http://localhost:3000/#/mobiles/example

I would like for it to look something like this: http://localhost:3000/#/mobiles/#/example

Problem is, React Router HashRouter only creates hash (#) for the first path, not the dynamic parameter.

Anyone had this problem?

Thanks.

答: React Router doesn't offer this capability. The hash (#) is a part of the URI Spec (RFC 3986), and is intended to identify one fragment of a URI. It doesn't make sense to have two in the URL, just like it wouldn't make sense to have two question marks (?) in a URL.</p>

Body:
Im trying to make this

<Route
    exact
    path={"/" + myPath + "/:product"}
    render={(props) => {
        return (
            <ProductInFocus
                productFocus={this.props.productFocus}
                state={this.props.productFocusState}
                match={props.match}
            />
        )
    }}
/>

where myPath is something like root/mobiles/ or root/clothes or to whatever category the product belongs.

Right now, url ends up like this: http://localhost:3000/#/mobiles/example

I would like for it to look something like this: http://localhost:3000/#/mobiles/#/example

Problem is, React Router HashRouter only creates hash (#) for the first path, not the dynamic parameter.

Anyone had this problem?

Thanks.


问:
How to add inside Laravel (Blade engine?)
ROUTE:

```<code>Route::get('usuario/{id}/edit', ['as' => 'users.edit', 'uses' => 'Admin\UserController@edit']);
</code>```

if it brings me the right id (data.id):

```<code><a href="users.edit/' + data.id + '"  class="btn btn-xs btn-primary" ><i class="glyphicon glyphicon-edit"></i></a>
</code>```

it does not bring me the right id:

```<code><a href="{{ route('users.edit','+data.id+') }}"  class="btn btn-xs btn-primary" ><i class="glyphicon glyphicon-edit"></i></a>
</code>```

How to add inside Laravel (Blade engine?)
Concatenation doesn't work

CODE:
{data: null, render: function (data, type, row) {
                        return '';
                        //return '';
                        }
                    }

答:
The problem is that you're literally passing: +data.id+ as your argument. Because PHP cannot be interpreted on the client side, you can only alias it ahead of time and modify it later:

```<code>let route = '{{ route('users.edit', '%DATA_ID%') }}'
</code>```

Add a class to the anchor link for reference:

```<code><a class="btn btn-xs btn-primary edit-link"...
</code>```

Then select it and update the route later:

```<code>document.querySelector('a.edit-link').href = route.replace('%DATA_ID%', data.id)
</code>```

Or if you've got $data as an stdClass coming back from Laravel:

```<code><a href="{{ route('users.edit', $data->id) }}" class="btn btn-xs btn-primary">
</code>```

Body:
ROUTE:

Route::get('usuario/{id}/edit', ['as' => 'users.edit', 'uses' => 'Admin\UserController@edit']);

if it brings me the right id (data.id):

it does not bring me the right id:

How to add inside Laravel (Blade engine?)
Concatenation doesn't work

CODE:
{data: null, render: function (data, type, row) {
                        return '';
                        //return '';
                        }
                    }

Body:
The problem is that you're literally passing: +data.id+ as your argument. Because PHP cannot be interpreted on the client side, you can only alias it ahead of time and modify it later:

let route = '{{ route('users.edit', '%DATA_ID%') }}'

Add a class to the anchor link for reference:

<a class="btn btn-xs btn-primary edit-link"...

Then select it and update the route later:

document.querySelector('a.edit-link').href = route.replace('%DATA_ID%', data.id)

Or if you've got $data as an stdClass coming back from Laravel:

<a href="{{ route('users.edit', $data->id) }}" class="btn btn-xs btn-primary">


问:
Finding the common value on Google Sheets
Having a bit of an issue creating this algorithm hoping someone can help. I am trying to see what laptops are most commonly being damaged in accordance to the teacher.

Basically what I am trying to do is, I am trying to figure out what laptops that are assigned to a specific teacher are being damaged the most. I work at a school and I want to see if theres a pattern to the laptops that are damaged.

I want to go from an overall data set of ALL teachers and ALL incidents, to then having a tally count of each teachers, and finally to the laptop and teacher that is most commonly being repaired

Example Teacher1 has the laptop with the asset tag 1232 that pops up twice. I want the most common laptop that is assigned to the teacher to pop up in the Most Common column.

a test sheet

答:
You can also do it with a query like this

```<code>=query(A:E,"select C,count(C) where A='"&G2&"' group by C order by count(C) desc limit 1 label C '',count(C) ''")
</code>```

Where the asset tag is in column C and the teacher name is in G2.

Body:
You can also do it with a query like this

=query(A:E,"select C,count(C) where A='"&G2&"' group by C order by count(C) desc limit 1 label C '',count(C) ''")

Where the asset tag is in column C and the teacher name is in G2.


问:
Github v3 API get all organizations more than 100
I am trying to get all organization items through http://host/api/v3/organizations?page=2&per_page=100

The default size seems like 30, and 100 seems like the max limit per request.
But above link still only returns the first 100 items, i.e, not 101-200th

I also tried http:host//api/v3/organizations?page=2
No matter which page I set, it only returns the first 30 items.

How can I get the entire list of organization items please? Please help. Appreciate.

答:
From Github API reference for listing organizations :

Note: Pagination is powered exclusively by the since parameter. Use
  the Link header to get the URL for the next page of organizations.

For instance checking the 2nd page using curl :

curl -I "https://api.github.com/organizations"
```

<p>gives the following link header : </p>

```Link: <https://api.github.com/organizations?since=3043>; rel="next", <https://api.github.com/organizations{?since}>; rel="first"
```

So the next page will be https://api.github.com/organizations?since=3043

For each request you would check this header to get the next url to hit

Body:
From Github API reference for listing organizations :

Note: Pagination is powered exclusively by the since parameter. Use
  the Link header to get the URL for the next page of organizations.

For instance checking the 2nd page using curl :

curl -I "https://api.github.com/organizations"

gives the following link header :

Link: <https://api.github.com/organizations?since=3043>; rel="next", <https://api.github.com/organizations{?since}>; rel="first"

So the next page will be https://api.github.com/organizations?since=3043

For each request you would check this header to get the next url to hit


问:
How to handle matrices of different dimensions using templates?
I would like to achieve the conversion of a matrix to a string, regardless of its size(s), type or dimension(s). Using templates, I've managed to make it work by defining one template for each "sort" of matrix I need.

Template for arrays:

```<code>template < typename NUM, std::size_t SIZE >
std::string to_string( const std::array< NUM, SIZE > &arr ) {

    std::string buf;
    for ( uint32_t i = 0; i < SIZE; i++ )
        buf += std::to_string( arr[i] ) + " ";

    return buf;
}
</code>```

Template for 2-dimensionnal matrices:

```<code>template < typename NUM, std::size_t INNER_SIZE, std::size_t OUTER_SIZE >
std::string to_string( const std::array< std::array<NUM, INNER_SIZE>, OUTER_SIZE > &arr ) {

    std::string buf;

    for ( uint32_t i = 0; i < OUTER_SIZE; i++ ) {
        for ( uint32_t j = 0; j < INNER_SIZE; j++ )
            buf += std::to_string( arr[i][j] ) + " ";
    }

    return buf;
}
</code>```

However, I'd like to make the solution more 'elegant', by only having a generic template that could handle matrices regardless of their dimensions. Is there any way to do that ?

答:
First of all: I strongly suggest to avoid to give your functions the same name of a standard function. So, in the following example, I've renamed fooString() your function to avoid the risk of a clash with std::to_string.

Second: as observed by Bob__, if you replace the inner loop with a call to to_string(arr[i]) (fooString(arr[i]), with my renaming), you resolve recursively the problem of the multidimensional (for every dimension) array.

Third: I suggest to write a ground case that get the std::to_string() for a single value (where T is the base (not array) type, like int, float, etc.)

```<code>template <typename T>
std::string fooString (T const & val)
 { return std::to_string(val); }
</code>```

and the recursive case become

```<code>template <typename T, std::size_t Dim>
std::string fooString (std::array<T, Dim> const & arr)
 {
    std::string buf;

    for ( auto const & elem : arr )
        buf += fooString( elem ) + " ";

    return buf;
}
</code>```

With a ground case that treat a base type you have one more level of indirection (so performances are, presumably, a little worse) but the logic of array management is only in one function and not almost equal in two (less error prone maintaining the code).

The following is a full working C++11 example

```<code>#include <array>
#include <string>
#include <iostream>

template <typename T>
std::string fooString (T const & val)
 { return std::to_string(val); }

template <typename T, std::size_t Dim>
std::string fooString (std::array<T, Dim> const & arr)
 {
    std::string buf;

    for ( auto const & elem : arr )
        buf += fooString( elem ) + " ";

    return buf;
}

int main()
 {
   std::array<std::array<std::array<int, 2U>, 3U>, 4U> a3dim
    {{ {{ {{  2,  3 }}, {{  5,  7 }}, {{ 11, 13 }} }},
       {{ {{ 17, 19 }}, {{ 23, 29 }}, {{ 31, 37 }} }},
       {{ {{ 41, 43 }}, {{ 47, 53 }}, {{ 59, 61 }} }},
       {{ {{ 67, 71 }}, {{ 73, 79 }}, {{ 83, 89 }} }} }};

   std::cout << fooString(a3dim) << std::endl;
 }
</code>```

Body:
I would like to achieve the conversion of a matrix to a string, regardless of its size(s), type or dimension(s). Using templates, I've managed to make it work by defining one template for each "sort" of matrix I need.

Template for arrays:

template < typename NUM, std::size_t SIZE >
std::string to_string( const std::array< NUM, SIZE > &arr ) {

    std::string buf;
    for ( uint32_t i = 0; i < SIZE; i++ )
        buf += std::to_string( arr[i] ) + " ";

    return buf;
}

Template for 2-dimensionnal matrices:

template < typename NUM, std::size_t INNER_SIZE, std::size_t OUTER_SIZE >
std::string to_string( const std::array< std::array<NUM, INNER_SIZE>, OUTER_SIZE > &arr ) {

    std::string buf;

    for ( uint32_t i = 0; i < OUTER_SIZE; i++ ) {
        for ( uint32_t j = 0; j < INNER_SIZE; j++ )
            buf += std::to_string( arr[i][j] ) + " ";
    }

    return buf;
}

However, I'd like to make the solution more 'elegant', by only having a generic template that could handle matrices regardless of their dimensions. Is there any way to do that ?

Body:
First of all: I strongly suggest to avoid to give your functions the same name of a standard function. So, in the following example, I've renamed fooString() your function to avoid the risk of a clash with std::to_string.

Second: as observed by Bob__, if you replace the inner loop with a call to to_string(arr[i]) (fooString(arr[i]), with my renaming), you resolve recursively the problem of the multidimensional (for every dimension) array.

Third: I suggest to write a ground case that get the std::to_string() for a single value (where T is the base (not array) type, like int, float, etc.)

template <typename T>
std::string fooString (T const & val)
 { return std::to_string(val); }

and the recursive case become

template <typename T, std::size_t Dim>
std::string fooString (std::array<T, Dim> const & arr)
 {
    std::string buf;

    for ( auto const & elem : arr )
        buf += fooString( elem ) + " ";

    return buf;
}

With a ground case that treat a base type you have one more level of indirection (so performances are, presumably, a little worse) but the logic of array management is only in one function and not almost equal in two (less error prone maintaining the code).

The following is a full working C++11 example

#include <array>
#include <string>
#include <iostream>

template <typename T>
std::string fooString (T const & val)
 { return std::to_string(val); }

template <typename T, std::size_t Dim>
std::string fooString (std::array<T, Dim> const & arr)
 {
    std::string buf;

    for ( auto const & elem : arr )
        buf += fooString( elem ) + " ";

    return buf;
}

int main()
 {
   std::array<std::array<std::array<int, 2U>, 3U>, 4U> a3dim
    {{ {{ {{  2,  3 }}, {{  5,  7 }}, {{ 11, 13 }} }},
       {{ {{ 17, 19 }}, {{ 23, 29 }}, {{ 31, 37 }} }},
       {{ {{ 41, 43 }}, {{ 47, 53 }}, {{ 59, 61 }} }},
       {{ {{ 67, 71 }}, {{ 73, 79 }}, {{ 83, 89 }} }} }};

   std::cout << fooString(a3dim) << std::endl;
 }