问:
Application hits blank screen after running for couple hours
We recently upgraded our server from Tomcat 6 to Tomcat 9 and have been experiencing issues with the application going down every couple of hours. Some points I have gathered so far:

The system loads up without any errors and on the local machine and  this only happens on production site.

The application works for 6-7 hours and then hits this white screen issue.

Once you restart the Tomcat server, the system is back again for a couple of hours and then the whole process is repeated.

It usually has connection issues after it's up for couple hours and it seems like the client connections in database seem to be really high when this happens.

This is what is logged in Tomcat. On debugging, the user is not null so I'm not exactly sure what the real issue is. I'm not sure if I need to redo the connections for the database or if it's a configuration issue with Tomcat.

```<code>26-Jan-2022 11:23:46.614 SEVERE [https-jsse-nio-443-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [] threw exception [An exception occurred processing [jsp/index.jsp] at line [86]

83: <%
84:     AccountInfo accountInfo = new AccountInfo();
85:     String user = testOBJECTS.getName();
86:     accountInfo.init(user);
87:

Stacktrace:] with root cause
    java.lang.IllegalStateException: Failed to get connection..
        at test.library.TestConnectionFactory.getConnection(Unknown Source)
        at test.model.AccountInfo.init(Unknown Source)
        at org.apache.jsp.jsp.index_jsp._jspService(index_jsp.java:248)
        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.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:542)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)
        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.lang.Thread.run(Unknown Source)
</code>```

Here is the code in index.jsp page where it's getting the user.

```<code><jsp:useBean id="testOBJECTS" class="test.mainJspBean"/>
<jsp:useBean id="testTop" class="test.loggedInBean"/>
<jsp:useBean id="aircraftFolder" class="test.library.AircraftFolder"/>
<%
  testOBJECTS.setLogin(request);
    if (testOBJECTS.getLoggedIn()) {
     testTop.setServletTop(request, testOBJECTS.getLoggedIn(), null, testOBJECTS.getName());

    AccountInfo accountInfo = new AccountInfo();
    String user = testOBJECTS.getName();
    accountInfo.init(user);

    }
%>
</code>```

And here is the MainJspBean.java class where it's setting the user.

package test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

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

import test.library.SubscribeConnectionFactory;
import test.loginLibraries.Login;

public class mainJspBean
{
    static Logger log = LogManager.getLogger(mainJspBean.class.getName());
    private String clientPage = "";
    private boolean loggedIn = false;
    private String name = "";

    public String getLogin()
    {
        return clientPage;
    }

    public void setLogin(HttpServletRequest request) throws SQLException {
        String user = (String) request.getSession().getAttribute(Login.UID);
        String pass = (String) request.getSession().getAttribute(Login.PASS);
        boolean loggedin = loggedInBean.isLoggedIn(user, pass);
        if (loggedin) {
            this.loggedIn = loggedin;
            name = user;
            System.out.println("name: " + name);

            clientPage += "
TEST Online
\n";
        } else {
            clientPage += "
<FORM  autocomplete=\"off\" METHOD=\"post\" ACTION=\"https://"+ IPs.WebAddress() +"/test/login\" onSubmit=\"return checkWhiteSpace()\">\n" +
                      "
\n" +
                      "
\n" +
                      "User Name: <input type=\"text\" name=\"uid\" id=\"uid\" size=\"8\" >	\n" +
                      "
\n" +
                      "
\n" +
                      "Password: <input type=\"password\" name=\"auth\" size=\"8\">	\n" +
                      "
\n" +
                      "
\n" +
                      "<input type=\"checkbox\" name=\"remember\" value=\"1\" checked> Remember me.	\n" +
                      "
\n" +
                      "
\n" +
                      "<input type=\"submit\" class=\"IP\" name=\"login\" value=\"Login\">\n" +
                      "Register	\n" +
                      "
\n" +

                      "
\n" +
                      "\n" +
                      "</form>\n";
        }
      }

    public String getWebAddress()
    {
        return IPs.WebAddress();
    }

    public boolean getLoggedIn()
    {
        return loggedIn;
    }

    public String getName()
    {
        return name;
    }
}
```
<p>And here is the actual TestConnection page.</p>
<pre class="lang-java prettyprint-override"><code>public class TestConnectionFactory {
    static final Runtime RUNTIME = Runtime.getRuntime();
    static Logger log = LogManager.getLogger(TestConnectionFactory.class.getName());
    DataSource ds = null;
    long connectCount;
    /**
     * A handle to the unique Singleton instance.
     */
    static private TestConnectionFactory instance = null;

    /**
     * The constructor could be made private
     * to prevent others from instantiating this class.
     * But this would also make it impossible to
     * create instances of Singleton subclasses.
     */
    protected TestConnectionFactory() {
        log.debug("<init> freeMemory:"+RUNTIME.freeMemory());
        if (ds == null) {
            ds = getDataSource();
        }
    }

    /**
     * @return The unique instance of this class.
     */
    static public synchronized TestConnectionFactory getInstance() {
        if (instance == null) {
            log.info("getInstance():creating new instance");
            instance = new TestConnectionFactory();
            log.debug("getInstance():reusing existing instance");
        }
        return instance;
    }

    public Connection getConnection() {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

            try {
                connection = ds.getConnection();

            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;

    }

</code>```

Something I tried was referring to this Java web app in tomcat periodically freezes up
post as the issues sounded similar to my application but the fix didn't work. Things I tried:

Changing the maxWaitMillis and maxActive in the context.xml file.

Increasing total number of client database connections.

Set traps for null user in the Java code.

答:
Updated the getConnection() method seems to fix my issue.</p>
```<code>public Connection getConnection() {
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

        try {
            connection = ds.getConnection();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;

}
</code>```

Body:
We recently upgraded our server from Tomcat 6 to Tomcat 9 and have been experiencing issues with the application going down every couple of hours. Some points I have gathered so far:

The system loads up without any errors and on the local machine and  this only happens on production site.

The application works for 6-7 hours and then hits this white screen issue.

Once you restart the Tomcat server, the system is back again for a couple of hours and then the whole process is repeated.

It usually has connection issues after it's up for couple hours and it seems like the client connections in database seem to be really high when this happens.

This is what is logged in Tomcat. On debugging, the user is not null so I'm not exactly sure what the real issue is. I'm not sure if I need to redo the connections for the database or if it's a configuration issue with Tomcat.

26-Jan-2022 11:23:46.614 SEVERE [https-jsse-nio-443-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [] threw exception [An exception occurred processing [jsp/index.jsp] at line [86]

83: <%
84:     AccountInfo accountInfo = new AccountInfo();
85:     String user = testOBJECTS.getName();
86:     accountInfo.init(user);
87:

Stacktrace:] with root cause
    java.lang.IllegalStateException: Failed to get connection..
        at test.library.TestConnectionFactory.getConnection(Unknown Source)
        at test.model.AccountInfo.init(Unknown Source)
        at org.apache.jsp.jsp.index_jsp._jspService(index_jsp.java:248)
        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.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:542)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)
        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.lang.Thread.run(Unknown Source)

Here is the code in index.jsp page where it's getting the user.

<jsp:useBean id="testOBJECTS" class="test.mainJspBean"/>
<jsp:useBean id="testTop" class="test.loggedInBean"/>
<jsp:useBean id="aircraftFolder" class="test.library.AircraftFolder"/>
<%
  testOBJECTS.setLogin(request);
    if (testOBJECTS.getLoggedIn()) {
     testTop.setServletTop(request, testOBJECTS.getLoggedIn(), null, testOBJECTS.getName());

    AccountInfo accountInfo = new AccountInfo();
    String user = testOBJECTS.getName();
    accountInfo.init(user);

    }
