Server crashes with "huge task timeout"

Question: First things first, I've read a lot about the "huge task timeout" kernel panic and know that this often happens if the server is out of resources.
Error messages which appear only in the VNC console not in any log file:
[264240.505133] "echo 0 > /proc/sys/kernel/huge_task_timeout_secs" disables this message.
[264240.505359] INFO: task nginx:2333 blocked for more than 120 secounds.
[264240.505454] "echo 0 > /proc/sys/kernel/huge_task_timeout_secs" disables this message.
[264240.505658] INFO: task nginx:2334 blocked for more than 120 secounds.
[264240.505752] "echo 0 > /proc/sys/kernel/huge_task_timeout_secs" disables this message.
[264240.505946] INFO: task nginx:2335 blocked for more than 120 secounds.
[264240.506038] "echo 0 > /proc/sys/kernel/huge_task_timeout_secs" disables this message.
[264240.506251] INFO: task php5-fpm:2415 blocked for more than 120 secounds.
...

Server specs:
8 Core Intel® Xeon® E5-2660V3
24 GB DDR4
320GB SSD

The machine is KVM virtualized.
It runs debian wheezy with PHP5-FPM, NGINX, MySQL and some other smaller stuff.
Mainly it hosts a WebSite and a huge MySQL DB with around 25 GB data.
Disk usage is around 12%.
I've installed Munin for monitoring, which shows no anomaly.
But since the last crash I installed also sysstat but I don't really know which of the log files could be useful for you. So please request that one you think are needed.
The crash happened around 10.03.2015 17:37 GMT.
In my opinion this has something to do with MySQL.
Here the my.cnf
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

bind-address        = 127.0.0.1

key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
myisam-recover-options  = BACKUP
max_connections         = 50
query_cache_limit   = 1M
query_cache_size        = 16M

log_error = /var/log/mysql/error.log

slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log

expire_logs_days    = 10
max_binlog_size         = 100M

innodb_buffer_pool_size = 18G
innodb_log_file_size    = 256M

[mysqldump]
quick
quote-names
max_allowed_packet  = 16M

[mysql]

[isamchk]
key_buffer      = 16M

!includedir /etc/mysql/conf.d/

As you can see I configured MySQL that it can use around 80% of the total RAM.
The MySQL server performs in average 2k queries/secound with 50/50 read/write.
Right before the crash I saw in htop that around 21 GB of 24 GB are used and 500 MB of the 1,5 GB swap, CPU usage was normal.
EDIT:
sar -u of the time direct before the crash:
18:27:01        CPU     %user     %nice   %system   %iowait    %steal     %idle
18:29:01        all      8,28      0,00      1,31      5,61      0,02     84,77
18:31:01        all      7,65      0,41      1,41      5,73      0,03     84,78
18:33:01        all      7,95      0,00      1,25      5,51      0,02     85,27
18:35:01        all      8,87      0,00      1,42      5,53      0,03     84,15
18:37:01        all      8,99      0,42      1,40      5,94      0,03     83,22
Average:        all      8,65      0,16      1,35      5,08      0,03     84,73

EDIT:
Munin images
https://i.stack.imgur.com/hOK7w.jpg
MySQL Query
EDIT:
I contacted my ISP an they said, that nothing abnormal happened at the time of the crash. So it has something to do with my setup.
Now I will check what happens if I reduce the innodb_buffer_pool_size to 14 GB and add the innodb_flush_method = O_DIRECT.
Comment: You should probably look at `iowait` in  `sar`. Your symptoms leads me to believe it's an IO issue.
Comment: Could you please explain the crashing behavior? Is it a core dump, a kernel panic? Resource starvation? OOM Killer? KVM crash?
Comment: The server freezes completely, I'm unable to connect via SSH/HTTP/etc. only in the VNC Console which is buffered, I can see the last print out (see main post). I asked my provider and they said that the KVM is still running, so I think it is a kernel panic.
Comment: %steal is CPU requested by your VM and not given because another VM was scheduled to run. The higher it is the slower will be your VM.
Answer: The problem is not a kernel panic. What you see on the console is hung process in a kernel call.
You should check either the console or the /var/log/syslog or /var/log/messages and search for the full stack trace that is logged by the kernel. You will have an idea which subsystem is slow. Could be disk as mentioned by @Belmin Fernandez, could be network...
Now you have to get some stats from the host too. If CPU usage or disk I/O are overcommited, you could have a resource starvation caused by other VMs running on the same host. It will be difficult to determine if this is the cause only from VM.
KVM has support for paravirtualization drivers. Check with the ISP if they are installed and up to date on all VMs running on the host machine.
If you run both MySQL and Nginx on the same machine, make sure that MySQL and Nginex can keep all active data in RAM. 80% allocated for MySQL could be to high.
Could you please post Munin graphs of the File System Cache. When FS Cache is going lower and lower, then your VM is starving memory.
If you have access on the console, you can use kernel's magic SysRq key to trigger a task list. Enable it echo 1 > /proc/sys/kernel/sysrq, then you can use the console to list the running tasks: ALT + SysRq + t
Comment: `/var/log/syslog` and `/var/log/messages` contain **no** stack. Both stop right before 18:37. Syslog contains as last entrie before the crash the start of the sysstat cronjob while messsages starts with the boot kernel stack.
Comment: The memory graphs of Munin would be interesting then. If you have Disk I/O would be great too.
Comment: FS Cache is ok in the Munin graphs
Comment: The disk I/O is very low after reboot. I was wondering why is so high before reboot?
Comment: 19GB active memory average - I think soon you will need to ad more memory to the VM and to MySQL too.
Comment: I've added an image of the MySQL Queries/second which shows why there is such a heavy IO before the crash. The DB will be optimized soon as well as I will upgrade to a much bigger instance. But for now I have this one. What do you mean by "access to console"? I only have SSH access and VNC.
Comment: Access to the console, means the terminal where you can configure the BIOS and see the kernel boot messages.
Comment: Canonically, the console is the primary terminal where the kernel messages are printed. It could be a serial tty.
Comment: In my VNC console I can see the kernel boot messages, but it does not support the `SysRq` key.

Server crashes with "huge task timeout"


Induction step for $\sum\limits_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6}$

Question: I want to prove by induction that,
$\sum\limits_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6}$
OK I got the initial step, however, I have problems with the induction step:
Here is what I tried:
$\sum\limits_{i=1}^{n+1} i^2  + n+1= \frac{n(n+1)(2n+1)}{6} + n+1 =\frac{n(n+1)(2n+1)}{6} + \frac{6*(n+1)}{6} = \frac{(n+1)(n+6)(2n+1)}{6}$
Here I am stuck. How to conclude this for $A(n+1)$?
I appreciate your answers!
UPDATE:
$\sum\limits_{i=1}^{n+1} i^2  + n+1= \frac{n(n+1)(2n+1)}{6} + n+1 =\frac{n(n+1)(2n+1)}{6} + \frac{6*(n+1)}{6} = \frac{(n+1)*[n(2n+1) + 6]}{6}$
Comment: Here is the same [problem](http://math.stackexchange.com/questions/472292/critique-on-a-proof-by-induction-that-sum-i-1n-i2-nn12n1-6).
Comment: You last step is wrong: $\frac a n + \frac b n = \frac{a+b}{n}$
Comment: @ulead86 Thx for your answer! I edited my last step!
Answer: $\sum_{i=1}^{n+1}i^{2}=\sum_{i=1}^{n}i^{2}+(n+1)^{2}$
by the induction hypothesis we have
$=\frac{n(n+1)(2n+1)}{6}+(n+1)^{2}=\frac{(n^{2}+n)(2n+1)}{6}+\frac{6(n^{2}+2n+1)}{6}$
$=\frac{2n^{3}+3n^{2}+n}{6}+\frac{6n^{2}+12n+6}{6}=\frac{2n^{3}+9n^{2}+13n+6}{6}=\frac{(2n^{3}+9n^{2}+7n)+(6n+6)}{6}=\frac{n(2n+7)(n+1)+6(n+1)}{6}=\frac{(n+1)(2n^{2}+7n+6)}{6}$
$=\frac{(n+1)(2n+3)(n+2)}{6}=\frac{(n+1)((n+1)+1)(2(n+1)+1)}{6}$.
Answer: If the induction is to work we need $\sum_{i=1}^{n+1}{i^2}$ = (n+1)(n+2)(2n+3) which we get by substituting (n+1) for n in the proposed formula.  We have
$\sum_{i=1}^{n+1}{i^2}$ = $\sum_{i=1}^{n}{i^2}$ + $(n+1)^2$ = $\frac{n(n+1)(2n+1)}{6}$ + $(n+1)^2$ = $\frac{n(n+1)(2n+1) + 6(n+1)^2}{6}$ .  We can now deal just with the numerator and we have
n(n+1)(2n+1) + 6$(n+1)^2$ = (n+1)[n(2n+1) + 6(n+1)] = (n+1)[2$n^2$ + 7n + 6] = (n+1)(n+2)(2n+3).
That is exactly what the numerator should be, so the induction step is done.


Prove $a^2\cos B\cos C+b^2\cos C\cos A+c^2\cos A\cos B\leq2S.$

Question: Prove that in any triangle inequality holds:
$$a^2\cos B\cos C+b^2\cos C\cos A+c^2\cos A\cos B\leq2S.$$
Is gender inequality that occurs right triangle, not an equilateral triangle. For this reason I suspect you have used other ways different from the usual.
Answer: Let $H$ be the orthocenter of $ABC$. Then
$$ d(H,BC) = 2R\cos B\cos C $$
hence:
$$ \sum_{cyc} 2R a\cos B\cos C = 2S. $$
If $ABC$ is an acute triangle, then $\cos A,\cos B,\cos C>0$ and $a,b,c < 2R$, hence:
$$ \sum_{cyc} a^2\cos B\cos C < \sum_{cyc} 2R a\cos B\cos C = 2S. $$
However, if $ABC$ is an obtuse triangle, the given inequality does not hold: consider, for instance, $(a,b,c)=(\sqrt{3},1,1)$, so that $(A,B,C)=(120^\circ,30^\circ,30^\circ)$,
$$\sum_{cyc}a^2\cos B\cos C = \frac{9}{4}-\frac{\sqrt{3}}{2},\qquad 2S=\frac{\sqrt{3}}{2}.$$


MySQLIntegrityConstraintViolationException: Column cannot be null - for lookup table

Question: I have a lookup table "Marital status" and "Employee" table.
a foreign key defined into employee to define marital status for this employee, this column accepts null value (not required).
now I am using hibernate and spring mvc.
The question is, I am selecting marital status for this employee from a dropdown list but it is trying to insert a new record into marital status table, which i do not need to happen, I just need a new employee with a reference to the marital status ?
public class MaritalStatus {

    @Id
    @Column(name = "id")
    @Basic(optional=false)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer maritalStatusId;

    @Basic(optional=false)
    @Column(name="description")
    private String maritalStatusDescription;

    @OneToMany
    @JoinColumn(name="fkMaritalStatus")
    private List<Employee> employeeList;

     ....other getters/setters
}

//////////EMPLOYEE
@Entity
@Table(name="employee")
public class Employee {

    @Id
    @Column(name="pk_id")
    @Basic(optional=false)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer employeeId;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="fk_marital_status", insertable=false, updatable=false)
    private MaritalStatus fkMaritalStatus;

    ....other columns and getters/setters
}

