问:
Adding hashrouter to routes makes 'push' to stop render components
I have a ConnectedRouter to which I wanted to add hashes to all the routes so I added the HashRouter component like this:

```<code>// @flow
import React from 'react';

import { Router, Route,Switch } from 'react-router'
import { HashRouter } from 'react-router-dom'
import { ConnectedRouter } from 'react-router-redux';
import { routerActions } from 'react-router-redux';
import { UserAuthWrapper } from 'redux-auth-wrapper';
import StudiesViewContainer from './components/views/studies/StudiesViewContainer';
import NotificationsViewContainer from './components/views/notifications/NotificationsViewContainer';
import UserView from './components/views/user/UserView';
import StudyViewContainer from './components/views/studies/StudyViewContainer';
import { getUser } from './reducers';
import LoginView from './components/views/login';
import NotFoundView from './components/views/notFound';
import ForbiddenView from './components/views/forbidden';

const UserIsAuthenticated = UserAuthWrapper({
  authSelector: getUser,
  redirectAction: routerActions.replace,
  failureRedirectPath: '/',
  wrapperDisplayName: 'UserIsAuthenticated'
});

const configRouter = (history: Object) => {
  return () =>
    <ConnectedRouter history={ history }>
      <HashRouter>
        <Switch>
          <Route path="/studies" component={ StudiesViewContainer } />
          <Route path="/study/:id" component={ StudyViewContainer } />
          <Route path="/user"  component={ UserView } />
          <Route path="/notifications" component={ NotificationsViewContainer } />
          <Route path="/forbidden" component={ ForbiddenView } />
          <Route path="/not-found" component={ NotFoundView } />
          <Route path="/" component={ LoginView } />
          <Route path="*" component={ NotFoundView } />
        </Switch>
      </HashRouter>
    </ConnectedRouter>
};

export default configRouter;
</code>```

The problem is that when I do something like this:

```<code>push('studies')
</code>```

The route does not add the hash and the new components are not rendered.

I added the browser history to my store, here is the configureStore file:

```<code>// @flow
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory'
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga'
import {
  persistStore,
  autoRehydrate,
  createTransform
} from 'redux-persist';

import mainSaga from '../sagas';
import reducer from '../reducers';

const history = createHistory();
const routingMiddleware = routerMiddleware(history);
const sagaMiddleware = createSagaMiddleware();

// Remove error field from persisted auth substate
let authTransform = createTransform(
  (inboundState, key) =>
    key === 'auth' ?
      { ...inboundState, error: undefined }:
      inboundState,
  outboundState => outboundState,
  {
    whitelist: [
      'auth',
      'permissions'
    ]
  }
);

const configureStore = (): Promise<*> => {
  let middlewares = [routingMiddleware,thunk, sagaMiddleware ];
  let composeEnhancers = compose;

  if(process.env.NODE_ENV !== 'production') {
    composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  }

  const store = createStore(
    reducer,
    composeEnhancers(
      applyMiddleware(...middlewares),
      autoRehydrate()));

  sagaMiddleware.run(mainSaga);

  return new Promise(resolve => {
    persistStore(
      store, {
        whitelist: ['auth', 'permissions'],
        debounce: 500,
        transforms: [
          authTransform
        ]
      },
      () => resolve({ store, history })
    );
  });
};

export default configureStore;
</code>```

Can anyone help me get the push working as expected?

I am using the following versions of router in package json:

```<code>"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "next",
</code>```

答:
I added the browser history to my store, here is the configureStore file:

Most likely that issue lies on difference between history-object, used in router, and proposed in redux state. Then history created in redux side const history = createHistory();, it seems that it had not linked with ConnectedRouter object, but it can't be followed by supposed code.

If valid history object is passed to ConnectedRouter, try to check that subsequent router actions are to intercepted with saga process or other middleware. Try to follow on emitting actions flow by https://github.com/gaearon/redux-devtools tool.

Also you can try to perform manual updating, by adding root component with full lifecycle (Inherited from React.Component class), and add there following code:

```<code>this.props.history.listen((location, action) => {
  console.log("on route change");
});
</code>```

Then you can discover had router state been changed, and if action is taken, just perform forceUpdate method in root component. Also consult this documentation: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md

Body:
I have a ConnectedRouter to which I wanted to add hashes to all the routes so I added the HashRouter component like this:

// @flow
import React from 'react';

import { Router, Route,Switch } from 'react-router'
import { HashRouter } from 'react-router-dom'
import { ConnectedRouter } from 'react-router-redux';
import { routerActions } from 'react-router-redux';
import { UserAuthWrapper } from 'redux-auth-wrapper';
import StudiesViewContainer from './components/views/studies/StudiesViewContainer';
import NotificationsViewContainer from './components/views/notifications/NotificationsViewContainer';
import UserView from './components/views/user/UserView';
import StudyViewContainer from './components/views/studies/StudyViewContainer';
import { getUser } from './reducers';
import LoginView from './components/views/login';
import NotFoundView from './components/views/notFound';
import ForbiddenView from './components/views/forbidden';

const UserIsAuthenticated = UserAuthWrapper({
  authSelector: getUser,
  redirectAction: routerActions.replace,
  failureRedirectPath: '/',
  wrapperDisplayName: 'UserIsAuthenticated'
});

const configRouter = (history: Object) => {
  return () =>
    <ConnectedRouter history={ history }>
      <HashRouter>
        <Switch>
          <Route path="/studies" component={ StudiesViewContainer } />
          <Route path="/study/:id" component={ StudyViewContainer } />
          <Route path="/user"  component={ UserView } />
          <Route path="/notifications" component={ NotificationsViewContainer } />
          <Route path="/forbidden" component={ ForbiddenView } />
          <Route path="/not-found" component={ NotFoundView } />
          <Route path="/" component={ LoginView } />
          <Route path="*" component={ NotFoundView } />
        </Switch>
      </HashRouter>
    </ConnectedRouter>
};

export default configRouter;

The problem is that when I do something like this:

push('studies')

The route does not add the hash and the new components are not rendered.

I added the browser history to my store, here is the configureStore file:

// @flow
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory'
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga'
import {
  persistStore,
  autoRehydrate,
  createTransform
} from 'redux-persist';

import mainSaga from '../sagas';
import reducer from '../reducers';

const history = createHistory();
const routingMiddleware = routerMiddleware(history);
const sagaMiddleware = createSagaMiddleware();

// Remove error field from persisted auth substate
let authTransform = createTransform(
  (inboundState, key) =>
    key === 'auth' ?
      { ...inboundState, error: undefined }:
      inboundState,
  outboundState => outboundState,
  {
    whitelist: [
      'auth',
      'permissions'
    ]
  }
);

const configureStore = (): Promise<*> => {
  let middlewares = [routingMiddleware,thunk, sagaMiddleware ];
  let composeEnhancers = compose;

  if(process.env.NODE_ENV !== 'production') {
    composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  }

  const store = createStore(
    reducer,
    composeEnhancers(
      applyMiddleware(...middlewares),
      autoRehydrate()));

  sagaMiddleware.run(mainSaga);

  return new Promise(resolve => {
    persistStore(
      store, {
        whitelist: ['auth', 'permissions'],
        debounce: 500,
        transforms: [
          authTransform
        ]
      },
      () => resolve({ store, history })
    );
  });
};

export default configureStore;

Can anyone help me get the push working as expected?

I am using the following versions of router in package json:

"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "next",

Body:
I added the browser history to my store, here is the configureStore file:

Most likely that issue lies on difference between history-object, used in router, and proposed in redux state. Then history created in redux side const history = createHistory();, it seems that it had not linked with ConnectedRouter object, but it can't be followed by supposed code.

If valid history object is passed to ConnectedRouter, try to check that subsequent router actions are to intercepted with saga process or other middleware. Try to follow on emitting actions flow by https://github.com/gaearon/redux-devtools tool.

Also you can try to perform manual updating, by adding root component with full lifecycle (Inherited from React.Component class), and add there following code:

this.props.history.listen((location, action) => {
  console.log("on route change");
});

