IIS 7.5 , Tomcat 7 - Isapi redirector - Fail Over - sticky sessions

Question: I have two instances of Tomcat 7.0.8 running in the same machine (Tomcat7A and Tomcat7B) and IIS 7.5 acting as front-end load-balancer with isapi-redirector 1.2.31, running on Windows 2008 R2.
When i disconnect the instance wich is handling a request i can see a new instance being assigned with the same sessionid but then the user is redirected to the login page.
server.xml configuration file

<Engine name="Catalina" defaultHost="localhost" jvmRoute="Tomcat7A">

  <Realm className="org.apache.catalina.realm.LockOutRealm">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="UserDatabase"/>
  </Realm>

  <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">

  <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
             channelSendOptions="8">

      <Manager className="org.apache.catalina.ha.session.DeltaManager"
               expireSessionsOnShutdown="false"
               notifyListenersOnReplication="true"/>

      <Channel className="org.apache.catalina.tribes.group.GroupChannel">
        <Membership className="org.apache.catalina.tribes.membership.McastService"
                    address="220.127.116.11"
        bind="18.104.22.168"
                    port="45564"
                    frequency="500"
                    dropTime="3000"/>
        <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                  address="auto"
                  port="4200"
                  autoBind="100"
                  selectorTimeout="5000"
                  maxThreads="6"/>

        <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
          <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
        </Sender>
        <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
        <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
      </Channel>

      <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
             filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt"/>
      <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

      <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
      <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
    </Cluster>

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>

  </Host>
</Engine>

worker_mount_file=C:\tomcat\iis\conf\uriworkermap_prod.properties
worker.list = balancer,status

worker.Tomcat7B.host = 188.8.131.52
worker.Tomcat7B.type = ajp13
worker.Tomcat7B.port = 8010
worker.Tomcat7B.lbfactor = 10

worker.Tomcat7A.host = 220.127.116.11
worker.Tomcat7A.type = ajp13
worker.Tomcat7A.port = 8009
worker.Tomcat7A.lbfactor = 10

worker.balancer.type = lb
worker.balancer.sticky_session = 1
worker.balancer.balance_workers = Tomcat7B, Tomcat7A

worker.status.type = status

