text:
Q: Hibernate - Spring Security - Spring MVC Versions I'm trying to implement a web application with Spring Security, Spring MVC and Hibernate. After some research on internet I'm facing with some incompatibility between jars. Can anyone help me with the correct versions for jars?
I'm using:
spring-webmvc, spring-aop, spring-beans, spring-context, spring-core, spring-expression, spring-web, spring-orm, spring-tx, spring-jdbc: 4.3.11.RELEASE
spring-security-config, spring-security-web, spring-security-core: 4.2.3.RELEASE
hibernate-core: 4.3.8.Final and hibernate-jpa-2.1: 1.0.0.Final
This is the exception that I'm getting right now:
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [5]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'org.springframework.security.provisioning.JdbcUserDetailsManager#0' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.provisioning.JdbcUserDetailsManager#0': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/hibernate-configurations.xml]: Invalid destruction signature; nested exception is org.springframework.beans.factory.support.BeanDefinitionValidationException: Couldn't find a destroy method named 'close' on bean with name 'dataSource'

Oct 24, 2017 8:24:11 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [5]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'org.springframework.security.provisioning.JdbcUserDetailsManager#0' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.provisioning.JdbcUserDetailsManager#0': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/hibernate-configurations.xml]: Invalid destruction signature; nested exception is org.springframework.beans.factory.support.BeanDefinitionValidationException: Couldn't find a destroy method named 'close' on bean with name 'dataSource'
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:382)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1531)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4643)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5105)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:657)
    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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [5]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'org.springframework.security.provisioning.JdbcUserDetailsManager#0' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.provisioning.JdbcUserDetailsManager#0': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/hibernate-configurations.xml]: Invalid destruction signature; nested exception is org.springframework.beans.factory.support.BeanDefinitionValidationException: Couldn't find a destroy method named 'close' on bean with name 'dataSource'
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:382)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    ... 47 more
and many more of this, but I didn't paste all of it.
EDIT - Hibernate Configurations XML:
<?xml version="1.0" encoding="UTF-8"?>

http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/xdvl" />
    <property name="username" value="root" />
    <property name="password" value="Parola1234" />
</bean>

<!-- Hibernate 3 Annotation SessionFactory Bean definition-->

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.crm</groupId>
<artifactId>customer-relationship-management</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>commons-pool</groupId>
        <artifactId>commons-pool</artifactId>
        <version>1.5.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.8.Final</version>
    </dependency>
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.2.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss</groupId>
        <artifactId>jboss-loggig</artifactId>
        <version>3.3.0.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
</dependencies>

A: org.springframework.jdbc.datasource.DriverManagerDataSource does not have a close method.
Replace your data source bean defintion with:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/xdvl" />
    <property name="username" value="root" />
    <property name="password" value="Parola1234" />
</bean>

Also please not the data source is not good for web applications as stated in its javadoc:

NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.
Useful for test or standalone environments outside of a J2EE container

A: after the discussion with @Wabi, I've changed the version of hibernate-commons-annotations jar from 4.0.2.Final to 4.0.5.Final version and now it's working :)
Thank you :)


text:
Q: How to remove index.php from a URL from CodeIgniter? I am new to CodeIgniter. I have an XAMPP server on Windows 8. Everything is fine, but the problem is about my URL, it doesn't look friendly. It looks like localhost/ci/index.php/site/home (where ci is my root folder for CodeIgniter). I want to make the URL more clean, like  localhost/ci/home, how can I do it?
My CodeIgniter version is 2.1.2.
I have done some research already, but in most of the cases it says to change the .htaccess file of CodeIgniter. But I have nothing in the .htaccess file; it's empty, except the line "Deny from all".

A: You can do this, in config/config.php:
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST']; //you can also leave blank this CI tend to find this by himself
$config['index_page'] = '';

And try the following .htaccess. I use it for many sites, and it satisfies me.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

If it is not working yet, use a phpinfo(); and check if mod_rewrite is enabled. If it is not enabled, you can follow the instructions in Stack Overflow question How do you enable mod_rewrite? to enable that.
If it is not working yet and mod_rewrite is enabled yet, you can try to switch these in config/config.php:
$config['uri_protocol'] = 'AUTO'; //If not working, try one of these:
     'PATH_INFO'        Uses the PATH_INFO
    | 'QUERY_STRING'    Uses the QUERY_STRING
    | 'REQUEST_URI'     Uses the REQUEST_URI
    | 'ORIG_PATH_INFO'  Uses the ORIG_PATH_INFO

A: You need to replace "Deny from all" with this:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

http://ellislab.com/codeigniter/user-guide/general/urls.html

A: Looking at the official documentation, CodeIgniter URLs:

You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the "negative" method in which everything is redirected except the specified items:

RewriteEngine on

RewriteCond $1 !^(index\.php|images|robots\.txt)

RewriteRule ^(.*)$ /index.php/$1 [L]

Also if you are using Apache place .htaccess file in your root web directory. For more information, look in Codeigniter .htaccess.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OffsetImage shows up different on screen and in PDF when aligning the image to the figure border I want to insert a scaled image on a figure and align it to right figure border. The following works fine in the interactive windows and when saving as png,
but when saving as a pdf the image is too to the left. How can i get the correct behavior for both cases? This happens also if the savefig and figure settings are identical.
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage
import numpy as np
fig = plt.figure(dpi=100)
image = np.ones((200, 200))
ob = OffsetImage(image, zoom=0.5)
rend = fig.canvas.get_renderer()
w, h, x, d =  ob.get_extent(rend)
fig.images.append(ob)
ob.set_offset((fig.bbox.xmax-w, 0))
plt.show()
fig.savefig("bla.pdf", dpi=100)

A: The following code, being more explicit about padding and bounding box, gives the same for png and pdf for me (matplotlib 1.4.3, python 2.7).
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage
import numpy as np

fig = plt.figure(figsize=(8,6))
image = np.ones((200, 200))
ob = OffsetImage(image, zoom=0.5)
rend = fig.canvas.get_renderer()
w, h, x, d =  ob.get_extent(rend)
fig.images.append(ob)
ob.set_offset((fig.bbox.xmax-w, 0))
fig.savefig("bla.pdf",figsize=(8,6),
                       bbox_inches='tight',
                       pad_inches=0)

The version of your code (even with plt.show() removed) gave an empty pdf document for me. As to why the above works, I guess it may be a bug with matplotlib or possibility a difference in coordinate system used in saving the pdf vs. the more wysiwyg display/png figure. Could also be matplotlib template, in which case this answer may help...


text:
Q: Dojo accessing variable from external Javascript file I am migrating to Dojo 10.4, before I have few customized javascript files which are modified by running dojo amd converter. But after migrating I cannot able to access variables in js files.
I have declared like this in a file called abc:
define([
    "dojo",
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/on",
    "dojo/request",
    "dijit/form/FilteringSelect"
], function (dojo, declare, lang, on, request, FilteringSelect) {
        var VARIABLE= {};
Now I am using this js file in jsp file by integrating with <script>command.
the main problem is, how can I access the var VARIABLE in the jsp file.
I have tried with require, provide etc..but still cannot access the declared variable.

A: If you worked with javascript objects, then you can understand:
Here var VARIABLE is defined as a private variable, if you need it in JSP, you have to make it public. Here is an example snippet for it.
in ui/some.js:
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dijit/form/FilteringSelect"
],function( declare, lang, FilteringSelect){
    return declare("ui.some", [],{
        VARIABLE: "testing",
    });
});

In index.jsp:
require(["ui/some"],function(Some){
    alert(Some.VARIABLE);
});


text:
Q: Errors with a Template in C++ regarding operators In my project, I am using a header file for an arrayList. During the main method, I initialize an object of type arrayList where FriendToken is another class defined in my project. However, this gives me quite a few errors while compiling arrayList.h. Apparently, I cannot use the built-in copy method and the operator == is unrecognized for an object of type FriendToken. Should I overload the == operator for FriendToken and if so, how should I do that?
Both errors are marked in the body ArrayList.h.
ArrayList.h:
#ifndef arrayList_h
#define arrayList_h