%>

And here is the MainJspBean.java class where it's setting the user.

package test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

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

import test.library.SubscribeConnectionFactory;
import test.loginLibraries.Login;

public class mainJspBean
{
    static Logger log = LogManager.getLogger(mainJspBean.class.getName());
    private String clientPage = "";
    private boolean loggedIn = false;
    private String name = "";

    public String getLogin()
    {
        return clientPage;
    }

    public void setLogin(HttpServletRequest request) throws SQLException {
        String user = (String) request.getSession().getAttribute(Login.UID);
        String pass = (String) request.getSession().getAttribute(Login.PASS);
        boolean loggedin = loggedInBean.isLoggedIn(user, pass);
        if (loggedin) {
            this.loggedIn = loggedin;
            name = user;
            System.out.println("name: " + name);

            clientPage += "
TEST Online
\n";
        } else {
            clientPage += "
<FORM  autocomplete=\"off\" METHOD=\"post\" ACTION=\"https://"+ IPs.WebAddress() +"/test/login\" onSubmit=\"return checkWhiteSpace()\">\n" +
                      "
\n" +
                      "
\n" +
                      "User Name: <input type=\"text\" name=\"uid\" id=\"uid\" size=\"8\" >	\n" +
                      "
\n" +
                      "
\n" +
                      "Password: <input type=\"password\" name=\"auth\" size=\"8\">	\n" +
                      "
\n" +
                      "
\n" +
                      "<input type=\"checkbox\" name=\"remember\" value=\"1\" checked> Remember me.	\n" +
                      "
\n" +
                      "
\n" +
                      "<input type=\"submit\" class=\"IP\" name=\"login\" value=\"Login\">\n" +
                      "Register	\n" +
                      "
\n" +

                      "
\n" +
                      "\n" +
                      "</form>\n";
        }
      }

    public String getWebAddress()
    {
        return IPs.WebAddress();
    }

    public boolean getLoggedIn()
    {
        return loggedIn;
    }

    public String getName()
    {
        return name;
    }
}

And here is the actual TestConnection page.

public class TestConnectionFactory {
    static final Runtime RUNTIME = Runtime.getRuntime();
    static Logger log = LogManager.getLogger(TestConnectionFactory.class.getName());
    DataSource ds = null;
    long connectCount;
    /**
     * A handle to the unique Singleton instance.
     */
    static private TestConnectionFactory instance = null;

    /**
     * The constructor could be made private
     * to prevent others from instantiating this class.
     * But this would also make it impossible to
     * create instances of Singleton subclasses.
     */
    protected TestConnectionFactory() {
        log.debug("<init> freeMemory:"+RUNTIME.freeMemory());
        if (ds == null) {
            ds = getDataSource();
        }
    }

    /**
     * @return The unique instance of this class.
     */
    static public synchronized TestConnectionFactory getInstance() {
        if (instance == null) {
            log.info("getInstance():creating new instance");
            instance = new TestConnectionFactory();
            log.debug("getInstance():reusing existing instance");
        }
        return instance;
    }

