问:
Calling method via jstl function fails with null pointer exception
I've read here about null pointer exception issue, please dont forward me there. I've already broken my head.

Have a tomcat v9. It's used to process voice calls as an IVR server. Inside is webapp with java classes and jsp pages (vxml inside). Problem, when calling this method:

```<code>    <c:if test="${(param.CUSTOMER_TYPE eq 'PPP') or (param.CUSTOMER_TYPE eq 'PKL') or (param.CUSTOMER_TYPE eq 'GIN')}">
    <c:set var="cin_cust_id" value="${param.VAR3}"/>
    <c:set var="cin_ani" value="${param.ANI}"/>
    <c:set var="cin_ursconnid" value="${param.URSCONNID}"/>
    <debug:message message="checkisnew.jsp. cin_cust_id: ${cin_cust_id}"/>
    <debug:message message="checkisnew.jsp. cin_ani: ${cin_ani}"/>
    <debug:message message="checkisnew.jsp. cin_ursconnid: ${cin_ursconnid}"/>
    <c:set var="isnew" value="${bakcellivr:cICN(cin_cust_id, cin_ani, cin_ursconnid)}" scope="request"/>
    <debug:message message="checkisnew.jsp. isnew: ${isnew}"/>
</c:if>
</code>```

This is taglib:

```<code><function>
    <description>Check if subscriber is calling for the first time or not</description>
    <name>cICN</name>
    <function-class>bkc.DB_Requests</function-class>
    <function-signature>java.lang.String checkIsCustomerNew(java.lang.String, java.lang.String, java.lang.String)</function-signature>
</function>
</code>```

This is the java method itself:

```<code>    package bkc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.ResultSet;

import javax.naming.NamingException;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

public class DB_Requests {

    private static Logger logger = LogManager.getLogger(DB_Requests.class);
    private static String url_out = "jdbc:oracle:thin:@xxxxxx:xxxx/xxxxx";

    public String checkIsCustomerNew (String custid, String msisdn, String connid) {

        Connection conn = null;
        CallableStatement s = null;

        String isNew = "-1";
        int ret_param = -2;

        try {
              conn = DBPool.getConnection();
        } catch (Exception e) {
            logger.error("Error while retrieving DB params from context. CONNID: " + connid);
            //System.out.println("DB_Requests.checkIsCustomerNew error retrieving DB params from context");
            //System.out.println("MSISDN is: " + msisdn + " ConnectioID is: " + connid + " Timestamp: " + sdf.format(date) + "\n");
            //e.printStackTrace();
            ErrorNotifier.sendMail("DB_Requests.checkIsCustomerNew", msisdn, connid, url_out, "--", "Error while retrieving DB params from context", e.getMessage(), e.getStackTrace());
            return "old";
        }

        String query = "{ ? = call cc.GET_SUBS_IVR_LISTEN_STATUS(?, ?) }";

        try {
            s = conn.prepareCall(query);
            s.registerOutParameter(1, java.sql.Types.INTEGER);
            s.setString(2, custid);
            s.setString(3, "BKC");
            s.execute();
            ret_param  = s.getInt(1);
        } catch (SQLException e) {
            logger.error("Failed to prepare or execute statement. CONNID: " + connid);
            //System.out.println("DB_Requests.checkIsCustomerNew failed to prepare or execute statement");
            //System.out.println("MSISDN is: " + msisdn + " ConnectioID is: " + connid + " Timestamp: " + sdf.format(date) + "\n");
            //e.printStackTrace();
            ErrorNotifier.sendMail("DB_Requests.checkIsCustomerNew", msisdn, connid, url_out, query, "Failed to prepare or execute statement", e.getMessage(), e.getStackTrace());
            return "old";
        }

        //System.out.println("DBPool.checkIsNew ret_param: " + ret_param);

        if (ret_param == 0) {
            isNew = "new";
        } else {
            isNew = "old";
        }

        //System.out.println("DBPool.checkIsNew isNew: " + isNew);

        try {
            conn.close();
        } catch (SQLException e) {
            logger.error("Failed to close connection object. CONNID: " + connid);
            //System.out.println("DB_Requests.getSubInfo failed to parse resultset object");
            //System.out.println("MSISDN is: " + msisdn + " ConnectioID is: " + connid + " Timestamp: " + sdf.format(date) + "\n");
            //e.printStackTrace();
            ErrorNotifier.sendMail("DB_Requests.checkIsNew", msisdn, connid, url_out, query, "Failed to close connection object", e.getMessage(), e.getStackTrace());
            return "old";
        }

        return isNew;

    }
}
</code>```

This is the exception i get in tomcat log:

```<code>09-Feb-2022 00:28:07.902 SEVERE [http-nio-0.0.0.0-8080-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/BAKCELLIVR] threw exception [An exception occurred processing [/vxml/checkisnew.jsp] at line [49]

46:         <debug:message message="checkisnew.jsp. cin_cust_id: ${cin_cust_id}"/>
47:         <debug:message message="checkisnew.jsp. cin_ani: ${cin_ani}"/>
48:         <debug:message message="checkisnew.jsp. cin_ursconnid: ${cin_ursconnid}"/>
49:         <c:set var="isnew" value="${bakcellivr:cICN(cin_cust_id, cin_ani, cin_ursconnid)}" scope="request"/>
50:         <debug:message message="checkisnew.jsp. isnew: ${isnew}"/>
51:     </c:if>
52:

Stacktrace:] with root cause
    java.lang.NullPointerException
        at java.base/java.lang.reflect.Method.invoke(Method.java:559)
        at org.apache.el.parser.AstFunction.getValue(AstFunction.java:198)
        at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
        at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:129)
        at org.apache.jsp.vxml.checkisnew_jsp._jspx_meth_c_005fset_005f6(checkisnew_jsp.java:1032)
        at org.apache.jsp.vxml.checkisnew_jsp._jspx_meth_c_005fif_005f2(checkisnew_jsp.java:860)
        at org.apache.jsp.vxml.checkisnew_jsp._jspService(checkisnew_jsp.java:161)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

looking at stacktrace it looks like tomcat is not even calling the method and exception occures on page render phase. I've checked all input variablesthey are not null. They print in log before the jstl is called and they have values. Dont't know where to dig.

答: Solved. It was my mistake. Function in tld must be refereced to static method. My method was not static.</p>

Body:
I've read here about null pointer exception issue, please dont forward me there. I've already broken my head.

Have a tomcat v9. It's used to process voice calls as an IVR server. Inside is webapp with java classes and jsp pages (vxml inside). Problem, when calling this method:

    <c:if test="${(param.CUSTOMER_TYPE eq 'PPP') or (param.CUSTOMER_TYPE eq 'PKL') or (param.CUSTOMER_TYPE eq 'GIN')}">
    <c:set var="cin_cust_id" value="${param.VAR3}"/>
    <c:set var="cin_ani" value="${param.ANI}"/>
    <c:set var="cin_ursconnid" value="${param.URSCONNID}"/>
    <debug:message message="checkisnew.jsp. cin_cust_id: ${cin_cust_id}"/>
    <debug:message message="checkisnew.jsp. cin_ani: ${cin_ani}"/>
    <debug:message message="checkisnew.jsp. cin_ursconnid: ${cin_ursconnid}"/>
    <c:set var="isnew" value="${bakcellivr:cICN(cin_cust_id, cin_ani, cin_ursconnid)}" scope="request"/>
    <debug:message message="checkisnew.jsp. isnew: ${isnew}"/>
</c:if>

This is taglib:

<function>
    <description>Check if subscriber is calling for the first time or not</description>
    <name>cICN</name>
    <function-class>bkc.DB_Requests</function-class>
    <function-signature>java.lang.String checkIsCustomerNew(java.lang.String, java.lang.String, java.lang.String)</function-signature>
</function>

This is the java method itself:

    package bkc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.ResultSet;

import javax.naming.NamingException;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

public class DB_Requests {

    private static Logger logger = LogManager.getLogger(DB_Requests.class);
    private static String url_out = "jdbc:oracle:thin:@xxxxxx:xxxx/xxxxx";

    public String checkIsCustomerNew (String custid, String msisdn, String connid) {

        Connection conn = null;
        CallableStatement s = null;

        String isNew = "-1";
        int ret_param = -2;

        try {
              conn = DBPool.getConnection();
        } catch (Exception e) {
            logger.error("Error while retrieving DB params from context. CONNID: " + connid);
            //System.out.println("DB_Requests.checkIsCustomerNew error retrieving DB params from context");
            //System.out.println("MSISDN is: " + msisdn + " ConnectioID is: " + connid + " Timestamp: " + sdf.format(date) + "\n");
            //e.printStackTrace();
            ErrorNotifier.sendMail("DB_Requests.checkIsCustomerNew", msisdn, connid, url_out, "--", "Error while retrieving DB params from context", e.getMessage(), e.getStackTrace());
            return "old";
        }

        String query = "{ ? = call cc.GET_SUBS_IVR_LISTEN_STATUS(?, ?) }";

        try {
            s = conn.prepareCall(query);
            s.registerOutParameter(1, java.sql.Types.INTEGER);
            s.setString(2, custid);
            s.setString(3, "BKC");
            s.execute();
            ret_param  = s.getInt(1);
        } catch (SQLException e) {
            logger.error("Failed to prepare or execute statement. CONNID: " + connid);
            //System.out.println("DB_Requests.checkIsCustomerNew failed to prepare or execute statement");
            //System.out.println("MSISDN is: " + msisdn + " ConnectioID is: " + connid + " Timestamp: " + sdf.format(date) + "\n");
            //e.printStackTrace();
            ErrorNotifier.sendMail("DB_Requests.checkIsCustomerNew", msisdn, connid, url_out, query, "Failed to prepare or execute statement", e.getMessage(), e.getStackTrace());
            return "old";
        }

        //System.out.println("DBPool.checkIsNew ret_param: " + ret_param);

        if (ret_param == 0) {
            isNew = "new";
        } else {
            isNew = "old";
        }

        //System.out.println("DBPool.checkIsNew isNew: " + isNew);

        try {
            conn.close();
        } catch (SQLException e) {
            logger.error("Failed to close connection object. CONNID: " + connid);
            //System.out.println("DB_Requests.getSubInfo failed to parse resultset object");
            //System.out.println("MSISDN is: " + msisdn + " ConnectioID is: " + connid + " Timestamp: " + sdf.format(date) + "\n");
            //e.printStackTrace();
            ErrorNotifier.sendMail("DB_Requests.checkIsNew", msisdn, connid, url_out, query, "Failed to close connection object", e.getMessage(), e.getStackTrace());
            return "old";
        }

        return isNew;

    }
}

This is the exception i get in tomcat log:

09-Feb-2022 00:28:07.902 SEVERE [http-nio-0.0.0.0-8080-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/BAKCELLIVR] threw exception [An exception occurred processing [/vxml/checkisnew.jsp] at line [49]

46:         <debug:message message="checkisnew.jsp. cin_cust_id: ${cin_cust_id}"/>
47:         <debug:message message="checkisnew.jsp. cin_ani: ${cin_ani}"/>
48:         <debug:message message="checkisnew.jsp. cin_ursconnid: ${cin_ursconnid}"/>
49:         <c:set var="isnew" value="${bakcellivr:cICN(cin_cust_id, cin_ani, cin_ursconnid)}" scope="request"/>
50:         <debug:message message="checkisnew.jsp. isnew: ${isnew}"/>
51:     </c:if>
52:

Stacktrace:] with root cause
    java.lang.NullPointerException
        at java.base/java.lang.reflect.Method.invoke(Method.java:559)
        at org.apache.el.parser.AstFunction.getValue(AstFunction.java:198)
        at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
        at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:129)
        at org.apache.jsp.vxml.checkisnew_jsp._jspx_meth_c_005fset_005f6(checkisnew_jsp.java:1032)
        at org.apache.jsp.vxml.checkisnew_jsp._jspx_meth_c_005fif_005f2(checkisnew_jsp.java:860)
        at org.apache.jsp.vxml.checkisnew_jsp._jspService(checkisnew_jsp.java:161)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)

looking at stacktrace it looks like tomcat is not even calling the method and exception occures on page render phase. I've checked all input variablesthey are not null. They print in log before the jstl is called and they have values. Dont't know where to dig.


来源: stackexchange

问:
TTF_RenderText locks up
Writing a SDL program using TRueType fonts. I call TTF_Init() to initialize TTF and open my font with TTF_OpenFont( name, size ).

I have a routine that inserts null terminated text strings into a listbox using
sdl_surface=TTF_RenderText_Solid( font, data, sdl_color). This routine works for I then blit the surface to my listbox surface and delete the one returned from RenderText. I do this over and over again and it works most of the time. But on the 11th string entered it hangs. No errors just locks up the program. I know this is not much to go on but I am stuck.

答: Yes, as it turns out the problem was in another routine with memory allocation offsets. Once I found that this went away.</p>

ContentLicense: CC BY-SA 3.0

Title: TTF_RenderText locks up


问:
Terraform - data resource access in AWS cross account
I writing a terraform script and I want to use data resource to get Kafka MSK related resources, such as Kafka cluster ARN, Kafka Topic ARN.

for example -

```<code>data "aws_s3_bucket" "content_bucket" {
  bucket = "nameof-bucket-from-another-account"
}
</code>```

and I'm wondering if terraform supports getting such resources cross AWS accounts?

I searched but could not find anything about it.

答:
Terraform itself does not care or know about accounts.

Whether the AWS provider supports this depends on the actual resource:

it works for S3 buckets because buckets are not account-scoped but have a global ARN and therefore the name is enough to basically address cross-account

e.g. KMS keys work if you specify the full ARN

e.g. IAM roles do not work because they fundamentally do not support cross-account access

Even for resources that do not themselves support cross-account access you can have a terraform config with multiple AWS providers with different account configs.

Obviously all this only works if the entity executing terraform has the proper IAM permissions do retrieve the targeted information / access the targeted resource.

ContentLicense: CC BY-SA 4.0

Body:
I writing a terraform script and I want to use data resource to get Kafka MSK related resources, such as Kafka cluster ARN, Kafka Topic ARN.

for example -

data "aws_s3_bucket" "content_bucket" {
  bucket = "nameof-bucket-from-another-account"
}

and I'm wondering if terraform supports getting such resources cross AWS accounts?

I searched but could not find anything about it.


问:
How does one sort dictionary values?
Is there a way to sort (and return) a dictionary by multiple values? The below returns the values in a list. I'd like to improve on the below and also return the keys so that the returned data structure is a sorted dictionary.</p>
```<code>df = pd.DataFrame([[-1,1,-1,3,1,2]], index =
                     pd.date_range(start = '2022-02-07', periods =1, name = 'Date'))

df.columns = pd.MultiIndex.from_tuples((("IINN", "s"), ("IINN", "count"),
                     ("GII", "s"), ("GII","count"),("HCM","s"), ("HCM", "count")))

dct={c:df[c] for c in df.columns.levels[0]}

sorted(dct.values(),key = lambda item: (item['s'][-1],item['count'][-1]), reverse=True)

[            s  count
 Date
 2022-02-07  1      2,
             s  count
 Date
 2022-02-07 -1      3,
             s  count
 Date
 2022-02-07 -1      1]
</code>```

答:
from operator import itemgetter
from typing import Any, Iterator

DCT = {
    'foo': 1,
    'bar': 2,
    'spamm': 0
}

print(DCT)

def sort_by_values(dct: dict) -> Iterator[tuple[Any, Any]]:
    """Yields dict items sorted by their values."""

    for key, value in sorted(dct.items(), key=itemgetter(1)):
        yield key, value

for key, value in sort_by_values(DCT):
    print(key, value)

print(dict(sort_by_values(DCT)))
```

Title: How does one sort dictionary values?

Body:
Is there a way to sort (and return) a dictionary by multiple values? The below returns the values in a list. I'd like to improve on the below and also return the keys so that the returned data structure is a sorted dictionary.

df = pd.DataFrame([[-1,1,-1,3,1,2]], index =
                     pd.date_range(start = '2022-02-07', periods =1, name = 'Date'))

df.columns = pd.MultiIndex.from_tuples((("IINN", "s"), ("IINN", "count"),
                     ("GII", "s"), ("GII","count"),("HCM","s"), ("HCM", "count")))

dct={c:df[c] for c in df.columns.levels[0]}

sorted(dct.values(),key = lambda item: (item['s'][-1],item['count'][-1]), reverse=True)

[            s  count
 Date
 2022-02-07  1      2,
             s  count
 Date
 2022-02-07 -1      3,
             s  count
 Date
 2022-02-07 -1      1]