#include "linearList.h"

#include <iostream>
#include <fstream>
#include <ostream>

using namespace std;
template<class T>
class arrayList : public linearList<T>
{
public:
    // constructor, copy constructor and destructor
    arrayList(int initialCapacity = 10);
    arrayList(const arrayList<T>&);
    ~arrayList() {delete [] element;}
    // ADT methods
    bool empty() const {return listSize == 0;}
    int size() const {return listSize;}
    T& get(int theIndex) const;
    int indexOf(const T& theElement) const;
    void erase(int theIndex);
    void insert(int theIndex, const T& theElement);
    void output(ostream& out) const;
    void changeLength1D(T*& a, int oldLength, int newLength);
    // additional method
    int capacity() const {return arrayLength;}
protected:
    void checkIndex(int theIndex) const;
    // throw illegalIndex if theIndex invalid
    T* element;      // 1D array to hold list elements
    int arrayLength;       // capacity of the 1D array
    int listSize;          // number of elements in list
};
template<class T>
arrayList<T>::arrayList(int initialCapacity)
{
    // Constructor.
    arrayLength = initialCapacity;
    element = new T[arrayLength];
    listSize = 0;
}
template<class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{
    // Copy constructor.
    arrayLength = theList.arrayLength;
    listSize = theList.listSize;
    element = new T[arrayLength];
    copy(theList.element, theList.element + listSize, element);
}
template<class T>
void arrayList<T>::checkIndex(int theIndex) const
{
    // Verify that theIndex is between 0 and
    // listSize - 1.
    if (theIndex < 0 || theIndex >= listSize)
    {
        cout << "index = " << theIndex << " size = "
            << listSize;
    }
}
template<class T>
T& arrayList<T>::get(int theIndex) const
{
    // Return element whose index is theIndex.
    // Throw illegalIndex exception if no such
    // element.
    checkIndex(theIndex);
    return element[theIndex];
}
template<class T>
int arrayList<T>::indexOf(const T& theElement)const
{
    // Return index of first occurrence of theElement.
        // search for theElement
        int theIndex = (int) (find(element, element
        + listSize, theElement) - element);
    // check if theElement was found
    if (theIndex == listSize)
        return -1; // not found
    else return theIndex;
}
template<class T>
void arrayList<T>::erase(int theIndex)
    {// Delete the element whose index is theIndex.
    checkIndex(theIndex);
    // valid index, shift elements with higher index
//PROBLEM********************************************
    copy(element + theIndex + 1, element + listSize,element + theIndex);
    element[--listSize].~T(); // invoke destructor
}
template<class T>
void arrayList<T>::insert(int theIndex, const T& theElement)
{
    // Insert theElement.
    if (theIndex < 0 || theIndex > listSize)

    {// invalid index
        // code to throw an exception comes here
    }
    // valid index, make sure we have space
    if (listSize == arrayLength)
    {
        // no space, double capacity
        changeLength1D(element, arrayLength,
        2 * arrayLength);
        arrayLength *= 2;
    }
    // shift elements right one position
//PROBLEM***************************************
    copy_backward(element + theIndex, element + listSize, element + listSize + 1);
    element[theIndex] = theElement;
    listSize++;
}
template<class T>
void arrayList<T>::output(ostream& out) const
{
    // Put the list into the stream out.
    copy(element, element + listSize, ostream_iterator<T>(out, "  "));
}
template <class T>
ostream& operator<<(ostream& out, const arrayList<T>& x)
{x.output(out); return out;}

template<class T>
void changeLength1D(T*& a, int oldLength, int newLength)
{
    if (newLength < 0)
        throw illegalParameterValue();
    T* temp = new T[newLength];
    // new array
    int number = min(oldLength, newLength);
    // number to copy
    copy(a, a + number, temp);
    delete [] a;
    // deallocate old memory
    a = temp;
}

#endif

FriendToken.h
#ifndef FriendToken_h
#define FriendToken_h

#include <string>

using namespace std;

class FriendToken
{
private:
    string birthDate, name, homeTown;
public:
    FriendToken(string birthDate = "01/01", string name = "John, Smith", string homeTown = "New York");
    string getBirthDate();
    string getName();
    string getHomeTown();
    bool equals(FriendToken a);
};

#endif

FriendToken.cpp
#include "FriendToken.h"
#include <string>

using namespace std;

FriendToken::FriendToken(string birthDate, string name, string homeTown)
{
    this->birthDate = birthDate;
    this->name = name;
    this->homeTown = homeTown;
}
string FriendToken::getBirthDate()
{
    return birthDate;
}
string FriendToken:: getName()
{
    return name;
}
string FriendToken::getHomeTown()
{
    return homeTown;
}
bool FriendToken::equals(FriendToken a)
{
    return (name == a.getName()) && (homeTown == a.getHomeTown()) && (birthDate == a.getBirthDate());
}

A: It's hard to tell without the compiler errors.
Either way, this is how you overload the operator.
template<typename T>
bool arrayList::operator== (const arrayList<T>& theList)
{
    // Compare the values, and return a bool result.
}


text:
Q: The difference between building a Rails application and an ASP.NET MVC Application? First of all some background: 4 years of C# experience and a year of Rails experience. I would appreciate any input from someone who has worked in both and knows a lot about developing ASP.NET MVC applications.
I've been doing nothing but Rails projects for the last year. Now, I have a client wants their application converted from ASP.NET Web Forms to ASP.NET MVC. This is the first time I've done MVC in C# so I'm trying to see how different things are and if certain productive Rails tasks map over to ASP.NET MVC.
First of all, is there such a thing as a Scaffold in ASP.NET MVC? I see something called an Area but I don't know if thats quite what I want. Also, how can I generate a scaffold (models, controllers and views), just a controller or just a model based on the same information I would give a Rails app?
For example I might do something like:
$>script/generate scaffold person first_name:string last_name:string

which produces a Person model, a migration script (what I run to build the database table), a People controller and views for each of the RESTful interfaces (index, new, create, edit, update, show, destroy). Can I do something like this in Visual Web Develop 2010 Express?

A: There is MVC Scaffolding with MVC3.
Here's a nice post on it.

A: Whereas Rails has tries (especially for beginners) to guide you into one way to write your app, MVC attempts to be all things to all people. So it's very flexible, but it's hard to specify the "one true way" to scaffold something.
So one way which works is:

*

*Create your DB. Create an Entity Framework model in the usual way from the DB.

*Compile.

*Right-click Controllers, Add, Controller. Check the box for actions.

*Right click one of the generated actions, choose Add View.

*Check the box for "Create strongly typed view" and select scaffolding from the combo box.

But there are many other ways!
There are 3rd party tools for migrations, but nothing built in. What is built into full VS (maybe not express) is database comparison and merge script generation, an arguably more powerful, but perhaps harder for new developers to understand, alternative.


text:
Q: Copy a geometry from one feature to another without attributes? With QGIS it's easy to add a new part to an existing feature/geometry but I can't see how to copy/paste this part from another existing feature/geometry.
Is it possible?

A: Yes it is possible, see instructions below:

*

*Start an edit session on both layers that you want to do the copy/paste between.

*Use the Select feature by rectangle tool to select the feature in the map (copy from).

*Click the Edit (menu)>Copy Features button.

*Highlight the layer in the TOC that the feature will be pasted to.

*Click the Edit (menu)>Paste Features button.

A: For copying just the geometry between existing features there is the plugin Geometry Paster: https://github.com/nextgis/geometry-paster

A: Old discussion but another answer if your source geometry is in a layer well supported by the DB Manager (PostGIS, GeoPackage, etc.):

*

*Get ID of feature to be copied (Identify Features tool)

*Open SQL Window on that database in DB Manager.

SELECT <geom> FROM <layer> WHERE id = <#>

*Load as layer

You have the geometry in the original projection without attributes in a scratch layer.


