问:
Hibernate NPE when using function() to call native sql method within jpa
I've got the following query which is used within a spring-data repository and runs fine in the jpa console. It has a subselect query which uses jpa's function() to call a native MySQL database method:

select run1.someAttribute1 AS someAttribute1,
       run1.someAttribute2 AS someAttribute2,
       run1.someAttribute3 AS someAttribute3,
(select
    sum(function('timestampdiff', SECOND, run2.runStartTime, run2.runEndTime))
    from runTable AS run2
    where run2.anotherAttribute1 = run1.anotherAttribute1
    and run2.anotherAttribute2 = run1.someAttribute2
    and run2.anotherAttribute3 = run1.someAttribute3
) AS runtime,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething1,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething2,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething3,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething4,
sum(
    case when type(event) = SomeEvent2 then 1
    else 0 end
) AS numberOfSomething5 from runTable AS run1 left join run1.events AS event
group by someAttribute1, someAttribute2, someAttribute3
order by
    max(function('right', function('left', someAttribute1, 8), 3)) desc,
    someAttribute2 desc,
    someAttribute3 desc
```

<p>The method timestampdiff is registered in my custom MySQLDialect:</p>

```public class MySQLDialect extends org.hibernate.dialect.MySQLDialect {

    public MySQLDialect() {
        super();
        registerFunction("timestampdiff", new SQLFunctionTemplate(LongType.INSTANCE, "timestampdiff(?1, ?2, ?3)"));
    }
}
```

<p>A spring boot application uses this repository and starts up without any error. When opening the page which is linked to the repository (through a bean and service layer of course), it loads up and shows the desired result in a datatable.</p>

<p>The problem occurs when I implement any unit (integration) test (i guess through scanning the repository package?!). While the unit test is starting up, Hibernate throws a NullPointerException.</p>

```@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(locations = {"/application-context-test.xml"})
@EnableJpaRepositories("de. ... .persistence.repositories")
public class AnalysisServiceTest {

    @Inject
    private AnalysisService analysisService;

    @Inject
    private CarService carService;

    @Test
    public void saveAnalysis() {

        ...
    }

}
```

<p>Application-context-test.xml</p>

```<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns="http://www.springframework.org/schema/beans"
       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.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <context:component-scan base-package="de. ... .analysis"/>

</beans>
```

<p>Stacktrace:</p>

```    java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '...Service' defined in file [C:\_Projekte\...\...Service.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...Repository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de. ... .Repository.getSomething()!
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...Repository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de. ... .repositories....Repository.getSomething()!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 42 more
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de. ... .repositories....Repository.getSomething()!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:144)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:211)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 53 more
Caused by: java.lang.NullPointerException
    at org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions$SumFunction.determineJdbcTypeCode(StandardAnsiSqlAggregationFunctions.java:200)
    at org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions$SumFunction.getReturnType(StandardAnsiSqlAggregationFunctions.java:158)
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.findFunctionReturnType(SessionFactoryHelper.java:414)
    at org.hibernate.hql.internal.ast.tree.AggregateNode.getDataType(AggregateNode.java:68)
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:156)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:1011)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:779)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:677)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2466)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.aliasedSelectExpr(HqlSqlBaseWalker.java:2509)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2239)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1503)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:585)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
    at com.sun.proxy.$Proxy69.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
    ... 66 more
