text:
Q: Spring Boot Multiple Datasource I'm quite new to spring boot and I'd like to create a multiple datasource for my project.
Here is my current case. I have two packages for entity for multiple database. Let's say
com.test.entity.db.mysql ; for entities that belong to MySql
com.test.entity.db.h2 ; for entities that belong to H2 Databases

So, currently I have two entities class
UserMySql.java
@Entity
@Table(name="usermysql")
public class UserMysql{

    @Id
    @GeneratedValue
    public int id;

    public String name;

}

UserH2.java
@Entity
@Table(name="userh2")
public class Userh2 {

    @Id
    @GeneratedValue
    public int id;

    public String name;
}

I'd like to achieve a configuration where if I create user from UserMySql, it will be saved to MySql Database, and if I create user from Userh2 it will be saved to H2 Databases. So, I also have two DBConfig, let's say MySqlDbConfig and H2DbConfig.
(com.test.model is package where I'll put my Repositories class. It will be defined below)
MySqlDbConfig.java
@Configuration
@EnableJpaRepositories(
    basePackages="com.test.model",
    entityManagerFactoryRef = "mysqlEntityManager")
public class MySqlDBConfig {

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.test.mysql")
public DataSource mysqlDataSource(){
    return DataSourceBuilder
            .create()
            .build();
}

@Bean(name="mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource())
            .packages("com.test.entity.db.mysql")
            .build();
}

}

H2DbConfig.java
@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "h2EntityManager")
public class H2DbConfig {

@Bean
@ConfigurationProperties(prefix="datasource.test.h2")
public DataSource h2DataSource(){
    return DataSourceBuilder
            .create()
            .driverClassName("org.h2.Driver")
            .build();
}

@Bean(name="h2EntityManager")
public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(h2DataSource())
            .packages("com.test.entity.db.h2")
            .build();
}
}

My application.properties file
#DataSource settings for mysql
datasource.test.mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/test
datasource.test.mysql.username = root
datasource.test.mysql.password = root
datasource.test.mysql.driverClassName = com.mysql.jdbc.Driver

#DataSource settings for H2
datasource.test.h2.jdbcUrl = jdbc:h2:~/test
datasource.test.h2.username = sa

# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.validation-query=SELECT 1

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.show_sql = true
spring.jpa.hibernate.format_sql = true

server.port=8080
endpoints.shutdown.enabled=false

And then for crud I have UserMySqlDao and UserH2Dao
UserMySqlDao.java
@Transactional
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{

    public UserMysql findByName(String name);
}

UserH2Dao.java
@Transactional
@Repositories
public interface UserH2Dao extends CrudRepository<Userh2, Integer>{

    public Userh2 findByName(String name);
}

And for last, I have an UserController as endpoint to access my service
UserController.java
@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private UserMysqlDao userMysqlDao;

@Autowired
private UserH2Dao userH2Dao;

@RequestMapping("/createM")
@ResponseBody
public String createUserMySql(String name){
    UserMysql user = new UserMysql();
    try{
        user.name = name;
        userMysqlDao.save(user);
        return "Success creating user with Id: "+user.id;
    }catch(Exception ex){
        return "Error creating the user: " + ex.toString();
    }
}

@RequestMapping("/createH")
@ResponseBody
public String createUserH2(String name){
    Userh2 user = new Userh2();
    try{
        user.name = name;
        userH2Dao.save(user);
        return "Success creating user with Id: "+user.id;
    }catch(Exception ex){
        return "Error creating the user: " + ex.toString();
    }
}
}

Application.java
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EntityScan(basePackages="com.test.entity.db")
@ComponentScan
public class Application {

public static void main(String[] args) {
    System.out.println("Entering spring boot");
    ApplicationContext ctx = SpringApplication.run(Application.class, args);

    System.out.println("Let's inspect the beans provided by Spring Boot:");
    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
        System.out.print(beanName);
        System.out.print(" ");
    }

    System.out.println("");
}

}

With this configuration my Spring boot run well, but when I access
http://localhost/user/createM?name=myname it writes an exception

Error creating the user: org.springframework.dao.InvalidDataAccessResourceUsageException:   could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement

I've googling around and haven't got a solution yet. Any ideas why this exception occurs? And is this the best way to implement multiple datasource to implement my case above? I'm open to full refactor if needed.
Thanks

A: I faced same issue few days back, I followed the link mentioned below and I could able to overcome the problem
http://www.baeldung.com/spring-data-jpa-multiple-databases

A: I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.

A: I solved the problem (How to connect multiple database using spring and Hibernate) in this way, I hope it will help :)
NOTE: I have added the relevant code, kindly make the dao with the help of impl I used in the below mentioned code.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>MultipleDatabaseConnectivityInSpring</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
     <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
    </servlet>
     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml
        </param-value>
    </context-param>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="localPersistenceUnitOne"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>in.india.entities.CustomerDetails</class>
        <exclude-unlisted-classes />
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.jdbc.batch_size" value="0" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankar?sslmode=require" />
            <property name="hibernate.connection.username" value="username" />
            <property name="hibernate.connection.password" value="password" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
    <persistence-unit name="localPersistenceUnitTwo"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>in.india.entities.CompanyDetails</class>
        <exclude-unlisted-classes />
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.jdbc.batch_size" value="0" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankarTwo?sslmode=require" />
            <property name="hibernate.connection.username" value="username" />
            <property name="hibernate.connection.password" value="password" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>

dispatcher-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
    default-autowire="byName"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="in.india.*" />
    <bean id="messageResource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        autowire="byName">
        <property name="basename" value="messageResource"></property>
    </bean>

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

    <bean id="entityManagerFactoryOne"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        autowire="constructor">
        <property name="persistenceUnitName" value="localPersistenceUnitOne" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        autowire="byName">
        <property name="basename" value="messageResource" />
    </bean>

    <bean id="entityManagerFactoryTwo"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        autowire="constructor">
        <property name="persistenceUnitName" value="localPersistenceUnitTwo" />
    </bean>

    <bean id="manager1" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoryOne" />
    </bean>

    <bean id="manager2" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoryTwo" />
    </bean>

    <tx:annotation-driven transaction-manager="manager1" />
    <tx:annotation-driven transaction-manager="manager2" />

    <bean class="in.india.service.dao.impl.CustomerServiceImpl" />
    <bean class="in.india.service.dao.impl.CompanyServiceImpl" />

    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <bean
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</beans>

java class to persist into one database
package in.india.service.dao.impl;

import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

public class CompanyServiceImpl implements CompanyService {

    @PersistenceContext(unitName = "entityManagerFactoryTwo")
    EntityManager entityManager;

    @Transactional("manager2")
    @Override
    public boolean companyService(CompanyDetails companyDetails) {

        boolean flag = false;
        try
        {
            entityManager.persist(companyDetails);
            flag = true;
        }
        catch (Exception e)
        {
            flag = false;
        }

        return flag;
    }

}

java class to persist in another database
package in.india.service.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;

public class CustomerServiceImpl implements CustomerService {

    @PersistenceContext(unitName = "localPersistenceUnitOne")
    EntityManager entityManager;

    @Override
    @Transactional(value = "manager1")
    public boolean customerService(CustomerDetails companyData) {

        boolean flag = false;
        entityManager.persist(companyData);
        return flag;
    }
}

customer.jsp
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

SpringWithMultipleDatabase's

    <form:form method="GET" action="addCustomer.htm"  modelAttribute="customerBean" >

                <form:label path="firstName">First Name</form:label>
                <form:input path="firstName" />

                <form:label path="lastName">Last Name</form:label>
                <form:input path="lastName" />

                <form:label path="emailId">Email Id</form:label>
                <form:input path="emailId" />

                <form:label path="profession">Profession</form:label>
                <form:input path="profession" />

                <form:label path="address">Address</form:label>
                <form:input path="address" />

                <form:label path="age">Age</form:label>
                <form:input path="age" />

                <input type="submit" value="Submit"/>

    </form:form>

company.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>

SpringWithMultipleDatabase's

 <form:form method="GET" action="addCompany.htm"  modelAttribute="companyBean" >

        <form:label path="companyName">Company Name</form:label>
        <form:input path="companyName" />

        <form:label path="companyStrength">Company Strength</form:label>
        <form:input path="companyStrength" />

        <form:label path="companyLocation">Company Location</form:label>
        <form:input path="companyLocation" />

            <input type="submit" value="Submit"/>

 </form:form>

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>

Multiple Database Connectivity In Spring sdfsdsd

Click here to go on Customer page

Click here to go on Company page

success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>

SpringWithMultipleDatabase

    Successfully Saved

CompanyController
package in.india.controller;