text:
Q: QLocalServer emits readyRead when bytes are not available I'm trying to start QLocalServer in my local OSX 10.11.
I have client which tries connection to server in loop:
int connect(const char* filename) {
  int sock;
  struct sockaddr_un serv_addr;

  memset(&serv_addr, 0x00, sizeof(serv_addr));
  serv_addr.sun_family = AF_LOCAL;
  strncpy(serv_addr.sun_path, filename, sizeof(serv_addr.sun_path) - 1);

  if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    return sock;
  }

  if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) {
    close(sock);
    sock = -1;
    return sock;
  }

  return sock;
}

int main() {
  int sock;
  while((sock = connect("my_socket_server")) == -1) {
    usleep(3000);
  }

  // The code never reaches this line

  const char* buffer = "hello";
  if (send(sock, buffer, strlen(buffer), 0) < 0) {
    exit(1);
  }

  return 0;
}

When this code is running, I try to start QLocalServer in another application:
// Starting server:

QString socket_path = "my_socket_server";
QLocalServer::removeServer(socket_path);
if (!server.listen(socket_path)) {
  return false;
}

connect(&server, &QLocalServer::newConnection, this, &MyServerClass::newConnection);

...

void MyServerClass::newConnection() {
  socket = server.nextPendingConnection(); // socket - member of MyServerClass
  connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
  connect(socket, &QLocalSocket::readyRead, this, &MyServerClass::readyRead);
}

...

void MyServerClass::readyRead() {
  if (!socket->bytesAvailable()) {
    exit(1); // THIS CODE WAS CALLED. WHY?
  }

  ...
}

Why when readyRead was called, bytes are not available?

A: You might be getting multiple connections, in which case the socket variable might be pointing to a different object from the one which emits the readyRead signal. Either use QObject::sender to get the correct object in the slot, or use the QSignalMapper. If you are using Qt5, you can also use a lambda function and capture the socket object.


text:
Q: Integral of inverse of square root of a quadratic I haven't taken a course on calculus so far so I don't know what to do. The integral may be wrong. Please tell me which part of it is wrong.
$$
q∫_{+a}^{-a}\lim_{c \to g}\frac 1{(b^2+c^2)^{3⁄2}} dc
$$
All letters in the problem are variables.
Since the question can't be understood. Here is the figure of the main context:

b: radius of the cylinder
+a and -a: the x component of the cylinder's corners' positon vectors
Actually this is an electrostatic problem. I am trying to find the electric field due to a tube applied on a point. Since the tube is infinite number of rings, I first found the electric field of a ring which is
$E=kcq/(c^2+b^2)^{(3⁄2)}$
where k=8,98... is Coulomb's constant and q is the charge of an infinitesmal ring. And g is the distance between the point and the +a.
Hope this helps.

A: You have a ring, with a center in $(0,0,0)$. And on the point on the axis it has induce the electric field:
$$
E = \frac{q z}{4\pi\varepsilon_0 (r^2 + z^2)^{3/2}}
$$
where, $r$ is a ring radius and $z$ is a distance from origin, so, point have coordinates $(0,0,z)$.
Then, if you move the ring by some factor $\delta$ it become and $\delta$ would be between $-a$ and $a$:
$$
E = \frac{q (z + \delta)}{4\pi\varepsilon_0 (r^2 + (z+\delta)^2)^{3/2}}
$$
Now, it's only needed to integrate this by $\delta$ from $-a$ to $a$:
$$
E = \int_{-a}^{a}\frac{q (z + \delta)}{4\pi\varepsilon_0 (r^2 + (z+\delta)^2)^{3/2}}\mathrm{d}\delta = \frac{q}{4\pi\varepsilon_0}\int_{-a}^{a}\frac{z+\delta}{(r^2 + (z+\delta)^2)^{3/2}}
$$
Integrating this:
$$
E = \frac{q}{4\pi\varepsilon_0}\left(\frac{1}{\sqrt{r^2 + (z-a)^2}} - \frac{1}{\sqrt{r^2 + (z+a)^2}}\right)
$$

A: Note that, for every $(b,g)\ne(0,0)$,
$$
\lim_{c \to g}\frac 1{(b^2+c^2)^{3⁄2}}=\frac 1{(b^2+g^2)^{3⁄2}}
$$
hence
$$
I=q∫_{+a}^{-a}\lim_{c \to g}\frac 1{(b^2+c^2)^{3⁄2}} dc,$$ is $$I=q∫_{+a}^{-a}\frac 1{(b^2+g^2)^{3⁄2}} dc=\frac q{(b^2+g^2)^{3⁄2}}∫_{+a}^{-a} dc=\frac{-2aq}{(b^2+g^2)^{3⁄2}}.
$$


text:
Q: How does configuration or phase space change in pseudo-Hermitian (or just non-Hermtiian) QM vs Hermitian QM? I was wondering if there is some relaxation of the configuration (or phase) space when considering pseudo-Hermitian physical situations vs Hermitian? For instance in "$C^*$-Algebras of Energy Observables: I. General Theory and Bumps Algebras"
the authors (GEORGESCU and IFTIMOVICI) let the configuration space be an arbitrary abelian locally compact group X. Are there any relaxations here when we look at pseudo-Hermitian Hamiltonians? Or just in general if/can the configuration space (or phase space) change in pseudo-Hermitian vs Hermitian QM?


text:
Q: AWS Linux sudo: unable to resolve host I have a problem when launching any instance (from and AMI) within a particular VPC. Everytime I type a "sudo" command, I get the following:
sudo: unable to resolve host ip-xxx-xx-x-xxx
I have seen many posts on the internet about this and they all mention the following two solutions:

*

*Manually edit the /etc/hosts file on every server... This is not practical (especially when using AutoScaling to generate new instances) and I shouldn't have to do this as I don't have to do this for any instances on other VPCs

*Turn on "DNS hostnames" on the VPC... I have done this and it hasn't made a difference. I have gone through all the settings on the VPC (and route tables, subnets etc) and I have it set exactly the same way as a "working" VPC on my account. Still no luck

Any help here?

A: It seems as if this is an AWS specific problem that has been run into before, it stems from not enabling enableDnsHostnames in your VPC configuration.
Here is a link to the AWS documentation that talks about this.
http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-dns.html#vpc-dns-updating

A: This is a really late answer, and I'm not sure if it's still relevant for newer EC2 instances, but I've just taken over an account running Ubuntu 16, and I solved this annoyance by just adding the dns hostname to the hosts file.  Presumably this could be automated for any auto-scaling if desired.  As simple as:
echo 127.0.0.1 ip-10.x.x.x >> /etc/hosts

Or any variant using tee or sed or your other Unix tool of choice. You could include ipv6 version as well, if you really want to be thorough, but ipv4 was enough to stop the warning in my case.


text:
Q: How to calculate the AUC value for a ranger RF model? How can I calculate the AUC value for a ranger model ? Ranger is a fast implementation of randomForest algorithm in R. I'm using the following code to build the ranger model for classification purposes, and get the prediction from the model:
#Build the model using ranger() function
ranger.model <- ranger(formula, data = data_train, importance = 'impurity',
write.forest = TRUE, num.trees = 3000, mtry = sqrt(length(currentComb)),
classification = TRUE)
#get the prediction for the ranger model
pred.data <- predict(ranger.model, dat = data_test,)
table(pred.data$predictions)

But I dont know how to calculate the AUC value
Any idea ?

A: The key to computing AUC is having a way to rank your test samples from "Most likely to be positive" to "Least likely to be positive". Modify your training call to include probability = TRUE. pred.data$predictions should now be a matrix of class probabilities. Make note of the column that corresponds to your "positive" class. This column provides the ranking we need to compute AUC.
To actually compute AUC, we will use Equation (3) from Hand and Till, 2001. We can implement this equation as follows:
## An AUC estimate that doesn't require explicit construction of an ROC curve
auc <- function( scores, lbls )
{
  stopifnot( length(scores) == length(lbls) )
  jp <- which( lbls > 0 ); np <- length( jp )
  jn <- which( lbls <= 0); nn <- length( jn )
  s0 <- sum( rank(scores)[jp] )
  (s0 - np*(np+1) / 2) / (np*nn)
}

