问:
Jersey 2.x Web APP on WL 12.2.1 and 12.1.3
I have a web application working with WebLogic 12.1.3 it needs to have a pointer to the correct jersey libraries.

I created a weblogic.xml file in webapp/WEB-INF folder based on a similar issue here on SW but that only solves part of the problem.

```<code><?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app
        xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">

    <container-descriptor>
        <prefer-application-packages>
            <!-- apis -->
            <package-name>javax.ws.rs.*</package-name>

            <!-- jersey providers -->
            <package-name>com.sun.jersey.*</package-name>
            <package-name>org.glassfish.jersey.*</package-name>

            <package-name>jersey.repackaged.*</package-name>

            <!-- hk2 -->
            <package-name>org.jvnet.hk2.*</package-name>
            <package-name>org.jvnet.hk2.tiger_types.*</package-name>
            <package-name>org.glassfish.hk2.*</package-name>

        </prefer-application-packages>
    </container-descriptor>
</weblogic-web-app>
</code>```

This runs properly in 12.1.3.

However with this config file WL 12.2.1 throws an error.

```<code>   org.glassfish.jersey.internal.ServiceConfigurationError: org.glassfish.jersey.server.spi.ComponentProvider: The class org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider implementing the provider interface org.glassfish.jersey.server.spi.ComponentProvider is not found. The provider implementation is ignored.
    at org.glassfish.jersey.internal.ServiceFinder.fail(ServiceFinder.java:433)
    at org.glassfish.jersey.internal.ServiceFinder.access$300(ServiceFinder.java:155)
    at org.glassfish.jersey.internal.ServiceFinder$LazyObjectIterator.handleClassNotFoundException(ServiceFinder.java:806)
    at org.glassfish.jersey.internal.ServiceFinder$LazyObjectIterator.hasNext(ServiceFinder.java:757)
    at org.glassfish.jersey.server.ApplicationHandler.getRankedComponentProviders(ApplicationHandler.java:743)
    at org.glassfish.jersey.server.ApplicationHandler.access$600(ApplicationHandler.java:184)
    at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:406)
    at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:399)
    at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:340)
    at org.glassfish.jersey.server.ApplicationHandler.createApplication(ApplicationHandler.java:366)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:342)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:343)
    at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:294)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
    at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
    at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
    at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
    at weblogic.servlet.internal.StubSecurityHelper.initServletInstance(StubSecurityHelper.java:99)
    at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:93)
    at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:69)
    at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:57)
    at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:36)
    at weblogic.servlet.internal.ServletStubImpl.initStubLifecycleHelper(ServletStubImpl.java:666)
    at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:612)
    at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:2053)
    at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:2030)
    at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1919)
    at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3063)
    at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1830)
    at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:875)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:237)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:232)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:82)
    at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:52)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:753)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:263)
    at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:53)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:265)
    at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:481)
    at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:53)
    at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:202)
    at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:52)
    at weblogic.management.deploy.internal.ConfiguredDeployments$2.doItem(ConfiguredDeployments.java:592)
    at weblogic.management.deploy.internal.parallel.BucketInvoker.invoke(BucketInvoker.java:138)
    at weblogic.management.deploy.internal.ConfiguredDeployments.transitionAppsParallel(ConfiguredDeployments.java:600)
    at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:259)
    at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:155)
    at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:221)
    at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:130)
    at weblogic.server.AbstractServerService.postConstruct(AbstractServerService.java:76)
    at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1262)
    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:332)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:374)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:698)
    at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:78)
    at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:211)
    at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:234)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:357)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:643)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
</code>```

Removing that configuration makes it run in 12.2.1.

Im using

```<code><jersey.version>2.23.1</jersey.version>
</code>```

How can I make it run on both versions without having to change the config file? I want to have the same code base and simply deploy to multiple versions of WebLogic without having to worry about library versions.

答:
Next to <prefer-application-packages> in weblogic.xml add:

```<code><prefer-application-resources>
  <!-- apis -->
  <resource-name>javax.ws.rs.*</resource-name>
  <!-- jersey -->
  <resource-name>META-INF/services/org.glassfish.jersey.*</resource-name>
  <resource-name>com.sun.jersey.*</resource-name>
  <resource-name>org.glassfish.jersey.*</resource-name>
  <resource-name>jersey.repackaged.*</resource-name>
  <!-- hk2 -->
  <resource-name>META-INF/services/org.glassfish.hk2.*</resource-name>
  <resource-name>org.glassfish.hk2.*</resource-name>
  <resource-name>org.jvnet.hk2.*</resource-name>
  <resource-name>org.jvnet.hk2.tiger_types.*</resource-name>
</prefer-application-resources>
</code>```

... and check whether it really is "hk2.tiger_types" or only "tiger_types".

Body:
I have a web application working with WebLogic 12.1.3 it needs to have a pointer to the correct jersey libraries.

I created a weblogic.xml file in webapp/WEB-INF folder based on a similar issue here on SW but that only solves part of the problem.

<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app
        xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">

    <container-descriptor>
        <prefer-application-packages>

            <package-name>javax.ws.rs.*</package-name>

            <package-name>com.sun.jersey.*</package-name>
            <package-name>org.glassfish.jersey.*</package-name>

            <package-name>jersey.repackaged.*</package-name>

            <package-name>org.jvnet.hk2.*</package-name>
            <package-name>org.jvnet.hk2.tiger_types.*</package-name>
            <package-name>org.glassfish.hk2.*</package-name>

        </prefer-application-packages>
    </container-descriptor>
</weblogic-web-app>

This runs properly in 12.1.3.

However with this config file WL 12.2.1 throws an error.

   org.glassfish.jersey.internal.ServiceConfigurationError: org.glassfish.jersey.server.spi.ComponentProvider: The class org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider implementing the provider interface org.glassfish.jersey.server.spi.ComponentProvider is not found. The provider implementation is ignored.
    at org.glassfish.jersey.internal.ServiceFinder.fail(ServiceFinder.java:433)
    at org.glassfish.jersey.internal.ServiceFinder.access$300(ServiceFinder.java:155)
    at org.glassfish.jersey.internal.ServiceFinder$LazyObjectIterator.handleClassNotFoundException(ServiceFinder.java:806)
    at org.glassfish.jersey.internal.ServiceFinder$LazyObjectIterator.hasNext(ServiceFinder.java:757)
    at org.glassfish.jersey.server.ApplicationHandler.getRankedComponentProviders(ApplicationHandler.java:743)
    at org.glassfish.jersey.server.ApplicationHandler.access$600(ApplicationHandler.java:184)
    at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:406)
    at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:399)
    at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:340)
    at org.glassfish.jersey.server.ApplicationHandler.createApplication(ApplicationHandler.java:366)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:342)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:343)
    at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:294)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
    at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
    at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
    at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
    at weblogic.servlet.internal.StubSecurityHelper.initServletInstance(StubSecurityHelper.java:99)
    at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:93)
    at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:69)
    at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:57)
    at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:36)
    at weblogic.servlet.internal.ServletStubImpl.initStubLifecycleHelper(ServletStubImpl.java:666)
    at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:612)
    at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:2053)
    at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:2030)
    at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1919)
    at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3063)
    at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1830)
    at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:875)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:237)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:232)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:82)
    at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:52)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:753)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:263)
    at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:53)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:265)
    at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:481)
    at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:53)
    at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:202)
    at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:52)
    at weblogic.management.deploy.internal.ConfiguredDeployments$2.doItem(ConfiguredDeployments.java:592)
    at weblogic.management.deploy.internal.parallel.BucketInvoker.invoke(BucketInvoker.java:138)
    at weblogic.management.deploy.internal.ConfiguredDeployments.transitionAppsParallel(ConfiguredDeployments.java:600)
    at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:259)
    at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:155)
    at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:221)
    at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:130)
    at weblogic.server.AbstractServerService.postConstruct(AbstractServerService.java:76)
    at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1262)
    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:332)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:374)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:698)
    at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:78)
    at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:211)
    at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:234)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:357)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:643)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)

Removing that configuration makes it run in 12.2.1.

Im using

<jersey.version>2.23.1</jersey.version>