isapi_redirect log
[debug] wc_get_worker_for_name::jk_worker.c (116): found a worker balancer
[debug] HttpExtensionProc::jk_isapi_plugin.c (2188): got a worker for name balancer
[debug] service::jk_lb_worker.c (1118): service sticky_session=1    id='89569C584CC4F58740D649C4BE655D36.Tomcat7B'
[debug] get_most_suitable_worker::jk_lb_worker.c (946): searching worker for partial sessionid   89569C584CC4F58740D649C4BE655D36.Tomcat7B
[debug] get_most_suitable_worker::jk_lb_worker.c (954): searching worker for session route Tomcat7B
[debug] get_most_suitable_worker::jk_lb_worker.c (968): found worker Tomcat7B (Tomcat7B) for route  Tomcat7B and partial sessionid 89569C584CC4F58740D649C4BE655D36.Tomcat7B
[debug] service::jk_lb_worker.c (1161): service worker=Tomcat7B route=Tomcat7B
[debug] ajp_get_endpoint::jk_ajp_common.c (3096): acquired connection pool slot=0 after 0 retries
[debug] ajp_marshal_into_msgb::jk_ajp_common.c (605): ajp marshaling done
[debug] ajp_service::jk_ajp_common.c (2379): processing Tomcat7B with 2 retries
[debug] jk_shutdown_socket::jk_connect.c (726): About to shutdown socket 820 [18.104.22.168:24482 -> 18.104.22.168:8010]
[debug] jk_shutdown_socket::jk_connect.c (797): shutting down the read side of socket 820 [22.214.171.124:24482 -> 220.127.116.11:8010]
[debug] jk_shutdown_socket::jk_connect.c (808): Shutdown socket 820 [184.108.40.206:24482 -> 184.108.40.206:8010] and read 0 lingering bytes in 0 sec.
[debug] ajp_send_request::jk_ajp_common.c (1496): (Tomcat7B) failed sending request, socket 820 is not connected any more (errno=-10000)
[debug] ajp_next_connection::jk_ajp_common.c (823): (Tomcat7B) Will try pooled connection socket 896 from slot 1
[debug] jk_shutdown_socket::jk_connect.c (726): About to shutdown socket 896 [18.104.22.168:24488 -> 184.108.40.206:8010]
[debug] jk_shutdown_socket::jk_connect.c (797): shutting down the read side of socket 896 [220.127.116.11:24488 -> 184.108.40.206:8010]
[debug] jk_shutdown_socket::jk_connect.c (808): Shutdown socket 896 [126.96.36.199:24488 -> 18.104.22.168:8010] and read 0 lingering bytes in 0 sec.
[debug] ajp_send_request::jk_ajp_common.c (1496): (Tomcat7B) failed sending request, socket 896 is not connected any more (errno=-10000)
[info] ajp_send_request::jk_ajp_common.c (1567): (Tomcat7B) all endpoints are disconnected, detected by connect check (2), cping (0), send (0)
[debug] jk_open_socket::jk_connect.c (484): socket TCP_NODELAY set to On
[debug] jk_open_socket::jk_connect.c (608): trying to connect socket 896 to 184.108.40.206:8010
[info] jk_open_socket::jk_connect.c (626): connect to 220.127.116.11:8010 failed (errno=61)
[info] ajp_connect_to_endpoint::jk_ajp_common.c (959): Failed opening socket to (184.108.40.206:8010) (errno=61)
[error] ajp_send_request::jk_ajp_common.c (1578): (Tomcat7B) connecting to backend failed. Tomcat is probably not started or is listening on the wrong port (errno=61)
[info] ajp_service::jk_ajp_common.c (2543): (Tomcat7B) sending request to tomcat failed (recoverable), because of error during request sending (attempt=1)
[debug] ajp_service::jk_ajp_common.c (2400): retry 1, sleeping for 100 ms before retrying
[debug] ajp_send_request::jk_ajp_common.c (1572): (Tomcat7B) all endpoints are disconnected.
[debug] jk_open_socket::jk_connect.c (484): socket TCP_NODELAY set to On
[debug] jk_open_socket::jk_connect.c (608): trying to connect socket 896 to 18.104.22.168:8010
[info] jk_open_socket::jk_connect.c (626): connect to 184.108.40.206:8010 failed (errno=61)
[info] ajp_connect_to_endpoint::jk_ajp_common.c (959): Failed opening socket to (220.127.116.11:8010) (errno=61)
[error] ajp_send_request::jk_ajp_common.c (1578): (Tomcat7B) connecting to backend failed. Tomcat is probably not started or is listening on the wrong port (errno=61)
[info] ajp_service::jk_ajp_common.c (2543): (Tomcat7B) sending request to tomcat failed (recoverable), because of error during request sending (attempt=2)
[error] ajp_service::jk_ajp_common.c (2562): (Tomcat7B) connecting to tomcat failed.
[debug] ajp_reset_endpoint::jk_ajp_common.c (757): (Tomcat7B) resetting endpoint with socket -1 (socket shutdown)
[debug] ajp_done::jk_ajp_common.c (3013): recycling connection pool slot=0 for worker Tomcat7B
[debug] service::jk_lb_worker.c (1374): worker Tomcat7B escalating local error to global error
[info] service::jk_lb_worker.c (1388): service failed, worker Tomcat7B is in error state
[debug] service::jk_lb_worker.c (1399): recoverable error... will try to recover on other worker
[debug] get_most_suitable_worker::jk_lb_worker.c (946): searching worker for partial sessionid 89569C584CC4F58740D649C4BE655D36.Tomcat7B
[debug] get_most_suitable_worker::jk_lb_worker.c (954): searching worker for session route Tomcat7B
[debug] get_most_suitable_worker::jk_lb_worker.c (1001): found best worker Tomcat7A (Tomcat7A) using method 'Request'
[debug] service::jk_lb_worker.c (1161): service worker=Tomcat7A route=Tomcat7B
[debug] ajp_get_endpoint::jk_ajp_common.c (3096): acquired connection pool slot=0 after 0 retries
[debug] ajp_marshal_into_msgb::jk_ajp_common.c (605): ajp marshaling done
[debug] ajp_service::jk_ajp_common.c (2379): processing Tomcat7A with 2 retries
[debug] ajp_send_request::jk_ajp_common.c (1572): (Tomcat7A) all endpoints are disconnected.
[debug] jk_open_socket::jk_connect.c (484): socket TCP_NODELAY set to On
[debug] jk_open_socket::jk_connect.c (608): trying to connect socket 896 to 188.8.131.52:8009
[debug] jk_open_socket::jk_connect.c (634): socket 896 [126.96.36.199:24496 -> 188.8.131.52:8009] connected
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): sending to ajp13 pos=4 len=615 max=8192
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0000     .4.c....HTTP/1.1
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0010     .../Accounter/pr
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0020     intFrameSet.jhtm
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0030     l...::1...::1...
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0040     localhost..P....
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0050     ...Keep-Alive...
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0060     ..0....rimage/jp
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0070     eg,.image/gif,.i
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0080     mage/pjpeg,.appl
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0090     ication/x-ms-app
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00a0     lication,.applic
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00b0     ation/xaml+xml,.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00c0     application/x-ms
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00d0     -xbap,.*/*...Acc
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00e0     ept-Encoding...g
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00f0     zip,.deflate...A
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0100     ccept-Language..
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0110     .nb-NO....]Usern
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0120     ame=NA_jose.mati
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0130     as_AT_addenergy.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0140     no;.JSESSIONID=8
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0150     9569C584CC4F5874
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0160     0D649C4BE655D36.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0170     Tomcat7B.....loc
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0180     alhost.....http:
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0190     //localhost/Acco
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01a0     unter/NemsAccoun
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01b0     ter.jhtml....uMo
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01c0     zilla/4.0.(compa
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01d0     tible;.MSIE.8.0;
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01e0     .Windows.NT.6.1;
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01f0     .WOW64;.Trident/
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0200    4.0;.SLCC2;..NET
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0210     .CLR.2.0.50727;.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0220     .NET4.0C;..NET4.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0230     0E)............F
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0240     rameName=Reports
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0250     _CS_EUETS....Tom
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0260     cat7B...........
[debug] ajp_send_request::jk_ajp_common.c (1632): (Tomcat7A) request body to send 0 - request body to resend 0
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): received from ajp13 pos=0 len=238 max=8192
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0000     .....Moved.Tempo
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0010     rarily......OJSE
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0020     SSIONID=6A2507A4
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0030     626F698EC74A733C
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0040     DBA7D9FE.Tomcat7
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0050     A;.Path=/Account
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0060     er;.HttpOnly...P
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0070     ragma...no-cache
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0080     ...Cache-Control
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0090     ...no-cache....&
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 00a0     http://localhost
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 00b0     /Accounter/login
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 00c0     .jhtml.....text/
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 00d0     html;charset=ISO
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 00e0     -8859-1.....0...
[debug] ajp_unmarshal_response::jk_ajp_common.c (660): status = 302
[debug] ajp_unmarshal_response::jk_ajp_common.c (667): Number of headers is = 6
[debug] ajp_unmarshal_response::jk_ajp_common.c (723): Header[0] [Set-Cookie] = [JSESSIONID=6A2507A4626F698EC74A733CDBA7D9FE.Tomcat7A; Path=/Accounter; HttpOnly]
[debug] ajp_unmarshal_response::jk_ajp_common.c (723): Header[1] [Pragma] = [no-cache]
[debug] ajp_unmarshal_response::jk_ajp_common.c (723): Header[2] [Cache-Control] = [no-cache]
[debug] ajp_unmarshal_response::jk_ajp_common.c (723): Header[3] [Location] = [http://localhost/Accounter/login.jhtml]
[debug] ajp_unmarshal_response::jk_ajp_common.c (723): Header[4] [Content-Type] = [text/html;charset=ISO-8859-1]
[debug] ajp_unmarshal_response::jk_ajp_common.c (723): Header[5] [Content-Length] = [0]
[debug] start_response::jk_isapi_plugin.c (963): Starting response for URI '/Accounter/printFrameSet.jhtml' (protocol HTTP/1.1)
[debug] start_response::jk_isapi_plugin.c (1063): Not using Keep-Alive
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): received from ajp13 pos=0 len=2 max=8192
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0000     ................

[debug] ajp_process_callback::jk_ajp_common.c (1943): AJP13 protocol: Reuse is OK
[debug] ajp_reset_endpoint::jk_ajp_common.c (757): (Tomcat7A) resetting endpoint with socket 896
[debug] ajp_done::jk_ajp_common.c (3013): recycling connection pool slot=0 for worker Tomcat7A
[debug] HttpExtensionProc::jk_isapi_plugin.c (2211): service() returned OK
[debug] HttpFilterProc::jk_isapi_plugin.c (1851): Filter started
[debug] map_uri_to_worker_ext::jk_uri_worker_map.c (1036): Attempting to map URI '/localhost/Accounter/login.jhtml' from 8 maps
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/servlet/*=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/ws/*=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/nems*.pdf=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/*.service=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/*.jhtml=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/*.json=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/jkmanager=status' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/servlet/*=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/ws/*=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/nems*.pdf=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/*.service=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (850): Attempting to map context URI '/Accounter/*.jhtml=balancer' source 'uriworkermap'
[debug] find_match::jk_uri_worker_map.c (863): Found a wildchar match '/Accounter/*.jhtml=balancer'
[debug] HttpFilterProc::jk_isapi_plugin.c (1938): check if [/Accounter/login.jhtml] points to the web-inf directory
[debug] HttpFilterProc::jk_isapi_plugin.c (1954): [/Accounter/login.jhtml] is a servlet url - should redirect to balancer
[debug] HttpFilterProc::jk_isapi_plugin.c (1994): fowarding escaped URI [/Accounter/login.jhtml]
[debug] init_ws_service::jk_isapi_plugin.c (2982): Reading extension header HTTP_TOMCATWORKER0000000180000000: balancer
[debug] init_ws_service::jk_isapi_plugin.c (2983): Reading extension header HTTP_TOMCATWORKERIDX0000000180000000: 5
[debug] init_ws_service::jk_isapi_plugin.c (2984): Reading extension header HTTP_TOMCATURI0000000180000000: /Accounter/login.jhtml
[debug] init_ws_service::jk_isapi_plugin.c (2985): Reading extension header HTTP_TOMCATQUERY0000000180000000: (null)
[debug] init_ws_service::jk_isapi_plugin.c (3040): Applying service extensions
[debug] init_ws_service::jk_isapi_plugin.c (3298): Service protocol=HTTP/1.1 method=GET host=::1 addr=::1 name=localhost port=80 auth= user= uri=/Accounter/login.jhtml
[debug] init_ws_service::jk_isapi_plugin.c (3310): Service request headers=9 attributes=0 chunked=no content-length=0 available=0
[debug] wc_get_worker_for_name::jk_worker.c (116): found a worker balancer
[debug] HttpExtensionProc::jk_isapi_plugin.c (2188): got a worker for name balancer
[debug] service::jk_lb_worker.c (1118): service sticky_session=1 id='6A2507A4626F698EC74A733CDBA7D9FE.Tomcat7A'
[debug] get_most_suitable_worker::jk_lb_worker.c (946): searching worker for partial sessionid 6A2507A4626F698EC74A733CDBA7D9FE.Tomcat7A
[debug] get_most_suitable_worker::jk_lb_worker.c (954): searching worker for session route Tomcat7A
[debug] get_most_suitable_worker::jk_lb_worker.c (968): found worker Tomcat7A (Tomcat7A) for route Tomcat7A and partial sessionid 6A2507A4626F698EC74A733CDBA7D9FE.Tomcat7A
[debug] service::jk_lb_worker.c (1161): service worker=Tomcat7A route=Tomcat7A
[debug] ajp_get_endpoint::jk_ajp_common.c (3096): acquired connection pool slot=0 after 0 retries
[debug] ajp_marshal_into_msgb::jk_ajp_common.c (605): ajp marshaling done
[debug] ajp_service::jk_ajp_common.c (2379): processing Tomcat7A with 2 retries
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): sending to ajp13 pos=4 len=577 max=8192
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0000     .4.=....HTTP/1.1
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0010     .../Accounter/lo
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0020     gin.jhtml...::1.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0030     ..::1...localhos
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0040     t..P.......Keep-
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0050     Alive.....0....r
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0060     image/jpeg,.imag
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0070     e/gif,.image/pjp
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0080     eg,.application/
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0090     x-ms-application
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00a0     ,.application/xa
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00b0     ml+xml,.applicat
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00c0     ion/x-ms-xbap,.*
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00d0     /*...Accept-Enco
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00e0     ding...gzip,.def
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 00f0     late...Accept-La
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0100     nguage...nb-NO..
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0110     ..]Username=NA_j
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0120     ose.matias_AT_ad
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0130     denergy.no;.JSES
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0140     SIONID=6A2507A46
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0150     26F698EC74A733CD
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0160     BA7D9FE.Tomcat7A
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0170     .....localhost..
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0180     ...http://localh
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0190     ost/Accounter/Ne
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01a0     msAccounter.jhtm
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01b0     l....uMozilla/4.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01c0     0.(compatible;.M
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01d0     SIE.8.0;.Windows
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01f0     Trident/4.0;.SLC
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 01e0     .NT.6.1;.WOW64;.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0200     C2;..NET.CLR.2.0
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0210     .50727;..NET4.0C
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0220     ;..NET4.0E).....
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0230     .......Tomcat7A.
[debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1145): 0240     ................
[debug] ajp_send_request::jk_ajp_common.c (1621): (Tomcat7A) Statistics about invalid connections: connect check (0), cping (0), send (0)
[debug] ajp_send_request::jk_ajp_common.c (1632): (Tomcat7A) request body to send 0 - request body to resend 0
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): received from ajp13 pos=0 len=135 max=8192
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0000   .....OK.....Prag
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0010   ma...no-cache...
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0020   Expires...Thu,.0
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0030   1.Jan.1970.00:00
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0040   :00.GMT...Cache-
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0050   Control...no-cac
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0060   he...Cache-Contr
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0070   ol...no-store...
[debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1329): 0080   ..2995..........

Answer: Setting up a cluster on the Tomcat side which does session replication often involves more than just editing server.xml. Often you have to mark your applications as "distributable" in web.xml, and potentially do other things. Also, all of the classes you put into a session must implement the serializable interface.
Finally, beware the Jakarta ISAPI plugin for IIS - it is a port from Apache mod_jk, and is quite broken, at least at high load. We have a 7-server tomcat cluster (300 req/sec peaks) and eventually switched to using nginx on Linux on the front end instead of IIS because the ISAPI_redirect.dll would spontaneously stop serving anything at high load (with nothing in the error logs and no other evidence of problems in perfmon). IIS 7.5 Application request routing plugin might be a better option if you want to stay all-windows.
Comment: Hi thanks for the answer, i already had the  tag to my webapps, and it was working fine for most of the pages but now it redirects all the time with a new session_id. I will try with Application Request Routing plugin to see if its more stable.


giving different data() based on the element in one call

Question: I'm trying to do something like this:
$('a').data('goto', this.href)

I realize I can do this in an each() call but is there a way to do this in one shot?
Answer: each is the most succinct way to do this. Unlike some functions (such as attr), data doesn't support the "pass a function and have it called for every element" convention.
Why do you need a duplicate of the href, though?
Comment: @Majid - It makes sense to not call a function passed in to a call to `data()` because it is a way of storing any kind of data.  You may want to store a function.  How could the method determine whether the function is to be called for each element, or that the function itself is the data?
Comment: He might be changing it and need to revert at some point, I've seen that asked for before a few times.
Comment: Love this kind of *reading between the lines*. Do you get this just from the documentation? i.e. you get clues from `.attr()` having `.attr( attributeName, function(index, attr) )` in the docs, but `.data()` missing it? If that is so, absorbing what is in the documentation takes more than casual reading.
Comment: @Majid: I'm... not sure what you meant by that exactly. Did you mean to ask something?
Comment: @Matti, This could do: Do you know a source thoroughly explaining fine differences between jquery methods - like `you cannot use this method without a septate iterator, because it has no callback function`?
Comment: @Majid: That would be [the documentation](http://docs.jquery.com/). For example, on the `attr` page, if you scroll further down it even has examples for the version that has the function parameter. The `data` page doesn't have that. But the signatures at the top are a big help too.
Comment: Thank you both. Good advice and good food for thought. I have a long way to go, but learning feels good, so I don't mind the distance ;)
Answer: .data() doesn't have a callback method like .attr() for instance, so probably not.  Using the .each() is probably the quickest way.


How to move node contents from local to server environments?

Question: What is the best way to move node contents from a local environment to a server environment?
I don't want to go with the Features modules.
Any examples that we can go with dbscripts?
Answer: Consider using module Backup and Migrate. From the modules project page:

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


Put GLib.Array in a GLib.Value?

Question: I can't figure out how to wrap a GLib.Array in a GLib.Value.
I tried this code.
public int main (string[] args) {
  var value = Value(typeof (Array));

  var a = new Array<string>();
  a.append_val("test");
  value.set_object((Object) a);

  return 0;
}

But it resulted in these errors.
(process:1797): GLib-GObject-WARNING **: invalid uninstantiatable type '(null)' in cast to 'GObject'
(process:1797): GLib-GObject-CRITICAL **: g_value_set_object: assertion 'G_VALUE_HOLDS_OBJECT (value)' failed

Answer: I think of GValue being used as a container for a single type of value, whereas GArray is a collection. GValue does have a type_compatible () method. Using that method as a check before your code shows GLib doesn't allow a GArray to be stored as a GObject:
public int main (string[] args) {
  if (!Value.type_compatible (typeof (Array), typeof (Object))) {
    message ("Incompatible types");
    return 1;
  }

  var value = Value(typeof (Array));

  var a = new Array<string>();
  a.append_val("test");
  value.set_object((Object) a);

  return 0;
}

This code stops where the check for compatible types is made.
I don't know what you are trying to achieve, but I suggest looking at GVariant:
void main () {
    string[] a = {"test"};
    Variant variant = a;
    print (variant.print(true) + "\n");
}

If you need a GValue then you can store a GVariant in a GValue using GValue's take_variant () method.
Comment: I'm trying to map a `a(ss)` GLib.Settings to my configuration object. The `SettingsBindGetMappingShared` function passes a GLib.Value to set the prop. I was planning to use a GLib.Array of Structs.
Answer: GArray is not a GObject. However, it is a boxed type (a more primitive version of type tagging used in GValue), so you should be able to store it in the GValue using value.set_boxed (a).

Put GLib.Array in a GLib.Value?


Can't run a pig script on apache Zeppelin

Question: <code>> org.apache.pig.backend.executionengine.ExecException: ERROR 4010:
> Cannot find hadoop configurations in classpath (neither
> hadoop-site.xml nor core-site.xml was found in the classpath). If you
> plan to use local mode, please put -x local option in command line at
> org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.getExecConf(HExecutionEngine.java:157)
> at
> org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.init(HExecutionEngine.java:194)
> at
> org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.init(HExecutionEngine.java:111)
> at org.apache.pig.impl.PigContext.connect(PigContext.java:310) at
> org.apache.pig.PigServer.<init>(PigServer.java:232) at
> org.apache.pig.PigServer.<init>(PigServer.java:220) at
> org.apache.pig.PigServer.<init>(PigServer.java:193) at
> org.apache.pig.PigServer.<init>(PigServer.java:185) at
> org.apache.zeppelin.pig.PigInterpreter.open(PigInterpreter.java:61) at
> org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
> at
> org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:617)
> at org.apache.zeppelin.scheduler.Job.run(Job.java:188) at
> org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:140)
> at
> java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
> at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
> java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
> at
> java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
> at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
> at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
> at java.lang.Thread.run(Thread.java:748)
</code>
I have tried run a pig script on apache Zeppelin but it gives me this error.I have checked all the configurations and settings but unable to resolve this.
Comment: What configurations did you check and where? What files are in your `HADOOP_CONF_DIR` environment variable? Can you please show your Pig configuration properties in the question? Can you run Pig shell outside Zeppelin?
Comment: https://stackoverflow.com/questions/66433489/running-pig-query-on-apache-zeppelin
please help me on this
Answer: Please check the doc here. https://zeppelin.apache.org/docs/0.8.0/interpreter/pig.html
Most likely you set execution mode as mapreduce, but didn't configure HADOOP_CONF_DIR
Comment: Thanks for your interest. The issue got fixed.


undefined local variable or method `your_questions_path'

Question: I receive an error saying that it has an
undefined local variable or method 'your_questions_path'

My routes.rb file:
Rails.application.routes.draw do
  get "/" => "main_app#index"
  get "/location" => "location#location"
  post "/location/index" => "location#index"
  get "/location/index" => "location#index"
  get "/location/directions" => "location#directions"

  root to: 'questions#index'

  resources :questions do
    collection do
      get :your_questions
    end
  end

  get '/logout', to: 'sessions#destroy', via: :delete
  resources :users, only: [:new, :create]
  resources :sessions, only: [:new, :create]
  resources :questions, except: [:new] do
    resources :answers, only: [:create]
  end

  get '/register', to: 'users#new'
  get '/login', to: 'sessions#new'
  get '/logout', to: 'sessions#destroy', via: :delete
  # get '/questions/your_questions', to: 'questions#your_questions' original
  get '/questions/:id', to: 'questions#show'
  get 'search', to: 'controller#action', as: :search

My view file with the questions path a.k.a app/views/layouts/application.html.erb

      <%= link_to 'Home', root_path %>

  <% if logged_in? %>

      <%= link_to "Your Q's", your_questions_path %>

      <%= link_to "Logout (#{current_user.username})", logout_path, method: 'get' %>

  <% else %>

      <%= link_to 'Register', register_path %>

      <%= link_to 'Login', login_path %>

I want the questions path to go to http://localhost:3000/questions/1
Thank you in advance!
Answer: The routes you've defined create the following routes:
          your_questions_questions GET    /questions/your_questions(.:format)           questions#your_questions
                         questions GET    /questions(.:format)                          questions#index
                                   POST   /questions(.:format)                          questions#create
                      new_question GET    /questions/new(.:format)                      questions#new
                     edit_question GET    /questions/:id/edit(.:format)                 questions#edit
                          question GET    /questions/:id(.:format)                      questions#show
                                   PATCH  /questions/:id(.:format)                      questions#update
                                   PUT    /questions/:id(.:format)                      questions#update
                                   DELETE /questions/:id(.:format)                      questions#destroy

The top route is the your_questions route, which means you want use:
your_questions_questions_path

Answer: this is happening because you have nested your path inside of a resources block, ie. you have this:
resources :questions do
  collection do
    get :your_questions
  end
end

if you were to get to this path, (run rake routes) you would need to use questions_your_questions_path, however since you want to route to something like http://localhost:3000/quesitons/1 this is a simple 'show' path that is provided to you by the resources command, instead change your routes file to simply say:
resources :questions
and then use question_path(@question) where @question is an instance variable set in the controller.
However... also looking from your code, you seem to be wanting the questions_path instead since that would provide the index action (a listing of questions). You can then in your controller scope the collection of questions to the ones the current user sees...
ie.
QuestionsController < ApplicationController

def index
  @questions = current_user.questions
end

(assuming your User has_many :questions)


Import raster stack and return new layer

Question: I am trying to import about 50 .tif files into a stack using the rasters package. Because of the large number of files I don't want to list them all out. I have tried a few methods but have been unsuccessful, including this code:

test<-stack(choose.files(),values=T)
  Error in .local(x, ...) :
    Arguments should be Raster* objects or filenames

In addition I want to classify a new raster based on the 50 I import. For example I have a group of polygons with the same extent (could convert to raster) and want to count the number of times a value "1" occurs in each polygon. I figure the "overlay" function would be best for this but am having trouble thinking of how to code the associated function. Any help would be appreciated.
Comment: it matters not that it's 50, do a test with just two, list them all out, test that they really are files that can be seen with file.exists() - my bet is your file paths are not right, or the files are raster-readable, demonstrate to yourself that it works with 1 by raster(x)
Answer: The easier way with many files should be to use (with some modifications)
f <- list.files(path='???', pattern='.tif$', full.names=TRUE)
s <- stack(f)

But if you want to do it interactively:
f <- choose.files()
s <- stack(f)

The error occurred because you use "values=TRUE" (which is not an argument to stack and gets interpreted as a file name)


Windows - Fine-grained administrator permissions

Question: Whenever the Windows UAC pop-up shows up to grant a program administrator rights there is just a Yes/No answer.
Is there any way to limit what a program can do when run as administrator.
Most programs do not need all priviledges, but just a little bit, that a standard user cannot do.
In Linux there a multiple ways, i can think of right now:
Root capabilities: partition the root priviledge into smaller capabilities
fakeroot: when the program checks for root but does not really need it
SELinux and similar tools: Everything must be explicitly granted
Another way of asking: Can i limit the amount of damage a program can cause while giving access to administrator rights.
Example: Give a program the right to see one specific programs adress space, but not all of them.
Answer: The UAC prompt is an all-or-nothing proposition, you either allow the program administrator access or don't run it at all.
That doesn't necessarily mean that you can't achieve your goals in other ways.  For example, if you want to give a user access to the address space of a particular process, you can change the permissions on that process.  Similarly with files and registry keys, though it is usually inadvisable to change permissions on the parts of the file system and registry that don't belong to you.
This question on Stack Overflow discusses ways of getting an application that requests administrator access (but doesn't actually need it) to run anyway.
Theoretically you can grant individual privileges (e.g., backup privilege) to individual accounts, but while the kernel still supports this, UAC breaks it.  Almost all admin-level privileges you could grant someone can be leveraged to gain unrestricted administrator access anyway.
The more usual approach if you want to allow a user to perform specific administrative tasks is to write a system service to do the work on the user's behalf.  This typically involves splitting the application into two parts, one that runs as a system service and has administrator access and one that runs on the user's desktop and does not.

Addendum: it is no longer true that UAC breaks granting individual privileges to individual accounts.  If you enter your own (non-administrator) username and password at the UAC prompt, the elevated process will receive whatever individual privileges your account has been granted.


Why won't Firefox parse this XSLT?

Question: I've recently been playing around with XML formatting and XLST files, because it seems like the most direct solution to a UI problem I've been wrestling with involving users accessing the central data differently.  In my experimentation I've created a really nice formatting sheet that looks great... in Internet Explorer.  When I test it in Firefox, I consistently get the same error message:
"Error loading stylesheet: Parsing an XSLT stylesheet failed."
I've tried paring the stylesheet down to a very basic document and still experience the same problem. I've been checking tutorials and other webforums and mimic'ing examples, but I can't seem to find anything that is explicitly applicable.
Here's my test XML file:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="fox.xslt"?>

   <title>Making Excellent Pasta Sauce</title>
   <synopsis>A simple recipe for an amazing sauce, with tips on getting that extra flavor.</synopsis>
   <content>Here is my content.</content>
   <tags>
      <tag>sauce</tag>
      <tag>recipes</tag>
   </tags>

And then, here's my XSLT file (named, as you might tell from the example block above, "fox.xslt".
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">

   <xsl:for-each select="article">
      TITLE: <xsl:value-of select="title"/>

      SYNOPSIS: <xsl:value-of select="synopsis"/>

   </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

I suspect that it may have something to do with
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> because I've seen a few different things done with this in examples, I've tried a few of the different values here and haven't seem to hit on one that works with this example.
I'm sure it's probably a basic problem, I just have been flummoxed at tracking down.  Hopefully someone can lead me to the "forehead smacking moment".
Thanks in advance!
Answer: Try to replace your stylesheet element with this:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

You may also want to add this:
xmlns="http://www.w3.org/1999/xhtml"

Comment: I should say it works with `version="1.0"` (or 1.1) too. The main issue is probably the `xsl` namespace.
Comment: The problem **is** the XSLT namespace. But your answer missed explanation. That namespace URI `http://www.w3.org/TR/WD-xsl` was used by earlier M$ productos implementing an old XSLT Working Draft. Later this was deprecated. None complain XSLT processor up today allows this namespace.
Comment: @Alejandro, yes indeed, but I've just tested on Firefox 3.6 and if the `version` attribute is missing, it doesn't work either (so both issues need to be fixed).
Answer: I find it most useful to use a separate tool to find the problems that FireFox (et al) will not report.  Install and use, say, the xsltproc command, which gives much more helpful results.
For example, I encountered a file where Firefox's only response was (take your pick):  "Parsing an XSLT stylesheet failed" or, with version=1.1 in the stylesheet, " the equally useless "Parsing an XSLT expression failed."
So, I went to the command-line and entered, say ..."xsltproc bah.xsl humbug.xml" then, presto, there it was:
error
xsltCompileStepPattern : ']' expected
compilation error: file bah.xsl line 157 element template
xsltCompilePattern : failed to compile 'ATOM[@STATE='GAS''

I therefore routinely run all of my XML and XSL files through xsltproc or its equivalent such that they "run clean" before feeding it to my friendly neighborhood browser.  I have not yet found any browser that "graciously and informatively" handles an XSLT issue.
In addition, I find it quite-frankly easier to look at the command output (which is HTML), say by piping it to the less or more commands for pagination, than to try looking at it in a browser, until I know that I am very close to what I am looking for.  If I'm trying to find a problem in the generated (say) HTML output, I really don't want to look at it "as HTML" at first.  If the XSL transforms are "spewing nonsense" (as, of course, they do at first, at least for me), a browser's attempts to turn it into something beautiful just gets in the way of finding the bugs in the stylesheet.

Why won't Firefox parse this XSLT?


How to setup Drupal Performance Monitoring to Bypass Varnish?

Question: I have lots of uptime problems with my Drupal hosting company this month.
Most of the time my Pingdom monitor doesn't even alert of the problem because Varnish is still able to serve a cached homepage.
How can I bypass Varnish to check true health of the Drupal instance? They have a username/password option but I'm sure that's for the http username/password and not for a form based login.
If I specify a fake session cookie I could bypass Varnish but then Drupal would just redirect me to the home page?
Answer: I could bypass it by adding a "NO_CACHE=1" cookie to the request. Using a POST instead of a GET request will bypass Varnish as well.
Answer: Varnish is just like a proxy, so you configured that to get data from something like 127.0.0.1:8080 I guess.
So you just have to configure your pingdom to check example.com:8080 if you allowed your webserver listen also public request.


Ir para âncora antes do carregamento completo da página

Question: Possuo uma página que toda vez ao atualizar, retorna ao topo após o carregamento completo. Porém, possuo uma segunda página que tem um link da seguinte forma: index.html#empresa, gostaria que a mesma parasse,"independentemente" do seu carregamento, na âncora empresa.
→ Pastebin do index.html
Comment: @LeonanCarvalho, o arquivo `index.html` excede o limite de caracteres permitido para publicação.
Comment: Sugiro colocar parte do código aqui dentro do stackoverflow ou então usar a opção snippet.
Comment: Sua duvida é "Como navegar pra uma ancora dentro da página com javascript?"
Comment: @LeonanCarvalho, não. Necessito que ao carregar o  link `index.html#empresa`, o mesmo pare na âncora **empresa** e não no topo da página. Pois, o parametro #empresa via URL, simplesmente está sendo "desconsiderado" pela chamada de carregamento completo da página: `$(document).ready(function(e) {});`, porém não sei se é realmente isso e como está ocorrendo esse problema.
Comment: Se você navegasse para ancora no on-load da página?
Comment: Podemos ir para o [chat](https://chat.stackexchange.com/rooms/64546/ir-para-ancora-antes-do-carregamento-completo-da-pagina)? @LeonanCarvalho
Comment: Não vi o indicador no código da sua pagina
Comment: Não vi o indicador no código da sua pagina. Veja esse exemplo
 http://kithomepage.com/kit/tutorial/html/hiperlinks.php#indicador
Answer: O código abaixo deve funcionar ao seu propósito:

Você pode usar o código sem esperar o carregamento da página ($(document).ready). Porém é preciso que o código esteja no final do . Isso porque a página é carregada linha por linha, de cima para baixo e o elemento em questão (#empresa) já foi carregado.

Obs.: Isso não funciona no exatíssimo momento em que a página é chamada. Vai
  depender da velocidade do carregamento da página até chegar no script,
  pois não é possível executar um script antes do carregamento normal da página.
Answer: $(window).load(function(){
    if(window.location.hash) {
        $('html, body').animate({
            scrollTop: $(window.location.hash).offset().top + 'px'
        }, 1000, 'swing');
    }
});


How to prove the following $\Theta$notation

Question: If the following function is given: $f(n)=n^2+ n \ln(n)+1$.
How do  you prove the $\Theta$ notation?
I assume that is must be $\Theta$($n^2$).
But I'm not sure how to solve it.
Answer: It's clear that
$$n^2\le f(n),\quad \forall n\ge1$$
so
$$n^2=\mathcal O(f(n))$$
moreover we have
$$\ln n\le n,\quad \forall n\ge1$$
so
$$f(n)\le 3n^2 ,\quad \forall n\ge1$$
and then
$$f(n)=\mathcal O(n^2)$$
so we get
$$f(n)=\Theta(n^2)$$
Comment: Can you please explain this step(It's not clear how you get $3n^2$): $$\ln n\le n,\quad \forall n\ge1$$
so
$$f(n)\le 3n^2 ,\quad \forall n\ge1$$
Comment: Since $\ln n\le n$ so $n\ln n\le n^2$ and since $1\le n^2$ we get
$$f(n)=n^2+n\ln n+1\le 3n^2$$
Answer: You may write, as $n$ tends to $+\infty$,
$$
\frac{f(n)}{n^2}=\frac{n^2+ n \ln n +1}{n^2}=1+\frac{\ln n}{n}+\frac{1}{n^2}
$$
thus
$$
\frac{f(n)}{n^2} \rightarrow 1
$$ then $f(n)=\Theta(n^2)$ moreover $f(n)\sim_{+\infty}n^2.$


Display the number of replies to a message with inner joins in PHP

Question: Anything beyond basic SQL statements, not my strong point.
I have a messaging system that I'm coding that is kind of like facebook's where instead of separate messages, you reply to one main message, and all the messages you're participating in are displayed in one spot.
mail table:

mailID
mailUser: person that sent the message
mailTo
mailUnread: 1 is unread
mailSubject
mailBody
mailCurrency
mailTime
mailDeleted: 1 is deleted

relevant fields in the  mailreply table:

mailreplyID
mailreplyUser: user that's replying
mailreplyDeleted: 1 is deleted
mailreplyTo: the id of the message that is replied to

Original I coded it so that it didn't count the number of replies and that worked fine, but I decided it would be helpful to include the number.
This is what I originally had:
SELECT
    a.mailID,
    a.mailUser,
    a.mailTo,
    b.username AS usernamea,
    c.username AS usernameb
FROM
    mail a, users b, users c
WHERE
    (a.mailUser = b.id OR a.mailUser = c.id)
    AND (a.mailTo = '".$id."' OR a.mailUser = '".$id."')
    AND a.mailDeleted = '0'
GROUP BY a.mailID
ORDER BY a.mailID DESC

This was my attempt:
SELECT
    a.mailID,
    a.mailUser,
    a.mailTo,
    b.username AS usernamea,
    c.username AS usernameb
FROM
    mail a, users b, users c
    LEFT JOIN mailreply d
    ON d.mailreplyTo = a.mailID
WHERE
    (a.mailUser = b.id OR a.mailUser = c.id)
    AND (a.mailTo = '".$id."' OR a.mailUser = '".$id."')
    AND a.mailDeleted = '0'
GROUP BY a.mailID
ORDER BY a.mailID DESC

Thanks
Comment: Hi Rebecca, Welcome to Stack Oveflow!  Did your second attempt work?  Did you get any errors or unexpected results?
Comment: Sadly no. I get a "supplied argument is not a valid MySQL result resource" error. I'm not sure what the problem is and I keep trying to change things around with no luck.
Comment: I took the liberty of removing any columns from your query that didn't look like they were important for solving this problem, I hope you don't mind...you should be able to just add them back in once we've figured this out.  Also, the error you mentioned sounds like it's a PHP error...did you get any errors from MySQL itself?
Comment: Thanks! It's fine.

I just assumed there's a problem with the SQL since the problem only happens when I change it away from what I originally had. The line the error is from is from a mysql_num_rows.
Comment: The mysql_* functions require the parameter to be a "MySQL resource" which is essentially what you get from a mysql_* function call that succeeds. Your error would indicate that whatever you're doing isn't working, or is causing an SQL error. Please try using [mysql_error](http://se.php.net/manual/en/function.mysql-error.php) to find out what the SQL error is. - Also, did you consider using a single table for all this? You could just store data in mailreply in your main mail table.
Comment: @Rebecca, could you try getting the MySQL error message with the [mysql_error function](http://php.net/manual/en/function.mysql-error.php) please?
Comment: Also rather than supplying just the sql could you please provided me with the php thats calling this query. I have you tried this query in PhpMyadmin or sqlpro or something, i find it often useful to test the sql im writing
Answer: Try this:
SELECT
    a.mailID,
    a.mailUser,
    a.mailTo,
    b.username AS fromUsername,
    c.username AS toUsername,
    count(d.mailReplyID) as mailCount
FROM
    mail a
    INNER JOIN users b ON b.id=a.mailUserId
    INNER JOIN users c ON c.id=a.mailTo
    LEFT JOIN mailreply d
    ON d.mailreplyTo = a.mailID
WHERE
   (a.mailTo = '".$id."' OR a.mailUser = '".$id."')
    AND a.mailDeleted = '0'
GROUP BY a.mailID
ORDER BY a.mailID DESC

You need to join to the users table on each side of the message to get the usernames. I think you were confusing the where clause to check if the current user is sender or recipient with the join specification, that's a good reason for using the INNER JOIN syntax rather than separating tables by commas and putting the join spec in the where clause.
You then group by the mail ID as you correctly did, and add in a count column on the mailreply table. As this table is left joined, which you were also right about, it will also return the messages with a count of zero replies.
Hope that sorts it for you - you were nearly there!
James


Moquette internalPublish equivalent function in Apache ActiveMQ Artemis

Question: Is there an equivalent Moquette internalPublish function in Apache ActiveMQ Artemis? I need to publish some message from within the broker in my code. Could someone please tell me how this can be done in ActiveMQ Artemis?
Answer: You can use PostOffice.route(Message) methods.
The current implementation is taking PostOffice.route(ServerMessage message, direct). Pass false on direct otherwise the consumer will deliver within the same thread.
I wouldn't recommend that thought. The proper way would be to create a proper producer. Make it IN-VM if you like.
At the moment I am changing the signature to route(Message, boolean direct).


Arel query through an association

Question: Here are my models:
class Player < ActiveRecord::Base
  has_many :registrations, :class_name => "PlayerRegistration"
end

class PlayerRegistration < ActiveRecord::Base
   belongs_to :player

   belongs_to :payment

   def self.paid
     where("payment_id IS NOT NULL")
   end

   def self.unpaid
     where(:payment_id => nil)
   end
end

class Payment < ActiveRecord::Base
  has_many :registrations, :class_name => "PlayerRegistration"
end

What I would like to do is create a scope on Player that returns all players who have an unpaid registration, so something like:
BAD PSUEDO CODE AHEAD
class Player < ActiveRecord::Base

  def self.paid
    registrations.unpaid  #But actually return the players
  end
end

Is this possible?  It must be, considering that all the data I need is out there, I just have no idea how to write that sort of an AREL query.  Can anybody help?
FWIW I've tried this:
class Player < ActiveRecord::Base
  def self.paid
    includes(:registrations).where("registrations.payment_id IS NOT NULL")
  end
end

but that provides me with the following error:
ActiveRecord::StatementInvalid:
   PGError: ERROR:  missing FROM-clause entry for table "registrations"
   LINE 1: ...registrations"."player_id" = "players"."id" WHERE "registrat...
                                                                ^
   : SELECT "players"."id" AS t0_r0, "players"."first_name" AS t0_r1, "players"."last_name" AS t0_r2, "players"."birthday" AS t0_r3, "players"."gender" AS t0_r4, "players"."created_at" AS t0_r5, "players"."updated_at" AS t0_r6, "players"."user_id" AS t0_r7, "player_registrations"."id" AS t1_r0, "player_registrations"."player_id" AS t1_r1, "player_registrations"."grade_id" AS t1_r2, "player_registrations"."shirt_size_id" AS t1_r3, "player_registrations"."division_id" AS t1_r4, "player_registrations"."coach_request" AS t1_r5, "player_registrations"."buddy_request" AS t1_r6, "player_registrations"."created_at" AS t1_r7, "player_registrations"."updated_at" AS t1_r8, "player_registrations"."league_id" AS t1_r9, "player_registrations"."season_id" AS t1_r10, "player_registrations"."school_id" AS t1_r11, "player_registrations"."payment_id" AS t1_r12 FROM "players" LEFT OUTER JOIN "player_registrations" ON "player_registrations"."player_id" = "players"."id" WHERE "registrations"."payment_id" IS NULL

Could anyone show me a better way?  Isn't there a way I can use the paid scope that I already have in PlayerRegistrations?
Comment: Side note, use [scope](http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#method-i-scope) instead of those paid/unpaid functions: `scope :paid where("payment_id IS NOT NULL")` You can also refer to [rail 3 where condition using NOT NULL](http://stackoverflow.com/questions/4252349/rail-3-where-condition-using-not-null)
Answer: You need the real table name in the where() filter:
class Player < ActiveRecord::Base
  def self.paid
    includes(:registrations).where("player_registrations.payment_id IS NOT NULL")
  end
end

Comment: +1. I wish I could give more! Your answer was the final hint that helped me answer my own question. Thanks! http://stackoverflow.com/questions/15470782/how-can-i-create-a-scope-in-a-model-that-returns-only-those-objects-with-an-asso
Answer: You could write:
class Player

  scope :unpaid, includes(:registrations).where("player_registrations.payment_id is null")
  scope :paid, includes(:registrations).where("player_registrations.payment_id is not null")

end

and now Player.unpaid will return all players with unpaid registrations.
If you write something like:
class Registration

  scope :paid, where("payment_id IS NOT NULL")
  scope :unpaid, where("payment_id is null")

end

then it is possible to write player1.registrations.unpaid, but that is not what you want.
If I understand correctly, you want to find all players with unpaid registrations, and that is only possible using the scope on the Player class.
Hope this helps.

Arel query through an association


testing if data is from a normal distribution

Question: I have some maximum temperature data. Here is the histogram and qqplot:

Visually they look pretty good and I would reasonably say they are from a normal distribution but the Shapiro-Wilk Normality Test (shapiro.test in R) is saying that it is not from a normal distribution.
I found this post which basically says: don't bother testing for normality it will get it wrong. However I used this test in the past (on a generated dataset for a class), and it worked well. It is also the most robust of the statistical tests out there.
Is it better to visually examine the data or use a test for normality to make sure my assumptions are valid? How robust is the Shapiro-Wilk Normality Test?
*I am curious if anyone else has had this issue with actual data as apposed to generated data.
Answer: The key quote from the SO post you link is the following, especially the second half:

When the sample size is small, even big departures from normality are not detected, and when your sample size is large, even the smallest deviation from normality will lead to a rejected null.

With normality tests (or any other goodness-of-fit test), there is always a continuum. If your data generating process is even slightly non-normal, then normality will be rejected if your $n$ is large enough. Look at that SO post again: even a $t$ distribution with 200 degrees of freedom will be rejected as non-normal given enough data - and that is about as normal as you can ever get, unless you are explicitly generating normal data.
Of course, it is no surprise that normality tests perform as expected if you have explicitly generated normally distributed data. Unfortunately, that doesn't tell you much about what happens with real data.
You seem to have more than 1500 data points. I'd say that you are well and truly beyond the threshold at which small deviations from non-normality are picked up.
The question isn't whether data are normally distributed. They never are. (Simply measuring accuracy means that real measured data are in the end always discrete, so they cannot be normal.) The question, if at all, is whether they are sufficiently normal for whatever you need normality for. And I'd argue that they typically are. For instance, ANOVA F tests are surprisingly robust against non-normally distributed residuals, since what is relevant is actually the normal distribution of the parameter estimates, which is certainly given once you have enough data that your normality tests start rejecting residuals.
Bottom line: think about why you need normality. And whether at all.
Answer: Stephan covers the direct issue very well. I just thought I'd address a couple of side issues:
The common notion that it's better to test normality and choose between a t-test and a nonparametric alternative (a signed rank test or a Wilcoxon-Mann-Whitney depending on whether it's a one-sample/paired vs a two-sample situation) appears to be somewhat mistaken; that process impacts the properties (significance level and power) of both the subsequent possible tests.
Unless you know to expect no-heavier-than-normal tails$^\dagger$, you may be better to simply not consider making the normality assumption in the first place (the power loss is never very large but the power advantage can be great, particularly with small effects and large samples).
$\dagger$ The t-test tends to perform slightly better than the usual nonparametric alternative at the normal ... but it has a bigger advantage when the tail is lighter. (Other choices would have bigger advantages still, but they're not usually in consideration in these sorts of questions)


Estou com um erro de conversão ao rodar um codigo C#

Question: Ao Rodar o codigo ele diz o seguinte:

Se eu der ok a aplicação roda normalmente mas os dados inseridos no banco não aparecem no DataGridView. Qual seria o meu erro?
   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using AcessoDados.Contracts;
    using AcessoDados.Entities;
    using System.Data;
    using System.Data.SqlClient;

    namespace AcessoDados.Repositories
    {
    public class FuncionarioRepository : MasterRepository, IFuncionarioRepository
    {
        private string selectAll;
        private string insert;
        private string update;
        private string delete;

        public FuncionarioRepository()
        {
            selectAll = "Select Nome, Telefone, Cpf, Endereco, Numero, Bairro, Cep, Cidade, Estado, Salario from Funcionario";
            insert = "insert into Funcionario values(@Nome,@Telefone,@Cpf,@Endereco,@Numero,@Bairro,@Cep,@Cidade,@Estado,@Salario)";
            update = "update Funcionario set Nome=@Nome,Telefone=@Telefone,Cpf=@Cpf,Endereco=@Endereco,Numero=@Numero,Bairro=@Bairro,Cep=@Cep,Cidade=@Cidade,Estado=@Estado,Salario@Salario where Id=@Id";
            delete = "delete from Funcionario where Id=@Id";
        }
        public int Add(Funcionario entity)
        {
            parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter("@Nome", entity.Nome));
            parameters.Add(new SqlParameter("@Telefone", entity.Telefone));
            parameters.Add(new SqlParameter("@Cpf", entity.Cpf));
            parameters.Add(new SqlParameter("@Endereco", entity.Endereco));
            parameters.Add(new SqlParameter("@Numero", entity.Numero));
            parameters.Add(new SqlParameter("@Bairro", entity.Bairro));
            parameters.Add(new SqlParameter("@Cep", entity.Cep));
            parameters.Add(new SqlParameter("@Cidade", entity.Cidade));
            parameters.Add(new SqlParameter("@Estado", entity.Estado));
            parameters.Add(new SqlParameter("@Salario", entity.Salario));
            return ExecuteNonQuery(insert);

        }

        public int Editar(Funcionario entity)
        {
            parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter("@Id", entity.Id));
            parameters.Add(new SqlParameter("@Nome", entity.Nome));
            parameters.Add(new SqlParameter("@Telefone", entity.Telefone));
            parameters.Add(new SqlParameter("@Cpf", entity.Cpf));
            parameters.Add(new SqlParameter("@Endereco", entity.Endereco));
            parameters.Add(new SqlParameter("@Numero", entity.Numero));
            parameters.Add(new SqlParameter("@Bairro", entity.Bairro));
            parameters.Add(new SqlParameter("@Cep", entity.Cep));
            parameters.Add(new SqlParameter("@Cidade", entity.Cidade));
            parameters.Add(new SqlParameter("@Estado", entity.Estado));
            parameters.Add(new SqlParameter("@Salario", entity.Salario));
            return ExecuteNonQuery(update);
        }

        public IEnumerable<Funcionario> GetAll()
        {
            var tableResult = ExecuteReader(selectAll);
            var listFuncionario = new List<Funcionario>();
            foreach (DataRow item in tableResult.Rows)
            {
                listFuncionario.Add(new Funcionario {
                    Id = Convert.ToInt32(item[0]),
                    Nome = item[1].ToString(),
                    Telefone = item[2].ToString(),
                    Cpf = item[3].ToString(),
                    Endereco = item[4].ToString(),
                    Numero = Convert.ToInt32(item[5]),
                    Bairro = item[6].ToString(),
                    Cep = item[7].ToString(),
                    Cidade = item[8].ToString(),
                    Estado = item[9].ToString(),
                    Salario = (float) Convert.ToDouble(item[0])
                });
            }
            return listFuncionario;
        }

        public int Remover(int Id)
        {
            parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter("@Id", Id));
            return ExecuteNonQuery(delete);
        }
    }
}

O Stack meio que bugou a indentação!
Comment: Da uma lida em https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%c3%83o-fazer-perguntas/5485#5485 ,refaça sua pergunta com o codigo ao inves de imagem.
Comment: Coloquei a imagem pq o codigo ta bem grande mas vou colocar so essa parte entao.
Comment: Você deve estar fazendo errado, só o que postou não tem como ajudar
Comment: Coloquei o codigo todo.
Answer: Pela imagem apresentada, o erro está na conversão de uma string para um inteiro. Os únicos lugares onde é feita tal conversão são Convert.ToInt32(item[0]) e Convert.ToInt32(item[5]).
Ao olhar o seu select é possível verificar que o primeiro item retornado é o nome e não o id, como vc espera no seu foreach, e por isso o 1o ToInt32 retorna erro.
Adicione o id à sua query e verifique se as demais propriedades estão na ordem correta. Uma coisa que poderia ajudar, nesses casos, é trocar todas as propriedades para string, assim vc já conseguiria verificar que algum campo da base de dados nao estaria sendo preenchido na propriedade correta.
Comment: Na imagem mostra que ele fez `Numero = Convert.ToInt32(item[0])` onde deveria ser `Numero = Convert.ToInt32(item[5])` também.
Comment: Sim, como houve o erro logo na primeira propriedade, todas as demais também estão erradas, só não vão apresentar erro por serem strings.


Looking for latest results by using group_by

Question: i'm trying to create an overview page for my customers and would like to show when the customer (within the last year) used a type of service (e.g. window cleaning or floor cleaning).
I tried it this way:
SELECT start, project_id, category_id, MAX(start)
FROM `time_entries`
WHERE project_id = '$project_id' AND start > '$oneyearago'
GROUP BY category_id

project_id = kind of a unique customer id
category_id = 1 for window cleaning, 2 for floor cleaning and so on
start = DATETIME when the last service started
I would like to show the LAST services, but it only shows the oldest services. What am i Doing wrong? does anyone here has a idea for me?
Thank you very much in advance.
EDIT: This is the database example
id   project_id category_id      start

---|------------|-----------|-------------------

1  |  1         | 1         |  2019-11-11 09:51:07

2  |  1         | 2         |  2019-11-12 09:51:07

5  |  1         | 3         |  2019-11-13 09:51:07

3  |  1         | 1         |  2020-11-11 09:51:07

4  |  1         | 2         |  2020-11-12 09:51:07

5  |  1         | 3         |  2020-11-13 09:51:07

6  |  1         | 1         |  2021-11-11 09:51:07

7  |  1         | 2         |  2021-11-12 09:51:07

I would like to see
category 1: last appointment was 2021-11-11
category 2: last appointment was 2021-11-12
category 3: last appointment was 2020-11-13
Comment: please share create table and sample data insert script. Also, output expected from sample data. Try with GROUP BY  start, project_id, category_id
Comment: I tried to insert a demo database, i hope this can clear up things :)
Comment: I can not reproduce. Please look: https://sqlize.online/?phpses=null&sqlses=fb8ac3e06a84c05b9cf92dc8bd822d94&php_version=null&sql_version=mysql57
Comment: You are very right, it was my mistake. I echoed "start", but not the Max(start), this was very stupid.
Comment: Thank you for your help, it was a very stupid mistake. I'm very sorry!
Answer: I was asking for scripts like this
CREATE TABLE time_entries (id int, project_id int,  category_id int, start datetime);

INSERT INTO time_entries VALUES(1 , 1 , 1 , '2019-11-11 09:51:07'),(2 , 1 , 2 , '2019-11-12 09:51:07'), (5 , 1 , 3 , '2019-11-13 09:51:07'), (3 , 1 , 1 , '2020-11-11 09:51:07'), (4 , 1 , 2 , '2020-11-12 09:51:07'), (5 , 1 , 3 , '2020-11-13 09:51:07'), (6 , 1 , 1 , '2021-11-11 09:51:07'), (7 , 1 , 2 , '2021-11-12 09:51:07');

Now, solution to your problem. you can add date check in where clause.
SELECT T1.id, T1.start, T1.project_id, T1.category_id, T2.start
FROM time_entries T1
INNER JOIN(
    SELECT  category_id, MAX(start)start
    FROM time_entries
    WHERE project_id=1
    GROUP BY  category_id
)T2 ON T1.category_id=T2.category_id AND T1.start = T2.Start
ORDER BY T1.category_id

Answer: Please try below query
SELECT project_id, category_id, MAX(start) as last_datetime FROM time_entries WHERE project_id = '$project_id' GROUP BY category_id

Comment: if we add ID field in select statement then this will not work.


await messages, get a channel by the given ID

Question: So i want that my poll command asks for the channel and the question in a conversation, but i haven't figured out how to get the channel when the user only gives the ID, i have figured out that i have to use .content but i still don't know how to implement it.
My code:
run: async(message, client, args) => {

  // Channel where the poll should take palce
  await message.channel.send(`Please provide a channel where the poll should take place or cancel this command with "cancel"!`)
  const response1 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
  const channel = response1.first().mentions.channels.first() || response1.content.guild.channels.cache.get()

  if (!channel) {
    return message.channel.send(`You did not mention or provide the ID of a channel where the poll should take place!`)
  }

  // Channel where the poll should take palce
  await message.channel.send(`Please provide a question for the poll!`)
  const response2 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
  let question = response2.first();

  if (!question) {
    return message.channel.send(`You did not specify your question!`)
  }

  const Embed = new Discord.MessageEmbed()
    .setTitle(`New poll!`)
    .setDescription(`${question}`)
    .setFooter(`${message.author.username} created this poll.`)
    .setColor(`0x0099ff`)
  let msg = await client.channels.cache.get(channel.id).send(Embed)
  await msg.react("")
  await msg.react("")
}

And it is this line: response1.content.guild.channels.cache.get() that is writte wrong by me but idk what i have to change/where to add the .content so that it works.
Would be nice if someone can help me.
My message event for the args:
module.exports = async (client, message) => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    if (!message.guild) return;
    if (!message.member) message.member = await message.guild.fetchMember(message);
    const args = message.content.slice(prefix.length).split(/ +/g);
    const cmd = args.shift().toLowerCase();
    if (cmd.length == 0) return;
    let command = client.commands.get(cmd)
    if (!command) command = client.commands.get(client.aliases.get(cmd));
    if (command) {
        try {
            command.run(message, client, args)
        } catch (error) {
            console.error(error);
            message.reply('There was an error trying to execute that command!');
        }
    }
}

Answer: You need the content to grab the id, but I assume that's already handled by the code that generates the args parameter.
To get the guild you can use Message.guild, and then just Guild.channels.cache.get()
That means that your code would look like this:
const channel = response1.first().mentions.channels.first()
  || response1.first().guild.channels.cache.get(args[0]) // Assuming args[0] is your id

Comment: thanks but "channels" is undefined like that, that is what the error says, and yeah the content is handled by the args, i forgot that
Comment: response1.first().guild.channels.cache.get()     that was recommended by someone but it then goes to the if(!channel)
Comment: I've updated my answer (I forgot to add `.first()` after `response1`. About your problem: please see that its not just .`get()`, but you need to pass in the id (`.get(args[0]`)
Comment: i now have it ecactly like your comment (with your edit) but it still doesn't accepts the Id (it is a real channel Id, i made sure) and goes straight to the if (!channel), really annoys me...
Comment: You should try doing some debugging to make sure that the arguments are picked up correctly...
Try using `console.log` to see if `response1`, `args[0]` and the two statements you use for `channel` are correct.
Comment: so when i log response1 it logs/shows all the methods but when i log channel then it logs /shows "undefined" but what is undefined?
Comment: And what about `args[0]`?
Comment: also undefined, so i guess i have to look into my message event, that i will add to this question
Comment: Yeah, try using `console.log` there too to see where exactly is the problem, since it's certainly in that part of the code. Try logging the `args` array and, if the ID is present in just after the definition, try to see where it disappears
Comment: whyever the the args are undefined the message.content is undefined idk anymore/what have i done wrong ... frustrating
Comment: i think i will jus only go with the mention
Comment: `message.content` should **NEVER** be undefined, this shows that you have a problem in your command handler. I know this can be frustrating, but if you don't try to solve this your bot will continue to have this problem, and it's not a little one. This however is beyond the topic of this question, so I advise you look carefully at that and open other questions if needed. If, after you fixed this issue, you still need to do this command, you can look at my answer, which should be valid
Answer: So i went around it with making another constructor means:
const ID = client.channels.cache.get(response1.first().content)
const channel = response1.first().mentions.channels.first() || ID
It works fine now


On the determination of residue

Question: I need your help on the following.
(1)First we are to find the residue of $\frac{x^s}{s}$ at $s=0$. Since $s=0$ is the pole of order 1, so we get
Res$(\frac{x^s}{s},s=0)=\frac{1}{2\pi i}\int_{C_1^+(0)} \frac{f(s)}{s}ds$ where $f(s)=x^s$. In other words,
Res$(\frac{x^s}{s},s=0)=f(0)=1$. Please tell me if I made any mistake on it or not.
(2)My next problem is to find the poles of $\frac{\zeta(s-1)}{\zeta(s)}\frac{x^s}{s}$.
Well I got stuck at this. My instructor is saying it has a pole of order 1 at 2 but I could not understand what he is trying to say, with due respect. May be I heard him wrong or may be I am missing something. Please help me out. I am not getting confidence.
Answer: One may recall that the Riemann zeta function admits a pole at $u=1$ and we have

$$
\zeta(u) =\frac1{u-1}+\gamma+\mathcal{O}(u-1), \quad u \to1,
$$

where $\gamma=0.5772...$ is the Euler Mascheroni constant.
Setting $u:=s-1$, which gives $u-1=s-2$ and $u \to 1$ as $s \to 2$, we may then write
$$
\begin{align}
\frac{\zeta(s-1)}{\zeta(s)}\frac{x^s}{s}&=\frac{\zeta(u)}{\zeta(u+1)}\frac{x^{u+1}}{u+1}\\\\
&=\frac{x^{u+1}}{u+1}\frac{\frac1{u-1}+\gamma+\mathcal{O}(u-1)}{\zeta((u-1)+2)}\\\\
&=\frac{x^{2+(u-1)}}{2+(u-1)}\frac{\frac1{u-1}+\gamma+\mathcal{O}(u-1)}{\zeta(2)+\mathcal{O}(u-1)}\\\\
&=\frac{x^{2+(u-1)}}{2+(u-1)}\frac{\frac1{u-1}+\gamma+\mathcal{O}(u-1)}{\zeta(2)+\mathcal{O}(u-1)}\\\\
&=\frac{x^2}{2\:\zeta(2)}\frac{1}{(u-1)}+\mathcal{O}(1)\\\\
&=\frac{3x^2}{\pi^2}\frac{1}{s-2}+\mathcal{O}(1)\\\\
\end{align}
$$ where we have used $\displaystyle \zeta(2)=\frac{\pi^2}6$, and the pole is of order $1$ with a residue equal to $\displaystyle \frac{3x^2}{\pi^2}$.
Comment: That was really nice explanation indeed. Can you please help me on the following http://math.stackexchange.com/questions/1283214/what-is-the-inner-steps-here
Comment: @Anjan3 Thanks! I've answered it too.
Comment: Please help me to understand the step # 4 and 5. How they are performed ?

On the determination of residue


Generate an apk failed on React native

Question: When i'm build my React native project using this command
gradlew bundleRelease

Give a big error on Task :app:mergeReleaseResources
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:mergeReleaseResources'.

[drawable-hdpi-v4/node_modules_reactnavigation_stack_src_views_assets_backicon] C:\Users\victo\Documents\git\melhor\app-user\android\app\src\main\res\drawable-hdpi\node_modules_reactnavigation_stack_src_views_assets_backicon.png  [drawable-hdpi-v4/node_modules_reactnavigation_stack_src_views_assets_backicon] C:\Users\victo\Documents\git\melhor\app-user\android\app\build\generated\res\react\release\drawable-hdpi\node_modules_reactnavigation_stack_src_views_assets_backicon.png: Error: Duplicate resources
  [drawable-mdpi-v4/node_modules_reactnavigation_stack_src_views_assets_backicon] C:\Users\victo\Documents\git\melhor\app-user\android\app\src\main\res\drawable-mdpi\node_modules_reactnavigation_stack_src_views_assets_backicon.png  [drawable-mdpi-v4/node_modules_reactnavigation_stack_src_views_assets_backicon] C:\Users\victo\Documents\git\melhor\app-user\android\app\build\generated\res\react\release\drawable-mdpi\node_modules_reactnavigation_stack_src_views_assets_backicon.png: Error: Duplicate resources
  [drawable-mdpi-v4/node_modules_reactnavigation_stack_src_views_assets_backiconmask] C:\Users\victo\Documents\git\melhor\app-user\android\app\src\main\res\drawable-mdpi\node_modules_reactnavigation_stack_src_views_assets_backiconmask.png  [drawable-mdpi-v4/node_modules_reactnavigation_stack_src_views_assets_backiconmask] C:\Users\victo\Documents\git\melhor\app-user\android\app\build\generated\res\react\release\drawable-mdpi\node_modules_reactnavigation_stack_src_views_assets_backiconmask.png: Error: Duplicate resources
  [drawable-mdpi-v4/src_assets_address_emptyaddress] C:\Users\victo\Documents\git\melhor\app-user\android\app\src\main\res\drawable-mdpi\src_assets_address_emptyaddress.png    [drawable-mdpi-v4/src_assets_address_emptyaddress] C:\Users\victo\Documents\git\melhor\app-user\android\app\build\generated\res\react\release\drawable-mdpi\src_assets_address_emptyaddress.png: Error: Duplicate resources
  [drawable-mdpi-v4/src_assets_address_faildelivery] C:\Users\victo\Documents\git\melhor\app-user\android\app\src\main\res\drawable-mdpi\src_assets_address_faildelivery.png    [drawable-mdpi-v4/src_assets_address_faildelivery] C:\Users\victo\Documents\git\melhor\app-user\android\app\build\generated\res\react\release\drawable-mdpi\src_assets_address_faildelivery.png: Error: Duplicate resources
  [drawable-mdpi-v4/src_assets_brands_bayer] C:\Users\victo\Documents\git\melhor\app-user\android\app\src\main\res\drawable-mdpi\src_assets_brands_bayer.png    [drawable-mdpi-v4/src_assets_brands_bayer]

This error is larger and have more "Duplicated resources".
I see that is a problem with the images i use inside the aplication But that is only one image with those names with the name inside the app, why is "duplicated"?
and other assets like "node_modules_reactnavigation_stack_src_views_assets_backicon" assets on react navigation that i dont have control.
Answer: This problem ocurrs because the project builded duplicates files.
To resolve it, you need delete the files inside of res folder.
Delete drawable folder and raw folder.
Your project directory will be like that:
Comment: Tanks, i had already solved doing this, but thanks!
Comment: +1 This is just a quick fix. The next questions are "why it's creating duplicate data every time" and "how to solve it"?

Generate an apk failed on React native


Angular directives: Is there a better way than '$timeout' to get info about DOM elements created in "compile" function?

Question: I created a custom <select> dropdown element using a directive, and one aspect of its behavior is automatic sizing, where the element is fit to one of three sizes depending on how wide its widest option is.
However, because the options are populated in the compile function based on data from the controller, I cannot determine the width of the option list until later, in a pre- or post-link function, but the only way I've been able to check the width was by waiting for the list to be populated through nesting my post-link function in a 0-ms timer.
This was the solution I found through various resources, but I feel there might be a more elegant way?
Here is my directive's code:
    .directive('slidingSelect', function($timeout) {
        return {
            restrict: 'E',

            compile: function(element, attrs) {
                var selecting = attrs.selecting;
                // ng-repeated options come from selecting attr
                var dropDownList = $('

');
                dropDownList.append('
{{item.name}}
');
                element.append(dropDownList);

                element.click(
                    // Function to slide up/down the list as necessary
                    function() {
                        /* omitted */
                });

                // With compile defined, can return post-link functions
                return function(scope, element, attrs) {
                        $timeout(function() {
                            var list = element.find('.sliding-select-list');
                            var options = list.children();

                            // Find natural width of list, set data-width, then list to match
                            var listWidth = list.width();
                            element.attr('data-width', (listWidth>180?'large':(listWidth>100?'medium':'small')));

                            // Hide list
                            element.addClass('closed');
                        }, 0);
                    };
                 }
              };