where scores would be the column of pred.data$predictions that corresponds to the positive class, and lbls are the corresponding test labels encoded as a binary vector (1 for positive, 0 or -1 for negative).


text:
Q: TikZ node placement and arrow drawing I just started using TikZ and try to get a process control drawn by TikZ. It looks wonderful, but I am a real beginner. I use the simple flow chart as base and came to this result:

I use shapes (blue nodes) and lines together with "fit" to draw the dashed container around "Resources" and "Sensors" (complete code below). I am not satisfied with this for four reasons:

*

*I'd like to place the left box in between of the two middle ones (see red rectangle)

*Drawing an arrow from "Processing" to "Planning" is drawn right in the middle through "Sensors" and "Resources". Also, the arrow pointing to the dashed container should just be inside the container, not pointing to the egde

*I'd like to label the dashed container (see small rectangle just below "Planning")

*See the code, but the spacing of the rectangle is now done with a minimum height and width, because without it, the fit is too tight. However, it's not a real scalable solution, so I need to adjust the width/height every time I want to fit a rectangle around several nodes

This is my source code:
\tikzstyle{b} = [rectangle, draw, fill=blue!20, node distance=3cm, text width=6em, text centered, rounded corners, minimum height=4em, thick]
\tikzstyle{c} = [rectangle, draw, minimum height=15em, minimum width=10em, dashed]
\tikzstyle{l} = [draw, -latex',thick]

\begin{tikzpicture}[auto]
    \node [b] (planning) {Planning};
    \node [b, below of=planning] (resources) {Resources};
    \node [b, below of=resources] (sensors) {Sensors};
    \node [b, left of=resources, node distance=4cm] (information) {Information system};
    \node [b, below of=sensors] (processing) {Processing};

    \node[c,fit=(resources) (sensors)] (container) {};

    \path [l] (planning) -- (resources);
    \path [l] (resources) -- (sensors);
    \path [l] (sensors) -- (processing);

    \path [l] (information) |- (planning);
    \path [l] (information) |- (processing);
\end{tikzpicture}

Can someone point me in the right direction to solve my problems?

A: Is this what you are looking for?  I have made the following changes:

*

*First (minor), I am using the positioning library to place the nodes rather than the default right of = syntax, which the manual tells me is deprecated.  Basically, you write right = of instead :)

*Second (minor), I am using the syntax \tikzset{key/.style = } rather than \tikzstyle, since the manual also says this is deprecated (actually, I think it's not even in there anymore).  It's good to get in the habit of using \tikzset and, by extension, pgfkeys, directly, and no more writing.

*Enough lecturing.  You actually have most of the elements already.  I placed information left = of container to get it in the middle where you wanted it, and I created a fictitious coordinate called fit right to the right of container through which I could pass some piecewise-rectilinear paths.  I also used "incremental coordinates" to get the arrow from fit right to move a desired distance left.

*I fixed the spacing of your rectangle by creating some more fictitious coordinates (also using incremental coordinates, rather than the calc library) to stretch the corners to the desired distance.  It is not totally automated, but it is right there in the code.  An alternative solution would be to use outer sep on the nodes resources and sensors, which pushes their anchors away from their borders, but that also affects the placement of the arrows, so it's not useful here.

*I did use outer sep to place the label, as well as some more relative positioning.
Just a comment: you should have given a full document in your example.  I had to guess which tikz libraries you used.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning,fit,arrows}

\tikzset{
 b/.style
  = {rectangle, draw, fill=blue!20, node distance=3cm, text width=6em,
     text centered, rounded corners, minimum height=4em, thick},
 c/.style
  = {rectangle, draw, dashed,inner sep = 0pt},
 l/.style
  = {draw, -latex',thick}
}

\begin{document}

\begin{tikzpicture}[auto]
    \node [b] (planning) {Planning};
    \node [b, below = of planning] (resources) {Resources};
    \node [b, below = of resources] (sensors) {Sensors};
    \node [b, below = of sensors] (processing) {Processing};

    \path
     (resources.north west) ++(-1cm,1cm) coordinate (resources fit)
     (sensors.south east)   ++(1cm,-1cm) coordinate (sensors fit)
    ;
    \node [c,fit=(resources fit) (sensors fit)] (container) {};
    \node [above left = 0pt of container, anchor = south, draw, outer sep = 6pt] (container label) {Resources and sensors};

    \node [b, left = 4cm of container] (information) {Information system};
    \coordinate [right = 4cm of container] (fit right) {};

    \path [l] (planning) -- (resources);
    \path [l] (resources) -- (sensors);
    \path [l] (sensors) -- (processing);

    \path [l] (information) |- (planning);
    \path [l] (information) |- (processing);

    \path [l] (processing) -| (fit right) |- (planning);
    \path [l] (fit right) -- ++(-4.5cm,0);
\end{tikzpicture}

\end{document}

A: There's a good chance some more elegant solution will appear soon, but here goes:

*

*By using the calc library you can add node halfway between sensors and resources, and position information with relation to this. I actually used the corners of these, resources.south west and sensors.north west, and put the new node midway between these.

*One way is to use relative coordinates to first go a little right of processing, then up, left to planning. By using |-/-| you can access coordinates that lie on the intersection of the horizontal line from one node and vertical line from another. That way you can end the arrow directly above sensors.north east, for example.
I first add a new node, lowerright while drawing the line from resources to planning. (lowerright |- container.east) is the point that lies on the vertical line from lowerright and the horizontal line from container.east. Similar for (container.east -| resources.south east).

*You can add a node above the top left corner of container.

*Add inner sep=<dimension> to the container node, instead of defining width and height. This sets the distance from the contents of the node to the edge of the node.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit,arrows,calc,positioning}