How can I make it run on both versions without having to change the config file? I want to have the same code base and simply deploy to multiple versions of WebLogic without having to worry about library versions.

Body:
Next to <prefer-application-packages> in weblogic.xml add:

<prefer-application-resources>
  <!-- apis -->
  <resource-name>javax.ws.rs.*</resource-name>
  <!-- jersey -->
  <resource-name>META-INF/services/org.glassfish.jersey.*</resource-name>
  <resource-name>com.sun.jersey.*</resource-name>
  <resource-name>org.glassfish.jersey.*</resource-name>
  <resource-name>jersey.repackaged.*</resource-name>
  <!-- hk2 -->
  <resource-name>META-INF/services/org.glassfish.hk2.*</resource-name>
  <resource-name>org.glassfish.hk2.*</resource-name>
  <resource-name>org.jvnet.hk2.*</resource-name>
  <resource-name>org.jvnet.hk2.tiger_types.*</resource-name>
</prefer-application-resources>

... and check whether it really is "hk2.tiger_types" or only "tiger_types".


来源: stackexchange

问:
How to implement custom sobel-filter-based loss function using Keras
I am new to DL and Keras and currently I am trying to implement a sobel-filter-based custom loss function in Keras.

The idea is to calculate the mean squared loss of a sobel filtered prediction and a sobel filtered ground truth image.

So far, my custom loss function looks like this:

```<code>from scipy import ndimage

def mse_sobel(y_true, y_pred):

    for i in range (0, y_true.shape[0]):
        dx_true = ndimage.sobel(y_true[i,:,:,:], 1)
        dy_true = ndimage.sobel(y_true[i,:,:,:], 2)
        mag_true[i,:,:,:] = np.hypot(dx_true, dy_true)
        mag_true[i,:,:,:] *= 1.0 / np.max(mag_true[i,:,:,:])

        dx_pred = ndimage.sobel(y_pred[i,:,:,:], 1)
        dy_pred = ndimage.sobel(y_pred[i,:,:,:], 2)
        mag_pred[i,:,:,:] = np.hypot(dx_pred, dy_pred)
        mag_pred[i,:,:,:] *= 1.0 / np.max(mag_pred[i,:,:,:])

    return(K.mean(K.square(mag_pred - mag_true), axis=-1))
</code>```

Using this loss function leads to this error:

```<code>in mse_sobel
for i in range (0, y_true.shape[0]):
TypeError: __index__ returned non-int (type NoneType)
</code>```

Using the debugger I found out, that y_true.shape only returns None - fine. But when I replace y_true.shape with for example 1 such that it looks like this for i in range (0,1):, another error occurs:

```<code>in sobel
axis = _ni_support._check_axis(axis, input.ndim)

in _check_axis
raise ValueError('invalid axis')
ValueError: invalid axis
</code>```

Here, I am not sure about why the axis seems to be invalid?

Can anyone help me figure out how to implement that loss function?
Thank you very much for your help!

答:
Losses must be made with tensor operations, using the keras backend, or tensorflow/theano/cntk functions. This is the only way to keep backpropagation. Using numpy, scipy etc. breaks the graph.

Let's import the keras backend:

```<code>import keras.backend as K
</code>```

Defining the filters:

```<code>#this contains both X and Y sobel filters in the format (3,3,1,2)
#size is 3 x 3, it considers 1 input channel and has two output channels: X and Y
sobelFilter = K.variable([[[[1.,  1.]], [[0.,  2.]],[[-1.,  1.]]],
                      [[[2.,  0.]], [[0.,  0.]],[[-2.,  0.]]],
                      [[[1., -1.]], [[0., -2.]],[[-1., -1.]]]])
</code>```

Here, a function that repeats the filters for each input channel, in case your images are RGB or have more than 1 channel. This will just replicate the sobel filters for each input channel: (3,3,inputChannels, 2):

```<code>def expandedSobel(inputTensor):

    #this considers data_format = 'channels_last'
    inputChannels = K.reshape(K.ones_like(inputTensor[0,0,0,:]),(1,1,-1,1))
    #if you're using 'channels_first', use inputTensor[0,:,0,0] above

    return sobelFilter * inputChannels
</code>```

And this is the loss function:

```<code>def sobelLoss(yTrue,yPred):

    #get the sobel filter repeated for each input channel
    filt = expandedSobel(yTrue)

    #calculate the sobel filters for yTrue and yPred
    #this generates twice the number of input channels
    #a X and Y channel for each input channel
    sobelTrue = K.depthwise_conv2d(yTrue,filt)
    sobelPred = K.depthwise_conv2d(yPred,filt)

    #now you just apply the mse:
    return K.mean(K.square(sobelTrue - sobelPred))
</code>```

Apply this loss in the model:

```<code>model.compile(loss=sobelLoss, optimizer = ....)
</code>```

My experience shows that calculating the unified sobel filter sqrt(X² + Y²) brings terrible results and the resulting images sound like chess boards. But if you do want it:

```<code>def squareSobelLoss(yTrue,yPred):

    #same beginning as the other loss
    filt = expandedSobel(yTrue)
    squareSobelTrue = K.square(K.depthwise_conv2d(yTrue,filt))
    squareSobelPred = K.square(K.depthwise_conv2d(yPred,filt))

    #here, since we've got 6 output channels (for an RGB image)
    #let's reorganize in order to easily sum X² and Y²: change (h,w,6) to (h,w,3,2)
    #caution: this method of reshaping only works in tensorflow
    #if you do need this in other backends, let me know
    newShape = K.shape(squareSobelTrue)
    newShape = K.concatenate([newShape[:-1],
                              newShape[-1:]//2,
                              K.variable([2],dtype='int32')])

    #sum the last axis (the one that is 2 above, representing X² and Y²)
    squareSobelTrue = K.sum(K.reshape(squareSobelTrue,newShape),axis=-1)
    squareSobelPred = K.sum(K.reshape(squareSobelPred,newShape),axis=-1)

    #since both previous values are already squared, maybe we shouldn't square them again?
    #but you can apply the K.sqrt() in both, and then make the difference,
    #and then another square, it's up to you...
    return K.mean(K.abs(squareSobelTrue - squareSobelPred))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to DL and Keras and currently I am trying to implement a sobel-filter-based custom loss function in Keras.

The idea is to calculate the mean squared loss of a sobel filtered prediction and a sobel filtered ground truth image.

So far, my custom loss function looks like this:

from scipy import ndimage

def mse_sobel(y_true, y_pred):

    for i in range (0, y_true.shape[0]):
        dx_true = ndimage.sobel(y_true[i,:,:,:], 1)
        dy_true = ndimage.sobel(y_true[i,:,:,:], 2)
        mag_true[i,:,:,:] = np.hypot(dx_true, dy_true)
        mag_true[i,:,:,:] *= 1.0 / np.max(mag_true[i,:,:,:])

        dx_pred = ndimage.sobel(y_pred[i,:,:,:], 1)
        dy_pred = ndimage.sobel(y_pred[i,:,:,:], 2)
        mag_pred[i,:,:,:] = np.hypot(dx_pred, dy_pred)
        mag_pred[i,:,:,:] *= 1.0 / np.max(mag_pred[i,:,:,:])

    return(K.mean(K.square(mag_pred - mag_true), axis=-1))

Using this loss function leads to this error:

in mse_sobel
for i in range (0, y_true.shape[0]):
TypeError: __index__ returned non-int (type NoneType)

Using the debugger I found out, that y_true.shape only returns None - fine. But when I replace y_true.shape with for example 1 such that it looks like this for i in range (0,1):, another error occurs:

in sobel
axis = _ni_support._check_axis(axis, input.ndim)

in _check_axis
raise ValueError('invalid axis')
ValueError: invalid axis

Here, I am not sure about why the axis seems to be invalid?

Can anyone help me figure out how to implement that loss function?
Thank you very much for your help!

Body:
Losses must be made with tensor operations, using the keras backend, or tensorflow/theano/cntk functions. This is the only way to keep backpropagation. Using numpy, scipy etc. breaks the graph.

Let's import the keras backend:

import keras.backend as K

Defining the filters:

#this contains both X and Y sobel filters in the format (3,3,1,2)
#size is 3 x 3, it considers 1 input channel and has two output channels: X and Y
sobelFilter = K.variable([[[[1.,  1.]], [[0.,  2.]],[[-1.,  1.]]],
                      [[[2.,  0.]], [[0.,  0.]],[[-2.,  0.]]],
                      [[[1., -1.]], [[0., -2.]],[[-1., -1.]]]])

Here, a function that repeats the filters for each input channel, in case your images are RGB or have more than 1 channel. This will just replicate the sobel filters for each input channel: (3,3,inputChannels, 2):

def expandedSobel(inputTensor):

    #this considers data_format = 'channels_last'
    inputChannels = K.reshape(K.ones_like(inputTensor[0,0,0,:]),(1,1,-1,1))
    #if you're using 'channels_first', use inputTensor[0,:,0,0] above

    return sobelFilter * inputChannels

And this is the loss function:

def sobelLoss(yTrue,yPred):

    #get the sobel filter repeated for each input channel
    filt = expandedSobel(yTrue)

    #calculate the sobel filters for yTrue and yPred
    #this generates twice the number of input channels
    #a X and Y channel for each input channel
    sobelTrue = K.depthwise_conv2d(yTrue,filt)
    sobelPred = K.depthwise_conv2d(yPred,filt)

    #now you just apply the mse:
    return K.mean(K.square(sobelTrue - sobelPred))

Apply this loss in the model:

model.compile(loss=sobelLoss, optimizer = ....)

My experience shows that calculating the unified sobel filter sqrt(X² + Y²) brings terrible results and the resulting images sound like chess boards. But if you do want it:

def squareSobelLoss(yTrue,yPred):

    #same beginning as the other loss
    filt = expandedSobel(yTrue)
    squareSobelTrue = K.square(K.depthwise_conv2d(yTrue,filt))
    squareSobelPred = K.square(K.depthwise_conv2d(yPred,filt))

    #here, since we've got 6 output channels (for an RGB image)
    #let's reorganize in order to easily sum X² and Y²: change (h,w,6) to (h,w,3,2)
    #caution: this method of reshaping only works in tensorflow
    #if you do need this in other backends, let me know
    newShape = K.shape(squareSobelTrue)
    newShape = K.concatenate([newShape[:-1],
                              newShape[-1:]//2,
                              K.variable([2],dtype='int32')])

    #sum the last axis (the one that is 2 above, representing X² and Y²)
    squareSobelTrue = K.sum(K.reshape(squareSobelTrue,newShape),axis=-1)
    squareSobelPred = K.sum(K.reshape(squareSobelPred,newShape),axis=-1)

    #since both previous values are already squared, maybe we shouldn't square them again?
    #but you can apply the K.sqrt() in both, and then make the difference,
    #and then another square, it's up to you...
    return K.mean(K.abs(squareSobelTrue - squareSobelPred))


问:
Why template is getting compiled four times in angular 4?
I am calling a function from inside an angular template (interpolation), strangely the function is getting invoked four times !!

I do know how change detection works in angular, as I understood change-detection process kickstarts if binding value gets updated.

In this scenario, I am not binding / changing any thing as such..

var i = 0;

@Component({
  selector: 'my-app',
  template: `

{{ parentCounter() }}

  `,
})
export class App {
  name:string;
  constructor() {

  }

  parentCounter(){
    alert(`${++i} called`);
    return 5;
  }
}```

Ref: https://plnkr.co/edit/pta0s0nzcsLdTsjCtb3D?p=preview

Note: Template got compiled four times before the async event

答:
If you bind to functions in the view like

```<code><h1>{{ parentCounter() }}</h1>
</code>```

then Angular calls this function every time change detection is run.

If this function returns a new object every time it is called, you'll even get an exception in development mode.

Expression has changed since it was last checked

It is better to assign the result of the call to a field and bind to that field instead.

```<code>var i = 0;

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h1>{{ counter }}</h1>
    </div>
  `,
})
export class App {
  name:string;
  counter:number;
  constructor() {
    this.counter = this.parentCounter();
  }

  parentCounter(){
    alert(`${++i} called`);
    return 5;
  }
}
</code>```

Body:
I am calling a function from inside an angular template (interpolation), strangely the function is getting invoked four times !!

I do know how change detection works in angular, as I understood change-detection process kickstarts if binding value gets updated.

In this scenario, I am not binding / changing any thing as such..

var i = 0;

@Component({
  selector: 'my-app',
  template: `

{{ parentCounter() }}

  `,
})
export class App {
  name:string;
  constructor() {

  }

  parentCounter(){
    alert(`${++i} called`);
    return 5;
  }
}

Ref: https://plnkr.co/edit/pta0s0nzcsLdTsjCtb3D?p=preview

Note: Template got compiled four times before the async event

Body:
If you bind to functions in the view like

<h1>{{ parentCounter() }}</h1>

then Angular calls this function every time change detection is run.

If this function returns a new object every time it is called, you'll even get an exception in development mode.

Expression has changed since it was last checked

It is better to assign the result of the call to a field and bind to that field instead.

var i = 0;

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h1>{{ counter }}</h1>
    </div>
  `,
})
export class App {
  name:string;
  counter:number;
  constructor() {
    this.counter = this.parentCounter();
  }

  parentCounter(){
    alert(`${++i} called`);
    return 5;
  }
}


问:
SQLiteDataBase Create
in SQLiteDataBase , what is the duty NULL on this Line?

```<code>myDataBase = this.openOrCreateDatabase("myDB.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
</code>```

答:
Read official guideline about openOrCreateDatabase  .

```<code>SQLiteDatabase openOrCreateDatabase (String path,
                    SQLiteDatabase.CursorFactory factory,
                    DatabaseErrorHandler errorHandler)
</code>```

errorHandler value may be null.

The third parameter is a reference for CursorFactory object. This
  object will be used to create custom Cursor objects. This value is passed as null reference, since there are no needs for a custom Cursor object (You will receive a default Cursor object when reading from database).

Courtesy goes to Basic Android Database.

Title: SQLiteDataBase Create

Body:
in SQLiteDataBase , what is the duty NULL on this Line?