Then you can discover had router state been changed, and if action is taken, just perform forceUpdate method in root component. Also consult this documentation: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md


来源: stackexchange

问:
Enabling Both HTTP and HTTPS for an Application in Tomcat 8
I have one application deployed in Tomcat 8, which i want to run on http and https both. I have configured server.xml to run both on http and https. web.xml for application is also configured to handle both requests. Issue is i am getting response for https requests only. For http it says request timed out.

https port configured is 9999 and http port is 8080.
https://URL:9999/path  => working
http://URL:8080/path   => not working

Below is attached code for server.xml , web.xml inside WEB-INF directory and catalina.out response when i start Tomcat.

SERVER.XML

```<code><Connector port="8080" protocol="HTTP/1.1"
       connectionTimeout="20000"/>
  <Connector
       protocol="org.apache.coyote.http11.Http11NioProtocol"
       port="9999" maxThreads="200"
       scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="/root/.keystore" keystorePass="Pooltooadm!n"
       clientAuth="false" sslProtocol="TLS"/>
</code>```

web.xml

```<code>    <welcome-file-list>
        <welcome-file>/index.html</welcome-file>
        <welcome-file>/index.xhtml</welcome-file>
        <welcome-file>/index.htm</welcome-file>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    <security-constraint>
    <web-resource-collection>
    <web-resource-name>HTTP</web-resource-name>
    <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
    <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
    </security-constraint>
    <security-constraint>
    <web-resource-collection>
    <web-resource-name>HTTPS</web-resource-name>
    <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
    </security-constraint>

    <error-page>
    <error-code>404</error-code>
    <location>/index.html</location>
  </error-page>
</code>```

CATALINA.OUT=>

```<code>17-Nov-2017 14:07:46.349 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.5.23
17-Nov-2017 14:07:46.433 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Sep 28 2017 10:30:11 UTC
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.5.23.0
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            4.4.21-90-default
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/java/jdk1.8.0_151/jre
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_151-b12
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/opt/apache-tomcat-8.5.23/conf/logging.properties
17-Nov-2017 14:07:46.595 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
17-Nov-2017 14:07:46.595 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/opt/apache-tomcat-8.5.23/temp
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
17-Nov-2017 14:07:51.020 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
17-Nov-2017 14:07:51.711 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Nov-2017 14:07:51.832 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-jsse-nio-9999"]
17-Nov-2017 14:08:00.507 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Nov-2017 14:08:00.509 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
17-Nov-2017 14:08:00.510 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Nov-2017 14:08:00.592 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 28123 ms
17-Nov-2017 14:08:01.206 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
17-Nov-2017 14:08:01.207 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.23
17-Nov-2017 14:08:01.495 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/host-manager]
17-Nov-2017 14:08:11.450 WARNING [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [159] milliseconds.
17-Nov-2017 14:08:12.311 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/host-manager] has finished in [10,816] ms
17-Nov-2017 14:08:12.312 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/manager]
17-Nov-2017 14:08:12.924 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/manager] has finished in [612] ms
17-Nov-2017 14:08:12.924 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/docs]
17-Nov-2017 14:08:13.415 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/docs] has finished in [491] ms
17-Nov-2017 14:08:13.415 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/ROOT]
17-Nov-2017 14:08:13.825 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/ROOT] has finished in [409] ms
17-Nov-2017 14:08:13.825 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/examples]
17-Nov-2017 14:08:20.096 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/examples] has finished in [6,271] ms
17-Nov-2017 14:08:20.097 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/pooltooadmin]
17-Nov-2017 14:08:20.549 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/pooltooadmin] has finished in [451] ms
17-Nov-2017 14:08:20.836 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
17-Nov-2017 14:08:20.999 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["https-jsse-nio-9999"]
17-Nov-2017 14:08:21.163 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
17-Nov-2017 14:08:21.204 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 20612 ms
</code>```

答:
Maybe port 8080 is taken already. If you have apache2 on your server the default port for apache2 is 8080. Try another port or check:</p>

```<code>sudo netstat -tulpn |grep apache
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one application deployed in Tomcat 8, which i want to run on http and https both. I have configured server.xml to run both on http and https. web.xml for application is also configured to handle both requests. Issue is i am getting response for https requests only. For http it says request timed out.

https port configured is 9999 and http port is 8080.
https://URL:9999/path  => working
http://URL:8080/path   => not working

Below is attached code for server.xml , web.xml inside WEB-INF directory and catalina.out response when i start Tomcat.

SERVER.XML

<Connector port="8080" protocol="HTTP/1.1"
       connectionTimeout="20000"/>
  <Connector
       protocol="org.apache.coyote.http11.Http11NioProtocol"
       port="9999" maxThreads="200"
       scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="/root/.keystore" keystorePass="Pooltooadm!n"
       clientAuth="false" sslProtocol="TLS"/>

web.xml

    <welcome-file-list>
        <welcome-file>/index.html</welcome-file>
        <welcome-file>/index.xhtml</welcome-file>
        <welcome-file>/index.htm</welcome-file>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    <security-constraint>
    <web-resource-collection>
    <web-resource-name>HTTP</web-resource-name>
    <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
    <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
    </security-constraint>
    <security-constraint>
    <web-resource-collection>
    <web-resource-name>HTTPS</web-resource-name>
    <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
    </security-constraint>

    <error-page>
    <error-code>404</error-code>
    <location>/index.html</location>
  </error-page>

CATALINA.OUT=>

17-Nov-2017 14:07:46.349 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.5.23
17-Nov-2017 14:07:46.433 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Sep 28 2017 10:30:11 UTC
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.5.23.0
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            4.4.21-90-default
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
17-Nov-2017 14:07:46.593 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/java/jdk1.8.0_151/jre
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_151-b12
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.594 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/opt/apache-tomcat-8.5.23/conf/logging.properties
17-Nov-2017 14:07:46.595 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
17-Nov-2017 14:07:46.595 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/opt/apache-tomcat-8.5.23
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/opt/apache-tomcat-8.5.23/temp
17-Nov-2017 14:07:46.637 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
17-Nov-2017 14:07:51.020 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
17-Nov-2017 14:07:51.711 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Nov-2017 14:07:51.832 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-jsse-nio-9999"]
17-Nov-2017 14:08:00.507 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Nov-2017 14:08:00.509 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
17-Nov-2017 14:08:00.510 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Nov-2017 14:08:00.592 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 28123 ms
17-Nov-2017 14:08:01.206 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
17-Nov-2017 14:08:01.207 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.23
17-Nov-2017 14:08:01.495 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/host-manager]
17-Nov-2017 14:08:11.450 WARNING [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [159] milliseconds.
17-Nov-2017 14:08:12.311 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/host-manager] has finished in [10,816] ms
17-Nov-2017 14:08:12.312 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/manager]
17-Nov-2017 14:08:12.924 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/manager] has finished in [612] ms
17-Nov-2017 14:08:12.924 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/docs]
17-Nov-2017 14:08:13.415 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/docs] has finished in [491] ms
17-Nov-2017 14:08:13.415 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/ROOT]
17-Nov-2017 14:08:13.825 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/ROOT] has finished in [409] ms
17-Nov-2017 14:08:13.825 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/examples]
17-Nov-2017 14:08:20.096 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/examples] has finished in [6,271] ms
17-Nov-2017 14:08:20.097 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/apache-tomcat-8.5.23/webapps/pooltooadmin]
17-Nov-2017 14:08:20.549 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/apache-tomcat-8.5.23/webapps/pooltooadmin] has finished in [451] ms
17-Nov-2017 14:08:20.836 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
17-Nov-2017 14:08:20.999 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["https-jsse-nio-9999"]
17-Nov-2017 14:08:21.163 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
17-Nov-2017 14:08:21.204 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 20612 ms

Body:
Maybe port 8080 is taken already. If you have apache2 on your server the default port for apache2 is 8080. Try another port or check:

sudo netstat -tulpn |grep apache


问:
How to solve Element compilerArgs is not allowed here Error in maven compiler plugin?
I am using the maven compiler plugin 3.0 and I get the error "Element compilerArgs is not allowed here". This seems to work for command line but I get this Error in the IDE,.I use IDEA 2017.2 community edition. There is likely some schema missing somewhere, but I am not sure. Does anyone have a good way to solve issues like this, that is not to send a bug report to JetBrains and wait for a fix?</p>

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
        <fork>true</fork>
        <compilerArgs>
            <arg>-DspecificArg</arg>
        </compilerArgs>
    </configuration>
</plugin>
</code>```