Comment: why do you use compile? why not link? in any case, take a look [here](http://stackoverflow.com/questions/12240639/angularjs-how-can-i-run-a-directive-after-the-dom-has-finished-rendering)
Comment: compile bc it allows me to add the options using an ng-repeat directive and have it compile that to display on the rendered page
Answer: When javascript is running, the browser pauses rendering of the DOM until the javascript execution has completed. So when you add the element to the DOM, the browser knows that it has new items to draw and that it has to repaint the screen, but it can't do it until the javascript finishes executing.
What setting a timeout does is it lets the browser regain control before calling any functions registered for timeouts, thus allowing it to repaint the screen and calculate the width of your options list before it runs your timeout code.
I'm sure it's much more complicated than how I have described, but thinking about it this way has helped me to better understand how javascript and the DOM work together.
I can't think of a better way of doing what you are trying to do. That's how I have always done it.


Nest.js inject service into plain typescript class

Question: I have a NestJS App and I have a Class where the app generates multiple instances from. Inside that class I need to access a service method but I dont know how to inject a service into a plain class.
This is the service I want to use inside the class "Stream"

import { Injectable } from '@nestjs/common';
import * as technicalindicators from 'technicalindicators';
import { CandleIndex } from 'src/utils/CandleIndex';
import * as ccxt from 'ccxt';
@Injectable()
export class AnalysisService {
  async RSI(ohlcv: ccxt.OHLCV[], period: number) {
    const close = ohlcv.map((candle) => candle[CandleIndex.CLOSE]);
    const result = technicalindicators.rsi({ values: close, period: period });
    return result;
  }
}

import { AnalysisService } from './analysis.service';
import { Module } from '@nestjs/common';

@Module({
  imports: [],
  controllers: [],
  providers: [AnalysisService],
  exports: [AnalysisService],
})
export class AnalysisModule {}

Here is the class I want to get access to the analysis service. The class is a normal typescript class, its not part of any module.

export class Stream {
  private exchange: ccxt.Exchange;
  private market: ccxt.Market;
  private timeframe: string;
  private ohlcv_cache: ccxt.OHLCV[];
  private createdAt: Date;
  private stream;
  @Inject(AnalysisService)
  private readonly analysisService: AnalysisService;
  constructor(exchange: ccxt.Exchange, market: ccxt.Market, timeframe: string) {
    this.exchange = exchange;
    this.market = market;
    this.timeframe = timeframe;
    this.createdAt = new Date();
    this.initialize();
    console.log(this.analysisService);
  }
  }

When I do this and call a method of the analysis service inside of the Stream class, analysisService is undefined.
Comment: How does this `Stream` class get created?
Comment: I have a service which has an Array of Streams[] Class. Inside the same service they get created by pushing new Instances of Stream into the array.
Comment: So you call `new Stream()` yourself?
Comment: yes. They are just simple es6 classes I create by /POST requests which then get stored inside stream.service class inside an array of Type Stream[]
Answer: As you're calling new Stream() yourself, Nest will do no injection for you. You'd need to either pass the AnalysisService instance yourself, or you'd need to create a setter for that property before running any methods that need the AnalysisService.
Comment: Yeah. Because if you handle the creation of the class, Nest won't do any injection for you
Comment: you basically make the Constructor of Stream have a param of analysisService and then on Object creation pass the service instance to the Object constructor?


Alguém pode me ajudar com a integração do angular 5 com firebase real time?

Question: Preciso integrar o banco de dados do firebase a uma aplicação em angular 5. Peguei o código gerado pelo firebase, criei um arquivo firebase config e coloquei ele lá fiz a importação no módulo. Estou com dificuldade de escrever no banco e buscar as informações de lá. Alguém poderia me ajudar?
Comment: cara tira a imagem das chaves, se nao qualquer um vai poder ver.
Comment: As chaves são ilustrativas
Comment: https://github.com/angular/angularfire2
Answer: enviroment.ts
export const environment = {
  production: false,
  firebase: //copiar o objeto de configuração.
  apiUrl: suaUrl
};

app.module.ts
import { AppComponent } from './app.component
import { AppRoutingModule } from './app-routing.module';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth } from 'angularfire2/auth';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),,
  ],
  providers: [AngularFireAuth],//se quiser usar a auth do firebase
  bootstrap: [AppComponent]
})
export class AppModule { }