here is the exception
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'description' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2468)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2629)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2719)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2450)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2371)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2355)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2966)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3477)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
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:734)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:726)
at org.hibernate.engine.spi.CascadingAction$5.cascade(CascadingAction.java:258)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:387)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:330)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:424)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:263)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:763)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:755)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:751)
at com.nassar.doa.impl.EmployeeDAOImpl.add(EmployeeDAOImpl.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy43.add(Unknown Source)
at com.nassar.service.impl.EmployeeServiceImpl.add(EmployeeServiceImpl.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy44.add(Unknown Source)
at com.nassar.controller.EmployeeController.addEmployee(EmployeeController.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

any help would be appreciated...
Answer: When MaritalStatus.maritalStatusId become null then Hibernate expect this to be an new instance. - Thats the reason why it try to insert the "new" item.
Solution: So try to set Employee.fkMaritalStatus to null instead. Then the employee will have no material status.
Comment: seriously I tried this solution

      if(employee.getFkMaritalStatus().getMaritalStatusId() == null)
       employee.setFkMaritalStatus(null);
      session.getCurrentSession().save(employee);

and it works perfectly, but I think there is better solution?
does hibernate provides one?
Comment: Omar.Nassar: This is the most straight forward solution - try to have a look at this from the view point of hibernate. -- You have an entity with an reference to an other entity with id=null (this mean, yet unsaved), and now you save it. -- The point is that hibernate try to save your objects, and when there is an object hibernate will try to save it.


Calculating the number of possible paths through grid

Question:
We are given with four integers $H$ , $W$ , $A$ , $B$ respectively

We have a large rectangular grid with $H$ rows and $W$ columns. Find the number of paths from top left to bottom right moving only right ($R$) or down ($D$) to adjacent cells .
However, we cannot enter the cells in the intersection of the bottom $A$ rows and the leftmost $B$ columns. (That is, there are $A \times B$ forbidden cells.) There is no restriction on entering the other cells.
Example 1 : $H = 2; W = 3; A = 1; B = 1$
Answer : $2$
Example 2 : $H = 10; W = 7; A = 3; B = 4$
Answer : $3570$
Comment: So what do you want to ask?
Comment: Number of ways to reach bottom right
Comment: What have you done so far?  Do you know the number of paths if there is no forbidden rectangle?
Comment: I bet this is from a programming competition of some kind. Codechef maybe?
Comment: No , it is from here https://atcoder.jp/contests/abc042/tasks/arc058_b past contest .
Comment: I ask because the editorial of this solution was in Japanese , and it was very difficult to understand from google translate
Answer: Assume there is no forbidden rectangle i.e. $A = B = 0$. Combinatorics tells us that then there are $\binom{W + H}{H}$ possible paths.
Now we want to subtract all forbidden paths. Note that a path is forbidden if he enters the forbidden rectangle. Let's think of a path as a string over $\{R, D\}$ of length $W+H$ where $R$ denotes a move to the right and $D$ denotes a move down.
We can see that a path enters the forbidden rectangle if and only if more than $H - A$ of the first $B + (H - A)$ moves are $D$'s. So how many strings of length $H + W$ are there where the first $B + (H - A)$ letters contain more than $(H - A)$ times a $D$? We can count this by the following sum: $$S := \Sigma_{i = H - A + 1}^{B + (H - A)}\binom{B+(H - A)}{i} \binom{W - B+A}{H - i}$$
For a given $i$ the first binom corresponds to the amount of strings of length $B + (H - A)$ with $i$ times a $D$. The second binom corresponds to the amount of strings of length $W - B + A$ containing $H-i$ times a $D$.
So the answer would be: $$ \binom{W + H}{H} - S$$
Comment: srry for late reply . I understand the part that i have to make more than (H-A) moves Down to reach a row containing forbidden zone . How is B + ( H - A) Right moves are for columns ? . I am assuming H for rows and W for columns
Comment: Consider the rectangle above the forbidden rectangle. Its height is $H - A$ and its width is $B$ (assuming it is right aligned with the forbidden rectangle). If we make $B$ right moves and $H - A$ down moves in the first $B + (H - A)$ moves then we end up in the right left corner of this rectangle. If we do more right moves and less down moves we're fine. But if we do more down moves and less right moves we'll enter the forbidden rectangle. I just played around with some examples until I got to $B + (H - A)$. And once I had the intuition it was not too hard to argue why that must be correct.


Hide Detailed Row in SSRS When Toggled Item are collapsed

Question: I went through many post on SO but not find the suitable solution to the problem
I have a tablix and I have groups and toggled on Run,Task Name and Procedure Name. when the groups are collapsed one detailed row after procedure name is visible.

What I want is to hide entire row when toggled is collapsed and will show when it is expanded. how to achive this
  I want to hide all information from operation to status columns in tablix when toggled is collapsed.

Here is the tablix I am dealing with

@user3540780 I have already done that groupings
here is what I have done
Answer: You need to set up four groups
Dimensions, Task Name, Procedure Name and Load.
Task Name is toggled by Dimension,
Procedure Name is toggled By Task Name,
Load is toggled by Procedure Name.
Load needs to be a grouping at detail line level simply grouping on all the fields in your detail section.
Set up your toggles in the Row Groups window at the bottom of the designer screen. If you have added the groups correctly there will be a dashed grouping line between the Operation column and the remaining columns. (You need to have selected a cell in the tablix to see these)
You will find that the whole detail line will be toggled
Comment: can you post a picture of the tablix in design view
Comment: You need to select a cell in the tablix before capturing the image so I can see the dashed grouping lines


Multiple RewriteCond for multiple RewriteRules

Question: I'm using these rewrite rules that only go into effect if there is NOT a "user" cookie.
RewriteCond %{HTTP_COOKIE} (user)
RewriteRule (.*)? - [S=5] # Skip the below 5 lines if the above test passes
RewriteRule ^$ app/webroot/cache_static_html/cache_static_popular_results_1.html [L]
RewriteRule ^popular/page:2$ app/webroot/cache_static_html/cache_static_popular_results_2.html [L]
RewriteRule ^popular/page:3$ app/webroot/cache_static_html/cache_static_popular_results_3.html [L]
RewriteRule ^popular/page:4$ app/webroot/cache_static_html/cache_static_popular_results_4.html [L]
RewriteRule ^popular/page:5$ app/webroot/cache_static_html/cache_static_popular_results_5.html [L]

Now, how can I add another condition that there must not be a query string value? If there is a "user" cookie OR a query string, those 5 rules should be skipped.
Answer: RewriteCond %{HTTP_COOKIE} (user) [OR]
RewriteCond %{QUERY_STRING} ^user=(.*) #assuming ?user=xyz
RewriteRule (.*)? - [S=5] # Skip the below 5 lines if the above test passes
RewriteRule ^$ app/webroot/cache_static_html/cache_static_popular_results_1.html [L]
RewriteRule ^popular/page:2$ app/webroot/cache_static_html/cache_static_popular_results_2.html [L]
RewriteRule ^popular/page:3$ app/webroot/cache_static_html/cache_static_popular_results_3.html [L]
RewriteRule ^popular/page:4$ app/webroot/cache_static_html/cache_static_popular_results_4.html [L]
RewriteRule ^popular/page:5$ app/webroot/cache_static_html/cache_static_popular_results_5.html [L]


Display shipping subtotal including taxes

Question: I'm settings up a shop with VAT and shipping. All works well except just one thing fails, when I include VAT in the shipping rate the price component displays the amount excluding taxes. But I want the full amount including taxes to be displayed.
How can I achieve this?
Answer: This is happening because the "Order Total" process combines like price components together and then lists them out. As a result, the base shipping rate component is appearing unaltered and the VAT is being combined into any other product VAT (or shipping VAT) components. It's an unfortunate display side effect of the implementation of price components, but it's on the roadmap to be updated in Commerce 2.x.
In the meantime, your solution will involve implementing hook_commerce_price_formatted_components_alter(), which you can find documented in commerce_price.api.php. This is purely a display alteration, so all the necessary data will still be there unaltered - you can just fiddle with the display amounts of the price components so your VAT component gets added to your shipping component instead.
Comment: Thank you very much! :)
For others with this problem:
`
foreach ($components as &$component) {
  if($component['title'] == "Shipping" ){
      $component['price']['amount'] += $component['price']['amount'] * 0.19; // for 19% VAT
     }
 }
`


EF 6, Mapeamento com Fluent Api em classes com herança

Question: Estou treinando o mapeamento de classes para o Entity Framework usando a Fluent API e estou com algumas dúvidas.
A primeira é a seguinte: Mapear uma foreign key com atributos seria assim:
public int EmpresaId {get; set;}
[ForeignKey("EmpresaId")]
public Empresa Empresa {get; set;}

Com a Fluent API seria assim:
HasRequired(p => p.Empresa).WithMany().HasForeignKey(p => p.EmpresaId);

Correto isso? O que não entendi é esse WithMany() já que é uma ligação simples de chave estrangeira e não é uma ICollection<>, por exemplo. Então porque desse WithMany()?
A outra dúvida seria, como ficaria o mapeamento com a Fluent API dessas classes, já que duas herdam da primeira?
public class Pessoa
{
    public int Id {get; set;}
    public string Nome {get; set;}
}

public class PessoaFisica : Pessoa
{
    public string CPF {get; set;}
}

public class PessoaJuridica : Pessoa
{
    public string CNPJ {get; set;}
}

Answer: WithMany
Usa-se WithMany() para especificar um relacionamento Many. O que está mesmo esquisito é o fato de você estar usando WithMany() sem argumentos. WithMany() serve para você especificar a relação inversa.
Por exemplo, se aquele trecho de código se refere a uma pessoa, o correto seria o mapeamento ser assim:
HasRequired(p => p.Empresa)
    .WithMany(e => e.Pessoas)
    .HasForeignKey(p => p.EmpresaId);

Classe Pessoa
Uma Pessoa em teoria só pode ser Física ou Jurídica, certo? O correto seria fazer assim:
public abstract class Pessoa
{
    public int Id {get; set;}
    public string Nome {get; set;}
}

public class PessoaFisica : Pessoa
{
    public string CPF {get; set;}
}

public class PessoaJuridica : Pessoa
{
    public string CNPJ {get; set;}
}

Na Fluent API:
modelBuilder.Entity<PessoaFisica>()
    .HasKey(pf => pf.Id);
modelBuilder.Entity<PessoaFisica>()
    .Property(pf => pf.Nome)
    .HasMaxLength(70)
    .IsRequired();
modelBuilder.Entity<PessoaJuridica>()
    .HasKey(pj => pj.Id);
modelBuilder.Entity<PessoaJuridica>()
    .Property(pj => pj.Nome)
    .HasMaxLength(70)
    .IsRequired();

Comment: Poxa, não dá nem tempo de responder tu aparece aqui já respondendo ein... kkk vai ser ativo assim lá na china...
brincadeira...
Comment: Legal seu exemplo da classe `abstrata` de `Pessoa`, mas quanto a propriedade Nome, se via `Fluent API` eu quiser especificar que ela é requerida e tem um máximo de 70 caracteres, por exemplo, onde eu faria essa especificação?
Comment: @Tiago Vou editar a resposta pra você.
Comment: @CiganoMorrisonMendez mas ele poderia fazer um `DbSet` e no `modelBuilder.Entity.Property(p => p.Nome).IsRequired();` ele poderia fazer a validação não poderia? Pois ai através do `Descriminator` o framework se encarregaria de distribuir as classes corretamente não é? (ps: não dá pra testar agora [longe de um pc com visual studio/.net])
Comment: @tchicotti Pode. Também vale como exemplo.
Answer: Tiago, provavelmente sua classe deve ser algo assim:
public Pessoa {
    public int Id { get; set; }
    public int EmpresaId {get; set;}
    [ForeignKey("EmpresaId")]
    public Empresa Empresa {get; set;}
}

Dai sua classe Empresa deve ser algo por volta de
public Empresa {
    public int Id { get; set; }
    //...
    public ICollection<Pessoa> Pessoas {get; set;}
}

Estou certo?
Se for, o seu relacionamento do Fluent deverá representar da seguinte maneira:
modelBuilder.Entity<Pessoa>()
            .HasRequired(p => p.Empresa)
            .WithMany(e => e.Pessoas)
            .HasForeignKey(p => p.EmpresaId);

O que acontece é o seguinte: A pessoa Entity<Pessoa> tem um campo obrigatório (requerido) HasRequired(p => p.Empresa) que faz parte de uma lista da empresa WithMany(e => e.Pessoas);
Ou seja, essa pessoa necessita ter uma empresa e essa pessoa estará vinculada as pessoas que existem naquela empresa (ICollection).
Comment: Essa propriedade `ICollection Pessoas` é uma `NavigationProperty` para que o `Context` saiba qual é o relacionamento entre as classes
Comment: O `Include` serve para quando você tentar acessar suas propriedades dê Pessoa, não precisar buscar novamente no banco, mas o exemplo ICollection foi só pra mostrar a existência da navigation property... Mas caso você queira manter assim e só carregar PessoaFisica vc pode usar ctx.Empresa.Pessoas.OfType.Load()
Comment: +1 pela resposta útil e relevante ;)
Comment: Sim, a estrutura das classes seriam essas. Creio então que minha falta de conhecimento foi na parte em que, já que uma Pessoa tem uma ligação a uma Empresa, na empresa eu TENHO QUE TER uma coleção de Pessoas que pertencem a ela. Seria esse o correto para o mapeamento para o EntityFramework? Esclarecendo melhor, eu não fiz essa `ICollection Pessoas`.
Comment: @tchicotti, muito obrigado!
Comment: Só que, podem existir cenários onde eu faça algo como: `ctx.Empresas.Include(x=>x.Pessoas);` **?** Acho muito inviável isso, não é?
Comment: @Tiago ja vou ver sim, só um instante que estou tendo que modelar umas tabelas de migração aqui no serviço e já vejo... :)