问:
Making a right triangle by arrays in python using loops and auto filling the arrays
I want to write a program that can help me to calculate some values using python.
The main idea is I want to make a table, which is only half of the cells are having value. (That means I want to make a triangle) So, the triangle I want to make is like this format.

```<code>12345
1234
123
12
1
</code>```

But, things are not that easy. Please see the table below. (Also same as picture 1)

```<code>6.00 6.45 6.80 7.10 7.36 7.56 7.77
6.90 7.20 7.47 7.70 7.88 8.06
7.50 7.75 7.97 8.12 8.30
8.00 8.20 8.33 8.50
8.40 8.50 8.67
8.60 8.80
9.00
</code>```

In the above triangle, each of the rows is make from the previous row by a certain formula. Please refer to the picture 2 and picture 3.

Also, please note that in the above triangle, each of the cells was multiplied by 100. For example, the 6.00 in the upper left corner is 6% (0.06) indeed. << Please do NOT multiplied the figures by 100 in my program, because it is just an accident here for demonstration.

Okay. So, I want to make a program that as long as I input the first row, then the program will calculate and show the remaining rows for me. (That means showing the whole triangle)

Below is my code. Please have a look. I have tried to write a frame, but there are two problems that I encounter.

I don't know how to automatically fill my other arrays(the other rows) base on the first arrays (the first row) that I input in the program.

I keep receiving the error of "IndexError: list index out of range" when I try to run my programme.

Here are my codes

```<code>array1 = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]         #This is the initial array that I input
array2 = []            #This should be the output after the first iteration, I hope that my programme can auto fill the remaining arrays (including this array) after I run my programme
array3 = []            #This is a blank array waiting for auto fill after I run my program
array4 = []            #This is a blank array waiting for auto fill after I run my program
array5 = []            #This is a blank array waiting for auto fill after I run my program
array6 = []            #This is a blank array waiting for auto fill after I run my program
array7 = []            #This is a blank array waiting for auto fill after I run my program
array8 = []            #This is a blank array waiting for auto fill after I run my program

r = 0  # Set the initial position for the table that I want to make, and this is similar to the x-asis. Please refer to picture 2.
s = 1  # Set the initial position for the table that I want to make, and this is similar to the y-asis. Please refer to picture 2.

def SpotRateForcast(i,j,k):
    global r
    global s

    while (r <= len(k)):                                     # I try to make the first loop here
        s = 1                                                # Reset the value when the first row is completed such that the second loop can work in the second row
        while (s <= len(k)):                                 # this is the second loop to determine when to stop in the each row
            x = ((((1 + k[j - 1])**j) / ((1 + k[i - 1])**i))**(1/(j-i))) - 1  #Calculate the value by the certain formula
            print(("%.4f" % round(x,4)), end=' ,  ')         #Print the value up to 4 decimal places
            s += 1                                           #Record one value is calculated and done
            SpotRateForcast(i,j+1,k)                         #Start to calculate and print the next value
        r += 1                                               # Switch to the next row when the second loop is finished

SpotRateForcast(r,s,array1)                                  #The code to run the program
</code>```

Thank you for reading my question.
I would like to ask someone to finish the programme for me. As you can see, my coding maybe bad because I am a newbie in programming. But I already tried my best to do everything I am able to do.

I do not mind your edit my codes. It is even better if you can write a new codes for me. And I can learn how to write better codes from you.

Lastly, I have one more request. Please add many many comments in the codes you wrote otherwise I may not able to understand what you wrote(I am a beginner). Thank you very much!

答:
```<code>array=[[0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]]

n = len(array[0])

#outer loop

for i in range(1, n):

       #append new row

    array.append([])

    for j in range(n-i):
        #i dont understand your calculations but they'd stand
        array[i][j] = #here
</code>```

Body:
I want to write a program that can help me to calculate some values using python.
The main idea is I want to make a table, which is only half of the cells are having value. (That means I want to make a triangle) So, the triangle I want to make is like this format.

12345
1234
123
12
1

But, things are not that easy. Please see the table below. (Also same as picture 1)

6.00 6.45 6.80 7.10 7.36 7.56 7.77
6.90 7.20 7.47 7.70 7.88 8.06
7.50 7.75 7.97 8.12 8.30
8.00 8.20 8.33 8.50
8.40 8.50 8.67
8.60 8.80
9.00

In the above triangle, each of the rows is make from the previous row by a certain formula. Please refer to the picture 2 and picture 3.

Also, please note that in the above triangle, each of the cells was multiplied by 100. For example, the 6.00 in the upper left corner is 6% (0.06) indeed. << Please do NOT multiplied the figures by 100 in my program, because it is just an accident here for demonstration.

Okay. So, I want to make a program that as long as I input the first row, then the program will calculate and show the remaining rows for me. (That means showing the whole triangle)

Below is my code. Please have a look. I have tried to write a frame, but there are two problems that I encounter.

I don't know how to automatically fill my other arrays(the other rows) base on the first arrays (the first row) that I input in the program.

I keep receiving the error of "IndexError: list index out of range" when I try to run my programme.

Here are my codes

array1 = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]         #This is the initial array that I input
array2 = []            #This should be the output after the first iteration, I hope that my programme can auto fill the remaining arrays (including this array) after I run my programme
array3 = []            #This is a blank array waiting for auto fill after I run my program
array4 = []            #This is a blank array waiting for auto fill after I run my program
array5 = []            #This is a blank array waiting for auto fill after I run my program
array6 = []            #This is a blank array waiting for auto fill after I run my program
array7 = []            #This is a blank array waiting for auto fill after I run my program
array8 = []            #This is a blank array waiting for auto fill after I run my program

r = 0  # Set the initial position for the table that I want to make, and this is similar to the x-asis. Please refer to picture 2.
s = 1  # Set the initial position for the table that I want to make, and this is similar to the y-asis. Please refer to picture 2.

def SpotRateForcast(i,j,k):
    global r
    global s

    while (r <= len(k)):                                     # I try to make the first loop here
        s = 1                                                # Reset the value when the first row is completed such that the second loop can work in the second row
        while (s <= len(k)):                                 # this is the second loop to determine when to stop in the each row
            x = ((((1 + k[j - 1])**j) / ((1 + k[i - 1])**i))**(1/(j-i))) - 1  #Calculate the value by the certain formula
            print(("%.4f" % round(x,4)), end=' ,  ')         #Print the value up to 4 decimal places
            s += 1                                           #Record one value is calculated and done
            SpotRateForcast(i,j+1,k)                         #Start to calculate and print the next value
        r += 1                                               # Switch to the next row when the second loop is finished

SpotRateForcast(r,s,array1)                                  #The code to run the program

Thank you for reading my question.
I would like to ask someone to finish the programme for me. As you can see, my coding maybe bad because I am a newbie in programming. But I already tried my best to do everything I am able to do.

I do not mind your edit my codes. It is even better if you can write a new codes for me. And I can learn how to write better codes from you.

Lastly, I have one more request. Please add many many comments in the codes you wrote otherwise I may not able to understand what you wrote(I am a beginner). Thank you very much!