答:
I suggest you try maven-compiler-plugin version 3.7.0.

If you stay on version 3.0, update your setup so it looks like this example: http://maven.apache.org/plugins-archives/maven-compiler-plugin-3.0/examples/pass-compiler-arguments.html

If you can go up to 3.7.0, take a look at this example (which is very similar to your code):
https://maven.apache.org/plugins/maven-compiler-plugin/examples/pass-compiler-arguments.html#

Body:
I am using the maven compiler plugin 3.0 and I get the error "Element compilerArgs is not allowed here". This seems to work for command line but I get this Error in the IDE,.I use IDEA 2017.2 community edition. There is likely some schema missing somewhere, but I am not sure. Does anyone have a good way to solve issues like this, that is not to send a bug report to JetBrains and wait for a fix?

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
        <fork>true</fork>
        <compilerArgs>
            <arg>-DspecificArg</arg>
        </compilerArgs>
    </configuration>
</plugin>


问:
Jquery: call a function automatically
I need to call a jquery function in each 10 Minuit in my MVC project. </p>

```<code>setInterval(function () {

            $.ajax({
                type: "GET",
                cache: false,
                url: "/Home/dwnld_all",
                success: function (result) {
                    alert(result);
                }
            });
        }, 600000);
</code>```

<p>This is my code. But in this, it doesn't work when the control go to next page.  Is there any jquery code for this? </p>

答:
Your js is limited to the current page. It can't by default be accessed across reloaded pages. You will need to take the help of some server side code. Something like this:

```<code>// Your controller action that you will be redirecting to
public ActionResult MyAction(int pendingInterval){
    ViewBag.Pending = pendingInterval;
    return View();
}
</code>```

You can now modify your js to the following:

```<code>function keepRunning() {

        $.ajax({
            type: "GET",
            cache: false,
            url: "/Home/dwnld_all",
            success: function (result) {
                alert(result);
            }
        });
 }
</code>```

In your view page you can have the following code to initially run the keepRunning function

```<code>setTimeout(function(){
    keepRunning() // run initially for the ending time
    setInterval(keepRunning, 600000);
}, @ViewBag.Pending);
</code>```

Now when you redirect your page, you will have to pass your remaining time as well to the url.

Title: Jquery: call a function automatically

Body:
I need to call a jquery function in each 10 Minuit in my MVC project.

setInterval(function () {

            $.ajax({
                type: "GET",
                cache: false,
                url: "/Home/dwnld_all",
                success: function (result) {
                    alert(result);
                }
            });
        }, 600000);

This is my code. But in this, it doesn't work when the control go to next page.  Is there any jquery code for this?

Body:
Your js is limited to the current page. It can't by default be accessed across reloaded pages. You will need to take the help of some server side code. Something like this:

// Your controller action that you will be redirecting to
public ActionResult MyAction(int pendingInterval){
    ViewBag.Pending = pendingInterval;
    return View();
}

You can now modify your js to the following:

function keepRunning() {

        $.ajax({
            type: "GET",
            cache: false,
            url: "/Home/dwnld_all",
            success: function (result) {
                alert(result);
            }
        });
 }

In your view page you can have the following code to initially run the keepRunning function

setTimeout(function(){
    keepRunning() // run initially for the ending time
    setInterval(keepRunning, 600000);
}, @ViewBag.Pending);

Now when you redirect your page, you will have to pass your remaining time as well to the url.


问:
How to read folder file on shared drive?
I'm newbie C# developer.
I'm doing new project on windows application.
And i want to read folder on shared drive then add to combobox.
Could you help me or show your solution to do it.

Now, I'm just read folder from my drive only.

This is my code.

  System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("D:\\Data\\");
            System.IO.FileSystemInfo[] files = di.GetFileSystemInfos();
            ddlCompany.Items.AddRange(files);```

答:
Maybe something Like the below:

```<code>DirectoryInfo dir = new DirectoryInfo(@"D:\Data\");
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();

foreach (FileInfo file in files)
{
  ddlCompany.Items.Add(file);
}
</code>```

However with this in mind I believe you will need to read from this address as a UNC path - \\SERVER\Data\

So would be more like:

```<code>DirectoryInfo dir = new DirectoryInfo(@"\\SERVER\Data\");
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();

foreach (FileInfo file in files)
{
  ddlCompany.Items.Add(file);
}
</code>```

Please note that this will pick up all files and folders in the location.

Hope this helps.

Body:
Maybe something Like the below:

DirectoryInfo dir = new DirectoryInfo(@"D:\Data\");
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();

foreach (FileInfo file in files)
{
  ddlCompany.Items.Add(file);
}

However with this in mind I believe you will need to read from this address as a UNC path - \\SERVER\Data\

So would be more like:

DirectoryInfo dir = new DirectoryInfo(@"\\SERVER\Data\");
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();

foreach (FileInfo file in files)
{
  ddlCompany.Items.Add(file);
}

Please note that this will pick up all files and folders in the location.

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Android Facebook Integration Invalid Key hash error on Android device but working fine on Emulator
When I run my Android app in my android device it was working fine when I clicked first time on Continues with Facebook button.When i try to login again after logged out it is showing an error "Invalid Key has" The key has does not match any stored key hash. I have already  regenerated key hash and replaced new key on facebook. bUt still did not get result.

First time I had easily logged-in, But after logged out again I'm trying to Continues with Facebook but it is showing an error message "Invalid Key has":

But the same application is running perfectly fine on Emulator. why it is not working on my devices?

答:
Hi Put this code in any reachable activity's onCreate method to print the hash key in the console and update that hash key in your facebook linked account with the application.</p>

```<code>try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.facebook.samples.loginhowto",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
</code>```

Body:
Hi Put this code in any reachable activity's onCreate method to print the hash key in the console and update that hash key in your facebook linked account with the application.

try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.facebook.samples.loginhowto",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }


问:
UIActionSheet Customization

Can we change the order in which the destructive button and Other buttons appear in an UIActionSheet. By default the destructive button (red colored) appears above other buttons, in my app I would like the other buttons to appear above the destructive button.

答:
No Problem.

Just alloc and init a new UIActionSheet instance and add the buttons in your order (one after another) using –addButtonWithTitle:. This method returns you the index at which the button has been added to. You can then set the Index of the destructive button via -setDestructiveButtonIndex:.

ContentLicense: CC BY-SA 2.5

Title: UIActionSheet Customization


问:
Waiting for location change to ends
I have a service that sends data for server periodically, and the longitude and the latitude are from the data to be sent.
The problem is the async task always starts its execution before the registerLocationUpdates() ends, please help me in solving it, the only thing i want is ro guarantee that the PostQos task won't be executed until the register location updates ends.</p>

```<code>public class QosTestsService extends Service {

private Handler handler;
SharedPreferences mshared;
protected LocationManager locationManager;
protected LocationListener locationListener;
double longitude = 0.0, latitude = 0.0;
String provider;
boolean waitingForLocationUpdate = true;

private boolean firstTime = true, running = true;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();

    int delay = 5000; //milliseconds
    mshared = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            handler.postDelayed(this, MyApplication.routineSchedule.getFrequency() * 60 * 1000);
            if (MyApplication.routineSchedule.getEnabled().equals("true")){

                registerLocationUpdates();
                new PostQosTest(getApplicationContext(), true).execute();
            }
        }
    }, delay);
    return START_STICKY;
}