myDataBase = this.openOrCreateDatabase("myDB.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);

Body:
Read official guideline about openOrCreateDatabase  .

SQLiteDatabase openOrCreateDatabase (String path,
                    SQLiteDatabase.CursorFactory factory,
                    DatabaseErrorHandler errorHandler)

errorHandler value may be null.

The third parameter is a reference for CursorFactory object. This
  object will be used to create custom Cursor objects. This value is passed as null reference, since there are no needs for a custom Cursor object (You will receive a default Cursor object when reading from database).

Courtesy goes to Basic Android Database.


问:
How to get NTWDBLIB.DLL as a 64 bit file
I am trying to compile and run a really really old application on my Windows 7 box.

It seems to need NTWDBLIB.DLL from SQL Server 2000.  I can get that file, but it is a 32 bit file.  When I try to run RegServ32 on it I get an error message.

Installing SQL Server 2000 Client tools is not allowed on Windows 7.

Is there any way of getting this file?  (Short of making a 64 bit VM and installing on it to get the file.)

答: Given the error message, it looks there may be issue with SQL Server 2000 executables in Windows 7. I'd suggest you to install a newer client (2005 or 2008 with all the required SP to be run on Windows 7), they are still able to connect to a SQL Server 2000 server.</p>

ContentLicense: CC BY-SA 2.5


问:
Fusion Tables vs. Postgres with PHP
I'm trying to draw 5 sets ~30k markers to a Google map at a time, which set is drawn depends on user input/selection.

I've noticed very slow load times by the application in rendering the points using the following code.

```<code>function set_markers(minyear,maxyear,minprice,maxprice){

  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
 } else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 // this method is used to capture the response of the http request
 xmlhttp.onreadystatechange = function(){
   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     var pinpoints = JSON.parse(xmlhttp.responseText);
     var marker;
     var i=0;
     var lat;
     var lng;
     var price;
     var address;
     var post_latlng;
     var content;
     for (i = 0;i<pinpoints.length;i++){
        a=pinpoints[i];
        lat=parseFloat(a["lat"]);
        lng=parseFloat(a["lng"]);
        price=parseFloat(a["price"]);
        address=String(a["address_string"]);
        date=String(a["date_of_sale"]);
        post_latlng = new google.maps.LatLng(lat,lng);
        content ="<b>Address:</b> " + address + "</br>" + "<b>Price:</b>€ " + price + '</br>' + "<b>Date of Sale:</b> " + date;
        add_marker(address,post_latlng);
        add_InfoWindow(content,marker);
      }
     }
  }
  xmlhttp.open("GET","ajax/pinpoints.php?lat1="+lat1+"&lat2="+lat2+"&lng1="+lng1+"&lng2="+lng2+"&minyear="+minyear+"&maxyear="+maxyear+"&minprice="+minprice+"&maxprice="+maxprice,true);
  xmlhttp.send();
}

function add_marker(add,posit){
  var marker = new google.maps.Marker({
        map: map,
        title: add,
        position: posit
      });
}
function add_InfoWindow(con,mark){
  var infowindow = new google.maps.InfoWindow();
  google.maps.event.addListener(marker,'click', (function(mark,con,infowindow{
    return function(){
     infowindow.setContent(con);
     infowindow.open(map,mark);
    };
  })(marker,content,infowindow));
 }
</code>```

I am wondering if using Fusion Tables would speed up this process and still allow me to draw the points as specified in the Javascript code above? If so, how can I call a Fusion Table from my Javascript and store the return in a JSON array so as I can cause minimal disruption to the application when switching from PHP/Postgres to Fusion Tables. I've already created the relevant Fusion Table, I just need to know if and how to connect it?

Suggestions on how to optimise the above code to speed up running time are also welcome.

答:
There are a few factors to consider here when it comes to loading large items from a database onto a map/clients display.. The best answer here IMHO is to do something similar to below .

Have you used the browsers inspector/dev tools or any javascript to measure how long after the ajax request is complete to when the map finishes loading the markers. Same goes for the php and sql side of things.

Indexing.... Do these lookup columns have a index? You will be amazed at the performance difference..

Measure the sql query time, any time taken to modify your data on php's side.

If you already have a powerful enough database/server, you should be able to avoid fusion tables easily.. This is a self made choice, use judgement.

Do you need interaction with the loaded items? If so then markers or similar will be the only true correct way. Layers are quicker and can be saved as a single object for later use but you can not interact with the points.

Do you need all items at once from the start or can you load them as required. Some times using a delayed ajax call to get the markers within the visible area on the maps interaction events will perform extremely well and allows the markers to be loaded over time...cache and check a id column.

Benchmark each part of the process.. Finding the slow points and tweaking your code around them will always lead to the best performance.. Explore alternative functions/methods/loop styles/sql queries...

Clustering might be an alternative method if you can find a style to match your display and the information feedback is acceptable for your use case.

You could get complex and store a unix timestamp for each measure point and add them to the output data then add more timestamps via javascript, once everything is done, just console.log it or have a table generated below the map showing the timing per point. This can be very handy when tweaking code as it shows any major differences (ignoring network performance)

Stages Of Rows/Array Of Data To The Map:

SERVER: Querying the rows from the database into a collection or sending the rows directly to the client request.

SERVER: Cleanup / formatting the rows and sending them to the client request

CLIENT: Receiving the data into a collection or adding directly to the map.

1: Querying the rows from the database...

While SQL is not one of my favorite languages, its something that more and more i do try to optimize as i need quicker results as a result of "Big Data" and trying to squeeze every little cpu tick out of a server can save some big $$$ in the long run.

Depending on your final code/setup... you can increase performance with doing simple things like for a ajax request.

```<code>$result = pg_query($conn, "SELECT * FROM table_poi;");
header('Content-Type: application/javascript');
echo json_encode(pg_fetch_assoc($result));
exit;
</code>```

2: Cleanup / formatting...

Basically you should try to make sure you do not have to loop the database results before sending them to the client or else it will be wasted time/resources.. use array mapping if you have to.. try to index your arrays so you can use key lookups in javascript.

3: Receiving the data into a collection...

Your javascript at a quick glance looks fine, the first thing i would benchmark/test here is how long after the ajax request is complete until all the markers are loaded.. This will depend on your computer speed, not the server you are working on... This is the part that requires finding a good balance of speed vs current age of commonly used devices/performance of devices.

Title: Fusion Tables vs. Postgres with PHP

Body:
I'm trying to draw 5 sets ~30k markers to a Google map at a time, which set is drawn depends on user input/selection.

I've noticed very slow load times by the application in rendering the points using the following code.

function set_markers(minyear,maxyear,minprice,maxprice){

  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
 } else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 // this method is used to capture the response of the http request
 xmlhttp.onreadystatechange = function(){
   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     var pinpoints = JSON.parse(xmlhttp.responseText);
     var marker;
     var i=0;
     var lat;
     var lng;
     var price;
     var address;
     var post_latlng;
     var content;
     for (i = 0;i<pinpoints.length;i++){
        a=pinpoints[i];
        lat=parseFloat(a["lat"]);
        lng=parseFloat(a["lng"]);
        price=parseFloat(a["price"]);
        address=String(a["address_string"]);
        date=String(a["date_of_sale"]);
        post_latlng = new google.maps.LatLng(lat,lng);
        content ="Address: " + address + "
" + "Price:€ " + price + '
' + "Date of Sale: " + date;
        add_marker(address,post_latlng);
        add_InfoWindow(content,marker);
      }
     }
  }
  xmlhttp.open("GET","ajax/pinpoints.php?lat1="+lat1+"&lat2="+lat2+"&lng1="+lng1+"&lng2="+lng2+"&minyear="+minyear+"&maxyear="+maxyear+"&minprice="+minprice+"&maxprice="+maxprice,true);
  xmlhttp.send();
}