jquery validation plug-in remote function with codeigniter

Question: I'm using the jquery validation plug-in. I don't have any idea how the remote function works.
So far this is my code:
functions.js
user: {
            required: true,
            remote: {
                url: "http://localhost/iTransaction/home/checkUser",
                type: "post",
                async: false
            }
        }

Controller:
    function checkUser(){
    return $this->itransaction_model->checkUser();
}

Model:
function checkUser(){
    $this->db->select("user");
    $query = $this->db->get("member");
    $row = $query->row();
    echo $row->user;

    if($row->user == $this->input->post("user")){
        return true;
    }else{
        return false;
    }
}

The remote is supposed to check whether the username already exists or not.
Answer: From the docs:

The serverside resource is called via jQuery.ajax (XMLHttpRequest) and gets a key/value pair corresponding to the name of the validated element and its value as a GET parameter. The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

Your controller method returns a boolean value in a way that does not makes any sense to the library and is interpreted as false. You need to return the validation result in a different way:
function checkUser(){
    $this->output->set_content_type('application/json');
    $this->output->set_header('Cache-Control: no-cache, must-revalidate');
    $this->output->set_header('Expires: '.date('r', time()+(86400*365)));

    $output = json_encode(
        $this->itransaction_model->checkUser() ? true : 'That username is alreay in use'
    );

    $this->output->set_output($output);
}