import in.india.bean.CompanyBean;
import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CompanyController {

    @Autowired
    CompanyService companyService;

    @RequestMapping(value = "/companyRequest.htm", method = RequestMethod.GET)
    public ModelAndView addStudent(ModelMap model) {
        CompanyBean companyBean = new CompanyBean();
        model.addAttribute(companyBean);
        return new ModelAndView("company");
    }

    @RequestMapping(value = "/addCompany.htm", method = RequestMethod.GET)
    public ModelAndView companyController(@ModelAttribute("companyBean") CompanyBean companyBean, Model model) {
        CompanyDetails  companyDetails = new CompanyDetails();
        companyDetails.setCompanyLocation(companyBean.getCompanyLocation());
        companyDetails.setCompanyName(companyBean.getCompanyName());
        companyDetails.setCompanyStrength(companyBean.getCompanyStrength());
        companyService.companyService(companyDetails);
        return new ModelAndView("success");

    }
}

CustomerController
package in.india.controller;

import in.india.bean.CustomerBean;
import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomerController {

    @Autowired
    CustomerService customerService;

    @RequestMapping(value = "/customerRequest.htm", method = RequestMethod.GET)
    public ModelAndView addStudent(ModelMap model) {
        CustomerBean customerBean = new CustomerBean();
        model.addAttribute(customerBean);
        return new ModelAndView("customer");
    }

    @RequestMapping(value = "/addCustomer.htm", method = RequestMethod.GET)
    public ModelAndView customerController(@ModelAttribute("customerBean") CustomerBean customer, Model model) {
        CustomerDetails customerDetails = new CustomerDetails();
        customerDetails.setAddress(customer.getAddress());
        customerDetails.setAge(customer.getAge());
        customerDetails.setEmailId(customer.getEmailId());
        customerDetails.setFirstName(customer.getFirstName());
        customerDetails.setLastName(customer.getLastName());
        customerDetails.setProfession(customer.getProfession());
        customerService.customerService(customerDetails);
        return new ModelAndView("success");

    }
}

CompanyDetails Entity
package in.india.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "company_details")
public class CompanyDetails {

    @Id
    @SequenceGenerator(name = "company_details_seq", sequenceName = "company_details_seq", initialValue = 1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_details_seq")
    @Column(name = "company_details_id")
    private Long companyDetailsId;
    @Column(name = "company_name")
    private String companyName;
    @Column(name = "company_strength")
    private Long companyStrength;
    @Column(name = "company_location")
    private String companyLocation;

    public Long getCompanyDetailsId() {
        return companyDetailsId;
    }

    public void setCompanyDetailsId(Long companyDetailsId) {
        this.companyDetailsId = companyDetailsId;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Long getCompanyStrength() {
        return companyStrength;
    }

    public void setCompanyStrength(Long companyStrength) {
        this.companyStrength = companyStrength;
    }

    public String getCompanyLocation() {
        return companyLocation;
    }

    public void setCompanyLocation(String companyLocation) {
        this.companyLocation = companyLocation;
    }
}

CustomerDetails Entity
package in.india.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "customer_details")
public class CustomerDetails {

    @Id
    @SequenceGenerator(name = "customer_details_seq", sequenceName = "customer_details_seq", initialValue = 1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_details_seq")
    @Column(name = "customer_details_id")
    private Long customerDetailsId;
    @Column(name = "first_name ")
    private String firstName;
    @Column(name = "last_name ")
    private String lastName;
    @Column(name = "email_id")
    private String emailId;
    @Column(name = "profession")
    private String profession;
    @Column(name = "address")
    private String address;
    @Column(name = "age")
    private int age;
    public Long getCustomerDetailsId() {
        return customerDetailsId;
    }

    public void setCustomerDetailsId(Long customerDetailsId) {
        this.customerDetailsId = customerDetailsId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

A: Update 2018-01-07 with Spring Boot 1.5.8.RELEASE
If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.
You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/
I copied some code here.
First you have to set application.properties like this
#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:
@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example
@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:
@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like
@Transactional //this will use the first datasource because it is @primary

or
@Transactional("tm2")

This should be enough. See example and detail in the link above.

A: Use multiple datasource or realizing the separation of reading & writing.
you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.
Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.
dbServer:
  default: localhost:3306
  read: localhost:3306
  write: localhost:3306
datasource:
  default:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: default
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  read:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: read
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  write:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: write
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false

A: Using two datasources you need their own transaction managers.
@Configuration
public class MySqlDBConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.test.mysql")
    public DataSource mysqlDataSource(){
         return DataSourceBuilder
                 .create()
                 .build();
    }

    @Bean("mysqlTx")
    public DataSourceTransactionManager mysqlTx() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    // same for another DS
}

And then use it accordingly within @Transaction
@Transactional("mysqlTx")
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
    public UserMysql findByName(String name);
}

A: Thanks all for your help but it is not complicated as it seems; almost everything is handled internally by SpringBoot.
In my case I want to use Mysql and Mongodb and the solution was to use EnableMongoRepositories and EnableJpaRepositories annotations on to my application class.
@SpringBootApplication
@EnableTransactionManagement
@EnableMongoRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
@EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
class TestApplication { ...

NB: All mysql entities have to extend JpaRepository and mongo enities have to extend MongoRepository.
The datasource configs are straight forward as presented by spring documentation:
//mysql db config
spring.datasource.url= jdbc:mysql://localhost:3306/tangio
spring.datasource.username=test
spring.datasource.password=test

#mongodb config
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=tangio
spring.data.mongodb.username=tangio
spring.data.mongodb.password=tangio
spring.data.mongodb.repositories.enabled=true

A: once you start work with jpa and some driver is in your class path spring boot right away puts it inside as your data source (e.g h2 )
for using the defult data source therefore u will need only to define
spring.datasource.url= jdbc:mysql://localhost:3306/
spring.datasource.username=test
spring.datasource.password=test

if we go one step farther and u want to use two
    I would reccomend to use two data sources such as explained here :
    Spring Boot Configure and Use Two DataSources

A: MySqlBDConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{

@Autowired
private Environment env;

@Bean(name="mysqlProperities")
@ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
    return new  DataSourceProperties();
}

@Bean(name="mysqlDataSource")
public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
    return dataSourceProperties.initializeDataSourceBuilder().build();

}

@Primary
@Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}

@Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){
    return new JpaTransactionManager(factory);
}
}

H2DBConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{

        @Autowired
        private Environment env;

        @Bean(name="dsProperities")
        @ConfigurationProperties(prefix="spring.h2")
        public DataSourceProperties dsProperities(){
            return new  DataSourceProperties();
        }

    @Bean(name="dsDataSource")
    public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();

    }

    @Bean(name="dsEmFactory")
    public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean em =  builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
        HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(ven);
        HashMap<String, Object> prop = new HashMap<>();
        prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
        prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));

        em.setJpaPropertyMap(prop);
        em.afterPropertiesSet();
        return em;
    }

    @Bean(name="dsTransactionManager")
    public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){
        return new JpaTransactionManager(factory);
    }
}

application.properties
#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------

#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------

#------JPA-----
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Application.java
@SpringBootApplication
public class Application {

    public static void main(String[] args)   {
        ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
        UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
        //for exemple save a new user using your repository
        userRepository.save(new UserMysql());

    }
}


text:
Q: How to build Ansible Playbook without username/password I am new to Ansible and started learning and working on Ansible Playboks especially on network automation. Part of our hosting infra, inorder to login to any device we have default script runs to ssh into the device, something like goto . Hence no need to give any username and password, it directly logs into the device.
How we can include this customization in Ansible playbook without using any username or password.

A: Ansible supports using ssh keys.

Confirm that you can connect using SSH to all the nodes in your inventory using the same username. If necessary, add your public SSH key to the authorized_keys file on those systems.

Refer to documentation here
Also, it is a good idea to read the 'getting started' page

A: You will still need to supply a Username, that the SSH Key belongs to:
Guide on Setting up an SSH key for a Linux User: Here
Once SSH Key is configured and Copied over to your Ansible Server:
Edit the Sudoers File on the Slave Node and set NOPASSWD for the user, that way your user won't be prompted for a password when you are duing Sudo Commands: Reference Here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why might Ironsides and the USS constitution be hostile with me? I'm pretty late in the game so I guess I could have done something. As far as I can remember I have had no direct with this ship or crew. I read that this was a cool mission with a legendary gun reward. Is there a way to fix this so that they are no longer hostile?
I am playing on Xbox One.

A: As mentioned in the notes on the quest's wikia page, there are a few ways you can inadvertently fail this quest:

*

*If your companion is wearing power armor that has Tesla Coils, it may trigger hostility in the robots, causing you to fail the mission.

*If Preston Garvey accompanies the Sole Survivor the robots will become hostile. To avoid failing the quest, simply walk around them and they will only attack Preston.

Do either of these sound like they may have been the cause?