function add_marker(add,posit){
  var marker = new google.maps.Marker({
        map: map,
        title: add,
        position: posit
      });
}
function add_InfoWindow(con,mark){
  var infowindow = new google.maps.InfoWindow();
  google.maps.event.addListener(marker,'click', (function(mark,con,infowindow{
    return function(){
     infowindow.setContent(con);
     infowindow.open(map,mark);
    };
  })(marker,content,infowindow));
 }

I am wondering if using Fusion Tables would speed up this process and still allow me to draw the points as specified in the Javascript code above? If so, how can I call a Fusion Table from my Javascript and store the return in a JSON array so as I can cause minimal disruption to the application when switching from PHP/Postgres to Fusion Tables. I've already created the relevant Fusion Table, I just need to know if and how to connect it?

Suggestions on how to optimise the above code to speed up running time are also welcome.

Body:
There are a few factors to consider here when it comes to loading large items from a database onto a map/clients display.. The best answer here IMHO is to do something similar to below .

Have you used the browsers inspector/dev tools or any javascript to measure how long after the ajax request is complete to when the map finishes loading the markers. Same goes for the php and sql side of things.

Indexing.... Do these lookup columns have a index? You will be amazed at the performance difference..

Measure the sql query time, any time taken to modify your data on php's side.

If you already have a powerful enough database/server, you should be able to avoid fusion tables easily.. This is a self made choice, use judgement.

Do you need interaction with the loaded items? If so then markers or similar will be the only true correct way. Layers are quicker and can be saved as a single object for later use but you can not interact with the points.

Do you need all items at once from the start or can you load them as required. Some times using a delayed ajax call to get the markers within the visible area on the maps interaction events will perform extremely well and allows the markers to be loaded over time...cache and check a id column.

Benchmark each part of the process.. Finding the slow points and tweaking your code around them will always lead to the best performance.. Explore alternative functions/methods/loop styles/sql queries...

Clustering might be an alternative method if you can find a style to match your display and the information feedback is acceptable for your use case.

You could get complex and store a unix timestamp for each measure point and add them to the output data then add more timestamps via javascript, once everything is done, just console.log it or have a table generated below the map showing the timing per point. This can be very handy when tweaking code as it shows any major differences (ignoring network performance)

Stages Of Rows/Array Of Data To The Map:

SERVER: Querying the rows from the database into a collection or sending the rows directly to the client request.

SERVER: Cleanup / formatting the rows and sending them to the client request

CLIENT: Receiving the data into a collection or adding directly to the map.

1: Querying the rows from the database...

While SQL is not one of my favorite languages, its something that more and more i do try to optimize as i need quicker results as a result of "Big Data" and trying to squeeze every little cpu tick out of a server can save some big $$$ in the long run.

Depending on your final code/setup... you can increase performance with doing simple things like for a ajax request.

$result = pg_query($conn, "SELECT * FROM table_poi;");
header('Content-Type: application/javascript');
echo json_encode(pg_fetch_assoc($result));
exit;

2: Cleanup / formatting...

Basically you should try to make sure you do not have to loop the database results before sending them to the client or else it will be wasted time/resources.. use array mapping if you have to.. try to index your arrays so you can use key lookups in javascript.

3: Receiving the data into a collection...

Your javascript at a quick glance looks fine, the first thing i would benchmark/test here is how long after the ajax request is complete until all the markers are loaded.. This will depend on your computer speed, not the server you are working on... This is the part that requires finding a good balance of speed vs current age of commonly used devices/performance of devices.


问:
Update a specific key in JSON Array using PYTHON
I have a JSON file which has some key-value pairs in Arrays. I need to update/replace the value for key id with a value stored in a variable called Var1

The problem is that when I run my python code, it adds the new key-value pair in outside the inner array instead of replacing:

PYTHON SCRIPT:

import json
import sys
var1=abcdefghi

with open('C:\\Projects\\scripts\\input.json', 'r+') as f:
    json_data = json.load(f)
    json_data['id'] = var1
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()
```

<p><strong>INPUT JSON</strong>:</p>

```{
    "channel": "AT",
    "username": "Maintenance",
    "attachments": [
      {
         "fallback":"[Urgent]:",
         "pretext":"[Urgent]:",
         "color":"#D04000",
         "fields":[
            {
               "title":"SERVERS:",
               "id":"popeye",
               "short":false
            }
         ]
      }
   ]
}
```

<p><strong>OUTPUT</strong>:</p>

```{
    "username": "Maintenance",
    "attachments": [
        {
            "color": "#D04000",
            "pretext": "[Urgent]:",
            "fallback": "[Urgent]:",
            "fields": [
                {
                    "short": false,
                    "id": "popeye",
                    "title": "SERVERS:"
                }
            ]
        }
    ],
    "channel": "AT",
    "id": "abcdefghi"
}
```

答:
Below will update the id inside fields :</p>

```<code>json_data['attachments'][0]['fields'][0]['id'] = var1
</code>```

Body:
I have a JSON file which has some key-value pairs in Arrays. I need to update/replace the value for key id with a value stored in a variable called Var1

The problem is that when I run my python code, it adds the new key-value pair in outside the inner array instead of replacing:

PYTHON SCRIPT:

import json
import sys
var1=abcdefghi

with open('C:\\Projects\\scripts\\input.json', 'r+') as f:
    json_data = json.load(f)
    json_data['id'] = var1
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()

INPUT JSON:

{
    "channel": "AT",
    "username": "Maintenance",
    "attachments": [
      {
         "fallback":"[Urgent]:",
         "pretext":"[Urgent]:",
         "color":"#D04000",
         "fields":[
            {
               "title":"SERVERS:",
               "id":"popeye",
               "short":false
            }
         ]
      }
   ]
}

OUTPUT:

{
    "username": "Maintenance",
    "attachments": [
        {
            "color": "#D04000",
            "pretext": "[Urgent]:",
            "fallback": "[Urgent]:",
            "fields": [
                {
                    "short": false,
                    "id": "popeye",
                    "title": "SERVERS:"
                }
            ]
        }
    ],
    "channel": "AT",
    "id": "abcdefghi"
}

Body:
Below will update the id inside fields :

json_data['attachments'][0]['fields'][0]['id'] = var1


问:
How to generate fpdf?
I am getting error 'Class "Fpdf" not found'.</p>

```<code>use Fpdf;
Fpdf::AddPage();
Fpdf::SetFont('Courier', 'B', 18);
Fpdf::Cell(50, 25, 'Hello World!');
Fpdf::Output();
</code>```

答:
Install using Composer
composer require codedge/laravel-fpdf

Add the following lines to your config/app.php

```<code>'providers' => [
    // ...

    Codedge\Fpdf\FpdfServiceProvider::class,
],

'aliases' => [
    // ...

    'Fpdf' => Codedge\Fpdf\Facades\Fpdf::class,
]
</code>```

Use it (omit use Fpdf):

```<code>Fpdf::AddPage();
Fpdf::SetFont('Courier', 'B', 18);
Fpdf::Cell(50, 25, 'Hello World!');
Fpdf::Output();
</code>```

or

```<code>$fpdf = new Codedge\Fpdf\Fpdf\Fpdf();
$fpdf->AddPage();
$fpdf->SetFont('Courier', 'B', 18);
$fpdf->Cell(50, 25, 'Hello World!');
$fpdf->Output();
</code>```

Title: How to generate fpdf?

Body:
I am getting error 'Class "Fpdf" not found'.

use Fpdf;
Fpdf::AddPage();
Fpdf::SetFont('Courier', 'B', 18);
Fpdf::Cell(50, 25, 'Hello World!');
Fpdf::Output();

Body:
Install using Composer
composer require codedge/laravel-fpdf

Add the following lines to your config/app.php

'providers' => [
    // ...

    Codedge\Fpdf\FpdfServiceProvider::class,
],

'aliases' => [
    // ...

    'Fpdf' => Codedge\Fpdf\Facades\Fpdf::class,
]

Use it (omit use Fpdf):

Fpdf::AddPage();
Fpdf::SetFont('Courier', 'B', 18);
Fpdf::Cell(50, 25, 'Hello World!');
Fpdf::Output();

or

$fpdf = new Codedge\Fpdf\Fpdf\Fpdf();
$fpdf->AddPage();
$fpdf->SetFont('Courier', 'B', 18);
$fpdf->Cell(50, 25, 'Hello World!');
$fpdf->Output();


问:
Using a photo as
 in CSS
In my school, they said this was the way to go if we used an image as a title with a special font for ex. Now, I'm trying this but I don't really understand

1) why you should do it

2) it doesn't seem to show up unless it is given a specific height.

Can someone show me a better way to do it, while still doing this

 thing?

.title{
  background-image: url(...);
  background-repeat: no-repeat;
  /*it displays nothing now, only when I add a height here*/
}

.titlespan{
  visibility: hidden;
}
```

<pre class="lang-html prettyprint-override"><code><h1 class="title"><span class="titlespan"></span></h1>
</code>```

答:
I'm a student and in school they said this was the way to go if we
  used an image as title with a special font for ex.

Using an image with written text to replace a title in this way is not a good idea because the text (image text) may be seen differently on different screens due to dimensions and resolution.

The approach seems right if the image is only the background.
And the text is completed inside the  tags, which in turn are made visible instead of hidden.

And the special font can be set for the h1 or the span in CSS. (In the example a font is linked from google fonts in the html)

.title{
  background-image: url(https://png.pngtree.com/thumb_back/fh260/back_pic/00/05/81/6456279a0080dd1.jpg);
  background-repeat: no-repeat;
  text-align:center;
}

.titlespan{
  font-family: 'Crimson Text', serif;
  color:white;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Crimson+Text" rel="stylesheet">
<h1 class="title"><span class="titlespan">This is the title</span></h1></code>```

Title: Using a photo as <h1> in CSS

Body:
I'm a student and in school they said this was the way to go if we
  used an image as title with a special font for ex.

Using an image with written text to replace a title in this way is not a good idea because the text (image text) may be seen differently on different screens due to dimensions and resolution.

The approach seems right if the image is only the background.
And the text is completed inside the <span> tags, which in turn are made visible instead of hidden.

And the special font can be set for the h1 or the span in CSS. (In the example a font is linked from google fonts in the html)

.title{
  background-image: url(https://png.pngtree.com/thumb_back/fh260/back_pic/00/05/81/6456279a0080dd1.jpg);
  background-repeat: no-repeat;
  text-align:center;
}

.titlespan{
  font-family: 'Crimson Text', serif;
  color:white;

}

<link href="https://fonts.googleapis.com/css?family=Crimson+Text" rel="stylesheet">
<h1 class="title"><span class="titlespan">This is the title</span></h1>


问:
How to insert 1 image in 2 different directories using codeigniter
I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.</p>

```<code>public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1);
    if($this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "```";
        print_r($error);
        exit();
    }else {
        $fdata = $this->upload->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );
    $this->upload->initialize($config2);

    if (!$this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "```";
        print_r($error);
        exit();
    } else {
        $fdata = $this->upload->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done!</strong> You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}
</code>```

答:
My problem resolved with following code:</p>

```<code>    public function image()
    {

            $config['upload_path']          = './upload/images';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 0;
         $this->load->library('upload', $config);
    if (!$this->upload->do_upload('userfile')){
       } else {
       $fdata = $this->upload->data();
    $data['file2'] = 'upload/images' . $fdata['file_name'];
       }
            $config2=array(
    'upload_path'=>'upload/',
    'allowed_types'=>'jpg|jpeg|png|bmp',
    'max_size'=>0,
     );
     $this->upload->initialize($config2);

    if($this->upload->do_upload('userfile')){
   $data = array(
    'name' =>$this->input->post('name'),
   'email' =>$this->input->post('email'),
   'phone' =>$this->input->post('phone'),
   'title' =>$this->input->post('someField'),
   'image'=>$this->upload->file_name,
    );
    //Transfering data to Model
    $this->insert_model->add($data);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

                    $this->load->view('upload_success', $data);
            }
     }
     }
