问:
How do I modify the first label from 0.0 to 0 of the x axis in my graph?
I have tried to change 0.0 to 0 at the start of the x-axis when I have my graph.

My numerical data are:

```<code>x = 0.115, 0.234, 0.329, 0.443, 0.536, 0.654, 0.765, 0.846

y = 5.598, 7.6942, 9.1384, 11.2953, 12.4065, 15.736, 21.603, 31.4367

s = 0.05, 0.1, 0.16, 0.4, 0.32, 0.17, 0.09, 1.2
</code>```

The original data does not have x = 0, y = 0.
I make the commands to add it and make the graph automatically.
But the graph starts at 0.0 on the x-axis. How do I change 0.0 to 0 without affecting the rest of the numbers?

I have studied the following links ... but still have not succeeded ...
Modify tick label text
pyplot remove the digits of zero ( start from 0 not 0.00)

The commands I have are:

```<code>import pandas as pd
import matplotlib.pyplot as plt

datos = pd.read_csv('.name.csv')
print(datos)

datosSM1 = datos[0:0]
datosSM1.loc[0] = 0
datosSM2 = datos[0:]

datosSM = pd.concat([datosSM1, datosSM2])
print(datosSM)

x = datosSM['x']
y = datosSM['y']
ys = datosSM['s']

plt.errorbar(x,y, fmt = 'ko', label = 'datos',
         yerr = ys, ecolor='r' )
plt.axis([0, x.max()+0.02, 0, y.max()+(y.max()/10)])

plt.show()
</code>```

I really appreciate your help and attention.

答:
To modify a selected label (actually its text), try the below code:

```<code># Prepend first row with zeroes
datosSM = pd.concat([pd.DataFrame({'x': 0, 'y': 0, 's': 0}, index=[0]),
    datos], ignore_index=True)
# Drawing
fig, ax = plt.subplots()  # Will be needed soon
plt.errorbar(datosSM.x, datosSM.y, yerr=datosSM.x, fmt='ko', label='datos', ecolor='r')
plt.axis([0, datosSM.x.max() + 0.02, 0, datosSM.y.max() + (datosSM.y.max() / 10)])
fig.canvas.draw()  # Needed to get access to label texts
# Get label texts
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = '0'    # Modify the selected label
ax.set_xticklabels(labels)
plt.show()
</code>```

One additional improvement in the above code is a more concise way to
generate a Dataframe with prepended row with zeroes.

Another improvement is that you don't need to "extract" individual columns.
You can pass existing columns of your DataFrame.

The result is:

Body:
I have tried to change 0.0 to 0 at the start of the x-axis when I have my graph.

My numerical data are:

x = 0.115, 0.234, 0.329, 0.443, 0.536, 0.654, 0.765, 0.846

y = 5.598, 7.6942, 9.1384, 11.2953, 12.4065, 15.736, 21.603, 31.4367

s = 0.05, 0.1, 0.16, 0.4, 0.32, 0.17, 0.09, 1.2

The original data does not have x = 0, y = 0.
I make the commands to add it and make the graph automatically.
But the graph starts at 0.0 on the x-axis. How do I change 0.0 to 0 without affecting the rest of the numbers?

I have studied the following links ... but still have not succeeded ...
Modify tick label text
pyplot remove the digits of zero ( start from 0 not 0.00)

The commands I have are:

import pandas as pd
import matplotlib.pyplot as plt

datos = pd.read_csv('.name.csv')
print(datos)

datosSM1 = datos[0:0]
datosSM1.loc[0] = 0
datosSM2 = datos[0:]

datosSM = pd.concat([datosSM1, datosSM2])
print(datosSM)

x = datosSM['x']
y = datosSM['y']
ys = datosSM['s']

plt.errorbar(x,y, fmt = 'ko', label = 'datos',
         yerr = ys, ecolor='r' )
plt.axis([0, x.max()+0.02, 0, y.max()+(y.max()/10)])

plt.show()

I really appreciate your help and attention.

Body:
To modify a selected label (actually its text), try the below code:

# Prepend first row with zeroes
datosSM = pd.concat([pd.DataFrame({'x': 0, 'y': 0, 's': 0}, index=[0]),
    datos], ignore_index=True)
# Drawing
fig, ax = plt.subplots()  # Will be needed soon
plt.errorbar(datosSM.x, datosSM.y, yerr=datosSM.x, fmt='ko', label='datos', ecolor='r')
plt.axis([0, datosSM.x.max() + 0.02, 0, datosSM.y.max() + (datosSM.y.max() / 10)])
fig.canvas.draw()  # Needed to get access to label texts
# Get label texts
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = '0'    # Modify the selected label
ax.set_xticklabels(labels)
plt.show()

One additional improvement in the above code is a more concise way to
generate a Dataframe with prepended row with zeroes.

Another improvement is that you don't need to "extract" individual columns.
You can pass existing columns of your DataFrame.

The result is:


来源: stackexchange

问:
Finding trouble in links in html not working
```<code><body >
    <div class="outer-container">
        <div class="container">
            <div class="header">
               <a href="#">HOME</a>
               <a href="#">ABOUT</a>
               <a href="#">CONTACT</a>
               <a href="">RESUME</a>
            </div>
            <div class="big-heading">
                <h2 style=color:white>
                   I'm Ankit Soni.
                </h2>
            </div>

            <div class="social-media">
                    <a href="https://www.linkedin.com/in/ankit-soni-991495152/">
                    <i class="fa fa-linkedin"></i></a>
                    <a href="https://github.com/ankysony">
                    <i class="fa fa-github"></i></a>
                    <a href="mailto:ankit.soni.che16@iitbhu.ac.in">
                    <i class="fa fa-envelope"></i></a>
            </div>
            <div class="scrolldown">
                <a href="">
                    <i class="fa fa-arrow-circle-down"></i>
                </a>
            </div>
        </div>
    </div>
</body>
</code>```

I cannot find any type of mistake in it but my links in it are not working (no cursor pointer no redirects). Only the last one with arrow circle is working. The links under class social-media are not.

I got a part of css which is creating the error please see to it and suggest the possible way to fix error.

```<code>.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}
</code>```

and the entire css code is below.

```<code> *
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.outer-container
{
    height: 792px;
    width: 1440px;
}
h2{
    font-family: sans-serif;
}
html {
    background: url(../images/banner.jpg);
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
    overflow: scroll;
    overflow-x: hidden;
  }
.outer-container .container .header
{
    text-align: center;
    word-spacing: 100px;
    padding-top: 10px;
}
.outer-container .container .header a
{
    font-family: sans-serif;
    text-decoration: none;
    color: white;
}
.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}
.outer-container .container .social-media
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
}
.outer-container .container .social-media i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 30px;
}
.outer-container .container .scrolldown
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 300px;
}
 .outer-container .container .scrolldown i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 50px;
}
</code>```

答:
Cursor: pointer is showing and working fine in your code, to get font awesome work you need to include the library of font awesome.

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

               HOME
               ABOUT
               CONTACT
               RESUME

                   I'm Ankit Soni.