text:
Q: Looking for graph#tree transformer usage examples I'm writing new transpiler compiler of my programming language Ya. Since the AST Abstract Syntax Tree transformations and output language code generations is a big deal then I'm looking to use existing tree#graph transformers  and  output generators = pretty printers.
Yet up now failed to find the tool since failed to find use examples.
The list of promising tools that I've read about:

*

*Spoofax + Stratego/XT : have not found source code up now; or maybe found but it's in Java that disallows to evaluate the power of Stratego lang.

*Rascal MPL. It has only JVM execution => as initial C++ follower I'm in trouble to use it if to.

*OBJ OBJ3 Maude. Know nothing.

And also have found:

*

*Coctail http://cocolab.com costs €3K so with hidden source code so can't see it's source code as best example of use => can't evaluate it's power. €3K also near to disable this for me.

Questions:

*

*Are there other tree#graph transformation tools#langs # outputers of source code text from AST_like data?

*Looking for graph#tree transformer good+big+complex usage examples. Expecting that compiler source code is the best case.

*All ideas for Spoofax Stratego/XT Rascal Obj are welcome.

A: Your question is very broad and I will try to answer it from the Rascal perspective.
First, Rascal provides extensive support for both concrete and abstract syntax trees. The former are concrete parse trees including all lexical information and can be very conveniently traversed, analyzed and transformed. Preserving all textual information is important for reengineering applications but is convenient in compiler writing as well. The latter are abstract data types (typed trees) that can be traversed and transformed as well.
Second, Rascal provides built-in data types like maps, sets and relations that can be used to conveniently compute with relational data. In fact, many relational algebra operators such as join and transitive closure are built-in. We use this all the time to manipulate graph-like data.
Third, Rascal provides sophisticated string templates for, amongst others, code generation.
Fourth, it is correct that the Rascal implementation is based on the JVM and JVM byte code generation. However, we package Rascal applications as self-contained jars, hence a tool written in Rascal can be deployed and executed independently.
Finally, there are many usage examples including several large compilers, source code analysis, many DSLs (both in research and commercial), and other applications.
Hope this can further help you in your explorations!


text:
Q: Flutter Getx on list view error the improper use of a GetX has been detected I am trying to use Getx on simple ListView but its showing error that [Get] the improper use of a GetX has been detected.
  Widget getBody() {
    var size = MediaQuery.of(context).size;
    final controller = Get.put(PassionController());

    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.only(left: 30, right: 30),
        child: Column(
          children: [
            GetX<PassionController>(
                builder: (_) => ListView.builder(
                    itemCount: controller.passionItems.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title:
                            Text('Number: ${controller.passionItems[index]}'),
                      );
                    })),
            GestureDetector(
              onTap: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (_) => MyHomePage()));
              },
              child: Container(
                width: size.width,
                height: 55,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(30), color: Colors.white
                    // gradient:
                    //     LinearGradient(colors: [primary_one, primary_two])

                    ),
                child: Center(
                  child: Text(
                    "Continue",
                    style: TextStyle(
                        color: kPrimarycolor,
                        fontSize: 18,
                        fontWeight: FontWeight.w500),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

I also try GetxBuilder but same error showing. I already wrap GetMaterial on main.dart


text:
Q: pandoc | How to convert nested tables? | longtable vs tabular I've successfully converted Jupyter HTML-format simple tables to LaTex-format tables using pandoc.read(raw.text, 'html').blocks in a lua filter.  The resulting LaTex is \begin(longtable} …  That's okay for simple tables, but longtable does not support nested tables, which I do need.
How to convert to LaTex tabular tables (which support nested tables) rather than to longtable tables (which do not)?  Or is there some other solution to converting nested tables?

A: I've come to better overall solution.  Rather than have pandoc convert HTML tables to LaTex tables, I've coded the tables in both HTML and LaTex format within the Jupyter notebook.  The HTML representation will be rendered when running Jupyter; the LaTex representation will be copied as-is by pandoc when converting from Jupyter-format to LaTeX format.
x = data.frame(a=c(1,2,3), b=c(10,20,30), c=c(100,200,300))
x.html = kable(x, format="html", escape=FALSE, align=rep("r", ncol(x)), caption="This is from HTML", row.names=FALSE, table.attr="style="white-space: nowrap;"")
x.latex = kable_styling(latex_options=c("hold_position"),
kable(x, format="latex", escape=FALSE, align=rep("r", ncol(x)), caption="This is from LaTex", row.names=FALSE))
mbx = list(data=list("text/html"=as.character(x.html), "text/latex"=as.character(x.latex)), metadata=NULL)
publish_mimebundle(mbx$data, mbx$metadata)


text:
Q: Sectioned RecyclerView in mvvmcross android I'm trying to make a RecyclerView look like the following Sections
I'm using mvvmcross and the xml I have so far is this:
<MvvmCross.Droid.Support.V7.RecyclerView.MvxRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    fab:MvxBind="ItemsSource EmballageGroups"
    fab:MvxTemplateSelector="Hocras.OnRoute.Droid.TypeTemplateSelector,Hocras.OnRoute.Droid" />

But this is a simple list without sections. How do I get sections in there? (it has to be sectioned per product type)

A: Have a look at the sample here https://github.com/MvvmCross/MvvmCross-Samples/tree/master/WorkingWithCollections
It uses MvxExpandableListView
<Mvx.MvxExpandableListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    local:MvxItemTemplate="@layout/listitem_kitten"
    local:MvxGroupItemTemplate="@layout/listitem_expandablegroup"
    local:MvxBind="ItemsSource KittenGroups" />

A: Android ExpandableListView is a view that shows items in a vertically scrolling two-level list. It differs from a ListView by allowing two levels which are groups that can be easily expanded and collapsed by touching to view and their respective children items.
ExpandableListViewAdapter in android loads the data into the items associated with this view.
Following are some important methods that are used by this class :
please find complete information into below link
Android ExpandableListView


text:
Q: Where is a value type object stored in swift? I declared an object of Array, like:
let data = ["foo", "bar"]

Array type in swift is value type, where is it stored? heap or stack?
I guess it is stored in heap, but how to access it?
And does it follow ARC rule, when will it release?
Can you give me the graphic of the object's memory?

A: Given the empty array:
let data = Array<Any>()

Array type in swift is value type, where is it stored? heap or stack?

This is a constant, empty array, so it is stored nowhere. Literally nowhere. If it had some elements in it, the boxes for them would be stored on the stack. The contents of those boxes might be stored on the stack or heap depending on the size. If it had more elements, the boxes would also be stored on the heap.

And does it follow ARC rule, when will it release?

Value types are destroyed when their referent goes out of scope, so whenever data leaves scope. ARC is not relevant here. That said, if there are other reference of the backing (heap) storage, then that storage may not be destroyed until later and ARC is totally relevant (but completely internal, so not related to data).

Can you give me the graphic of the object's memory?

In the case given, the graphic of object memory is:

That's it. There is no memory. But if you put things in it, then it would wildly depend on what you put it in it.
I know I'm being incredibly flippant here. That's on purpose. The answer is "it depends, and also, in most cases, you shouldn't care, and in all cases, it's an internal implementation detail that is not promised and can change from release to release."
The time where you do care is when there's a performance concern, and then you care a lot. Unfortunately, Swift gives almost no promises about that. Even so, we do have a lot of specific information from the Swift team. The best resource is Understanding Swift Performance from WWDC 2016 which explains the internal memory layout. It is likely nothing like you're expecting, and it is incredibly dependent on the specifics of the array. Given the array you've asked about, the answer is "nowhere; it's empty."

A: In Swift or other language, by default, Value type is stored in Stack and Reference Type is stored in Heap.
If the value is part of a reference type, then, it's stored in Heap.
So we don't need a reference counting and the value will be clean after the end of its scope, or in the other case, when the container is released.
In your example: the data of Array instance will be stored in Stack of the Application while its elements can be stored in Heap, depend on the element is reference type or value typed.


text:
Q: Blazor hosted - authorize immediately before displaying application Can anybody give me a helping push to get my hosted Blazor application (Client, Server and Shared) to request a login immediately, before the application is initially shown. I want the experience that a user must log in before accessing the application at all.
My starting point is the Blazor Webassembly (hosted) template with Api Authorization (Individual User Accounts)
Using the Authorize attribute on either server-side actions or a client-side Razor page will not initiate the authentication flow before the specific action/page with the Authorize attribute is being requested by the user. How would I go about having the authorization flow kicked off as the first thing, before the application is even displayed for the first time?
I am sure this is possible and even trivial for somebody more savvy than me. Can anybody give me a shove in the right direction, please?

A: I created a control RedirectToLogin.razor
@inject NavigationManager Navigation
@code {
    protected override void OnInitialized()
    {
        String thisPage = Navigation.Uri.Replace(Navigation.BaseUri, "~/");
        Navigation.NavigateTo($"Identity/Account/Login?returnUrl={thisPage}");
        base.OnInitialized();
    }
}

And then inserted it into the mainlayout.razor
<div class="container-fluid">
 <AuthorizeView>
        <Authorized>
            <NavigationLogger />
            <ContextMenuMouseClick>
                <MenuTopBar />
                <NavMenu />
                <SubPageContainer>
                    @Body
                </SubPageContainer>
            </ContextMenuMouseClick>
        </Authorized>
        <NotAuthorized>
            <RedirectToLogin />
        </NotAuthorized>
</AuthorizeView>
</div>

So when the layout is loaded and it is in the NotAuthorized state it will redirect to the login page and after authorising  will return to the page it was trying to access.
Hope this helps.

A: The Blazor Client is bootstrapped from a static index.html in the wwwroot. In the Server project this is mapped to an Endpoint in the Startup.cs, basically a catch-all to all endpoints not taken by your Razor Pages or Controllers:
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("index.html");
});