问:
SwiftUI using ForEach and onTapGesture to update selected element causing crash
I have some code that I am using, the idea is that the user selects a card they like and a sheet is presented to show more information about that card. The problem is, if I don't have the Text(selectedCard?.name ?? "Not selected") line, it crashes. I was just wondering what I don't understand about Swift/SwiftUI that is making this happen and how I could fix it (as I don't want it to say what card they have selected).

It is where the sheet comes to be presented that it crashes as it finds a nil value for selectedCard but selectedCard should not be nil when that runs. If I add the seemingly unrelated line to display which card has been selected, the value is set fine and it does not crash.

Full code:

```<code>import SwiftUI

struct CardsView: View {

    @State private var cardlist = [Cards]()
    @State private var showingSheet = false
    @State private var selectedCard: Cards?

    let columns = [
        GridItem(.adaptive(minimum: 120))
    ]

    var body: some View {
        NavigationView() {
            ScrollView (.vertical, showsIndicators: false) {
                Text("View our full collection of cards below:")
                    .padding(.leading, 20)
                    .frame(maxWidth: .infinity, alignment: .leading)

                Text(selectedCard?.name ?? "Not selected") // This line stops it from crashing

                    LazyVGrid(columns: columns, spacing: 10) {
                        ForEach(cardlist, id: \.name) { thecard in
                            CardItem(card: thecard)
                                .onTapGesture {
                                    selectedCard = thecard
                                    showingSheet.toggle()
                                }
                        }

                    }
                    .padding([.leading, .trailing])

                Spacer()
            }

            .navigationTitle("Cards")
        }

        .sheet(isPresented: $showingSheet) {
            SpecificCardView(card: selectedCard!)
        }

        .onAppear() {
            loadCards()
        }

    }

    func loadCards() {
        ...
    }

}
</code>```

答:
Your problem is likely due to the view diffing algorithm having a different outcome if you have the text value present, since that would be a difference in the root view. Since you have two pieces of state that represent the sheet, and you are force unwrapping one of them, you're leaving yourself open to danger.

You should get rid of showingSheet, then use the item binding of sheet instead. Make Cards conform to Identifiable, then rewrite the sheet modifier as:

```<code>.sheet(item: $selectedCard) { SpecificCardView(card: $0) }
</code>```

This will also reset your selected card to nil when the sheet is dismissed.

Body:
I have some code that I am using, the idea is that the user selects a card they like and a sheet is presented to show more information about that card. The problem is, if I don't have the Text(selectedCard?.name ?? "Not selected") line, it crashes. I was just wondering what I don't understand about Swift/SwiftUI that is making this happen and how I could fix it (as I don't want it to say what card they have selected).

It is where the sheet comes to be presented that it crashes as it finds a nil value for selectedCard but selectedCard should not be nil when that runs. If I add the seemingly unrelated line to display which card has been selected, the value is set fine and it does not crash.

Full code:

import SwiftUI

struct CardsView: View {

    @State private var cardlist = [Cards]()
    @State private var showingSheet = false
    @State private var selectedCard: Cards?

    let columns = [
        GridItem(.adaptive(minimum: 120))
    ]

    var body: some View {
        NavigationView() {
            ScrollView (.vertical, showsIndicators: false) {
                Text("View our full collection of cards below:")
                    .padding(.leading, 20)
                    .frame(maxWidth: .infinity, alignment: .leading)

                Text(selectedCard?.name ?? "Not selected") // This line stops it from crashing

                    LazyVGrid(columns: columns, spacing: 10) {
                        ForEach(cardlist, id: \.name) { thecard in
                            CardItem(card: thecard)
                                .onTapGesture {
                                    selectedCard = thecard
                                    showingSheet.toggle()
                                }
                        }

                    }
                    .padding([.leading, .trailing])

                Spacer()
            }

            .navigationTitle("Cards")
        }

        .sheet(isPresented: $showingSheet) {
            SpecificCardView(card: selectedCard!)
        }

        .onAppear() {
            loadCards()
        }

    }

    func loadCards() {
        ...
    }

}

Body:
Your problem is likely due to the view diffing algorithm having a different outcome if you have the text value present, since that would be a difference in the root view. Since you have two pieces of state that represent the sheet, and you are force unwrapping one of them, you're leaving yourself open to danger.

You should get rid of showingSheet, then use the item binding of sheet instead. Make Cards conform to Identifiable, then rewrite the sheet modifier as:

.sheet(item: $selectedCard) { SpecificCardView(card: $0) }

This will also reset your selected card to nil when the sheet is dismissed.


问:
How to select every (1918/1000)th record from SQL?
I have this SQL to select 1000 from 2000 records.

```<code>(SELECT
        @rownum := @rownum + 1 AS rownum,
        data.*,
        IF(@rownum % 2 = 1, '1', '2') AS grp,
</code>```

But now I am required to select 1000 from 1918 using the same notation, order.

That means I need to do instead of 2 a value of 1.918

How to do that via the SQL?

答:
```<code>SELECT
  @rownum := @rownum + 1 AS rownum,
  data.*,
  IF( FLOOR( @rownum % (1918.0/1000.0) ) = 0, '1', '2') AS grp
</code>```

Body:
I have this SQL to select 1000 from 2000 records.

(SELECT
        @rownum := @rownum + 1 AS rownum,
        data.*,
        IF(@rownum % 2 = 1, '1', '2') AS grp,

But now I am required to select 1000 from 1918 using the same notation, order.

That means I need to do instead of 2 a value of 1.918

How to do that via the SQL?


问:
Determine if the string is palindrome
This function takes a string as input and returns True if string is palindrome and
False otherwise. A palindrome is a symmetric sequence of characters, reading
the same forward and backward.
For example: radar, anna, mom, dad, …</p>

答:
You can do this like the below:</p>
```<code>def is_palindrome(phrase):
    string = ""
    for char in phrase:
        if char.isalnum():
            string += char
    print(string)
    return string[::-1].casefold() == string.casefold()

word = input("Please enter a word to check: ")
if is_palindrome(word):
    print("'{}' is a palindrome".format(word))
else:
    print("'{}' is not a palindrome".format(word))
</code>```

Title: Determine if the string is palindrome

Body:
You can do this like the below:

def is_palindrome(phrase):
    string = ""
    for char in phrase:
        if char.isalnum():
            string += char
    print(string)
    return string[::-1].casefold() == string.casefold()

word = input("Please enter a word to check: ")
if is_palindrome(word):
    print("'{}' is a palindrome".format(word))
else:
    print("'{}' is not a palindrome".format(word))


问:
Check if powerhshell was started using "run as administrator"
i found an old question on this topic. However, i am not clear.
I have a script that checks, if PS has been run using "run as administrator" and if yes it does the job, otherweise it prompts that the script must be run as administrator.

```<code>$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CheckforAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
</code>```

it gives true or false. I have if-else statement that does the rest.

```<code>    If($CheckforAdmin -eq 'True'){
        $MSG = ""
        If(($EventLogCheck -ne $EventLog) -or ($EventLogsourceCheck -ne 'True')){
            New-EventLog -LogName $EventLog -Source $EventLogSource -ErrorAction Stop
            $MSG = "$env:USERNAME has successfully created a new eventlog named $EventLog with the source $EventLogSource."
            Write-EventLog -logname $PiEventLog -source  $PiEventLogSource -eventID 1021 -entrytype Information -message $MSG
        }
        else{
            $MSG = "$env:USERNAME tried to create an EventLog named $EventLog with the source $EventLogSource. `nSince the EventLog and the source already exist, this step was aborted."
            Write-EventLog -logname $EventLog -source  $EventLogSource -eventID 1021 -entrytype Information -message $MSG
        }

#           Wenn der Parameter Silent auf true gesetzt ist, wird das Skript nach der Erstellung des EventLogs unmittelbar beendet.
        if($install -eq $true){
            Write-Host $MSG
            Read-Host 'Press any key to continue...'
        }
        exit
    }
    else{
        Write-Host "The Script must be executed as admin"
     [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
        [System.Windows.Forms.MessageBox]::Show('Installation: The script must be run as administrator in order to create the event log', 'Run as admin')
        exit
    }
</code>```

It works well, if i am logged in with a normal user. But on my server where i want to run the script, i log in as domain administrator. Even if if run the script just double clicking on it, it runs instead of prompting that the script must be run using "run as administrator".

I red the articles about UAC (User Account control) and as far as i understood: running a script using "run as administor" is actually the same as logging in as domain administrator and double clicking on the script.

Is there any other way to check, if the script was run using "run as administrator" option that shows up if u right click on powershell (doesn't matter, whether you are logged in as admin or not) ?

答:
Original comment:

How did you implement the prompt? Because obviously, this part only returns $true or $false. I suppose a way to work around this would be something like

```<code>PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""PS_Script_Path&Name.ps1""' -Verb RunAs}"
</code>```

To call the script as admin again, if it wasnt before.

Newly added:

Additionally, you have an error in your if-statement. To compare to boolean, you want to have your if-statement like following:

```<code> If($CheckforAdmin -eq $true){
</code>```

Comparing against strings can lead to problems. Otherwise I cannot locate any other errors.

Body:
i found an old question on this topic. However, i am not clear.
I have a script that checks, if PS has been run using "run as administrator" and if yes it does the job, otherweise it prompts that the script must be run as administrator.

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CheckforAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

it gives true or false. I have if-else statement that does the rest.

    If($CheckforAdmin -eq 'True'){
        $MSG = ""
        If(($EventLogCheck -ne $EventLog) -or ($EventLogsourceCheck -ne 'True')){
            New-EventLog -LogName $EventLog -Source $EventLogSource -ErrorAction Stop
            $MSG = "$env:USERNAME has successfully created a new eventlog named $EventLog with the source $EventLogSource."
            Write-EventLog -logname $PiEventLog -source  $PiEventLogSource -eventID 1021 -entrytype Information -message $MSG
        }
        else{
            $MSG = "$env:USERNAME tried to create an EventLog named $EventLog with the source $EventLogSource. `nSince the EventLog and the source already exist, this step was aborted."
            Write-EventLog -logname $EventLog -source  $EventLogSource -eventID 1021 -entrytype Information -message $MSG
        }

#           Wenn der Parameter Silent auf true gesetzt ist, wird das Skript nach der Erstellung des EventLogs unmittelbar beendet.
        if($install -eq $true){
            Write-Host $MSG
            Read-Host 'Press any key to continue...'
        }
        exit
    }
    else{
        Write-Host "The Script must be executed as admin"
     [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
        [System.Windows.Forms.MessageBox]::Show('Installation: The script must be run as administrator in order to create the event log', 'Run as admin')
        exit
    }

It works well, if i am logged in with a normal user. But on my server where i want to run the script, i log in as domain administrator. Even if if run the script just double clicking on it, it runs instead of prompting that the script must be run using "run as administrator".

I red the articles about UAC (User Account control) and as far as i understood: running a script using "run as administor" is actually the same as logging in as domain administrator and double clicking on the script.

Is there any other way to check, if the script was run using "run as administrator" option that shows up if u right click on powershell (doesn't matter, whether you are logged in as admin or not) ?

Body:
Original comment:

How did you implement the prompt? Because obviously, this part only returns $true or $false. I suppose a way to work around this would be something like

PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""PS_Script_Path&Name.ps1""' -Verb RunAs}"

To call the script as admin again, if it wasnt before.

Newly added:

Additionally, you have an error in your if-statement. To compare to boolean, you want to have your if-statement like following:

 If($CheckforAdmin -eq $true){

Comparing against strings can lead to problems. Otherwise I cannot locate any other errors.


问:
Convert Number into Word in C# window
I am trying to Convert Number into Word in C# windows. My code is :

```<code>namespace Num2Text
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox2.Text = changeToWords(textBox1.Text, false);
        }
        public String changeNumericToWords(double numb)
        {
            String num = numb.ToString();
            return changeToWords(num, false);
        }
        public String changeCurrencyToWords(String numb)
        {
            return changeToWords(numb, true);
        }
        public String changeNumericToWords(String numb)
        {
            return changeToWords(numb, false);
        }
        public String changeCurrencyToWords(double numb)
        {
            return changeToWords(numb.ToString(), true);
        }
        private String changeToWords(String numb, bool isCurrency)
        {
            String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
            String endStr = (isCurrency) ? ("Only") : ("Only"); //-- Only--
            try
            {
                int decimalPlace = numb.IndexOf(".");
                if (decimalPlace > 0)
                {
                    wholeNo = numb.Substring(0, decimalPlace);
                    points = numb.Substring(decimalPlace + 1);
                    if (Convert.ToInt32(points) > 0)
                    {
                        andStr = (isCurrency) ? ("and") : ("Point");// just to separate whole numbers from points/cents
                        endStr = (isCurrency) ? ("Cents " + endStr) : ("Only"); //--Paisa Only--
                        pointStr = translateCents(points);
                    }
                }
                val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
            }
            catch { ;}
            return val;
        }
        private String translateWholeNumber(String number)
        {
            string word = " "; //--Taka--
            try
            {
                bool beginsZero = false;//tests for 0XX
                bool isDone = false;//test if already translated
                double dblAmt = (Convert.ToDouble(number));
                //if ((dblAmt > 0) && number.StartsWith("0"))
                if (dblAmt > 0)
                {//test for zero or digit zero in a nuemric
                    beginsZero = number.StartsWith("0");
                    int numDigits = number.Length;
                    int pos = 0;//store digit grouping
                    String place = " ";//digit grouping name:hundres,thousand,etc...
                    switch (numDigits)
                    {
                        case 1://ones' range
                            word = ones(number);
                            isDone = true;
                            break;
                        case 2://tens' range
                            word = tens(number);
                            isDone = true;
                            break;
                        case 3://hundreds' range
                            pos = (numDigits % 3) + 1;
                            place = " Hundred ";
                            break;
                        case 4://thousands' range
                        case 5:
                        case 6:
                            pos = (numDigits % 4) + 1;//
                            place = " Thousand ";
                            break;
                        case 7://millions' range
                        case 8:
                        case 9:
                            pos = (numDigits % 7) + 1;
                            place = " Million ";
                            break;
                        case 10://Billions's range
                            case 11:
                            case 12:
                            pos = (numDigits % 10) + 1;
                            place = " Billion ";
                            break;
                        //add extra case options for anything above Billion...
                        default:
                            isDone = true;
                            break;
                    }
                    if (!isDone)
                    {//if transalation is not done, continue...(Recursion comes in now!!)
                        word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
                        //check for trailing zeros
                        if (beginsZero) word = "  " + word.Trim();//-----"and"---
                    }
                    //ignore digit grouping names
                    if (word.Trim().Equals(place.Trim())) word = "";
                }
            }
            catch { ;}
            return word.Trim();
        }
        private String tens(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = null;
            switch (digt)
            {
                case 10:
                    name = "Ten";
                    break;
                case 11:
                    name = "Eleven";
                    break;
                case 12:
                    name = "Twelve";
                    break;
                case 13:
                    name = "Thirteen";
                    break;
                case 14:
                    name = "Fourteen";
                    break;
                case 15:
                    name = "Fifteen";
                    break;
                case 16:
                    name = "Sixteen";
                    break;
                case 17:
                    name = "Seventeen";
                    break;
                case 18:
                    name = "Eighteen";
                    break;
                case 19:
                    name = "Nineteen";
                    break;
                case 20:
                    name = "Twenty";
                    break;
                case 30:
                    name = "Thirty";
                    break;
                case 40:
                    name = "Fourty";
                    break;
                case 50:
                    name = "Fifty";
                    break;
                case 60:
                    name = "Sixty";
                    break;
                case 70:
                    name = "Seventy";
                    break;
                case 80:
                    name = "Eighty";
                    break;
                case 90:
                    name = "Ninety";
                    break;
                default:
                    if (digt > 0)
                    {
                        name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
                    }
                    break;
            }
            return name;
        }
        private String ones(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = "";
            switch (digt)
            {
                case 1:
                    name = "One";
                    break;
                case 2:
                    name = "Two";
                    break;
                case 3:
                    name = "Three";
                    break;
                case 4:
                    name = "Four";
                    break;
                case 5:
                    name = "Five";
                    break;
                case 6:
                    name = "Six";
                    break;
                case 7:
                    name = "Seven";
                    break;
                case 8:
                    name = "Eight";
                    break;
                case 9:
                    name = "Nine";
                    break;
            }
            return name;
        }
        private String translateCents(String cents)
        {
            String cts = "", digit = "", engOne = "";
            for (int i = 0; i < cents.Length; i++)
            {
                digit = cents[i].ToString();
                if (digit.Equals("0"))
                {
                    engOne = "Zero";
                }
                else
                {
                    engOne = ones(digit);
                }
                cts += " " + engOne;
            }
            return cts;
        }
</code>```

It working to convert (from One to Billion). But there is a error ,when Hundred Position is null. <<>>

what is the right code ?

答:
This will convert number to word 0 - 9999.</p>
```<code>public static string word(int number)
{
    string[] ones = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
    string[] tens = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    string word = "";
    if (number == 0)
    {
        Console.WriteLine(ones[number]);
        word += ones[number];
    }
    if (number > 0 && number <=10)
    {
        Console.WriteLine(ones[number]);
        word += ones[number];
    }
    if(number > 10 && number <20)
    {
        Console.WriteLine(ones[number]);
        word += ones[number];
    }
    if (number >= 20 && number < 100)
    {
        int last = Math.Abs(number) % 10;
        if(last > 0)
        {
            Console.WriteLine(tens[number / 10] + " " + ones[last]);
            word += tens[number / 10] + " " + ones[last];
        }
        else
        {
            Console.WriteLine(tens[number / 10]);
            word += tens[number / 10];
        }

    }
    if (number >= 100 && number <= 9999)
    {
        int spliter = Math.Abs(number / 10) % 10;
        if(number.ToString().Length == 2) {
            if ((spliter / 100) % 10 > 10)
            {
                int first = number / 100;
                int second = Math.Abs(number / 10) % 10;
                word += ones[first] + " hundred " + tens[second];
                Console.WriteLine(word);
            }
            else
            {
                int first = number / 100;
                int second = Math.Abs(number / 10) % 10;
                word += ones[first] + " hundred " + tens[second] + " " + ones[Math.Abs(number) % 10];
                Console.WriteLine(word);
            }
        }
        else if (number.ToString().Length >= 3)
        {
            if ((number / 1000) % 10 > 0)
            {
                int first = number / 1000;
                int secondDigit = Math.Abs(number / 100) % 10;
                if (secondDigit > 0)
                {
                    int thirdDigit = Math.Abs(number / 100) % 10;
                    int lastDigit = Math.Abs(number / 1000) / 10;
                    if (thirdDigit > 0) {
                        if (lastDigit == 0)
                        {
                            // if number contains 0 at second to the last index
                            int last2Digit = Math.Abs(number) % 10;
                            int secondToTheLast = Math.Abs(number) / 10 % 10;
                            int thirdToTheLast = Math.Abs(number) % 100;
                            int lastTwoDigits = Math.Abs(number) % 100;
                            if (last2Digit > 0 && secondToTheLast > 0)
                            {
                                int lastTwoDigit = Math.Abs(number) % 100 / 10;
                                int last = Math.Abs(thirdToTheLast) % 10;

                                if (lastTwoDigits > 0 && lastTwoDigits < 20)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + ones[lastTwoDigits];
                                    Console.WriteLine(word);
                                }
                                else if(lastTwoDigits > 19)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[lastTwoDigit] + " " + ones[last];
                                    Console.WriteLine(word);
                                }

                            }
                            else
                            {
                                if(lastTwoDigits == 00)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred ";
                                    Console.WriteLine(word);
                                }
                                else
                                {
                                    if(lastTwoDigits < 10)
                                    {
                                        word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[secondToTheLast] + " " + ones[last2Digit];
                                        Console.WriteLine(word);
                                    }
                                    else
                                    {
                                        word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[secondToTheLast];
                                        Console.WriteLine(word);
                                    }

                                }

                            }

                        }
                        else
                        {
                            word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[thirdDigit] + " " + ones[Math.Abs(number / 100) % 10];
                            Console.WriteLine(word);
                        }

                    }
                    else
                    {

                        word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[thirdDigit] + ones[Math.Abs(number) % 100];
                        Console.WriteLine(word);
                    }

                }
                else
                {
                    if (
                        number == 1000
                        || number == 2000
                        || number == 3000
                        || number == 4000
                        || number == 5000
                        || number == 6000
                        || number == 7000
                        || number == 8000
                        || number == 9000
                     )
                    {
                        word += ones[number / 1000] + " thousand ";
                        Console.WriteLine(word);
                    }
                    else
                    {
                        int firstDigit = Math.Abs(Math.Abs(number) % 100) / 10;
                        int lastTwoDigit = Math.Abs(number)%100;
                        int firstDig = Math.Abs(lastTwoDigit / 10) % 100;
                        int last = Math.Abs(lastTwoDigit) % 10;
                        if (Math.Abs(number) % 10 == 0)
                        {
                            word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + tens[firstDigit];
                            Console.WriteLine(word);
                        }
                        else
                        {
                            if(lastTwoDigit > 0 && lastTwoDigit < 20)
                            {
                                if(lastTwoDigit < 10)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + ones[number / 100 % 10] + " " + ones[lastTwoDigit];
                                    Console.WriteLine(word);
                                }
                                else
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + ones[lastTwoDigit];
                                    Console.WriteLine(word);
                                }

                            }
                            else if(lastTwoDigit > 19)
                            {
                                word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + tens[firstDig] + " "+ ones[last];
                                Console.WriteLine(word);
                            }

                        }

                    }

                }

            }
            else
            {
                int first = Math.Abs(number / 100) % 10;
                int middle = Math.Abs(number / 10) % 10;
                int last = Math.Abs(number) % 10;
                int last2Digit = Math.Abs(number) % 100;
                Console.WriteLine(middle);
                if (last2Digit > 0 && last2Digit < 20)
                {
                    if(last2Digit < 10)
                    {
                        word += ones[first] + " hundred " + tens[middle] + " " + ones[last2Digit];
                        Console.WriteLine(word);
                    }
                    else
                    {
                        word += ones[first] + " hundred " + ones[last2Digit];
                        Console.WriteLine(word);
                    }

                }
                else if (last2Digit > 19)
                {
                    word += ones[first] + " hundred " + tens[middle] + " " + ones[last];
                    Console.WriteLine(word);
                }
                else
                {
                    word += ones[first] + " hundred " + tens[middle] + ones[last];
                    Console.WriteLine(word);
                }
            }
        }
    }
    else if (number >= 10000)
    {
        Console.WriteLine("Max number is 9999");
    }

    return word;

}
</code>```

Title: Convert Number into Word in C# window

Body:
I am trying to Convert Number into Word in C# windows. My code is :

namespace Num2Text
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox2.Text = changeToWords(textBox1.Text, false);
        }
        public String changeNumericToWords(double numb)
        {
            String num = numb.ToString();
            return changeToWords(num, false);
        }
        public String changeCurrencyToWords(String numb)
        {
            return changeToWords(numb, true);
        }
        public String changeNumericToWords(String numb)
        {
            return changeToWords(numb, false);
        }
        public String changeCurrencyToWords(double numb)
        {
            return changeToWords(numb.ToString(), true);
        }
        private String changeToWords(String numb, bool isCurrency)
        {
            String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
            String endStr = (isCurrency) ? ("Only") : ("Only"); //-- Only--
            try
            {
                int decimalPlace = numb.IndexOf(".");
                if (decimalPlace > 0)
                {
                    wholeNo = numb.Substring(0, decimalPlace);
                    points = numb.Substring(decimalPlace + 1);
                    if (Convert.ToInt32(points) > 0)
                    {
                        andStr = (isCurrency) ? ("and") : ("Point");// just to separate whole numbers from points/cents
                        endStr = (isCurrency) ? ("Cents " + endStr) : ("Only"); //--Paisa Only--
                        pointStr = translateCents(points);
                    }
                }
                val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
            }
            catch { ;}
            return val;
        }
        private String translateWholeNumber(String number)
        {
            string word = " "; //--Taka--
            try
            {
                bool beginsZero = false;//tests for 0XX
                bool isDone = false;//test if already translated
                double dblAmt = (Convert.ToDouble(number));
                //if ((dblAmt > 0) && number.StartsWith("0"))
                if (dblAmt > 0)
                {//test for zero or digit zero in a nuemric
                    beginsZero = number.StartsWith("0");
                    int numDigits = number.Length;
                    int pos = 0;//store digit grouping
                    String place = " ";//digit grouping name:hundres,thousand,etc...
                    switch (numDigits)
                    {
                        case 1://ones' range
                            word = ones(number);
                            isDone = true;
                            break;
                        case 2://tens' range
                            word = tens(number);
                            isDone = true;
                            break;
                        case 3://hundreds' range
                            pos = (numDigits % 3) + 1;
                            place = " Hundred ";
                            break;
                        case 4://thousands' range
                        case 5:
                        case 6:
                            pos = (numDigits % 4) + 1;//
                            place = " Thousand ";
                            break;
                        case 7://millions' range
                        case 8:
                        case 9:
                            pos = (numDigits % 7) + 1;
                            place = " Million ";
                            break;
                        case 10://Billions's range
                            case 11:
                            case 12:
                            pos = (numDigits % 10) + 1;
                            place = " Billion ";
                            break;
                        //add extra case options for anything above Billion...
                        default:
                            isDone = true;
                            break;
                    }
                    if (!isDone)
                    {//if transalation is not done, continue...(Recursion comes in now!!)
                        word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
                        //check for trailing zeros
                        if (beginsZero) word = "  " + word.Trim();//-----"and"---
                    }
                    //ignore digit grouping names
                    if (word.Trim().Equals(place.Trim())) word = "";
                }
            }
            catch { ;}
            return word.Trim();
        }
        private String tens(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = null;
            switch (digt)
            {
                case 10:
                    name = "Ten";
                    break;
                case 11:
                    name = "Eleven";
                    break;
                case 12:
                    name = "Twelve";
                    break;
                case 13:
                    name = "Thirteen";
                    break;
                case 14:
                    name = "Fourteen";
                    break;
                case 15:
                    name = "Fifteen";
                    break;
                case 16:
                    name = "Sixteen";
                    break;
                case 17:
                    name = "Seventeen";
                    break;
                case 18:
                    name = "Eighteen";
                    break;
                case 19:
                    name = "Nineteen";
                    break;
                case 20:
                    name = "Twenty";
                    break;
                case 30:
                    name = "Thirty";
                    break;
                case 40:
                    name = "Fourty";
                    break;
                case 50:
                    name = "Fifty";
                    break;
                case 60:
                    name = "Sixty";
                    break;
                case 70:
                    name = "Seventy";
                    break;
                case 80:
                    name = "Eighty";
                    break;
                case 90:
                    name = "Ninety";
                    break;
                default:
                    if (digt > 0)
                    {
                        name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
                    }
                    break;
            }
            return name;
        }
        private String ones(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = "";
            switch (digt)
            {
                case 1:
                    name = "One";
                    break;
                case 2:
                    name = "Two";
                    break;
                case 3:
                    name = "Three";
                    break;
                case 4:
                    name = "Four";
                    break;
                case 5:
                    name = "Five";
                    break;
                case 6:
                    name = "Six";
                    break;
                case 7:
                    name = "Seven";
                    break;
                case 8:
                    name = "Eight";
                    break;
                case 9:
                    name = "Nine";
                    break;
            }
            return name;
        }
        private String translateCents(String cents)
        {
            String cts = "", digit = "", engOne = "";
            for (int i = 0; i < cents.Length; i++)
            {
                digit = cents[i].ToString();
                if (digit.Equals("0"))
                {
                    engOne = "Zero";
                }
                else
                {
                    engOne = ones(digit);
                }
                cts += " " + engOne;
            }
            return cts;
        }

It working to convert (from One to Billion). But there is a error ,when Hundred Position is null. <<>>

what is the right code ?

Body:
This will convert number to word 0 - 9999.

public static string word(int number)
{
    string[] ones = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
    string[] tens = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    string word = "";
    if (number == 0)
    {
        Console.WriteLine(ones[number]);
        word += ones[number];
    }
    if (number > 0 && number <=10)
    {
        Console.WriteLine(ones[number]);
        word += ones[number];
    }
    if(number > 10 && number <20)
    {
        Console.WriteLine(ones[number]);
        word += ones[number];
    }
    if (number >= 20 && number < 100)
    {
        int last = Math.Abs(number) % 10;
        if(last > 0)
        {
            Console.WriteLine(tens[number / 10] + " " + ones[last]);
            word += tens[number / 10] + " " + ones[last];
        }
        else
        {
            Console.WriteLine(tens[number / 10]);
            word += tens[number / 10];
        }

    }
    if (number >= 100 && number <= 9999)
    {
        int spliter = Math.Abs(number / 10) % 10;
        if(number.ToString().Length == 2) {
            if ((spliter / 100) % 10 > 10)
            {
                int first = number / 100;
                int second = Math.Abs(number / 10) % 10;
                word += ones[first] + " hundred " + tens[second];
                Console.WriteLine(word);
            }
            else
            {
                int first = number / 100;
                int second = Math.Abs(number / 10) % 10;
                word += ones[first] + " hundred " + tens[second] + " " + ones[Math.Abs(number) % 10];
                Console.WriteLine(word);
            }
        }
        else if (number.ToString().Length >= 3)
        {
            if ((number / 1000) % 10 > 0)
            {
                int first = number / 1000;
                int secondDigit = Math.Abs(number / 100) % 10;
                if (secondDigit > 0)
                {
                    int thirdDigit = Math.Abs(number / 100) % 10;
                    int lastDigit = Math.Abs(number / 1000) / 10;
                    if (thirdDigit > 0) {
                        if (lastDigit == 0)
                        {
                            // if number contains 0 at second to the last index
                            int last2Digit = Math.Abs(number) % 10;
                            int secondToTheLast = Math.Abs(number) / 10 % 10;
                            int thirdToTheLast = Math.Abs(number) % 100;
                            int lastTwoDigits = Math.Abs(number) % 100;
                            if (last2Digit > 0 && secondToTheLast > 0)
                            {
                                int lastTwoDigit = Math.Abs(number) % 100 / 10;
                                int last = Math.Abs(thirdToTheLast) % 10;

                                if (lastTwoDigits > 0 && lastTwoDigits < 20)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + ones[lastTwoDigits];
                                    Console.WriteLine(word);
                                }
                                else if(lastTwoDigits > 19)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[lastTwoDigit] + " " + ones[last];
                                    Console.WriteLine(word);
                                }

                            }
                            else
                            {
                                if(lastTwoDigits == 00)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred ";
                                    Console.WriteLine(word);
                                }
                                else
                                {
                                    if(lastTwoDigits < 10)
                                    {
                                        word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[secondToTheLast] + " " + ones[last2Digit];
                                        Console.WriteLine(word);
                                    }
                                    else
                                    {
                                        word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[secondToTheLast];
                                        Console.WriteLine(word);
                                    }

                                }

                            }

                        }
                        else
                        {
                            word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[thirdDigit] + " " + ones[Math.Abs(number / 100) % 10];
                            Console.WriteLine(word);
                        }

                    }
                    else
                    {

                        word += ones[first] + " thousand " + ones[number / 100 % 10] + " hundred " + tens[thirdDigit] + ones[Math.Abs(number) % 100];
                        Console.WriteLine(word);
                    }

                }
                else
                {
                    if (
                        number == 1000
                        || number == 2000
                        || number == 3000
                        || number == 4000
                        || number == 5000
                        || number == 6000
                        || number == 7000
                        || number == 8000
                        || number == 9000
                     )
                    {
                        word += ones[number / 1000] + " thousand ";
                        Console.WriteLine(word);
                    }
                    else
                    {
                        int firstDigit = Math.Abs(Math.Abs(number) % 100) / 10;
                        int lastTwoDigit = Math.Abs(number)%100;
                        int firstDig = Math.Abs(lastTwoDigit / 10) % 100;
                        int last = Math.Abs(lastTwoDigit) % 10;
                        if (Math.Abs(number) % 10 == 0)
                        {
                            word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + tens[firstDigit];
                            Console.WriteLine(word);
                        }
                        else
                        {
                            if(lastTwoDigit > 0 && lastTwoDigit < 20)
                            {
                                if(lastTwoDigit < 10)
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + ones[number / 100 % 10] + " " + ones[lastTwoDigit];
                                    Console.WriteLine(word);
                                }
                                else
                                {
                                    word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + ones[lastTwoDigit];
                                    Console.WriteLine(word);
                                }

                            }
                            else if(lastTwoDigit > 19)
                            {
                                word += ones[first] + " thousand " + ones[number / 100 % 10] + " " + tens[firstDig] + " "+ ones[last];
                                Console.WriteLine(word);
                            }

                        }

                    }

                }

            }
            else
            {
                int first = Math.Abs(number / 100) % 10;
                int middle = Math.Abs(number / 10) % 10;
                int last = Math.Abs(number) % 10;
                int last2Digit = Math.Abs(number) % 100;
                Console.WriteLine(middle);
                if (last2Digit > 0 && last2Digit < 20)
                {
                    if(last2Digit < 10)
                    {
                        word += ones[first] + " hundred " + tens[middle] + " " + ones[last2Digit];
                        Console.WriteLine(word);
                    }
                    else
                    {
                        word += ones[first] + " hundred " + ones[last2Digit];
                        Console.WriteLine(word);
                    }

                }
                else if (last2Digit > 19)
                {
                    word += ones[first] + " hundred " + tens[middle] + " " + ones[last];
                    Console.WriteLine(word);
                }
                else
                {
                    word += ones[first] + " hundred " + tens[middle] + ones[last];
                    Console.WriteLine(word);
                }
            }
        }
    }
    else if (number >= 10000)
    {
        Console.WriteLine("Max number is 9999");
    }

    return word;

}