```

ContentLicense: CC BY-SA 4.0

Body:
               HOME
               ABOUT
               CONTACT
               RESUME

                   I'm Ankit Soni.

I cannot find any type of mistake in it but my links in it are not working (no cursor pointer no redirects). Only the last one with arrow circle is working. The links under class social-media are not.

I got a part of css which is creating the error please see to it and suggest the possible way to fix error.

.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}

and the entire css code is below.

 *
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.outer-container
{
    height: 792px;
    width: 1440px;
}
h2{
    font-family: sans-serif;
}
html {
    background: url(../images/banner.jpg);
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
    overflow: scroll;
    overflow-x: hidden;
  }
.outer-container .container .header
{
    text-align: center;
    word-spacing: 100px;
    padding-top: 10px;
}
.outer-container .container .header a
{
    font-family: sans-serif;
    text-decoration: none;
    color: white;
}
.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}
.outer-container .container .social-media
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
}
.outer-container .container .social-media i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 30px;
}
.outer-container .container .scrolldown
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 300px;
}
 .outer-container .container .scrolldown i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 50px;
}

Body:
Cursor: pointer is showing and working fine in your code, to get font awesome work you need to include the library of font awesome.

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<body >
    <div class="outer-container">
        <div class="container">
            <div class="header">
               <a href="#">HOME</a>
               <a href="#">ABOUT</a>
               <a href="#">CONTACT</a>
               <a href="">RESUME</a>
            </div>
            <div class="big-heading">
                <h2 style=color:white>
                   I'm Ankit Soni.
                </h2>
            </div>

            <div class="social-media">
                    <a target="_blank" href="https://www.linkedin.com/in/ankit-soni-991495152/">
                    <i class="fa fa-linkedin"></i></a>
                    <a target="_blank" href="https://github.com/ankysony">
                    <i class="fa fa-github"></i></a>
                    <a target="_blank" href="mailto:ankit.soni.che16@iitbhu.ac.in">
                    <i class="fa fa-envelope"></i></a>
            </div>
            <div class="scrolldown">
                <a href="">
                    <i class="fa fa-arrow-circle-down"></i>
                </a>
            </div>
        </div>
    </div>
</body>


问:
Client uses RestTemplate.getPostObject() to Server, but @RequestBody can't parse
Springboot 2.2.2 + SpringCloud Hoxton SR1

It is just an order-payment demo.

Here is my code for the client to create an order to server:

@Resource
private RestTemplate restTemplate;

@GetMapping(value = "/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
  return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
```

<p>Code for Server</p>

