问:
Math in highcharts to change units?
I've been making a website to display weather data: http://erbweather.com/US.html?station=NYC&year=2016.  Currently all of my temperature data is in Fahrenheit, but I'd like to add an option to show it in Celsius.  The data is read from a text file.  Is there a way to covert the values to Celsius after reading it from the file?  The lines to read the data look like this:

```<code>$.get("data/QCLCD/" + year + "/daily_data_" + station_code + "_" + year + ".csv", function(csv) {
  $('#container1').highcharts({
    chart: {
      type: 'line',
      zoomType: 'xy'
    },
    data: {
      csv: csv,
      startColumn:0,
      endColumn: 4
    },
    ...
</code>```

The equation I want to add is a simple one: TEMP_C = (5/9)*(TEMP_F-32).  Any ideas how to implement this?

答:
You could achieve expected effect using update() functions on Series and Chart objects for example.

First, you should calculate all values from Farenheit to Celcius. I used for that code below:

```<code>const oldSeriesData = []
const fToCel = temp => Math.round( (temp - 32)/1.8 ) // Converting function

// Create array with old data values
chart.series.forEach(series => { oldSeriesData.push(series.userOptions.data) })

// Create array with calculated values
const newSeriesData = oldSeriesData.map( subarray =>  {
    return subarray.map( elem => {
        return [elem[0], (elem[1] !== null) ? fToCel(elem[1]) : null]
    });
})
</code>```

If you will calculate new values, then you've to update a chart series data with those new calculated values, so I did that using update():

```<code>// Update series with Celsius data values
chart.series.forEach((series, i) => {
    series.update({
        data: newSeriesData[i]
    })
})

// Update yAxis title and tooltip suffix
chart.update({
    yAxis: {
        title: {
            text: 'Temperature (\xB0C)'
        }
    },
    tooltip: {
        valueSuffix: '\xB0C'
    }
})
</code>```

Here is the complete JSFiddle live example

API Reference:
Chart.update()
Series.update()

Title: Math in highcharts to change units?

Body:
I've been making a website to display weather data: http://erbweather.com/US.html?station=NYC&year=2016.  Currently all of my temperature data is in Fahrenheit, but I'd like to add an option to show it in Celsius.  The data is read from a text file.  Is there a way to covert the values to Celsius after reading it from the file?  The lines to read the data look like this:

$.get("data/QCLCD/" + year + "/daily_data_" + station_code + "_" + year + ".csv", function(csv) {
  $('#container1').highcharts({
    chart: {
      type: 'line',
      zoomType: 'xy'
    },
    data: {
      csv: csv,
      startColumn:0,
      endColumn: 4
    },
    ...

The equation I want to add is a simple one: TEMP_C = (5/9)*(TEMP_F-32).  Any ideas how to implement this?

Body:
You could achieve expected effect using update() functions on Series and Chart objects for example.

First, you should calculate all values from Farenheit to Celcius. I used for that code below:

const oldSeriesData = []
const fToCel = temp => Math.round( (temp - 32)/1.8 ) // Converting function

// Create array with old data values
chart.series.forEach(series => { oldSeriesData.push(series.userOptions.data) })

// Create array with calculated values
const newSeriesData = oldSeriesData.map( subarray =>  {
    return subarray.map( elem => {
        return [elem[0], (elem[1] !== null) ? fToCel(elem[1]) : null]
    });
})

If you will calculate new values, then you've to update a chart series data with those new calculated values, so I did that using update():

// Update series with Celsius data values
chart.series.forEach((series, i) => {
    series.update({
        data: newSeriesData[i]
    })
})

// Update yAxis title and tooltip suffix
chart.update({
    yAxis: {
        title: {
            text: 'Temperature (\xB0C)'
        }
    },
    tooltip: {
        valueSuffix: '\xB0C'
    }
})

Here is the complete JSFiddle live example

API Reference:
Chart.update()
Series.update()


来源: stackexchange

问:
Correct type annotation for a view function which takes no argument
I'm currently learning Elm and I know this a noob question but I can't seem to properly type annotate this function which return just a pure div.

```<code>header =
    div [] [ text "Hello" ]
</code>```

What would be accurate way to type annotate this function?

答:
The correct annotation is this:

```<code>header : Html msg
header =
    div [] [ text "Hello" ]
</code>```

In the future, you can use the Elm REPL to find the type of something:

> import Html exposing (..)
> div [] [ text "Hello" ]
{ type = "node", tag = "div", facts = {}, children = {}, namespace = <internal structure>, descendantsCount = 0 }
: Html.Html msg
```

The part after the colon specifies the signature, which is Html.Html msg

ContentLicense: CC BY-SA 3.0

Body:
I'm currently learning Elm and I know this a noob question but I can't seem to properly type annotate this function which return just a pure div.

header =
    div [] [ text "Hello" ]

What would be accurate way to type annotate this function?

Body:
The correct annotation is this:

header : Html msg
header =
    div [] [ text "Hello" ]

In the future, you can use the Elm REPL to find the type of something:

> import Html exposing (..)
> div [] [ text "Hello" ]
{ type = "node", tag = "div", facts = {}, children = {}, namespace = <internal structure>, descendantsCount = 0 }
: Html.Html msg

The part after the colon specifies the signature, which is Html.Html msg


问:
Set Recipient ID or Email in URL Parameters with PayPal
I have tried (with success) the adaptative payments and was wondering if it was possible to "bypass" it by directly specifying recipient information in a /myaccount/transfer/send link in URL parameters like so

https://www.paypal.com/myaccount/transfer/send/external?recipient=john.doe%40gmail.com&amount=25&currencyCode=EUR

I want, as a third party, to be able to initiate a payment towards a given e-mail address (not mine) from any Paypal user

答:
The following URL worked for me:</p>

```<code>https://www.paypal.com/myaccount/transfer/buy/external?recipient=john.doe%40gmail.com&amount=25&currencyCode=EUR
</code>```

Body:
The following URL worked for me:

https://www.paypal.com/myaccount/transfer/buy/external?recipient=john.doe%40gmail.com&amount=25&currencyCode=EUR


问:
router.navigate changes url but the view won't change
i am having trouble when using router.navigate on a click listener for a marker in googlemaps. The page url changes to the desired path but the outlet wont change the view.

loadEquipos(locacion:  Locacion) {
    for (let i = 0; i < this.equipos.length; i++) {
      if(this.equipos[i].idLocacion === locacion.id) {
        const marker = new google.maps.Marker({
          position: new google.maps.LatLng(this.equipos[i].mapData.center.lat, this.equipos[i].mapData.center.lng),
          map: map,
          label: {
            color: 'black',
            fontWeight: 'bold',
            text: this.equipos[i].nombre,
          },
          idEquipo: this.equipos[i].id
        });
        google.maps.event.addListener(marker, 'click',() => {
          this.router.navigate(['/tanque', marker.idEquipo]);
        });
      }
    }
  }```
</div>
</div>
</p>

<p>Thats the method in witch the event listener is added.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>RouterModule.forRoot([
      {
        path: 'admLocaciones',
        component: AdmLocacionesComponent
      },
      {
        path: '',
        redirectTo: '/inicio',
        pathMatch: 'full'
      },
      {
        path: 'inicio',
        component: InicioComponent
      },
      {
        path: 'buscarLocacion/:id',
        component: BuscarLocacionComponent
      },
      {
        path: 'editarLocacion/:id',
        component: EditarLocacionComponent
      },
      {
        path: 'nuevaLocacion',
        component: NuevaLocacionComponent
      },
      {
        path: 'admRegiones',
        component: AdmRegionesComponent
      },
      {
        path: 'locacion/:id',
        component: LocacionComponent
      },
      {
        path: 'tableroTanque',
        component: TableroTanqueComponent
      },
      {
        path: 'tanque/:id',
        component: TanqueComponent
      }
    ])
  ],</code>```

and those are my paths, any other navigation works perfectly fine inside the app.

Thanks for your help.

答: Somehow adding de listener inside a Google.Maps.Listener made the navigate method run outside the ngzone. Solved it using the Ngzone.run and running the navigate that way. </p>

Body:
i am having trouble when using router.navigate on a click listener for a marker in googlemaps. The page url changes to the desired path but the outlet wont change the view.

loadEquipos(locacion:  Locacion) {
    for (let i = 0; i < this.equipos.length; i++) {
      if(this.equipos[i].idLocacion === locacion.id) {
        const marker = new google.maps.Marker({
          position: new google.maps.LatLng(this.equipos[i].mapData.center.lat, this.equipos[i].mapData.center.lng),
          map: map,
          label: {
            color: 'black',
            fontWeight: 'bold',
            text: this.equipos[i].nombre,
          },
          idEquipo: this.equipos[i].id
        });
        google.maps.event.addListener(marker, 'click',() => {
          this.router.navigate(['/tanque', marker.idEquipo]);
        });
      }
    }
  }

Thats the method in witch the event listener is added.

RouterModule.forRoot([
      {
        path: 'admLocaciones',
        component: AdmLocacionesComponent
      },
      {
        path: '',
        redirectTo: '/inicio',
        pathMatch: 'full'
      },
      {
        path: 'inicio',
        component: InicioComponent
      },
      {
        path: 'buscarLocacion/:id',
        component: BuscarLocacionComponent
      },
      {
        path: 'editarLocacion/:id',
        component: EditarLocacionComponent
      },
      {
        path: 'nuevaLocacion',
        component: NuevaLocacionComponent
      },
      {
        path: 'admRegiones',
        component: AdmRegionesComponent
      },
      {
        path: 'locacion/:id',
        component: LocacionComponent
      },
      {
        path: 'tableroTanque',
        component: TableroTanqueComponent
      },
      {
        path: 'tanque/:id',
        component: TanqueComponent
      }
    ])
  ],

and those are my paths, any other navigation works perfectly fine inside the app.

Thanks for your help.


问:
soap:ServerThese policy alternatives can not be satisfied in Jmeter
I get the following error in the Jmeter response

```<code>        ?xml version="1.0" encoding="UTF-8"?>soap:ServerThese policy alternatives can not be satisfied:

 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} AsymmetricBinding: Received Timestamp does not match the requirements
 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} InitiatorToken
 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} RecipientToken
 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} IncludeTimestamp: Received Timestamp does not match the requirements