\begin{document}
\tikzstyle{b} = [rectangle, draw, fill=blue!20, node distance=3cm, text width=6em, text centered, rounded corners, minimum height=4em, thick]
\tikzstyle{c} = [rectangle, draw, inner sep=0.5cm, dashed]
\tikzstyle{l} = [draw, -latex',thick]

\begin{tikzpicture}[auto]
    \node [b] (planning) {Planning};
    \node [b, below=of planning] (resources) {Resources};
    \node [b, below=of resources] (sensors) {Sensors};
    \coordinate (RSmid) at ($(resources.south west)!0.5!(sensors.north west)$);
    \node [b, left=of RSmid, node distance=4cm] (information) {Information system};
    \node [b, below=of sensors] (processing) {Processing};

    \node [c,fit=(resources) (sensors)] (container) {};

    \path [l] (planning) -- (resources);
    \path [l] (resources) -- (sensors);
    \path [l] (sensors) -- (processing);

    \path [l] (information) |- (planning);
    \path [l] (information) |- (processing);

    \node at (container.north west) [above right] {Desc};

    \draw [l] (processing.east) -- ++(2,0) node(lowerright){} |- (planning.east);
    \draw [l] (lowerright |- container.east) -- (container.east -| resources.south east);
\end{tikzpicture}
\end{document}

A: The problem with answers based on positioning is that very difficult to scale the picture.
Here an answer with the possibility to scale the picture without modify the texts.
\documentclass{article}
\usepackage{tikz,fullpage}
\usetikzlibrary{arrows,calc,fit}

\begin{document}

\tikzstyle{b} = [rectangle, draw, fill=blue!20, text width=6em,
                 text centered, rounded corners, minimum height=4em, thick]
\tikzstyle{c} = [rectangle, draw, dashed]
\tikzstyle{l} = [draw, -latex',thick]

\begin{tikzpicture}[auto,scale=1.25]
    \node [b]    (planning) {Planning};
    \node [b]    (resources)   at ([shift={(0,-3)}] planning) {Resources};
    \node [b]    (sensors)     at ([shift={(0,-6)}] planning) {Sensors};
    \coordinate  (RSmid)       at ($(resources)!0.5!(sensors)$);
    \node [b]    (information) at ([shift={(-4,0)}] RSmid)    {Information system};
    \node [b]    (processing)  at ([shift={(0,-9)}] planning) {Processing};
    % here I need to use `transform shape` because I need to transform `inner sep` ,
    %  the node is empty, ouf !!!
     \node [c,transform shape,inner sep=0.5cm,fit=(resources) (sensors)] (container) {};

    \path [l] (planning)  -- (resources);
    \path [l] (resources) -- (sensors);
    \path [l] (sensors)   -- (processing);

    \path [l] (information) |- (planning);
    \path [l] (information) |- (processing);

    \node at (container.north west) [above right] {Desc};

    \draw [l] (processing.east) -- ++(2,0) node(lowerright){} |- (planning.east);
    \draw [l] (lowerright |- container.east) -- (container.east -| resources.south east);
\end{tikzpicture}
\end{document}

A:
It is definitely a late answer.  Its reason is that the proposed solution follows closely the initial code:

*

*it is based on the positioning library only by introducing two phantom nodes at the center and at the center-right of the flow chart

*the node information is placed and the arrows on the right are drawn with respect to these phantom nodes

*the label of the dash container is a label of the node container.

The code
\documentclass[11pt, margin=1cm]{standalone}

\usepackage{tikz}
\usetikzlibrary{fit, arrows, positioning}

\begin{document}

\tikzstyle{b} = [rectangle, draw, fill=blue!20, node distance=3cm,
text width=6em, text centered, rounded corners, minimum height=4em, thick]
\tikzstyle{c} = [rectangle, draw, minimum height=15em,
minimum width=10em, dashed]
\tikzstyle{l} = [draw, -latex', thick]

\begin{tikzpicture}[auto, every label/.style={scale=.8}]
  \node[b] (planning) {Planning};
  \node[b, below of=planning] (resources) {Resources};
  \node[b, below of=resources] (sensors) {Sensors};
  \node[b, below of=sensors] (processing) {Processing};

  \path (resources.center) -- (sensors.center) node[pos=.5, minimum width=7em, anchor=center] (phantom-c) {} ;
  \node[right of=phantom-c, node distance=3cm, inner sep=0pt, outer sep=0pt] (phantom-r) {};
  \node[b, left of=phantom-c, node distance=4cm] (information) {Information system};

  \node[c, fit=(resources) (sensors), label={105:some label}] (container) {};

  \path[l] (planning) -- (resources);
  \path[l] (resources) -- (sensors);
  \path[l] (sensors) -- (processing);

  \path[l] (information) |- (planning);
  \path[l] (information) |- (processing);

  \path[l] (processing) -| (phantom-r) |- (planning);
  \path[l] (phantom-r) -- (phantom-c);
\end{tikzpicture}

\end{document}


text:
Q: WIX + LAMP under one domain I'm trying to get my head around a problem and hoping for some clarity
I have built a basic LAMP site running on a VPS.
My client also has a site built on WIX (online website builder)
I would like to get both sites running under the one domain name. Perfect solution would be (though I don't believe is possible):

*

*example.com - WIX

*example.com - WIX

*example.com/y - LAMP

*example.com/z - LAMP

My next idea would be to use subdomains:

*

*www.example.com - WIX

*xyz.example.com - LAMP

Is any of the above possible when trying to work with WIX and LAMP setups without spending lots of money on something like nginx? Or do I just have to use different domains?

A: I am not familiar with WIX ecosystem but I think that the path of least resistance is to just setup a subdomain using DNS records.
Refer to your DNS manager, but basically you just want to add an A record.
Your DNS records might look like
example.com.       A    1.2.3.4
www.example.com.   A    1.2.3.4

So you will just need to add
xyz.example.com.   A    5.6.7.8

If your DNS records are managed by WIX, I found the proper documentation.

By the way, Nginx open source is free. Nginx plus is a paid service that includes some goodies on top. Blog post Feature comparison


text:
Q: Interface property depend on other property Let's say I have the next interface:
interface TestInterface {
  id?: string;
  type?: string;
}

Is it possible to rewrite in a way that when I perform a check that id !== undefined it'll automatically mean that type property is also defined?

A: You can mimic this with union types.
Simple example:
interface INonNullable {
    id: string;
    type: string;
}
interface INullable {
    id?: undefined;
    type?: undefined;
}
type FinalType = INonNullable | INullable;

function testId(x: FinalType)
{
  if (x.id !== undefined) {
    x.type // string
  }
}

FinalType is optional, you can simply use (x: INonNullable | INullable) everywhere.
Add type-guard function:
You can also make function with type guard to test for your criteria and narrow the type that way:
interface INonNullable {
    id: string;
    type: string;
}
interface INullable {
    id?: undefined;
    type?: undefined;
}
type FinalType = INonNullable | INullable;

function isNonNullable(x: FinalType): x is INonNullable
{
  return x.id !== undefined;
}

let x = {};

if (isNonNullable(x)) {
  x.type // string;
}

You have more info about this in Typescript documentation:
User-Defined Type Guards
Reusable Empty<T>:
Another neat option, as mentioned in the comment by Patrick Roberts, to make more re-usable solution using mapped types and generics:
interface INonNullable {
    id: string;
    type: string;
}
type Empty<T> = {
  [K in keyof T]?: undefined;
}
type FinalType<T> = T | Empty<T>;

function testId(x: FinalType<INonNullable>) {
  if (x.id !== undefined) {
    x.type // string
  }
}

A: Lets see your example:
interface TestInterface {
  id?: string;
  type?: string;
}

const objectForTest: TestInterface = {
  id: '12345',
  type: 'some type'
}

You can do it in the following ways:
1) objectForTest?.id
If this operator meet undefined, it will return this value without throwing a TypeError.
This is equvalent to:
const testValue = (objectForTest === null || objectForTest === undefined) ?
    undefined
    :
    objectForTest.id;

2) objectForTest!.id
In this case you say to type checker: "Hey, I promise you that objectForTest is not null or undefined".

A: Here a way to do what you want, using union :
interface IdWithType {
  id: string;
  type: string;
}

interface WithoutId {
  id?: never;
  type?: string;
}

type TestInterface = IdWithType | WithoutId

// You cannot instansiate an object of type TestInterface with an id and with out a type

const yo: TestInterface = { // Type '{ id: string; }' is not assignable to type 'TestInterface'.
  id: "hey"
}

const testFunction = (a: TestInterface) => {
  if (a.id) {
    const b = a.type // string
  }
  const c = a.type // string | undefined
}


text:
Q: PHP: Best way to check if input is a valid number? What is the best way of checking if input is numeric?

*

*1-

*+111+

*5xf

*0xf

Those kind of numbers should not be valid. Only numbers like: 123, 012 (12), positive numbers should be valid.
This is mye current code:
$num = (int) $val;
if (
    preg_match('/^\d+$/', $num)
    &&
    strval(intval($num)) == strval($num)
    )
{
    return true;
}
else
{
    return false;
}

A: ctype_digit was built precisely for this purpose.

A: I use
if(is_numeric($value) && $value > 0 && $value == round($value, 0)){

to validate if a value is numeric, positive and integral
http://php.net/is_numeric
I don't really like ctype_digit as its not as readable as "is_numeric" and actually has less flaws when you really want to validate that a value is numeric.

A: filter_var()
$options = array(
    'options' => array('min_range' => 0)
);

if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
 // you're good
}

A: return ctype_digit($num) && (int) $num > 0

A: For PHP version 4 or later versions:
<?PHP
$input = 4;
if(is_numeric($input)){  // return **TRUE** if it is numeric
    echo "The input is numeric";
}else{
    echo "The input is not numeric";
}
?>

A:
The most secure way

if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
  //if all made of numbers "-" or ".", then yes is number;
}


text:
Q: How to remove Itemid from url in JOOMLA 2.5 I have some modules on homepage which have article title with link that must be redirect on article page.
Problem is that if there is menu associated with article then when I click on the article title, the article opens correctly. But if there menu isn't associated with article, the article isn't open at all and redirected to again home page.
Module article links have Itemid, it is default Itemid added by joomla when i have remove that Itemid from url manually article open properly but with Itemid it is not.
Here's the site link i have working on please have a look
http://www.econewsindia.com/

A: What I found from your site is you do not have proper menu items created for article categories. Follow this procedure.

*

*Create a new menus and name it as Articles Menu or whatever you like

*Create a menu item for each "Top Level" article category under this menus (no need for sub categories). Use "Category List" or "Category Blog" menu item type - first one is preferred.

*If you would like, you can show this menus on front-end using Menu Module but that is not necessary.

Now every article will have a proper item id associated with it and your articles will redirect properly.


text:
Q: How to extract N random different elements from a set of unique elements? I have a set of unique elements (there are not two identical elements). And I would like to extract N random and different elements from the set. What is the easiest way to do it in Java?

A: Set<MyObject> mySet = getTheSetFromSomeWhere();
List<MyObject> myObjects = new ArrayList<MyObject>(mySet);
Collections.shuffle(myObjects);
myObjects = myObjects.subList(0, n);


text:
Q: Trying to Convert VB.Net to C# I'm having a problem converting vb.net code I found on the web to C#.
vb.net
 Protected Overridable Sub OnRowClicked(ByVal e As GridViewRowClickedEventArgs)
    'raise the RowClicked event
    RaiseEvent RowClicked(Me, e)
End Sub

'setup our EventHandler for RowClicked
Public Custom Event RowClicked As EventHandler(Of GridViewRowClickedEventArgs)
    AddHandler(ByVal value As EventHandler(Of GridViewRowClickedEventArgs))
        Events.AddHandler(RowClickedEventKey, value)
    End AddHandler

    RemoveHandler(ByVal value As EventHandler(Of GridViewRowClickedEventArgs))
        Events.RemoveHandler(RowClickedEventKey, value)
    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As GridViewRowClickedEventArgs)
        Dim ev As EventHandler(Of GridViewRowClickedEventArgs) = TryCast(Events(RowClickedEventKey), EventHandler(Of GridViewRowClickedEventArgs))
        If Not IsNothing(ev) Then
            ev(sender, e)
        End If
    End RaiseEvent