问:
Is there a ReSharper or similar extension for Visual Studio Code?
I would like to know if there is some extension to VS Code that helps with cleaning code and suggesting more concise code (i.e., hinting for coding best practices).</p>

答:
There are a large number of ways to lint or provide code suggestions or refactoring tips in VSCode, some baked-in or improved with the C# extension.

But if I understand your question right, for something akin to an extension to suggest code simplification, like ReSharper, I would point you to the Roslynator extension. I have used Roslynator2022 (the Visual Studio 2022 version)  and like how it links you out to see detailed reasons about the suggestions it makes.

For formatting your code the VSCode Marketplace has multiple good options such as the CSharpier extension.


问:
JS event loop priority
I run this code on Nodejs and I expect that got an error but it worked!
If I set 2500 ms to setTimeout I got an error and it’s normal.
Is there anybody here to explain it for me?
And why I see IIFE log first?

I run this code on browser and got error as I expected.

```<code>const data = [{}]
const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([1,2,3,4]);
    }, 3000);
  });

console.log('hiiii');

setTimeout(() => {
    data[0].map(e => console.log('to ',e))
  }, 2999);
(async() => {
     data[0] = await myPromise
     data[0].map(e => console.log('iife ',e))
    }
)()

console.log('byeeeee')
</code>```