Comment: It didn't work. It didn't even run the function. I placed some pop-ups and echoes in it to check. Do you know what's wrong, sir?
Comment: Which function are you talking about? The `checkUser` method in the controller? Try checking your requests in the browser using Firebug (or a similar tool) and see if the proper URL is being called. Also, check CI routes for any overrides (just in case)


Inject javascript into HtmlDocument in C#

Question: Is there a simple way to inject a javascript into a HtmlDocument object without using PhantomJS?
Is there such a method in HtmlAgilityPack.HtmlDocument class?
Any advice is apreciated,
Thank you!
Answer: You can create the element with
<code>HtmlElement script = doc.CreateElement("SCRIPT");
</code>
Set the value with the script that you want and then attach to the Header of the HtmlDocument
Answer: You can inject a script tag (with script in it) in a HTMLDocument.
You still need something to execute the javascript though. If you want your c# code to somehow evaluate the result of the javascript - especially if you are doing dom manipulation - then PhantomJS is probably the best way to go as it's a headless browser that you can run without user interaction and interface.
The short answer is yes, but i think what you want is not possible without an engine that knows both javascript and the html dom. There are alternatives to PhantomJS like http://slimerjs.org/ so my cheeky answer is still yes ;)
Hint: Don't be afraid to run PhantomJS or the like.
Comment: Yes I am doing DOM manipulation. I think I will try to use PhantomJS after all. Can you please provide an example of how I can get a javascript variable in C#?
Comment: For example I have a variable var price = productPrice();  I want to evaluate the function productPrice() and get the price in C# using PhantomJS.
Comment: Are you doing testing on a website, or are you trying to automate a task, or are you perhaps 'scraping' a site? I think context will help a lot here.