End Event

c#
protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
    {
        //raise the RowClicked event
        if (RowClicked != null)
        {
            RowClicked(this, e);
        }
    }

    //setup our EventHandler for RowClicked
    public event EventHandler<GridViewRowClickedEventArgs> RowClicked
    {
        add { Events.AddHandler(RowClickedEventKey, value); }

        remove { Events.RemoveHandler(RowClickedEventKey, value); }

    }

I used a code converter on the web. The problem is on line
//raise the RowClicked event
    if (RowClicked != null)
    {
        RowClicked(this, e);
    }

The error I'm getting is: The event 'RowClickGridView.RowClicked' can only appear on the left hand side of += or -=
Any ideas?

A: just remove the add/remove - parts:
public event EventHandler<GridViewRowClickedEventArgs> RowClicked;

A: I dont see anthing special here.  Id just use the standard event constructs and forget this custom stuff.

A: protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
{
   EventHandler<GridViewRowClickedEventArgs> temp = RowClicked ;
    //raise the RowClicked event
    if (temp != null)
    {
        temp(this, e);
    }
}

public event EventHandler<GridViewRowClickedEventArgs> RowClicked;

cf http://msdn.microsoft.com/en-us/library/db0etb8x.aspx


text:
Q: Connection to cloudant using Java I am currently referring to this github project to connect to cloudant using java. I am not sure where I am going wrong but am not able to connect
I am facing the following error message as shown in my console
java.lang.NoClassDefFoundError: com/cloudant/client/api/ClientBuilder
at com.controller.DisplayCheck(controller.java:61)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
Caused by: java.lang.ClassNotFoundException: com.cloudant.client.api.ClientBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:434)
at com.ws.bootstrap.ExtClassLoader.findClass(ExtClassLoader.java:204)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:665)
Here are my dependencies that i declared in my POM.xml
<dependencies>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
    <scope>compile</scope>
    </dependency>

    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.6</version>
    <scope>compile</scope>
    </dependency>

    <dependency>
    <groupId>com.cloudant</groupId>
    <artifactId>cloudant-http</artifactId>
    <version>2.12.0</version>
    <scope>compile</scope>
    </dependency>

    <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>mockwebserver</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.jmockit</groupId>
    <artifactId>jmockit</artifactId>
    <version>1.34</version>
    <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.littleshoot</groupId>
    <artifactId>littleproxy</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
    </dependency>

    </dependencies>

Below is my piece of code that I am trying to test from my controller.
CloudantClient client = ClientBuilder.account("account")
                .username("Id")
                .password("pas")
                .build();

        System.out.println("Server Version: " + client.serverVersion());
        List<String> databases = client.getAllDbs();
        System.out.println("All my databases : ");
        for ( String db : databases ) {
            System.out.println(db);
        }

Below are the imports used
import com.cloudant.client.api.ClientBuilder;
import com.cloudant.client.api.CloudantClient;

A: From the github link that you posted, you should have these two dependencies
<dependency>
  <groupId>com.cloudant</groupId>
  <artifactId>cloudant-client</artifactId>
  <version>2.12.0</version>
</dependency>

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp-urlconnection</artifactId>
  <version>3.8.1</version>
</dependency>

I see some sort of a resemblance to them in your dependencies, but its not quite them and thus I cant be sure what they are.


text:
Q: Jquery vertical accordion expand if active I don't know jquery well, so please don't judge me.
i have vertical menu with accordion effect, i want: if i click on child element, than accordion menu will not collapse, but stay expanded until i choose another element. Now menu collapses after every click.
My Accordion menu looks like:

         Menu item name

                  Level 2 item name

                  Level 2 item name2