```

So i debugged into that problem and as you can see in the stacktrace, Hibernate fails during AST building within the method findFunctionReturnType(String functionName, SQLFunction sqlFunction, AST firstArgument) which is located in the SessionFactoryHelper class. That method tries to resolve the argumentType through casting firstArgument to an SqlNode and calling getDataType() on it and finally it returns sqlFunction.getReturnType with that argumentType.

In my case, the NPE occurs when resolving the argumentType from the subselect's sum function. functionName is "sum", sqlFunction is an instance of SumFunction and firstArgument is "function(timestampdiff)" (instance of MethodeNode). When getReturnType(argumentType, ... ) is called on return, argumentType is null because obvoiusly, it cannot be resolved from "function(timestampdiff)", thus causing the NPE.

Question

Is there any way i can use function() together with hibernate in a subselect? Why does it fail in my unit tests while working perfectly in the spring boot application?

EDIT
It appears to only work for me in my spring boot application. One of m coworkers has it also fail for the application startup. There is nothing different from our code and IDE

I've already read about that magic NPE but couldn't find a solution for my problem.

答:
This sounds like a dependency/class loading issue. I'd try the following

make a diff of your dependencies/classpath. If you're using maven use its dependency plugin to print the dependency tree (mvn dependency:tree). Look out for duplicate dependencies and different versions in test and production code. Print out the classpath at runtime and again compare it between test and production.

put a breakpoint in the MySqlDialect to ensure it gets loaded.

Body:
I've got the following query which is used within a spring-data repository and runs fine in the jpa console. It has a subselect query which uses jpa's function() to call a native MySQL database method:

select run1.someAttribute1 AS someAttribute1,
       run1.someAttribute2 AS someAttribute2,
       run1.someAttribute3 AS someAttribute3,
(select
    sum(function('timestampdiff', SECOND, run2.runStartTime, run2.runEndTime))
    from runTable AS run2
    where run2.anotherAttribute1 = run1.anotherAttribute1
    and run2.anotherAttribute2 = run1.someAttribute2
    and run2.anotherAttribute3 = run1.someAttribute3
) AS runtime,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething1,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething2,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething3,
sum(
    case when type(event) = SomeEvent and event.someType = '...' then 1
    else 0 end
) AS numberOfSomething4,
sum(
    case when type(event) = SomeEvent2 then 1
    else 0 end
) AS numberOfSomething5 from runTable AS run1 left join run1.events AS event
group by someAttribute1, someAttribute2, someAttribute3
order by
    max(function('right', function('left', someAttribute1, 8), 3)) desc,
    someAttribute2 desc,
    someAttribute3 desc

The method timestampdiff is registered in my custom MySQLDialect:

public class MySQLDialect extends org.hibernate.dialect.MySQLDialect {

    public MySQLDialect() {
        super();
        registerFunction("timestampdiff", new SQLFunctionTemplate(LongType.INSTANCE, "timestampdiff(?1, ?2, ?3)"));
    }
}

A spring boot application uses this repository and starts up without any error. When opening the page which is linked to the repository (through a bean and service layer of course), it loads up and shows the desired result in a datatable.

The problem occurs when I implement any unit (integration) test (i guess through scanning the repository package?!). While the unit test is starting up, Hibernate throws a NullPointerException.

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(locations = {"/application-context-test.xml"})
@EnableJpaRepositories("de. ... .persistence.repositories")
public class AnalysisServiceTest {

    @Inject
    private AnalysisService analysisService;

    @Inject
    private CarService carService;

    @Test
    public void saveAnalysis() {

        ...
    }

}

Application-context-test.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns="http://www.springframework.org/schema/beans"
       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.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <context:component-scan base-package="de. ... .analysis"/>

</beans>

Stacktrace:

    java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '...Service' defined in file [C:\_Projekte\...\...Service.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...Repository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de. ... .Repository.getSomething()!
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...Repository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de. ... .repositories....Repository.getSomething()!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 42 more
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de. ... .repositories....Repository.getSomething()!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:144)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:211)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 53 more
Caused by: java.lang.NullPointerException
    at org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions$SumFunction.determineJdbcTypeCode(StandardAnsiSqlAggregationFunctions.java:200)
    at org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions$SumFunction.getReturnType(StandardAnsiSqlAggregationFunctions.java:158)
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.findFunctionReturnType(SessionFactoryHelper.java:414)
    at org.hibernate.hql.internal.ast.tree.AggregateNode.getDataType(AggregateNode.java:68)
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:156)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:1011)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:779)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:677)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2466)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.aliasedSelectExpr(HqlSqlBaseWalker.java:2509)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2239)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1503)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:585)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
    at com.sun.proxy.$Proxy69.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
    ... 66 more

So i debugged into that problem and as you can see in the stacktrace, Hibernate fails during AST building within the method findFunctionReturnType(String functionName, SQLFunction sqlFunction, AST firstArgument) which is located in the SessionFactoryHelper class. That method tries to resolve the argumentType through casting firstArgument to an SqlNode and calling getDataType() on it and finally it returns sqlFunction.getReturnType with that argumentType.

In my case, the NPE occurs when resolving the argumentType from the subselect's sum function. functionName is "sum", sqlFunction is an instance of SumFunction and firstArgument is "function(timestampdiff)" (instance of MethodeNode). When getReturnType(argumentType, ... ) is called on return, argumentType is null because obvoiusly, it cannot be resolved from "function(timestampdiff)", thus causing the NPE.

Question

Is there any way i can use function() together with hibernate in a subselect? Why does it fail in my unit tests while working perfectly in the spring boot application?

EDIT
It appears to only work for me in my spring boot application. One of m coworkers has it also fail for the application startup. There is nothing different from our code and IDE

I've already read about that magic NPE but couldn't find a solution for my problem.


来源: stackexchange

问:
jQuery smooth scroll for WordPress not working
I've been trying to make my links work on my theme I am creating but I have no knowledge of jQuery for the smooth scrolling. In my theme I used the following jQuery I saw was working online:

```<code>$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});
</code>```

In my dynamic WordPress menu I set the urls to #values, #about, #contact etc. and the links to it on the specific places on the page I used ,  and

It works, but the smooth scrolling doesn't work. I see that anchors are used for smooth scrolling online in the parts of the page but I want to be able to target the id of the span tags. I tried to make an anchor tag to test if it works but it still doesn't.

How do I get this to work?

答: Miro replied in the comments the correct answer - "In Wordpress you need to add external jquery or equate the dollar sign to the one already in use. Try adding $ = jQuery; above all your scroll code. If that doesn't work replace all $ with jQuery."

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to make my links work on my theme I am creating but I have no knowledge of jQuery for the smooth scrolling. In my theme I used the following jQuery I saw was working online:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

In my dynamic WordPress menu I set the urls to #values, #about, #contact etc. and the links to it on the specific places on the page I used ,  and

It works, but the smooth scrolling doesn't work. I see that anchors are used for smooth scrolling online in the parts of the page but I want to be able to target the id of the span tags. I tried to make an anchor tag to test if it works but it still doesn't.

How do I get this to work?


问:
How to assign the address of an existing object to a smart pointer?
```<code>#include <memory>

class bar{};