The below code is what I see on my console

```<code>hiiii
byeeeee
iife 1
iife 2
iife 3
iife 4
to 1
to 2
to 3
to 4
</code>```

答:
If line 10 happens to execute at least 1 ms after line 2, then its callback will get queued to run after the callback with the resolve() (and hence after the "iife" logging, which happens in the aftermath of the resolve()).

The solution is to move the second setTimeout() before the first one, to ensure their callbacks are queued in the expected order.  So, for instance, this code:

```<code>const data = [[99]];
setTimeout(() => {
    data[0].forEach(e => console.log('to ',e))
  }, 2999);
const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([1,2,3,4]);
    }, 3000);
  });

console.log('hiiii');

(async() => {
     data[0] = await myPromise
     data[0].forEach(e => console.log('iife ',e))
    }
)();

console.log('byeeeee');
</code>```

reliably produces this result:

```<code>hiiii
byeeeee
to  99
iife  1
iife  2
iife  3
iife  4
</code>```

The logic of the event loop is such that calling setTimeout will queue its callback to become runnable x milliseconds after the current time.  Once that amount of time passes, it then has to wait for whatever task is currently executing to finish, and then wait for any other tasks that got queued ahead of it, before it can actually run.

Not sure what you're trying to do, but you'll never get the "to 1" line to appear before the "iife 4" line, because everything from setting data[0] to logging "iife 4" happens inside a single, synchronous chunk of code.