</code>```

Body:
I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.

public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1);
    if($this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "
";
        print_r($error);
        exit();
    }else {
        $fdata = $this->upload->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );
    $this->upload->initialize($config2);

    if (!$this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "
";
        print_r($error);
        exit();
    } else {
        $fdata = $this->upload->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done! You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}

Body:
My problem resolved with following code:

    public function image()
    {

            $config['upload_path']          = './upload/images';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 0;
         $this->load->library('upload', $config);
    if (!$this->upload->do_upload('userfile')){
       } else {
       $fdata = $this->upload->data();
    $data['file2'] = 'upload/images' . $fdata['file_name'];
       }
            $config2=array(
    'upload_path'=>'upload/',
    'allowed_types'=>'jpg|jpeg|png|bmp',
    'max_size'=>0,
     );
     $this->upload->initialize($config2);

    if($this->upload->do_upload('userfile')){
   $data = array(
    'name' =>$this->input->post('name'),
   'email' =>$this->input->post('email'),
   'phone' =>$this->input->post('phone'),
   'title' =>$this->input->post('someField'),
   'image'=>$this->upload->file_name,
    );
    //Transfering data to Model
    $this->insert_model->add($data);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

                    $this->load->view('upload_success', $data);
            }
     }
     }


问:
Inside CollapsingToolbarLayout ImageView Click event is not trigger Android
Image View inside CollapsingToolbarLayout , but click event is not triggering.
How to to solve this issue. </p>

答: You can put the ImageView outside collapsing toolbar. I was facing the same issue. Solved it by placing the view outside collapsing toolbar and anchoring it accordingly.</p>


答:
This is for doing additional operations on the query results. The reason of passing null is you want the standard SQLiteCursor behaviour

SQLiteDatabase.CursorFactory

Title: SQLiteDataBase Create


问:
i want to hide fragment layout when click any place in screen
Here is one frame layout added in bottom view. i want to hide if user click on any place on the screen

i have tried to get parent layout and on that touch listener set visiblity GONE but on touch listner is not working. here my code is.
View rootView = getWindow().getDecorView().getRootView();

```<code>    rootView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");
            return true;
        }
    });

    rootView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    llParentView = (LinearLayout) findViewById(R.id.llParentView);
    llParentView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

            return true;
        }
    });
</code>```

please any one help me in that.

答: setOnClickListener() on Fragment's Parent View Layout</p>

Body:
Here is one frame layout added in bottom view. i want to hide if user click on any place on the screen

i have tried to get parent layout and on that touch listener set visiblity GONE but on touch listner is not working. here my code is.
View rootView = getWindow().getDecorView().getRootView();

    rootView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");
            return true;
        }
    });

    rootView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    llParentView = (LinearLayout) findViewById(R.id.llParentView);
    llParentView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

            return true;
        }
    });

please any one help me in that.

ContentLicense: CC BY-SA 4.0


问:
Clearing attributes set in JSON file
How one does remove attribte set in JSON data file (-j used during chef-client run)? Lets say, I needed to override attribute:

```<code>default['param']['myParam'] = 'A'
</code>```

So I've created JSON file:

```<code>{
 "param" : {
    "myParam" : "B"
 }
}
</code>```

In the next version of cookbook, this parameter gets new value: C. I'm removing it from JSON datafile and want to use this new value, but Chef stores B even when it isn't in JSON file.

How can I ensure that Chef will ignore old attributes?

答: Your attributes will be updated once you run chef-client only. So run chef-client on node and verify the attribute value after that</p>

Title: Clearing attributes set in JSON file

Body:
How one does remove attribte set in JSON data file (-j used during chef-client run)? Lets say, I needed to override attribute:

default['param']['myParam'] = 'A'

So I've created JSON file:

{
 "param" : {
    "myParam" : "B"
 }
}

In the next version of cookbook, this parameter gets new value: C. I'm removing it from JSON datafile and want to use this new value, but Chef stores B even when it isn't in JSON file.

How can I ensure that Chef will ignore old attributes?


问:
Handling positions in FirebaseRecyclerAdapter
I have fiddled with the FirebaseRecyclerAdapter for quite some time now. It's really a great tool to populate a custom list/recycler view very fast with all of its features. However, one thing that I would like to ask is how to handle positions of items inside the adapter itself.

So for example, I want to mimic this small feature that WhatsApp has in their chats.

So, in a group chat setting, if a person sends more than one consecutive message in a row, the display name of that particular person will be invisible.

The logic behind it according to my understanding: if the person who sends the message is the same for (position - 1), then I will just make the EditText invisible for (position). This is, of course, to prevent a very long stream of text with minimum amounts of repetitive information.

Let's say the JSON tree from Firebase database is as follows.

```<code>{
  "messages" : {
    "pushed_id_1" : {
      "message_sender" : "AppleJuice",
      "message_text" : "Are you free?"
    },
    "pushed_id_2" : {
      "message_sender" : "AppleJuice",
      "message_text" : "On Saturday I mean..."
    }
  }
}
</code>```

The FirebaseRecyclerAdapter would look like this.

```<code>FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {

            @Override
            protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
                viewHolder.messageSender.setText(model.getMessage_sender());
                viewHolder.messageText.setText(model.getMessage_text());

                //put some code here to implement the feature that we need
            }
        };
        messages_recycler_menu.setAdapter(adapter);
</code>```

The furthest I have gone is to use getItemCount() method in the FirebaseRecyclerAdapter, but I am still unable to achieve the feature that mimics that of Whatsapp's that I was talking about previously.

Is there a method that can achieve this? Or am I missing something very important in this example?

答:
```<code>String lastSender=null; //or some random string

FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter =
new FirebaseRecyclerAdapter<Message, MessageViewHolder>
(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {

@Override
protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
if (model.getMessage_sender().equals(lastSender){   //check if the current sender is same as the last sender
    viewHolder.messageText.setText(model.getMessage_text());    //setting only message text
    viewHolder.messageSender.setVisibility(View.GONE);  //if required
}else{
    lastSender=model.getMessage_sender();//updating the lastSender value
    viewHolder.messageSender.setVisibility(View.VISIBLE);   //if required
    viewHolder.messageSender.setText(model.getMessage_sender());
    viewHolder.messageText.setText(model.getMessage_text());
}
     //put some code here to implement the feature that we need
}

};

messages_recycler_menu.setAdapter(adapter);
</code>```

Body:
I have fiddled with the FirebaseRecyclerAdapter for quite some time now. It's really a great tool to populate a custom list/recycler view very fast with all of its features. However, one thing that I would like to ask is how to handle positions of items inside the adapter itself.

So for example, I want to mimic this small feature that WhatsApp has in their chats.

So, in a group chat setting, if a person sends more than one consecutive message in a row, the display name of that particular person will be invisible.

The logic behind it according to my understanding: if the person who sends the message is the same for (position - 1), then I will just make the EditText invisible for (position). This is, of course, to prevent a very long stream of text with minimum amounts of repetitive information.

Let's say the JSON tree from Firebase database is as follows.

{
  "messages" : {
    "pushed_id_1" : {
      "message_sender" : "AppleJuice",
      "message_text" : "Are you free?"
    },
    "pushed_id_2" : {
      "message_sender" : "AppleJuice",
      "message_text" : "On Saturday I mean..."
    }
  }
}

The FirebaseRecyclerAdapter would look like this.

FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {

            @Override
            protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
                viewHolder.messageSender.setText(model.getMessage_sender());
                viewHolder.messageText.setText(model.getMessage_text());

                //put some code here to implement the feature that we need
            }
        };
        messages_recycler_menu.setAdapter(adapter);

The furthest I have gone is to use getItemCount() method in the FirebaseRecyclerAdapter, but I am still unable to achieve the feature that mimics that of Whatsapp's that I was talking about previously.

Is there a method that can achieve this? Or am I missing something very important in this example?


问:
double quotes inside double quotes
i am writing the following connection string into web.config
but it giving me error.what is the correct way to write it?</p>

```<code><add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>
</code>```

答:
web.config is XML, so you need to escape the inner quotes to ":

```<code><add name="stargaze_stargazeConnectionString1"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>
</code>```

Title: double quotes inside double quotes

Body:
i am writing the following connection string into web.config
but it giving me error.what is the correct way to write it?

<add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>

Body:
web.config is XML, so you need to escape the inner quotes to &quot;:

<add name="stargaze_stargazeConnectionString1"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=&quot;D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf&quot;;Integrated Security=True;User Instance=True"/>


问:
Update an existing column in mysql
I have a column pass VARCHAR(50). I need to change it to VARCHAR(255):

```<code>ALTER TABLE college
ALTER column pass varchar (255) NOT NULL

ALTER TABLE college
CHANGE COLUMN pass VARCHAR (255) NOT NULL;

ALTER TABLE college
SET COLUMN pass VARCHAR (255) NOT NULL;
</code>```

I tried the above commands, but nothing is working.

答:
You are using it wrong, try like that: </p>

```<code>ALTER TABLE college
 CHANGE  pass pass VARCHAR (255) NOT NULL;
</code>```

Title: Update an existing column in mysql

Body:
I have a column pass VARCHAR(50). I need to change it to VARCHAR(255):

ALTER TABLE college
ALTER column pass varchar (255) NOT NULL

ALTER TABLE college
CHANGE COLUMN pass VARCHAR (255) NOT NULL;

ALTER TABLE college
SET COLUMN pass VARCHAR (255) NOT NULL;

I tried the above commands, but nothing is working.

Body:
You are using it wrong, try like that:

ALTER TABLE college
 CHANGE  pass pass VARCHAR (255) NOT NULL;


问:
running multiple commands in parallel in bash
I want to run multiple scripts/commands in parallel in bash.
Here is the bash script :

```<code>python test_script.py &
docker stop process &
docker stop process1 &
sleep(1)
wait

docker start process1 &
docker start process &
wait
</code>```

Here, im running multiple dockers and want to start/stop docker when my script python test_script.py is running.

for ex: python script is running and on parallel i want to stop process & process1 docker. python script is still in-progress and then say wait or sleep for 1 min and start the process again.

How can i achieve it ?

答:
From your original description, it seems that we can organize the problem into two scripts

A main python script test_script.py

A docker restart script say restart_docker.sh which contains all the docker related commands that will be executed in sequence

```<code>docker stop process
sleep 1m
docker start process
</code>```

With GNU parallel, you can provide these two scripts as arguments to be executed in parallel

```<code>parallel ::: 'python test_script.py' 'bash restart_docker.sh'
</code>```

Body:
I want to run multiple scripts/commands in parallel in bash.
Here is the bash script :

python test_script.py &
docker stop process &
docker stop process1 &
sleep(1)
wait

docker start process1 &
docker start process &
wait

Here, im running multiple dockers and want to start/stop docker when my script python test_script.py is running.

for ex: python script is running and on parallel i want to stop process & process1 docker. python script is still in-progress and then say wait or sleep for 1 min and start the process again.

How can i achieve it ?

Body:
From your original description, it seems that we can organize the problem into two scripts

A main python script test_script.py

A docker restart script say restart_docker.sh which contains all the docker related commands that will be executed in sequence

docker stop process
sleep 1m
docker start process

With GNU parallel, you can provide these two scripts as arguments to be executed in parallel

parallel ::: 'python test_script.py' 'bash restart_docker.sh'


问:
Split date in pandas
In excel file I have columns "date" which contains dates in the following format:
11/17/2017 2:40:40 PM this translates to month/day/year H:M:S

When importing this file in Pandas its dtype is <M8[ns]

So, I want to split the values. Desired output have to be 11/17/2017 and it has to be in the same format as it would be if we do this split in excel file. I mean, I need the values to be like 11/17/2017 but format this date to show only day and month like this:17-Nov

I tried several methods but didn't work. Can anyone help me?

答:
It seems you need strftime because if need 17-Nov as datetime it is not possible in python:

```<code>df = pd.DataFrame({'date':pd.to_datetime(['11/17/2017 2:40:40 PM','11/17/2017 2:40:40 PM'])})
print (df)
                 date
0 2017-11-17 14:40:40
1 2017-11-17 14:40:40

print (df['date'].dt.strftime('%d/%m/%Y'))
0    17/11/2017
1    17/11/2017
Name: date, dtype: object

print (df['date'].dt.strftime('%d-%b'))
0    17-Nov
1    17-Nov
Name: date, dtype: object
</code>```

Title: Split date in pandas

Body:
It seems you need strftime because if need 17-Nov as datetime it is not possible in python:

df = pd.DataFrame({'date':pd.to_datetime(['11/17/2017 2:40:40 PM','11/17/2017 2:40:40 PM'])})
print (df)
                 date
0 2017-11-17 14:40:40
1 2017-11-17 14:40:40

print (df['date'].dt.strftime('%d/%m/%Y'))
0    17/11/2017
1    17/11/2017
Name: date, dtype: object

print (df['date'].dt.strftime('%d-%b'))
0    17-Nov
1    17-Nov
Name: date, dtype: object


问:
Xsl transformation of large xmls
I am aware of ways of applying XSL transformation to XMLs in java using

javax.xml.transform.Transformer

This approach works well for small XML data. But when it comes to large XML data where DOM based approach is difficult to use because of memory constraints, this becomes a nightmare.

I want to know what is the best approach to apply XSL transformation to large XMLs. Is there any transformer which operates on SAX and not DOM?

答: If you are working with huge XSLT and/or working with multiple XSLT's then compiling and caching the xslt is a good option to improve performance. This article explains how to cache xslt's</p>

Title: Xsl transformation of large xmls


问:
What are the differences between unit tests, integration tests, smoke tests, and regression tests?
What are unit tests, integration tests, smoke tests, and regression tests?  What are the differences between them and which tools can I use for each of them?

For example, I use JUnit and NUnit for unit testing and integration testing. Are there any tools for the last two, smoke testing or regression testing?

答:
Smoke and sanity testing are both performed after a software build to identify whether to start testing. Sanity may or may not be executed after smoke testing. They can be executed separately or at the same time - sanity being immediately after smoke.

Because sanity testing is more in-depth and takes more time, in most cases it is well worth to be automated.

Smoke testing usually takes no longer than 5-30 minutes for execution. It is more general: it checks a small number of core functionalities of the whole system, in order to verify that the stability of the software is good enough for further testing and that there are no issues, blocking the run of the planned test cases.

Sanity testing is more detailed than smoke and may take from 15 minutes up to a whole day, depending on the scale of the new build. It is a more specialized type of acceptance testing, performed after progression or re-testing. It checks the core features of certain new functionalities and/or bug fixes together with some closely related to them features, in order to verify that they are functioning as to the required operational logic, before regression testing can be executed at a larger scale.


问:
How to create a database in docker mysql/mysql-server image and connect it through java
I have pulled the image mysql/mysql-server from the docker hub. Now I wanted to create a table with name and email columns and connect to this mysql db from java

Can I connect to this db using the below statement ?

Connection connect = DriverManager.getConnection("jdbc:mysql://xxxxxxx:xxxxx/dbname","uname","pwd");

答:
You can use docker inspect <container_name> to check details of a docker container. In the output you can find IP address of the container under "NetworkSettings" section.

After getting the IP address of the container, you can treat it just like a remote server and connect to it using normal mysql-client or in Java code using JDBC.


问:
Hover dosnt fit in my navigation because every icon has a different size
I'm looking for a solution to this problem: I have a vertical navigation and in this the icons I've used have different sizes but I "fixed" that by resizing them with different IDs. Now I want a :hover effect on them. But because of the different sizes of the icons the hover dosnt fit my navigation border. I want them do behave like this: https://www.w3schools.com/w3css/tryw3css_templates_dark_portfolio.htm
Can somebody help me with this?

```<code>  <nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  <a class="icontitle" href="./fotowand.html">HOME</a>
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   <a class="icontitle" href="">STUDIEN-<br>INTERESSIERTE</a>
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   <a class="icontitle" href="">STUDIERENDE</a>
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   <a class="icontitle" href="">UNTERNEHMEN</a>
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   <a class="icontitle" href="">KONTAKT</a>
   <div class="after"></div>
 </div>
</nav>
</code>```

This is my CSS

```<code>  .navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;
  width:200px;
  height: 100px;
  display: none;
  text-align: center;

  color: white;

}