</code>```

when I run the Jmeter request. The same works well using SOAP UI.

I see the request doesnt have the time stamp ID in an encrypted form.

Below is the request I triggerred using JMeter

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="http://soap.abz.com/">
   <soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
                      xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
           <wsu:Timestamp>
               <wsu:Created>${CREATED}</wsu:Created>
               <wsu:Expires>${EXPIRES}</wsu:Expires>
           </wsu:Timestamp>
       </wsse:Security>
         </soapenv:Header>
   <soapenv:Body>
      <soap:validate>
         <!--Optional:-->
         <check>1007 1940 0000 0100 27</check>
      </soap:validate>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

Server logs:

```<code>Dec 07, 2017 2:57:30 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://soap.abz.com/}ServiceImplService#{http://soap.abz.com/}validate has thrown exception, unwinding now
org.apache.cxf.ws.policy.PolicyException: These policy alternatives can not be satisfied:
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}AsymmetricBinding: Received Timestamp does not match the requirements
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}InitiatorToken
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}RecipientToken
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}IncludeTimestamp: Received Timestamp does not match the requirements
        at org.apache.cxf.ws.policy.AssertionInfoMap.checkEffectivePolicy(AssertionInfoMap.java:167)
        at org.apache.cxf.ws.policy.PolicyVerificationInInterceptor.handle(PolicyVerificationInInterceptor.java:101)
        at org.apache.cxf.ws.policy.AbstractPolicyInterceptor.handleMessage(AbstractPolicyInterceptor.java:44)
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
        at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:218)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:198)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:243)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:163)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:219)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