Title: JS event loop priority

Body:
I run this code on Nodejs and I expect that got an error but it worked!
If I set 2500 ms to setTimeout I got an error and it’s normal.
Is there anybody here to explain it for me?
And why I see IIFE log first?

I run this code on browser and got error as I expected.

const data = [{}]
const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([1,2,3,4]);
    }, 3000);
  });

console.log('hiiii');

setTimeout(() => {
    data[0].map(e => console.log('to ',e))
  }, 2999);
(async() => {
     data[0] = await myPromise
     data[0].map(e => console.log('iife ',e))
    }
)()

console.log('byeeeee')

The below code is what I see on my console

hiiii
byeeeee
iife 1
iife 2
iife 3
iife 4
to 1
to 2
to 3
to 4

Body:
If line 10 happens to execute at least 1 ms after line 2, then its callback will get queued to run after the callback with the resolve() (and hence after the "iife" logging, which happens in the aftermath of the resolve()).

The solution is to move the second setTimeout() before the first one, to ensure their callbacks are queued in the expected order.  So, for instance, this code:

const data = [[99]];
setTimeout(() => {
    data[0].forEach(e => console.log('to ',e))
  }, 2999);
const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([1,2,3,4]);
    }, 3000);
  });

console.log('hiiii');

(async() => {
     data[0] = await myPromise
     data[0].forEach(e => console.log('iife ',e))
    }
)();