private void registerLocationUpdates() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);

    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);

    provider = locationManager.getBestProvider(criteria, true);

    // Cant get a hold of provider
    if (provider == null) {
        return;
    }

    locationListener = new MyLocationListener();

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, locationListener);
    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    // connect to the GPS location service
    Location oldLocation = locationManager.getLastKnownLocation(provider);

    if (oldLocation != null) {
        waitingForLocationUpdate = false;
    }
}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d("hello im here", "the value are " + latitude + " "
                + longitude);// , msg)
        // Log.v(TAG, "IN ON LOCATION CHANGE");

        if (waitingForLocationUpdate) {
            // getNearbyStores();
            waitingForLocationUpdate = false;
        }

        if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        locationManager.removeUpdates(this);
    }

    public void onStatusChanged(String s, int i, Bundle bundle) {
        // Log.v(TAG, "Status changed: " + s);
    }

    public void onProviderEnabled(String s) {
        // Log.e(TAG, "PROVIDER DISABLED: " + s);
    }

    public void onProviderDisabled(String s) {
        // Log.e(TAG, "PROVIDER DISABLED: " + s);
    }
}

private class PostQosTest extends AsyncTask<Void, Void, String> {

    String ipAddress, res;
    Profile profile;
    Context context;
    String carrierName;
    QosTest qosTest;
    boolean isSignalStrength;
    String testDate;