client side validation

Question: I am trying to enable client side validation on my web forms. I installed & enabled the modules as per the Drupal.org link:
https://www.drupal.org/node/1324924
& then went into the Configuration > Client Side Validation & inserted the form ids I had in my HTML code.
However, I am unable to get the client side validation to work (errors are not recognised in the input fields), the attached screenshot shows the modules view.
The only module that seems to be missing is the 'IFE' module which I cannot find / install.
Comment: You may do this through custom code...
Comment: Notice that you are simply stating facts without asking any explicit question. Stack Exchange doesn't work fine with implicit questions. In the case you were asking where to find the IFE module, that would be off-topic for us.
Answer: You need to download, install and enable the IFE  (aka. "Inline Form Errors") module.
Like all Drupal modules, its project page is immediately below https://www.drupal.org/project/.
Here is a link to the project page where you can download it:  IFE project page.
Answer: You Can use Field Validation module in case of content type. If you are using webform module then use Webform validation

client side validation


Display date and time in header

Question: I would like to display current date and time to the header section.
I am using a subtheme of Bartik. Any suggestions?
Answer: You can also add code page.html.twig as well.
For print only date use {{ "now"|date("m/d/Y") }}
More Details
http://twig.sensiolabs.org/doc/2.x/filters/date.html
https://stackoverflow.com/questions/17364206/symfony2-how-can-i-set-twig-dated-f-y-filter-to-output-months-in-swedish
Comment: Does this take into account site/user TZ settings, localization, and handle cache contexts properly?
Answer: I can't comment directly on Smalution's answer, but can confirm that
{{ "now"|date("m/d/Y") }}
in twig DOES respect drupal user timezones. (Tested it in america/new york - 2:50, switched to america/edmonton - 12:50) as per  mpdonadio's question.
Comment: This should not be an answer, it should be a comment on the DRUPWAY´s answer.
Answer: For this you can create custom block and insert the PHP date function in it. (Install PHP module for insert php code in block or drupal site).
Place this block on the header or where you want to place.
Comment: Also not advised to inject PHP code as body content.
Comment: Does this take into account site/user TZ settings, localization, and handle cache contexts properly?