void foo(bar &object){
    std::unique_ptr<bar> pointer = &object;
}
</code>```

I want to assign an address of the object to the pointer. The above code obviously wont compile, because the right side of the assignment operator needs to be a std::unique_ptr. I've already tried this:

```<code>pointer = std::make_unique<bar>(object)
</code>```

But it throws many errors during compilation. How can I do that?

Update

As said in the answers - using the std::unique_ptr::reset method led to undefined behaviour. Now I know, that in such cases I should use a standard pointer.

答:
Allow me to disappoint you, but you don't. You have there a reference, which can point to either a dynamically allocated object or a stack allocated object, or, maybe, an object in a dynamically allocated array, which was not individually allocated.

You want to place its address in a class that will automatically call delete on that address. Which is invalid for most situations presented above. That is wrong. So passing a reference and putting the address of the reference in a smart pointer should never be done, ever. Especially not with reset().

At most, what you may want to do is initialize the smart pointer with the newly allocated object, for example:

```<code>auto ptr = std::unique_ptr<X>(new X(p1, p2));
</code>```

Do not ever take the address of a reference. Ever. For no reason. It's morally wrong. It's not because the use of reference addresses is invalid, because it can be valid use; it's because two months later the new colleague will want to use that address with a smart pointer because that's how (s)he heard it's done nowadays, and then come to Stack Overflow and read that they should use „reset” for that pointer. Which is wrong, painfully wrong.

ContentLicense: CC BY-SA 4.0

Body:
#include <memory>

class bar{};

void foo(bar &object){
    std::unique_ptr<bar> pointer = &object;
}

I want to assign an address of the object to the pointer. The above code obviously wont compile, because the right side of the assignment operator needs to be a std::unique_ptr. I've already tried this:

pointer = std::make_unique<bar>(object)

But it throws many errors during compilation. How can I do that?

Update

As said in the answers - using the std::unique_ptr::reset method led to undefined behaviour. Now I know, that in such cases I should use a standard pointer.

Body:
Allow me to disappoint you, but you don't. You have there a reference, which can point to either a dynamically allocated object or a stack allocated object, or, maybe, an object in a dynamically allocated array, which was not individually allocated.

You want to place its address in a class that will automatically call delete on that address. Which is invalid for most situations presented above. That is wrong. So passing a reference and putting the address of the reference in a smart pointer should never be done, ever. Especially not with reset().

At most, what you may want to do is initialize the smart pointer with the newly allocated object, for example:

auto ptr = std::unique_ptr<X>(new X(p1, p2));

Do not ever take the address of a reference. Ever. For no reason. It's morally wrong. It's not because the use of reference addresses is invalid, because it can be valid use; it's because two months later the new colleague will want to use that address with a smart pointer because that's how (s)he heard it's done nowadays, and then come to Stack Overflow and read that they should use „reset” for that pointer. Which is wrong, painfully wrong.


问:
Load balancing sockets on a horizontally scaling WebSocket server?
Every few months when thinking through a personal project that involves sockets I find myself having the question of "How would you properly load balance sockets on a dynamic horizontally scaling WebSocket server?"

I understand the theory behind horizontally scaling the WebSockets and using pub/sub models to get data to the right server that holds the socket connection for a specific user. I think I understand ways to effectively identify the server with the fewest current socket connections that I would want to route a new socket connection too. What I don't understand is how to effectively route new socket connections to the server you've picked with low socket count.

I don't imagine this answer would be tied to a specific server implementation, but rather could be applied to most servers. I could easily see myself implementing this with vert.x, node.js, or even perfect.

答:
Route the websocket requests to a load balancer that makes the decision about where to send the connections.

As an example, HAProxy has a leastconn method for long connections that picks the least recently used server with the lowest connection count.

The HAProxy backend server weightings can also be modified by external inputs, @jfriend00 detailed the technicalities of weighting in their answer.


问:
Will changing subscription interrupt bulk insert with an Azure SQL database?
Long story short, my database crashed and I wish to restore it. I am moving everything to Azure. I have a free trial subscription and have been running a bcp bulk insert for the past 4 hours.

I need more power, so I would like to move the SQL database to a new subscription and its forcing me to move the resource group as well. Will this interrupt my bcp bulk insert?

答: I had to take the chance. It did not interrupt.Boy what a difference when I increased DTU from 50 to 400.</p>


问:
Get a type identified by a string in the Scala macros
I have a bunch of strings (essentially names of java.lang. classes and some custom classes). In the macro I need to add the type to the function:

```<code>q"""propKey[${resolveType(c)(argType)}]($name, classOf[$argType])"""
</code>```

where argType is String.

So far I tried q"$argType" - but that adds the weird signature propKey[String("java.lang.Integer")](...)

with c.universe.TypeName- there's no method to get a c.universe.Type instance.

Body:
I have a bunch of strings (essentially names of java.lang. classes and some custom classes). In the macro I need to add the type to the function:

q"""propKey[${resolveType(c)(argType)}]($name, classOf[$argType])"""

where argType is String.

So far I tried q"$argType" - but that adds the weird signature propKey[String("java.lang.Integer")](...)

with c.universe.TypeName- there's no method to get a c.universe.Type instance.

Body: c.mirror.staticClass("java.lang.String").toType


问:
Unhandled Promise Rejections 17
i am writing test cases using mocha , mockgoose and chai. while running test cases i will get unhandle Promise Rejections 17 error.

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 17): Mongod shutting down

Unhandle Promise Rejection error 17

var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var expect = require("chai").expect;
var testData = require('./testData');
var apiUrl = require('./apiUrl');

chai.use(chaiHttp);

var Mongoose = require('mongoose').Mongoose,
      mongoose = new Mongoose,
      Mockgoose = require('mockgoose').Mockgoose,
      mockgoose = new Mockgoose(mongoose);

var server = require('../../../app');
var productFamily = require('../../../api/models/referenceData/productFamilyModel');
var productType = require('../../../api/models/referenceData/productTypeModel');
var product = require('../../../api/models/product/productModel');
var delivery = require('../../../api/models/delivery/deliveryModel');
var deliveryId;
var prod_common_cases = require("../common/product-common-cases");
var country_state_district_cases = require("../common/country-state-district-common-cases");
var delivery_common_cases=require("../common/delivery-common-cases");
describe('Delivery API', function () {
      before(function (done) {
            mockgoose.helper.reset().then(function () {
                  done();
            });
      });
      //Test1
      it("isMocked", function (done) {
            expect(mockgoose.helper.isMocked()).to.be.true;
            done();
      });

           it("should create productFamily", function (done) {
            prod_common_cases.create_prod_family(done);
            });
            ```

答:
We need to set timeout as it async.  Simply put this.timeout(222222) in every test. i.e. in every it function.

```<code> it("should create product Family ", function (done) {
     this.timeout(222222);
     prod_common_cases.create_prod_family(done);
 });
</code>```

Title: Unhandled Promise Rejections 17

Body:
We need to set timeout as it async.  Simply put this.timeout(222222) in every test. i.e. in every it function.

 it("should create product Family ", function (done) {
     this.timeout(222222);
     prod_common_cases.create_prod_family(done);
 });


问:
view pager load more than one fragment data once
i am working tabs in App but when fragment loaded it load the data for two fragment . how to rectify that when i clock a tab it loaded only this tab data how to do this

this is my code for view pager
     // for tab selected event

```<code>private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) {

    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}

private void setupViewPager(ViewPager viewPager) {
    //int numberOfPages = 0;

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Matches_Tab(), "Matches");
    adapter.addFragment(new NewMatches_Tab(), "New matches");
    adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
    adapter.addFragment(new ShortlistTab(), "ShortListed");
    adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
    adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
    adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
    //viewPager.setOffscreenPageLimit(numberOfPages);
    viewPager.setAdapter(adapter);
    //viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    //onTabSelectedListener(viewPager);
}

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

// view pager adapter
 class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

答:
Load your data when fragment becomes visible by overriding setUserVisibleHint Method like below:

```<code>@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
       //Load your data here ...
    }
}
</code>```

Secondly setOffScreenPageLimit(0) will not work as by default OFF SCREEN VALUE is 1 and value < 1 will not work.

Body:
i am working tabs in App but when fragment loaded it load the data for two fragment . how to rectify that when i clock a tab it loaded only this tab data how to do this

this is my code for view pager
     // for tab selected event

private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) {

    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}

private void setupViewPager(ViewPager viewPager) {
    //int numberOfPages = 0;

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Matches_Tab(), "Matches");
    adapter.addFragment(new NewMatches_Tab(), "New matches");
    adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
    adapter.addFragment(new ShortlistTab(), "ShortListed");
    adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
    adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
    adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
    //viewPager.setOffscreenPageLimit(numberOfPages);
    viewPager.setAdapter(adapter);
    //viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    //onTabSelectedListener(viewPager);
}

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

// view pager adapter
 class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

Body:
Load your data when fragment becomes visible by overriding setUserVisibleHint Method like below:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
       //Load your data here ...
    }
}

Secondly setOffScreenPageLimit(0) will not work as by default OFF SCREEN VALUE is 1 and value < 1 will not work.


问:
Ajax calls from browser over Asynchronous Controller
I am calling an external REST service (Vimeo REST API). The response of the service is JSON object. A single view in my application might end up making multiple calls to the service (for loading multiple videos).

I wanted to gauge the Pros and Cons of using the following architecture in this situation

using jquery ajax calls for loading individual videos (call made to the REST service from the browser as each video has its Id which is the only thing needed to get the details)

using ansynchronous controller action to make the REST call in the controller and then displaying the vedios

Note: I am using simple API services which do not require authentication.

答:
You may have problems with the first method, because cross-domain ajax calls (the page opened is from yoursite.com domain, and you making a call to vimeo.com) are prohibited by the browsers.

In addition to the second method, you can use JSONP provided by Vimeo API: http://vimeo.com/api/docs/response-formats

ContentLicense: CC BY-SA 2.5


问:
how would i remove some portion of
 from a table in php?
this is my table -

```<code> <table>
     <tr>
      <td>ABC</td>
     </tr>
     <tr>
      <td> </td>
     </tr>
 </table>