    public Connection getConnection() {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

            try {
                connection = ds.getConnection();

            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;

    }

Something I tried was referring to this Java web app in tomcat periodically freezes up
post as the issues sounded similar to my application but the fix didn't work. Things I tried:

Changing the maxWaitMillis and maxActive in the context.xml file.

Increasing total number of client database connections.

Set traps for null user in the Java code.

Body:
Updated the getConnection() method seems to fix my issue.

public Connection getConnection() {
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

        try {
            connection = ds.getConnection();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;

}


来源: stackexchange

问:
How to use external database (AWS RDS) with Bitnami Keycloak
I'm trying to use Bitnami Keycloak Helm, which has an internal dependency on Bitnami PostgreSQL that I cannot use. I have to use our existing RDS as an external DB, which seems possible but instruction on this page is completely empty. Unfortunately, I can only use the Bitnami helm for Keycloak, FYI. Can anyone point me to the right direction or show what and where to change the stock chart to make it happen pls? Not getting much luck with Google atm.

Thanks in advance!

答:
You need to use a sidecar container which will handle authorization and proxy the db calls from keycloak to your managed database :

[keycloak] --localhost:XXXX-> [sidecar container] -> [Aws RDS]

You'll find documentation for this on the bitnami chart github repo : https://github.com/bitnami/charts/tree/master/bitnami/keycloak#use-sidecars-and-init-containers

ContentLicense: CC BY-SA 4.0


问:
validating if a user entered an ip address or CIDR notation when prompted
im using the ipaddress module in python. Here is my current scenario. we have self service portal of sorts that will promt the user to enter an IP address. We will allow this to be an individual IP like 165.136.219.5 or something like this 165.136.219.0/24. Once the have entered the data, i want my code to check and ensure its either a valid IPV4 address or a valid IPV4 CIDR.

when i do something like this code below, i get a failure that "/" isnt a valid character. Am i using the ipaddress package wrong ?

```<code>newIpAddress = input("Please enter the IP address for SFTP access: ")
if ipaddress.IPv4Address(newIpAddress) == True or ipaddress.IPv4Network(newIpAddress) == True:
</code>```

Im basically grabbing input from a end user, and then I want to use an if statement basically stating so long as its either a valid IPV4 IP or a valid IPV4 CIDR then go do some tasks, then ill do some else statements that print out some verbiage about not meeting the address or network requirements.

my current code spits out the the following error:

Unexpected '/' in '165.136.219.0/24'
File "C:\Users\myname\Documents\my_Scripts\PaloAlto\sftpNew.py", line 21, in
if ipaddress.IPv4Address(newIpAddress) == True or ipaddress.IPv4Network(newIpAddress) == True:

答:
The ipaddress class does not appear to provide any convenience methods for determinig whether a string represents a valid IPv4 address versus a valid IPv4 network versus neither a valid address or network.

However, you can build your own rudimentary functionality to check to see if one or the other throws an exception and return true or false and use it in your conditional:

```<code>import ipaddress
def valid_ip_or_cidr(ip):
    try:
        ipaddress.IPv4Address(ip)
        print('valid as address')
        return True
    except:
        try:
            ipaddress.IPv4Network(ip)
            print('valid as network')
            return True
        except:
            print('invalid as both an address and network')
            return False

valid_ip_or_cidr('192.168.1.1')
# valid as address
# True
valid_ip_or_cidr('192.168.1.0/24')
# valid as network
# True
valid_ip_or_cidr('foo')
# invalid as both an address and network
# False
</code>```

In your context, this would be implemented in your conditional as:

```<code>newIpAddress = input("Please enter the IP address for SFTP access: ")
if valid_ip_or_cidr(newIpAddress):
    # code to execute if validation succeeds
</code>```

Body:
im using the ipaddress module in python. Here is my current scenario. we have self service portal of sorts that will promt the user to enter an IP address. We will allow this to be an individual IP like 165.136.219.5 or something like this 165.136.219.0/24. Once the have entered the data, i want my code to check and ensure its either a valid IPV4 address or a valid IPV4 CIDR.

when i do something like this code below, i get a failure that "/" isnt a valid character. Am i using the ipaddress package wrong ?

newIpAddress = input("Please enter the IP address for SFTP access: ")
if ipaddress.IPv4Address(newIpAddress) == True or ipaddress.IPv4Network(newIpAddress) == True:

Im basically grabbing input from a end user, and then I want to use an if statement basically stating so long as its either a valid IPV4 IP or a valid IPV4 CIDR then go do some tasks, then ill do some else statements that print out some verbiage about not meeting the address or network requirements.

my current code spits out the the following error:

Unexpected '/' in '165.136.219.0/24'
File "C:\Users\myname\Documents\my_Scripts\PaloAlto\sftpNew.py", line 21, in
if ipaddress.IPv4Address(newIpAddress) == True or ipaddress.IPv4Network(newIpAddress) == True:

Body:
The ipaddress class does not appear to provide any convenience methods for determinig whether a string represents a valid IPv4 address versus a valid IPv4 network versus neither a valid address or network.

However, you can build your own rudimentary functionality to check to see if one or the other throws an exception and return true or false and use it in your conditional:

import ipaddress
def valid_ip_or_cidr(ip):
    try:
        ipaddress.IPv4Address(ip)
        print('valid as address')
        return True
    except:
        try:
            ipaddress.IPv4Network(ip)
            print('valid as network')
            return True
        except:
            print('invalid as both an address and network')
            return False

valid_ip_or_cidr('192.168.1.1')
# valid as address
# True
valid_ip_or_cidr('192.168.1.0/24')
# valid as network
# True
valid_ip_or_cidr('foo')
# invalid as both an address and network
# False

In your context, this would be implemented in your conditional as:

newIpAddress = input("Please enter the IP address for SFTP access: ")
if valid_ip_or_cidr(newIpAddress):
    # code to execute if validation succeeds


问:
How to change font size of title in iphone?
this is the code ,this will show the default size, i want to change the font size of the title becoz this title is too big n not showing the whole only "Cook Great Indian..." is showing...pl let me help out</p>

```<code>- (void)viewDidLoad {

    self.title = @"Cook Great Indian Recipes";
}
</code>```

答:
You can not change the font of title. Instead create a UILabel with your own customization and assign it as navigationItem's titleView.

```<code>UILabel *titleLbl = [[UILabel alloc] init];
label.frame = CGRectMake(...
label.font = [UIFont ...
// And the other things
self.navigationItem.titleView = titleLbl;
[titleLbl release];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this is the code ,this will show the default size, i want to change the font size of the title becoz this title is too big n not showing the whole only "Cook Great Indian..." is showing...pl let me help out

- (void)viewDidLoad {

    self.title = @"Cook Great Indian Recipes";
}

Body:
You can not change the font of title. Instead create a UILabel with your own customization and assign it as navigationItem's titleView.

UILabel *titleLbl = [[UILabel alloc] init];
label.frame = CGRectMake(...
label.font = [UIFont ...
// And the other things
self.navigationItem.titleView = titleLbl;
[titleLbl release];


问:
TypeError: Cannot read properties of undefined (reading 'start')
Giveaway.js

I am getting this error, and I don't know how to fix it, but tutorials use the same thing and don't get this error.

Cannot read properties of undefined (reading 'start')

My code:

case 'start': {
  const gchannel = options.getChannel('channel') || interaction.channel;
  const duration = options.getString('duration');
  const winnerCount = options.getInteger('winners');
  const prize = options.getString('prize');

  client.giveawaysManager
    .start(gchannel, {
      duration: ms(duration),
      winnerCount,
      prize,
      messages: {
        giveaway: ' **GIVEAWAY STARTED**',
        giveawayEnded: ' **GIVEAWAY ENDED** ',
        winMessage: 'Congratulations, {winners}! You won **{this.prize}**!',
      },
    })
    .then(async () => {
      successembed.setDescription('giveaway successfully started.');
      wait(4000);
      interaction.reply({ embeds: [successembed], ephemeral: true });
    })
    .catch((err) => {
      errorembed.setDescription(`An error has occured \n\`${err}\``);
      wait(4000);
      interaction.reply({ embeds: [errorembed], ephemeral: true });
    });
}
```
<p>The error is in:</p>
<pre class="lang-js prettyprint-override"><code>client.giveawaysManager.start(gchannel, {
  duration: ms(duration),
  winnerCount,
  prize,
  messages: {
    giveaway: ' **GIVEAWAY STARTED**',
    giveawayEnded: ' **GIVEAWAY ENDED** ',
    winMessage: 'Congratulations, {winners}! You won **{this.prize}**!',
  },
})
</code>```

答:
It is not client.giveawaysManager, it needs to be constructed by itself:

```<code>manager= new GiveawaysManager(client, options(opt), init(opt));
</code>```

And then it is called this way:

```<code>manager.start(gchannel, {
  duration: ms(duration),
  winnerCount,
  prize,
  messages: {
    giveaway: ' **GIVEAWAY STARTED**',
    giveawayEnded: ' **GIVEAWAY ENDED** ',
    winMessage: 'Congratulations, {winners}! You won **{this.prize}**!',
  },
})
</code>```

DOC: https://discord-giveaways.js.org/GiveawaysManager.html

Body:
Giveaway.js

I am getting this error, and I don't know how to fix it, but tutorials use the same thing and don't get this error.

Cannot read properties of undefined (reading 'start')

My code:

case 'start': {
  const gchannel = options.getChannel('channel') || interaction.channel;
  const duration = options.getString('duration');
  const winnerCount = options.getInteger('winners');
  const prize = options.getString('prize');

  client.giveawaysManager
    .start(gchannel, {
      duration: ms(duration),
      winnerCount,
      prize,
      messages: {
        giveaway: ' **GIVEAWAY STARTED**',
        giveawayEnded: ' **GIVEAWAY ENDED** ',
        winMessage: 'Congratulations, {winners}! You won **{this.prize}**!',
      },
    })
    .then(async () => {
      successembed.setDescription('giveaway successfully started.');
      wait(4000);
      interaction.reply({ embeds: [successembed], ephemeral: true });
    })
    .catch((err) => {
      errorembed.setDescription(`An error has occured \n\`${err}\``);
      wait(4000);
      interaction.reply({ embeds: [errorembed], ephemeral: true });
    });
}

The error is in:

client.giveawaysManager.start(gchannel, {
  duration: ms(duration),
  winnerCount,
  prize,
  messages: {
    giveaway: ' **GIVEAWAY STARTED**',
    giveawayEnded: ' **GIVEAWAY ENDED** ',
    winMessage: 'Congratulations, {winners}! You won **{this.prize}**!',
  },
})

Body:
It is not client.giveawaysManager, it needs to be constructed by itself:

manager= new GiveawaysManager(client, options(opt), init(opt));

And then it is called this way:

manager.start(gchannel, {
  duration: ms(duration),
  winnerCount,
  prize,
  messages: {
    giveaway: ' **GIVEAWAY STARTED**',
    giveawayEnded: ' **GIVEAWAY ENDED** ',
    winMessage: 'Congratulations, {winners}! You won **{this.prize}**!',
  },
})

DOC: https://discord-giveaways.js.org/GiveawaysManager.html


问:
Webdriver IO API test passes even though request is not executed
I've initialised a basic WDIO project using mocha framework.

I have a class below

```<code>const axios =  require('axios');
class Joke{
    async getJoke(){
        const response = axios.get('https://api.chucknorris.io/jokes/random');
        return response;
    }
 }
module.exports = new Joke();
</code>```

This is my spec file:

```<code>const Joke = require("./Joke");

describe("GET random jokes", () => {
  it("responds with json", async () => {
    const res = browser.call(async() => await Joke.getJoke());
    console.log(res);
  });
});
</code>```

The console shows that my test has passed however there's no output of the response. Been trying to crack my head at this, could anyone point out what the issue is?

答:
Aren't you missing an await here before browser.call?

const res = **await** browser.call(async() => await Joke.getJoke());
```

Body:
I've initialised a basic WDIO project using mocha framework.

I have a class below

const axios =  require('axios');
class Joke{
    async getJoke(){
        const response = axios.get('https://api.chucknorris.io/jokes/random');
        return response;
    }
 }
module.exports = new Joke();

This is my spec file:

const Joke = require("./Joke");

describe("GET random jokes", () => {
  it("responds with json", async () => {
    const res = browser.call(async() => await Joke.getJoke());
    console.log(res);
  });
});

The console shows that my test has passed however there's no output of the response. Been trying to crack my head at this, could anyone point out what the issue is?


问:
React Native Possible Unhandled Promise Error with axios
I am trying to fetch two different api with axios and use it on different flatlist

I'm getting this error:

[Unhandled promise rejection: Error: Request failed with status code 429]

Possible Unhandled Promise Rejection (id: 28)

Here's the my code

```<code> const [data, setData] = React.useState([]);
 const [data1, setData1] = React.useState([]);

 axios.all([
        axios.get('https://jsonplaceholder.typicode.com/nation'),
        axios.get('https://jsonplaceholder.typicode.com/state')
      ])
      .then(responseArr => {
        setData(responseArr[0].data);
        setData1(responseArr[1].data);
      });

  return (
      <View style={styles.container}>

            <View >
                <FlatList
                    data={data}
                    listKey="nation"
                    keyExtractor={item => item.id}
                    showsVerticalScrollIndicator = {false}
                    renderItem={({item}) => {
                        return (
                            <View>
                                <Text>{item.event_id}</Text>
                            </View>
                        )
                    }}
                />
            </View>

            <View style={{ marginTop: 30 }}>
                <FlatList
                    data={data1}
                    listKey="state"
                    keyExtractor={item => item.id}
                    showsVerticalScrollIndicator = {false}
                    renderItem={({item}) => {
                        return (
                            <View>
                                <Text>{item.venue_id}</Text>
                            </View>
                        )
                    }}
                />
            </View>

      </View>
  );
};
</code>```

Thank for your help

答:
You are receiving a HTTP 429 error code which means:

The HTTP 429 Too Many Requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting").

You are calling the API too many times, what's happening is:

axios is called.

setData() is executed and your state variable updates.

The rerender is causing axios to run again.

Congratulations, you're now in a loop!

Refactor your code to only run the API call at appropriate times. Something like this:

useEffect(() => {
   axios.all([
        axios.get('https://jsonplaceholder.typicode.com/nation'),
        axios.get('https://jsonplaceholder.typicode.com/state')
      ])
      .then(responseArr => {
        setData(responseArr[0].data);
        setData1(responseArr[1].data);
      });
}, []); // Ensure any dependencies are added here.
```
<p>For good measure you should also handle the rejection, which is what the original error is mentioning.</p>
<p><code>axios.all().then().catch()</code> - You're missing a catch statement.</p>
<hr />
<p>For the question in the comments, you need to use back ticks when interpolating strings.</p>
```<Image
  source={{
    uri: `https://jsonplaceholder.typicode.com/nation/image/${item.nation_image}`
  }}
/>
```

Body:
I am trying to fetch two different api with axios and use it on different flatlist

I'm getting this error:

[Unhandled promise rejection: Error: Request failed with status code 429]

Possible Unhandled Promise Rejection (id: 28)

Here's the my code

 const [data, setData] = React.useState([]);
 const [data1, setData1] = React.useState([]);

 axios.all([
        axios.get('https://jsonplaceholder.typicode.com/nation'),
        axios.get('https://jsonplaceholder.typicode.com/state')
      ])
      .then(responseArr => {
        setData(responseArr[0].data);
        setData1(responseArr[1].data);
      });

  return (
      <View style={styles.container}>

            <View >
                <FlatList
                    data={data}
                    listKey="nation"
                    keyExtractor={item => item.id}
                    showsVerticalScrollIndicator = {false}
                    renderItem={({item}) => {
                        return (
                            <View>
                                <Text>{item.event_id}</Text>
                            </View>
                        )
                    }}
                />
            </View>

            <View style={{ marginTop: 30 }}>
                <FlatList
                    data={data1}
                    listKey="state"
                    keyExtractor={item => item.id}
                    showsVerticalScrollIndicator = {false}
                    renderItem={({item}) => {
                        return (
                            <View>
                                <Text>{item.venue_id}</Text>
                            </View>
                        )
                    }}
                />
            </View>

      </View>
  );
};

Thank for your help

Body:
You are receiving a HTTP 429 error code which means:

The HTTP 429 Too Many Requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting").

You are calling the API too many times, what's happening is:

axios is called.

setData() is executed and your state variable updates.

The rerender is causing axios to run again.

Congratulations, you're now in a loop!

Refactor your code to only run the API call at appropriate times. Something like this:

useEffect(() => {
   axios.all([
        axios.get('https://jsonplaceholder.typicode.com/nation'),
        axios.get('https://jsonplaceholder.typicode.com/state')
      ])
      .then(responseArr => {
        setData(responseArr[0].data);
        setData1(responseArr[1].data);
      });
}, []); // Ensure any dependencies are added here.

For good measure you should also handle the rejection, which is what the original error is mentioning.

axios.all().then().catch() - You're missing a catch statement.

For the question in the comments, you need to use back ticks when interpolating strings.

<Image
  source={{
    uri: `https://jsonplaceholder.typicode.com/nation/image/${item.nation_image}`
  }}
/>


问:
Nuxt component data not fetched
```<code><template>
  <div>
    <h1>Index</h1>
    <button @click="showMe">BUTTON</button>
  </div>
</template>

<script>
export default {
  name: 'Index',

  async fetch ({ $axios }) {
    const result = await $axios.$get('https://api.sampleapis.com/beers/ale')
    console.log(result) // show arr that length 100.
    this.arr = result
  },

  data: () => ({
    arr: []
  }),

  methods: {
    showMe() {
      console.log(this.arr) // show arr that length 0.
    }
  }
}
</script>
</code>```

The example on the official website is the same way.

But my this.arr is not updated.

What should I do to solve this problem?

This really drives me crazy.

why? Why the hell?

My Nuxt version is 2.15.8

答:
fetch(context) only works on pages and is a deprecated syntax:

Before Nuxt 2.12, there was a different fetch hook that only worked
for page components and didn't have access to the component
instance. If your fetch() accepts a context argument, it will be
treated like a legacy fetch hook. This functionality is deprecated,
and should be replaced with either asyncData or an anonymous
middleware

Instead you should use it like this:

```<code>    async fetch () {
     const result = await this.$axios.$get('https://api.sampleapis.com/beers/ale')
     console.log(result) // show arr that length 100.
     this.arr = result
   }
</code>```

Title: Nuxt component data not fetched

Body:
<template>

Index

    <button @click="showMe">BUTTON</button>

</template>

The example on the official website is the same way.

But my this.arr is not updated.

What should I do to solve this problem?

This really drives me crazy.

why? Why the hell?

My Nuxt version is 2.15.8