Display date and time in header


Como deixar uma transação JPA com Spring aberta?

Question: Gostaria de saber como deixar uma transação JPA com spring aberta, hoje eu utilizo a anotação @Transaction o que ocorre é que toda vez que eu quero carregar algum atributo que não está como EAGER gera NullPointerException, a solução que eu tinha antigamente era deixar a transação aberta, assim onde eu precisa-se do objeto que ainda estava NULL, quando eu dava um get nesse objeto ele buscava para mim sem problemas.
Caso não saibam como trabalhar com transações abertas, alguém tem uma solução para mim de como usar LAZY load com Spring MVC e deixar que ele gerencie minhas transações quando eu precisar delas?

Meu método no DAO:

    @Transactional(readOnly = true)
        public Locador buscarElemento(int id) throws IdentificadorNaoExisteNaBaseDeDadosException {
            try {
                Locador locador = manager.find(Locador.class, id);
   /*
   *  Retirando os comentarios abaixo funciona, mas não é uma boa pratica,
   *  por que vai ter o mesmo comportamente do EAGER.
   */

    //          locador.getContatos().forEach(contato -> contato.getEmail());
    //          locador.getDocumentos().getCpf();
    //          locador.getEnderecos().forEach(endereco -> endereco.getBairro());*
                return locador;
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                throw new IdentificadorNaoExisteNaBaseDeDadosException(e);
            }
        }

A exception gerada quando tento recuperar todos os atributos do objeto :

Hibernate: select locador0_.id as id1_3_0_, locador0_.codigo as codigo2_3_0_, locador0_.dataNascimento as dataNasc3_3_0_, locador0_.documentos_id as document6_3_0_, locador0_.nome as nome4_3_0_, locador0_.observacao as observac5_3_0_ from Locador locador0_ where locador0_.id=?
    abr 30, 2019 6:38:32 PM org.apache.catalina.core.StandardWrapperValve invoke
    GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/SistemaGestaoImobiliario] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session] with root cause
    org.hibernate.LazyInitializationException: could not initialize proxy - no Session
        at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
        at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
        at org.hibernate.Hibernate.getClass(Hibernate.java:111)
        at adapters.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:49)
        at adapters.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:19)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
        at com.google.gson.Gson.toJson(Gson.java:704)
        at com.google.gson.Gson.toJson(Gson.java:683)
        at com.google.gson.Gson.toJson(Gson.java:638)
        at com.google.gson.Gson.toJson(Gson.java:618)
        at services.GoogleJSONService.gerarJSON(GoogleJSONService.java:14)
        at control.LocadorController.carregarLocador(LocadorController.java:87)
        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:221)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
        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.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
        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.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        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:200)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)

Comment: Um título todo em maiúsculo é um pecado estilístico. Parece que está tentando chamar a atenção no grito, e não no conteúdo
Comment: Coloque aqui o seu código e também a stack do erro. Procure formular bem a sua pergunta, inserindo os códigos e facilitando a vida de quem está aqui disposto a te ajudar.
Comment: Aproveitando, o que é `EAGUE`?
Comment: @FilipeL.Constante ja editei o post, ve se consegue me ajudar por favor ! ate mais !
Answer: Achei a solução para o meu problema, faltava uma propriedade a ser configurada.

Meu arquivo de configuração do JPA

package config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = {"exceptions", "dao"})
public class JPAConfiguration {

    @Bean
    public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() {

        LocalContainerEntityManagerFactoryBean manager = new LocalContainerEntityManagerFactoryBean();

        // mapeia o provedor
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        // configura o data source, configurações sobre o banco de dados
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/imobiliaria?useTimezone=true&serverTimezone=UTC");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");

        // propriedades do jpa
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        props.setProperty("hibernate.show_sql", "true");
//      props.setProperty("hibernate.format_sql", "true");
        props.setProperty("hibernate.hbm2ddl.auto", "update");
        props.setProperty("hibernate.enable_lazy_load_no_trans", "true");

        manager.setPackagesToScan("model");
        manager.setDataSource(dataSource);
        manager.setJpaProperties(props);
        manager.setJpaVendorAdapter(vendorAdapter);

        return manager;

    }

    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager manager = new JpaTransactionManager(emf);
        return manager;
    }

}

No meu JPAConfig eu estava esquecendo da propriedade :

props.setProperty("hibernate.enable_lazy_load_no_trans", "true");

Assim o Hibernate abre a conexão automaticamente sempre que ele precisar buscar um objeto Lazy Load.
Até mais !!


application crashing due to null pointer exception

Question: I have created the instance of other class in send class and called the function of other class from the send class but it gives NPE . My send class from where I called the function of other class ,which is broadcast class and also this function is called when the button is clicked.
  broadcast broadcastobject.threadfunc(messages);

My class where I create threads is:
  public class broadcast  {

private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";

public void threadfunc(String message){
    str=message;
                new Thread(new ClientThread()).start();
}

/*
 private InetAddress getBroadcastAddress() throws IOException {
        DhcpInfo dhcp = mWifi.getDhcpInfo();
        if (dhcp == null) {
          //Log.d(TAG, "Could not get dhcp info");
          return null;
        }

        int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
        byte[] quads = new byte[4];
        for (int k = 0; k < 4; k++)
          quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
        return InetAddress.getByAddress(quads);
      }

      */

class ClientThread implements Runnable {

    @Override
    public void run() {

        try {
            socket = new DatagramSocket(SERVERPORT);

            socket.setBroadcast(true);
    //              socket.setSoTimeout(TIMEOUT_MS);
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            InetAddress serverAddr = null;
            try {

                serverAddr = InetAddress.getByName(SERVER_IP);

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

           packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);

            try {

                    socket.send(packet);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }

    }

}

My send.java is:
public class Send extends android.app.ListFragment  {

WifiManager mwifi;
Button bt1;
boolean testwifi;
TextView tv1;
EditText et1;
String str1;
int id=1;
String messages;
private DataSource datasource;
broadcast broadcastobject;

void wifi() {
    mwifi=(WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

    if(!mwifi.isWifiEnabled())
    {
        if(mwifi.getWifiState()!=WifiManager.WIFI_STATE_ENABLED)
            mwifi.setWifiEnabled(true);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View rootView = inflater.inflate(R.layout.send, container, false);
    datasource = new DataSource(getActivity());
    datasource.open();

    List<Message> values = datasource.getAllMessages();

    // Use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(getActivity(), android.R.layout.simple_list_item_1, values);
   setListAdapter(adapter);

    bt1=(Button)rootView.findViewById(R.id.button1);
    tv1=(TextView)rootView.findViewById(R.id.textView1);
    et1=(EditText)rootView.findViewById(R.id.editText1);

    bt1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             @SuppressWarnings("unchecked")
            ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
                Message message = null;

            /*  ConnectivityManager cn= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = cn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    testwifi=networkInfo.isConnected();
    if(!testwifi)
        tv1.setText("wifi is off");
    else
        tv1.setText("wifi is on");*/

                wifi();

                // Save the Data in Database
                messages=et1.getText().toString();

                // check if any of the fields are vaccant
                if(messages.equals(""))
                {
                                           Toast.makeText(getActivity().getApplicationContext(), "Field Vaccant",    Toast.LENGTH_LONG).show();
                        return;
                }
                else
                {

                     message = datasource.createMessage(messages);
                      adapter.add(message);

                // broadcastobject=new broadcast(messages);
                //broadcastobject.start();

                      broadcastobject.threadfunc(messages);

                      et1.setText("");
                }

                  adapter.notifyDataSetChanged();
        }

    });

    return rootView;

}
/*public class MyLocationListener implements LocationListener
{

public void onLocationChanged(Location loc)

{

loc.getLatitude();

loc.getLongitude();
String Text = "My location is: " +

"Latitude = " + loc.getLatitude() +

"Longitude = " + loc.getLongitude();

//finish();

Toast.makeText( getActivity().getApplicationContext(),Text,Toast.LENGTH_SHORT).show();

}

public void onProviderDisabled(String provider)

{

Toast.makeText(getActivity(). getApplicationContext(),"GPS Disabled",Toast.LENGTH_SHORT ).show();

}

public void onProviderEnabled(String provider)

{

Toast.makeText( getActivity().getApplicationContext(),"GPS Enabled",Toast.LENGTH_SHORT).show();

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}

     }*/
@Override
public void onResume() {
    datasource.open();
    super.onResume();
  }

  @Override
public void onPause() {
    datasource.close();
    super.onPause();
  }

    }

My log cat is:
09-01 17:35:50.350: D/gralloc_goldfish(3557): Emulator without GPU emulation detected.
 09-01 17:36:10.300: D/AndroidRuntime(3557): Shutting down VM
09-01 17:36:10.309: W/dalvikvm(3557): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
 09-01 17:36:10.369: E/AndroidRuntime(3557): FATAL EXCEPTION: main
 09-01 17:36:10.369: E/AndroidRuntime(3557): java.lang.NullPointerException
  09-01 17:36:10.369: E/AndroidRuntime(3557):   at soft.b.peopleassist.Send$1.onClick(Send.java:114)
  09-01 17:36:10.369: E/AndroidRuntime(3557):   at android.view.View.performClick(View.java:3480)
  09-01 17:36:10.369: E/AndroidRuntime(3557):   at android.view.View$PerformClick.run(View.java:13983)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at android.os.Handler.handleCallback(Handler.java:605)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at android.os.Handler.dispatchMessage(Handler.java:92)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at android.os.Looper.loop(Looper.java:137)
09-01 17:36:10.369: E/AndroidRuntime(3557):     at android.app.ActivityThread.main(ActivityThread.java:4340)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at java.lang.reflect.Method.invokeNative(Native Method)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at java.lang.reflect.Method.invoke(Method.java:511)
09-01 17:36:10.369: E/AndroidRuntime(3557):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-01 17:36:10.369: E/AndroidRuntime(3557):     at dalvik.system.NativeStart.main(Native Method)
   09-01 17:36:13.150: I/Process(3557): Sending signal. PID: 3557 SIG: 9

Comment: Where is `Send.java`? The exception is thrown in that class.
Comment: check my edited question i've added send class in the question it is the class from where i am calling the function .
Comment: Where is the line 114 in send.java point that out too in the code block using comment.
Comment: broadcastobject.threadfunc(messages);
Comment: @AmeerHumXa Instead of `if(messages.equals(""))` have a check there that `if((messages==null) || (messages.equals("")))` . Chekc for the null condition as well.
Comment: still not working ,same error, @ShobhitPuri
Comment: That's because you haven't created any object of class `broadcast` and are calling the function directly. First you need to create an object. Since the function is not static you cannot use it without using an object of that class.  Before using it something you need to create object lilke : `broadcast broadcastobject = new broadcast();`
Comment: @ShobhitPuri broadcastobject is the object of broadcast class and i have defined it globally.
Comment: Do you feel that there is there a difference between defining and creating an object ? Can you please refer to me where in the code are you creating an object ?
Comment: @ShobhitPuri thanks you were absolutely right ,its now working ok for one or two time.but after that I press the button and the instance is created again and function is called ,its again crashing.
Comment: This might be because each time you'll click a new object will be created. You can declare the function inside `broadcast` class as `static` and access it as `broadcastobject .functionName(...)`.
Comment: @ShobhitPuri shall i create the instance every time the event is called or for once in the code?
Comment: @AmeerHumXa Once I guess.
Comment: @ShobhitPuri i have created the instance in onCreate for once instead of making the function static and now its working absolutely fine, Put it in answer so i can mark it as answer, thanks alot man,
Comment: Glad to help Ameer :)
Answer: You are receiving null pointer because you haven't created any object of class broadcast and are trying to call the function present in that class. Since the function is not static you cannot use it without using an object of that class. So, first you need to create an object before calling the function like:
broadcast broadcastobject = new broadcast();