<pre class="lang-java prettyprint-override"><code>@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){
  int result = paymentService.create(payment);
  log.info("******result：" + result + "******" + payment + "******");
  if(result > 0){
     return new CommonResult(200, "insert success，ServerPort：" + serverPort, result);
   } else {
       return new CommonResult(444, "insert failed，ServerPort：" + serverPort, null);
   }
}
</code>```

Then

I used postman send an address:

http://localhost/consumer/payment/create?serial=tom

The error for client is:

```<code>2020-05-29 19:42:15.546 ERROR 5348 --- [p-nio-80-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException$UnsupportedMediaType: 415 : [{"timestamp":"2020-05-29T11:42:15.544+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/xml;charset=UTF-8' not supported","trace":"org.springframework.web.HttpMe... (6245 bytes)]] with root cause

org.springframework.web.client.HttpClientErrorException$UnsupportedMediaType: 415 : [{"timestamp":"2020-05-29T11:42:15.544+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/xml;charset=UTF-8' not supported","trace":"org.springframework.web.HttpMe... (6245 bytes)]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:133) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:785) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at edu.imu.springcloud.Controller.OrderController.create(OrderController.java:29) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) ~[spring-boot-actuator-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
</code>```

The warning for the server is:

```<code>Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/xml;charset=UTF-8' not supported]
</code>```

I debugged the create method on the server-side. After sending the get request using postman, I found that the create method was not executed, or did not enter the function body, but when debugging the client, I found that he had returned the result.

When I removed @RequestBody it can work but the content for 'payment' is null.

It seems to me that @RequestBody rejected my request and returned an error message.

Here is my application.yml

```<code>server:
  port: 80

spring:
  application:
    name: cloud-order-service

 eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/, http://localhost:7002/eureka/
</code>```

And ApplicatonConfig

    @Configuration
    public class ApplicationContextConfig {

        @Bean
        @LoadBalanced
        public RestTemplate getRestTemplete(){
            return new RestTemplate();
        }
    }
```

I do not know what happened pls help me...

答:
```<code>@GetMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", payment.getId());
        jsonObject.put("serial", payment.getSerial());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<Object> entity = new HttpEntity<>(jsonObject, headers);
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", entity, CommonResult.class);
    }
</code>```

Body:
Springboot 2.2.2 + SpringCloud Hoxton SR1

It is just an order-payment demo.

Here is my code for the client to create an order to server:

@Resource
private RestTemplate restTemplate;

@GetMapping(value = "/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
  return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}

Code for Server

@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){
  int result = paymentService.create(payment);
  log.info("******result：" + result + "******" + payment + "******");
  if(result > 0){
     return new CommonResult(200, "insert success，ServerPort：" + serverPort, result);
   } else {
       return new CommonResult(444, "insert failed，ServerPort：" + serverPort, null);
   }
}

Then

I used postman send an address:

http://localhost/consumer/payment/create?serial=tom

The error for client is:

2020-05-29 19:42:15.546 ERROR 5348 --- [p-nio-80-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException$UnsupportedMediaType: 415 : [{"timestamp":"2020-05-29T11:42:15.544+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/xml;charset=UTF-8' not supported","trace":"org.springframework.web.HttpMe... (6245 bytes)]] with root cause

org.springframework.web.client.HttpClientErrorException$UnsupportedMediaType: 415 : [{"timestamp":"2020-05-29T11:42:15.544+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/xml;charset=UTF-8' not supported","trace":"org.springframework.web.HttpMe... (6245 bytes)]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:133) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:785) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at edu.imu.springcloud.Controller.OrderController.create(OrderController.java:29) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) ~[spring-boot-actuator-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.29.jar:9.0.29]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]

The warning for the server is:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/xml;charset=UTF-8' not supported]

I debugged the create method on the server-side. After sending the get request using postman, I found that the create method was not executed, or did not enter the function body, but when debugging the client, I found that he had returned the result.

When I removed @RequestBody it can work but the content for 'payment' is null.

It seems to me that @RequestBody rejected my request and returned an error message.

Here is my application.yml

server:
  port: 80

spring:
  application:
    name: cloud-order-service

 eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/, http://localhost:7002/eureka/

And ApplicatonConfig

    @Configuration
    public class ApplicationContextConfig {

        @Bean
        @LoadBalanced
        public RestTemplate getRestTemplete(){
            return new RestTemplate();
        }
    }

I do not know what happened pls help me...


问:
jQuery validator - Different error messages for same control
In my MVC validation I am using a calendar control and all validations work fine.

```<code>var today = $('#TodayDateHf').val();

$('#myform').validate({

    errorPlacement: $.calendars.picker.errorPlacement,

    rules: {

        DateFrom: {
            cpDate:true,
            cpCompareDate: { notAfter: '#DateTo', 'notAfter' : today }
        },
        DateTo: {
            cpDate:true,
            cpCompareDate: { notBefore: '#DateFrom' }
        }

    },

    messages: {
        DateFrom: 'Please enter a valid date less than or equal to To date',
        DateTo: 'Please enter a valid date greater than or equal to From date'

    }

});
</code>```

Everything works fine, but my problem is that I don't know how I can display different messages for same control.

For example, for DateFrom a rule is defined and there are two parameters in that rule, but it only displays the same error message. How can I display a different error messages based on the parameter evaluated?

答:
You can use something like this</p>

```<code>messages:{
                DateFrom:{
                    cpDate:"Message1",
                    cpCompareDate: "Message2"
                }

            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my MVC validation I am using a calendar control and all validations work fine.

var today = $('#TodayDateHf').val();

$('#myform').validate({

    errorPlacement: $.calendars.picker.errorPlacement,

    rules: {

        DateFrom: {
            cpDate:true,
            cpCompareDate: { notAfter: '#DateTo', 'notAfter' : today }
        },
        DateTo: {
            cpDate:true,
            cpCompareDate: { notBefore: '#DateFrom' }
        }

    },

    messages: {
        DateFrom: 'Please enter a valid date less than or equal to To date',
        DateTo: 'Please enter a valid date greater than or equal to From date'

    }

});

Everything works fine, but my problem is that I don't know how I can display different messages for same control.

For example, for DateFrom a rule is defined and there are two parameters in that rule, but it only displays the same error message. How can I display a different error messages based on the parameter evaluated?

Body:
You can use something like this

messages:{
                DateFrom:{
                    cpDate:"Message1",
                    cpCompareDate: "Message2"
                }

            }


问:
Why does this beginner python program stop midway?
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

```<code># This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
</code>```

but the program only runs

```<code>Hello world!
What is your name?
Mizu
</code>```

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.

答:
The programme is not stopped. It is waiting for your input.
In the input function you have to give some valut at the run time.
myName = input("Mizu"). In this line you have entered your question. You have to give answer at run time
myName = input("what is your name")</p>

Body:
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

but the program only runs

Hello world!
What is your name?
Mizu

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.


问:
How do I programmatically trigger an “input” event without jQuery?
I installed an event handler on an input using

```<code>var element = document.getElementById('some-input');
element.addEventListener('input', function() {
    console.log('The value is now ' + element.value);
});
</code>```

As expected, the handler is triggered when I type into the text field, but I also need to invoke this handler from my code. How can I simulate the input event so that my event listener is called?

答:
If you are using react, following will work:</p>

```<code>const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
</code>```

Body:
I installed an event handler on an input using

var element = document.getElementById('some-input');
element.addEventListener('input', function() {
    console.log('The value is now ' + element.value);
});

As expected, the handler is triggered when I type into the text field, but I also need to invoke this handler from my code. How can I simulate the input event so that my event listener is called?

Body:
If you are using react, following will work:

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));


问:
appending data to python dictionary
I have used the following code to initialize a dictionary from the list of keys

```<code>z=df1[2].value_counts().keys().tolist()
mydict=dict.fromkeys(z,None)
</code>```

further, I have used

```<code>value=df2[2].value_counts().keys().tolist()
counts=df2[2].value_counts().tolist()
    for j,items in value:
        if mydict.has_key(items):
            mydict.setdefault(items,[]).append(counts[j])
</code>```

it is generating the following error

mydict.setdefault(items,[]).append(counts[j])
  AttributeError: 'NoneType' object has no attribute 'append'

答:
```<code>mydict = {}
print(mydict) # {}
</code>```

Appending one key:

```<code>mydict['key1'] = 1
print(mydict) # {'key1': 1}
</code>```

Appending multiple keys:

```<code>mydict.update({'key2': 2, 'key3': 3})
print(mydict) # {'key1': 1, 'key2': 2, 'key3': 3}
</code>```

Title: appending data to python dictionary

Body:
I have used the following code to initialize a dictionary from the list of keys

z=df1[2].value_counts().keys().tolist()
mydict=dict.fromkeys(z,None)

further, I have used

value=df2[2].value_counts().keys().tolist()
counts=df2[2].value_counts().tolist()
    for j,items in value:
        if mydict.has_key(items):
            mydict.setdefault(items,[]).append(counts[j])

it is generating the following error

mydict.setdefault(items,[]).append(counts[j])
  AttributeError: 'NoneType' object has no attribute 'append'

Body:
mydict = {}
print(mydict) # {}

Appending one key:

mydict['key1'] = 1
print(mydict) # {'key1': 1}

Appending multiple keys:

mydict.update({'key2': 2, 'key3': 3})
print(mydict) # {'key1': 1, 'key2': 2, 'key3': 3}


问:
asp.net - gridview update refresh page and reload data
I have a page with a gridview. When I click on edit and update, the value in the update function reverts to the value before the update. I tried adding if(!IsPostback) to my page_load. Now the data is updated, but after the update, the data is not bound again.

What should I do?

Thank you!

答:
Well... I found my error. My binding function is called BindData(), and I was calling DataBind() by mistake.

Lesson of the day: It's not a good idea to call a function that binds data BindData()

Thank you anyway :)


问:
Trigger Change event when the Input value changed programmatically?
I have an Input in my form. </p>

```<code><input type="text" id="changeProgramatic" onchange="return ChangeValue(this);"/>
</code>```

<p>If I change the value in this textBox (changeProgramatic) using another JavaScript function it won't trigger the change Event.(Note: I'm passing 'this' into the method) </p>

答:
If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

```<code>const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
</code>```

Body:
I have an Input in my form.

<input type="text" id="changeProgramatic" onchange="return ChangeValue(this);"/>

If I change the value in this textBox (changeProgramatic) using another JavaScript function it won't trigger the change Event.(Note: I'm passing 'this' into the method)

Body:
If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));


问:
Application's Autosave functionality causing selenium script failure
org.openqa.selenium.ElementClickInterceptedException: Element  is not clickable at point (856,732) because another element  obscures it</p>

答:
Please try out the below options,

As per my understanding, if we are on a webform with the auto-save functionality, then if we come out of a particular field autosave will be triggered and it will take some time for the autosave to happen. So in your case, you could try coming out of the field(i.e., by clicking outside that field using selenium) and have the code wait for some time to get the auto-save to complete.

You could use an explicit wait for this scenario. The below command will wait for a maximum of 40 seconds in order for the button to become clickable. If the element is clickable before 40 seconds it will click it. If the 40 seconds wait time gets over, then it will throw an exception.

```<code>        WebDriverWait wait = new WebDriverWait(driver, 40);
        wait.until(ExpectedConditions.elementToBeClickable(driver.findElementById("element-id"));
</code>```

Body:
Please try out the below options,

As per my understanding, if we are on a webform with the auto-save functionality, then if we come out of a particular field autosave will be triggered and it will take some time for the autosave to happen. So in your case, you could try coming out of the field(i.e., by clicking outside that field using selenium) and have the code wait for some time to get the auto-save to complete.

You could use an explicit wait for this scenario. The below command will wait for a maximum of 40 seconds in order for the button to become clickable. If the element is clickable before 40 seconds it will click it. If the 40 seconds wait time gets over, then it will throw an exception.

        WebDriverWait wait = new WebDriverWait(driver, 40);
        wait.until(ExpectedConditions.elementToBeClickable(driver.findElementById("element-id"));


问:
how to add a newly created node to linklist?
here is my code, i can only add the node to the head of the linklist, but how to append to the tail to the linklist? thanks</p>

```<code>struct recordNode {
  char name[256];
  char event[128];  /
  float time;
  struct recordNode* next;
};

struct recordNode* temp;
struct recordNode* aRecordPointer = NULL;

struct recordNode* createRecord(char* name, char* event, float time) {

  temp = (struct recordNode*)malloc(sizeof(struct recordNode));
  strcpy(temp->name, name);
  strcpy(temp->event, event);
  temp->time = time;

  /* link up */
  if (aRecordPointer == NULL) {
     aRecordPointer = temp;
     temp->next = NULL;
  } else {
     temp->next = aRecordPointer;
     aRecordPointer = temp;
  }

  return  aRecordPointer;

}

int main() {

  struct recordNode* record = createRecord("1abc", "abc", 12.25);
  record = createRecord("2abc", "abc", 25.98);
  record = createRecord("3abc", "abc", 52.60);

}

/* now result:

   3abc abc 12.25
   2abc abc 25.98
   1abc abc 52.60

   needed result:

   1abc abc 52.6
   2abc abc 25.98
   3abc abc 12.25

*/
</code>```

答:
```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Traverse();

struct recordNode {
  char name[256];
  char event[128];
  float time;
  struct recordNode* next;
};

struct recordNode* temp;
struct recordNode* aRecordPointer = NULL;

struct recordNode* createRecord(char* name, char* event, float time) {

  struct recordNode * ToTraverseTheLinkedList;
  temp = (struct recordNode*)malloc(sizeof(struct recordNode));
  strcpy(temp->name, name);
  strcpy(temp->event, event);
  temp->time = time;
  temp->next = NULL;

  /* link up */
  if (aRecordPointer == NULL) {
     aRecordPointer = temp;
     //temp->next = NULL;
  }
    else
    {
    ToTraverseTheLinkedList = aRecordPointer;
    while(ToTraverseTheLinkedList->next != NULL)
        {
             ToTraverseTheLinkedList =  ToTraverseTheLinkedList ->next;

        }
    ToTraverseTheLinkedList->next = temp;
    }
  return  aRecordPointer;

}

int main() {

  createRecord("1abc", "abc", 12.25);
  //Traverse();
  createRecord("2abc", "abc", 25.98);
  createRecord("3abc", "abc", 52.60);
        Traverse();
}

void Traverse()
{
struct recordNode * temp;
temp = aRecordPointer;
while(temp != NULL)
{
printf("%s\n",temp->name);
printf("%s\n",temp->event);
printf("%f\n",temp->time);
temp = temp->next;
}
}
</code>```

Body:
here is my code, i can only add the node to the head of the linklist, but how to append to the tail to the linklist? thanks

struct recordNode {
  char name[256];
  char event[128];  /
  float time;
  struct recordNode* next;
};

struct recordNode* temp;
struct recordNode* aRecordPointer = NULL;

struct recordNode* createRecord(char* name, char* event, float time) {

  temp = (struct recordNode*)malloc(sizeof(struct recordNode));
  strcpy(temp->name, name);
  strcpy(temp->event, event);
  temp->time = time;

  /* link up */
  if (aRecordPointer == NULL) {
     aRecordPointer = temp;
     temp->next = NULL;
  } else {
     temp->next = aRecordPointer;
     aRecordPointer = temp;
  }

  return  aRecordPointer;

}

int main() {

  struct recordNode* record = createRecord("1abc", "abc", 12.25);
  record = createRecord("2abc", "abc", 25.98);
  record = createRecord("3abc", "abc", 52.60);

}

/* now result:

   3abc abc 12.25
   2abc abc 25.98
   1abc abc 52.60

   needed result:

   1abc abc 52.6
   2abc abc 25.98
   3abc abc 12.25

*/


问:
How to combine two flat lists into one nested object
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

```<code>public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}
</code>```

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

```<code>{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}
</code>```

and with this output we want to form object as

```<code>public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}
</code>```

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

答:
There seems to be a number of questions here combined, I'll try to work through them:

Data Models and Deserialization

With respect to generating a single structure from your API response, I would recommend using the Newtonsoft.Json libraries, available on NuGet Json.NET. They will allow you to deserialize the response from your API, into a single object, which given the sample you provided, should contain a collection of each of your models, Order, PaymentDetail, CouponUsageDetail:

```<code>public class APIResponceContainer
{
    [JsonProperty("Orders")]
    public List<Order> Orders { get; set; }
    [JsonProperty("PaymentDetails")]
    public List<PaymentDetail> PaymentDetails { get; set; }
    [JsonProperty("CouponUsageDetails")]
    public List<CouponUsageDetail> CouponUsageDetails { get; set; }

    public APIResponceContainer()
    {
        Orders = new List<Order>();
        PaymentDetails = new List<PaymentDetail>();
        CouponUsageDetails = new List<CouponUsageDetail>();
    }
}
</code>```

Be aware to add the required attributes to each of your models as so:

```<code>public class Order
{
    [JsonProperty("ProductId")]
    public int ProductId { get; set; }
    [JsonProperty("CustomerId")]
    public int CustomerId { get; set; }
    [JsonProperty("OrderId")]
    public int OrderId { get; set; }
}
</code>```

Deserialization then happens from your JSON string, as such:

```<code>StringReader stringReader = new StringReader(myJSONString);
JsonSerializer js = JsonSerializer.Create();
APIResponceContainer APIResponce = (APIResponceContainer)js.Deserialize(stringReader, typeof(APIResponceContainer));
</code>```

Queries

As discussed in the comments, your data is unfortunately in terrible need of normalization. However, what I have inferred is that you would like to produce a flat structure, maintaining the "Few other Properties" and "key properties", for a combination of Order, PaymentDetail and CouponUsageDetail. You can use Linq for this, importantly I would recommend you choose yourself a "Primary Key". In other words, one property that can independently tie all the others together. In the example below, I have choose OrderID since it should be unique (?):

```<code>var flatSequence =
            from order in APIResponce.Orders
            join coupon in APIResponce.CouponUsageDetails on order.OrderId equals coupon.OrderId
            join payment in APIResponce.PaymentDetails on order.OrderId equals payment.OrderId
            select new
            {
                // Here extract all the properties you care about
                OrderID = order.OrderId,
                Customer = order.CustomerId,
                Product = order.ProductId,
                // All the "other Properties" ?
                BankDetail = payment.PaymentOnlyProperty
            };
</code>```

Here I have extracted to var, however if you know the final flat structure you would like, of course determine a class of your own to receive the result.

Please comment if there is any questions.

Body:
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}

and with this output we want to form object as

public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

Body:
There seems to be a number of questions here combined, I'll try to work through them:

Data Models and Deserialization

With respect to generating a single structure from your API response, I would recommend using the Newtonsoft.Json libraries, available on NuGet Json.NET. They will allow you to deserialize the response from your API, into a single object, which given the sample you provided, should contain a collection of each of your models, Order, PaymentDetail, CouponUsageDetail:

public class APIResponceContainer
{
    [JsonProperty("Orders")]
    public List<Order> Orders { get; set; }
    [JsonProperty("PaymentDetails")]
    public List<PaymentDetail> PaymentDetails { get; set; }
    [JsonProperty("CouponUsageDetails")]
    public List<CouponUsageDetail> CouponUsageDetails { get; set; }

    public APIResponceContainer()
    {
        Orders = new List<Order>();
        PaymentDetails = new List<PaymentDetail>();
        CouponUsageDetails = new List<CouponUsageDetail>();
    }
}

Be aware to add the required attributes to each of your models as so:

public class Order
{
    [JsonProperty("ProductId")]
    public int ProductId { get; set; }
    [JsonProperty("CustomerId")]
    public int CustomerId { get; set; }
    [JsonProperty("OrderId")]
    public int OrderId { get; set; }
}

Deserialization then happens from your JSON string, as such:

StringReader stringReader = new StringReader(myJSONString);
JsonSerializer js = JsonSerializer.Create();
APIResponceContainer APIResponce = (APIResponceContainer)js.Deserialize(stringReader, typeof(APIResponceContainer));

Queries

As discussed in the comments, your data is unfortunately in terrible need of normalization. However, what I have inferred is that you would like to produce a flat structure, maintaining the "Few other Properties" and "key properties", for a combination of Order, PaymentDetail and CouponUsageDetail. You can use Linq for this, importantly I would recommend you choose yourself a "Primary Key". In other words, one property that can independently tie all the others together. In the example below, I have choose OrderID since it should be unique (?):

var flatSequence =
            from order in APIResponce.Orders
            join coupon in APIResponce.CouponUsageDetails on order.OrderId equals coupon.OrderId
            join payment in APIResponce.PaymentDetails on order.OrderId equals payment.OrderId
            select new
            {
                // Here extract all the properties you care about
                OrderID = order.OrderId,
                Customer = order.CustomerId,
                Product = order.ProductId,
                // All the "other Properties" ?
                BankDetail = payment.PaymentOnlyProperty
            };

Here I have extracted to var, however if you know the final flat structure you would like, of course determine a class of your own to receive the result.

Please comment if there is any questions.


问:
Do objects have a copy of their class methods?
I wanted to know whether an object has a copy of all its class methods. So I created a class person, defined a method getName and created an object Harry. I used dir function to check whether both the class and the object have getName method stored inside them and both of them returned true. I then printed out the getName method of both the class and the object and they returned different addresses, but I noticed that harry.getName method is bounded to person.getName. So does that mean that harry.getName is not a copy of its class method rather just a reference to its class method. To check this used delattr method to delete the getName attribute of the person class and again used dir to check it. And as expected it deleted it from both the class person and object Harry.

So please review my code and tell whether my thoughts are correct.

Note:

The dir() function returns all properties and methods of the specified object, without the values.

The delattr() method is used to delete the named attribute from the object, with the prior permission of the object.

答:
What I conclude is this:

When we instantiate a class using variableName = className(args) it creates an object in memory, initializes all its data attributes using init method (constructor) and returns the memory address of the object data to the object variable name and we call it as an instance.

The object data contains two things

Data attributes and its values

Memory references of its class methods.

Whenever we call any method on the object by instanceName.method(), it refers to the class method and passes the object data itself as specified by the self argument and execute it to access or modify the object data.

Thus, the object in the memory only contains data attribute values and not a copy of its class methods, but only their memory references.


问:
Querying a view vs tables in SSRS Dataset
Is there a best practice when it comes to using Datasets in SSRS? Should I be writing a query for the dataset that pulls directly from tables, or should I be creating a view in the source database and then querying the view via the Dataset?

I understand there are some scenarios where the view would be better (centralizing a view for use in multiple reports) and some scenarios where a query of the tables would be better (if you are not allowed access to create views in the source DB or if you utilize multiple DB data sources in one report). But are there any performance implications? Can the server still cache the results of the dataset query from SSRS in a similar fashion as it would the results in a view?

Any insight will be appreciated :-)

答:
If performance is really important (and if the DBAs will allow it) consider actually creating a table - not a view - for every report report.

Create a stored procedure to update the tables in the nightly refresh.  The data set in your report will be a simple

```<code>select *
from rptRydmansTable
where Column1 = @Parm1 and Column2 = @Parm2
</code>```

These things fly!

ContentLicense: CC BY-SA 2.5

Body:
If performance is really important (and if the DBAs will allow it) consider actually creating a table - not a view - for every report report.

Create a stored procedure to update the tables in the nightly refresh.  The data set in your report will be a simple

select *
from rptRydmansTable
where Column1 = @Parm1 and Column2 = @Parm2

These things fly!


问:
How do I check if a users input is a valid IP address or not?
I want to check if an entered input is a valid IP address or not. I would like a specific function that will help me validate a users input.</p>

答:
```<code>// Usually you'd get the value from $_POST or $_GET
$ip = "10.3.1.5";
if(!filter_var($ip, FILTER_VALIDATE_IP)) {
   echo "Not a valid IP address!";
}
</code>```

You can modify this by filtering for IPv4 and IPv6 IP addresses and exclude private and reserved IPs.

http://www.php.net/manual/filter.filters.validate.php

Body:
// Usually you'd get the value from $_POST or $_GET
$ip = "10.3.1.5";
if(!filter_var($ip, FILTER_VALIDATE_IP)) {
   echo "Not a valid IP address!";
}

You can modify this by filtering for IPv4 and IPv6 IP addresses and exclude private and reserved IPs.

http://www.php.net/manual/filter.filters.validate.php


问:
Split string into parts of equal length c++
I want to iteratively break up a string of arbitrary length into substrings of length = 80 until the size of the final substring is either less than 80 or 0.
Assume the string is not divisible by 80 so length of final substring is not necessarily 80.
What am I doing wrong here?

```<code>#include <string>
#include <math.h>

string sub;

for (int i = 0; i < ceil(str.length()/80); i++) {
            if(str.length()/80 >= 1){
                sub = str.substr(i*80, 80);
            }
            if(str.length()/80 == 0){
                 sub = str.substr(i*80, str.length()%80);
            }
            if(sub.length() <= 0){
                 return;
</code>```

答:
Here is the alternate solution to your problem:</p>

```<code>#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;

int main() {
    string initial_str =  "";  //your main string
    int len = initial_str.size(); // size of the main string
    vector<string> sub_str; // vector of substrings

    for (int i = 0; i < len; i += 80){
        sub_str.push_back(initial_str.substr(i, 80));
        //cout<< initial_str.substr(i, 5) << endl;
    }

    for (int i = 0; i < sub_str.size(); i++)
        cout << sub_str[i] << "\n";
    return 0;
}
</code>```

Body:
I want to iteratively break up a string of arbitrary length into substrings of length = 80 until the size of the final substring is either less than 80 or 0.
Assume the string is not divisible by 80 so length of final substring is not necessarily 80.
What am I doing wrong here?

#include <string>
#include <math.h>

string sub;

for (int i = 0; i < ceil(str.length()/80); i++) {
            if(str.length()/80 >= 1){
                sub = str.substr(i*80, 80);
            }
            if(str.length()/80 == 0){
                 sub = str.substr(i*80, str.length()%80);
            }
            if(sub.length() <= 0){
                 return;

Body:
Here is the alternate solution to your problem:

#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;

int main() {
    string initial_str =  "";  //your main string
    int len = initial_str.size(); // size of the main string
    vector<string> sub_str; // vector of substrings

    for (int i = 0; i < len; i += 80){
        sub_str.push_back(initial_str.substr(i, 80));
        //cout<< initial_str.substr(i, 5) << endl;
    }

    for (int i = 0; i < sub_str.size(); i++)
        cout << sub_str[i] << "\n";
    return 0;
}


问:
Allow others to view repo w/o being added as collaborators
Is there a way to allow others to view a private repo on GitHub without adding them as collaborators? </p>

答: Nope, repo permissions are all or nothing.</p>


问:
How can I prevent my VB application to crash
I hope that you can help me with my problem.

I get this error:

System.Net.WebException:

  The remote server returned an error: (401) Unauthorized.

when I click on button_2. I want to prevent the application from crashing using, show a MessageBox error or something similar.

Can anyone help?

```<code>Private Sub Guna2Button1_Click(sender As Object, e As EventArgs) Handles Guna2Button1.Click
    Dim api As String
    api = Guna2TextBox1.Text
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("link")
    Dim wc As New WebClient
    Dim data As String
    Dim response As System.Net.HttpWebResponse
    Try
        response = request.GetResponse()
    Catch ex As System.Net.WebException
        MsgBox("Bad API")
    End Try
    MsgBox("Good API")

        data = wc.DownloadString("link")
        Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
        Dim ipstr As String = ("")
        Dim total As String = ("")
        Dim myJObject = JObject.Parse(data)

        For Each match In myJObject("matches")
            Dim ip = match("http")("host")
            If IPV4Regex.Match(ip).Success Then
                ipstr = ip
                total = total + ipstr & vbCrLf
                Guna2TextBox2.Text = total
                Label4.Visible = True
            End If
        Next
End Sub
</code>```

答:
Why your code dose not stop if api is wrong !!
your code must handle any error before going to next step
at least use Exit Sub </p>

```<code>Try
    response = request.GetResponse()
Catch ex As System.Net.WebException
    MsgBox("Bad API")

    Exit Sub

End Try
MsgBox("Good API")
</code>```

Body:
I hope that you can help me with my problem.

I get this error:

System.Net.WebException:

  The remote server returned an error: (401) Unauthorized.

when I click on button_2. I want to prevent the application from crashing using, show a MessageBox error or something similar.

Can anyone help?

Private Sub Guna2Button1_Click(sender As Object, e As EventArgs) Handles Guna2Button1.Click
    Dim api As String
    api = Guna2TextBox1.Text
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("link")
    Dim wc As New WebClient
    Dim data As String
    Dim response As System.Net.HttpWebResponse
    Try
        response = request.GetResponse()
    Catch ex As System.Net.WebException
        MsgBox("Bad API")
    End Try
    MsgBox("Good API")

        data = wc.DownloadString("link")
        Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
        Dim ipstr As String = ("")
        Dim total As String = ("")
        Dim myJObject = JObject.Parse(data)

        For Each match In myJObject("matches")
            Dim ip = match("http")("host")
            If IPV4Regex.Match(ip).Success Then
                ipstr = ip
                total = total + ipstr & vbCrLf
                Guna2TextBox2.Text = total
                Label4.Visible = True
            End If
        Next
End Sub

Body:
Why your code dose not stop if api is wrong !!
your code must handle any error before going to next step
at least use Exit Sub

Try
    response = request.GetResponse()
Catch ex As System.Net.WebException
    MsgBox("Bad API")

    Exit Sub

End Try
MsgBox("Good API")


问:
swiftui Array contents updated inside function closure but does not persist in other views
When fetching data from my database, I update an array from the json received inside the fetching function. While inside the function, the array stays updated, but when I try to access the array in a separate view, the array is empty.

the code that fetches the data and updates the "events" array looks like this:

```<code>import Foundation
import SwiftUI

let apiUrl = "http://localhost:5000/"

class DataFetcher: ObservableObject {

    @Published var events: [eventdata] = []

   func fetchEvents(){

        events.removeAll()
        let url = NSMutableURLRequest(url: NSURL(string: apiUrl)! as URL)

        url.httpMethod = "GET"

        URLSession.shared.dataTask(with: url as URLRequest) { data, response, err in
            if let err = err {
                print(err.localizedDescription)
                return
            }

            guard let response = response as? HTTPURLResponse else { return }
            if response.statusCode == 200 {
                guard let data = data else { return }
                DispatchQueue.main.async {
                    do{

                        self.events = try JSONDecoder().decode([eventdata].self, from: data)

                    //    print(self.events.last?.address)
                    }catch let err {
                        print("Error: \(err)")
                    }
                }
            } else {
                print("HTTPURLResponse code: \(response.statusCode)")
            }
        }.resume()

        //print(self.events.last?.address)
    }

}
</code>```

The view that calls this function looks like this:

```<code>import Foundation
import SwiftUI

struct CreateEventButton: View {
    @ObservedObject var request = DataFetcher()
    @State private var isPresentedEvent = false
    @State private var eventName: String = ""
    @State private var eventDescription: String = ""
    @State private var selectedStartTime = Date()
    @State private var selectedEndTime = Date()
    @State private var startTimeStamp: String = ""
    @State private var endTimeStamp: String = ""
    @Binding var annotationSelected: Bool
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .full
        return formatter
    }

    func send(_ sender: Any) {

        let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:5000/")! as URL)
            request.httpMethod = "POST"

        self.startTimeStamp = "\(self.selectedStartTime)"
        self.endTimeStamp = "\(self.selectedEndTime)"

        self.startTimeStamp.removeLast(5)
        self.endTimeStamp.removeLast(5)

        let postString = "b=\(self.eventName)&c=\(self.eventDescription)&d=\(self.startTimeStamp)&e=\(self.endTimeStamp)"

            request.httpBody = postString.data(using: String.Encoding.utf8)

            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in

                if error != nil {
                    print("error=\(String(describing: error))")
                    return
                }

                print("response = \(String(describing: response))")

                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("responseString = \(String(describing: responseString))")
            }
            task.resume()

            self.eventName = ""
            self.eventDescription = ""
            self.selectedStartTime = Date()
            self.selectedEndTime = Date()

        }

    var body: some View {
        //UNCOMMENT THIS STUFF BELOW TO MAKE AN EVENT CREATION BUTTON IN THE SHEET INSTEAD OF JUST DIRECTING TO A SHEET WITH THE EVENT CREATION DETAILS
      Button(action: {
            self.isPresentedEvent.toggle() //trigger modal presentation
        }, label: {
            Text("Create Event").font(.system(size: 18)).foregroundColor(Color(.darkGray)).shadow(radius: 8)
            }).padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
                .foregroundColor(.secondary)
                .background(Color(.secondarySystemBackground))
                .cornerRadius(50.0)
                .sheet(isPresented: $isPresentedEvent, content:{
            VStack{
                TextField("Event Name", text: self.$eventName).padding()
                TextField("Event Description", text: self.$eventDescription).padding()
                Form {
                    DatePicker("When your event starts: ", selection: self.$selectedStartTime, in: Date()...)
                }
                Form {
                    DatePicker("When your event ends:   ", selection: self.$selectedEndTime, in: Date()...)
                }
                HStack{
                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.annotationSelected = false
                    print("Start: \(self.selectedStartTime)")
                    print("End: \(self.selectedEndTime)")
                    self.send((Any).self)
                    }, label: {
                        Text("Create Event")
                    })
                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.request.fetchEvents()
                    print("yo yo \(self.request.events.last?.address)")
                   }, label: {
                       Text("Cancel")
                   })
                }
                Text("Create Event Button (Non Functional)").padding()
            }
        } )
     }
}
</code>```

Any insight on where I might be going wrong is much appreciated

答:
```<code>                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.request.fetchEvents()
                   }, label: {
                       if self.request.events.count > 0 {
                         Text("hey we have requests!")
                       } else {
                         Text("Cancel")
                       }
                   })
</code>```

woops posted the accidently before finishing. one sec.

I believe it's a timing issue. The view is rendered before your request finishes fetching your data. You can add an if statement like above to update your view once the data is fully fetched.

Body:
When fetching data from my database, I update an array from the json received inside the fetching function. While inside the function, the array stays updated, but when I try to access the array in a separate view, the array is empty.

the code that fetches the data and updates the "events" array looks like this:

import Foundation
import SwiftUI

let apiUrl = "http://localhost:5000/"

class DataFetcher: ObservableObject {

    @Published var events: [eventdata] = []

   func fetchEvents(){

        events.removeAll()
        let url = NSMutableURLRequest(url: NSURL(string: apiUrl)! as URL)

        url.httpMethod = "GET"

        URLSession.shared.dataTask(with: url as URLRequest) { data, response, err in
            if let err = err {
                print(err.localizedDescription)
                return
            }

            guard let response = response as? HTTPURLResponse else { return }
            if response.statusCode == 200 {
                guard let data = data else { return }
                DispatchQueue.main.async {
                    do{

                        self.events = try JSONDecoder().decode([eventdata].self, from: data)

                    //    print(self.events.last?.address)
                    }catch let err {
                        print("Error: \(err)")
                    }
                }
            } else {
                print("HTTPURLResponse code: \(response.statusCode)")
            }
        }.resume()

        //print(self.events.last?.address)
    }

}

The view that calls this function looks like this:

import Foundation
import SwiftUI

struct CreateEventButton: View {
    @ObservedObject var request = DataFetcher()
    @State private var isPresentedEvent = false
    @State private var eventName: String = ""
    @State private var eventDescription: String = ""
    @State private var selectedStartTime = Date()
    @State private var selectedEndTime = Date()
    @State private var startTimeStamp: String = ""
    @State private var endTimeStamp: String = ""
    @Binding var annotationSelected: Bool
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .full
        return formatter
    }

    func send(_ sender: Any) {

        let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:5000/")! as URL)
            request.httpMethod = "POST"

        self.startTimeStamp = "\(self.selectedStartTime)"
        self.endTimeStamp = "\(self.selectedEndTime)"

        self.startTimeStamp.removeLast(5)
        self.endTimeStamp.removeLast(5)

        let postString = "b=\(self.eventName)&c=\(self.eventDescription)&d=\(self.startTimeStamp)&e=\(self.endTimeStamp)"

            request.httpBody = postString.data(using: String.Encoding.utf8)

            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in

                if error != nil {
                    print("error=\(String(describing: error))")
                    return
                }

                print("response = \(String(describing: response))")

                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("responseString = \(String(describing: responseString))")
            }
            task.resume()

            self.eventName = ""
            self.eventDescription = ""
            self.selectedStartTime = Date()
            self.selectedEndTime = Date()

        }

    var body: some View {
        //UNCOMMENT THIS STUFF BELOW TO MAKE AN EVENT CREATION BUTTON IN THE SHEET INSTEAD OF JUST DIRECTING TO A SHEET WITH THE EVENT CREATION DETAILS
      Button(action: {
            self.isPresentedEvent.toggle() //trigger modal presentation
        }, label: {
            Text("Create Event").font(.system(size: 18)).foregroundColor(Color(.darkGray)).shadow(radius: 8)
            }).padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
                .foregroundColor(.secondary)
                .background(Color(.secondarySystemBackground))
                .cornerRadius(50.0)
                .sheet(isPresented: $isPresentedEvent, content:{
            VStack{
                TextField("Event Name", text: self.$eventName).padding()
                TextField("Event Description", text: self.$eventDescription).padding()
                Form {
                    DatePicker("When your event starts: ", selection: self.$selectedStartTime, in: Date()...)
                }
                Form {
                    DatePicker("When your event ends:   ", selection: self.$selectedEndTime, in: Date()...)
                }
                HStack{
                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.annotationSelected = false
                    print("Start: \(self.selectedStartTime)")
                    print("End: \(self.selectedEndTime)")
                    self.send((Any).self)
                    }, label: {
                        Text("Create Event")
                    })
                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.request.fetchEvents()
                    print("yo yo \(self.request.events.last?.address)")
                   }, label: {
                       Text("Cancel")
                   })
                }
                Text("Create Event Button (Non Functional)").padding()
            }
        } )
     }
}

Any insight on where I might be going wrong is much appreciated

Body:
                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.request.fetchEvents()
                   }, label: {
                       if self.request.events.count > 0 {
                         Text("hey we have requests!")
                       } else {
                         Text("Cancel")
                       }
                   })

woops posted the accidently before finishing. one sec.

I believe it's a timing issue. The view is rendered before your request finishes fetching your data. You can add an if statement like above to update your view once the data is fully fetched.


问:
Implement primitive recursive factorial in haskell
I am currently trying to implement primitive recursive factorial in Haskell.
I'm using the function recNat, as a recursor. That is:

```<code>recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero = a
recNat a h (Succ n) = h n (recNat a h n)
</code>```

This is our attempt, but can't quite figure out what's wrong

```<code>factR :: Nat -> Nat
factR Zero = Succ Zero
factR (Succ m) = recNat (Succ m) (\ _ y -> y) (factR m)
</code>```

I was also trying to implement the exponential function, but it seems even more confusing.

答:
In order to implement a factorial, we can implement a function for multiplication. For the multiplication function, we need the addition function

data Nat = Zero | Succ Nat

add :: Nat -> Nat -> Nat
add a Zero     = a
add a (Succ b) = Succ (add a b)

mul :: Nat -> Nat -> Nat
mul a Zero     = Zero
mul a (Succ b) = add a (mul a b)
```

<p>Then the factorial function just comes down to:</p>

<pre class="lang-hs prettyprint-override"><code>fac :: Nat -> Nat
fac Zero = Succ Zero
fac (Succ a) = mul (Succ a) (fac a)
</code>```

Body:
I am currently trying to implement primitive recursive factorial in Haskell.
I'm using the function recNat, as a recursor. That is:

recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero = a
recNat a h (Succ n) = h n (recNat a h n)

This is our attempt, but can't quite figure out what's wrong

factR :: Nat -> Nat
factR Zero = Succ Zero
factR (Succ m) = recNat (Succ m) (\ _ y -> y) (factR m)

I was also trying to implement the exponential function, but it seems even more confusing.

Body:
In order to implement a factorial, we can implement a function for multiplication. For the multiplication function, we need the addition function

data Nat = Zero | Succ Nat

add :: Nat -> Nat -> Nat
add a Zero     = a
add a (Succ b) = Succ (add a b)

mul :: Nat -> Nat -> Nat
mul a Zero     = Zero
mul a (Succ b) = add a (mul a b)

Then the factorial function just comes down to:

fac :: Nat -> Nat
fac Zero = Succ Zero
fac (Succ a) = mul (Succ a) (fac a)


答:
Here's how I would code it:</p>

```<code>void split(const std::string& str)
{
    const size_t linelength = 80;

    size_t count = str.length() / linelength;
    auto start = str.begin();
    std::string sub;

    for (size_t i = 0; i < count; i++)
    {
        size_t startoffset = i * linelength;
        size_t endoffset = startoffset + linelength;
        sub = std::string(start + startoffset, start + endoffset);
    }
    if (str.length() % linelength)
    {
        sub = std::string(start + count * linelength, str.end());
    }
}
</code>```

Title: Split string into parts of equal length c++

Body:
Here's how I would code it:

void split(const std::string& str)
{
    const size_t linelength = 80;

    size_t count = str.length() / linelength;
    auto start = str.begin();
    std::string sub;

    for (size_t i = 0; i < count; i++)
    {
        size_t startoffset = i * linelength;
        size_t endoffset = startoffset + linelength;
        sub = std::string(start + startoffset, start + endoffset);
    }
    if (str.length() % linelength)
    {
        sub = std::string(start + count * linelength, str.end());
    }
}


问:
Efficient string Match with SQL and Python
I want to know what is the best approach for a String Match with Python and a PSQL database. My db contains pubs names and zip codes. I want check if there are observations refering to the same pub but spelled differently by mistake.

Conceptually, I was thinking of looping through all the names and, for each other row in the same zip code, obtain a string similarity metric using strsim. If this metric is above a threshold, I insert it into another SQL table which stores the match candidates.

I think I am being inefficient. In "pseudo-code", having pub_table, candidates_table and using the JaroWinkler function, I mean to do something like:

```<code>from similarity.jarowinkler import JaroWinkler
jarowinkler = JaroWinkler()

cursor = conn.cursor()
cur.execute("SELECT name, zip from pub_table")
rows = cur.fetchall()
for r in rows:
    cur.execute("SELECT name FROM pub_tables WHERE zip = %s", (r[1],))
    search = cur.fetchall()

    for pub in search:
        if jarowinkler.similarity(r[0], pub[0]) > threshold:
             insertion = ("INSERT INTO candidates_table (name1, name2, zip)
                          VALUES (%s, %s, %s)")
             cur.execute(insertion, (r[0], pub[0], zip))

cursor.close ()
conn.commit ()
conn.close ()
</code>```

I am sorry if am not being clear (novice here). Any guidance for string matching using PSQL and Python will be highly appreciated. Thank you.

答:
Both the SELECT queries are on the same pub_tables table. And the inner loop with the second query on zip-match repeats for every row of pub_tables. You could directly get the zip equality comparison in one query by doing an INNER JOIN of pub_tables with itself.

SELECT p1.name, p2.name, p1.zip
FROM   pub_table p1,
       pub_table p2
WHERE  p1.zip = p2.zip
AND    p1.name != p2.name  -- this line assumes your original pub_table
                           -- has unique names for each "same pub in same zip"
                           -- and prevents the entries from matching with themselves.
```

<p>That would reduce your code to just the outer query & inner check + insert, without needing a second query:</p>

```cur.execute("<my query as above>")
rows = cur.fetchall()
for r in rows:
    # r[0] and r[1] are the names. r[2] is the zip code
    if jarowinkler.similarity(r[0], r[1]) > threshold:
         insertion = ("INSERT INTO candidates_table (name1, name2, zip)
                      VALUES (%s, %s, %s)")
         # since r already a tuple with the columns in the right order,
         # you can replace the `(r[0], r[1], r[2])` below with just `r`
         cur.execute(insertion, (r[0], r[1], r[2]))
         # or ...
         cur.execute(insertion, r)
```

Another change: The insertion string is always the same, so you can move that to before the for loop and only keep the parameterised cur.execute(insertion, r) inside the loop. Otherwise, you're just redefining the same static string over and over.

Body:
I want to know what is the best approach for a String Match with Python and a PSQL database. My db contains pubs names and zip codes. I want check if there are observations refering to the same pub but spelled differently by mistake.

Conceptually, I was thinking of looping through all the names and, for each other row in the same zip code, obtain a string similarity metric using strsim. If this metric is above a threshold, I insert it into another SQL table which stores the match candidates.

I think I am being inefficient. In "pseudo-code", having pub_table, candidates_table and using the JaroWinkler function, I mean to do something like:

from similarity.jarowinkler import JaroWinkler
jarowinkler = JaroWinkler()

cursor = conn.cursor()
cur.execute("SELECT name, zip from pub_table")
rows = cur.fetchall()
for r in rows:
    cur.execute("SELECT name FROM pub_tables WHERE zip = %s", (r[1],))
    search = cur.fetchall()

    for pub in search:
        if jarowinkler.similarity(r[0], pub[0]) > threshold:
             insertion = ("INSERT INTO candidates_table (name1, name2, zip)
                          VALUES (%s, %s, %s)")
             cur.execute(insertion, (r[0], pub[0], zip))

cursor.close ()
conn.commit ()
conn.close ()

I am sorry if am not being clear (novice here). Any guidance for string matching using PSQL and Python will be highly appreciated. Thank you.

Body:
Both the SELECT queries are on the same pub_tables table. And the inner loop with the second query on zip-match repeats for every row of pub_tables. You could directly get the zip equality comparison in one query by doing an INNER JOIN of pub_tables with itself.

SELECT p1.name, p2.name, p1.zip
FROM   pub_table p1,
       pub_table p2
WHERE  p1.zip = p2.zip
AND    p1.name != p2.name  -- this line assumes your original pub_table
                           -- has unique names for each "same pub in same zip"
                           -- and prevents the entries from matching with themselves.

That would reduce your code to just the outer query & inner check + insert, without needing a second query:

cur.execute("<my query as above>")
rows = cur.fetchall()
for r in rows:
    # r[0] and r[1] are the names. r[2] is the zip code
    if jarowinkler.similarity(r[0], r[1]) > threshold:
         insertion = ("INSERT INTO candidates_table (name1, name2, zip)
                      VALUES (%s, %s, %s)")
         # since r already a tuple with the columns in the right order,
         # you can replace the `(r[0], r[1], r[2])` below with just `r`
         cur.execute(insertion, (r[0], r[1], r[2]))
         # or ...
         cur.execute(insertion, r)

Another change: The insertion string is always the same, so you can move that to before the for loop and only keep the parameterised cur.execute(insertion, r) inside the loop. Otherwise, you're just redefining the same static string over and over.