</code>```

and I want to remove this one table row:

```<code><tr>
   <td> </td>
</tr>
</code>```

my expected output is:

```<code> <table>
   <tr>
     <td>ABC</td>
   </tr>
 </table>
</code>```

is it possible??please help me

答:
You can do this by using JQuery function .remove(). You can look it up here

Edit: If you want to locate that specific tag, you can do that by using .next()read here, .find() read here,.parent()read here, .children read here

Title: how would i remove some portion of <tr><td> from a table in php?

Body:
this is my table -

      ABC

and I want to remove this one table row:

my expected output is:

     ABC

is it possible??please help me


问:
Laravel - How to create multiple user roles and assign privilege to them?
I have to create an application in which there are 5 types of accounts

Super admin

Inventory admin

Shop owner

Shop manager

User

So How can I create these multiple accounts with Laravel, should I use different middleware group for each. also, i have to create privileges with all.

Currently, I am using it with different middleware and session for each and separate tables in DB for each, but I don't think so that's a good way to do it.

What is the way to create these multiple accounts with Laravel.

@Thanks

答:
You can add a column to users table called user_type and
insert the decimal value for each user for example </p>

```<code>Super admin = 1;
Inventory admin = 2;
Shop owner  = 3;
Shop manager = 4;
User = 5;
</code>```

<p>and based on the user_type you can do all your operation. </p>

Body:
You can add a column to users table called user_type and
insert the decimal value for each user for example

Super admin = 1;
Inventory admin = 2;
Shop owner  = 3;
Shop manager = 4;
User = 5;

and based on the user_type you can do all your operation.


问:
What is the meaning of this regular expression? ['`?!\"-/]
What is the meaning of this regular expression?

```<code>    ['`?!\"-/]
</code>```

Why it matches parenthesis?

I used Java for development

答:
Because you didn't escape the dash -. The dash, inside a character class [] denotes a range of characters. In this case from " to /. And parentheses are between those, in ASCII.

The dash needs to be escaped \-, if it's not the first or last character, inside a character class, when you want it to be matched as a literal.

Body:
What is the meaning of this regular expression?

    ['`?!\"-/]

Why it matches parenthesis?

I used Java for development


问:
on click event leads to chain of events after first click
Im trying to add and remove class followed by click events to perform ajax calls. later on success retrieve back the old class. Like Im changing a state of input field to enable, change text of edit button to save and adding class at the same time. when i click same button it has to send modified value in input field to api and restore back to original save button. This is happening for first time when I click edit button. After saving if I click the edit button its changing the state to save and edit back again.help needed.</p>

```<code>           $.each(data, function(key, value) {
            if (parseInt(cat_id[i].innerHTML) == value.category.id) {
                base_rate[i].value = value.base_rate;
                ast[i].innerHTML = value.service_type.name;
                airportEditId[i].setAttribute("id",value.id);
                newEvent = value.id;
                airportEditId[i].classList.add("fireevent"+value.id);
                j = true;
                base_rate[i].setAttribute("disabled",true);
                      $('.fireevent'+value.id).on('click',function(){
                        $(this).attr("id",value.id);
                        $(this).parents("tr").find("input").prop('disabled',false);
                        $(this).text("save");
                        $(this).removeClass().addClass("smokeevent"+value.id).addClass("btn btn-primary");
                        console.log(this);

                      $('.smokeevent'+value.id).on('click',function(){
                           var airport = {
                              "updated_by":{{user.id}},
                              "city":parseInt($('#city_list option:selected').val()),
                              "service_type":parseInt($('#select_service1 option:selected').val()),
                              "base_rate":parseInt($(this).parents("tr").find("input").val()),
                              "vehicle_varient":[1,2]
                           };

                           console.log(airport);
                         $.ajax({
                            url: '/rapido/api/update_airportratecard/'+value.id+'/',
                            method: 'PUT',
                            headers:{'X-CSRFToken':'{{ csrf_token }}'},
                            contentType : 'application/json',
                            context:this,
                            data: JSON.stringify(airport),
                            success:function(res){
                              console.log(this);
                              $(this).text("Edit");
                              $(this).parents("tr").find("input").prop('disabled',true);
                              $(this).removeClass().addClass("btn btn-success");
                            }
                         });
                      });
                    });
</code>```

答:
You are binding the event to elements through class selector in a loop.

By the end of the loop you will have multiple event handlers assigned to all the elements belong to that class. As a result of this, one trigger of a click will invoke all those event handlers.

Instead use your own airportEditId[i] to bind the event instead of

```<code>$( airportEditId[i] ).on('click',function(){
</code>```

Note :Judging by this line

```<code>$(".airportdata").removeClass().addClass("airport_editid").addClass("btn btn-success");
</code>```