Body:
fetch(context) only works on pages and is a deprecated syntax:

Before Nuxt 2.12, there was a different fetch hook that only worked
for page components and didn't have access to the component
instance. If your fetch() accepts a context argument, it will be
treated like a legacy fetch hook. This functionality is deprecated,
and should be replaced with either asyncData or an anonymous
middleware

Instead you should use it like this:

    async fetch () {
     const result = await this.$axios.$get('https://api.sampleapis.com/beers/ale')
     console.log(result) // show arr that length 100.
     this.arr = result
   }


问:
Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock
Trying to run this simple query, but getting this error
https://prnt.sc/1rb6pl5</p>

答:
Since you're using PopSQL: Try switching the Connection Type to local:
.


问:
VS Code: Why does the User Installer warn about administrator privileges?
So I've read that when installing Visual Studio Code, the User Installer is recommended because it installs to the Users folder and does not require administrator privileges, but apparently it also allows for better background updating of the program.

However, when I try to install the User Installer, I get the following message:

This User Installer is not meant to be run as an Administrator. If you would like to install VS Code for all users in this system, download the System Installer instead.

I tried installing it once before by accepting this, but the title bar of VS Code will show "Administrator," so I'm wondering what was the point of the User Installer if it still warns me of administrator privileges and still installs with them? If it installs to the Users folder, why would it even show this warning message? Is there a way to avoid this?

If not, will this cause any issues, like slowdowns or such? Do I still get the benefit of the smoother updating that the User Installer supposedly gives?

答:
Stealing from this answer, I see that visualstudio.com says:

If you are a current user of the system-wide Windows setup, you will be prompted to install user setup, which we recommend using from now on.

That suggests to me that the error message we've both seen will soon be obsolete.

That is, when the installer sees you logged in as admin (which conventionally means you wouldn't be coding), it assumes you wanted this now-intended-to-be-deprecated use case where you're installing once on the system for ALL users, which the user setup won't do.

You've probably seen installers ask this: "Do you want to install for all users or just your user?" If all users, it asks you to give the installer admin permissions and installs in Program Files. If just you, it installs in a user path (like VS Code for users does: C:\Users\thySmyUserName\AppData\Local\Programs\Microsoft VS Code).

Instead of a unified system/user install, VS Code seems to have broken it into two.

Make sense? If you're installing to code when logged in as admin, like on a remote box or something, that might still be a bit of an admin smell, but the user setup sh/w/ould otherwise be fine.

If you wanted to install for every user on the box, which you could do with your fancy admin permissions, you'd need to get a different installer. That's all.


问:
Programmatically interacting with gdb using java
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

```<code>try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

```<code>08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]
</code>```

答: You just shouldn't close(). Closing it sends EOF.

Body:
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]


问:
Docker - failed to compute cache key: not found - runs fine in Visual Studio
I've generated a Dockerfile with Visual Studio. It runs in Visual Studio just fine and now I'm trying to build it from Windows itself (docker build ., and I tried many combinations). Yet I get the following error:

```<code>> [build 3/7] COPY [client/client.csproj, client/]:
------
failed to compute cache key: "/client/client.csproj" not found: not found
</code>```

When I change copy to ./client.csproj it does continue and then I get:

```<code> => ERROR [build 7/7] RUN dotnet build "client.csproj" -c Release -o /app/build                3.3s
------
> [build 7/7] RUN dotnet build "client.csproj" -c Release -o /app/build:
#15 0.652 Microsoft (R) Build Engine version 16.8.3+39993d9d for .NET
#15 0.652 Copyright (C) Microsoft Corporation. All rights reserved.
#15 0.652
#15 1.169   Determining projects to restore...
#15 1.483   All projects are up-to-date for restore.
#15 3.231 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/src/client/client.csproj]
#15 3.240
#15 3.240 Build FAILED.
#15 3.240
#15 3.240 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/src/client/client.csproj]
#15 3.240     0 Warning (5)
#15 3.240     1 Error (5)
#15 3.240
#15 3.240 Time Elapsed 00:00:02.51
-----
executor failed running [/bin/sh -c dotnet build "client.csproj" -c Release -o /app/build]: exit code: 1
</code>```

What am I doing wrong? I changed Docker Linux to Windows, changed WSL, and restarted everything.

```<code>#See https://aka.ms/containerfastmode to understand how Visua...

FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["client/client.csproj", "client/"]
RUN dotnet restore "client/client.csproj"
COPY . .
WORKDIR "/src/client"
RUN dotnet build "client.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "client.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet', "client.dll"]
</code>```

答:
In my Case,
i was doing mistake in '/' and ''. Let me explain
Open your dockerfile (it should be named as dockerfile only, not DockerFile or Dockerfile).
You may have something like this-
FROM mcr.microsoft.com/dotnet/runtime:5.0
COPY bin\Release\net5.0\publish .
ENTRYPOINT ["dotnet", "HelloDocker.dll"]

Replace COPY bin\Release\net5.0\publish . to COPY bin/Release/net5.0/publish .

Body:
I've generated a Dockerfile with Visual Studio. It runs in Visual Studio just fine and now I'm trying to build it from Windows itself (docker build ., and I tried many combinations). Yet I get the following error:

> [build 3/7] COPY [client/client.csproj, client/]:
------
failed to compute cache key: "/client/client.csproj" not found: not found

When I change copy to ./client.csproj it does continue and then I get:

 => ERROR [build 7/7] RUN dotnet build "client.csproj" -c Release -o /app/build                3.3s
------
> [build 7/7] RUN dotnet build "client.csproj" -c Release -o /app/build:
#15 0.652 Microsoft (R) Build Engine version 16.8.3+39993d9d for .NET
#15 0.652 Copyright (C) Microsoft Corporation. All rights reserved.
#15 0.652
#15 1.169   Determining projects to restore...
#15 1.483   All projects are up-to-date for restore.
#15 3.231 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/src/client/client.csproj]
#15 3.240
#15 3.240 Build FAILED.
#15 3.240
#15 3.240 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/src/client/client.csproj]
#15 3.240     0 Warning (5)
#15 3.240     1 Error (5)
#15 3.240
#15 3.240 Time Elapsed 00:00:02.51
-----
executor failed running [/bin/sh -c dotnet build "client.csproj" -c Release -o /app/build]: exit code: 1

What am I doing wrong? I changed Docker Linux to Windows, changed WSL, and restarted everything.

#See https://aka.ms/containerfastmode to understand how Visua...

FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["client/client.csproj", "client/"]
RUN dotnet restore "client/client.csproj"
COPY . .
WORKDIR "/src/client"
RUN dotnet build "client.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "client.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet', "client.dll"]


问:
How to check if next element in a list is greater than the previous in Haskell?
(I am currently doing an online course on Haskell and this is an exercise. I am not looking for answers, but simply for some pointers on how to proceed!)

I have trouble wrapping my head around this. In imperative languages I would simply use a loop, but since Haskell doesn't really have those I am left scratching my head.

I need to write a function nextIsGreater :: [Int] -> [Int] that, given a list of numbers, produces a list with all elements of the input list such that the element is followed by a greater number in the input list (the next number is greater).

Here is what I've managed to come up with so far.

```<code>nextIsGreater :: [Int] -> [Int]