MVC3 and IIS6 RedirectToAction redirects to wrong URL

Question: This is weird.  I have a virtual directory setup for an MVC3 application called (for the sake of this question) I'll call 'foobar'.  The full URL to this site is:
http://localservername.domainname.com/foobar

In my logon form, I have the following line that is supposed to redirect to the main/home page of the application after logon.
return RedirectToAction("Index", "Home");

However, when this line executes, I get redirected to the wrong location - so instead of redirecting me back to:
http://localservername.domainname.com/foobar

I get redirected back to:
http://localservername.domainname.com/foobar/foobar

Which of course gets me a resource not found error.  Also, any links in my views seem to do the opposite - for example if I have a link like this:
Widget Search

I would expect the following URL to open:
http://localservername.domainname.com/foobar/WidgetSearch

Instead, I get redirected to
http://localservername.domainname.com/WidgetSearch

Which of course also gets me a resource not found error.  I've never encountered this type of behaviour before.  I've gone over the basic and advanced settings and created a new application pool.  Fiddler also shows me that (of course) the URLs listed above return 404 responses.
Any suggestions would be greatly appreciated.
Thanks!
Comment: If you have any routes other than the default route, please show them.
Comment: did you manage to solve ur first problem? I am facing the same issue. My route is  routes.MapRoute(
             "BarCodeScan", //Route name
             "{controller}/{action}/BarCode/{*BarCode}", // URL with parameters
             new { controller = "Home", action = "ProcessBinBatchBarCode", BarCode = string.Empty } // Parameter defaults
            );
Answer: The first issue shouldn't really happen. RedirectToAction should take into account your virtual directory path (you haven't hard coded an extra /foobar into your route setup have you?).
The second problem has nothing to do with MVC, it's just that you're using a vanilla HTML link that is pointing directly to the root of the server (that's what saying /blah implies). You should change your link to use one of the MVC helper methods to generate the URL instead to make sure it adds the virtual directory for you. So one of the following (the first is probably the best way, unless you need to heavily customise what the anchor tag looks like):
@Html.ActionLink("Widget Search", "Index", "WidgetSearch")

or
Widget Search

Comment: Thanks for the answer, I'll update the links this evening.  But that first one has me stumped - a real head scratcher.
Comment: @AndyEvans - Only thing I can think of is your route setup... What do your route registrations look like? Do you have anything other than the normal default `"{controller}/{action}/{id}"` one? There should be no mention of your virtual directory `/foobar` anywhere in your code as that should be being handled by the underlying framework.
Comment: You are correct.  No where in my project does /foobar appear.  This is aggravating.