airport_editid and airportdata are classes of same element. Hence you can replace both by $( airportEditId[i] ).on('click',function(){

Edit

Another approach could be to pull these two click event handlers outside the loop and bind them separately

```<code>$.each(data, function(key, value) {
  if (parseInt(cat_id[i].innerHTML) == value.category.id) {
    base_rate[i].value = value.base_rate;
    ast[i].innerHTML = value.service_type.name;
    airportEditId[i].setAttribute("id", value.id);
    newEvent = value.id;
    j = true;
    base_rate[i].setAttribute("disabled", true);
  }
});
$(".airport_editid").on('click', function() { //notice that this line is outside
  $(this).parents("tr").find("input").prop('disabled', false);
  $(this).text("save");
  $(this).removeClass().addClass("airportdata").addClass("btn btn-primary");

  $(this).on('click', function() { //notice that this line is using `this` instead of selector
    var airport = {
      "updated_by": {
        {
          user.id
        }
      },
      "city": parseInt($('#city_list option:selected').val()),
      "service_type": parseInt($('#select_service1 option:selected').val()),
      "base_rate": parseInt($(this).parents("tr").find("input").val()),
      "vehicle_varient": [1, 2]
    };
    $.ajax({
      url: api,
      method: 'PUT',
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      },
      contentType: 'application/json',
      data: JSON.stringify(airport),
      success: function(res) {        $(".airportdata").parents("tr").find("input").prop('disabled', true);
        $(".airportdata").text("Edit");        $(".airportdata").removeClass().addClass("airport_editid").addClass("btn btn-success");
      }
    });
  });
});
</code>```

Body:
Im trying to add and remove class followed by click events to perform ajax calls. later on success retrieve back the old class. Like Im changing a state of input field to enable, change text of edit button to save and adding class at the same time. when i click same button it has to send modified value in input field to api and restore back to original save button. This is happening for first time when I click edit button. After saving if I click the edit button its changing the state to save and edit back again.help needed.

           $.each(data, function(key, value) {
            if (parseInt(cat_id[i].innerHTML) == value.category.id) {
                base_rate[i].value = value.base_rate;
                ast[i].innerHTML = value.service_type.name;
                airportEditId[i].setAttribute("id",value.id);
                newEvent = value.id;
                airportEditId[i].classList.add("fireevent"+value.id);
                j = true;
                base_rate[i].setAttribute("disabled",true);
                      $('.fireevent'+value.id).on('click',function(){
                        $(this).attr("id",value.id);
                        $(this).parents("tr").find("input").prop('disabled',false);
                        $(this).text("save");
                        $(this).removeClass().addClass("smokeevent"+value.id).addClass("btn btn-primary");
                        console.log(this);

                      $('.smokeevent'+value.id).on('click',function(){
                           var airport = {
                              "updated_by":{{user.id}},
                              "city":parseInt($('#city_list option:selected').val()),
                              "service_type":parseInt($('#select_service1 option:selected').val()),
                              "base_rate":parseInt($(this).parents("tr").find("input").val()),
                              "vehicle_varient":[1,2]
                           };

                           console.log(airport);
                         $.ajax({
                            url: '/rapido/api/update_airportratecard/'+value.id+'/',
                            method: 'PUT',
                            headers:{'X-CSRFToken':'{{ csrf_token }}'},
                            contentType : 'application/json',
                            context:this,
                            data: JSON.stringify(airport),
                            success:function(res){
                              console.log(this);
                              $(this).text("Edit");
                              $(this).parents("tr").find("input").prop('disabled',true);
                              $(this).removeClass().addClass("btn btn-success");
                            }
                         });
                      });
                    });

Body:
You are binding the event to elements through class selector in a loop.

By the end of the loop you will have multiple event handlers assigned to all the elements belong to that class. As a result of this, one trigger of a click will invoke all those event handlers.

Instead use your own airportEditId[i] to bind the event instead of

$( airportEditId[i] ).on('click',function(){

Note :Judging by this line

$(".airportdata").removeClass().addClass("airport_editid").addClass("btn btn-success");

airport_editid and airportdata are classes of same element. Hence you can replace both by $( airportEditId[i] ).on('click',function(){

Edit

Another approach could be to pull these two click event handlers outside the loop and bind them separately

$.each(data, function(key, value) {
  if (parseInt(cat_id[i].innerHTML) == value.category.id) {
    base_rate[i].value = value.base_rate;
    ast[i].innerHTML = value.service_type.name;
    airportEditId[i].setAttribute("id", value.id);
    newEvent = value.id;
    j = true;
    base_rate[i].setAttribute("disabled", true);
  }
});
$(".airport_editid").on('click', function() { //notice that this line is outside
  $(this).parents("tr").find("input").prop('disabled', false);
  $(this).text("save");
  $(this).removeClass().addClass("airportdata").addClass("btn btn-primary");

  $(this).on('click', function() { //notice that this line is using `this` instead of selector
    var airport = {
      "updated_by": {
        {
          user.id
        }
      },
      "city": parseInt($('#city_list option:selected').val()),
      "service_type": parseInt($('#select_service1 option:selected').val()),
      "base_rate": parseInt($(this).parents("tr").find("input").val()),
      "vehicle_varient": [1, 2]
    };
    $.ajax({
      url: api,
      method: 'PUT',
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      },
      contentType: 'application/json',
      data: JSON.stringify(airport),
      success: function(res) {        $(".airportdata").parents("tr").find("input").prop('disabled', true);
        $(".airportdata").text("Edit");        $(".airportdata").removeClass().addClass("airport_editid").addClass("btn btn-success");
      }
    });
  });
});


问:
pdfmake: Align table inside the column
No matter what I tried, I'm not able to align table inside of second column.

```<code>var docDefinition = {
    content: [
        {
            columns: [
                {   text: 'Column 1',
                },
                [
                    {
                        text: 'Column 2',
                        alignment: 'right' // WORKS
                    },
                    {
                        alignment: 'right', // NO EFFECT
                        table: {
                            alignment: 'right', // NO EFFECT
                            body: [
                                ['Date', '07/21/2017' ],
                                ['Representative', 'Test' ]
                            ]
                        }
                    }
                ]
            ]
        }
    ]
};

pdfMake.createPdf(docDefinition).download();
</code>```

https://jsfiddle.net/8kqnrduw/

I'm looking for any possible workarounds.

Please help

Expected result:

答:
How do you think about this idea?</p>

```<code>   {
      alignment: 'right',
      columns: [
        {
           stack: [
              { table: {....}}
           ]
        }
      ]
    }
</code>```

Title: pdfmake: Align table inside the column

Body:
No matter what I tried, I'm not able to align table inside of second column.

var docDefinition = {
    content: [
        {
            columns: [
                {   text: 'Column 1',
                },
                [
                    {
                        text: 'Column 2',
                        alignment: 'right' // WORKS
                    },
                    {
                        alignment: 'right', // NO EFFECT
                        table: {
                            alignment: 'right', // NO EFFECT
                            body: [
                                ['Date', '07/21/2017' ],
                                ['Representative', 'Test' ]
                            ]
                        }
                    }
                ]
            ]
        }
    ]
};

pdfMake.createPdf(docDefinition).download();

https://jsfiddle.net/8kqnrduw/

I'm looking for any possible workarounds.

Please help

Expected result:

Body:
How do you think about this idea?

   {
      alignment: 'right',
      columns: [
        {
           stack: [
              { table: {....}}
           ]
        }
      ]
    }


问:
How to update data by visually manipulating a chart
Is it possible at all to update data by visually manipulating a SVG object on a D3 chart? Or could point me in the right direction of where to find out how?

In this case, I am building a D3 Gantt chart and want to update an item's start and end date data by dragging the objects dates along the timeline.

答:
In D3 you can manipulate both the DOM elements based on the data and the data based on the interaction with those elements. Keep in mind that the datum is just an object, that you can change anytime. In most D3 methods, it is the first argument in the callback.

Here is a very basic demo (since you didn't provide your code). There are three bars, foo, bar and baz, whose values are 2000, 4000 and 1500. The scale's domain goes from 0 to 5000.

In the SVG I'm drawing the bars based on their data and according to the scale. However, I added a drag function that changes not only the DOM element itself but the data bound to it. This can be achieved with a callback like this:

```<code>function(d){
    //   ^--- the first argument is the datum
    d = whatever;//changing the datum
}
</code>```

Here is the demo, drag the bars horizontally and look at the console:

var data = [{
  name: 'foo',
  value: 2000
}, {
  name: 'bar',
  value: 4000
}, {
  name: 'baz',
  value: 1500
}];

var svg = d3.select("svg");

var scale = d3.scaleLinear()
  .domain([0, 5000])
  .range([0, 500]);

var bars = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("y", function(d, i) {
    return 10 + i * 30
  })
  .attr("height", 20)
  .attr("width", function(d) {
    return scale(d.value)
  })
  .style("fill", "#666")
  .call(d3.drag().on("drag", function(d) {
    d.value = scale.invert(d3.mouse(this)[0])
    d3.select(this).attr("width", scale(d.value))
    console.log("datum: " + JSON.stringify(d))
  }))```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .as-console-wrapper { max-height: 25% !important;}</code>```

<svg width="500" height="200"></svg>```

Body:
In D3 you can manipulate both the DOM elements based on the data and the data based on the interaction with those elements. Keep in mind that the datum is just an object, that you can change anytime. In most D3 methods, it is the first argument in the callback.

Here is a very basic demo (since you didn't provide your code). There are three bars, foo, bar and baz, whose values are 2000, 4000 and 1500. The scale's domain goes from 0 to 5000.

In the SVG I'm drawing the bars based on their data and according to the scale. However, I added a drag function that changes not only the DOM element itself but the data bound to it. This can be achieved with a callback like this:

function(d){
    //   ^--- the first argument is the datum
    d = whatever;//changing the datum
}

Here is the demo, drag the bars horizontally and look at the console:

var data = [{
  name: 'foo',
  value: 2000
}, {
  name: 'bar',
  value: 4000
}, {
  name: 'baz',
  value: 1500
}];

var svg = d3.select("svg");

var scale = d3.scaleLinear()
  .domain([0, 5000])
  .range([0, 500]);

var bars = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("y", function(d, i) {
    return 10 + i * 30
  })
  .attr("height", 20)
  .attr("width", function(d) {
    return scale(d.value)
  })
  .style("fill", "#666")
  .call(d3.drag().on("drag", function(d) {
    d.value = scale.invert(d3.mouse(this)[0])
    d3.select(this).attr("width", scale(d.value))
    console.log("datum: " + JSON.stringify(d))
  }))

 .as-console-wrapper { max-height: 25% !important;}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="200"></svg>


答:
As @Fawzan has said, if you only working with Roles (or a Group) then just create a groups table and then link each user to the appropriate group. You then have a single user table with a groupID for each user.

Then you could create a blade directive to help you in your app to check if a user has a specific role. (Place this inside your AppServiceProvider)

```<code>Blade::directive('hasRole', function ($role) {
    return auth()->user()->role->name = $role;
});

// Or a little more performant if you call the directive many times.

$roles = Role::all()->pluck('id', 'name')->toArray();
Blade::directive('hasRole', function ($role) use ($roles) {
    return auth()->user()->roleID == $roles[$role];
});
</code>```

Title: Laravel - How to create multiple user roles and assign privilege to them?

Body:
I have to create an application in which there are 5 types of accounts

Super admin

Inventory admin

Shop owner

Shop manager

User

So How can I create these multiple accounts with Laravel, should I use different middleware group for each. also, i have to create privileges with all.

Currently, I am using it with different middleware and session for each and separate tables in DB for each, but I don't think so that's a good way to do it.

What is the way to create these multiple accounts with Laravel.

@Thanks

Body:
As @Fawzan has said, if you only working with Roles (or a Group) then just create a groups table and then link each user to the appropriate group. You then have a single user table with a groupID for each user.

Then you could create a blade directive to help you in your app to check if a user has a specific role. (Place this inside your AppServiceProvider)

Blade::directive('hasRole', function ($role) {
    return auth()->user()->role->name = $role;
});

// Or a little more performant if you call the directive many times.

$roles = Role::all()->pluck('id', 'name')->toArray();
Blade::directive('hasRole', function ($role) use ($roles) {
    return auth()->user()->roleID == $roles[$role];
});


问:
BIML OLE DB connection uses the wrong database (sometimes)
I'm using BIML to interrogate the schema of the source and destination databases, check that everything is configured correctly, and then generate a bunch of SSIS packages. My issues is that occasionally the OLE DB connection starts using the Master system database instead of the one I've specified in the connection string. I can tell it is the master database by examining the tables that get returned.

I define the connection using BIML markup:

```<code><OleDbConnection Name="appdb" ConnectionString="Server=<#=ReplicationConfig.appdbHostname#>;Database=<#=ReplicationConfig.appdbDatabaseName#>;Integrated Security=SSPI;Provider=SQLNCLI11;" CreateInProject="true" />
</code>```

I've hit the issue mostly when trying to use the GetDatabaseSchema() method of the OleDbConnection object on the BIML root node. Though I have also run across it when trying to use an Execute SQL task. It was easy to work around with the Execute SQL task because I could fully qualify the table with [DatabaseName].[schema].[Table] but I don't have that option with the GetDatabaseSchema() method. I've also tried using ImportDB() and GetTableNodes() and they both experience the same issue.

When trying to migrate my solution from the development environment to test the issue has cropped up again. In the past this has been fixed by restarting Visual Studio (or working around it in the SQL query). However, that hasn't worked this time.

I'm using BIML Express with Visual Studio 2015.

Does anyone have any idea what could be wrong or how to get around this?

答: I ended up working around the issue by setting the default database for my login to the one that I needed to work with. For some reason BIML seems to be ignoring the database specified in the connection string.</p>

Body:
I'm using BIML to interrogate the schema of the source and destination databases, check that everything is configured correctly, and then generate a bunch of SSIS packages. My issues is that occasionally the OLE DB connection starts using the Master system database instead of the one I've specified in the connection string. I can tell it is the master database by examining the tables that get returned.

I define the connection using BIML markup:

<OleDbConnection Name="appdb" ConnectionString="Server=<#=ReplicationConfig.appdbHostname#>;Database=<#=ReplicationConfig.appdbDatabaseName#>;Integrated Security=SSPI;Provider=SQLNCLI11;" CreateInProject="true" />

I've hit the issue mostly when trying to use the GetDatabaseSchema() method of the OleDbConnection object on the BIML root node. Though I have also run across it when trying to use an Execute SQL task. It was easy to work around with the Execute SQL task because I could fully qualify the table with [DatabaseName].[schema].[Table] but I don't have that option with the GetDatabaseSchema() method. I've also tried using ImportDB() and GetTableNodes() and they both experience the same issue.

When trying to migrate my solution from the development environment to test the issue has cropped up again. In the past this has been fixed by restarting Visual Studio (or working around it in the SQL query). However, that hasn't worked this time.

I'm using BIML Express with Visual Studio 2015.

Does anyone have any idea what could be wrong or how to get around this?


答:
I've used Python3.6.  Think this should give what you are looking for.</p>

```<code>import pandas as pd

df1 = pd.read_csv('t1.csv', skipfooter=1)
df1.columns = [c.strip() for c in df1.columns]
df2 = pd.read_csv('t2.csv', skipfooter=1)
df2.columns = [c.strip() for c in df2.columns]
df2 = df2.ffill()
combined = pd.merge(df1[['Host', 'Time Up']], df2[['Host', 'Service', 'Time OK']], on='Host')
combined['Time Up'] = combined['Time Up'].apply(lambda x : x.split('(')[0])
combined['Time OK'] = combined['Time OK'].apply(lambda x : x.split('(')[0])
print(combined[combined.Service == 'server_hit_rate'])
</code>```

Title: column operation in csv [python]

Body:
I have a scenario where I am extracting a row value from a csv file.

(CSV) test1:

    Host, Time Up, Time Down, Time Unreachable, Time Undetermined
server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000

(CSV) test2:

Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined
server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000

This is my code:

df = pd.read_csv('test1.csv',skipfooter=1)
df2 = pd.read_csv('test2.csv',skipfooter=1)
combined = pd.merge(df[['Host',' Time Up']],df2[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])

Here I am trying to get the value of "server_hit_rate" which is 99% & belongs to 3rd row data.
But with this above code I am able to get the data which is in first row only. i.e.

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%   100.000%
1  server2.test.com:1717  100.000%   100.000%

The required output should be:

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%    99.000%
1  server2.test.com:1717  100.000%    99.000%

Any advice to achieve the following will be helpful.

Edit1:

import pandas as pd
import pandas
import os, shutil, glob
import sys
import datetime
import time
def t1():
    import pandas as pd
    import pandas
    today=datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
    print "date :", today
    df = pd.read_csv('t1.csv',skipfooter=1, engine='python')
    df2 = pd.read_csv('t2.csv',skipfooter=1, engine='python')
    temp = df2.ffill()[df2['Service']=='server_hit_rate']
    combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
    combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
    combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])
    combined.to_csv('test.csv',index=False)
t1()

O/P:

Wed Nov 15 10:07:01  2017
Empty DataFrame
Columns: [Host, % Time Up, % Time OK]
Index: []

Body:
I've used Python3.6.  Think this should give what you are looking for.

import pandas as pd

df1 = pd.read_csv('t1.csv', skipfooter=1)
df1.columns = [c.strip() for c in df1.columns]
df2 = pd.read_csv('t2.csv', skipfooter=1)
df2.columns = [c.strip() for c in df2.columns]
df2 = df2.ffill()
combined = pd.merge(df1[['Host', 'Time Up']], df2[['Host', 'Service', 'Time OK']], on='Host')
combined['Time Up'] = combined['Time Up'].apply(lambda x : x.split('(')[0])
combined['Time OK'] = combined['Time OK'].apply(lambda x : x.split('(')[0])
print(combined[combined.Service == 'server_hit_rate'])


问:
material design stretching image to take full browser width with auto height
the header image i have obviously wont fit to all browser width so i used following css to take auto adjust it to the browser width. however, if i dont specify the height attribute the div does not appear. specifying height as auto or % does not work either. only way it works is giving a fix px. but then that will make the whole design non responsive on small devices as the height will stay constant. please advise</p>

```<code><div fxLayout="column">
<app-nav-bar></app-nav-bar>
<div fxLayout="row" fxLayoutAlign="start stretch" style="background: url('../../assets/images/header1.png') no-repeat;background-size: 100%;height:300px">
</div>
</div>
</code>```

答: Try using "background-size:cover" instead of 100%.</p>

Body:
the header image i have obviously wont fit to all browser width so i used following css to take auto adjust it to the browser width. however, if i dont specify the height attribute the div does not appear. specifying height as auto or % does not work either. only way it works is giving a fix px. but then that will make the whole design non responsive on small devices as the height will stay constant. please advise

<app-nav-bar></app-nav-bar>


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答: If you did decide to obfuscate the database by changing column names in the future, you could alias those columns in your query to keep the indexer code functional.  I suggest indexing by name.</p>

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower


问:
ASP.Net MVC returning values from List of Checkboxes
I have a model with a property that is a List. MyObjects simply has an id, a description and a selected boolean property.

I have managed to display the items as checkboxes on my view. I did this via:

```<code> <%foreach (var cat in Model.DefaultCategories)
      {%>
    <tr>
        <td>
        <%=cat.Category %>

        </td>
        <td>
           <%=Html.CheckBoxFor(x=>cat.Selected) %>
        </td>
    </tr>
    <%
        }%>
</table>
</code>```

However, there is a problem. They all end up, when rendered, with the same names. Here's a portion of my list:

```<code>        <tr>
        <td>
        Medical

        </td>
        <td>
           <input id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />
        </td>

    </tr>

    <tr>
        <td>
        Salary

        </td>
        <td>
           <input checked="checked" id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />
        </td>
    </tr>
</code>```

They have all been named "cat.Selected".

How can I resolve this?

And then, when I submit, I need to iterate through them. With different names, I assume I can get them in my HttpPost method:

```<code>        [HttpPost]
    public ActionResult Modify(int id, FormCollection formValues)
    {
        PayeeDto p = new PayeeDto { Name = Request.Form["name"], PayeeId = id };

        Services.PayeeServices.Save(p);
        return RedirectToAction("Index");
    }
</code>```

The FormCollection will have the different names? At the moment, it just has the single 'cat.selected' item.

答:
There is a way you can submit collections to your action by using names with []. As described here http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

```<code><% for (int i = 0; i < Model.DefaultCategories.Count; i++) { %>
<td>
   <input type="checkbox" name="[<%= i %>].Selected" <% Model.DefaultCategories[i].Selected ? "checked=\"checked\"" : string.Empty %>/>
</td>
<% }%>
</code>```

Then your action can take a collection of models like so

```<code>public ActionResult Modify(int id, ICollection<UpdateModel> updates)
{}
</code>```

Body:
I have a model with a property that is a List. MyObjects simply has an id, a description and a selected boolean property.

I have managed to display the items as checkboxes on my view. I did this via:

 <%foreach (var cat in Model.DefaultCategories)
      {%>

        <%=cat.Category %>

           <%=Html.CheckBoxFor(x=>cat.Selected) %>

    <%
        }%>

However, there is a problem. They all end up, when rendered, with the same names. Here's a portion of my list:

        Medical

           <input id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />

        Salary

           <input checked="checked" id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />

They have all been named "cat.Selected".

How can I resolve this?

And then, when I submit, I need to iterate through them. With different names, I assume I can get them in my HttpPost method:

        [HttpPost]
    public ActionResult Modify(int id, FormCollection formValues)
    {
        PayeeDto p = new PayeeDto { Name = Request.Form["name"], PayeeId = id };

        Services.PayeeServices.Save(p);
        return RedirectToAction("Index");
    }

The FormCollection will have the different names? At the moment, it just has the single 'cat.selected' item.

Body:
There is a way you can submit collections to your action by using names with []. As described here http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

<% for (int i = 0; i < Model.DefaultCategories.Count; i++) { %>
<td>
   <input type="checkbox" name="[<%= i %>].Selected" <% Model.DefaultCategories[i].Selected ? "checked=\"checked\"" : string.Empty %>/>
</td>
<% }%>

Then your action can take a collection of models like so

public ActionResult Modify(int id, ICollection<UpdateModel> updates)
{}


问:
Scala manifest not Found Spark Streaming
I'm new to Spark Streaming,
From Spark Streaming I created a direct stream to Kafka Using KafkaUtils. like below

```<code>jssc = new JavaStreamingContext(sparkConf, Durations.seconds(KafkaConfig.getInstance().getBatchDuration()));

HashMap<String, String> kafkaParams = new HashMap<>();

kafkaParams.put(KafkaConstants.ZOOKEEPER_CONNECTION_STRING, zookeeperHost + ":" + zookeeperPort);
kafkaParams.put(KafkaConstants.METADATA_BROKER_LIST_STRING, bootstrapHost  + ":" + bootstrapPort);
kafkaParams.put(KafkaConstants.GROUP_ID_STRING, groupId);

HashSet<String> topicSet = new HashSet<String>();
topicSet.add(topic);

JavaPairInputDStream<String, String> topicStream = KafkaUtils.createDirectStream(jssc, String.class,
        String.class, StringDecoder.class, StringDecoder.class, kafkaParams, topicSet);

JavaDStream<String> topicMessages = topicStream.map(Tuple2::_2);
topicMessages.print()
</code>```

When I tried to run the job It is throwing below error

java.lang.NoClassDefFoundError: scala/reflect/ClassManifest

Full Stack is here :

Exception in thread "main" java.lang.NoClassDefFoundError:
  scala/reflect/ClassManifest   at
  kafka.utils.Log4jController$.(Log4jController.scala:29)     at
  kafka.utils.Log4jController$.(Log4jController.scala)  at
  kafka.utils.Logging$class.$init$(Logging.scala:29)    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala:28)
    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitionMetadata(KafkaCluster.scala:130)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitions(KafkaCluster.scala:119)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.getFromOffsets(KafkaUtils.scala:211)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:484)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:607)
    at
  org.apache.spark.streaming.kafka.KafkaUtils.createDirectStream(KafkaUtils.scala)
    at
  consumer.spark.KafkaConsumer.consumeMessages(KafkaConsumer.java:103)
    at consumer.spark.KafkaConsumer.executeStream(KafkaConsumer.java:142)
    at
  consumer.spark.KafkaConsumerService.main(KafkaConsumerService.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
    at
  org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Caused
  by: java.lang.ClassNotFoundException: scala.reflect.ClassManifest     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 23 more

Here is my pom.xml

```<code><!-- Scala version -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.10.3</version>
</dependency>

<!--Spark Core -->
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.11 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-kafka-0-8_2.11 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!--Spark Streaming -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-hive_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-hive_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!--Kafka -->
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>0.8.2.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.1</version>
</dependency>
</code>```

Please let me know how to resolve this.

答: You have defined the Scala version -> 2.10.3 and you have written artifactID with 2.11. You should change artifactID to 2.10 for every dependency and then it should work.

Body:
I'm new to Spark Streaming,
From Spark Streaming I created a direct stream to Kafka Using KafkaUtils. like below

jssc = new JavaStreamingContext(sparkConf, Durations.seconds(KafkaConfig.getInstance().getBatchDuration()));

HashMap<String, String> kafkaParams = new HashMap<>();

kafkaParams.put(KafkaConstants.ZOOKEEPER_CONNECTION_STRING, zookeeperHost + ":" + zookeeperPort);
kafkaParams.put(KafkaConstants.METADATA_BROKER_LIST_STRING, bootstrapHost  + ":" + bootstrapPort);
kafkaParams.put(KafkaConstants.GROUP_ID_STRING, groupId);

HashSet<String> topicSet = new HashSet<String>();
topicSet.add(topic);

JavaPairInputDStream<String, String> topicStream = KafkaUtils.createDirectStream(jssc, String.class,
        String.class, StringDecoder.class, StringDecoder.class, kafkaParams, topicSet);

JavaDStream<String> topicMessages = topicStream.map(Tuple2::_2);
topicMessages.print()

When I tried to run the job It is throwing below error

java.lang.NoClassDefFoundError: scala/reflect/ClassManifest

Full Stack is here :

Exception in thread "main" java.lang.NoClassDefFoundError:
  scala/reflect/ClassManifest   at
  kafka.utils.Log4jController$.(Log4jController.scala:29)     at
  kafka.utils.Log4jController$.(Log4jController.scala)  at
  kafka.utils.Logging$class.$init$(Logging.scala:29)    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala:28)
    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitionMetadata(KafkaCluster.scala:130)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitions(KafkaCluster.scala:119)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.getFromOffsets(KafkaUtils.scala:211)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:484)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:607)
    at
  org.apache.spark.streaming.kafka.KafkaUtils.createDirectStream(KafkaUtils.scala)
    at
  consumer.spark.KafkaConsumer.consumeMessages(KafkaConsumer.java:103)
    at consumer.spark.KafkaConsumer.executeStream(KafkaConsumer.java:142)
    at
  consumer.spark.KafkaConsumerService.main(KafkaConsumerService.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
    at
  org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Caused
  by: java.lang.ClassNotFoundException: scala.reflect.ClassManifest     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 23 more

Here is my pom.xml

<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.10.3</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-hive_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>0.8.2.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

Please let me know how to resolve this.