Jquery script:
(function (e) {
var a = function () {};
e.extend(a.prototype, {
    name: "accordionMenu",
    options: {
        mode: "default",
        display: null,
        collapseall: !1,
        toggler: "span.level1.parent",
        content: "ul.level2",
        onaction: function () {}
    },
    initialize: function (a, b) {
        var b = e.extend({}, this.options, b),
            f = a.find(b.toggler);
        f.each(function (a) {
            var c = e(this),
                d = c.next(b.content).wrap("
").parent();
            d.data("height", d.height());
            c.hasClass("active") || a == b.display ? d.show() : d.hide().css("height", 0);
            c.bind("click", function () {
                g(a)
            })
        });
        var g = function (a) {
            var c =
                e(f.get(a)),
                d = e([]);
            c.hasClass("active") && (d = c, c = e([]));
            b.collapseall && (d = f.filter(".active"));
            switch (b.mode) {
            case "slide":
                c.next().stop().show().animate({
                    height: c.next().data("height")
                }, 400);
                d.next().stop().animate({
                    height: 0
                }, 400, function () {
                    d.next().hide()
                });
                setTimeout(function () {
                    b.onaction.apply(this, [c, d])
                }, 401);
                break;
            default:
                c.next().show().css("height", c.next().data("height")), d.next().hide().css("height", 0), b.onaction.apply(this, [c, d])
            }
            c.addClass("active").parent().addClass("active");
            d.removeClass("active").parent().removeClass("active")
        }
    }
});
e.fn[a.prototype.name] = function () {
    var h = arguments,
        b = h[0] ? h[0] : null;
    return this.each(function () {
        var f = e(this);
        if (a.prototype[b] && f.data(a.prototype.name) && "initialize" != b) f.data(a.prototype.name)[b].apply(f.data(a.prototype.name), Array.prototype.slice.call(h, 1));
        else if (!b || e.isPlainObject(b)) {
            var g = new a;
            a.prototype.initialize && g.initialize.apply(g, e.merge([f], h));
            f.data(a.prototype.name, g)
        } else e.error("Method " + b + " does not exist on jQuery." + a.name)
    })
}
})(jQuery);

A: you have to prevent click event on child elements from propagating
for example:

$('#parent').click(function(){alert('abcd')})

$('#parent').find('#list1').click(function(e){

   stopPropagation();
})

now click on the list2 will only show alert message


text:
Q: Connecting Android Application to MySQL Database hosted on AWS Good day everyone,
I have developed an android application and I would like to store my business information on MySQL database. I have decided to use amazon services for this project however I'm very confused how to allow my application to establish a proper/secure connection with MySQL database in order to pull and push the information into it. I have read many articles/stack overflow posts and realized I have to deploy a REST api in order to provide a layer between the application and the actual database. However with AWS being very confusing, in my opinion, i'm super lost.
Could any of you gentle folks provided with the step-by-step guide what services to use, how to connect them together and deploy them in order to be able to use it in my android application. Or maybe an article describing the steps? I don't really need a detailed explanation just a nudge in the right direction and I will try to figure out the rest.
Thank you greatly.

A: First of all, connecting to MySQL directly from an Android application is not secure, since you need the MySQL database access credentials for the app to communicate with the database.
This is why people recommend using a REST API Layer in between the MySQL database which you can implement using API Gateway and Lambda. This can be secured using a strong authentication mechanism for the API and using SSL for encrypting the messages at Transit.
However, this is not the case if you plan to connect to AWS DynamoDB from Android App. You can enforce Fine-Grained Access Permission to DynamoDB tables and roles using IAM policies.
Few Tutorials that might help,

*

*Serverless REST API in Minutes with Serverless Framework.

*Querying RDS MySQL with NodeJS Lambda Function.

*Using Mobile Hub (To Simplify Things).

*User Authentication with Cognito UserPools.


text:
Q: How does method_name= work under the hood? I was hacking a simple implementation of linked lists in Ruby and I came across something very peculiar.
I created a List class with an attr_accessor to a first_node. Something like this:
class List
  attr_accessor :first_node

  # Some code here ...
end

Then, while implementing the method delete_at I had the following error
linearly.rb:39:in `delete_at': undefined method `next' for nil:NilClass (NoMethodError)
    from linearly.rb:81:in `<main>'
This is a piece of the method:
def delete_at(position)
  if position == 0
    deleted_node = first_node
    first_node = first_node.next   # This is line 39.

    return deleted_node
  else
    # More code here ...

I forgot to use the class variable @first_node and instead I used the reader method first_node. Then, I started wondering why first_node returns nil when using first_node= in the same line.
Does it set @first_node to nil before setting a new value?
Notice that this piece of code works just fine:
def delete_at(position)
  if position == 0
    deleted_node = first_node
    first_node = deleted_node.next

    return deleted_node
  else
    # Some code here ...

EDIT:
This is how I call the implementation:
list = List.new
list.first_node = Node.new(1)
list.first_node.next = Node.new(2)
list.first_node.next.next = Node.new(3)

puts "Delete at 0"
puts list.delete_at(0)

A: This:
first_node = first_node.next

creates a local variable called first_node. Variable declarations are hoisted to the top of the scope in Ruby so your method is equivalent to:
def delete_at(position)
  deleted_node = nil # Declare deleted_node and first_node
  first_node = nil   # as local variables.
  if position == 0
    deleted_node = first_node
    first_node = deleted_node.next

    return deleted_node
  else
    # Some code here ...

That means that all first_node references in your method will be the local first_node variable rather than the getter and setting methods that attr_accessor creates for you.
Either don't use variables that match method names or be explicit about what you mean by supplying the self receiver for the method calls:
def delete_at(position)
  if position == 0
    deleted_node = self.first_node
    self.first_node = deleted_node.next
    #...

A: Are you sure @first_node has been set?  Instance variables will return nil when unset.
class Test
  attr_accessor :foo
  def print_foo
    puts "@foo=[#{@foo}]"
    puts "foo=[#{foo}]"
    puts @foo.nil?
  end
end

t1 = Test.new
t1.foo # => nil
t1.print_foo  # prints "@foo=[]" and "foo=[]" and returns true


text:
Q: How to decide the p and q for GARCH model? My question is simple. When shall I stop when trying the value for p and q?
I have got the loglikelihood from ARCH(1) to ARCH(10). It's increasing. And then I tried GARCH(1,1), GARCH(2,1) etc. The loglikelihood is always increasing so I'm confused. Do I need to continue to apply for larger lags until the log likelihood start to decrease? What argument shall I make when I stop trying?

A: As the commenters point out, increasing ARCH/GARCH orders amounts to including additional degrees of freedom, so the (log) likelihood is guaranteed to increase. If you simply follow this increase in (log) likelihood, you will overfit.
One possibility would be to balance the gain in (log) likelihood against model complexity by adding a penalty term. Information criteria like the AIC or BIC are helpful here.
Here is an alternative. ARCH and GARCH are fundamentally ways to forecast future volatility. They aim at producing good density forecasts, by modeling the conditional heteroskedasticity. So one way of choosing model orders would be to fit each model, then create density forecasts for a holdout sample and assess which model gives the best density forecast. Possible tools would be the Probability Integral Transform or (proper) scoring-rules.


text:
Q: react event target parent node Is it possible to get the event target's parent node on the virtual DOM?
In my basic react component I have a method which is triggered from onClick event, I would like to get the parent virtual DOM node properties.
handleClick(e){
    // The following code only gives me the actual DOM parent Node
    ReactDOM.findDOMNode(e.target).parentNode

}

A: Yes. React works on a virtual DOM model, and will update the real Browser DOM only if needed. The events in React work on a virtual DOM also and they are called synthetic events. If you find that you need the underlying browser level event for some reason, simply use the nativeEvent attribute to get it.
There are some constraints in React Virtual DOM that you may read from here:
Also, this may be helpful and explains the difference between the Virtual Dom and Browser DOM.

Browser DOM is just an abstraction of the on page elements, and React DOM would be an abstraction of that abstraction.
The render method of ReactDOM is crucial how we send React elements to Browser DOM:
var React = require('react');
var ReactDOM = require('react-dom');
var root = React.createElement('div');
ReactDOM.render(root, document.getElementById('example'));
        ^
        |---- Where React elements from React Virtual DOM enter the Browser DOM

In React we are dealing with React Elements and React Components.

Since React Element is a virtual representation of a DOM Element, to work with the events and catch the parents, you need to create React Components either of these three ways:

To navigate the parent inside the click Event for instance you may check this:
 var parent = this._reactInternalInstance._currentElement._owner._instance;

REF: is there any way to access the parent component instance in React? and http://jsfiddle.net/BinaryMuse/j8uaq85e/


text:
Q: OpenLayers - What exactly is the "document" element I use the function document.getElementById('...') but I don't get what exactly 'document' is ! I try to search where my bug is, I have a big problem in placing two types of markers (with 2 different GeoJSON files) ...

A: The document is the webpage content. You can read more here. document.getElementById let you access a particular element (a div or else) so you can modify its content.
In the context of OpenLayers, one would typically use it to display information in a div that is either overlaid over the map, or elsewhere in the page.


text:
Q: Swift set orientation to specific screen in code I want to programaticlly set a ViewController orientation and after dismissing the ViewController i want the orientation to return to previous mode
This is what i currently use:
if(GamePrefrences.orientation == "landscape")
    {
        value = UIInterfaceOrientation.LandscapeLeft.rawValue
    }
    else
    {
        value = UIInterfaceOrientation.Portrait.rawValue
    }

A:
You can override the preferredInterfaceOrientationForPresentation for
  a view controller that is intended to be presented full screen in a
  specific orientation.

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/


text:
Q: Unexpected EOF while parsing - Python I'm not sure what the issue is with my code but I get the error "Unexpected EOF while parsing" when attempting to go through my try and except code.
Here is the code that's causing problems:
`
def main():
    t = False
    while t != True:
        print('1) Addition\n')
        print('2) Subtraction\n')
        print('3) Division\n')
        print('4) Multiplication\n')
        print('5) Exponential\n')
        print('6) Exit\n')

        choice = input('Enter choice (from 1-6): ')
        try:
            send = input('Enter numbers (seperate by space: ')
            a, b = send.split(' ')
            a = int(a)
            b = int(b)
        except TypeError:
            print('Invalid Input')

main()

`
Any help is appreciated. Thank you.


text:
Q: How to put parameters into httpPost? Entity keeps giving me null for params I'm trying to send parameters to php to mysql via the POST method. It seems that my code doesn't load the parameters into httpPost. When debugging I see that params are null under httpPost variable and it seems that the entity isn't being picked up. Please any help would be greatly appreciated. I'm using android studio.
Main Activity
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void setSave(View view) {
    new TestSQL().execute();

}

private class TestSQL extends AsyncTask<String, String, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
        WriteToDatabase write = new WriteToDatabase();
        String a = "1";
        String b = "2";
        String c = "3";
        String d = "4";
        String e = "5";
        String f = "6";
        String g = "7";
        JSONObject json1 = write.writeDB(a, b,
                c, d, e, f, g);
        return json1;
    }
}

WriteToDatabase.java  to build List Namevaluepairs
public class WriteToDatabase {

private JSONParser test;

// URL of the PHP API
private static String link = "http://192.168.1.102/test/test2.php";

public JSONObject writeDB(String a,String b,
                          String  c, String d,String e,String f,String g) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("name", b));
    params.add(new BasicNameValuePair("description",
            c));
    params.add(new BasicNameValuePair("add", d));
    params.add(new BasicNameValuePair("city", e));
    params.add(new BasicNameValuePair("cat", a));
    params.add(new BasicNameValuePair("uid", f));
    params.add(new BasicNameValuePair("day", g));
    JSONParser test = new JSONParser();
    JSONObject json = test.getJSONFromUrl(link, params);

    return json;

}

}
my JSONParser.
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
     // With or without HTTP.UTF_8 won't work
        DefaultHttpClient httpClient = new DefaultHttpClient();
        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        httpPost.setEntity(ent);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            Log.i("RESPONSE", EntityUtils.toString(httpEntity));
        }
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
}

}
and my Logcat
11-15 21:30:04.273      818-836/com.example.julian.testforsql E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.IllegalStateException: Content has been consumed
        at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
        at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:100)
        at com.example.julian.testforsql.JSONParser.getJSONFromUrl(JSONParser.java:57)
        at com.example.julian.testforsql.WriteToDatabase.writeDB(WriteToDatabase.java:30)
        at com.example.julian.testforsql.MainActivity$TestSQL.doInBackground(MainActivity.java:62)
        at com.example.julian.testforsql.MainActivity$TestSQL.doInBackground(MainActivity.java:50)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:856)

A: Remove this line :
    if (httpEntity != null) {
        Log.i("RESPONSE", EntityUtils.toString(httpEntity));
    }

I just found out that calling EntityUtils.toString(httpEntity)) is counted for using the used (consumed) Entity hence getting you the exception.
I know this from @dvm's answer in this question (Thanks to him) :
IllegalStateException: Content has been consumed

A: For some reason, maybe of migrating from Eclipse to Android Studio, or some other reason I can't figure out, I was not able to put the parameters into the httpPost via the entity. I found thisenter link description here and followed the steps how to send it via json object and then modified my php code. The final result was:
MainActivity:
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public void setSave(View view) {
    new TestSQL().execute();

}

private class TestSQL extends AsyncTask<String, String, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
        WriteToDatabase write = new WriteToDatabase();
        String a = "1";
        String b = "2";
        String c = "3";
        String d = "4";
        String e = "5";
        String f = "6";
        String g = "7";
        JSONObject json1 = null;

        try {
            json1 = write.writeDB(a, b,
                    c, d, e, f, g);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        return json1;
    }
}

}
WriteTodatabase.class as if building parameters
public class WriteToDatabase {

// URL of the PHP API
private static String link = "http://192.168.1.102/test/test.php";

public JSONObject writeDB(String a,String b,
                          String  c, String d,String e,String f,String g) throws JSONException{

    JSONObject jsonObj = new JSONObject();
    jsonObj.put("name", b);
    jsonObj.put("description",c);
    jsonObj.put("add", d);
    jsonObj.put("city", e);
    jsonObj.put("cat", a);
    jsonObj.put("uid", f);
    jsonObj.put("day", g);

    JSONArray postjson=new JSONArray();
    postjson.put(jsonObj);

    JSONParser test = new JSONParser();
    JSONObject json = test.getJSONFromUrl(link, postjson,jsonObj);

    return json;

}

}
JSONparser
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, JSONArray postjson, JSONObject json) {

    // Making HTTP request
    try {

        HttpPost httpPost = new HttpPost(url);
        // Post the data:
        httpPost.setHeader("json", json.toString());
        httpPost.getParams().setParameter("jsonpost", postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);

        // for JSON:
        if (response != null) {
            InputStream is = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(sb.toString());
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return json;
}

}
and modified my php code. I had made it before by reading POST variables but now how to reassign them as such, I put this code at the top of php and then fed it with an insert statement to mysql:
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);

/  echo "--------------\n";
$_POST ['name'] = $data->name;
$_POST ['description']= $data->description;
$_POST ['add']= $data->add;
$_POST ['city']= $data->city;
$_POST ['uid']= $data->uid;
$_POST ['day']= $data->day;
$_POST ['cat']= $data->cat;

Hope this helps someone sometime.


text:
Q: Intersection of CGAL::Iso_rectangle_2 and CGAL::Ray_2 There is a function Object intersection(Type1<Kernel> obj1, Type2<Kernel> obj2) in CGAL which will return an object, representing intersection of two given objects of different possible types. It is said, that intersection of CGAL::Iso_rectangle_2 (rectangle with sides parallel to the x and y axis) and CGAL::Ray_2 (oriented ray outgoing from given point) is either CGAL::Point_2 or CGAL::Segment_2 (just point or segment).
And what about the case when ray intersects rectangle in two points? Cannot see anything about it in the manual.

A: Answered by Sebastien Loriot in cgal-discuss mailing list:

The iso_rectangle is considered as full so that what you call
  the two point case is the segment one.


text:
Q: Losing power in the UK vs US: what's more common? Which of the following is more common in British English vs American English?

*

*Power cut

*Power outage

*Power failure

*Blackout

A: "Power cut" is certainly the most common in the UK, as seen in the comments.  Lexico Oxford Dictionaries gives the phrase the "British" tag.
On Google News, almost all of the news is UK stories, and it's the same story ;-) for power outage in the US.
As for blackout being used as a term for a mass outage in the UK, the fairly recent mass power cut that affected the nation is indeed referred to as a blackout more often than power cut.
"Power outage" is often used to refer to a more local failure, whereas "Power failure" is almost never heard, clearly shown on NGrams:
"Blackout" is also seemingly used to mean a wide-scale outage in the US, as shown in News as well.
"Power failure" doesn't seem that popular either, and as it's a UK term, "power cut" is close to nonexistent. (where "cut" is used, it's usually published by a UK news site).

A: I heard "outage" being used in a film set in 1940s England - which led me here. I never heard the term "outage" before this millennium. I have only used and heard "power cut" before, whether the cause was accidental or planned.

A: The Google NGrams corpus search on all four, for UK and US separately are shown here:

Blackout seems to be by far the most popular in both the UK and US, then 'power failure'. 'Power outage' and 'power cut' both seem to be rare in the US.


text:
Q: What does "use their washing machine" refer to or imply in this sentence? I have trouble in understanding the metaphor or whatever implied meaning of "how many people use their washing machine". Nor could I understand WHY he was asked "when was the last time they had left the country". I seriously not get it at all, though I understand every meaning of the words.
The context is : "Dad" is a fifty-five year old man who was recently got fired and he had tried several job interviews without any success. So he decided to apply for benefits. During the filling of the forms for applying , he was asked to answer some questions.
Here is the sentence:

After a fortnight of rejections, he and Mum admitted they would have
  to apply for benefits, just to tide them over, and spent their
  evenings poring over incomprehensible, fifty-page forms which asked
  how many people used their washing machine, and when was the last time
  they had left the country (Dad thought it might have been 1988).
Me Before You by Jojo Moyes

A: Applying for unemployment benefits can be a difficult process. Invasive and seemingly arbitrary questions such as "how many people use your washing machine" are used to determine household size or how many dependents (e.g. children) an applicant has. Many government forms ask about overseas trips for security purposes, but here the likely intent is to assess the applicant's wealth or economic status.
The point is that the questions are tiresome, specific, and hard to answer, invasive, etc.