nextIsGreater xs = [x | x <- init xs, y <- tail xs, x < y]
</code>```

So far it works if I have only two numbers in the list. Say [0,5], it returns [0] as it is supposed to. If I have, say [0,5,6] then my code seems to check the 0 against both of the next numbers in the list and returns [0,0,5], when it should return [0,5]. How could I compare each adjacent number to eachother?

答:
The intention of this exercise is almost certainly to have you write a standard recursive solution using pattern matching, not use list comprehensions or higher level functions or anything like that.

If the course is any good, you should already have covered some recursive list-to-list transformations, functions with definitions of the form:

```<code>foo :: [Int] -> [Int]
foo (x:xs) = ... something involving "x" and "foo xs" ...
foo [] = ...
</code>```

or similar, and you're expected to write something along the same lines.

Here's a first hint, with further spoilers below.

A simple way of writing a recursive function that operates on adjacent elements of lists is to write a pattern that names the first two elements:

```<code>foo (x:y:zs) = ...
</code>```

The "..." can operate on x and y, and then perform a recursive call to process the "rest" of the list.  The recursive call might be either foo zs or foo (y:zs) (or switch between those based on some condition), depending on what the function is doing.

Because this pattern will only match lists with at least two elements, you will usually also need patterns to match both one-element and empty lists:

```<code>foo [x] = ...
foo [] = ...
</code>```

If that's not clear enough, let me refresh your memory on basic recursive list-to-list transformations starting with an example that doesn't inspect adjacent elements.

SPOILERS

.

.

.

Suppose we want to filter out all even elements from a list.  A recursive solution would consider the two cases:

```<code>evens (x:xs) = ...
evens [] = ...
</code>```

For the first case, the extraction of all evens from x:xs either includes x plus all the evens from xs (i.e., evens xs) or excludes x and includes only evens xs, depending on whether or not x itself even:

```<code>evens (x:xs) | even x = ...
             | otherwise = ...
</code>```

In particular, if x is even, the answer should include x together with evens xs:

```<code>evens (x:xs) | even x = x : evens xs
</code>```

and if x is odd, the answer just should include evens xs:

```<code>             | otherwise = evens xs
</code>```

The final case is the subset of even numbers from the empty list, which is just the empty list:

```<code>evens [] = []
</code>```

giving the complete definition:

```<code>evens :: [Int] -> [Int]
evens (x:xs) | even x = x : evens xs
             | otherwise = evens xs
evens [] = []
</code>```

The main difference in your example is that the decision to include x depends not only on x but on the element appearing after x, so let's consider a slightly different problem:   take a list and output all elements that are followed by an even number.

We might consider starting with a similar structure:

```<code>beforeEvens (x:xs) | ... = x : beforeEvens xs     -- include x
                   | otherwise = beforeEvens xs   -- exclude x
beforeEvens [] = []
</code>```

where "..." checks to see if the element after x (i.e., the first element of xs) is even.  For example, we might call a separate function to check this:

```<code>beforeEvens (x:xs) | headIsEven xs = x : beforeEvens xs
                   | otherwise     = beforeEvens xs
beforeEvens [] = []
</code>```

You ought to be able to write a decent definition of headIsEven to complete this.  Bonus points if instead of using head, it uses pattern matching.  Note the special case headIsEven [] should return False.

A more direct approach, though, is to take advantage of the fact that patterns can be used to examine multiple elements at the start of the list.  Here, we match a pattern that names the first two elements x and y, plus the rest of the list zs:

```<code>beforeEvens (x:y:zs) | even y = x : beforeEvens (y:zs)
                     | otherwise = beforeEvens (y:zs)
beforeEvens [x] = []
beforeEvens [] = []
</code>```

Note a couple of tricky points here.  If we match against the pattern (x:y:zs), then we have to be careful about whether we recurse on y:zs or zs alone.  It depends on whether y should or shouldn't be considered for inclusion in the output.  Also, the pattern (x:y:zs) won't match a singleton list, so we need an extra pattern match on that.

Because the last two cases are the same, we can combine them into a single case:

```<code>beforeEvens (x:y:zs) | even y = x : beforeEvens (y:zs)
                     | otherwise = beforeEvens (y:zs)
beforeEvens _ = []
</code>```

You should find it relatively straightforward to modify beforeEvens to write your nextIsGreater function.

Body:
(I am currently doing an online course on Haskell and this is an exercise. I am not looking for answers, but simply for some pointers on how to proceed!)

I have trouble wrapping my head around this. In imperative languages I would simply use a loop, but since Haskell doesn't really have those I am left scratching my head.

I need to write a function nextIsGreater :: [Int] -> [Int] that, given a list of numbers, produces a list with all elements of the input list such that the element is followed by a greater number in the input list (the next number is greater).

Here is what I've managed to come up with so far.

nextIsGreater :: [Int] -> [Int]

nextIsGreater xs = [x | x <- init xs, y <- tail xs, x < y]

So far it works if I have only two numbers in the list. Say [0,5], it returns [0] as it is supposed to. If I have, say [0,5,6] then my code seems to check the 0 against both of the next numbers in the list and returns [0,0,5], when it should return [0,5]. How could I compare each adjacent number to eachother?

Body:
The intention of this exercise is almost certainly to have you write a standard recursive solution using pattern matching, not use list comprehensions or higher level functions or anything like that.

If the course is any good, you should already have covered some recursive list-to-list transformations, functions with definitions of the form:

foo :: [Int] -> [Int]
foo (x:xs) = ... something involving "x" and "foo xs" ...
foo [] = ...

or similar, and you're expected to write something along the same lines.

Here's a first hint, with further spoilers below.

A simple way of writing a recursive function that operates on adjacent elements of lists is to write a pattern that names the first two elements:

foo (x:y:zs) = ...

The "..." can operate on x and y, and then perform a recursive call to process the "rest" of the list.  The recursive call might be either foo zs or foo (y:zs) (or switch between those based on some condition), depending on what the function is doing.

Because this pattern will only match lists with at least two elements, you will usually also need patterns to match both one-element and empty lists:

foo [x] = ...
foo [] = ...

If that's not clear enough, let me refresh your memory on basic recursive list-to-list transformations starting with an example that doesn't inspect adjacent elements.

SPOILERS

.

.

.

Suppose we want to filter out all even elements from a list.  A recursive solution would consider the two cases:

evens (x:xs) = ...
evens [] = ...

For the first case, the extraction of all evens from x:xs either includes x plus all the evens from xs (i.e., evens xs) or excludes x and includes only evens xs, depending on whether or not x itself even:

evens (x:xs) | even x = ...
             | otherwise = ...

In particular, if x is even, the answer should include x together with evens xs:

evens (x:xs) | even x = x : evens xs

and if x is odd, the answer just should include evens xs:

             | otherwise = evens xs

The final case is the subset of even numbers from the empty list, which is just the empty list:

evens [] = []

giving the complete definition:

evens :: [Int] -> [Int]
evens (x:xs) | even x = x : evens xs
             | otherwise = evens xs
evens [] = []

The main difference in your example is that the decision to include x depends not only on x but on the element appearing after x, so let's consider a slightly different problem:   take a list and output all elements that are followed by an even number.

We might consider starting with a similar structure:

beforeEvens (x:xs) | ... = x : beforeEvens xs     -- include x
                   | otherwise = beforeEvens xs   -- exclude x
beforeEvens [] = []

where "..." checks to see if the element after x (i.e., the first element of xs) is even.  For example, we might call a separate function to check this:

beforeEvens (x:xs) | headIsEven xs = x : beforeEvens xs
                   | otherwise     = beforeEvens xs
beforeEvens [] = []

You ought to be able to write a decent definition of headIsEven to complete this.  Bonus points if instead of using head, it uses pattern matching.  Note the special case headIsEven [] should return False.

A more direct approach, though, is to take advantage of the fact that patterns can be used to examine multiple elements at the start of the list.  Here, we match a pattern that names the first two elements x and y, plus the rest of the list zs:

beforeEvens (x:y:zs) | even y = x : beforeEvens (y:zs)
                     | otherwise = beforeEvens (y:zs)
beforeEvens [x] = []
beforeEvens [] = []

Note a couple of tricky points here.  If we match against the pattern (x:y:zs), then we have to be careful about whether we recurse on y:zs or zs alone.  It depends on whether y should or shouldn't be considered for inclusion in the output.  Also, the pattern (x:y:zs) won't match a singleton list, so we need an extra pattern match on that.

Because the last two cases are the same, we can combine them into a single case:

beforeEvens (x:y:zs) | even y = x : beforeEvens (y:zs)
                     | otherwise = beforeEvens (y:zs)
beforeEvens _ = []

You should find it relatively straightforward to modify beforeEvens to write your nextIsGreater function.


问:
In Ubuntu 20.04.3 sudo su or any other command not working
```<code>yashm@yashm-Inspiron-15-3567:~$ sudo su
Traceback (most recent call last):
  File "/usr/lib/command-not-found", line 28, in <module>
    from CommandNotFound import CommandNotFound
  File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module>
    from CommandNotFound.db.db import SqliteDatabase
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
</code>```

答:
i found the fix myself
as sudo command doesn't work you will have to have synaptic package manager installed before hand
search for python3-apt mark it for complete removal and reinstall it completely everything would be normal again
refer :https://www.datasciencelearner.com/importerror-no-module-named-apt_pkg-fix/</p>


问:
Xcode's Project Navigator Files Icons Turned Black
After updating to xcode 13.0(13A233) for some reason all the project navigator icons turned black and does anybody know how I can fix this. Here's the screenshot.

https://i.stack.imgur.com/5HWay.png

答:
Had the same issue, what solved it for me was:

Go to System Settings -> Accessibility -> Display -> Check "Increase Contrast"

Then you should be able to see the file icons in their original colour again.

Still dont know what is the reason for this, but I hope this solutions works for you aswell.


问:
How to define a class template for both type and values?
How do I write a template class using parameter pack which can:

Take values as template args

Take itself as template arg

Something like this:

```<code>struct Vector