For your scenario:

*

*Create a new layout in Server, say _LayoutBlazor.cshtml

*Re-create the contents of the index.html from the Client. Note that the _framework files from the Client are copied to the Server wwwroot upon build:
:
<app>Loading...</app>
<script  src="@Href("~/_framework/blazor.webassembly.js")"></script>

*Create a new Razor page and put the "Authorize" tag on it and use the _LayoutBlazor.

*Remove the endpoints.MapFallbackToFile("index.html"); from Startup.cs
Mark Gould has created a proof of concept here: RazorBlazor


text:
Q: How can I remove a class inside my table with "$(this)" I want to remove the class fail from the first table row when I click inside img with id="rollback1" without removing the class fail from the table row two.

I tried this:
$("#rollback1").on('click',function(){
 $(this).find('.fail').removeClass();
});

And also this:
$("#rollback1").on('click',function(){
 $(this).prev().removeClass();
});

$("#rollback1").on('click',function(){
 $(this).closest('.fail').removeClass();
});

Still, can't figure out, how i can remove a class from just one row.

A: You could do it like:
$(this).closest('tr').find('td.fail').removeClass('fail');

You could use id and start with selector ^= like:
$("[id^=rollback]").on('click', function() {
    $(this).closest('tr').find('.fail').removeClass('fail');
});

$("[id^=rollback]").on('click', function() {
  $(this).closest('tr').find('.fail').removeClass('fail');
});
.fail {
  background-color: red;
}

    TD 1

    TD 1

My suggestions: I suggest one of the following solutions :

*

*Target by img tag like :
$("table img").on('click', function() {
   //Your code
});

*Use common class instead like :
$(".rollback").on('click', function() {
   //Your code
});

Then your HTML code must be like :

A:  $("#rollback1").on('click',function(){
 $(this).parent().find('.fail').removeClass();
 });

A: If #rollback2 should do the same on the second row, you could do something more generic:
$('img[id^="rollback"]').on('click', function(e) {
    e.preventDefault();
    $(this).closest('tr').find('.fail').removeClass('fail');
});

A: The closest() method returns the first ancestor of the selected element.
An ancestor is a parent, grandparent, great-grandparent, and so on.
And the find() method returns descendant elements of the selected element.
$(this).closest('tr').find('.fail').removeClass('fail');

A: You can target the element with parent() and prev() like the following way:

$("#rollback1").on('click',function(){
  $(this).parent().prev('.fail').removeClass('fail');
  // if you have `td` in between use siblings()
  //$(this).parent().siblings('.fail').removeClass('fail');
});
.fail{color:red;}

   11

    22

A: Try this:
$("#rollback1").on('click', function() {
 $(this).closest('table').find('tr:nth-child(1)').removeClass('fail');
});


text:
Q: Ubuntu 18 LTS & 20 LTS freeze on boot from USB I'm in the process of repurposing an old-to-me PC into a home server. I've been trying to install Ubuntu on it, but when I boot from a USB, Ubuntu freezes at the initial Ubuntu boot up screen. This happens both when I "Try Ubuntu without installing" and "Try Ubuntu without installing (safe graphics)". This happens both with Ubuntu 18 and Ubuntu 20. I've been creating the bootable USB with Rufus 3.13 on Windows 10.
Things I've Tried:

*

*Disabling secure boot in the BIOS

*Tried both Ubuntu 18 and 20

*Reformatting the USB when creating the bootable USB

*Adding nomodeset to the boot options Source

*Adding nouveau.noaccel=1 instead of nomodeset to the boot options

*Replacing quiet splash with noapic noacpi nosplash irqpoll

*Adding acpi=off to the boot options Source
Computer Specs:

*

*Ryzen 7 1800X

*EVGA GTX 760 SC (temporary GPU)

*ASUS ROG Strix B450-F Gaming

*32 GB Corsair Vengeance RAM (forget the speed)

I've pretty much tried everything I can think of at this point. Any suggestions would be much appreciated! Thanks in advance!

A: Update for anyone who stumbles upon this post: I have found the solution! I can't find where I read it, but apparently Ubuntu or Linux can have a voltage issue where it thinks (or actually doesn't) have enough power to function. Fixes for this include: unplugging your mouse; ensuring your mouse and keyboard aren't plugged in next to each other; or unplugging unused drives in your PC. Unplugging the mouse did it for me.


text:
Q: how to run bash script from Docker Image I have created a docker image from a Dockerfile. Projects working perfectly. I've a few tests and to invoke those tests I've created a run_tests.sh file, I've made the file executable too.
So, when I run docker run -it --rm <image_name> run_tests.sh it should output the test result, instead it outputting server ip address it listening to.
How to run bash script from a Docker Image without entering it's shell?
This is my Dockerfile...
FROM python:3.8-slim-buster

RUN pip install --upgrade pip
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /app

COPY requirements.txt /app/requirements.txt

# install dependencies
RUN pip install -r requirements.txt
RUN apt-get update
RUN apt-get install gnupg -y

# copy project
COPY . /app/

# making executable test file and entrypoint file for bash shell
RUN chmod +x run_tests.sh
RUN chmod +x entrypoint.sh

COPY ./entrypoint.sh /
ENTRYPOINT ["sh", "/entrypoint.sh"]

A: You can run achieve that by running:
docker run --rm --entrypoint '' <image_name> /bin/bash -c './run_tests.sh'

or
docker run --rm --entrypoint '' <image_name> sh -c './run_tests.sh'

in case your image has only sh available
In either case, you are just running a container from the desired image and then running either /bin/bash or sh with the -c flag, that allows you to define the command to run from a string. Also, by setting --entrypoint '', you are overriding the default entrypoint set on the Dockerfile. When you have an entrypoint set, the docker command would be appended as parameters for that, so we override the entrypoint to be an empty one.
Also, you should no use the options -it in this case, given that they are used when you want to interact with the container (i.e access the terminal within the container).

A: Here's a list of things to check:
Use CMD and not ENTRYPOINT in the Dockerfile.  The command after the docker run image name overrides the Dockerfile CMD, and if both an ENTRYPOINT and a CMD are present then the CMD gets passed as arguments to the ENTRYPOINT.  You can work around this using docker run --entrypoint as described in @MarcosParreiras's answer but there's no benefit to using ENTRYPOINT here; just use CMD instead.
CMD ["sh", "/entrypoint.sh"]

Make sure your script can execute normally.  It should be executable (as in chmod +x), and it should begin with a "shebang" line
#!/bin/sh
# ^^^ as the very very first thing in the script

Outside Docker you should be able to run ./run_tests.sh and it should run without explicitly naming an interpreter.  If the file is executable on the host (and checked into source control as executable) then Dockerfile COPY will preserve the executable bit and you don't need to RUN chmod in the Dockerfile.
(You can do the same thing with your entrypoint.sh script and omit the explicit sh interpreter from the CMD.)
Put the script in $PATH somewhere. /usr/local/bin is often a good choice.
(In a Python context, if your setup.cfg file contains setuptools entry points, then pip install will put its wrapper scripts into /usr/local/bin and you can just run them; this is done automatically.)
Putting these all together, you'd get a Dockerfile like:
COPY entrypoint.sh run_tests.sh /usr/local/bin
# RUN chmod +x /usr/local/bin/*
CMD ["entrypoint.sh"]

And you should be able to run exactly the docker run command you initially proposed
docker run -it --rm image_name run_tests.sh


text:
Q: Memory related errors in counting sort? I have been trying to implement counting sort.
It requests the user for the number of times the program should run n.
The number of elements which will be sorted sz and the element with the maximum value k. Though the program runs correctly with n = 1, i.e. running it once, in other cases I get an error.
#include <stdio.h>
#include <stdlib.h>

void cntsrt(int a[], int b[], int k);

int sz;