</code>```

I use the SOAP message encrypter and signer key as preprocessor in Jmeter for the SOAP request in JMeter 3.3

Any help over here is much appreciated.

答:
The message indicates that the timestamp format is wrong. If your application is indeed using WS protocol based security without any specific username and password, the below solution might work. I think you need to correct the format for your timestamp. In my case, I just used to regular HTTP sampler with the entire SOAP protocol message without using SOAP specific pre/post processors

http://abeykoon.blogspot.com/2015/03/jmeter-test-for-secured-proxy-service.html

As per the above link, you need to send the header along with username and password if your application expects that but with the correct timestamp. Code to generate one is also given in the above link. Please note that you can pass an empty value for NOnce which I did for my application. Otherwise, you need to ensure that the corresponding jboss jar file is placed under the \lib\ext directory of your JMeter installation

```<code>   <soapenv:Header>
        <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsu:Timestamp wsu:Id="TS-05CB7D74E166EF0AB614268666650771109">
                <wsu:Created>${#timeC#}</wsu:Created>
                <wsu:Expires>${#timeE#}</wsu:Expires>
            </wsu:Timestamp>
            <wsse:UsernameToken wsu:Id="UsernameToken-05CB7D74E166EF0AB614268666650771108">
                <wsse:Username>${username}</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">${password}</wsse:Password>
                <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">${#nonce#}</wsse:Nonce>
                <wsu:Created>${#UTtimeC#}</wsu:Created>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>

import org.apache.jmeter.protocol.http.sampler.WebServiceSampler;
import org.apache.jmeter.protocol.http.sampler.SoapSampler;
import org.jboss.ws.extensions.security.nonce.DefaultNonceGenerator; //(jbosswscore.jar)
import org.jboss.util.Base64; //this class is called inside the DefaultNonceGenerator class (jbosscommon.jar)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

//generating NONCE
DefaultNonceGenerator nonce_Gen = new DefaultNonceGenerator();
String nonce = nonce_Gen.generateNonce();
//generating relevant Timestamps
long ctmilli = System.currentTimeMillis(); // current time in milliseconds
SimpleDateFormat dformat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");    // timestamp format with nonce
SimpleDateFormat dformat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");  //timestamp format for usernametoken, with miliseconds
Date dtime = new Date();
dformat1.setTimeZone(TimeZone.getTimeZone("UTC"));
dtime.setTime(ctmilli);  // current time
String timeCreated = dformat1.format(dtime); // timestamp created in format1
String uttimeCreated = dformat2.format(dtime); // timestamp created in format2
dtime.setTime(ctmilli+2000); // setting the timeout  for 2seconds, change the timeout as required
String timeExpire = dformat1.format(dtime);  // expiration timestamp in format1
vars.put("#timeC#",timeCreated);
vars.put("#timeE#",timeExpire);
vars.put("#nonce#",nonce);
vars.put("#UTtimeC#",uttimeCreated);
</code>```

Body:
I get the following error in the Jmeter response

        ?xml version="1.0" encoding="UTF-8"?>soap:ServerThese policy alternatives can not be satisfied:

 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} AsymmetricBinding: Received Timestamp does not match the requirements
 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} InitiatorToken
 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} RecipientToken
 {http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702} IncludeTimestamp: Received Timestamp does not match the requirements

when I run the Jmeter request. The same works well using SOAP UI.

I see the request doesnt have the time stamp ID in an encrypted form.

Below is the request I triggerred using JMeter

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="http://soap.abz.com/">
   <soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
                      xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
           <wsu:Timestamp>
               <wsu:Created>${CREATED}</wsu:Created>
               <wsu:Expires>${EXPIRES}</wsu:Expires>
           </wsu:Timestamp>
       </wsse:Security>
         </soapenv:Header>
   <soapenv:Body>
      <soap:validate>

         <check>1007 1940 0000 0100 27</check>
      </soap:validate>
   </soapenv:Body>
</soapenv:Envelope>

Server logs:

Dec 07, 2017 2:57:30 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://soap.abz.com/}ServiceImplService#{http://soap.abz.com/}validate has thrown exception, unwinding now
org.apache.cxf.ws.policy.PolicyException: These policy alternatives can not be satisfied:
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}AsymmetricBinding: Received Timestamp does not match the requirements
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}InitiatorToken
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}RecipientToken
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}IncludeTimestamp: Received Timestamp does not match the requirements
        at org.apache.cxf.ws.policy.AssertionInfoMap.checkEffectivePolicy(AssertionInfoMap.java:167)
        at org.apache.cxf.ws.policy.PolicyVerificationInInterceptor.handle(PolicyVerificationInInterceptor.java:101)
        at org.apache.cxf.ws.policy.AbstractPolicyInterceptor.handleMessage(AbstractPolicyInterceptor.java:44)
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
        at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:218)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:198)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:243)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:163)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:219)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

I use the SOAP message encrypter and signer key as preprocessor in Jmeter for the SOAP request in JMeter 3.3

Any help over here is much appreciated.

Body:
The message indicates that the timestamp format is wrong. If your application is indeed using WS protocol based security without any specific username and password, the below solution might work. I think you need to correct the format for your timestamp. In my case, I just used to regular HTTP sampler with the entire SOAP protocol message without using SOAP specific pre/post processors

http://abeykoon.blogspot.com/2015/03/jmeter-test-for-secured-proxy-service.html

As per the above link, you need to send the header along with username and password if your application expects that but with the correct timestamp. Code to generate one is also given in the above link. Please note that you can pass an empty value for NOnce which I did for my application. Otherwise, you need to ensure that the corresponding jboss jar file is placed under the \lib\ext directory of your JMeter installation

   <soapenv:Header>
        <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsu:Timestamp wsu:Id="TS-05CB7D74E166EF0AB614268666650771109">
                <wsu:Created>${#timeC#}</wsu:Created>
                <wsu:Expires>${#timeE#}</wsu:Expires>
            </wsu:Timestamp>
            <wsse:UsernameToken wsu:Id="UsernameToken-05CB7D74E166EF0AB614268666650771108">
                <wsse:Username>${username}</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">${password}</wsse:Password>
                <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">${#nonce#}</wsse:Nonce>
                <wsu:Created>${#UTtimeC#}</wsu:Created>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>

import org.apache.jmeter.protocol.http.sampler.WebServiceSampler;
import org.apache.jmeter.protocol.http.sampler.SoapSampler;
import org.jboss.ws.extensions.security.nonce.DefaultNonceGenerator; //(jbosswscore.jar)
import org.jboss.util.Base64; //this class is called inside the DefaultNonceGenerator class (jbosscommon.jar)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

//generating NONCE
DefaultNonceGenerator nonce_Gen = new DefaultNonceGenerator();
String nonce = nonce_Gen.generateNonce();
//generating relevant Timestamps
long ctmilli = System.currentTimeMillis(); // current time in milliseconds
SimpleDateFormat dformat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");    // timestamp format with nonce
SimpleDateFormat dformat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");  //timestamp format for usernametoken, with miliseconds
Date dtime = new Date();
dformat1.setTimeZone(TimeZone.getTimeZone("UTC"));
dtime.setTime(ctmilli);  // current time
String timeCreated = dformat1.format(dtime); // timestamp created in format1
String uttimeCreated = dformat2.format(dtime); // timestamp created in format2
dtime.setTime(ctmilli+2000); // setting the timeout  for 2seconds, change the timeout as required
String timeExpire = dformat1.format(dtime);  // expiration timestamp in format1
vars.put("#timeC#",timeCreated);
vars.put("#timeE#",timeExpire);
vars.put("#nonce#",nonce);
vars.put("#UTtimeC#",uttimeCreated);


问:
Postgres “missing FROM-clause entry” error on query
I am trying to use this query in Postgres:

```<code>SELECT ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;
</code>```

I get this error:

ERROR:  column reference "ean" is ambiguous
LINE 1: SELECT ean, count(nif)

If I change the query to:

```<code>SELECT P.ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;
</code>```

Appears another error:

ERROR:  missing FROM-clause entry for table "p"
LINE 4: GROUP BY P.ean

Those two tables are created this way:

```<code>create table produto (
ean char(13) not null unique,
design varchar(255) not null,
categoria varchar(80) not null,
forn_primario char(9) not null,
data date not null,
constraint ean_size CHECK (Length(ean)=13),
constraint pk_produto primary key(ean),
constraint fk_produto_categoria foreign key(categoria) references categoria(nome) ON DELETE CASCADE,
constraint fk_produto_fornecedor foreign key(forn_primario) references fornecedor(nif));

create table fornece_sec (
nif char(9) not null,
ean char(13) not null,
constraint pk_fornece_sec primary key(nif, ean),
constraint fk_fornece_sec_fornecedor foreign key(nif) references fornecedor(nif),
constraint fk_fornece_sec_produto foreign key(ean) references produto(ean) ON DELETE CASCADE);
</code>```

Note: the attribute nif in fornece_sec table is the same type of the attribute forn_primario in the product table.

答:
This probably has nothing to do with it, but maybe try explicitly declaring the INNER JOIN:</p>

```<code>SELECT P.ean, count(nif)
FROM produto P
INNER JOIN fornece_sec F ON P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;
</code>```

Body:
I am trying to use this query in Postgres:

SELECT ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;

I get this error:

ERROR:  column reference "ean" is ambiguous
LINE 1: SELECT ean, count(nif)

If I change the query to:

SELECT P.ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;

Appears another error:

ERROR:  missing FROM-clause entry for table "p"
LINE 4: GROUP BY P.ean

Those two tables are created this way:

create table produto (
ean char(13) not null unique,
design varchar(255) not null,
categoria varchar(80) not null,
forn_primario char(9) not null,
data date not null,
constraint ean_size CHECK (Length(ean)=13),
constraint pk_produto primary key(ean),
constraint fk_produto_categoria foreign key(categoria) references categoria(nome) ON DELETE CASCADE,
constraint fk_produto_fornecedor foreign key(forn_primario) references fornecedor(nif));

create table fornece_sec (
nif char(9) not null,
ean char(13) not null,
constraint pk_fornece_sec primary key(nif, ean),
constraint fk_fornece_sec_fornecedor foreign key(nif) references fornecedor(nif),
constraint fk_fornece_sec_produto foreign key(ean) references produto(ean) ON DELETE CASCADE);

Note: the attribute nif in fornece_sec table is the same type of the attribute forn_primario in the product table.

Body:
This probably has nothing to do with it, but maybe try explicitly declaring the INNER JOIN:

SELECT P.ean, count(nif)
FROM produto P
INNER JOIN fornece_sec F ON P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;


问:
Scrape data using beautiful soup
While Scraping data using beautifulSoap
In this html code there are two
 tag but I want to extract data from second
 tag. So how can i do this?
and so on if there are multiples of same tag and i want to extract data from any one of the tag how can I do that?

Code:

```<code><h2>Video Instructions For Making Soft Idlis</h2>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/p3uF3LK5734?rel=0" allowfullscreen="allowfullscreen"></iframe>
</div>

<h2>Recipe For Making Soft Idlis</h2>
</code>```

I had thought of extracting data using keyword instead of using tag.
for example I can use
 tag and use keyword Recipe to find the data of second
 tag

答:
If you know what h2 you want based on order, you simply need to use that as an index to the return of .findAll method:

```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup('''<h2>Video Instructions For Making Soft Idlis</h2>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/p3uF3LK5734?rel=0" allowfullscreen="allowfullscreen"></iframe>
</div>

<h2>Recipe For Making Soft Idlis</h2>''', "html.parser")
</code>```

```<code>>>> soup.findAll("h2")[1]
<h2>Recipe For Making Soft Idlis</h2>
</code>```

Title: Scrape data using beautiful soup

Body:
While Scraping data using beautifulSoap
In this html code there are two
 tag but I want to extract data from second
 tag. So how can i do this?
and so on if there are multiples of same tag and i want to extract data from any one of the tag how can I do that?

Code:

Video Instructions For Making Soft Idlis

Recipe For Making Soft Idlis

I had thought of extracting data using keyword instead of using tag.
for example I can use
 tag and use keyword Recipe to find the data of second
 tag

Body:
If you know what h2 you want based on order, you simply need to use that as an index to the return of .findAll method:

from bs4 import BeautifulSoup
soup = BeautifulSoup('''<h2>Video Instructions For Making Soft Idlis</h2>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/p3uF3LK5734?rel=0" allowfullscreen="allowfullscreen"></iframe>
</div>

<h2>Recipe For Making Soft Idlis</h2>''', "html.parser")

>>> soup.findAll("h2")[1]
<h2>Recipe For Making Soft Idlis</h2>


问:
Reinforced.Typings cannot handle attributes on properties
I have an ASP.NET Core project using ASP.NET Identity. Some classes cannot be exported since their properties contain attributes from System.ComponentModel.DataAnnotations. If I ignore such properties, everything works fine.

Example class:

```<code>public class LoginViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}
</code>```

Since I don't want to strip out these attributes, what is the recommended course of action?

```<code>[assembly: TsGlobal(
    CamelCaseForMethods = true,
    CamelCaseForProperties = true,
    GenerateDocumentation = true,
    UseModules = true,
    DiscardNamespacesWhenUsingModules = true)]

namespace X
{
    public static class ReinforcedTypingsConfiguration
    {
        public static void Configure(ConfigurationBuilder builder)
        {
            builder
                .ExportAsInterface<LoginViewModel>()
                .AutoI(false)
                .WithProperty(x => x.RememberMe)
                ;
        }
    }
}
</code>```

Other than that, it seems that UseModules does the opposite of what I want it to do. When set to true, the generated ts file doesn't contain any modules. When set to false, I get module in my ts files.

Also, when dividing types among files, I get strange folder names on mac that contain \ for every . in my namespace. Can I just flatten out the structure? And completely ignore backend namespaces?

In the above configuration (and I use file splitting) I get the annoying error message error MSB3552: Resource file "**/*.resx" cannot be found..

答: Upgrade to 1.4.2 to fix this issue.</p>

Body:
I have an ASP.NET Core project using ASP.NET Identity. Some classes cannot be exported since their properties contain attributes from System.ComponentModel.DataAnnotations. If I ignore such properties, everything works fine.

Example class:

public class LoginViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

Since I don't want to strip out these attributes, what is the recommended course of action?

[assembly: TsGlobal(
    CamelCaseForMethods = true,
    CamelCaseForProperties = true,
    GenerateDocumentation = true,
    UseModules = true,
    DiscardNamespacesWhenUsingModules = true)]

namespace X
{
    public static class ReinforcedTypingsConfiguration
    {
        public static void Configure(ConfigurationBuilder builder)
        {
            builder
                .ExportAsInterface<LoginViewModel>()
                .AutoI(false)
                .WithProperty(x => x.RememberMe)
                ;
        }
    }
}

Other than that, it seems that UseModules does the opposite of what I want it to do. When set to true, the generated ts file doesn't contain any modules. When set to false, I get module in my ts files.

Also, when dividing types among files, I get strange folder names on mac that contain \ for every . in my namespace. Can I just flatten out the structure? And completely ignore backend namespaces?

In the above configuration (and I use file splitting) I get the annoying error message error MSB3552: Resource file "**/*.resx" cannot be found..

Body: Upgrade to 1.4.2 to fix this issue.


答:
It seems tough to do this without some looping:</p>

```<code>linked = df.Linked_To.str.split(';')

def pull_name(iden):
    try:
        return df[df.ID == int(iden)].Name.iat[0]
    except:
        return str(None)

res = linked.apply(lambda ids: '; '.join([pull_name(i) for i in ids]))

print(res)
0         Name B; Name C
1     Name A; None; None
2    Name B; Name A; ...
Name: Linked_To, dtype: object
</code>```

Title: Compare and update pandas dataframe column lists with strings from another column

Body:
I have a pandas data frame:

+--------+---------+------+----------------+
|  Name  | Address |  ID  |   Linked_To    |
+--------+---------+------+----------------+
| Name A | ABC     | 1233 | 1234;1235      |
| Name B | DEF     | 1234 | 1233;1236;1237 |
| Name C | GHI     | 1235 | 1234;1233;2589 |
+--------+---------+------+----------------+

Some of the ID's in the Linked_To column are records, under the Name column. I can create a dictionary and pass the data in the Linked_To column as a list. However, I am unsure how to proceed. Ideally I would like to see something like:

+--------+---------+------+-------------------------+
|  Name  | Address |  Id  |        Linked To        |
+--------+---------+------+-------------------------+
| Name A | ABC     | 1233 | Name B;Name C           |
| Name B | DEF     | 1234 | Name A;Name D; Name E   |
| Name C | HIJ     | 1235 | Name B;Name A; None     |
+--------+---------+------+-------------------------+

Body:
It seems tough to do this without some looping:

linked = df.Linked_To.str.split(';')

def pull_name(iden):
    try:
        return df[df.ID == int(iden)].Name.iat[0]
    except:
        return str(None)

res = linked.apply(lambda ids: '; '.join([pull_name(i) for i in ids]))

print(res)
0         Name B; Name C
1     Name A; None; None
2    Name B; Name A; ...
Name: Linked_To, dtype: object


问:
c, get rid of uninitialized warning error
In function my_func1() in c the 1st thing I do is call another function  my_func2(), which always sets the pointer. GCC warns me that the pointer might not be set. How can I get rid of the warning?

Here's some simplified code to merely demonstrate it.

```<code>int bla;
void my_func2(int *ptr) {
   ptr = &bla;
}
void my_func1() {
    int *ptr;
    //ptr=0;
    my_func2(ptr);
}
</code>```

If the line ptr=0 is uncommented, then the warning goes away. I don't want to set the variable because it does nothing since the my_func2() sets it.

The gcc warning message is

warning: 'ptr' is used uninitialized in this function
  [-Wuninitialized]

Any help would be greatly appreciated.

答:
I think what you're trying to do is this:</p>

```<code>int bla;
void my_func2(int **pp) {
    *pp = &bla;
}
void my_func1() {
    int *ptr;
    my_func2(&ptr);
    ...
}
</code>```

Body:
In function my_func1() in c the 1st thing I do is call another function  my_func2(), which always sets the pointer. GCC warns me that the pointer might not be set. How can I get rid of the warning?

Here's some simplified code to merely demonstrate it.

int bla;
void my_func2(int *ptr) {
   ptr = &bla;
}
void my_func1() {
    int *ptr;
    //ptr=0;
    my_func2(ptr);
}

If the line ptr=0 is uncommented, then the warning goes away. I don't want to set the variable because it does nothing since the my_func2() sets it.

The gcc warning message is

warning: 'ptr' is used uninitialized in this function
  [-Wuninitialized]

Any help would be greatly appreciated.

Body:
I think what you're trying to do is this:

int bla;
void my_func2(int **pp) {
    *pp = &bla;
}
void my_func1() {
    int *ptr;
    my_func2(&ptr);
    ...
}


问:
jsoup posting Java
Im struggling getting java submitting POST requests over HTTPS

Code used is here

```
     try{
        Response res = Jsoup.connect(LOGIN_URL)
    .data("username", "blah", "password", "blah")

    .method(Method.POST)
  .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .execute();
        System.out.println(res.body());
        System.out.println("Code " +res.statusCode());

        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
```

and also this

```
Document doc = Jsoup.connect(LOGIN_URL)
  .data("username", "blah")
  .data("password", "blah")
  .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0")
        .header("Content-type", "application/x-www-form-urlencoded")
         .method(Method.POST)
  .timeout(3000)
  .post();
            ```

Where LOGIN_URL = https://xxx.com/Login?val=login

When used over HTTP it seems to work, HTTPS it doesnt, But doesnt throw any exceptions

How can I POST over HTTPS

Edit:

seems there is a 302 redirect involved when the server gets a POST over HTTPS  (which doesnt happen over http) How can I use jsoup to store the cookie sent with the 302 to the next page ?

答:
Here is what you can try...

```<code>import org.jsoup.Connection;

Connection.Response res = null;
    try {
        res = Jsoup
                .connect("your-first-page-link")
                .data("username", "blah", "password", "blah")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Now save all your cookies and make a request to the other page you want.

```<code>//Saving Cookies
cookies = res.cookies();
</code>```

Making a request to another page.

```<code>try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}
</code>```

Comment if further help needed.

Title: jsoup posting Java

Body:
Im struggling getting java submitting POST requests over HTTPS

Code used is here

     try{
        Response res = Jsoup.connect(LOGIN_URL)
    .data("username", "blah", "password", "blah")

    .method(Method.POST)
  .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .execute();
        System.out.println(res.body());
        System.out.println("Code " +res.statusCode());

        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }

and also this

Document doc = Jsoup.connect(LOGIN_URL)
  .data("username", "blah")
  .data("password", "blah")
  .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0")
        .header("Content-type", "application/x-www-form-urlencoded")
         .method(Method.POST)
  .timeout(3000)
  .post();

Where LOGIN_URL = https://xxx.com/Login?val=login

When used over HTTP it seems to work, HTTPS it doesnt, But doesnt throw any exceptions

How can I POST over HTTPS

Edit:

seems there is a 302 redirect involved when the server gets a POST over HTTPS  (which doesnt happen over http) How can I use jsoup to store the cookie sent with the 302 to the next page ?

Body:
Here is what you can try...

import org.jsoup.Connection;

Connection.Response res = null;
    try {
        res = Jsoup
                .connect("your-first-page-link")
                .data("username", "blah", "password", "blah")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }

Now save all your cookies and make a request to the other page you want.

//Saving Cookies
cookies = res.cookies();

Making a request to another page.

try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}

Comment if further help needed.


问:
How to sort an array of structs in ColdFusion
I have an array of structs in ColdFusion. I'd like to sort this array based on one of the attributes in the structs. How can I achieve this?  I've found the StructSort function, but it takes a structure and I have an array.

If this is not possible purely in ColdFusion, is it possible in Java somehow (maybe using Arrays.sort(Object[], Comparator))?

答:
I don't have the reputation points to comment on @mikest34 post above but @russ was correct that this callback no longer works the way it was explained.

It was Adam Cameron who discovered that when using arraySort with a callback, it no longer requires a True/False response but rather:

-1, if first parameter is "smaller" than second parameter

   0, if first parameter is equal to second parameter

   1, first parameter is "bigger" than second parameter

So the correct callback is:

```<code>ArraySort(yourArrayOfStructs, function(a,b) {
    return compare(a.struct_date, b.struct_date);
});
</code>```

Testing and working in CF2016

ContentLicense: CC BY-SA 2.5

Body:
I don't have the reputation points to comment on @mikest34 post above but @russ was correct that this callback no longer works the way it was explained.

It was Adam Cameron who discovered that when using arraySort with a callback, it no longer requires a True/False response but rather:

-1, if first parameter is "smaller" than second parameter

   0, if first parameter is equal to second parameter

   1, first parameter is "bigger" than second parameter

So the correct callback is:

ArraySort(yourArrayOfStructs, function(a,b) {
    return compare(a.struct_date, b.struct_date);
});

Testing and working in CF2016


问:
Mapping some HashMap Key/Values to a POJO
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

```<code>    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));
</code>```

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

```<code>Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)
</code>```

To ignore the errors I tried :

```<code>mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
</code>```

But then nothing got mapped.

答: Try using Dozer mapping to map HashMap to POJO.You can look at MapStruct too.</p>

Body:
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)

To ignore the errors I tried :

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

But then nothing got mapped.


问:
Distinct values from regexp_replace in oracle not working
I am trying to extract distinct values from pipe delimited text. When i searched in google i got the below expression but it is not working in some cases

EG:

```<code>   select regexp_replace('Bhal|Bhal|Bhal|Bhaloo|Bhaloo|Bhaloo|Bhaloooo|Bhaloooo|Bhaloooo|Baker|Baker|Baker', '([^|]+)(\|\1)+', '\1') from dual;
</code>```

Expected Output:

Bhal|Bhaloo|Bhaloooo|Baker

I have tried some combinations in the regex but it is not working for me.

Any help would be appreciated.

答:
I combined a few ideas, and now use a function that returns a distinct sorted list of unique values from a string.  This method doesn't require the list to be already sorted as the other answers do.

This SQL could also be utilized within a sub-select rather than a function.

```<code>    function UniqueList (cList varchar2, cNewItem varchar2 default '', cDelim varchar2 default ',')
return varchar2
is
  cResult varchar2(4000);
begin
  select distinct listagg(txt,cDelim) WITHIN GROUP (ORDER BY txt) OVER () into cResult
    from (
    select distinct * from (
        SELECT REGEXP_SUBSTR (cList||cDelim||cNewItem,'[^'||cDelim||']+',1,LEVEL) TXT
                 FROM DUAL
           CONNECT BY REGEXP_SUBSTR (cList||cDelim||cNewItem,'[^'||cDelim||']+',1,LEVEL)
                 IS NOT NULL
        )
   );
    return cResult;
end;
</code>```

Body:
I am trying to extract distinct values from pipe delimited text. When i searched in google i got the below expression but it is not working in some cases

EG:

   select regexp_replace('Bhal|Bhal|Bhal|Bhaloo|Bhaloo|Bhaloo|Bhaloooo|Bhaloooo|Bhaloooo|Baker|Baker|Baker', '([^|]+)(\|\1)+', '\1') from dual;

Expected Output:

Bhal|Bhaloo|Bhaloooo|Baker

I have tried some combinations in the regex but it is not working for me.

Any help would be appreciated.

Body:
I combined a few ideas, and now use a function that returns a distinct sorted list of unique values from a string.  This method doesn't require the list to be already sorted as the other answers do.

This SQL could also be utilized within a sub-select rather than a function.

    function UniqueList (cList varchar2, cNewItem varchar2 default '', cDelim varchar2 default ',')
return varchar2
is
  cResult varchar2(4000);
begin
  select distinct listagg(txt,cDelim) WITHIN GROUP (ORDER BY txt) OVER () into cResult
    from (
    select distinct * from (
        SELECT REGEXP_SUBSTR (cList||cDelim||cNewItem,'[^'||cDelim||']+',1,LEVEL) TXT
                 FROM DUAL
           CONNECT BY REGEXP_SUBSTR (cList||cDelim||cNewItem,'[^'||cDelim||']+',1,LEVEL)
                 IS NOT NULL
        )
   );
    return cResult;
end;


问:
How to decrease vertical space between two cell in collectionview?

How to decrease the vertical space between two cell in collectionview?

答:
The method is: minimumLineSpacingForSectionAt.
Just specify in it the spacing value that you want to have. Doc description:

For a vertically scrolling grid, this value represents the minimum spacing between successive rows.

For changing the minimum spacing between items in the same row, (I suppose you need this too) use: minimumInteritemSpacingForSectionAt.


问:
mysqli conversion PDO
How can I turn this to PDO? I tried, but I don't know how.
It was MySQLi at first and I tried to turn it to PDO and so, that was the result:

```<code><?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $conn-> prepare("SELECT * FROM resident WHERE '$username' = ? AND '$password' = ?");
    //mysqli_stmt_bind_param($sql, "ss", $username, $password);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt ->execute();
    mysqli_stmt_store_result($sql);
    $stmt-> BindParam($sql, $name, $username, $password);
    $response=array();
    $response["succes"] = false;
    while (mysqli_stmt_fetch($sql)) {
        $response["success"] = true;
        $response["name"]= $name;
    }
    echo json_encode ($response);
?>
</code>```

答:
You can use answer of tadman, also this:

```<code>$stmt = $conn-> prepare("SELECT `id` FROM resident WHERE username=:username AND password=:password");

$stmt->execute(array(':username' => $username, ':password' => $password);
</code>```

And hash your passwords.
You can learn some basics of pdo Here, W3schools

Title: mysqli conversion PDO

Body:
How can I turn this to PDO? I tried, but I don't know how.
It was MySQLi at first and I tried to turn it to PDO and so, that was the result:

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $conn-> prepare("SELECT * FROM resident WHERE '$username' = ? AND '$password' = ?");
    //mysqli_stmt_bind_param($sql, "ss", $username, $password);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt ->execute();
    mysqli_stmt_store_result($sql);
    $stmt-> BindParam($sql, $name, $username, $password);
    $response=array();
    $response["succes"] = false;
    while (mysqli_stmt_fetch($sql)) {
        $response["success"] = true;
        $response["name"]= $name;
    }
    echo json_encode ($response);
?>

Body:
You can use answer of tadman, also this:

$stmt = $conn-> prepare("SELECT `id` FROM resident WHERE username=:username AND password=:password");

$stmt->execute(array(':username' => $username, ':password' => $password);

And hash your passwords.
You can learn some basics of pdo Here, W3schools


问:
Reading in TSP file Python
I need to figure out how to read in this data of the filename 'berlin52.tsp'

This is the format I'm using

```<code>NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0
</code>```

And this is my current code

```<code># Open input file
infile = open('berlin52.tsp', 'r')

# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()

# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
    x,y = infile.readline().strip().split()[1:]
    nodelist.append([int(x), int(y)])

# Close input file
infile.close()
</code>```

The code should read in the file, output out a list of tours with the values "1, 2, 3..." and more while the x and y values are stored to be calculated for distances. It can collect the headers, at least. The problem arises when creating a list of nodes.

This is the error I get though

```<code>ValueError: invalid literal for int() with base 10: '565.0'
</code>```

What am I doing wrong here?

答:
You are feeding the string "565.0" into nodelist.append([int(x), int(y)]).
It is telling you it doesn't like that because that string is not an integer. The .0 at the end makes it a float.

So if you change that to nodelist.append([float(x), float(y)]), as just one possible solution, then you'll see that your problem goes away.

Alternatively, you can try removing or separating the '.0' from your string input.

Title: Reading in TSP file Python

Body:
I need to figure out how to read in this data of the filename 'berlin52.tsp'

This is the format I'm using

NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0

And this is my current code

# Open input file
infile = open('berlin52.tsp', 'r')

# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()

# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
    x,y = infile.readline().strip().split()[1:]
    nodelist.append([int(x), int(y)])

# Close input file
infile.close()

The code should read in the file, output out a list of tours with the values "1, 2, 3..." and more while the x and y values are stored to be calculated for distances. It can collect the headers, at least. The problem arises when creating a list of nodes.

This is the error I get though

ValueError: invalid literal for int() with base 10: '565.0'

What am I doing wrong here?


问:
Button content closes on click of next button
I have two buttons which store tables, but I want the table to disappear on click of the second button and show the contents of the second button immediately after clicking it, rather than clicking it twice (first click hides the table from the previous button, next clicks opens table from the current button).I don't seem to know how to do that.

function myFunction2() {
  var x = document.getElementById("displaytable");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" id="Button1" value="Button1" onClick="myFunction2()" />
<div id="displaytable" style="display:none">
  <table id="displaytable" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

<input type="button" id="Button2" value="Button1" onClick="myFunction2()" />
<div id="displaytable" style="display:none">
  <table id="displaytable" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">36</td>
      <td align="center">45</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div></code>```

答:
You used an id in multiple times that is completely wrong, you most use classes instead or use unique ids. BTW you used an id 4th times and this will puts you in trouble when you are using JS and its not standard coding.

JS:

```<code>function myFunction1() {
    var x = document.getElementById("displaytable1");
    var y = document.getElementById("displaytable2");
    y.style.display = "none";

    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

function myFunction2() {
    var x = document.getElementById("displaytable2");
    var y = document.getElementById("displaytable1");
    y.style.display = "none";
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</code>```

HTML:

```<code><input type="button" id="Button1" value="Button1" onClick="myFunction1()"/>
<div id="displaytable1" style="display:none">
    <table id="displaytable1_1" width="100%" cellpadding="1" cellspacing="0" border="3">
        <tr align="center">
            <td class="lbl">column1</td>
            <td class="lbl">column2</td>
            <td class="lbl">column3</td>
        </tr>
        <tr>
            <td align="center">1</td>
            <td align="center">2</td>
            <td align="center">33</td>
        </tr>
        <tr>
            <td align="center">4</td>
            <td align="center">5</td>
            <td align="center">6</td>
        </tr>
    </table>
</div>

<input type="button" id="Button2" value="Button1" onClick="myFunction2()"/>
<div id="displaytable2" style="display:none">
    <table id="displaytable2_2" width="100%" cellpadding="1" cellspacing="0" border="3">
      <tr align="center">
          <td class="lbl">column1</td>
          <td class="lbl">column2</td>
          <td class="lbl">column3</td>
      </tr>
      <tr>
          <td align="center">36</td>
          <td align="center">45</td>
          <td align="center">33</td>
      </tr>
      <tr>
          <td align="center">4</td>
          <td align="center">5</td>
          <td align="center">6</td>
      </tr>
    </table>
</div>
</code>```

P.S: i made changes as follow:
convert id from displaytable to displaytable1 for first div element and
convert id from displaytable to displaytable2 for secound div that contains second table, and gave each table an unique ids. Regards

Body:
I have two buttons which store tables, but I want the table to disappear on click of the second button and show the contents of the second button immediately after clicking it, rather than clicking it twice (first click hides the table from the previous button, next clicks opens table from the current button).I don't seem to know how to do that.

function myFunction2() {
  var x = document.getElementById("displaytable");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<input type="button" id="Button1" value="Button1" onClick="myFunction2()" />

      column1
      column2
      column3

      1
      2
      33

      4
      5
      6

<input type="button" id="Button2" value="Button1" onClick="myFunction2()" />

      column1
      column2
      column3

      36
      45
      33

      4
      5
      6

Body:
You used an id in multiple times that is completely wrong, you most use classes instead or use unique ids. BTW you used an id 4th times and this will puts you in trouble when you are using JS and its not standard coding.

JS:

function myFunction1() {
    var x = document.getElementById("displaytable1");
    var y = document.getElementById("displaytable2");
    y.style.display = "none";

    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

function myFunction2() {
    var x = document.getElementById("displaytable2");
    var y = document.getElementById("displaytable1");
    y.style.display = "none";
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

HTML:

<input type="button" id="Button1" value="Button1" onClick="myFunction1()"/>
<div id="displaytable1" style="display:none">
    <table id="displaytable1_1" width="100%" cellpadding="1" cellspacing="0" border="3">
        <tr align="center">
            <td class="lbl">column1</td>
            <td class="lbl">column2</td>
            <td class="lbl">column3</td>
        </tr>
        <tr>
            <td align="center">1</td>
            <td align="center">2</td>
            <td align="center">33</td>
        </tr>
        <tr>
            <td align="center">4</td>
            <td align="center">5</td>
            <td align="center">6</td>
        </tr>
    </table>
</div>

<input type="button" id="Button2" value="Button1" onClick="myFunction2()"/>
<div id="displaytable2" style="display:none">
    <table id="displaytable2_2" width="100%" cellpadding="1" cellspacing="0" border="3">
      <tr align="center">
          <td class="lbl">column1</td>
          <td class="lbl">column2</td>
          <td class="lbl">column3</td>
      </tr>
      <tr>
          <td align="center">36</td>
          <td align="center">45</td>
          <td align="center">33</td>
      </tr>
      <tr>
          <td align="center">4</td>
          <td align="center">5</td>
          <td align="center">6</td>
      </tr>
    </table>
</div>

P.S: i made changes as follow:
convert id from displaytable to displaytable1 for first div element and
convert id from displaytable to displaytable2 for secound div that contains second table, and gave each table an unique ids. Regards


问:
Create user registration using stored procedure in mysql
I am trying to create user registration stored procedure in mysql but I am getting an error.

Query

```<code>CREATE PROCEDURE `test`.`sp_register`(fullname VARCHAR(50), Mob VARCHAR(10), Email VARCHAR(50), pass VARCHAR(255))
BEGIN
DECLARE s VARCHAR(20);
IF EXISTS(SELECT id FROM users WHERE email = Email)
    THEN SET s = 'User already exists';
ELSE
    INSERT INTO users(`name`,`mobile`,`email`,`password`,`created_at`)
        VALUES(fullname,Mob, Email, pass,CURRENT_TIMESTAMP())
        THEN SET s =  "User Registered";
END IF;

END
</code>```

答:
As Matthew answered, you don't need the "THEN".
You're also missing a semi-colon after the INSERT.</p>

Body:
I am trying to create user registration stored procedure in mysql but I am getting an error.

Query

CREATE PROCEDURE `test`.`sp_register`(fullname VARCHAR(50), Mob VARCHAR(10), Email VARCHAR(50), pass VARCHAR(255))
BEGIN
DECLARE s VARCHAR(20);
IF EXISTS(SELECT id FROM users WHERE email = Email)
    THEN SET s = 'User already exists';
ELSE
    INSERT INTO users(`name`,`mobile`,`email`,`password`,`created_at`)
        VALUES(fullname,Mob, Email, pass,CURRENT_TIMESTAMP())
        THEN SET s =  "User Registered";
END IF;

END


问:
Layout Problem in Android
I am fairly new to android and am having some problems with a layout. Below is an approximation of what I want the layout to look like. (I would like the list to be below the screen at first so that the user can scroll down to see it.) However my code as it currently stands makes all of the views on the left only take up a quarter the screen instead of half, as depicted, even though I have all widths set to fill_parent.

Also, this layout seems to mess up the coordinate system on my custom view. Normally this wouldn't be much of an issue, but in this case I am using that view to draw a picture and the picture ends up in the wrong place. Does anybody have any idea how to resolve these issues?

Here is my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TableRow>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow>
 <TextView android:text="Resultant Force" android:id="@+id/resForceTitle"
  android:textSize="25dip" android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:padding="3dip"
  android:gravity="center" android:layout_span="2" />
</TableRow>
<TableRow>
 <TextView android:id="@+id/magText" android:text="Magnitude (N) ="
  android:textSize="15dip" android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:padding="3dip"
  android:gravity="center_vertical" android:layout_span="2" />
</TableRow>
<TableRow>
 <EditText android:id="@+id/magnitude" android:inputType="numberDecimal"
  android:layout_width="fill_parent" android:padding="3dip"
  android:layout_height="fill_parent" android:layout_span="2" />
</TableRow>
<TableRow>
 <TextView android:id="@+id/dirText" android:text="Angle (deg) ="
  android:layout_width="fill_parent" android:layout_height="fill_parent"
  android:textSize="15dip" android:gravity="center_vertical"
  android:layout_span="2" />
</TableRow>
<TableRow>
 <EditText android:id="@+id/direction" android:inputType="numberDecimal"
  android:layout_height="fill_parent" android:padding="3dip"
  android:layout_width="fill_parent" android:layout_span="2" />
</TableRow>
<TableRow>
 <Button android:id="@+id/pushButton" android:text="Add Force"
  android:layout_height="fill_parent" android:padding="3dip"
  android:layout_width="fill_parent" />
 <Button android:id="@+id/clearButton" android:text="Clear"
  android:layout_height="fill_parent" android:padding="3dip"
  android:layout_width="fill_parent" />
</TableRow>
</TableLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<android.physicsengine.AxisDrawing
 android:id="@+id/image" android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</FrameLayout>
</TableRow>
</TableLayout>
<ListView android:id="@android:id/list" android:layout_height="wrap_content"
android:padding="3dip" android:layout_width="fill_parent"
android:clickable="false" />
<TextView android:id="@android:id/empty" android:text="Add Forces to List Components"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:textSize="15dip" android:gravity="center_vertical" />
</LinearLayout>
</code>```

答:
That is because you have entered android:layout_span="2" in your EditTexts. If you remove these all behaves more normally.

Then you can control left side by setting the width of EditText to 200dp for example...
You can also use right margin of EditText to control the left column.

As for the coordinates in the custom view canvas they start from 0,0 in the top-right corner of it.

Title: Layout Problem in Android

Body:
I am fairly new to android and am having some problems with a layout. Below is an approximation of what I want the layout to look like. (I would like the list to be below the screen at first so that the user can scroll down to see it.) However my code as it currently stands makes all of the views on the left only take up a quarter the screen instead of half, as depicted, even though I have all widths set to fill_parent.

Also, this layout seems to mess up the coordinate system on my custom view. Normally this wouldn't be much of an issue, but in this case I am using that view to draw a picture and the picture ends up in the wrong place. Does anybody have any idea how to resolve these issues?

Here is my code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TableRow>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow>
 <TextView android:text="Resultant Force" android:id="@+id/resForceTitle"
  android:textSize="25dip" android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:padding="3dip"
  android:gravity="center" android:layout_span="2" />
</TableRow>
<TableRow>
 <TextView android:id="@+id/magText" android:text="Magnitude (N) ="
  android:textSize="15dip" android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:padding="3dip"
  android:gravity="center_vertical" android:layout_span="2" />
</TableRow>
<TableRow>
 <EditText android:id="@+id/magnitude" android:inputType="numberDecimal"
  android:layout_width="fill_parent" android:padding="3dip"
  android:layout_height="fill_parent" android:layout_span="2" />
</TableRow>
<TableRow>
 <TextView android:id="@+id/dirText" android:text="Angle (deg) ="
  android:layout_width="fill_parent" android:layout_height="fill_parent"
  android:textSize="15dip" android:gravity="center_vertical"
  android:layout_span="2" />
</TableRow>
<TableRow>
 <EditText android:id="@+id/direction" android:inputType="numberDecimal"
  android:layout_height="fill_parent" android:padding="3dip"
  android:layout_width="fill_parent" android:layout_span="2" />
</TableRow>
<TableRow>
 <Button android:id="@+id/pushButton" android:text="Add Force"
  android:layout_height="fill_parent" android:padding="3dip"
  android:layout_width="fill_parent" />
 <Button android:id="@+id/clearButton" android:text="Clear"
  android:layout_height="fill_parent" android:padding="3dip"
  android:layout_width="fill_parent" />
</TableRow>
</TableLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<android.physicsengine.AxisDrawing
 android:id="@+id/image" android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</FrameLayout>
</TableRow>
</TableLayout>
<ListView android:id="@android:id/list" android:layout_height="wrap_content"
android:padding="3dip" android:layout_width="fill_parent"
android:clickable="false" />
<TextView android:id="@android:id/empty" android:text="Add Forces to List Components"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:textSize="15dip" android:gravity="center_vertical" />
</LinearLayout>


问:
How to pass current date to a text field using Angular JS in protractor
I have a field to add date which is of type text.It has the following HTML code

```<code><input class="form-control ng-pristine ng-invalid ng-touched" type="text" id="date" name="date">
</code>```

Could someone help me to send current date to the field.I tried many ways,but when I am using Date() to get current date,it is not even executing the test

答:
This seems to work just fine for me. I just used the google search page to check it. I put a 10 second sleep in so I can visually check it was working.</p>

```<code>it('should do something', () => {
    var d = new Date().toString();

    browser.waitForAngularEnabled(false);
    browser.get('http://google.com');
    const searchTextBox = browser.element(by.id('lst-ib'));

    searchTextBox.sendKeys(d);

    //expect(something).toBe(true);
});
</code>```

Body:
I have a field to add date which is of type text.It has the following HTML code

<input class="form-control ng-pristine ng-invalid ng-touched" type="text" id="date" name="date">

Could someone help me to send current date to the field.I tried many ways,but when I am using Date() to get current date,it is not even executing the test

Body:
This seems to work just fine for me. I just used the google search page to check it. I put a 10 second sleep in so I can visually check it was working.

it('should do something', () => {
    var d = new Date().toString();

    browser.waitForAngularEnabled(false);
    browser.get('http://google.com');
    const searchTextBox = browser.element(by.id('lst-ib'));

    searchTextBox.sendKeys(d);

    //expect(something).toBe(true);
});


答:
Hi I don't know if it's a good Idea but you could convert your map to a json and convert json to your POJO.
You could use gson.</p>

Title: Mapping some HashMap Key/Values to a POJO


问:
Creation of formatted DataFrame and then adding data line by line
I have a continuous stream of data coming in so I want to define the DataFrame before hand so that I don't have tell pandas to format data or set index

So I want to create a DataFrame like

```<code>df = pd.DataFrame(columns=["timestamp","stockname","price","volume"])
</code>```

but I want to tell Pandas that index of data should be timestamp and that the format would be

```<code>"%Y-%m-%d %H:%M:%S:%f"
</code>```

and one this it set, then I would read through file and pass data to the DataFrame initialized

I get data in variables like these populated every time in loop like

```<code>for line in filehandle:

    timestamp, stockname, price, volume = fetch(line)

    here I want to update the "df"
</code>```

this update would go on while I would keep using the copy of

```<code>df
</code>```

let us say into a

```<code>tempdf
</code>```

to do re-sampling or any other task at any given point in time because original dataframe

```<code>df
</code>```

is getting updated continuously

答:
```<code>import numpy as np
import pandas as pd
import datetime as dt
import time

# create df with timestamp as index
df = pd.DataFrame(columns=["timestamp","stockname","price","volume"], dtype = float)
pd.to_datetime(df['timestamp'], format = "%Y-%m-%d %H:%M:%S:%f")
df.set_index('timestamp', inplace = True)

for i in range(10): # for the purposes of functioning demo code
    i += 1 # counter
    time.sleep(0.01) # give jupyter notebook a moment
    timestamp = dt.datetime.now() # to be used as index
    df.loc[timestamp] = ['AAPL', np.random.randint(1000), np.random.randint(10)] # replace with your database read

tempdf = df.copy()
</code>```

If you are reading a file or database continuously, you can replace the for: loop with what you described in your question. @MattR's questions should also be addressed; if you need to continuously log or update data, I am not sure if pandas is the best solution.

Body:
I have a continuous stream of data coming in so I want to define the DataFrame before hand so that I don't have tell pandas to format data or set index

So I want to create a DataFrame like

df = pd.DataFrame(columns=["timestamp","stockname","price","volume"])

but I want to tell Pandas that index of data should be timestamp and that the format would be

"%Y-%m-%d %H:%M:%S:%f"

and one this it set, then I would read through file and pass data to the DataFrame initialized

I get data in variables like these populated every time in loop like

for line in filehandle:

    timestamp, stockname, price, volume = fetch(line)

    here I want to update the "df"

this update would go on while I would keep using the copy of

df

let us say into a

tempdf

to do re-sampling or any other task at any given point in time because original dataframe

df

is getting updated continuously

Body:
import numpy as np
import pandas as pd
import datetime as dt
import time

# create df with timestamp as index
df = pd.DataFrame(columns=["timestamp","stockname","price","volume"], dtype = float)
pd.to_datetime(df['timestamp'], format = "%Y-%m-%d %H:%M:%S:%f")
df.set_index('timestamp', inplace = True)

for i in range(10): # for the purposes of functioning demo code
    i += 1 # counter
    time.sleep(0.01) # give jupyter notebook a moment
    timestamp = dt.datetime.now() # to be used as index
    df.loc[timestamp] = ['AAPL', np.random.randint(1000), np.random.randint(10)] # replace with your database read

tempdf = df.copy()

If you are reading a file or database continuously, you can replace the for: loop with what you described in your question. @MattR's questions should also be addressed; if you need to continuously log or update data, I am not sure if pandas is the best solution.


问:
Unable to register new color javascript tracking.js
I'm trying to add an identification to a green color.
All default colors work fine but I have not been able to add a new color for color with camera.

for more info : ColorTracker

```<code>window.onload = function() {
  var video = document.getElementById('video');
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');

  var tracker = new tracking.ColorTracker();

  tracking.ColorTracker.registerColor('green', function (r, g, b) {
      if (r < 50 && g > 200 && b < 50) {
          return true;
      }
      return false;
  });

  tracking.track('#video', tracker, { camera: true });

  tracker.on('track', function(event) {
    context.clearRect(0, 0, canvas.width, canvas.height);

    event.data.forEach(function(rect) {
      if (rect.color === 'custom') {
        rect.color = tracker.customColor;
      }

      context.strokeStyle = rect.color;
      context.strokeRect(rect.x, rect.y, rect.width, rect.height);
      context.font = '11px Helvetica';
      context.fillStyle = "#fff";
      context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
      context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
    });
  });

 initGUIControllers(tracker);
};
</code>```

答:
You are doing it right, just the color tracking is very picky. It will choose whatever is closest to the G in the RGB color. It does pick up some black and other colors because of that. I would recommend getting the RGB color of the exact green you want to track and go off of that. I included the few I have working in my project( this does not mean these will work for your green) </p>

```<code>tracking.ColorTracker.registerColor('darkgreen', function (r, g, b) {
  if (r < 120   &&   r > 80   &&   g < 150  && b < 70) {
    return true;
  }
    return false;
});

tracking.ColorTracker.registerColor('lightgreen', function (r, g, b) {
  if (r < 30 && g < 100 && b < 30) {
    return true;
  }
  return false;
});

tracking.ColorTracker.registerColor('green', function (r, g, b) {
  if (r < 30 && g < 50 && b < 30) {
    return true;
  }
  return false;
});
</code>```

Body:
I'm trying to add an identification to a green color.
All default colors work fine but I have not been able to add a new color for color with camera.

for more info : ColorTracker

window.onload = function() {
  var video = document.getElementById('video');
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');

  var tracker = new tracking.ColorTracker();

  tracking.ColorTracker.registerColor('green', function (r, g, b) {
      if (r < 50 && g > 200 && b < 50) {
          return true;
      }
      return false;
  });

  tracking.track('#video', tracker, { camera: true });

  tracker.on('track', function(event) {
    context.clearRect(0, 0, canvas.width, canvas.height);

    event.data.forEach(function(rect) {
      if (rect.color === 'custom') {
        rect.color = tracker.customColor;
      }

      context.strokeStyle = rect.color;
      context.strokeRect(rect.x, rect.y, rect.width, rect.height);
      context.font = '11px Helvetica';
      context.fillStyle = "#fff";
      context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
      context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
    });
  });

 initGUIControllers(tracker);
};

Body:
You are doing it right, just the color tracking is very picky. It will choose whatever is closest to the G in the RGB color. It does pick up some black and other colors because of that. I would recommend getting the RGB color of the exact green you want to track and go off of that. I included the few I have working in my project( this does not mean these will work for your green)

tracking.ColorTracker.registerColor('darkgreen', function (r, g, b) {
  if (r < 120   &&   r > 80   &&   g < 150  && b < 70) {
    return true;
  }
    return false;
});

tracking.ColorTracker.registerColor('lightgreen', function (r, g, b) {
  if (r < 30 && g < 100 && b < 30) {
    return true;
  }
  return false;
});

tracking.ColorTracker.registerColor('green', function (r, g, b) {
  if (r < 30 && g < 50 && b < 30) {
    return true;
  }
  return false;
});


问:
Catching command-line errors using %x
Whenever you want to execute something on the command line, you can use the following syntax:

```<code>%x(command to run)
</code>```

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

```<code>result = %x(command to run)
</code>```

and using a try-catch

```<code>begin
  %x(command to run)
rescue
  "didn't work"
end
</code>```

to no avail. How can I capture the results instead of having them printed out?

答:
You might want to redirect stderr to stdout:

```<code>result = %x(command to run 2>&1)
</code>```

Or if you want to separate the error messages from the actual output, you can use popen3:

```<code>require 'open3'
stdin, stdout, stderr = Open3.popen3("find /proc")
</code>```

Then you can read the actual output from stdout and error messages from stderr.

Title: Catching command-line errors using %x

Body:
Whenever you want to execute something on the command line, you can use the following syntax:

%x(command to run)

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

result = %x(command to run)

and using a try-catch

begin
  %x(command to run)
rescue
  "didn't work"
end

to no avail. How can I capture the results instead of having them printed out?

Body:
You might want to redirect stderr to stdout:

result = %x(command to run 2>&1)

Or if you want to separate the error messages from the actual output, you can use popen3:

require 'open3'
stdin, stdout, stderr = Open3.popen3("find /proc")

Then you can read the actual output from stdout and error messages from stderr.


答:
You can inject something in a pojo member variable through e.g. a method like this. I do not say that it is a good way to do this, but it can be done like this.</p>

```<code>import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * @author Ivo Woltring
 */
public class HashMapKeyStuff {

    /**
     * The most simple cdi like method.
     *
     * @param injectable the object you want to inject something in
     * @param fieldname  the fieldname to inject to
     * @param value      the value to assign to the fieldname
     */
    public static void injectField(final Object injectable, final String fieldname, final Object value) {
        try {
            final Field field = injectable.getClass()
                    .getDeclaredField(fieldname);
            final boolean origionalValue = field.isAccessible();
            field.setAccessible(true);
            field.set(injectable, value);
            field.setAccessible(origionalValue);
        } catch (final NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private void doIt() {
        HashMap<String, String> foo = new HashMap<>();
        foo.put("hello", "world");
        foo.put("message", "You are great");

        MyPOJO pojo = new MyPOJO();
        for (final String key : foo.keySet()) {
            injectField(pojo, key, foo.get(key));
        }
        System.out.println("pojo = " + pojo);
    }

    public static void main(String[] args) {
        new HashMapKeyStuff().doIt();
    }

}

class MyPOJO {
    private String hello;
    private String message;

    public String getHello() {
        return this.hello;
    }

    public String getMessage() {
        return this.message;
    }

    @Override
    public String toString() {
        return "MyPOJO{" +
                "hello='" + hello + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
</code>```

Body:
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)

To ignore the errors I tried :

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

But then nothing got mapped.

Body:
You can inject something in a pojo member variable through e.g. a method like this. I do not say that it is a good way to do this, but it can be done like this.

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * @author Ivo Woltring
 */
public class HashMapKeyStuff {

    /**
     * The most simple cdi like method.
     *
     * @param injectable the object you want to inject something in
     * @param fieldname  the fieldname to inject to
     * @param value      the value to assign to the fieldname
     */
    public static void injectField(final Object injectable, final String fieldname, final Object value) {
        try {
            final Field field = injectable.getClass()
                    .getDeclaredField(fieldname);
            final boolean origionalValue = field.isAccessible();
            field.setAccessible(true);
            field.set(injectable, value);
            field.setAccessible(origionalValue);
        } catch (final NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private void doIt() {
        HashMap<String, String> foo = new HashMap<>();
        foo.put("hello", "world");
        foo.put("message", "You are great");

        MyPOJO pojo = new MyPOJO();
        for (final String key : foo.keySet()) {
            injectField(pojo, key, foo.get(key));
        }
        System.out.println("pojo = " + pojo);
    }

    public static void main(String[] args) {
        new HashMapKeyStuff().doIt();
    }

}

class MyPOJO {
    private String hello;
    private String message;

    public String getHello() {
        return this.hello;
    }

    public String getMessage() {
        return this.message;
    }

    @Override
    public String toString() {
        return "MyPOJO{" +
                "hello='" + hello + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}


问:
How to do bitwise AND in javascript on variables that are longer than 32 bit?
I have 2 numbers in javascript that I want to bit and. They both are 33bit long

in C#:

```<code> ((4294967296 & 4294967296 )==0) is false
</code>```

but in javascript:

```<code> ((4294967296 & 4294967296 )==0) is true
</code>```

4294967296 is ((long)1) << 32

As I understand it, it is due to the fact that javascript converts values to int32 when performing bit wise operations.

How do I work around this?
Any suggestions on how to replace bit and with a set of other math operations so that bits are not lost?

答:
The simplest bit-wise AND, that works up to JavaScript's maximum number

JavaScript's max integer value is 2^53 for internal reasons (it's a double float). If you need more there are good libraries for that big integer handling.

2^53 is 9,007,199,254,740,992, or about 9,000 trillion (~9 quadrillion).

```<code>// Works with values up to 2^53
function bitwiseAnd_53bit(value1, value2) {
    const maxInt32Bits = 4294967296; // 2^32

    const value1_highBits = value1 / maxInt32Bits;
    const value1_lowBits = value1 % maxInt32Bits;
    const value2_highBits = value2 / maxInt32Bits;
    const value2_lowBits = value2 % maxInt32Bits;
    return (value1_highBits & value2_highBits) * maxInt32Bits + (value1_lowBits & value2_lowBits)
}
</code>```

Body:
I have 2 numbers in javascript that I want to bit and. They both are 33bit long

in C#:

 ((4294967296 & 4294967296 )==0) is false

but in javascript:

 ((4294967296 & 4294967296 )==0) is true

4294967296 is ((long)1) << 32

As I understand it, it is due to the fact that javascript converts values to int32 when performing bit wise operations.

How do I work around this?
Any suggestions on how to replace bit and with a set of other math operations so that bits are not lost?

Body:
The simplest bit-wise AND, that works up to JavaScript's maximum number

JavaScript's max integer value is 2^53 for internal reasons (it's a double float). If you need more there are good libraries for that big integer handling.

2^53 is 9,007,199,254,740,992, or about 9,000 trillion (~9 quadrillion).

// Works with values up to 2^53
function bitwiseAnd_53bit(value1, value2) {
    const maxInt32Bits = 4294967296; // 2^32

    const value1_highBits = value1 / maxInt32Bits;
    const value1_lowBits = value1 % maxInt32Bits;
    const value2_highBits = value2 / maxInt32Bits;
    const value2_lowBits = value2 % maxInt32Bits;
    return (value1_highBits & value2_highBits) * maxInt32Bits + (value1_lowBits & value2_lowBits)
}


问:
OS X / Linux: pipe into two processes?
I know about

```<code>program1 | program2
</code>```

and

```<code>program1 | tee outputfile | program2
</code>```

but is there a way to feed program1's output into both program2 and program3?

答: use (;) syntax...  try ps aux | (head -n 1; tail -n 1)

Title: OS X / Linux: pipe into two processes?

Body:
I know about

program1 | program2

and

program1 | tee outputfile | program2

but is there a way to feed program1's output into both program2 and program3?