.navItem:hover .after {
 background-color: rgba(0, 0, 0, .6);
 display: block;
 left:0px;
}
</code>```

Navigation Screenshot

Navigation Screenshot

答:
You can apply a transform effect on hover.

```<code>.navItem:hover{
   transform: scale(2);
}
</code>```

.navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
  transition: all 500ms ease;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;

  display: none;
  text-align: center;

  color: white;

}

.navItem:hover {
    transform: scale(2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  HOME
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   STUDIEN-<br>INTERESSIERTE
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   STUDIERENDE
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   UNTERNEHMEN
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   KONTAKT
   <div class="after"></div>
 </div>
</nav></code>```

Body:
I'm looking for a solution to this problem: I have a vertical navigation and in this the icons I've used have different sizes but I "fixed" that by resizing them with different IDs. Now I want a :hover effect on them. But because of the different sizes of the icons the hover dosnt fit my navigation border. I want them do behave like this: https://www.w3schools.com/w3css/tryw3css_templates_dark_portfolio.htm
Can somebody help me with this?

  HOME

   STUDIEN-
INTERESSIERTE

   STUDIERENDE

   UNTERNEHMEN

   KONTAKT

This is my CSS

  .navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;
  width:200px;
  height: 100px;
  display: none;
  text-align: center;

  color: white;

}

.navItem:hover .after {
 background-color: rgba(0, 0, 0, .6);
 display: block;
 left:0px;
}

Navigation Screenshot

Navigation Screenshot

Body:
You can apply a transform effect on hover.

.navItem:hover{
   transform: scale(2);
}

.navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
  transition: all 500ms ease;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;

  display: none;
  text-align: center;

  color: white;

}

.navItem:hover {
    transform: scale(2);
}

<nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  <a class="icontitle" href="./fotowand.html">HOME</a>
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   <a class="icontitle" href="">STUDIEN-<br>INTERESSIERTE</a>
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   <a class="icontitle" href="">STUDIERENDE</a>
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   <a class="icontitle" href="">UNTERNEHMEN</a>
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   <a class="icontitle" href="">KONTAKT</a>
   <div class="after"></div>
 </div>
</nav>


答:
You should do this. Did you run the container before? From where you want to connect to the DB (a container?), try a "telnet  "

If the connection is accepted, you are OK.

Title: How to create a database in docker mysql/mysql-server image and connect it through java

Body:
I have pulled the image mysql/mysql-server from the docker hub. Now I wanted to create a table with name and email columns and connect to this mysql db from java

Can I connect to this db using the below statement ?

Connection connect = DriverManager.getConnection("jdbc:mysql://xxxxxxx:xxxxx/dbname","uname","pwd");


问:
After updating Android Studio error in compiling
Can anyone help me to resolve this issue. the project was working fine in old version. thanks in advance. please do help me. I googled and tried many ways but not getting sucess
error shows like this

```<code>Information:Gradle tasks [clean, :app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
Error:resource

    android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
    Error:resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
    Error:failed linking references.
    Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:Execution failed for task ':app:processDebugResources'.
    > Failed to execute aapt
    Information:BUILD FAILED in 44s
    Information:7 errors
    Information:0 warnings
    Information:See complete output in console
</code>```

gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    defaultConfig {
        applicationId "com.example.chippy.entekottayam"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.google.android.gms:play-services:11.4.2'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.android.support:recyclerview-v7:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

Can anyone help me to resolve this issue. the project was working fine in old version. thanks in advance. please do help me. I googled and tried many ways but not getting sucess

答:
This could also be caused by missing the "@" symbol in the reference to the style, for example doing "android:style/TextAppearance.Material.Widget.Button.Borderless.Colored" instead of "@android:style/TextAppearance.Material.Widget.Button.Borderless.Colored".

AAPT would ignore such mistakes and then your app could run into issues during runtime, AAPT2 catches these mistakes early on during compilation.

Body:
Can anyone help me to resolve this issue. the project was working fine in old version. thanks in advance. please do help me. I googled and tried many ways but not getting sucess
error shows like this

Information:Gradle tasks [clean, :app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
Error:resource

    android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
    Error:resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
    Error:failed linking references.
    Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:Execution failed for task ':app:processDebugResources'.
    > Failed to execute aapt
    Information:BUILD FAILED in 44s
    Information:7 errors
    Information:0 warnings
    Information:See complete output in console

gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    defaultConfig {
        applicationId "com.example.chippy.entekottayam"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.google.android.gms:play-services:11.4.2'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.android.support:recyclerview-v7:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Can anyone help me to resolve this issue. the project was working fine in old version. thanks in advance. please do help me. I googled and tried many ways but not getting sucess


问:
How to change the attributes of the
```

<p>How can i change the value of <code>data-amount="100"</code> to my desired value</p>

<p>I tried like</p>

```document.getElementById("paymentWidget").attr("data-amount") = total
```

<p>But it is showing error like </p>

```document.getElementById(...).attr is not a function
```

How can i fix this and set values dynamically ?

答:
Try this</p>

```<code>document.getElementById('paymentWidget').setAttribute('data-amount', total)
</code>```

Title: How to change the attributes of the <script> tag

Body:
Here is my script tag

How can i change the value of data-amount="100" to my desired value

I tried like

document.getElementById("paymentWidget").attr("data-amount") = total

But it is showing error like

document.getElementById(...).attr is not a function

How can i fix this and set values dynamically ?

Body:
Try this

document.getElementById('paymentWidget').setAttribute('data-amount', total)


问:
regular expression pattern replacement *.xml
I am new to regular expression, and don't deal with it regularly so posting it as a question.

I want to replace

```<code>blah.xml
haha.xml
</code>```

to

```<code>user/home/blah.xml
user/home/haha.xml
</code>```

I would prefer to do it with sed.

Cheers

SK

答:
```<code>sed -e 's#^#user/home/#'
</code>```

inserts user/home/ at the beginning of each line.

Body:
I am new to regular expression, and don't deal with it regularly so posting it as a question.

I want to replace

blah.xml
haha.xml

to

user/home/blah.xml
user/home/haha.xml

I would prefer to do it with sed.

Cheers

SK

Body:
sed -e 's#^#user/home/#'

inserts user/home/ at the beginning of each line.