int main(int argc, char **argv) {
    int n, k,*b, *a, i, j;

    scanf("%d", &n);

    while (n--) {
        scanf("%d", &sz);
        scanf("%d", &k);

        a = (int *) calloc(sz + 1, sizeof(int));

        for (i = 1; i <= sz; i++)
            scanf("%d", &a[i]);

        b = (int *) calloc(sz + 1, sizeof(int));

        cntsrt(a, b, k);
        printf("\n");

        for (j = 1; j <= sz; j++)
            printf("\t%d", b[j]);

        free((void*)a);
        free((void*)b);
    }

    printf("\n");

    return 0;
}

void cntsrt(int a[], int b[], int k) {
    int  i, j,*c;

    c = (int*) malloc(k*(sizeof(int)));

    for (i = 0; i <= k; i++)
        c[i] = 0;

    for (j = 1; j <= sz; j++)
        c[a[j]] = c[a[j]] + 1;

    for (i = 1; i <= k; i++)
        c[i] = c[i] + c[i - 1];

    for (j = 8; j > 0; j--) {
        b[c[a[j]]] = a[j];
        c[a[j]] = c[a[j]] - 1;
    }
}

A:  a = (int *) calloc(sz + 1, sizeof(int));
for (i = 1; i <= sz; i++)
    scanf("%d", &a[i]);

Array index should start from 0 to sz.
Int the function cntsrt -
 c = (int*) malloc(k*(sizeof(int)));
 for (i = 0; i <= k; i++)  // should be < k. There is no kth index
     c[i] = 0;

If the length of the array is n, then it's accessible indexes are from 0 to n-1.


text:
Q: Unable to modify fxml elements on Stage start I'm working on a restaurant application. It starts with a login screen then according to the user, it starts the correct dashboard.
I'm trying to fill a label and 2 comboboxes on the dashboard on its start but I keep getting NullPointerException on all of them.
I followed the function using IntelliJ debugger and found out it navigates to "timepulse()" function javafx.animation.Animation and that is what returns null.
My code:
public class CustomerController {

    static Stage window;
    public ComboBox<TableType> tableTypeCB;
    public ComboBox<DishType> categoryCB;
    public Label nameLabel;
    private static int userID;

    private void fillOnStart(String name)
    {
        nameLabel.setText("Hello, " + name);
        tableTypeCB.getItems().addAll(RestaurantData.restaurant.getTableTypes().getTableTypes());
        categoryCB.getItems().addAll(RestaurantData.restaurant.getDishTypes().getDishTypes());
    }

    public void start(int ID,String name) throws IOException {
        userID=ID;
        window = new Stage();
        window.setTitle("Hakuna Matata Restaurant");
        Parent root = FXMLLoader.load(CookerController.class.getResource("/restaurant/Customer-nReserv.fxml"));
        Scene scene = new Scene (root, 1024, 720);
        scene.getStylesheets().add(CustomerController.class.getResource("bootstrap3.css").toExternalForm());
        fillOnStart(name);
        window.setScene(scene);
        window.show();
    }
}

start function is called when the user enters a correct username and password to start the Customer Dashboard.
That is the error I get
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at Controllers.CustomerController.fillOnStart(CustomerController.java:26)
    at Controllers.CustomerController.start(CustomerController.java:38)
    at Controllers.LoginController.validateLogin(LoginController.java:68)
    at Controllers.LoginController.lambda$login$0(LoginController.java:37)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
    at java.lang.Thread.run(Thread.java:748)


text:
Q: How should I respond to 404 errors in winetricks? I am running into 404 errors using winetricks:
user@host:~$ bash winetricks gdiplus
Executing w_do_call gdiplus
Executing load_gdiplus
Executing mkdir -p /home/user/.cache/winetricks/gdiplus
Downloading http://download.microsoft.com/download/a/b/c/abc45517-97a0-4cee-a362-1957be2f24e1/WindowsXP-KB975337-x86-ENU.exe to /home/user/.cache/winetricks/gdiplus
--2012-08-10 10:29:24--  http://download.microsoft.com/download/a/b/c/abc45517-97a0-4cee-a362-1957be2f24e1/WindowsXP-KB975337-x86-ENU.exe
Resolving download.microsoft.com (download.microsoft.com)... 23.66.230.90, 23.66.230.8, 23.66.230.74, ...
Connecting to download.microsoft.com (download.microsoft.com)|23.66.230.90|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2012-08-10 10:29:24 ERROR 404: Not Found.

------------------------------------------------------
Downloading http://download.microsoft.com/download/a/b/c/abc45517-97a0-4cee-a362-1957be2f24e1/WindowsXP-KB975337-x86-ENU.exe failed
------------------------------------------------------

user@host:~$ bash winetricks tahoma
Executing w_do_call tahoma
Executing load_tahoma
Executing mkdir -p /home/user/.cache/winetricks/tahoma
Downloading http://download.microsoft.com/download/office97pro/fonts/1/w95/en-us/tahoma32.exe to /home/user/.cache/winetricks/tahoma
--2012-08-10 10:39:23--  http://download.microsoft.com/download/office97pro/fonts/1/w95/en-us/tahoma32.exe
Resolving download.microsoft.com (download.microsoft.com)... 23.66.230.81, 23.66.230.90, 23.66.230.74, ...
Connecting to download.microsoft.com (download.microsoft.com)|23.66.230.81|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2012-08-10 10:39:24 ERROR 404: Not Found.

------------------------------------------------------
Downloading http://download.microsoft.com/download/office97pro/fonts/1/w95/en-us/tahoma32.exe failed
------------------------------------------------------

How should I respond to these? Is there a way to get this stuff straight out of my Windows installation (dual booted)? Are there mirrors that I can point winetricks to in order to get these files?

A: Here's how you install it manually when you get a 404 error:

*

*Google for the package name, here WindowsXP-KB975337-x86-ENU.exe

*Download it.

*From the terminal, simply run wine ~/Downloads/WindowsXP-KB975337-x86-ENU.exe (or similar) to install in your default Wine prefix.

*

*You may have to click on EULAs, press one or two Next buttons, etc.; winetricks usually performs the quiet install.

Note: you can also try updating winetricks to the latest bleeding-edge version from their github (winetricks is a script)

A: Like Bruno said,
1.) Google it, also try ftp search engines (Google for them first, then search with them for that file).
2.) Download it.
Then either
3 a.) (Recommended!) Copy it to your winetricks cache directory in the correct subfolder.

*

*To do this:
cd to ~/.cache/winetricks/  (keep in mind that directories beginning with an . are not visible by default! If You are using nautilus You might try pressing Ctrl+L and entering the address manually, or, better use a console )

*There you should find the corresponding subfolder (like crypt32 or corefonts). Copy your downloaded file into that subfolder. If the file already exists, overwrite it or delete it first.

*Then run winetricks again. Your package should now appear as "cached". Just select it, as you did the first time. Now it will install, if no other required package is missing (in which case you need to Google and copy that file, too, and run winetricks again).
OR
3 b.) As an alternative, you could try Bruno's way and execute the file with wine, but:

*

*Be sure to check the shasum of your download first, to ensure you got the right version (as there are sometimes different versions using the same filename, and to avoid manipulated files).

*Look at the scripts winetricks uses, some packages might not install out-of-the-box without some (wine-)tricks like Windows-version hacking.

*To do this, you need to take a look at the winetricks script (hint: try opening it with a nice text editor like gedit).

To Your Question "Is there a way to get this stuff straight out of my Windows installation (dual booted)?":
Well, theoretically, yes, but (!) keep the following in mind:

*

*The file version Winetricks uses is known to work. Depending on Your Windows version and architecture, Your file might, or might not work. Winetricks uses files from different windows versions.

*Winetricks sometimes uses special tricks ;-) to get things to work, like registry settings and so on. So You would need to look at the winetricks source to find out what winetricks does.

*You would need to register Your dll file override manually.

*You should be aware of potential license issues with Microsoft!
Or, the short answear to Your question: I don't think You really want to :-)

A: I had the same problem and solved it by replacing the gdiplus.dll inside the windows/system32 with the downloaded from this site :
http://www.dll-files.com/dllindex/dll-files.shtml?gdiplus
Once in the site, select the download gdiplus.zip. Unzip and extract to home/.wine/ drive_c/windows/system32.
Having done this, check by runing the winetricks,  select default winepreficks, install a windows dll or component, select gdiplus and.........should be installed.

A: Microsoft has released a new update for GDIPlus, therefore removing their old download link. The new file can be downloaded from http://www.microsoft.com/en-us/download/details.aspx?id=12488 - I'm not sure that this will work for Wine/Winetricks, but I'm hoping it will :D