Comment: i've one more little problem in broadcasting the packet in broadcast class, would you help me?
Comment: Sure. If I know I'll love to help. Although for a different problem, its good to post a different question. Other can have a look as well. Do post the link here once you post the new question.
Comment: http://stackoverflow.com/questions/18556332/message-only-received-once-on-the-server-on-android-app
Comment: check if you can help :)
Comment: @AmeerHumXa Sorry, I read it but couldn't contribute. since I don't have much experience with that.


stop an apt-get upgrade

Question: I was trying to upgrade just a single package, so I typed sudo apt-get upgrade packagename.  (Now I know I'm supposed to use apt-get install for that.)  Now apt-get is upgrading everything in my whole system.  I stopped it with shutdown -h now (hey, it worked) as C-c doesn't seem to work very well.
However apt-get has a memory and now I can't do anything with apt-get such as install without it attempting to continue with a full system upgrade.  How do I get apt-get to just abort the upgrade?

When I follow the instructions in the accepted answer as suggested by Itai Ganot, this is what happens:
<code>$ sudo apt-get autoclean
[sudo] password for dsw:
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
dsw@dsw-VirtualBox:~$ cd /var/cache/apt/archives/partial
dsw@dsw-VirtualBox:/var/cache/apt/archives/partial$ ls
dsw@dsw-VirtualBox:/var/cache/apt/archives/partial$ ls -a
.  ..
</code>
Following the instructions in the message:
<code>sudo dpkg --configure -a
</code>
eventually stops.  So the above method does seem to stop the apt-get update eventually.
Answer: There are two things you can do in order to cancel the upgrade:

Try running the following command:
<code># sudo apt-get autoclean
</code>
Emptying /var/cache/apt/archives/partial
To do that, open a file manager using the gksudo command, such as:
<code># gksudo nautilus /var/cache/apt/archives/partial
</code>

Delete the files within "partial" but not the folder itself.
Comment: Cannot do autoclean.     E: Could not get lock /var/cache/apt/archives/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the download directory
Comment: this method did seem to work after apt-get did a few more things; there is no room to give the details in this little box, so I made them another answer; thanks
Comment: Cannot install gksudo.  E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
Comment: Use sudo before the command.

stop an apt-get upgrade


What makes a piece a nocturne?

Question: I am wanting to compose a second nocturne. I composed my first one about a year ago and pretty much all the feedback I got was that it should have been written in 3/4 instead of 4/4. I wonder if that is because the bass in my previous nocturne was all triplets until the last few bars. I know one thing that is critical to call a piece a nocturne is that it is evocative of the night. I only know of Chopin's nocturnes. And I know that Chopin uses a simple bass line, quite often uses triplets, and focuses on the melody in most of his works, not just his nocturnes.
So whenever I write a nocturne or think of writing one, Chopin is the composer who comes to mind. I often listen to Chopin's nocturnes before I write one of my own. His nocturnes were my first Chopin pieces to be in my repertoire. But is there anything besides being evocative of the night that I need in order to call my piece a nocturne? I mean, it sounds very freeform, like it could be in any form, even sonata form, and still be considered a nocturne(though a nocturne in sonata form, I think would be very hard to achieve). But is it very freeform like that or are there other things critical besides the feel of the piece for it to be considered a nocturne?
Comment: A nocturne in sonata form is deceptively easy to achieve. Just take any slow movement that's in sonata form...or take a slow movement that's in sonatina form and stick a small development section in the middle.
Comment: related - https://music.stackexchange.com/questions/77388/why-is-debussys-clair-de-lune-not-considered-a-nocturne/77410#77410
Answer: Here is a definition from the this link: nocturne. As you can see you have great freedom to compose it your way:
noun Music.
1 a piece appropriate to the night or evening.
2 an instrumental composition of a dreamy or pensive character.

Here follows another definition from the same link:
noun
1 a short, lyrical piece of music, esp one for the piano
2 a painting or tone poem of a night scene

What makes a piece a nocturne?


What is the best way to track teleport position in Aframe?

Question: I am using the aframe-teleport-controls and I was wondering what is the best way to track the position of the user.
I've been searching and I found two ways to do that.
1 - I use the position of the teleport controller which is almost the position of the user.
var teleportControls = el.closest('a-scene').querySelector('[teleport-controls]');
var worldPos = new THREE.Vector3();
worldPos.setFromMatrixPosition(teleportControls.object3D.matrixWorld);
console.log(worldPos);

2 - I define an a-camera element in my scene and I use his position.
var teleportControls = el.closest('a-scene').querySelector('a-camera');
var worldPos = new THREE.Vector3();
worldPos.setFromMatrixPosition(teleportControls.object3D.matrixWorld);
console.log(worldPos);

I'm not sure it is the good practice, and how can I listen that the user change his position?
Thanks for reading this.
Answer: The controller element (not the camera) will emit a teleport event when the user teleports (found in source here). The easiest way to detect those events would be to listen on the scene element, as the events bubble up.
sceneEl.addEventListener('teleport', function (e) {
  console.log(e.detail.oldPosition, e.detail.newPosition);
});


Solving a System of non-linear recurrence relations

Question: While evaluating some integrals I came across this system. I know that most of the times systems of non-linear recurrence relations are unsolvable, but looking at the outputs I got for different m it seems to me like a solution exists, just I'm not able to find it.
Here is the problem:
$$ A_m=mA_{m-1}+B_{m-1}$$
$$ B_m=mB_{m-1}-A_{m-1} $$
Comment: You could convert it into a single recurrence to see if that helps you, e.g. $B_{m+1}=(2m+1)B_{m}-(m^2+1)B_{m-1}$. In any way I would try generating functions.
Comment: $A_m=B_m=0$ for all $m$ looks like a solution.
Comment: Thank you I didnt notice, but I forgot to mention that in my problem I have Initial conditions $A_1=1, B_1=-1$
Comment: Thank you. With generating functions I get stuck with a non-homogeneous system of differential equations.
Comment: I see, well one can always try to evaluate first couple terms of the sequence and find on oeis.org, in this case we find [A009454](https://oeis.org/A009454) and [A003703](https://oeis.org/A003703) which match with some simple sign adjustments, both sequences have exponential generating functions $\cos\ln(1+x)$ and $\sin\ln(1+x)$, some formulas are included as well (without proof though)
Answer: Hint.
This recurrence is linear and can be written as
$$
\left(\matrix{A_m\\ B_m}\right) = \left(\matrix{m & 1 \\ -1 & m}\right)\left(\matrix{A_{m-1}\\ B_{m-1}}\right)
$$
now $\left(\matrix{m & 1 \\ -1 & m}\right) = T\cdot \Lambda_m\cdot T^{-1}$ with
$$
T = \left(
\begin{array}{cc}
 i & -i \\
 1 & 1 \\
\end{array}
\right)\ \ \ \text{}\ \ \ \Lambda_m = \left(
\begin{array}{cc}
 m-i & 0 \\
 0 & m+i \\
\end{array}
\right)
$$
so calling now $X_m = T^{-1}\cdot \left(\matrix{A_m\\ B_m}\right)$ we have the recast recurrence
$$
X_m = \Lambda_m\cdot X_{m-1}
$$
with solution
$$
X_m = \left(\prod_{k=1}^m\Lambda_k\right)\cdot X_1
$$
etc.
NOTE
$$
\prod_{k=1}^m\Lambda_k = \left(\matrix{(m-i)!& 0\\ 0&(m+i)!}\right)
$$
This result is not amenable to work with. Using generating functions we follow with
$$
\cases{
A_m x^m = m A_{m-1}x^m + B_{m-1}x^m\\
B_m x^m = -A_{m-1}x^m + m B_{m-1}x^m
}
$$
or
$$
\cases{
A(x) = x(x A(x))'+x B(x) + \phi_A(x)\\
B(x) = -x A(x) + x(x B(x))'+\phi_B(x)
}
$$
them we have
$$
\cases{
B'(x) = \frac{1-x}{x^2}-\frac 1x B(x) + \frac{1}{x^2}\phi_A(x)\\
A'(x) = \frac 1x A(x) + \frac{1-x}{x^2}B(x) + \frac{1}{x^2}\phi_B(x)
}
$$
Here $\phi_A(x), \phi_B(x)$ are initial condition polynomials. Assuming $\phi_A(x) = \phi_B(x) = 0$ we have the solution
$$
\cases{
A(x) = \frac{c_1 e^{-1/x} \cos (\log (x))}{x}-\frac{c_2 e^{-1/x} \sin (\log (x))}{x}\\
B(x) = \frac{c_1 e^{-1/x} \sin (\log (x))}{x}+\frac{c_2 e^{-1/x} \cos (\log(x))}{x}
}
$$
not expandable in series around $x=0$.
Comment: Note that $\Lambda_m$ is diagonal. This makes the answer quite easy to handle.
Comment: Yes. I mean that.
Comment: Yes I got a similar solution, but left it since I wasn't able to find a closed form for the product of the matrices. Do you think such a closed form exists or this is the best we can get?
Comment: I also have a tray with MATHEMATICA  and gave an answer quite similar.
Comment: Ah ok this is where my method failed,  thank you
Comment: Fixed a notation error.
Comment: when you say $\\(m-i)!$ you mean $\prod_{k=1}^{m} (k-i) $ ?
Comment: I would try the use of generating functions. I will include a note indicating this way.
Comment: Great solution. I tried the approach of generating functions but got stuck at the system of differential equations. How did you manage to solve it?


No matter what I try to do, I cannot get anaconda navigator to run on windows 10

Question: When I try to open anaconda navigator my cmd prompt flashes open with some text and immedietly terminates.
Please help me figure this out... Thanks.
I've tried fresh installs and different directories.
I've tried opening through the shortcut, command prompt, and through the script file.
I've tried all the command prompt commands that I've found on SOF and through github and many help forums. I really cannot figure this out and it's making me want to smash my head through dry wall.
<code>(base) C:\Users\itsat>anaconda-navigator
Traceback (most recent call last):
  File "C:\Users\itsat\anaconda3\Scripts\anaconda-navigator-script.py", line 6, in <module>
    from anaconda_navigator.app.main import main
  File "C:\Users\itsat\anaconda3\lib\site-packages\anaconda_navigator\app\main.py", line 19, in <module>
    from anaconda_navigator.app.start import start_app
  File "C:\Users\itsat\anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 27, in <module>
    from anaconda_navigator.widgets.main_window import MainWindow
  File "C:\Users\itsat\anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window\__init__.py", line 25, in <module>
    from anaconda_navigator.api.anaconda_api import AnacondaAPI
  File "C:\Users\itsat\anaconda3\lib\site-packages\anaconda_navigator\api\anaconda_api.py", line 30, in <module>
    from anaconda_navigator.api.client_api import ClientAPI
  File "C:\Users\itsat\anaconda3\lib\site-packages\anaconda_navigator\api\client_api.py", line 23, in <module>
    import binstar_client
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\__init__.py", line 21, in <module>
    from .mixins.channels import ChannelsMixin
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\mixins\channels.py", line 7, in <module>
    from binstar_client.utils import jencode
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\utils\__init__.py", line 14, in <module>
    from .config import (get_server_api, dirs, load_token, store_token,
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\utils\config.py", line 90, in <module>
    USER_LOGDIR = dirs.user_log_dir
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\utils\appdirs.py", line 253, in user_log_dir
    return user_log_dir(self.appname, self.appauthor, version=self.version)
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\utils\appdirs.py", line 192, in user_log_dir
    path = user_data_dir(appname, appauthor, version)
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\utils\appdirs.py", line 68, in user_data_dir
    path = os.path.join(_get_win_folder(const), appauthor, appname)
  File "C:\Users\itsat\anaconda3\lib\site-packages\binstar_client\utils\appdirs.py", line 280, in _get_win_folder_with_pywin32
    from win32com.shell import shellcon, shell
ImportError: DLL load failed while importing shell: The specified procedure could not be found.

(base) C:\Users\itsat>

</code>
Comment: pip install pywin32==300 worked
Answer: pip install pywin32==300 fixed the issues.


Job configurations are missing when copied from folders in Jenkins

Question: This is reproducible 100%.
We are working on different branches of the release, but each branch should run the same jobs, with some minor change.  So ideally I want to copy all the jobs from one working branch to a new branch.
I select a New item -> folder and select copy from another folder.
The new folder contains the all the jobs from source folder, but all the job configurations are missing. In another word, I have jobs created just with job names, I need to refill everything else.  This is essentially useless.
I googled and did not see any related errors. Anyone have any good advice on copy jenkins folders ?  I am jenkins 1.651.3, ubuntu 14.04
Comment: A simple, brute, but effective way to clone jenkins jobs is copying corresponding config.xml file between jobs subfolders on file system level (at /var/lib/jenkins ...). Better to shutdown Jenkins service doing this
Comment: hi thanks for your input. However I did exactly that and jenkins still doesn't show the proper configuration.  I can see the config.xml files are updated on the disk.  I also reload from disk/ and even shut down jenkins.  The jobs are still missing the right config.
Answer: I tried the same on jenkins 2.19.1 and worked with out the issue your are seeing.
The best way to create similar array of jobs for new branches is via groovy & using https://jenkinsci.github.io/job-dsl-plugin/
create a job where you execute a groovy script to iterate over a list of branches and creates jobs .
DSL plugin is available for jenkins 1.642 and above
Note that manipulating content in JENKINS_HOME is not advised and is typically restricted
Comment: Hi Thanks for your feedback. It turns out that it depends on how many jobs in the folder. If there are too many jobs jenkins cannot handle the copying and doesn't update the jobs properly.  My colleague copied a folder with 13 jobs and it worked with our Jenkins.  Mine folder contains over 30+ jobs and all jobs are empty.  So at this point I will not risk to upgrade Jenkins but will try DSL plugin you mentioned. Will report back if a few days.
Answer: I should also mentioned it turns out just our computer issue. Lack of ram. After we added more ram, it' all working perfectly!


Reading data from file handle leaks memory on Linux

Question: I am experiencing a memory leak when reading data from files. This code creates the leak:
func read() throws {
    let url = URL(fileURLWithPath: "content.pdf")
    let fileHandle = try FileHandle(forReadingFrom: url)
    while true {
        let chunk = fileHandle.readData(ofLength: 256)
        guard !chunk.isEmpty else {
            break
        }
    }
    print("read")
}

do {
   for _ in 0 ..< 10000 {
        try read()
    }
}
catch {
    print("Error: \(error)")
}

*FYI: to run this code you will have to have a "content.pdf" file in your working directory.
If I run this on linux with Swift 3.1.1 (or 3.1), it does a number of iterations of the loop consuming more and more memory until the process is killed.
On Mac this also happens because the data is put into the Autorelease pool and I can fix the memory issue by wrapping each iteration in an autorelease pool but that does not exist on Linux so I don't know how I can free up that memory. Does anyone have an idea?
Comment: Please take a look at the swift user mail list: Hopefully this can help.
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161031/003823.html
Comment: @LuisRamirez yes thank you, I had found that already before posting. The auto release pool is not used with the Linux implementation of FileHandle/Data. I ended up digging into the corelibs code and found the ultimate bug and came up with a workaround (answered below).
Answer: I found the problem which is within the standard library. There is actually already a bug report open for it. Basically the problem is that the readData(ofLength:) method is returning a Data object that is not cleaning up after itself when deallocated.
For now, I am using this workaround:
extension FileHandle {
    public func safelyReadData(ofLength length: Int) -> Data {
        #if os(Linux)
            var leakingData = self.readData(ofLength: length)
            var data: Data = Data()
            if leakingData.count > 0 {
                leakingData.withUnsafeMutableBytes({ (bytes: UnsafeMutablePointer<UInt8>) -> Void in
                    data = Data(bytesNoCopy: bytes, count: leakingData.count, deallocator: .free)
                })
            }
            return data
        #else
            return self.readData(ofLength: length)
        #endif
    }
}

Anywhere I was previously using readData(ofLength:) I am now using my safelyReadData(ofLength:) method. On all platforms other than Linux it simply calls the original because those implementations are fine. On Linux I am creating a copy of the data that will actually free the underlying data when deallocated.
Answer: Instead of how to work around the missing autorelease pool, a better question is how to prevent the leak. Maybe creating (and not deallocating) 10,000 FileHandles are the problem. Try this.
func read() throws {
    let url = URL(fileURLWithPath: "content.pdf")
    let fileHandle = try FileHandle(forReadingFrom: url)
    while true {
        let chunk = fileHandle.readData(ofLength: 256)
        guard !chunk.isEmpty else {
            break
        }
    }
    fileHandle.closeFile()
    print("read")
}

This may not be the problem, but it is still good code hygiene. How many loops are made before the crash?
Comment: File handles close themselves when deallocated. They are deallocated as the function exits which is within each iteration of the loop. Just in case, I added it and either way it crashes for me after 386 iterations (i'm sure this is dependent on my environment though).


Derived from template class?

Question: I'm trying to use the following code, but can't get it to complete.
Can anyone see the problem?
class IResourceJob
{
public:
   virtual ~IResourceJob() {}

   virtual void execute() = 0;
};

template<typename T>
class ResourceJob : public IResourceJob
{
public:
   void execute()
   {
      static_assert(false, "Specialised ResourceJob<T> not defined!");
   }
};

template<>
class ResourceJob<int>
{
public:
   void execute()
   {
       // test.
   }
};

The following usage gives a compile error:
IResourceJob* job = new ResourceJob<int>;

Thanks!
Comment: you explicit specialization `ResourceJob` doesn't inherits from `IResourceJob` , also that static cast is wrong, did you mean `static_assert` ?
Comment: Thanks, sorry - the static_cast was a typo.
Answer: The compiler gives an error for any template that can never be instantiated. For your member function of the class template (i assume you mean static_assert), that is true, so the compiler is in right to give you a diagnostic.
You want to make the condition depend on T and cleverly make it always evaluate to false when instantiated. For example like
template<typename T>
struct always_false : std::false_type {};

template<typename T>
class ResourceJob : public IResourceJob
{
public:
   void execute()
   {
      static_assert(always_false<T>::value,
        "Specialised ResourceJob<T> not defined!");
   }
};

Since the compiler cannot know whether the user will put a specialization of always_false (which you won't, of course), it cannot early-reject the template anymore.
I also doubt that you wanted to put the static_assert into execute, since your error message indicates that ResourceJob as a whole needs to be specialized. So put the static_assert outside of the member function into the class body. If you don't want the user to specialize the whole template, but only the member function, the user instead needs to say
// either "inline" and in the header, or not "inline" and in the .cpp file, but then
// put this into the header: template<> void ResourceJob<int>::execute();
template<> inline void ResourceJob<int>::execute() {

}

This will provide an alternative definition of execute which will be used by the template if T is int.
Answer: IResourceJob* job = new ResourceJob<int>;

fails because the class ResourceJob<int> is not derived from from IResourceJob.
The code should be
template<>
class ResourceJob<int> : public IResourceJob
{
     public:
     void execute()
     {
         // test.
     }
 };

Answer: You need to derive the template specialization as well, as in:
template<>
class ResourceJob<int> : public IResourceJob
{ /* ... */ };

Derived from template class?


Getting all users from db that participated for an activity

Question: I am currently facing the following problem: Users are able to create activities. Other users have the possibility, to participate the activity. I now want that the users, which already participated to an activity are going to be listed in the view of the activity. So what I try is to show all the users that participated for an activity in the show method of the activity_controller with an activity_id.
The relations of the models are as follows:
 class Activity < ActiveRecord::Base
  has_many :users, through: :participations
  belongs_to :user
  has_many :participations
  has_many :reviews

end

 class Participation < ActiveRecord::Base
  belongs_to :user
  belongs_to :activity
  has_many :activities
end

 class User < ActiveRecord::Base
  has_many :activities
  has_many :participations
  has_many :reviews

end

My activity controller ist doing the following:
class ActivitiesController < ApplicationController
  before_action :set_activity, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show]

  def index
    @activities = Activity.all
  end

  def show
    @participated = Participation.where("activity_id = ? AND user_id = ?", @activity.id, current_user.id).present? if current_user
    @reviews = @activity.reviews
    @hasReview = @reviews.find_by(user_id: current_user.id) if current_user

    @participant = Participation.where (:activity_id == 'activity_id')
  end

  def new
    @activity = current_user.activities.build
  end

  def create
    @activity = current_user.activities.build(activity_params)

    if @activity.save

      redirect_to edit_activity_path(@activity), notice: "We want to give you a warm welcome!"

    else
      render :new, notice: "Something seems to be missing!"
    end
  end

  def edit
    if current_user.id == @activity.user.id
      redirect_to root_path
    end
  end

  def update
    if @activity.update(activity_params)
      redirect_to edit_activity_path(@activity), notice: "Updated!"
    else
      render :edit
    end
  end

  def destroy
    @activity = Activity.find(params[:id])

    if @activity.destroy
      redirect_to activities_path, notice: "Deleted!"
    end
  end

  private

  def set_activity
    @activity = Activity.find(params[:id])
  end

  def activity_params
    params.require(:activity).permit(:activity_name,
                                     :activity_starttime,
                                     :activity_duration,
                                     :activity_intensity,
                                     :activity_distance,
                                     :activity_topography,
                                     :activity_address,
                                     :activity_track,
                                     :activity_summary)

  end
end

Meanwhile the participations controller handles this:
    class ParticipationsController < ApplicationController
  before_action :authenticate_user!

  def preload
    activity= Activity.find(params[:activity_id])
    participations = activity.participations
    render json: participations
  end

  def create

    if Participation.exists?(user_id: current_user.id)

      redirect_to activities_path(@activity), notice: "Du nimmst bereits teil!"

    else

      @participation = current_user.participations.create(participation_params)
      redirect_to @participation.activity, notice: "Klasse, du nimmst nun teil!"

    end

  end

  def participant
    @participant = user.participations
  end

  def your_matches
    @matches = current_user.participations
  end

  def your_participations
    @activities = current_user.activities
  end

  private

  def participation_params
    params.permit(:activity_id, :status)
  end
end

In my view, I called the controller by using:

Wer kommt bis jetzt mit?

      <% @participant.each do |participant| %>

            <%= participant.user.fullname %>

      <% end %>

Which gives me a list of all users that participated for any activity. But the only thing I want now is to show all the users which participated for the activity requested. I would say that my relations should work properly, therefore I guess I just need a small hint to solve the problem. At another point of my app I already got a list, where I am able to show the users which participated, but because of the different controllers, I am not able to call this from the activity controller. All in all, this causes an error because I am not able to call the participations_controller from an activitities_view.

    <% @activities.each do |activity| %>
      <% activity.participations.each do |participation| %>

          <%= link_to user_path(participation.user) do %>
              <%= participation.user.fullname %>
          <% end %>

Would really appreciate any help and thanks in advance!
Edit 1: Some more information about what the DB include:
class CreateParticipations < ActiveRecord::Migration
  def change
    create_table :participations do |t|
      t.references :user, index: true, foreign_key: true
      t.references :activity, index: true, foreign_key: true

      t.string :status

      t.timestamps null: false
    end
  end
end

class CreateActivities < ActiveRecord::Migration
  def change
    create_table :activities do |t|

      t.string :activity_name
      t.datetime :activity_starttime
      t.time :activity_duration
      t.string :activity_intensity
      t.integer :activity_distance
      t.string :activity_topography
      t.string :activity_address
      t.string :activity_track
      t.string :activity_summary

      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

Comment: `participation_params` hasn't the `user_id`?, just `activitiy` and `status`, but your migration has it.
Comment: It has. Via references he is fetching the user_id and activity_id. So a participations consists of the user_id, the activity_id and the status (which has no function so far, need to remove it...)
Comment: Can you provide a repository?
Comment: I got it, I'll take a look.
Comment: I'm assuming your are using your show route for activities to display these participants of a particular activity and your route is restful? If so pass along the activity id in the params hash, and plug it in to your instance variable query.  Something like this `@participant = Participation.where (activity_id: params[:id])`.  Hope that helps.
Answer: I still don't understand when you add a has_many and belongs_to relantionship in your Participation model with reference to the Activity model.
If you'd have:

User          has_many participations
Activity      has_many
participations
Participation belongs_to user and belongs_to activity

Then you could join User with Participation in a query and try to get all the users that have participated to a particular activity like:
User.joins(:participations).where('participations.activity_id = 1')

Edit: I've tested your code, without touching nothing in the models, migrations, etc. I've inserted some example records like:
User.new(fullname: 'seb', ...).save
User.new(fullname: 'sab', ...).save
User.new(fullname: 'frank', ...).save

Activity.new(name: 'yoga', user_id: 1).save
Activity.new(name: 'pilates', user_id: 1).save
Activity.new(name: 'tennis', user_id: 2).save
Activity.new(name: 'etc etc etc', user_id: 3).save

Participation.new(user_id: 1, activity_id: 1).save
Participation.new(user_id: 2, activity_id: 1).save
Participation.new(user_id: 3, activity_id: 1).save

And I run the query, having 3 users that have participated in the activity with id 3:
User.joins(:participations).where('participations.activity_id = 1').pluck(:fullname)

And I get:
SELECT "users"."fullname" FROM "users" INNER JOIN "participations" ON "participations"."user_id" = "users"."id" WHERE (participations.activity_id = 1)
# => ["seb", "sab", "frank"]

Comment: The relations are made as they are because: Every User is able to create an activity, but can also join an activity via participations. So I would say that the relations should work the way I want, or do I miss a thing? If I add your code to my controller's show method and call it from the activities/show.html.erb I still get all participants that participated to any activity, and not only the specific users that participated.
Comment: So, I was omitting that part, I meant the Participation `belongs_to :activity`
and `has_many :activities` part. Did that query gave you some error?
Comment: What about adding the user_id? `User.joins(:participations).where('participations.activity_id = 1 AND participations.user_id = 1')` for instance.
Comment: If I change the relations I am getting an error. The only line I can remove is `has_many :users, through: :participations` , which causes no change at all. Adding the ID also leads to an error `SQLite3::SQLException: no such column: participations.activity_id: SELECT "users".* FROM "users" INNER JOIN "participations" ON "participations"."user_id" = "users"."id" WHERE (participations.activity_id = 1 AND participations.user_id = 1)`
Comment: I do not get why I am not able to make it like I posted right before my edit. In this case I first call the activities and afterwards the participations. In this case the participations_controller seems is also calling the information from the activities_controller and therefore, I do not understand why it is not working the opposite way...
Comment: So in that case, as you mentioned, you'd need to make two steps to get the result, through your relationships it should be easier.
Comment: Oh damn. I did not see your edit from yesterday...I just tried your last approach with pluck and this returns me the right sets of users which participated for the specific activity (in this case `activity` with `activity_id = 1`). Thank you so far, my approaches where not able to do this. I now have to only find a way to only get the data for the called activity from the database, so `activity_id = 1` needs to be dynamic in somehow.
Comment: Think I finally got it. Changing your approach to: `User.joins(:participations).where('participations.activity_id = ?', @activity.id).pluck(:fullname)` gives me the right set of users for the right activity. Hopefully this works! Thank you so much and thank you for taking some time! I think I need to rework this topic again for myself...


Como focar em uma DIV específica e desfocar o restante

Question: Existe alguma biblioteca Javascript/Jquery que de um targetdelimitando uma área em uma DIV específica e desfoque no restante ?
Exemplo
Adicionei um novo item ao menu e assim que carregasse a tela desse um foco em cima e desfocasse o restante para ficar em evidência ?
Obs: Acredito que terá que trabalhar com coordenadas pois queria ter a liberdade de colocar esse target em qualquer lugar da tela
Foto hipotética:
Comment: Só uma dúvida, quando vc fala "desfocar" vc quer que o resto do menu fique com um efeito de "embaçado" tipo desfocado mesmo, ou vc quer que o item quando clicado aparece essa borda vermelha?
Comment: @hugocsl exatamente isso, assim que carregar a tela, ele vai desfocar (embaçado) a pagina inteira e apenas deixar e evidência o novo item, com esse borda/target delimitando ele ai caso seja clicado em qualquer lugar essa estilização suma ...

isso é para 'mostrar' novas funcionalidades, pra ajudar operadores que são 'visuais'
Comment: `border: 10px solid red`?
Answer: Fiz esse modelo só com CSS, usando um pouco de JS vc consegue fazer do jeito que quer, basta adaptar pra sua situação ai.
O ideia e colocar no elemento que engloba todo o conteúdo um filter:blur(), e quando vc clicar no btn vc remove o filter do container que tem o restante do conteúdo.
Esse é apenas um exemplo, eu usei label + input para fazer a dinâmica da coisa ok

#btn {
  display: none;
}
#btn:checked + .holder .fake {
  display: none;
}
#btn:checked ~ .blur {
  filter: blur(0);
}
.holder {
  position: relative;
  z-index: 2;
}
.btn {
  width: 60px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #000;
  color: #fff;
  position: absolute;
  cursor: pointer;
}
.blur {
  filter: blur(6px);
}
<input type="checkbox" id="btn">

  btn
  btn

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Praesentium maiores vero asperiores quisquam assumenda laudantium quidem esse dolores. Voluptatem velit et officia iste. Autem corrupti, asperiores in maxime alias explicabo.

Possimus quo alias veniam! Obcaecati ea ipsam unde, sit dolorum architecto, deserunt in aperiam recusandae neque qui officia minus provident. Similique adipisci recusandae facere reiciendis cupiditate repellat, dolores nisi maxime?

Porro, harum repudiandae dolores praesentium ducimus pariatur voluptate, nihil doloremque ratione obcaecati inventore laboriosam veritatis. Minima dolore molestiae tempore repellendus consequatur quisquam voluptates, incidunt repellat accusantium eaque? Magni, totam! Animi.

Sunt delectus odit facere impedit officiis, ea rerum nobis nesciunt iure atque quisquam, maiores, tempore earum suscipit eaque nihil nostrum. Nihil quaerat laborum adipisci autem veritatis vero recusandae reiciendis voluptatem!

Sequi enim commodi culpa impedit quos nostrum repudiandae consequatur ullam. Quaerat necessitatibus repellat odio, velit eos beatae iste eaque sed quas, consequuntur doloremque iure voluptate totam asperiores culpa. Perferendis, odio.

Aspernatur eius rerum harum necessitatibus natus repellendus sit optio perspiciatis voluptatum, consectetur corporis magnam adipisci debitis, voluptatem ea aliquam quaerat explicabo. Sit atque quas tempore assumenda tempora nam culpa non?

Sed, dolor architecto. Error voluptate exercitationem beatae accusamus id voluptatum modi architecto nemo harum eveniet ex totam, blanditiis dolorum deleniti, est necessitatibus? Consequatur blanditiis nulla quod pariatur sed adipisci nisi?

Itaque laudantium alias, vel placeat cupiditate omnis, possimus aut, corrupti at suscipit nostrum veritatis fuga consequuntur aliquid reiciendis laboriosam! Beatae, et ratione atque neque assumenda sunt ut laborum laboriosam ad!

Amet autem omnis atque provident facere praesentium sint, consequuntur illum adipisci libero assumenda vero natus quis reiciendis hic alias iure nemo, quaerat, sequi ex! Consequuntur voluptates excepturi tempore esse repellendus.

Sapiente consequuntur recusandae soluta debitis sequi totam ratione obcaecati veritatis laborum deserunt, incidunt quae quia nostrum harum illum quaerat ipsum a deleniti vel voluptatibus vitae! Commodi rerum reiciendis quas magni?

Answer: Você pode trabalhar com a propriedade position e z-index do CSS... Ao clicar no elemento desejado você adiciona uma div com 100% com o fundo desejado e define o position e o z-index acima desta div criada para sobrepor o restante do conteúdo.
Comment: Isso ajuda em 70% do problema. Mas a questão é que eu preciso trabalhar com coordenadas para ter a liberdade de jogar esse target em qualquer lugar da página, e não tem que ser no clique, iria ser ao carregar a página.
Comment: Você não pode jogar esse target através de um identificador?