    public PostQosTest(Context context, boolean isSignalStrength){

        this.context = context;
        this.isSignalStrength = isSignalStrength;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        try {
            testDate = new SimpleDateFormat("HH:mm:ss dd-MMM-yyyy", Locale.ENGLISH).format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            InetAddress ip = Actions.GetIp();
            ipAddress = ip.toString();

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

        TCTDbAdapter sour = new TCTDbAdapter(context);
        sour.open();
        ArrayList<Profile> arr = sour.getAllProfiles();
        profile = arr.get(0);
        sour.close();

        TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        carrierName = manager.getSimOperatorName();

        qosTest = new QosTest();

        qosTest.setId(0);

        try {
            qosTest.setUserId(profile.getId());
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setUserId("");
        }

        try {
            qosTest.setDeviceId(String.valueOf(mshared.getInt(getString(R.string.device_id), 0)));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setDeviceId("");
        }

        try {
            qosTest.setDeviceModel(Actions.getDeviceName());
        } catch (Exception e) {

            qosTest.setDeviceModel("");
        }

        qosTest.setDeviceType("1");

        try {
            qosTest.setServiceProvider(carrierName);
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setServiceProvider("");
        }

        try {
            qosTest.setIp(ipAddress.substring(1));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setIp("");
        }

        try {
            qosTest.setLocationIPAddress(MyApplication.ip);
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setLocationIPAddress("");
        }

        try {
            qosTest.setLocationX(Double.toString(longitude));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setLocationX("");
        }

        try {
            qosTest.setLocationY(Double.toString(latitude));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setLocationY("");
        }

        try {
            qosTest.setTimeStamp("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTimeStamp("");
        }

        qosTest.setTestType(isSignalStrength ? MyApplication.SIGNAL_STRENGTH_TEST : MyApplication.CALL_DISCONNECTION_TEST);

        qosTest.setCallDisconnectionReason("");

        try {
            qosTest.setTestDateTime(testDate);
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTestDateTime(testDate);
        }

        try {
            qosTest.setIsIncident("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setIsIncident("");
        }

        try {
            qosTest.setSignalStrength("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setSignalStrength("");
        }

        try {
            qosTest.setConnectionType(NetworkUtil.getNetworkClass(context));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setConnectionType(NetworkUtil.getNetworkClass(context));
        }

        try {
            qosTest.setCallDuration("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setCallDuration("");
        }

        try {
            qosTest.setTestTriggerType("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTestTriggerType("");
        }

        try {
            qosTest.setTriggerStartDate("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTriggerStartDate("");
        }

        try {
            qosTest.setValidationEndDate("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setValidationEndDate("");
        }

        try {
            qosTest.setResultId("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setResultId("");
        }

        try {
            qosTest.setStatusId("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setStatusId("");
        }
    }

    @Override
    protected String doInBackground(Void... a) {
        // URLEncoder.encode(searchText, "utf-8");
        String url = ****;
        try {
            url = url
                    + "UserId="
                    + URLEncoder.encode(profile.getId(), "utf-8")
                    + "&"
                    + "mobileNumber="
                    + URLEncoder.encode(profile.getnum(), "utf-8")
                    + "&"
                    + "ServiceProvider="
                    + URLEncoder.encode(qosTest.getServiceProvider(), "utf-8")
                    + "&"
                    + "ipAddress="
                    + URLEncoder.encode(qosTest.getIp(), "utf-8")
                    + "&"
                    + "LocationIPAddress="
                    + URLEncoder.encode(qosTest.getLocationIPAddress(), "utf-8")
                    + "&"
                    + "DeviceId="
                    + URLEncoder.encode(String.valueOf(qosTest.getDeviceId()), "utf-8")
                    + "&"
                    + "DeviceModel="
                    + URLEncoder.encode(qosTest.getDeviceModel(), "utf-8")
                    + "&"
                    + "DeviceType="
                    + URLEncoder.encode(qosTest.getDeviceType(), "utf-8")
                    + "&"
                    + "LocationX="
                    + URLEncoder.encode(qosTest.getLocationX(), "utf-8")
                    + "&"
                    + "LocationY="
                    + URLEncoder.encode(qosTest.getLocationY(), "utf-8")
                    + "&"
                    + "TestTypeId="
                    + URLEncoder.encode(qosTest.getTestType(), "utf-8")
                    + "&"
                    + "CallDisconnectionReason="
                    + URLEncoder.encode(qosTest.getCallDisconnectionReason(), "utf-8")
                    + "&"
                    + "TestDate="
                    + URLEncoder.encode(qosTest.getTestDateTime(), "utf-8")
                    + "&"
                    + "IsIncident="
                    + URLEncoder.encode(qosTest.getIsIncident(), "utf-8")
                    + "&"
                    + "SignalStrength="
                    + URLEncoder.encode(qosTest.getSignalStrength(), "utf-8")
                    + "&"
                    + "ConnectionType="
                    + URLEncoder.encode(qosTest.getConnectionType(), "utf-8")
                    + "&"
                    + "CallDuration="
                    + URLEncoder.encode(qosTest.getCallDuration(), "utf-8")
                    + "&"
                    + "TestTriggerTypeId="
                    + URLEncoder.encode(qosTest.getTestTriggerType(), "utf-8")
                    + "&"
                    + "TriggerStartDate="
                    + URLEncoder.encode(qosTest.getTriggerStartDate(), "utf-8")
                    + "&"
                    + "ValidationEndDate="
                    + URLEncoder.encode(qosTest.getValidationEndDate(), "utf-8")
                    + "&"
                    + "ResultId="
                    + URLEncoder.encode(qosTest.getResultId(), "utf-8")
                    + "&"
                    + "StatusId="
                    + URLEncoder.encode(qosTest.getStatusId(), "utf-8");

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

...
        return "";

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}
}
</code>```

答: Solved, I just moved the execution code to the last line in the on location changed function.</p>

Title: Waiting for location change to ends

Body:
I have a service that sends data for server periodically, and the longitude and the latitude are from the data to be sent.
The problem is the async task always starts its execution before the registerLocationUpdates() ends, please help me in solving it, the only thing i want is ro guarantee that the PostQos task won't be executed until the register location updates ends.

public class QosTestsService extends Service {

private Handler handler;
SharedPreferences mshared;
protected LocationManager locationManager;
protected LocationListener locationListener;
double longitude = 0.0, latitude = 0.0;
String provider;
boolean waitingForLocationUpdate = true;

private boolean firstTime = true, running = true;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();

    int delay = 5000; //milliseconds
    mshared = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            handler.postDelayed(this, MyApplication.routineSchedule.getFrequency() * 60 * 1000);
            if (MyApplication.routineSchedule.getEnabled().equals("true")){

                registerLocationUpdates();
                new PostQosTest(getApplicationContext(), true).execute();
            }
        }
    }, delay);
    return START_STICKY;
}

private void registerLocationUpdates() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);

    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);

    provider = locationManager.getBestProvider(criteria, true);

    // Cant get a hold of provider
    if (provider == null) {
        return;
    }

    locationListener = new MyLocationListener();

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, locationListener);
    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    // connect to the GPS location service
    Location oldLocation = locationManager.getLastKnownLocation(provider);

    if (oldLocation != null) {
        waitingForLocationUpdate = false;
    }
}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d("hello im here", "the value are " + latitude + " "
                + longitude);// , msg)
        // Log.v(TAG, "IN ON LOCATION CHANGE");

        if (waitingForLocationUpdate) {
            // getNearbyStores();
            waitingForLocationUpdate = false;
        }

        if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        locationManager.removeUpdates(this);
    }

    public void onStatusChanged(String s, int i, Bundle bundle) {
        // Log.v(TAG, "Status changed: " + s);
    }

    public void onProviderEnabled(String s) {
        // Log.e(TAG, "PROVIDER DISABLED: " + s);
    }

    public void onProviderDisabled(String s) {
        // Log.e(TAG, "PROVIDER DISABLED: " + s);
    }
}

private class PostQosTest extends AsyncTask<Void, Void, String> {

    String ipAddress, res;
    Profile profile;
    Context context;
    String carrierName;
    QosTest qosTest;
    boolean isSignalStrength;
    String testDate;

    public PostQosTest(Context context, boolean isSignalStrength){

        this.context = context;
        this.isSignalStrength = isSignalStrength;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        try {
            testDate = new SimpleDateFormat("HH:mm:ss dd-MMM-yyyy", Locale.ENGLISH).format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            InetAddress ip = Actions.GetIp();
            ipAddress = ip.toString();

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

        TCTDbAdapter sour = new TCTDbAdapter(context);
        sour.open();
        ArrayList<Profile> arr = sour.getAllProfiles();
        profile = arr.get(0);
        sour.close();

        TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        carrierName = manager.getSimOperatorName();

        qosTest = new QosTest();

        qosTest.setId(0);

        try {
            qosTest.setUserId(profile.getId());
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setUserId("");
        }

        try {
            qosTest.setDeviceId(String.valueOf(mshared.getInt(getString(R.string.device_id), 0)));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setDeviceId("");
        }

        try {
            qosTest.setDeviceModel(Actions.getDeviceName());
        } catch (Exception e) {

            qosTest.setDeviceModel("");
        }

        qosTest.setDeviceType("1");

        try {
            qosTest.setServiceProvider(carrierName);
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setServiceProvider("");
        }

        try {
            qosTest.setIp(ipAddress.substring(1));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setIp("");
        }

        try {
            qosTest.setLocationIPAddress(MyApplication.ip);
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setLocationIPAddress("");
        }

        try {
            qosTest.setLocationX(Double.toString(longitude));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setLocationX("");
        }

        try {
            qosTest.setLocationY(Double.toString(latitude));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setLocationY("");
        }

        try {
            qosTest.setTimeStamp("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTimeStamp("");
        }

        qosTest.setTestType(isSignalStrength ? MyApplication.SIGNAL_STRENGTH_TEST : MyApplication.CALL_DISCONNECTION_TEST);

        qosTest.setCallDisconnectionReason("");

        try {
            qosTest.setTestDateTime(testDate);
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTestDateTime(testDate);
        }

        try {
            qosTest.setIsIncident("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setIsIncident("");
        }

        try {
            qosTest.setSignalStrength("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setSignalStrength("");
        }

        try {
            qosTest.setConnectionType(NetworkUtil.getNetworkClass(context));
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setConnectionType(NetworkUtil.getNetworkClass(context));
        }

        try {
            qosTest.setCallDuration("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setCallDuration("");
        }

        try {
            qosTest.setTestTriggerType("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTestTriggerType("");
        }

        try {
            qosTest.setTriggerStartDate("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setTriggerStartDate("");
        }

        try {
            qosTest.setValidationEndDate("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setValidationEndDate("");
        }

        try {
            qosTest.setResultId("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setResultId("");
        }

        try {
            qosTest.setStatusId("");
        } catch (Exception e) {
            e.printStackTrace();
            qosTest.setStatusId("");
        }
    }

    @Override
    protected String doInBackground(Void... a) {
        // URLEncoder.encode(searchText, "utf-8");
        String url = ****;
        try {
            url = url
                    + "UserId="
                    + URLEncoder.encode(profile.getId(), "utf-8")
                    + "&"
                    + "mobileNumber="
                    + URLEncoder.encode(profile.getnum(), "utf-8")
                    + "&"
                    + "ServiceProvider="
                    + URLEncoder.encode(qosTest.getServiceProvider(), "utf-8")
                    + "&"
                    + "ipAddress="
                    + URLEncoder.encode(qosTest.getIp(), "utf-8")
                    + "&"
                    + "LocationIPAddress="
                    + URLEncoder.encode(qosTest.getLocationIPAddress(), "utf-8")
                    + "&"
                    + "DeviceId="
                    + URLEncoder.encode(String.valueOf(qosTest.getDeviceId()), "utf-8")
                    + "&"
                    + "DeviceModel="
                    + URLEncoder.encode(qosTest.getDeviceModel(), "utf-8")
                    + "&"
                    + "DeviceType="
                    + URLEncoder.encode(qosTest.getDeviceType(), "utf-8")
                    + "&"
                    + "LocationX="
                    + URLEncoder.encode(qosTest.getLocationX(), "utf-8")
                    + "&"
                    + "LocationY="
                    + URLEncoder.encode(qosTest.getLocationY(), "utf-8")
                    + "&"
                    + "TestTypeId="
                    + URLEncoder.encode(qosTest.getTestType(), "utf-8")
                    + "&"
                    + "CallDisconnectionReason="
                    + URLEncoder.encode(qosTest.getCallDisconnectionReason(), "utf-8")
                    + "&"
                    + "TestDate="
                    + URLEncoder.encode(qosTest.getTestDateTime(), "utf-8")
                    + "&"
                    + "IsIncident="
                    + URLEncoder.encode(qosTest.getIsIncident(), "utf-8")
                    + "&"
                    + "SignalStrength="
                    + URLEncoder.encode(qosTest.getSignalStrength(), "utf-8")
                    + "&"
                    + "ConnectionType="
                    + URLEncoder.encode(qosTest.getConnectionType(), "utf-8")
                    + "&"
                    + "CallDuration="
                    + URLEncoder.encode(qosTest.getCallDuration(), "utf-8")
                    + "&"
                    + "TestTriggerTypeId="
                    + URLEncoder.encode(qosTest.getTestTriggerType(), "utf-8")
                    + "&"
                    + "TriggerStartDate="
                    + URLEncoder.encode(qosTest.getTriggerStartDate(), "utf-8")
                    + "&"
                    + "ValidationEndDate="
                    + URLEncoder.encode(qosTest.getValidationEndDate(), "utf-8")
                    + "&"
                    + "ResultId="
                    + URLEncoder.encode(qosTest.getResultId(), "utf-8")
                    + "&"
                    + "StatusId="
                    + URLEncoder.encode(qosTest.getStatusId(), "utf-8");

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

...
        return "";

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}
}


问:
How to auto format JSON on save in Vim
To be honest go has spoiled me. With go I got used to having a strict formatting standard that is being enforced by my editor (vim) and is almost accepted and followed by everybody else on the team and around the world.

I wanted to format JSON files on save the same way.

Question: How to auto format/indent/lint json files on save in vim.

答:
%!python -m json.tool

or

%!python -c "import json, sys, collections; print json.dumps(json.load(sys.stdin, object_pairs_hook=collections.OrderedDict), ensure_ascii=False, indent=4)"

you can add this to your vimrc:

com! FormatJSON %!python -m json.tool

than you can use :FormatJson format json files

Title: How to auto format JSON on save in Vim


问:
how to include google analytics in php web service
I have a webservice writen in php and it is called from an desktop application installed on PC's.
I want to have a register of the users who calls the functions on the web service and for this I only want to send hits to Google Analytics.

webservice in php:

```<code><?php
   require_once('lib/nusoap.php'); // basic include.. must go at the top

   $SERVICE_NAMESPACE = "urn:Service"; // create a namespace to run under.

   $server = new soap_server(); // the soap object from the include above.

   // this has many input parameters but we only need two: the service name and the namespace
   $server->configureWSDL('Service', $SERVICE_NAMESPACE);

    $server->register('test',// method name
        array('name' => 'xsd:string', 'name99' => 'xsd:string'),// input parameter called name.. and it's a string.
        array('return' => 'xsd:string'),// output - one string is returned called "return"
        $SERVICE_NAMESPACE,// namespace
        $SERVICE_NAMESPACE . '#hello1',// soapaction
        'rpc',// style.. remote procedure call
        'encoded',// use of the call
        'Nada interesante'// documentation for people who hook into your service.
    );

    function test($sName,$sName99)
    {
        return 'TEST ';
    }

    //This processes the request and returns a result.
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
    $server->service($HTTP_RAW_POST_DATA);
?>
</code>```

I want to have google analytics info and for that i want to integrate the following script:

```<code><script async src="https://www.googletagmanager.com/gtag/js?id=UA-89356985-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());

  gtag('config', 'UA-89356985-1');
</script>
</code>```

I don't know how to integrate in the test function. I want to know when the users calls the test function.

Thanks in advance very much.

答:
This can be used as en example of what you need. use http_build_queryto build you hit as you want to Google Analytics. Change Google_Analytics_UA_Stringto match your Google Analytics ID

```<code><?php
    //some of the functions we need to make it work
    function generate_serial($n) {
        $c = "abcdefghijklmnopqrstuvwyxz0123456789";
        $s = '';
        for($i=0;$i<$n;$i++) {
            $s .= substr($c,rand(0,37),1);
        }
        return $s;
    }
    function generate_uuid() {
        return generate_serial(8).'-'.generate_serial(4).'-4'.generate_serial(3).'-a'.generate_serial(3).'-'.generate_serial(12);
    }
    function ip() {
        $ip = false;
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim(array_shift($ip));
        }
        elseif(isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    //define necessary variables
    define('Google_Analytics_UA_String','UA-XXXXXXXX-X');

    //create a UUID string for the user sending the request and store in the the session
    if(isset($_COOKIE['Google_Analytics_UUID']) and !empty($_COOKIE['Google_Analytics_UUID'])) {
        define('Google_Analytics_UUID',$_COOKIE['Google_Analytics_UUID']);
    }
    else {
        define('Google_Analytics_UUID',generate_uuid());
        setcookie('Google_Analytics_UUID',Google_Analytics_UUID,time()+63072000);
    }
    //compile the data we want to send to the API
    $data = http_build_query(array(
        'v'         =>  1,  // version
        'ds'            =>  'app',  // data source
        'tid'       =>  Google_Analytics_UA_String, // Tracking ID / Web Property ID
        'cid'       =>  Google_Analytics_UUID,  // Client ID
        'uip'       =>  ip(),   // IP Override
        't'         =>  'event',        // Hit type
        'ec'            =>  'site clicks',  // event category
        'ea'            =>  'click',        // event action
        'el'            =>  'button',   // event label
        'ev'            =>  'Click here!'   // event value
    ));

    //send using PHP's cURL extension
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,'https://www.google-analytics.com/collect');
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    $response = curl_exec($ch);

    //parse the response and send back to the browser
    header('Content-Type: application/json');
    $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    if($status == 200) {
        echo json_encode([
            'success'   =>  true
        ]);
    }
    else {
        echo json_encode([
            'error' =>  true
        ]);
    }
        ?>
</code>```

Body:
I have a webservice writen in php and it is called from an desktop application installed on PC's.
I want to have a register of the users who calls the functions on the web service and for this I only want to send hits to Google Analytics.

webservice in php:

<?php
   require_once('lib/nusoap.php'); // basic include.. must go at the top

   $SERVICE_NAMESPACE = "urn:Service"; // create a namespace to run under.

   $server = new soap_server(); // the soap object from the include above.

   // this has many input parameters but we only need two: the service name and the namespace
   $server->configureWSDL('Service', $SERVICE_NAMESPACE);

    $server->register('test',// method name
        array('name' => 'xsd:string', 'name99' => 'xsd:string'),// input parameter called name.. and it's a string.
        array('return' => 'xsd:string'),// output - one string is returned called "return"
        $SERVICE_NAMESPACE,// namespace
        $SERVICE_NAMESPACE . '#hello1',// soapaction
        'rpc',// style.. remote procedure call
        'encoded',// use of the call
        'Nada interesante'// documentation for people who hook into your service.
    );

    function test($sName,$sName99)
    {
        return 'TEST ';
    }

    //This processes the request and returns a result.
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
    $server->service($HTTP_RAW_POST_DATA);
?>

I want to have google analytics info and for that i want to integrate the following script:

I don't know how to integrate in the test function. I want to know when the users calls the test function.

Thanks in advance very much.

Body:
This can be used as en example of what you need. use http_build_queryto build you hit as you want to Google Analytics. Change Google_Analytics_UA_Stringto match your Google Analytics ID

<?php
    //some of the functions we need to make it work
    function generate_serial($n) {
        $c = "abcdefghijklmnopqrstuvwyxz0123456789";
        $s = '';
        for($i=0;$i<$n;$i++) {
            $s .= substr($c,rand(0,37),1);
        }
        return $s;
    }
    function generate_uuid() {
        return generate_serial(8).'-'.generate_serial(4).'-4'.generate_serial(3).'-a'.generate_serial(3).'-'.generate_serial(12);
    }
    function ip() {
        $ip = false;
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim(array_shift($ip));
        }
        elseif(isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    //define necessary variables
    define('Google_Analytics_UA_String','UA-XXXXXXXX-X');

    //create a UUID string for the user sending the request and store in the the session
    if(isset($_COOKIE['Google_Analytics_UUID']) and !empty($_COOKIE['Google_Analytics_UUID'])) {
        define('Google_Analytics_UUID',$_COOKIE['Google_Analytics_UUID']);
    }
    else {
        define('Google_Analytics_UUID',generate_uuid());
        setcookie('Google_Analytics_UUID',Google_Analytics_UUID,time()+63072000);
    }
    //compile the data we want to send to the API
    $data = http_build_query(array(
        'v'         =>  1,  // version
        'ds'            =>  'app',  // data source
        'tid'       =>  Google_Analytics_UA_String, // Tracking ID / Web Property ID
        'cid'       =>  Google_Analytics_UUID,  // Client ID
        'uip'       =>  ip(),   // IP Override
        't'         =>  'event',        // Hit type
        'ec'            =>  'site clicks',  // event category
        'ea'            =>  'click',        // event action
        'el'            =>  'button',   // event label
        'ev'            =>  'Click here!'   // event value
    ));

    //send using PHP's cURL extension
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,'https://www.google-analytics.com/collect');
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    $response = curl_exec($ch);

    //parse the response and send back to the browser
    header('Content-Type: application/json');
    $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    if($status == 200) {
        echo json_encode([
            'success'   =>  true
        ]);
    }
    else {
        echo json_encode([
            'error' =>  true
        ]);
    }
        ?>


问:
VBA/Excel: "Subscript out of range" error
I am trying to populate the Hrs array with values conditioned on whether specific cells are empty or not:

```<code>Sub Add_training_hrs()
    Dim Rng1, Rng2 As Range
    Dim m, n As Integer
    Dim Hrs() As Double

    Set Rng11 = Application.InputBox("Upper-left cell (e.g., C4): ", "Box #1", Type:=8)
    Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8)

    Col11 = Rng11.Column
    Row11 = Rng11.Row
    Col22 = Rng22.Column
    Row22 = Rng22.Row

    nRows = Row22 - Row11
    nCols = Col22 - Col11

    ReDim Hrs(1 To nCols)

    Debug.Print "Hrs(1) = "; Hrs(1)

    For n = 1 To nRows
        For m = 1 To nCols
            If IsEmpty(Cells(n, m).Value) Then
                Hrs(m) = 0
                Debug.Print "Hrs(m) = "; Hrs(m)
            Else
                Hrs(m) = Cells(Row11 - 1, m).Value
            End If
        Cells(n, Col22 + 1).Value = Application.Sum(Hrs)
        Erase Hrs
        Next m
    Next n
End Sub
</code>```

For some reason, I keep getting the "Subscription out..." error right after my If... Then statement at Hrs(m) = 0, but I can't figure out why.  Any advice is appreciated, and if there is a duplicate question out there that can help, don't hesitate in letting me know (I've looked...).

Updated (and working) code

There were various problems with my original script, but I got it to work.  I'm posting it here in case it helps others:

```<code>Sub Add_training_hrs()
    Dim Rng11 As Range
    Dim Rng22 As Range
    Dim m As Integer
    Dim n As Integer
    Dim Hrs() As Double

    Set Rng11 = Application.InputBox("Upper-left cell (e.g., C4): ", "Box #1", Type:=8)
    Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8)

    Col11 = Rng11.Column
    Row11 = Rng11.Row
    Col22 = Rng22.Column
    Row22 = Rng22.Row

    nRows = (Row22 - Row11) + 1
    nCols = (Col22 - Col11) + 1

    ReDim Hrs(1 To nCols)

    For n = 0 To nRows - 1
        For m = 0 To nCols - 1
            If IsEmpty(Cells(Row11 + n, Col11 + m).Value) Then
                Hrs(m + 1) = 0
            Else
                Hrs(m + 1) = Cells(Row11 - 1, Col11 + m).Value
            End If
        Next m
        Cells(Row11 + n, Col22 + 1).Value = Application.Sum(Hrs)
        Erase Hrs
        ReDim Hrs(1 To nCols)
    Next n
End Sub
</code>```

答:
I suppose you get the error only starting on the second row.

When you Erase a dynamic array, you are releasing the memory (see Erase )

You will need to reallocate it after.

Body:
I am trying to populate the Hrs array with values conditioned on whether specific cells are empty or not:

Sub Add_training_hrs()
    Dim Rng1, Rng2 As Range
    Dim m, n As Integer
    Dim Hrs() As Double

    Set Rng11 = Application.InputBox("Upper-left cell (e.g., C4): ", "Box #1", Type:=8)
    Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8)

    Col11 = Rng11.Column
    Row11 = Rng11.Row
    Col22 = Rng22.Column
    Row22 = Rng22.Row

    nRows = Row22 - Row11
    nCols = Col22 - Col11

    ReDim Hrs(1 To nCols)

    Debug.Print "Hrs(1) = "; Hrs(1)

    For n = 1 To nRows
        For m = 1 To nCols
            If IsEmpty(Cells(n, m).Value) Then
                Hrs(m) = 0
                Debug.Print "Hrs(m) = "; Hrs(m)
            Else
                Hrs(m) = Cells(Row11 - 1, m).Value
            End If
        Cells(n, Col22 + 1).Value = Application.Sum(Hrs)
        Erase Hrs
        Next m
    Next n
End Sub

For some reason, I keep getting the "Subscription out..." error right after my If... Then statement at Hrs(m) = 0, but I can't figure out why.  Any advice is appreciated, and if there is a duplicate question out there that can help, don't hesitate in letting me know (I've looked...).

Updated (and working) code

There were various problems with my original script, but I got it to work.  I'm posting it here in case it helps others:

Sub Add_training_hrs()
    Dim Rng11 As Range
    Dim Rng22 As Range
    Dim m As Integer
    Dim n As Integer
    Dim Hrs() As Double

    Set Rng11 = Application.InputBox("Upper-left cell (e.g., C4): ", "Box #1", Type:=8)
    Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8)

    Col11 = Rng11.Column
    Row11 = Rng11.Row
    Col22 = Rng22.Column
    Row22 = Rng22.Row

    nRows = (Row22 - Row11) + 1
    nCols = (Col22 - Col11) + 1

    ReDim Hrs(1 To nCols)

    For n = 0 To nRows - 1
        For m = 0 To nCols - 1
            If IsEmpty(Cells(Row11 + n, Col11 + m).Value) Then
                Hrs(m + 1) = 0
            Else
                Hrs(m + 1) = Cells(Row11 - 1, Col11 + m).Value
            End If
        Next m
        Cells(Row11 + n, Col22 + 1).Value = Application.Sum(Hrs)
        Erase Hrs
        ReDim Hrs(1 To nCols)
    Next n
End Sub


问:
Changing '?' to '&' in address bar
For example, in my web-app I have a link with url www.example.com/profile?name=name. When I click to that link, I'm getting a page, where I can change profile's information, BUT after clicking to that link, url in adress bar turns into www.example.com/profile&name=name.

More interesting: when I make some changes and click SAVE - url reverts to www.example.com/profile?name=name.

If I don't click SAVE, just refresh page, i'm getting error 404.

How can it be possible?

P.S My view function

```<code>@check_document_access_permission()
def notebook(request, is_embeddable=False):
  if not SHOW_NOTEBOOKS.get():
    return serve_403_error(request)

  notebook_id = request.GET.get('notebook', request.GET.get('editor'))

  is_yarn_mode = False
  try:
    from spark.conf import LIVY_SERVER_SESSION_KIND
    is_yarn_mode = LIVY_SERVER_SESSION_KIND.get()
  except:
    LOG.exception('Spark is not enabled')

  return render('notebook.mako', request, {
      'editor_id': notebook_id or None,
      'notebooks_json': '{}',
      'is_embeddable': request.GET.get('is_embeddable', False),
      'options_json': json.dumps({
          'languages': get_ordered_interpreters(request.user),
          'session_properties': SparkApi.get_properties(),
          'is_optimizer_enabled': has_optimizer(),
          'is_navigator_enabled': has_navigator(request.user),
          'editor_type': 'notebook'
      }),
      'is_yarn_mode': is_yarn_mode,
  })
</code>```

答:
I found error.

In frontend was JS function, which incorrectly changed url.

Title: Changing '?' to '&' in address bar

Body:
For example, in my web-app I have a link with url www.example.com/profile?name=name. When I click to that link, I'm getting a page, where I can change profile's information, BUT after clicking to that link, url in adress bar turns into www.example.com/profile&name=name.

More interesting: when I make some changes and click SAVE - url reverts to www.example.com/profile?name=name.

If I don't click SAVE, just refresh page, i'm getting error 404.

How can it be possible?

P.S My view function

@check_document_access_permission()
def notebook(request, is_embeddable=False):
  if not SHOW_NOTEBOOKS.get():
    return serve_403_error(request)

  notebook_id = request.GET.get('notebook', request.GET.get('editor'))

  is_yarn_mode = False
  try:
    from spark.conf import LIVY_SERVER_SESSION_KIND
    is_yarn_mode = LIVY_SERVER_SESSION_KIND.get()
  except:
    LOG.exception('Spark is not enabled')

  return render('notebook.mako', request, {
      'editor_id': notebook_id or None,
      'notebooks_json': '{}',
      'is_embeddable': request.GET.get('is_embeddable', False),
      'options_json': json.dumps({
          'languages': get_ordered_interpreters(request.user),
          'session_properties': SparkApi.get_properties(),
          'is_optimizer_enabled': has_optimizer(),
          'is_navigator_enabled': has_navigator(request.user),
          'editor_type': 'notebook'
      }),
      'is_yarn_mode': is_yarn_mode,
  })


问:
How to get the values from inputs of dynamically opening modals in jQuery?
I have a foreach loop in blade which generates dynamic modal for each row where I want to fetch the values of inputs from the open modal and edit the record through AJAX but cannot get the values. Please see the below code I am working on:

```<code>@foreach($doctors as $doctor)
    <tr class="tr">
        <td>{{ $doctor->id }}</td>
        <td>{{$doctor->name}}</td>
        <td>{{ $doctor->percentage }}</td>
        <td><button class="btn btn-primary" data-toggle="modal" data-
        target="#editModal-{{ $doctor->id }}" id="btnEdit" value="{{$doctor->id }}">
           Edit   </button>

       <button type="button" class="btn btn-danger btn-sm" data-toggle="modal"
        data-target="#modal_theme_primary">Delete</button>
        </td>
        <td><!-- Horizontal form modal -->
        <div id="editModal-{{ $doctor->id }}" class="modal fade">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">
             <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">×</button>
                <h5 class="modal-title">Edit Record</h5>
             </div>

              <form action="#" class="form-horizontal">
                <div class="modal-body">
                  <div class="form-group">
                   <label class="control-label col-sm-3"><b>Name:</b></label>
                   <div class="col-sm-9">
                    <input type="text" class="form-control" id="txtName"
                    value="{{ $doctor->name }}">
                   </div>
                </div>

                <div class="form-group">
                 <label class="control-label col-sm-3"><b>Percentage:</b></label>
                   <div class="col-sm-9">
                    <input type="text" class="form-control" id="txtPercentage"
                    value="{{ $doctor->percentage }}">
                   </div>
                </div>

                <div class="modal-footer">
                  <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
                  <button id="btnSaveChanges" type="button" class="btn btn-primary">Save Changes</button>
                 </div>
            </form>
        </div>
    </div>
</div>
<!-- /horizontal form modal -->
</td>
</tr>
@endforeach
</code>```

Now when I click the Edit button the modal for the clicked row opens up from where I want to get the values from the inputs of the open modal.

when I use the following code it alerts the first record's values.

```<code><script type="text/javascript">
    jQuery(document).ready(function($) {
        $(document).on('click', '#btnSaveChanges' function(){
            var id = $('#btnEdit').val();
            var name = $('#txtName').val();
            var percentage = ('#txtPercentage').val();
            alert(id + " " + name + " " + percentage);
        });
    });
</script>
</code>```

答:
You can not use an id several times. Right now every time you make a new modal you add in the same id's (btnEdit, txtName, txtPercentage). You can not make the right selection when using duplicate id's with jQuery by selecting id.

In the example below I have used classes instead of id's to select the modal inputs.

jQuery(document).ready(function($) {

  $('.btnSaveChanges').click(function() {
   var parent = $(this).parent().parent();

    var name = parent.find('.txtName').val();
    var percentage = parent.find('.txtPercentage').val();

    alert(name + " " + percentage);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="editModal-1" class="modal fade">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h5 class="modal-title">Edit Record</h5>
      </div>

      <form action="#" class="form-horizontal">
        <div class="modal-body">
          <div class="form-group">
            <label class="control-label col-sm-3"><b>Name:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtName"value="name1">
            </div>
          </div>

          <div class="form-group">
            <label class="control-label col-sm-3"><b>Percentage:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtPercentage" value="10%">
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary btnSaveChanges">Save Changes</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<div id="editModal-2" class="modal fade">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h5 class="modal-title">Edit Record</h5>
      </div>

      <form action="#" class="form-horizontal">
        <div class="modal-body">
          <div class="form-group">
            <label class="control-label col-sm-3"><b>Name:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtName"value="name2">
            </div>
          </div>

          <div class="form-group">
            <label class="control-label col-sm-3"><b>Percentage:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtPercentage" value="20%">
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary btnSaveChanges">Save Changes</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></code>```

Body:
I have a foreach loop in blade which generates dynamic modal for each row where I want to fetch the values of inputs from the open modal and edit the record through AJAX but cannot get the values. Please see the below code I am working on:

@foreach($doctors as $doctor)

        {{ $doctor->id }}
        {{$doctor->name}}
        {{ $doctor->percentage }}
        <button class="btn btn-primary" data-toggle="modal" data-
        target="#editModal-{{ $doctor->id }}" id="btnEdit" value="{{$doctor->id }}">
           Edit   </button>

       <button type="button" class="btn btn-danger btn-sm" data-toggle="modal"
        data-target="#modal_theme_primary">Delete</button>

id }}" class="modal fade">

              <button type="button" class="close" data-dismiss="modal">×</button>

Edit Record

              <form action="#" class="form-horizontal">

                   Name:

                    <input type="text" class="form-control" id="txtName"
                    value="{{ $doctor->name }}">

                 Percentage:

                    <input type="text" class="form-control" id="txtPercentage"
                    value="{{ $doctor->percentage }}">

                  <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
                  <button id="btnSaveChanges" type="button" class="btn btn-primary">Save Changes</button>

            </form>

@endforeach

Now when I click the Edit button the modal for the clicked row opens up from where I want to get the values from the inputs of the open modal.

when I use the following code it alerts the first record's values.

Body:
You can not use an id several times. Right now every time you make a new modal you add in the same id's (btnEdit, txtName, txtPercentage). You can not make the right selection when using duplicate id's with jQuery by selecting id.

In the example below I have used classes instead of id's to select the modal inputs.

jQuery(document).ready(function($) {

  $('.btnSaveChanges').click(function() {
   var parent = $(this).parent().parent();

    var name = parent.find('.txtName').val();
    var percentage = parent.find('.txtPercentage').val();

    alert(name + " " + percentage);
  });
});

<div id="editModal-1" class="modal fade">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h5 class="modal-title">Edit Record</h5>
      </div>

      <form action="#" class="form-horizontal">
        <div class="modal-body">
          <div class="form-group">
            <label class="control-label col-sm-3"><b>Name:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtName"value="name1">
            </div>
          </div>

          <div class="form-group">
            <label class="control-label col-sm-3"><b>Percentage:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtPercentage" value="10%">
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary btnSaveChanges">Save Changes</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<div id="editModal-2" class="modal fade">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h5 class="modal-title">Edit Record</h5>
      </div>

      <form action="#" class="form-horizontal">
        <div class="modal-body">
          <div class="form-group">
            <label class="control-label col-sm-3"><b>Name:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtName"value="name2">
            </div>
          </div>

          <div class="form-group">
            <label class="control-label col-sm-3"><b>Percentage:</b></label>
            <div class="col-sm-9">
              <input type="text" class="form-control txtPercentage" value="20%">
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary btnSaveChanges">Save Changes</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


答:
try this also</p>

```<code>DECLARE @StartDate  DATE='15 JAN 2011',
        @EndDate    DATE='31 DEC 2018'

;WITH CTE_DATE AS
(
    SELECT  DATEADD(DD,1,DATEADD(DD,-DATEPART(DD,@StartDate),@StartDate)) [START_DATE],
            DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,@StartDate)),DATEADD(MM,1,@StartDate)) END_DATE
    UNION ALL
    SELECT  DATEADD(DD,1,DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,[START_DATE])),DATEADD(MM,1,[START_DATE]))) [START_DATE],
            DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,DATEADD(MM,1,[START_DATE]))),DATEADD(MM,1,DATEADD(MM,1,[START_DATE]))) END_DATE
    FROM CTE_DATE
    WHERE END_DATE<@EndDate
)

SELECT * FROM CTE_DATE
</code>```

Title: list date period between two date

Body:
I was wondering if there is way to use sql output list the date start date end by year + 1 interval(have leap year) like following:

Date_start      2014-06-01 00:00:00                   Date_End 2017-05-31 00:00:00

select '2014-06-01 00:00:00',dateadd(DAY, 365, '2014-06-01 00:00:00')

2014-06-01 00:00:00   2015-06-01 00:00:00

2015-06-01 00:00:00     2016-05-31 00:00:00

2016-05-31 00:00:00     2017-05-31 00:00:00

Body:
try this also

DECLARE @StartDate  DATE='15 JAN 2011',
        @EndDate    DATE='31 DEC 2018'

;WITH CTE_DATE AS
(
    SELECT  DATEADD(DD,1,DATEADD(DD,-DATEPART(DD,@StartDate),@StartDate)) [START_DATE],
            DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,@StartDate)),DATEADD(MM,1,@StartDate)) END_DATE
    UNION ALL
    SELECT  DATEADD(DD,1,DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,[START_DATE])),DATEADD(MM,1,[START_DATE]))) [START_DATE],
            DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,DATEADD(MM,1,[START_DATE]))),DATEADD(MM,1,DATEADD(MM,1,[START_DATE]))) END_DATE
    FROM CTE_DATE
    WHERE END_DATE<@EndDate
)

SELECT * FROM CTE_DATE