auto v1 = Vector<1,2,3>;
auto v2 = Vector<Vector<1,2>,Vector<3,4>>;
</code>```

I can write the following to meet #1 above:

```<code>template<int... I>
struct Vector;
</code>```

But I am confused about how to extend/specialise it to support #2 as well

答:
It's possible if you use a function to build your Vector objects:

```<code>template <class... Ts>
struct Vector {};

template <size_t... Dims>
auto make_vector() -> Vector<std::integral_constant<size_t, Dims>...> {
}

template <class... Ts>
auto make_vector() -> Vector<Ts...> {
}

int main()
{
    auto v1 = make_vector<1,2,3>();
    auto v2 = make_vector<decltype(v1), decltype(make_vector<4,5,6>())>();
}
</code>```

https://godbolt.org/z/7GvY3G5We

Body:
How do I write a template class using parameter pack which can:

Take values as template args

Take itself as template arg

Something like this:

struct Vector

auto v1 = Vector<1,2,3>;
auto v2 = Vector<Vector<1,2>,Vector<3,4>>;

I can write the following to meet #1 above:

template<int... I>
struct Vector;

But I am confused about how to extend/specialise it to support #2 as well

Body:
It's possible if you use a function to build your Vector objects:

template <class... Ts>
struct Vector {};

template <size_t... Dims>
auto make_vector() -> Vector<std::integral_constant<size_t, Dims>...> {
}

template <class... Ts>
auto make_vector() -> Vector<Ts...> {
}

int main()
{
    auto v1 = make_vector<1,2,3>();
    auto v2 = make_vector<decltype(v1), decltype(make_vector<4,5,6>())>();
}

https://godbolt.org/z/7GvY3G5We


问:
Simple ARRAYFORMULA issue
I'm trying to get a simple IF statement into my ARRAYFORMULA but I'm getting a formula parse error. I'm unsure why.

Here's what I've got. Any ideas what I'm missing?

```<code>=ArrayFormula({"Column Name";if(ISBLANK(C2:C),"",if(and(E2:E="b",G2:G">1.9"),G2:G-0.5,"")}))
</code>```

https://docs.google.com/spreadsheets/d/1kh_gNxouYN7nL3xAnqsG8GvNGDxji5DkD6zZs0nSgxg/edit?usp=sharing

答:
You had your parentheses mismatched. First, select all of Col J and press "Delete" to make sure it is completely empty. Then place this in J1:

=ArrayFormula({"Stop@2";if(ISBLANK(C2:C),"",if((E2:E="b")*(G2:G>1.9),G2:G-0.5,""))})

To be more specific about your error, you had =ArrayFormula({ ... })); so your outer IF had no closure while your ArrayFormula wrap had two.

Title: Simple ARRAYFORMULA issue

Body:
I'm trying to get a simple IF statement into my ARRAYFORMULA but I'm getting a formula parse error. I'm unsure why.

Here's what I've got. Any ideas what I'm missing?

=ArrayFormula({"Column Name";if(ISBLANK(C2:C),"",if(and(E2:E="b",G2:G">1.9"),G2:G-0.5,"")}))

https://docs.google.com/spreadsheets/d/1kh_gNxouYN7nL3xAnqsG8GvNGDxji5DkD6zZs0nSgxg/edit?usp=sharing


问:
Python SQLAlchemy structure and averaged data retrieval
I have a database using Flask-sqlalchemy and I want to store and retrieve (averaged) temperature and humidity data of a sensor.
I've written the class below that stores both together, since I figured it was one sensor and the values are valid for the same timestep they were measured.

My question is, how can I make this performant?

Specifically I found that the retrieval of data takes a long time ~5s for some hundered points. I know that it's programmed very inefficiently - how do I improve this mindfully? The only thing I really need is a function to retrieve measurements in a time-range or in the order that I put them in, which is equivalent and a moving average or blockwise averages.
The bulk of the time is consumed by:
TempHum.query.filter(TempHum.timestamp>starttime)

The main focus is: how do I efficiently structure the database and how to retrieve (and filter) the data efficiently.

```<code>#!/usr/bin/python3

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
from math import floor

db = SQLAlchemy()

# Define a Table in the database
class TempHum(db.Model):
    __tablename__  = 'tempHumMeasurements'
    # Here we define columns for the table
    # Each column is also a Python attribute.
    id = db.Column(db.Integer, primary_key = True)
    timestamp = db.Column(db.DateTime(timezone=True))
    temperature = db.Column('temperature', db.Float)
    humidity = db.Column('humidity', db.Float)
    location = db.Column('location', db.String(32))

    def __init__(self, **kwargs):
        super(TempHum, self).__init__(**kwargs)
        # do custom initialization here
        #now.isoformat(timespec="seconds")
        self.timestamp = datetime.now().replace(microsecond=0)
        self.location = 'room1'

    def __repr__(self):
        return "<TempHum {}>".format(self.timestamp.strftime("%d %m %Y, %H:%M"))

    def getNSamples(n):
        return TempHum.query.\
            order_by(TempHum.timestamp.desc()).\
            limit(n).\
            from_self().order_by(TempHum.timestamp.asc()).all()

    def getSampledNDays(n):
        starttime = datetime.now() - timedelta(days=n)
        meas = TempHum.query.\
            filter(TempHum.timestamp>starttime).\
            order_by(TempHum.timestamp.asc()).all()
        return meas1