console.log('byeeeee');

reliably produces this result:

hiiii
byeeeee
to  99
iife  1
iife  2
iife  3
iife  4

The logic of the event loop is such that calling setTimeout will queue its callback to become runnable x milliseconds after the current time.  Once that amount of time passes, it then has to wait for whatever task is currently executing to finish, and then wait for any other tasks that got queued ahead of it, before it can actually run.

Not sure what you're trying to do, but you'll never get the "to 1" line to appear before the "iife 4" line, because everything from setting data[0] to logging "iife 4" happens inside a single, synchronous chunk of code.


问:
Spring JPA long wait time
I have a simple DAL using Spring-boot/security/jpa on MSSQL backend. This is working great apart from some calls take an age to return.
Reviewing the logs, I can see that some JPA methods are idle for ages (23>sec). Note that the code is doing nothing at this point as it's all Spring JPA and not "real code".
The calls to the database and OAuth take around 30ms and the rest is what??

The data returned is around 100 records with less than 5 properties so the data requirement is relatively small.

It can't take 23> seconds to serialize some POJO?
I'm not sure how to hunt this down as it's not my code, but part of the Spring Framework.
Any advice would be gratefully appreciated.

答:
Thanx to @duffymo for the helping hand.

This was down to logs. We have Trace set and this was causing issues with non-synchronous logging.

Turn off logs: 30ms
Turn on TRACE: 30 s

Title: Spring JPA long wait time


问:
Xcode target Deployment Target vs. project Deployment Target
Excuse my ignorance, but what is the difference in Xcode between the Deployment Target field under "Targets" and the deployment target under "Project"?

What happens if my project deployment target is 3.2, and my iOS Application Target is 4.0? Or vice versa?

答: Target settings override project settings. Project settings are valid for all targets whose settings haven't been overridden.</p>


问:
Spring Boot Application stuck at INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [] milliseconds
I am trying to deploy a Spring Boot application in my local Tomcat server. (It has a very old Spring dependency so it needed to be ran as WAR in Tomcat)

I have excluded spring-boot-starter-tomcat from the pom.xml, and made the neccessary changes inside main class (extended SpringBootServletInitializer etc).
The Applications runs perfectly when i run it from IntellIJ as a Spring Boot App, but when i deploy it in my local environment (packaging war) it does not run at all.

It simply says that Server Startup at ... like the following image:

Any ideas what might be wrong ? (It doesnt even throw an error at all)

答:
Apparently, for this specific error, the version of tomcat played an important role. I checked the Spring Boot Starter Tomcat version which was 8.5.43. The external tomcats on my machine were 9 and 10 (in both it didn't run) so I downloaded Tomcat 8.5.43 version and deployed the war there.

It worked and solved the problem


问:
I want to align the text in the list box from right to left In AS3
I have created a list box, but I want to make the text written in it right to left, in the following code, in order to write the text in Arabic starting from right to left. Please help us solve this problem</p>
```<code>stop();
import fl.controls.List;

var list:List = new List();
list.setSize(167,300);
list.move(788,165);
list.addItem({label:"Track 1"});
list.addItem({label:"Track 2"});
list.addItem({label:"Track 3"});
list.addItem({label:"Track 4"});
list.addItem({label:"Track 5"});
list.addItem({label:"Track 6"});

addChild(list);
</code>```

答:
I've got the code that is used for alignment and other formatting of text in a cell.
Thank you for cooperation in solving our problems.</p>
```<code>var tf:TextFormat = new TextFormat();
tf.font = "Arial";
tf.color = 0x000000;
tf.size = 18;
tf.italic = true;
tf.bold = true;
tf.underline = true;
tf.align = "right";
list.setRendererStyle("textFormat", tf);
</code>```

Body:
I have created a list box, but I want to make the text written in it right to left, in the following code, in order to write the text in Arabic starting from right to left. Please help us solve this problem

stop();
import fl.controls.List;

var list:List = new List();
list.setSize(167,300);
list.move(788,165);
list.addItem({label:"Track 1"});
list.addItem({label:"Track 2"});
list.addItem({label:"Track 3"});
list.addItem({label:"Track 4"});
list.addItem({label:"Track 5"});
list.addItem({label:"Track 6"});

addChild(list);

Body:
I've got the code that is used for alignment and other formatting of text in a cell.
Thank you for cooperation in solving our problems.

var tf:TextFormat = new TextFormat();
tf.font = "Arial";
tf.color = 0x000000;
tf.size = 18;
tf.italic = true;
tf.bold = true;
tf.underline = true;
tf.align = "right";
list.setRendererStyle("textFormat", tf);