text:
Q: Question about definition of topological manifold The following definition of topological manifold is given in Lee's Introduction to topological manifolds (2000) on page 33:
A topological manifold is a second countable Hausdorff space that is locally Euclidean.
I omitted the dimension since it's not relevant to my question so it's not a faithful quote.
My question is: Doesn't Hausdorffness follow from being locally Euclidean? Pick $x,y$ in $M$. Then for each point there exists an open set homeomorphic to an open subset of $\mathbb R^n$. Let's call them $U_x, U_y \subset M$. Then either they are already disjoint or if they intersect, by Euclidenaity, we can pick smaller open sets inside them so that the smaller sets don't intersect. So we have a Hausdorff space.
Question 1: What am I missing? Why does this not work?
Question 2: I guess we have to require second countability because otherwise the disjoint union $\bigsqcup_{r \in \mathbb R \setminus \mathbb Q} (0,1)$ would be a $1$-manifold (that doesn't admit a countable basis) . Is that a correct counter example?
Thanks for your help.

A: To reply to your first question. Consider the real line with two origins. That is, take disjoint copies of the real line and identify $x$ in the first copy with $x$ in the second copy except for the point $x=0$. This space is locally 1-Euclidean and second countable, but not Hausdorff. Any two open sets containing either origin will have points in common.
More information line with two origins.

A: On the first question: DrKW has already given you a counterexample. The error in your proof is that if $U_x, U_y$ intersect, it's not guaranteed that the smaller open sets you want to take will actually contain your original points $x$ and $y$.
On the second question: An uncountable disjoint union of intervals is indeed locally Euclidean but not second countable, if you take the disjoint union topology on them. I'm not sure exactly what you mean by your notation, but I'm worried that you're trying to take some subspace of $\Bbb{R}^2$, which would be guaranteed second countable as second-countability is a hereditary property. (An uncountable union of disjoint intervals in $\Bbb{R}^2%$ would also fail to be locally Euclidean — even if the intervals are disjoint, neighborhoods of points on one interval will be forced to include points on other intervals.)
You can also find connected spaces which are locally Euclidean but not second-countable; the standard example is the long line. In some ways this is a more important counterexample than the disjoint union one, as its non-second-countability also leads it to be nasty in other ways (e.g., it doesn't admit a partition of unity).


text:
Q: Can't get custom fonts to show using @font-face I am using @font-face to try and get the font 'Archisto' to load on my webpage. I am a newbie on building web pages and using @font-face. I followed all the steps on several tutorials and looked through several threads on here, but I can not get the font to load.
I have the css file uploaded in the folder http://www.unfoldmyworld.com/wp-content/themes/ashe/assets/css/Archistico.css
I have the font file uploaded in the folder http://www.unfoldmyworld.com/wp-content/themes/ashe/assets/fonts/FONT_11.TTF
The @font-face code in the .css file looks like this:
@font-face {
    font-family: Archistico;
    src: url(http://www.unfoldmyworld.com/wp-content/themes/ashe/assets/fonts/FONT_11.TTF);

}

I am calling the font with custom CSS that looks like this:
.page-content h5{
    font-family: 'Archistico' !important;
    font-size: 50px !important;
    display: inline !important;
    color: #231400 !important;
}

The page I am trying to get this to work on is: www.unfoldmyworld.com
I would really appreciate your help!

A: 1- Add to the head section of web page.<link href="//db.onlinewebfonts.com/c/50f290d070f58bdf56e1cc32e5636174?family=Archistico" rel="stylesheet" type="text/css"/>
-2 Using @import CSS directive, put the following line in add to your css file.(http | https)
@import url(//db.onlinewebfonts.com/c/50f290d070f58bdf56e1cc32e5636174?family=Archistico);

-3 Use font-face declaration Fonts.(http | https)
@font-face {font-family: "Archistico"; src: url("//db.onlinewebfonts.com/t/50f290d070f58bdf56e1cc32e5636174.eot"); src: url("//db.onlinewebfonts.com/t/50f290d070f58bdf56e1cc32e5636174.eot?#iefix") format("embedded-opentype"), url("//db.onlinewebfonts.com/t/50f290d070f58bdf56e1cc32e5636174.woff2") format("woff2"), url("//db.onlinewebfonts.com/t/50f290d070f58bdf56e1cc32e5636174.woff") format("woff"), url("//db.onlinewebfonts.com/t/50f290d070f58bdf56e1cc32e5636174.ttf") format("truetype"), url("//db.onlinewebfonts.com/t/50f290d070f58bdf56e1cc32e5636174.svg#Archistico") format("svg"); }

Let me know if this works for you :) Thanks

A: Have you tried it with a relative url?
I'm thinking of a CORS (Cross-Origin Resource Sharing) problem.
@font-face {
   font-family: Archistico;
   src: url('../fonts/FONT_11.TTF');
}


text:
Q: Symfony form: how to render an empty many-to-many relationship but still make it required On an old Symfony 5.2 application I inherited, I have two entities: Users and Influencers. These have a many-to-many relationship between them.
I'm creating a form to create and edit Influencers but the form field (a <select> HTML element) for the relationship with Users is rendered with an option (a user) already selected.
This is not what I want, since it means someone creating a new Influencer and not noticing the pre-selected option, will save the form with the wrong User assigned to the Influencer. I want the form to start without a User selected.
Additionally, I would like a value for the relationship to be required on the form. This means that:

*

*at least one User should be assigned to a newly created Influencer;

*when editing and existing Influencer, I should not be able to remove all Users from the relationship field.

I already tried several combinations of the allow_add, allow_delete, required, and messing with the choices options when adding the field with the form builder, but all to no avail.
I just can't figure out how to do this. Any help is greatly appreciated.

Here are the relevant parts of the code, simplified for brevity sake.
The Influencer entity in src/Entity/Influencer.php
<?php

namespace App\Entity;

use ........

/* ORM Stuff here... */
class Influencer
{
    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="influencers")
     * @ORM\JoinTable(name="influencers_account_managers")
     */
    private $accountManagers;

    public function __construct()
    {
        $this->accountManagers = new ArrayCollection();
    }

    public function getAccountManagers(): Collection
    {
        return $this->accountManagers;
    }

    public function addAccountManager(User $accountManager): self
    {
        if (!$this->accountManagers->contains($accountManager)) {
            $this->accountManagers[] = $accountManager;
        }

        return $this;
    }

    public function removeAccountManager(User $accountManager): self
    {
        if ($this->accountManagers->contains($accountManager)) {
            $this->accountManagers->removeElement($accountManager);
        }

        return $this;
    }

The User entity in src/Entity/User.php
<?php

namespace App\Entity;

use ........

/* ORM Stuff here... */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    // Other properties
    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Influencer", mappedBy="accountManagers")
     */
    private $influencers;

The InfluencerController in src/Controller/InfluencerController.php
<?php

namespace App\Controller;

use ....

class InfluencerController extends AbstractController
{
    /**
     * @Route("/add-influencer", name="influencer_create")
     */
    public function create(Request $request, InfluencerManager $influencerManager)
    {
        $form = $this->createForm(InfluencerType::class, new Influencer());

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $influencerManager->create($form->getData());

            return $this->redirectToRoute('influencers_list');
        }

        return $this->render('influencer/create.html.twig', [
            'form' => $form->createView(),
        ]);
    }

The InfluencerType in src/Form/InfluencerType.php
<?php

namespace App\Form;

use .......

class InfluencerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('accountManagers', CollectionType::class, [
            'entry_type' => EntityType::class,
            'required' => true,
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
            'prototype' => true,
            'entry_options' => [
                'class' => User::class,
                'label' => false,
            ]
        ]);
    }

A: You can use ChoiceType::class instead of CollectionType::class,  and in your User Entity, Influencer must have a relation.
 $builder->add('accountManagers', ChoiceType::class, array(
                'label' => '...',
                'choices' => User::Influencer,
                'multiple'  => false,
                'expanded' => true,
                'required' => true,
                )
            );


text:
Q: Fantasy movie where a young guy finds the love of his life through a magical doorway I am really sorry for the small amount of details, and I'm not even sure it is an English movie.
As far as I remember, a young guy who works in an old diner/restaurant (may be a pizza place) one day goes behind this restaurant/diner/or whatever place to bring something, and he accidentally discovers a magic door which takes him to another universe or a heavenly kind of place. In there is beach that I can remember, and the first time he goes into this place, the air is not even like air. For example he touches the air with his fingers and it is like water, or like the scene in The Matrix when Neo touches the mirror in the first movie, and the mirror acts like plasma, but only it happens in the air in the movie.
Then this young man meets a girl and they fall in love. Even though I am not sure, I think some bad stuff happens in this world too, and this young man turns back and consults his boss or maybe father, and decides to go back through the door to that world again to save the girl.
I have seen this movie when I was a little kid. Not even sure it is an English movie, because I watched the movie in another language and the name (again, not sure, just guessing and remembering that way) was "Chinese Restaurant's Door" or something like that.
I am really sorry for the small amount of details, but this is all I remember. like I said, I watched this a long time ago when I was a kid. It was probably a '90s, or at the very latest, early-2000s movie.
Edit: I can't remember the time, but it was a dubbed movie on TV, and I don't know what the original language was (could've been be English). I watched it between 1997 and 2000, but since it was on TV, it might have been produced years earlier. The ethnicity of the characters was white European, and it is a definitely a family movie. I don't remember anything more than this.

A: Could it be Under the Chinese Restaurant (1987)?  It has several matching elements:

*

*The date is approximately right

*The title mentions a "Chinese Restaurant" (original title Sotto il ristorante cinese)

*The protaganest goes through a door to a surreal beach setting

*He meets a girl (and her father)

I didn't find a mention of the air, but perhaps thats what they mean by surreal.
The original Italian version can be seen on youtube here.


text:
Q: fill dataframe with different dtype within for loop Hello I would like to create a dataframe containing the columns 'start', 'end', 'duration', and 'filename'
MyDataframe=pd.DataFrame(columns=['start','end','duration','filename'])

The columns start, end and duration should contain integers, and filename strings
I would need to fill the dataframe within a foor loop in which I read a file and I calculate start,end and duration of events.
for i in range(0,numFiles):
  [detected_events] = calculateevents(filename)

detected_events is an array containing the start,end and duration of all the events in filename
detected_events
Out[4]:
array([[ 24737,  24807,      4],
       [ 36221,  36221,      1],
       [ 37563,  37652,      4],
       ...,
       [179738, 179738,      1],
       [179829, 179829,      1],
       [179888, 179888,      1]])

I would like to include the information containend in detected events in MyDataframe along with the filename from where these events were calculated, but I cannot find a way. could you help me?

A: IIUC you need:
dfs = []
for i in range(0,numFiles):
  detected_events = calculateevents(filename)
  #create df by numpy array
  MyDataframe = pd.DataFrame(detected_events, columns=['start','end','duration'])
  #add new column, second row fill to filename (another values are NaN)
  MyDataframe[1, 'filename'] = filename
  #add df to list
  dfs.append(MyDataframe)

#concat all df to one big
df = pd.concat(dfs, ignore_index=True)


text:
Q: Limit of double sum is always series sum? Let $B$ be a (real or complex) Banach space, suppose $(b_{i, j})_{i, j \in \mathbb{N}}$ is a family of elements of $B$. If we know that
$$
\lim_{n \to +\infty} \left( \sum_{i=0}^{n} \sum_{j=0}^{n} b_{i, j} \right)
$$
exists in $B$, can we be sure that
$$
\lim_{n \to +\infty} \left( \sum_{i=0}^{n} \sum_{j=0}^{n} b_{i, j} \right) = \sum_{i=0}^{+\infty}\left( \sum_{j=0}^{+\infty} b_{i, j} \right)
$$
without assuming absolute convergence?

A: Without assuming absolute convergence,
the left and the right side may converge do different values or diverge independently.
For example, let
$$b_{i,0} = 1$$
$$\forall j > 0, b_{i,j} = \frac 1 {j + 1} - \frac 1 {j}$$
where $i$ may take arbitrary values.
In this case, $\sum_{j=0}^{n} b_{i,j} = \frac 1 {n + 1}$, for all $n > 0$.
The left side becomes
$$
\lim_{n \to + \infty} \left( \sum_{i=0}^{n} \sum_{j=0}^{n} b_{i, j} \right) =
\lim_{n \to + \infty} \left( n \frac 1 {n + 1} \right) = 1
$$
while the right one becomes
$$
\sum_{i=0}^{+ \infty} \left( \sum_{j=0}^{+ \infty} b_{i, j} \right) =
\sum_{i=0}^{+ \infty} \left( \lim_{n \to + \infty} \frac 1 {n + 1} \right) = 0
$$
moreover, if we'd reverse the order of the summation symbols,
we'd have some pretty messy situation.

Conversely,
if we know that either limit exists for the absolute values of the elements,
then this, and virtually any such equality, should hold. More precisely,
let $X$ be a normed vector space, say $\mathbb R$ or $\mathbb C$:

*

*Suppose $\sigma: \mathbb N \to \mathbb N$ is bijective (an "infinite transposition" of the indices).
And that the sequence $a: \mathbb N \to X$ is converging absolutely:

$$\sum_{k=0}^{\infty} |a_k| \in \mathbb R_{\geq 0}$$
then
$$\sum_{k=0}^{\infty} a_k = \sum_{k=0}^{\infty} a_{\sigma(k)}$$

*And also, if $\tau: \mathbb N \to \mathbb N \times \mathbb N$ is another bijection,
arranging the sequence of indices into an "infinite matrix" and vice versa,
and $b: \mathbb N \times \mathbb N \to X$ is such a matrix. Then

$$\sum_{k=0}^{\infty} |b_{\tau(k)}| \in \mathbb R_{\geq 0}$$
or
$$\sum_{i=0}^{\infty} \sum_{j=0}^{\infty} |b_{i, j}| \in \mathbb R_{\geq 0}$$
implies
$$\sum_{i=0}^{\infty} \sum_{j=0}^{\infty} b_{i, j} = \sum_{k=0}^{\infty} b_{\tau(k)}$$
A proof goes like this:

*

*First consider the case of a positive series,
and establish that the sum of original (on $k$) series
is $\leq$ the sum of the transposed series (on $\sigma(k)$).
Since the former series may also be viewed as transposition of the latter,
we also have the opposite inequality -- i.e. the sums are equal.
The extrapolation onto the general case of arbitrary such series
is done by virtue of grouping the elements of the same sign,
i.e. representation of the series as double sum:
first by the elements having the same sign,
then by the resulting values applied to the corresponding signs.
(e.g. in case of $X = \mathbb R$, it just two signs, $+$ and $-$)

*In one direction,
assuming $\bar{B} := \sum_{k=0}^{\infty} |b_{\tau(k)}|$ is defined.
Then $\bar{B}$ is an upper bound for the increasing sequences of partial sums:
$$ \bar{B}'_i(m) := \sum_{j = 0}^{j = m} |b_{i,j}| \leq \bar{B} $$
so these sums are converging:
$$ \sum_{j = 0}^{\infty} |b_{i,j}| \text{ and }
   \sum_{j = 0}^{\infty} b_{i,j} =: B'_i $$
and we want yet to check that
$$ \sum_{i = 0}^{\infty} B'_i = B :=
   \sum_{k = 0}^{\infty} b_{\tau(k)} $$
Due to the absolute convergence, for any $\epsilon > 0$, we have
$$
\left| B - \sum_{k = 0}^{k = \phi(\epsilon)} b_{\tau(k)} \right| =
\left| \sum_{k = \phi(\epsilon) + 1}^{\infty}  b_{\tau(k)} \right| \leq
       \sum_{k = \phi(\epsilon) + 1}^{\infty} |b_{\tau(k)}| \lt \epsilon
$$
where $\phi: \mathbb R_{\gt 0} \to \mathbb N$ is the "estimate map",
from the definition of the limit, for the absolute convergence for $b_{\tau(k)}$.
And if $S$ is an arbitrary subset of indices,
such that $[0, \phi(\epsilon)] \subseteq S \subseteq \mathbb N$, then also
$$
\left| B - \sum_{k \in S} b_{\tau(k)} \right| =
\left| \sum_{k \in \mathbb N \setminus S}  b_{\tau(k)} \right| \leq
       \sum_{k \in \mathbb N \setminus S} |b_{\tau(k)}| \leq
\sum_{k = \phi(\epsilon) + 1}^{\infty} |b_{\tau(k)}| \lt \epsilon
$$
generally, if $S$ and $S'$ are two such sets, and $S \subseteq S'$,
then $\left| B - \sum_{k \in S'} b_{\tau(k)} \right| \leq
      \left| B - \sum_{k \in S } b_{\tau(k)} \right|$.
Let $\psi (f, k) := \max_{0 \le x \le k} f(x)$,
and $(m, n) := \psi (\tau, \phi (\epsilon))$ defines the "index rectangle",
based at $(0, 0)$ and containing all the values $\tau(0), \dots, \tau(\phi(\epsilon))$.
We define $S$ to be $\tau^{-1}([0, m], [0, n])$,
i.e. a set of such an indices, that are mapped by $\tau$ into the rectangle
(large enough to satisfy the requirements on $S$).
Then
$$
\left| B - \sum_{k \in S} b_{\tau(k)} \right| =
\left| B - \sum_{i = 0}^{i = m} \sum_{j = 0}^{j = n} b_{i,j} \right|
$$
and, since all such expressions are bound by $\epsilon$,
and may only get smaller with $m$ and $n$, we also have
$$
\left| B - \sum_{i = 0}^{\infty} \sum_{j = 0}^{\infty} b_{i,j} \right| < \epsilon
$$
Since $\epsilon$ may be arbitrarily small, necessary
$$ \sum_{i = 0}^{\infty} \sum_{j = 0}^{\infty} b_{i,j} = B $$
In the other direction,
assuming $\bar{B} := \sum_{i=0}^{\infty} \sum_{j=0}^{\infty} |b_{i, j}|$ is defined.
Then
$$ \sum_{i=0}^{i=m} \sum_{j=0}^{j=n} |b_{i, j}| \leq \bar{B} $$
and
$$ \sum_{k=0}^{k=l} |b_{\tau(k)}| \leq
   \sum_{i=0}^{i=m} \sum_{j=0}^{j=n} |b_{i, j}| $$
where as before $(m, n) := \psi (\tau, l)$.
So $l \mapsto \sum_{k=0}^{k=l} |b_{\tau(k)}|$,
the sequence of positive partial sums,
is increasing and bounded, therefore, converging.
The equality of the limits follows from the previous result.
$\square$
Combination of these two rules gives the answer to the (second) question.
And, among other things,
it allows to swap the summation symbols for absolutely converging series.
These rules may be viewed as a generalization of the commutativity of addition.

See also: https://en.wikipedia.org/wiki/Series_(mathematics)

A: Consider the infinite matrix $b_{ij}$ consisting of $1$'s along the main diagonal, $-1$'s along the diagonal directly above the main diagonal, and $0$'s everywhere else. (Good to draw a picture.) Then the "square" sums over $n\times n$ blocks are all equal to $1.$ All horizontal infinite sums are $0.$ If we then sum the horizontal sums, we get $0.$ The first vertical infinite sum is $1;$ all other vertical infinite sums give $0.$ So if we sum the vertical sums, we get $1.$ And … $0 \ne 1!$


text:
Q: Convergence of the complex series $\sum_{n=0}^{\infty} \frac{(-1)^{n}}{z+n}$ I don't have familiarity with complex series.
I know this series won't converge if $z$ is a negative integer. Apart from that, I know that the series does not converge absolutely (because the absolute value gets close to $\frac{1}{n}$ which diverges).
If instead of complex number $z$ I had $x \in \mathbb{R}$, then:$$\sum_{n=0}^{\infty} \frac{(-1)^{n}}{x+n}$$
Would converge for all $x$ apart from negative integers, due to the Leibniz test. Can I use the same argument for a complex number $z$?
I'm not sure about what to do because I have never dealt with alternating complex series before.

A: The simplest way is to write
$$\frac{1}{z+n} = \frac{1}{n} - \biggl(\frac{1}{n} - \frac{1}{z+n}\biggr) = \frac{1}{n} - \frac{z}{n(z+n)}.$$
For $n \geqslant 2\lvert z\rvert$, we have $\lvert z+n\rvert \geqslant n - \lvert z\rvert \geqslant \frac{1}{2}n$, so
$$\sum_{n=1}^\infty \frac{z}{n(z+n)}$$
converges absolutely. Then the convergence of
$$\sum_{n=0}^\infty \frac{(-1)^n}{z+n} = \frac{1}{z} + \sum_{n=1}^\infty \frac{(-1)^{n}}{z+n} = \frac{1}{z} + \sum_{n=1}^\infty \frac{(-1)^{n}}{n} - \sum_{n=1}^\infty \frac{(-1)^{n}z}{n(z+n)}$$
for all $z$ that are not non-positive integers follows with the Leibniz criterion. In fact the convergence is locally uniform.


text:
Q: Will QGIS 2.99 and QGIS 3.0 always be the same? For a dev, QGIS 2.99.0-Master is the next QGIS version which will be released.
that why http://doc.qgis.org/api/index.html is so important to make the bridge.
But it is simple as that ?
What will become 2.99 when QGIS 3 will be released ?
Is the dev version of QGIS 3.x will be named QGIS 3.99.0-Master ?

A: After 3.0 is released, the dev version will be called 3.1, and the next release will be 3.2.
As AndreJ mentioned, the most recent roadmap is published on the QGIS website https://www.qgis.org/en/site/getinvolved/development/roadmap.html


text:
Q: Migrate validations from strus1.3 to struts2 I am current working on a migration project from struts1.x to struts2. I am looking for some help in migrating the existing validations.xml and validations-rules.xml to struts2 equivalent. I am aware that we need to create validation xml per action class in struts2, but idea of placing all validations under file like in struts1 looks more better in terms of managing the application. If anybody had done similar work, please give me some pointers or guidance.
Secondly, if validation using one single file is not possible, i would like some help on how to convert the validations file to equivalent struts2. I am not able to understand the plugins part, for eg, mask, date. Seems they are more easy in struts1, whereas in struts2 we have to write regex for almost everything. for eg, i couldnt find anything for just a Invalid date validation. Whereas just using the date plugin in struts1 its possible.


text:
Q: C++ template and ODR Rule Why does following works in C++, I thought ODR rule will come into picture for following code
typedef char      int8;
class Sample {
public:
  template <typename T>
  void test( T param){
  }
};

int main() {
  Sample s;
  s.test<char>('a');
  s.test<int8>((int8)'b');
  return 0;
}

A: Because when the template instantiations are done and compiler gets rid of typedefs and unnecessary casts, your code is exactly the same as:
class Sample {
public:
  void test(char param){
  }
};

int main() {
  Sample s;
  s.test('a');
  s.test('b');
  return 0;
}

You seem to think that a typedef declares another distinct type, but that's not the case. It's just an alias (for your convinience, usually). OTOH, when you call a function template with a different template parameter, functions with different signatures are generated. No ODR violation in either case.

A: It's doing the same thing both times. It just looks like they're different.
The first one says it'll use the char version, so T becomes a char.
The second says it'll use the int8 version, so T would become an int8, which is actually just a char in disguise. Therefore, T will still be a char, and you're passing in a char in both cases, so all is well.


text:
Q: Highlight geometry in Folium map on hover Is there a way to highlight geometry in Folium on hover along with the tooltip?
Sample Data:
import pandas as pd
import requests
import geopandas

response = requests.get(
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data/us-states.json"
)
data = response.json()
states = geopandas.GeoDataFrame.from_features(data, crs="EPSG:4326")

response = requests.get(
    "https://gist.githubusercontent.com/tvpmb/4734703/raw/"
    "b54d03154c339ed3047c66fefcece4727dfc931a/US%2520State%2520List"
)
abbrs = pd.read_json(response.text)

income = pd.read_csv(
    "https://raw.githubusercontent.com/pri-data/50-states/master/data/income-counties-states-national.csv",
    dtype={"fips": str},
)
income["income-2015"] = pd.to_numeric(income["income-2015"], errors="coerce")

statesmerge = states.merge(abbrs, how="left", left_on="name", right_on="name")
statesmerge["geometry"] = statesmerge.geometry.simplify(0.05)

statesmerge["medianincome"] = statesmerge.merge(
    income.groupby(by="state")[["state", "income-2015"]].median(),
    how="left",
    left_on="alpha-2",
    right_on="state",
)["income-2015"]
statesmerge["change"] = statesmerge.merge(
    income.groupby(by="state")[["state", "change"]].median(),
    how="left",
    left_on="alpha-2",
    right_on="state",
)["change"]

Code:
import branca
import folium
from folium.features import GeoJsonPopup, GeoJsonTooltip

colormap = branca.colormap.LinearColormap(
    vmin=statesmerge["change"].quantile(0.0),
    vmax=statesmerge["change"].quantile(1),
    colors=["red", "orange", "lightblue", "green", "darkgreen"],
    caption="State Level Median County Household Income (%)",
)

m = folium.Map(location=[35.3, -97.6], zoom_start=4)

tooltip = GeoJsonTooltip(
    fields=["name", "medianincome", "change"],
    aliases=["State:", "2015 Median Income(USD):", "Median % Change:"],
    localize=True,
    sticky=False,
    labels=True,
    style="""
        background-color: #F0EFEF;
        border: 2px solid black;
        border-radius: 3px;
        box-shadow: 3px;
    """,
    max_width=800,
)

g = folium.GeoJson(
    statesmerge,
    style_function=lambda x: {
        "fillColor": colormap(x["properties"]["change"])
        if x["properties"]["change"] is not None
        else "transparent",
        "color": "black",
        "fillOpacity": 0.4,
    },
    tooltip=tooltip,
).add_to(m)

colormap.add_to(m)

m

On hovering over the folium map it shows the tooltip like below, is there a way to highlight the geometry

A: The answer is highlight_function... For example:
folium.GeoJson(
    data=ecmap_gdf["geometry"],
    highlight_function= lambda feat: {'fillColor': 'blue'}
).add_to(m)

May be must review the link.