# ___________
# helper functions

    def mean(lst):
        return sum(lst)/len(lst)

    def averageData(measures):
        mid = floor(len(measures)/2)
        meantemp = TempHum.mean([tmp.temperature for tmp in measures])
        meanhum = TempHum.mean([tmp.humidity for tmp in measures])
        means = TempHum(temperature=meantemp,humidity=meanhum)
        means.timestamp = measures[mid].timestamp
        return means

    def downsample(arr,average_mins):
    # if values have the correct sampling time they are averaged
    # over average_count values, otherwise all data is taken into account
    # arr is an array of TempHum objects that should be downsampled
        average_time = timedelta(minutes=average_mins)
        buffer = []
        output_array = []
        for k,date in enumerate(arr):
            if not buffer: # buffer first one if buffer is empty
                buffer.append(arr[k])
                continue
            timestep = arr[k].timestamp-buffer[0].timestamp
            if timestep<average_time:
                # values within the window
                buffer.append(arr[k])
            else:
                averaged = TempHum.averageData(buffer)
                output_array.append(averaged)
                buffer.clear()
                buffer.append(arr[k])
        return output_array;

class HeaterState(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime(timezone=True))
    heating = db.Column('heating', db.Boolean)

    def __init__(self, **kwargs):
        super(HeaterState, self).__init__(**kwargs)
        self.timestamp = datetime.now().replace(microsecond=0)

    def __repr__(self):
        return "<HeaterState {}>".format(self.timestamp.strftime("%d %m %Y, %H:%M"))

    def getSampledNDays(n):
        starttime = datetime.now() - timedelta(days=n)
        meas = HeaterState.query.\
            filter(HeaterState.timestamp>starttime).\
            order_by(HeaterState.timestamp.asc()).all()
        return meas
</code>```

答:
Ok, I've tried the right things before, but I was sidetracked by strange effects and didn't debug well enough.
The most effetive Query I found is:

```<code>meas = TempHum.query.order_by(TempHum.id.desc()).limit(n).all()
</code>```

this gives a massive reduction for my 4320 samples (which are 3 days in minutes) query that now takes 1.8 seconds (compared to >4.7s before).
Yet another 0.1s on average was gone as soon as I only averaged over temperature OR humidity, not both of them.

All in all I am still not completely satisfied, but it seems the biggest mistakes were those two.

The problem with this query, that I had tried before was my handling of timedelta. I now use

```<code>  if abs(timediff) < average_time:
</code>```

which makes more sense here and allows to handle reversed lists.

The indexing tipp is still quite valuable and should be considered. However, the id is indexed automatically I think, so here, all is well.

Body:
I have a database using Flask-sqlalchemy and I want to store and retrieve (averaged) temperature and humidity data of a sensor.
I've written the class below that stores both together, since I figured it was one sensor and the values are valid for the same timestep they were measured.

My question is, how can I make this performant?

Specifically I found that the retrieval of data takes a long time ~5s for some hundered points. I know that it's programmed very inefficiently - how do I improve this mindfully? The only thing I really need is a function to retrieve measurements in a time-range or in the order that I put them in, which is equivalent and a moving average or blockwise averages.
The bulk of the time is consumed by:
TempHum.query.filter(TempHum.timestamp>starttime)

The main focus is: how do I efficiently structure the database and how to retrieve (and filter) the data efficiently.

#!/usr/bin/python3

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
from math import floor

db = SQLAlchemy()

# Define a Table in the database
class TempHum(db.Model):
    __tablename__  = 'tempHumMeasurements'
    # Here we define columns for the table
    # Each column is also a Python attribute.
    id = db.Column(db.Integer, primary_key = True)
    timestamp = db.Column(db.DateTime(timezone=True))
    temperature = db.Column('temperature', db.Float)
    humidity = db.Column('humidity', db.Float)
    location = db.Column('location', db.String(32))

    def __init__(self, **kwargs):
        super(TempHum, self).__init__(**kwargs)
        # do custom initialization here
        #now.isoformat(timespec="seconds")
        self.timestamp = datetime.now().replace(microsecond=0)
        self.location = 'room1'

    def __repr__(self):
        return "<TempHum {}>".format(self.timestamp.strftime("%d %m %Y, %H:%M"))

    def getNSamples(n):
        return TempHum.query.\
            order_by(TempHum.timestamp.desc()).\
            limit(n).\
            from_self().order_by(TempHum.timestamp.asc()).all()

    def getSampledNDays(n):
        starttime = datetime.now() - timedelta(days=n)
        meas = TempHum.query.\
            filter(TempHum.timestamp>starttime).\
            order_by(TempHum.timestamp.asc()).all()
        return meas1

# ___________
# helper functions

    def mean(lst):
        return sum(lst)/len(lst)

    def averageData(measures):
        mid = floor(len(measures)/2)
        meantemp = TempHum.mean([tmp.temperature for tmp in measures])
        meanhum = TempHum.mean([tmp.humidity for tmp in measures])
        means = TempHum(temperature=meantemp,humidity=meanhum)
        means.timestamp = measures[mid].timestamp
        return means

    def downsample(arr,average_mins):
    # if values have the correct sampling time they are averaged
    # over average_count values, otherwise all data is taken into account
    # arr is an array of TempHum objects that should be downsampled
        average_time = timedelta(minutes=average_mins)
        buffer = []
        output_array = []
        for k,date in enumerate(arr):
            if not buffer: # buffer first one if buffer is empty
                buffer.append(arr[k])
                continue
            timestep = arr[k].timestamp-buffer[0].timestamp
            if timestep<average_time:
                # values within the window
                buffer.append(arr[k])
            else:
                averaged = TempHum.averageData(buffer)
                output_array.append(averaged)
                buffer.clear()
                buffer.append(arr[k])
        return output_array;

class HeaterState(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime(timezone=True))
    heating = db.Column('heating', db.Boolean)

    def __init__(self, **kwargs):
        super(HeaterState, self).__init__(**kwargs)
        self.timestamp = datetime.now().replace(microsecond=0)

    def __repr__(self):
        return "<HeaterState {}>".format(self.timestamp.strftime("%d %m %Y, %H:%M"))

    def getSampledNDays(n):
        starttime = datetime.now() - timedelta(days=n)
        meas = HeaterState.query.\
            filter(HeaterState.timestamp>starttime).\
            order_by(HeaterState.timestamp.asc()).all()
        return meas

Body:
Ok, I've tried the right things before, but I was sidetracked by strange effects and didn't debug well enough.
The most effetive Query I found is:

meas = TempHum.query.order_by(TempHum.id.desc()).limit(n).all()

this gives a massive reduction for my 4320 samples (which are 3 days in minutes) query that now takes 1.8 seconds (compared to >4.7s before).
Yet another 0.1s on average was gone as soon as I only averaged over temperature OR humidity, not both of them.

All in all I am still not completely satisfied, but it seems the biggest mistakes were those two.

The problem with this query, that I had tried before was my handling of timedelta. I now use

  if abs(timediff) < average_time:

which makes more sense here and allows to handle reversed lists.

The indexing tipp is still quite valuable and should be considered. However, the id is indexed automatically I think, so here, all is well.