问:
React select custom input won't hide placeholder
I am following the React Select docs to alter the Input component of the Select (to add more properties I need to the default input:

```<code>const Input = ({ innerProps }) => {
  return <input {...innerProps} {...somethingElseINeed} />;
};

const CustomSelect = props => {
  return (
    <Select components={{ Input }}></Select>
  );
};
</code>```

It does add a custom input, however it:

Lacks any of the styles and aria attributes the original input has.

Doesn't hide a placeholder when focused.

I tried to use getStyled and theme properties that shoold come by default, but no luck.

Any idea what I am missing?

答:
1)

What about aria props, you can get it from input props, that has appropriate view

2)

if you look at react-select components tree you will see that RS paste placeholder into another component

and you can remove placeholder on focus like that just add styles with using state:

```<code>const styles = {
   placeholder(base, state) {
    return {
      ...base,
      display: state.isFocused && 'none',
    };
  }
}
</code>```

Body:
I am following the React Select docs to alter the Input component of the Select (to add more properties I need to the default input:

const Input = ({ innerProps }) => {
  return <input {...innerProps} {...somethingElseINeed} />;
};

const CustomSelect = props => {
  return (
    <Select components={{ Input }}></Select>
  );
};

It does add a custom input, however it:

Lacks any of the styles and aria attributes the original input has.

Doesn't hide a placeholder when focused.

I tried to use getStyled and theme properties that shoold come by default, but no luck.

Any idea what I am missing?

Body:
1)

What about aria props, you can get it from input props, that has appropriate view

2)

if you look at react-select components tree you will see that RS paste placeholder into another component

and you can remove placeholder on focus like that just add styles with using state:

const styles = {
   placeholder(base, state) {
    return {
      ...base,
      display: state.isFocused && 'none',
    };
  }
}


来源: stackexchange

问:
Is there a way to reference the function you are inside of in C?
I am writing a function that just looks up values inside of a table. Is it possible to call that function inside of itself? I've seen stuff about this and self and don't really understand it.

答:
Others have answered your question, but since it was alien to you, you might want to read up on recursion and recursive functions. There are some gotchas that may catch you if you are not aware.

The worst of which is that you can quickly overflow your stack if you are too deep, or if your function stack-allocates a lot of things. If you are planning to use a recursive implementation make sure your recursion is bounded and that you allocate the bare minimum on the stack.

You might want to consider an iterative approach - every recursive problem can be solved iteratively with some thought. It's usually an interesting exercise to do as well.

JoshLeaves has said that recursion is faster, but often it's not because of the need to allocate grow stack and set up registers. If your function makes two or more calls to itself to calculate its result then an iterative solution is always faster.

ContentLicense: CC BY-SA 3.0


问:
How to increase header size in Grails 4/tomcat (spring-boot)?
In Grails how can you increase the response header size?

We are using Grails 4. This is basically Spring boot. It uses an embedded Tomcat.

答:
You can add this to application.yml with

```<code>server:
    max-http-header-size: 20000
</code>```

Also check if you have any additional info in tokens, which is not needed.

ContentLicense: CC BY-SA 4.0

Body:
You can add this to application.yml with

server:
    max-http-header-size: 20000

Also check if you have any additional info in tokens, which is not needed.


问:
Trying to match on multiple characters
Have tried a variety of things but nothing is quite working...

I have the following code:

```<code>        correctList(id, e) {
          if (this.regex.test(e.key)) {
            this.correctLetters.push([e.key, id]);
          }

          this.correctLetters.forEach(
            (array) => {
              if (this.filteredWords.length > 1) {
                this.filteredList = this.filteredWords.filter((word) => word.indexOf(array[0]) === array[1]);
            } else {
                this.filteredList = this.FiveLetterWords.filter((word) => word.indexOf(array[0]) === array[1]);
            }
            this.setFilteredWords(this.filteredList);
            }
          );
        },
</code>```

Where 'this.correctLetters[]' is:

```<code>[[e,0], [l,1], [d,2]...]
</code>```

This is built up using inputs and the order they are typed is the index number ( the 0, 1, 2 in the arrays)

and

'this.filteredWords' is:

```<code>["cigar", "rebut", "sissy", "humph", "awake", "blush",  "focal", "evade", "naval", "serve", "heath", "dwarf", "model", "karma", "stink", "grade", "quiet", "bench", "abate", "feign", "major", "death", "fresh", "crust", "stool", "colon", "abase", "marry", "react", "batty", "pride", "floss", "helix", "croak", "staff", "paper", "unfed", "whelp", "trawl", "outdo", "adobe", "crazy", "sower", "repay", "digit", "crate", "cluck", "spike", "mimic", "elder".....]
</code>```

There are many more, but not really relevant to list all for question

My problem is the filter... Take the Word "elder"... If I type "e", "l" , "d", then I will get the list filters by words starting with "e", then filtered by words starting "el" and then filtered but words staring "eld".But as soon as I type "elde", it filters the array to empty (which I understand is technically correct due to my filtering method currently) and then if I type "elder", I will get all words ending in "r".

So essentially I understand my problem is the indexOf(() part of things as it`s only matching the first instance of the letter in the word, but I want to filter on words where the letter === the index of that letter but I am not sure how to change things. So if I type    E R then right ow, I get only ending in R words, I want any words ending ER, including any that START with E also, or have another E in there...

Hopefully this makes some sense, am going round in circles with this.... Somebody suggested regex, but my first few attempts didn`t help, but possibly doing it wrong...

EDIT:
Sort of fixed it with:

```<code>correctList(id, e) {
    if (this.regex.test(e.key)) {
    this.correctLetters.push([e.key, id]);
    }

    this.correctLetters.forEach(
    (array) => {
        if (this.filteredWords.length > 1) {
        this.filteredList = this.filteredWords.filter(
            (word) => {
                const wordSplit = word.split('');
                return wordSplit[array[1]] === array[0];
            }
        );
    } else {
        this.filteredList = this.FiveLetterWords.filter(
            (word) => {
                const wordSplit = word.split('');
                return wordSplit[array[1]] === array[0];
            }
        );
    }
    console.log(this.filteredList);
    this.setFilteredWords(this.filteredList);
    }
    );
</code>```

But not sure if there is a more elegant method...

答:
I may have completely missed the point here, but it looks like you're just trying to filter a list of words that contain what the user has typed/selected somewhere.... in which case its as easy as

```<code>const words = filteredWords.filter(x => x.indexOf(something) > -1);
</code>```

An example of this can be seen below, (start typing er and you'll get any word with "er" in it somewhere):

const filteredWords = ["cigar", "rebut", "sissy", "humph", "awake", "blush",  "focal", "evade", "naval", "serve", "heath", "dwarf", "model", "karma", "stink", "grade", "quiet", "bench", "abate", "feign", "major", "death", "fresh", "crust", "stool", "colon", "abase", "marry", "react", "batty", "pride", "floss", "helix", "croak", "staff", "paper", "unfed", "whelp", "trawl", "outdo", "adobe", "crazy", "sower", "repay", "digit", "crate", "cluck", "spike", "mimic", "elder"]

document.getElementById("entry").addEventListener("input", e => {
  const words = filteredWords.filter(x => x.indexOf(e.target.value)>-1);
  document.getElementById("output").value = words.join("\r\n")
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="entry" type="text">
<br>
<textarea id="output" rows="10"></textarea></code>```

Title: Trying to match on multiple characters

Body:
Have tried a variety of things but nothing is quite working...

I have the following code:

        correctList(id, e) {
          if (this.regex.test(e.key)) {
            this.correctLetters.push([e.key, id]);
          }

          this.correctLetters.forEach(
            (array) => {
              if (this.filteredWords.length > 1) {
                this.filteredList = this.filteredWords.filter((word) => word.indexOf(array[0]) === array[1]);
            } else {
                this.filteredList = this.FiveLetterWords.filter((word) => word.indexOf(array[0]) === array[1]);
            }
            this.setFilteredWords(this.filteredList);
            }
          );
        },

Where 'this.correctLetters[]' is:

[[e,0], [l,1], [d,2]...]

This is built up using inputs and the order they are typed is the index number ( the 0, 1, 2 in the arrays)

and

'this.filteredWords' is:

["cigar", "rebut", "sissy", "humph", "awake", "blush",  "focal", "evade", "naval", "serve", "heath", "dwarf", "model", "karma", "stink", "grade", "quiet", "bench", "abate", "feign", "major", "death", "fresh", "crust", "stool", "colon", "abase", "marry", "react", "batty", "pride", "floss", "helix", "croak", "staff", "paper", "unfed", "whelp", "trawl", "outdo", "adobe", "crazy", "sower", "repay", "digit", "crate", "cluck", "spike", "mimic", "elder".....]

There are many more, but not really relevant to list all for question

My problem is the filter... Take the Word "elder"... If I type "e", "l" , "d", then I will get the list filters by words starting with "e", then filtered by words starting "el" and then filtered but words staring "eld".But as soon as I type "elde", it filters the array to empty (which I understand is technically correct due to my filtering method currently) and then if I type "elder", I will get all words ending in "r".

So essentially I understand my problem is the indexOf(() part of things as it`s only matching the first instance of the letter in the word, but I want to filter on words where the letter === the index of that letter but I am not sure how to change things. So if I type    E R then right ow, I get only ending in R words, I want any words ending ER, including any that START with E also, or have another E in there...

Hopefully this makes some sense, am going round in circles with this.... Somebody suggested regex, but my first few attempts didn`t help, but possibly doing it wrong...

EDIT:
Sort of fixed it with:

correctList(id, e) {
    if (this.regex.test(e.key)) {
    this.correctLetters.push([e.key, id]);
    }

    this.correctLetters.forEach(
    (array) => {
        if (this.filteredWords.length > 1) {
        this.filteredList = this.filteredWords.filter(
            (word) => {
                const wordSplit = word.split('');
                return wordSplit[array[1]] === array[0];
            }
        );
    } else {
        this.filteredList = this.FiveLetterWords.filter(
            (word) => {
                const wordSplit = word.split('');
                return wordSplit[array[1]] === array[0];
            }
        );
    }
    console.log(this.filteredList);
    this.setFilteredWords(this.filteredList);
    }
    );

But not sure if there is a more elegant method...

Body:
I may have completely missed the point here, but it looks like you're just trying to filter a list of words that contain what the user has typed/selected somewhere.... in which case its as easy as

const words = filteredWords.filter(x => x.indexOf(something) > -1);

An example of this can be seen below, (start typing er and you'll get any word with "er" in it somewhere):

const filteredWords = ["cigar", "rebut", "sissy", "humph", "awake", "blush",  "focal", "evade", "naval", "serve", "heath", "dwarf", "model", "karma", "stink", "grade", "quiet", "bench", "abate", "feign", "major", "death", "fresh", "crust", "stool", "colon", "abase", "marry", "react", "batty", "pride", "floss", "helix", "croak", "staff", "paper", "unfed", "whelp", "trawl", "outdo", "adobe", "crazy", "sower", "repay", "digit", "crate", "cluck", "spike", "mimic", "elder"]

document.getElementById("entry").addEventListener("input", e => {
  const words = filteredWords.filter(x => x.indexOf(e.target.value)>-1);
  document.getElementById("output").value = words.join("\r\n")
})

<input id="entry" type="text">
<br>
<textarea id="output" rows="10"></textarea>


问:
5-digit-year in date export (52164-01-19 00:00:00+00)
I received a data export from an unspecified source system, which includes dates in the format of:

52164-01-19 00:00:00+00

52992-08-12 04:29:36+00

52838-10-19 04:08:32.999936+00

54022-03-12 17:20:36.999936+00

I was told that the error is caused by a faulty conversion of unix to datetime (seconds and milliseconds).

We came up with a possible approach to refactor the date in python, by separating the year into a "normal" year (2164) and convert the rest into milliseconds.

```<code>import time
import math

d0 = '52164-01-19 00:00:00+00'
d0_y = 52164
multiplier = 5

# avg gregorian year in seconds
avg_greg = (365.2425 * 24 * 3600)

d1_modulus = 52164 % (1000 * multiplier)
d1_rest = d0_y - d1_modulus

# replace orginal year with modulus
d1_time = time.strptime(str(d1_modulus) + '-10-19 04:08:32', '%Y-%m-%d %H:%M:%S')

#convert to milliseconds and add d1_rest in "seconds"
bigtime = time.mktime(d1_time) + (avg_greg * d1_rest) #in milliseconds
biggertime = bigtime / 1000 # in seconds
finaltime = time.ctime(biggertime)
# finaltime = 'Thu Mar 12 07:34:41 2020'
print(finaltime)
</code>```

This code can break for different dates and result in multiplier/modulus combinations to create out of range values for time.mktime.

Can someone suggest an alternative or better approach to this?

Thanks in advance
Gabe

答:
Python datetime only supports between years 1 and 9999.

So I installed astropy and it works fine :

import datetime
import re

import astropy.time as astropy_time  # installed with PIP

faulty_data = "52164-01-19 00:00:00+00"
timeformat = re.compile(r"(?P<year>\d{5})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<sign_tz>[+\- ])(?P<hour_tz>\d{2})")

match = timeformat.fullmatch(faulty_data)
assert match
assert len(match.group("year")) == 5
assert match.group("hour_tz") == "00"
missing_thousand_years = int(match.group("year")[0])

time = astropy_time.Time({"year": int(match.group("year")),
                          "month": int(match.group("month")),
                          "day": int(match.group("day")),
                          "hour": int(match.group("hour")),
                          "minute": int(match.group("minute")),
                          "second": int(match.group("second"))
                          },
                         scale="utc")
print(time)
milliseconds = time.unix
print(milliseconds)
actual_datetime = datetime.datetime.fromtimestamp(milliseconds / 1000)
print(actual_datetime)
```
```(52164, 1, 19, 0, 0, 0.)
1583971200000.0
2020-03-12 01:00:00
```

So it seems that the original date was 2020-03-12 01:00:00, which is close to what you got with your method.

NB: it raises two warnings, that you can silence

Body:
I received a data export from an unspecified source system, which includes dates in the format of:

52164-01-19 00:00:00+00

52992-08-12 04:29:36+00

52838-10-19 04:08:32.999936+00

54022-03-12 17:20:36.999936+00

I was told that the error is caused by a faulty conversion of unix to datetime (seconds and milliseconds).

We came up with a possible approach to refactor the date in python, by separating the year into a "normal" year (2164) and convert the rest into milliseconds.

import time
import math

d0 = '52164-01-19 00:00:00+00'
d0_y = 52164
multiplier = 5

# avg gregorian year in seconds
avg_greg = (365.2425 * 24 * 3600)

d1_modulus = 52164 % (1000 * multiplier)
d1_rest = d0_y - d1_modulus

# replace orginal year with modulus
d1_time = time.strptime(str(d1_modulus) + '-10-19 04:08:32', '%Y-%m-%d %H:%M:%S')

#convert to milliseconds and add d1_rest in "seconds"
bigtime = time.mktime(d1_time) + (avg_greg * d1_rest) #in milliseconds
biggertime = bigtime / 1000 # in seconds
finaltime = time.ctime(biggertime)
# finaltime = 'Thu Mar 12 07:34:41 2020'
print(finaltime)

This code can break for different dates and result in multiplier/modulus combinations to create out of range values for time.mktime.

Can someone suggest an alternative or better approach to this?

Thanks in advance
Gabe

Body:
Python datetime only supports between years 1 and 9999.

So I installed astropy and it works fine :

import datetime
import re

import astropy.time as astropy_time  # installed with PIP

faulty_data = "52164-01-19 00:00:00+00"
timeformat = re.compile(r"(?P<year>\d{5})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<sign_tz>[+\- ])(?P<hour_tz>\d{2})")

match = timeformat.fullmatch(faulty_data)
assert match
assert len(match.group("year")) == 5
assert match.group("hour_tz") == "00"
missing_thousand_years = int(match.group("year")[0])

time = astropy_time.Time({"year": int(match.group("year")),
                          "month": int(match.group("month")),
                          "day": int(match.group("day")),
                          "hour": int(match.group("hour")),
                          "minute": int(match.group("minute")),
                          "second": int(match.group("second"))
                          },
                         scale="utc")
print(time)
milliseconds = time.unix
print(milliseconds)
actual_datetime = datetime.datetime.fromtimestamp(milliseconds / 1000)
print(actual_datetime)

(52164, 1, 19, 0, 0, 0.)
1583971200000.0
2020-03-12 01:00:00

So it seems that the original date was 2020-03-12 01:00:00, which is close to what you got with your method.

NB: it raises two warnings, that you can silence


问:
Have Android SDK into a tablet with honeycomb?
I want to know if exists any form to have the Android SDK into a tablet with Honeycomb.
I ask this because I´ve a tablet with honeycomb and I like to programm into this device.</p>

答: Running IDE in your tablet? This wouldn't be very practical. Anyway, you could use Android Scripting Engine to edit and run primitive scripts on your tablet.</p>


问:
Not able to access other jsp pages other then index.jsp?
I'm using eclipse IDE and trying to run a simple HelloWorld Spring MVC app. While web/index.jsp doesn't have an issue, I cannot get the /WEB-INF/views/final.jsp to display correctly (I'm using http://localhost:8080/springmvc/home ). I keep getting (404-not found) error.

Below is my setup. Any suggestions?

Thanks.

pom.xml

```<code>
 <dependencies>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.4.RELEASE</version>
</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

  </dependencies>

</code>```

web.xml

```<code><!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- Configure dispatcher servlet -->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

</code>```

spring-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--Provide support for conversion, formatting and validation -->
    <mvc:annotation-driven/>
<context:component-scan base-package="springmvc.controller"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>

 </bean>

 </beans>
</code>```

HomeController.java

```<code>package springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class HomeController {

    @RequestMapping(value ="/home")
    public String home()
    {
        System.out.println("This is home URL");
        return "final";
    }

}
</code>```

index.jsp

```<code><html>
<body>
<a href="home">Click here...</a>
</body>
</html>
</code>```

final.jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home Page</title>
</head>
<body>
    <h1>This is home Page</h1>
</body>
</html>
</code>```

Project Structure is as below

答: I got the reason for this error I was executing this code on tomcat version 10, from  version 10 package (javax) are replaced with jakarta so dispatcherServlet was not able to detect javax package and was giving this error. I downgraded my tomcat version to 9 and it worked fine another solution could be to use packages which support jakarta insted of javax.</p>

Body:
I'm using eclipse IDE and trying to run a simple HelloWorld Spring MVC app. While web/index.jsp doesn't have an issue, I cannot get the /WEB-INF/views/final.jsp to display correctly (I'm using http://localhost:8080/springmvc/home ). I keep getting (404-not found) error.

Below is my setup. Any suggestions?

Thanks.

pom.xml

 <dependencies>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.4.RELEASE</version>
</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

  </dependencies>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven/>
<context:component-scan base-package="springmvc.controller"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>

 </bean>

 </beans>

HomeController.java

package springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class HomeController {

    @RequestMapping(value ="/home")
    public String home()
    {
        System.out.println("This is home URL");
        return "final";
    }

}

index.jsp

Click here...

final.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Home Page</title>

This is home Page

Project Structure is as below


问:
How to stack circles in flutter

I would like to stack circles exactly like in the picture, I tried to do it with Stack widget but doesn't seems to work.

Is it the right widget to use ? If yes how do I properly set it, and if not what widget should I use ?

Thanks for your help.

答:
You could use a Stack Widget with the CirlceAvatar widgets as positioned children, but in this case given that you also have to take into account if there is enough space to accomodate all items and display a count for unseen children, I would recommend using the overflow_view package. It's convenient, well maintained and small enough that if you're uncomfortable adding an extra dependency you could vendor it. If you decide to use it there are simple instructions on its README:</p>
```<code>OverflowView(
  // Either layout the children horizontally (the default)
  // or vertically.
  direction: Axis.horizontal,
  // The amount of space between children.
  spacing: 4,
  // The widgets to display until there is not enough space.
  children: <Widget>[
    for (int i = 0; i < _counter; i++)
      AvatarWidget(
        text: avatars[i].initials,
        color: avatars[i].color,
      )
  ],
  // The overview indicator showed if there is not enough space for
  // all chidren.
  builder: (context, remaining) {
    // You can return any widget here.
    // You can either show a +n widget or a more complex widget
    // which can show a thumbnail of not rendered widgets.
    return AvatarWidget(
      text: '+$remaining',
      color: Colors.red,
    );
  },
)
</code>```

Title: How to stack circles in flutter

Body:
You could use a Stack Widget with the CirlceAvatar widgets as positioned children, but in this case given that you also have to take into account if there is enough space to accomodate all items and display a count for unseen children, I would recommend using the overflow_view package. It's convenient, well maintained and small enough that if you're uncomfortable adding an extra dependency you could vendor it. If you decide to use it there are simple instructions on its README:

OverflowView(
  // Either layout the children horizontally (the default)
  // or vertically.
  direction: Axis.horizontal,
  // The amount of space between children.
  spacing: 4,
  // The widgets to display until there is not enough space.
  children: <Widget>[
    for (int i = 0; i < _counter; i++)
      AvatarWidget(
        text: avatars[i].initials,
        color: avatars[i].color,
      )
  ],
  // The overview indicator showed if there is not enough space for
  // all chidren.
  builder: (context, remaining) {
    // You can return any widget here.
    // You can either show a +n widget or a more complex widget
    // which can show a thumbnail of not rendered widgets.
    return AvatarWidget(
      text: '+$remaining',
      color: Colors.red,
    );
  },
)


问:
GameScene won't display correctly after transition from MainMenuScene in Swift
I'm making a game and at the moment I have a MenuScene and a GameScene. If I play the GameScene on its own, everything is displaying correctly. If I set the MenuScene as default and then press start the GameScene is out of position. As if it has been dragged slightly to the bottom left corner.

My Code for the transition:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first

        if let location = touch?.location(in: self) {
            let nodesArray = self.nodes(at: location)

            if nodesArray.first?.name == "newGameButton" {
                let transition = SKTransition.flipHorizontal(withDuration: 0.5)
                let gameScene = GameScene(size: self.size)
                gameScene.scaleMode = scaleMode
                self.view?.presentScene(gameScene, transition: transition)
            }
        }
    }
</code>```

From searching the issue I see others had the same problem, because they didn't set the scene mode. But I have this "gameScene.scaleMode = scaleMode", I also tried "gameScene.scaleMode = .aspectFill"

My settings for both scenes are the same in the attributes inspector, so not sure what I'm doing wrong. Is it programmable error or settings error. I have added photos. Any help appreciated. Thank you.

答:
I managed to fix it. I changed the Transition code.

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first

        if let location = touch?.location(in: self) {
            let nodesArray = self.nodes(at: location)

            if nodesArray.first?.name == "newGameButton" {
                //let gameScene = GameScene(size: self.size)
                let gameScene = GameScene(fileNamed: "GameScene")!
                let transition = SKTransition.flipHorizontal(withDuration: 0.5)
                gameScene.scaleMode = scaleMode
                self.view?.presentScene(gameScene, transition: transition)
            }
        }
    }
</code>```

Now the scene is displaying correctly. Hopefully won't lead to any other issues.

Body:
I'm making a game and at the moment I have a MenuScene and a GameScene. If I play the GameScene on its own, everything is displaying correctly. If I set the MenuScene as default and then press start the GameScene is out of position. As if it has been dragged slightly to the bottom left corner.

My Code for the transition:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first

        if let location = touch?.location(in: self) {
            let nodesArray = self.nodes(at: location)

            if nodesArray.first?.name == "newGameButton" {
                let transition = SKTransition.flipHorizontal(withDuration: 0.5)
                let gameScene = GameScene(size: self.size)
                gameScene.scaleMode = scaleMode
                self.view?.presentScene(gameScene, transition: transition)
            }
        }
    }

From searching the issue I see others had the same problem, because they didn't set the scene mode. But I have this "gameScene.scaleMode = scaleMode", I also tried "gameScene.scaleMode = .aspectFill"

My settings for both scenes are the same in the attributes inspector, so not sure what I'm doing wrong. Is it programmable error or settings error. I have added photos. Any help appreciated. Thank you.

Body:
I managed to fix it. I changed the Transition code.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first

        if let location = touch?.location(in: self) {
            let nodesArray = self.nodes(at: location)

            if nodesArray.first?.name == "newGameButton" {
                //let gameScene = GameScene(size: self.size)
                let gameScene = GameScene(fileNamed: "GameScene")!
                let transition = SKTransition.flipHorizontal(withDuration: 0.5)
                gameScene.scaleMode = scaleMode
                self.view?.presentScene(gameScene, transition: transition)
            }
        }
    }

Now the scene is displaying correctly. Hopefully won't lead to any other issues.


问:
toggle className using flag
```<code>const [flag, setFlag] = useState(false)

let visibleActive, visibleTransition

const handleSelect = () => {
    setFlag(!flag)
    visibleActive = flag ? 'visible active' : ''
    visibleTransition = flag ? 'visible transition' : ''
    console.log(flag)
    console.log(visibleActive)
    console.log(visibleTransition)
}

return (
    <>
        <div className="ui form">
            <div className="field">
                <label className="label">Select a color</label>
                <div className={`ui selection dropdown ${visibleActive}`} onClick={handleSelect}>
                    <i className="dropdown icon"></i>
                    <div className="text">Select Color</div>
                    <div className={`menu ${visibleTransition}`}>
                    </div>
                </div>
            </div>

        </div>
    </>
)
</code>```

classes don't toggle when I click on the dropdown. I see the results in the console but the same is not applying on the JSX. The variables 'visibleTransition' and 'visibleActive' have the correct values but still these values are not being applied.

答:
React setState calls are batched and enqueued and state updates may be async. You cannot access the flag state immediately after setting it.

The visibleActive, visibleTransition variables will loose their values after re-render. You can use useRef to maintain a value between re-renders.

```<code>import {useRef} from 'react'

const visibleActive = useRef("")
const visibleTransition = useRef("")
</code>```

You can assign a value to ref like visibleActive.current = flag ? "visible active" : "";

and Use useEffect to get the correct flag state value

```<code>useEffect(() => {
  visibleActive.current = flag ? "visible active" : "";
  visibleTransition.current = flag ? "visible transition" : "";
  console.log(flag);
  console.log(visibleActive);
  console.log(visibleTransition);
}, [flag]);
</code>```

Title: toggle className using flag

Body:
const [flag, setFlag] = useState(false)

let visibleActive, visibleTransition

const handleSelect = () => {
    setFlag(!flag)
    visibleActive = flag ? 'visible active' : ''
    visibleTransition = flag ? 'visible transition' : ''
    console.log(flag)
    console.log(visibleActive)
    console.log(visibleTransition)
}

return (
    <>

                Select a color
                <div className={`ui selection dropdown ${visibleActive}`} onClick={handleSelect}>

Select Color

                    <div className={`menu ${visibleTransition}`}>

    </>
)

classes don't toggle when I click on the dropdown. I see the results in the console but the same is not applying on the JSX. The variables 'visibleTransition' and 'visibleActive' have the correct values but still these values are not being applied.

Body:
React setState calls are batched and enqueued and state updates may be async. You cannot access the flag state immediately after setting it.

The visibleActive, visibleTransition variables will loose their values after re-render. You can use useRef to maintain a value between re-renders.

import {useRef} from 'react'

const visibleActive = useRef("")
const visibleTransition = useRef("")

You can assign a value to ref like visibleActive.current = flag ? "visible active" : "";

and Use useEffect to get the correct flag state value

useEffect(() => {
  visibleActive.current = flag ? "visible active" : "";
  visibleTransition.current = flag ? "visible transition" : "";
  console.log(flag);
  console.log(visibleActive);
  console.log(visibleTransition);
}, [flag]);


问:
Laravel Backpack DevTools: Create update migrations?
after diving into Laravel and Backpack just two days ago I already built a working prototype for an internal CRUD tool.

I used the DevTools to create my entity models and migrations and that worked fine. But I am still looking for a way to manage my field update / alter table migrations? Right now I still manually create my update migration file with a Schema::table() command.

Isn't that something the DevTools are supposed to handle through the web UI?

Maybe I'm just blind...

Thanks & kind regards
Sebastian

答:
DevTools does not offer “update migration” or “alter table” functionality at the moment. It will be very difficult to create one - the migration itself is easy enough to create, but the rest of the code (Model, CRUD, etc) would be very difficult to do, since the dev might have edited the generated files.

We do plan to add an “edit” functionality for migrations in the near future. But it will be limited in scope. It will cover the use case where you forgot to add a certain db column… which I assume is what most of us need, most of the time.

But until then, the only way to do that is manually… like they did “in the old days”, sorry.


问:
convert each element in array to binary python
I have a np array (100,100 dtype=unit8) and I would like to convert each element into binary represented by 8 bits.

I've looked over the two questions and answers below, but can't quite apply them to an n x m array:

Converting integer array to binary array in python

```<code> a=clip_8bit #clip_8bit is a 100x100 unit8 array
 b=np.zeros_like(a)

for i in a:
    b[i]=bin(int(a[i]))[2:].zfill(8)

IndexError: index 109 is out of bounds for axis 0 with size 100

</code>```

I tried vectorizing and flattening and received either type errors or size-1 array errors

```<code>vector = np.vectorize(np.int)
x=clip_8bit_int
x=vector(x)

y=np.zeros_like(x)
y=y.astype(int)
y=vector(y)

for i in y:
    y[i] = bin(i)[2:]

TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

How do I convert an array of integers to binary?

This looks to be exactly what I would like to do, but with the issues I had applying the first answer, I'm not understanding exactly how the array is being represented and how the conversion is being applied - here I'm not sure how to extend this code to iterate over an array. I know the following is wrong, but I've been going in circles a bit.

```<code>int = clip_8bit  #clip_8bit is a 100x100 unit8 array

int maxLen = 0;
for (int i = 0; i < n; i++) {
    bin[i] = Integer.toBinaryString(arr[i]);
    maxLen = Math.max(maxLen, bin[i].length());
}
for (int i = 0; i < n; i++) {
    if (bin[i].length() != maxLen)
        bin[i] = String.format("%" + maxLen + "s", bin[i]).replace(' ', '0');
    System.out.println(bin[i]);
}
</code>```

Thanks so much, and thanks for your patience with obviously novice questions!

**** edit ****

```<code>I did get this working, but the answer below is much better

flat = clip_8bit.flatten()
n = flat.shape[0]
a = flat
b = np.array(np.zeros((n)))

for i in range(n):
    b[i]=bin(int(a[i]))[2:].zfill(8)

c = np.reshape(b, (100, 100), order = 'C')
</code>```

Body:
I have a np array (100,100 dtype=unit8) and I would like to convert each element into binary represented by 8 bits.

I've looked over the two questions and answers below, but can't quite apply them to an n x m array:

Converting integer array to binary array in python

 a=clip_8bit #clip_8bit is a 100x100 unit8 array
 b=np.zeros_like(a)

for i in a:
    b[i]=bin(int(a[i]))[2:].zfill(8)

IndexError: index 109 is out of bounds for axis 0 with size 100

I tried vectorizing and flattening and received either type errors or size-1 array errors

vector = np.vectorize(np.int)
x=clip_8bit_int
x=vector(x)

y=np.zeros_like(x)
y=y.astype(int)
y=vector(y)

for i in y:
    y[i] = bin(i)[2:]

TypeError: only integer scalar arrays can be converted to a scalar index

How do I convert an array of integers to binary?

This looks to be exactly what I would like to do, but with the issues I had applying the first answer, I'm not understanding exactly how the array is being represented and how the conversion is being applied - here I'm not sure how to extend this code to iterate over an array. I know the following is wrong, but I've been going in circles a bit.

int = clip_8bit  #clip_8bit is a 100x100 unit8 array

int maxLen = 0;
for (int i = 0; i < n; i++) {
    bin[i] = Integer.toBinaryString(arr[i]);
    maxLen = Math.max(maxLen, bin[i].length());
}
for (int i = 0; i < n; i++) {
    if (bin[i].length() != maxLen)
        bin[i] = String.format("%" + maxLen + "s", bin[i]).replace(' ', '0');
    System.out.println(bin[i]);
}

Thanks so much, and thanks for your patience with obviously novice questions!

**** edit ****

I did get this working, but the answer below is much better

flat = clip_8bit.flatten()
n = flat.shape[0]
a = flat
b = np.array(np.zeros((n)))

for i in range(n):
    b[i]=bin(int(a[i]))[2:].zfill(8)

c = np.reshape(b, (100, 100), order = 'C')

Body:
Numpy has a fast function np.binary_repr() that does what you want for an individual number. You can apply it to an array with np.vectorize():

import numpy as np

l = np.arange(12).reshape([3, 4])
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11]])

np.vectorize(np.binary_repr)(l, 8)
# array([['00000000', '00000001', '00000010', '00000011'],
#        ['00000100', '00000101', '00000110', '00000111'],
#        ['00001000', '00001001', '00001010', '00001011']], dtype='<U8')


问:
OAuth 2.0 flow to authentication via access token
I have a public client which gets JWT access token. I need it to get another one (not refresh, but for some other purpose) and I need it to do it without a user interaction.

As a result, I am trying to figure out whether there is a standard OAuth flow where I can use (JWT) access token (issued in a previous OAuth flow) to be used to authenticate for another OAuth flow (I can't authentication with the client secret since it's a public client).

All the things which I found are not a perfect match.

RFC 7523 JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants

It does allow to authenticate via JWT token. However, it requires a client to issue JWT token (signed by a certificate owned by the client) and it checks for the signature. As a result, I can't use JWT access token which was issued by the Authorization server for this purpose.

RFC 8693 OAuth 2.0 Token Exchange

This one allows using JWT access token and get another JWT access token. So close, but no cigar. JWT access token is not used for authentication in this flow. As a result, you still need client id + client secret to authenticate

Token refresh

This one potentially can be used it. Just use the refresh token to get a new JWT access token. However, it feels hacky. (I may need to do this operation a lot, as a result, it feels like an abuse of token refresh mechanics. Also, my guess is it will gradually pollute DB with used refresh tokens (this is a tiny secondary concern, however, again this solution feels hacky).

Am I missing anything?

答:
Token Exchange is fit for your use case, the client authentication part is optional:

The supported methods of client    authentication and whether or not
to allow unauthenticated or    unidentified clients are deployment
decisions that are at the    discretion of the authorization server.

so you can use it with your public client. The other options listed are not meant to be used in the way that you require.


问:
How can I use any() on a multidimensional array?
I'm testing an arbitrarily-large, arbitrarily-dimensioned array of logicals, and I'd like to find out if any one or more of them are true. any() only works on a single dimension at a time, as does sum().  I know that I could test the number of dimensions and repeat any() until I get a single answer, but I'd like a quicker, and frankly, more-elegant, approach.

Ideas?

I'm running 2009a (R17, in the old parlance, I think).

答:
As pointed out, the correct solution is to reshape the result into a vector. Then any will give the desired result. Thus,

any(A(:))

gives the global result, true if any of numel(A) elements were true. You could also have used

any(reshape(A,[],1))

which uses the reshape operator explicitly. If you don't wish to do the extra step of converting your matrices into vectors to apply any, then another approach is to write a function of your own. For example, here is a function that would do it for you:

======================

function result = myany(A)

% determines if any element at all in A was non-zero

result = any(A(:));

======================

Save this as an m-file on your search path. The beauty of MATLAB (true for any programming language) is it is fully extensible. If there is some capability that you wish it had, just write a little idiom that does it. If you do this often enough, you will have customized the environment to fit your needs.

OwnerDisplayName: Marc

ContentLicense: CC BY-SA 2.5


问:
Is it possible to turn off automatic line wrapping in MessageBox()?
Win32's MessageBox() seems to do some automatic linewrapping after the text exceeds a certain width. But this seems to be somewhat erratic and I'm having a hard time figuring out when exactly it occurs. Consider the example text:

```<code>Hello World this is a test Hello World this is a test Hello World this is a test Hello World this is a test Hello World this is a test
</code>```

I get this result when MB_YESNO is set:

When adding the MB_ICONQUESTION style, linewrapping suddenly occurs at a different position and it looks like this:

So it looks like there is a some sort of fixed window width of around 470px after which the text will be wrapped. But this doesn't seem to be the full truth because when using wxWidgets' wxMessageBox() function, it suddenly looks like this:

That's why I'd like to ask two things:

Is it possible to turn off automatic linewrapping so that MessageBox() will only wrap the line in case there is a newline character in the text?

If it's not possible to turn off automatic linewrapping, is there any documentation on when MessageBox() will wrap the line because currently this seems to be a little inconsistent and I'm trying to figure out what is the rule here...

答:
There is no documentation on how MessageBox() auto-wraps long text. The only option it provides you to control how text is wrapped is by placing explicit line break characters in the text itself.

Regardless of word wrapping, if you want to control the size of the dialog, use TaskDialogIndirect() instead.  The TASKDIALOGCONFIG struct has a cxWidth field:

The width of the task dialog's client area, in dialog units. If 0, the task dialog manager will calculate the ideal width.

Body:
Win32's MessageBox() seems to do some automatic linewrapping after the text exceeds a certain width. But this seems to be somewhat erratic and I'm having a hard time figuring out when exactly it occurs. Consider the example text:

Hello World this is a test Hello World this is a test Hello World this is a test Hello World this is a test Hello World this is a test

I get this result when MB_YESNO is set:

When adding the MB_ICONQUESTION style, linewrapping suddenly occurs at a different position and it looks like this:

So it looks like there is a some sort of fixed window width of around 470px after which the text will be wrapped. But this doesn't seem to be the full truth because when using wxWidgets' wxMessageBox() function, it suddenly looks like this:

That's why I'd like to ask two things:

Is it possible to turn off automatic linewrapping so that MessageBox() will only wrap the line in case there is a newline character in the text?

If it's not possible to turn off automatic linewrapping, is there any documentation on when MessageBox() will wrap the line because currently this seems to be a little inconsistent and I'm trying to figure out what is the rule here...


问:
Doctrine not generating entity ID
I'm trying to create an entity, but i get a null value on the id of the entity, which is a generated value.

Controller :

```<code>if($buRepository->findOneBy(['buName' => $row['Bu1'], 'dateDeleted' => null]) > null)

elseif($buRepository->findOneBy(['buName' => $row['Bu1'], 'dateDeleted' => null]) === null)
{
       $bu1 = new Bu();
       $bu1->setBuName($row['Bu1']);
       $bu1->setLastUpdated(new \DateTime('now'));
       $bu1->setDateDeleted(null);
       $bu1->setSrcId(3);
       $bu1->setIdInSource($bu1->getBuId());
}
</code>```

Entity :

```<code> /**
     * @var int
     *
     * @ORM\Column(name="bu_id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $buId;
</code>```

Once my entity tries to flush i get an error on the buid, saying it can't be null.

答:
The Buid isn't created and assign if the entity isn't flushed, the best way to go around it, is to put a trigger in place.
Since IdInSource can't be of NULL value but is suppose to be the BuId (no relation just assigning the INT value), i assigned it a value of 0.
For each entity with a IdInSource of 0 my database trigger replaces it with the BuId.

Title: Doctrine not generating entity ID

Body:
I'm trying to create an entity, but i get a null value on the id of the entity, which is a generated value.

Controller :

if($buRepository->findOneBy(['buName' => $row['Bu1'], 'dateDeleted' => null]) > null)

elseif($buRepository->findOneBy(['buName' => $row['Bu1'], 'dateDeleted' => null]) === null)
{
       $bu1 = new Bu();
       $bu1->setBuName($row['Bu1']);
       $bu1->setLastUpdated(new \DateTime('now'));
       $bu1->setDateDeleted(null);
       $bu1->setSrcId(3);
       $bu1->setIdInSource($bu1->getBuId());
}

Entity :

 /**
     * @var int
     *
     * @ORM\Column(name="bu_id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $buId;

Once my entity tries to flush i get an error on the buid, saying it can't be null.


问:
How to add a complex constraint of 2 conditions
I have a table in SQL Server like this:

```<code>CREATE TABLE my_tablel
(
    main_id UNIQUEIDENTIFIER,
    name_id CHAR(13) NOT NULL,
    my_flag BIT,
    active BIT NOT NULL,

    CONSTRAINT my_table_pk PRIMARY KEY (main_id)
)
</code>```

I would like to add an extra constraint line on 'main flag' satisfying the following conditions:

There can only be one record with main_flag set to true for each name_id.

main_flag can only be set to true if active is also true

Can anybody help me?

答:
This will need to be served by 2 different objects, a filtered UNIQUE INDEX for the first, and a CHECK CONSTRAINT for the second.

For the first, you can create a filtered UNIQUE INDEX like this, which will mean that only name_id must be unique for rows where my_flag (I assume this is what you mean by "main_flag") is 1 (not "true", bit is not a boolean):

CREATE UNIQUE INDEX UQ_name_id_my_flag_equal_1 ON dbo.my_tablel (name_id)
WHERE my_flag = 1;
```
<p>For the latter you can use a <code>CHECK CONSTRAINT</code> to check that the value of <code>my_flag</code> and <code>active</code> are both <code>1</code>, or <code>my_flag</code> is <code>0</code> or <code>NULL</code>.</p>
<pre class="lang-sql prettyprint-override"><code>ALTER TABLE dbo.my_tablel ADD CONSTRAINT CK_MyFlag_Active
CHECK ((my_flag = 1 AND active = 1) OR my_flag = 0 OR my_flag IS NULL);
</code>```

db<>fiddle

Body:
I have a table in SQL Server like this:

CREATE TABLE my_tablel
(
    main_id UNIQUEIDENTIFIER,
    name_id CHAR(13) NOT NULL,
    my_flag BIT,
    active BIT NOT NULL,

    CONSTRAINT my_table_pk PRIMARY KEY (main_id)
)

I would like to add an extra constraint line on 'main flag' satisfying the following conditions:

There can only be one record with main_flag set to true for each name_id.

main_flag can only be set to true if active is also true

Can anybody help me?

Body:
This will need to be served by 2 different objects, a filtered UNIQUE INDEX for the first, and a CHECK CONSTRAINT for the second.

For the first, you can create a filtered UNIQUE INDEX like this, which will mean that only name_id must be unique for rows where my_flag (I assume this is what you mean by "main_flag") is 1 (not "true", bit is not a boolean):

CREATE UNIQUE INDEX UQ_name_id_my_flag_equal_1 ON dbo.my_tablel (name_id)
WHERE my_flag = 1;

For the latter you can use a CHECK CONSTRAINT to check that the value of my_flag and active are both 1, or my_flag is 0 or NULL.

ALTER TABLE dbo.my_tablel ADD CONSTRAINT CK_MyFlag_Active
CHECK ((my_flag = 1 AND active = 1) OR my_flag = 0 OR my_flag IS NULL);

db<>fiddle


问:
is it possible to set multiple shadow using filter: drop-shadow?
today i am learning 'clip-path' and find that it will cut box-shadow and let it not working. after searching, i determine to use drop-shadow.

Is it possible to set multiple shadow using drop-shadow ? just like using box-shadow

thanks

答:
Yes it is possible, as you can see from MDN, filter: <filter-function> [<filter-function>]* | none filter accepts one or more filter functions,
this is an example:

```<code>filter: drop-shadow(10px 3px 5px #000000) drop-shadow(3px 10px 2px #ff0000);
</code>```

Body:
Yes it is possible, as you can see from MDN, filter: <filter-function> [<filter-function>]* | none filter accepts one or more filter functions,
this is an example:

filter: drop-shadow(10px 3px 5px #000000) drop-shadow(3px 10px 2px #ff0000);


问:
ERROR: Error loading ASGI app. Import string "main" must be in format "<module>:<attribute>"
Trying to test my first FastAPI application using uvicorn.

The following code was written on Jupyter Notebook and saved as 'main.py' in the directory: /home/user

```<code>from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}
</code>```

From the same directory I am running:

```<code>$uvicorn main --reload
</code>```

It throws the following error:

ERROR:    Error loading ASGI app. Import string "main" must be in
format ":".

答:
As the error indicates, the "string main must be in format "<module>:<attribute>"". Hence, you should use:

```<code>uvicorn main:app --reload
</code>```

I would highly suggest you take a look at the FastAPI tutorial.

The command uvicorn main:app refers to:

main: the file main.py (the Python "module").

app: the object created inside of main.py with the line app = FastAPI().

--reload: make the server restart after code changes. Only use    for development.

Body:
Trying to test my first FastAPI application using uvicorn.

The following code was written on Jupyter Notebook and saved as 'main.py' in the directory: /home/user

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

From the same directory I am running:

$uvicorn main --reload

It throws the following error:

ERROR:    Error loading ASGI app. Import string "main" must be in
format ":".

Body:
As the error indicates, the "string main must be in format "<module>:<attribute>"". Hence, you should use:

uvicorn main:app --reload

I would highly suggest you take a look at the FastAPI tutorial.

The command uvicorn main:app refers to:

main: the file main.py (the Python "module").

app: the object created inside of main.py with the line app = FastAPI().

--reload: make the server restart after code changes. Only use    for development.


问:
Replace all non NaN values with the initial value per row
I have the following dataframe:

```<code>Periods            0      1      2      3      4      5      6      7     8     9     10    11    12   13   14   15   16   17   18   19
Item 1           89.0   89.0   88.0   86.0   73.0   73.0   67.0    NaN   NaN   NaN   NaN   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 2          197.0  197.0  157.0  157.0  156.0  156.0  153.0  153.0   3.0   3.0   2.0   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 3          105.0  105.0   98.0   47.0   40.0   21.0   20.0   15.0  13.0  11.0  11.0  11.0  10.0  7.0  7.0  5.0  5.0  3.0  2.0  1.0
</code>```

It has several NaNs, and columns from a range between 0 - 20. What i wanted, is to replicate the first column to the next columns, until this value is not NaN. Let me show you an example of what it should look like:

```<code>Periods                0      1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16     17     18     19
Item 1               89.0   89.0   89.0   89.0   89.0   89.0   89.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 2               197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 3               105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0
</code>```

But I can't figure out a way to do this. I wish i could post some code, but all I tried was to search for those methods: backfill, ffill. None of them looked like what I needed.

Any ideas? Thanks in advance.

Body:
I have the following dataframe:

Periods            0      1      2      3      4      5      6      7     8     9     10    11    12   13   14   15   16   17   18   19
Item 1           89.0   89.0   88.0   86.0   73.0   73.0   67.0    NaN   NaN   NaN   NaN   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 2          197.0  197.0  157.0  157.0  156.0  156.0  153.0  153.0   3.0   3.0   2.0   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 3          105.0  105.0   98.0   47.0   40.0   21.0   20.0   15.0  13.0  11.0  11.0  11.0  10.0  7.0  7.0  5.0  5.0  3.0  2.0  1.0

It has several NaNs, and columns from a range between 0 - 20. What i wanted, is to replicate the first column to the next columns, until this value is not NaN. Let me show you an example of what it should look like:

Periods                0      1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16     17     18     19
Item 1               89.0   89.0   89.0   89.0   89.0   89.0   89.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 2               197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 3               105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0

But I can't figure out a way to do this. I wish i could post some code, but all I tried was to search for those methods: backfill, ffill. None of them looked like what I needed.

Any ideas? Thanks in advance.

Body:
I am assuming here that "Periods" is the index

You can use mask on the columns with df.notna() as mask, and the first column (df.iloc[:, 0]) as replacement values:

df.mask(df.notna(), df.iloc[:, 0], axis=0)

output:

             0      1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16     17     18     19
Periods
Item 1    89.0   89.0   89.0   89.0   89.0   89.0   89.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 2   197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 3   105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0


问:
Sidekiq Two Default Queues
Both my staging and production apps use the same build command:

```<code>bundle exec sidekiq -c 2 -q default -q mailers
</code>```

The queue names in my staging application match exactly as the build command states:

However, my production application displays as such:

I understand that the prefix for the default comes from my cable.yml:

development:
  adapter: async

test:
  adapter: test

production:
  adapter: redis
  url: <%= ENV["REDIS_URL"] { "redis://localhost:6379/1" } %>
  channel_prefix: calendarize_production
```

I don't get why there are two defaults and no mailer queue? What am I doing wrong?

答:
The definition of queues for Sidekiq is not done on cable.yml but on sidekiq.yml, here is an example:

:concurrency: 5
:queues:
  - default
  - mailers

staging:
  :queues:
    - ["my_project_staging_default", 3]
    - ["my_project_staging_mailers", 2]
  :tag: STAGING
  :labels:
    - default
    - mailers

production:
  :queues:
    - ["my_project_production_default", 3]
    - ["my_project_production_mailers", 2]
  :concurrency: 5
  :tag: PRODUCTION
  :labels:
    - default
    - mailers
```

Th risk using default without naming it is to share workers between environments. Then I would suggest to name them so you're 100% sure of what's executing where.

Title: Sidekiq Two Default Queues

Body:
Both my staging and production apps use the same build command:

bundle exec sidekiq -c 2 -q default -q mailers

The queue names in my staging application match exactly as the build command states:

However, my production application displays as such:

I understand that the prefix for the default comes from my cable.yml:

development:
  adapter: async

test:
  adapter: test

production:
  adapter: redis
  url: <%= ENV["REDIS_URL"] { "redis://localhost:6379/1" } %>
  channel_prefix: calendarize_production

I don't get why there are two defaults and no mailer queue? What am I doing wrong?

Body:
The definition of queues for Sidekiq is not done on cable.yml but on sidekiq.yml, here is an example:

:concurrency: 5
:queues:
  - default
  - mailers

staging:
  :queues:
    - ["my_project_staging_default", 3]
    - ["my_project_staging_mailers", 2]
  :tag: STAGING
  :labels:
    - default
    - mailers

production:
  :queues:
    - ["my_project_production_default", 3]
    - ["my_project_production_mailers", 2]
  :concurrency: 5
  :tag: PRODUCTION
  :labels:
    - default
    - mailers

Th risk using default without naming it is to share workers between environments. Then I would suggest to name them so you're 100% sure of what's executing where.


问:
Usage of adal4j api (ADAL) for Java
I am just trying to use ADAL api for java.

using the PublicClient.java example to get the accesstoken and idtoken

```<code>      AuthenticationResult result = getAccessTokenFromUserCredentials(
                username, password);
        System.out.println("Access Token - " + result.getAccessToken());
        System.out.println("Refresh Token - " + result.getRefreshToken());
        System.out.println("ID Token - " + result.getIdToken());
</code>```

So does the api provides any util classes to do the following

1) How does the id token looks like.Do we need to decrypt it for readable

2) Verifying the json web token:

Meaning I need to verify that the token is valid by passing the privatekey and token to check if its valid

3) Validate the token signature

Then token has header,claimset and signature. How to validate the signature--Any util class available

Any help is really appreciated.
thanks

答: Kind of late but answering it anyways in case someone needs help with this. Please use msal4j instead of adal4j. adal4j is now deprecated.</p>

Title: Usage of adal4j api (ADAL) for Java

Body:
I am just trying to use ADAL api for java.

using the PublicClient.java example to get the accesstoken and idtoken

      AuthenticationResult result = getAccessTokenFromUserCredentials(
                username, password);
        System.out.println("Access Token - " + result.getAccessToken());
        System.out.println("Refresh Token - " + result.getRefreshToken());
        System.out.println("ID Token - " + result.getIdToken());

So does the api provides any util classes to do the following

1) How does the id token looks like.Do we need to decrypt it for readable

2) Verifying the json web token:

Meaning I need to verify that the token is valid by passing the privatekey and token to check if its valid

3) Validate the token signature

Then token has header,claimset and signature. How to validate the signature--Any util class available

Any help is really appreciated.
thanks


问:
C++ macros generating and error which I can't identify
Here I was just practicing on macros and I tried this but it's generating an error, says expecting and ; but it seems right from me.</p>
```<code>#include <iostream>
using namespace std;

#define REP(i, a, b) for(int i = a, i <= b; i++)

int main()
{
    int i;
//REP showing an error
    REP(i, 0, 6){
        cout << "Hello"<< " ";
    }

    return 0;
}
</code>```

答:
replace  for(int i = a, i <= b; i++)
with   for(int i = a; i <= b; i++)

the ',' symbol after "= a" is wrong, should be semi-colon.

Body:
Here I was just practicing on macros and I tried this but it's generating an error, says expecting and ; but it seems right from me.

#include <iostream>
using namespace std;

#define REP(i, a, b) for(int i = a, i <= b; i++)

int main()
{
    int i;
//REP showing an error
    REP(i, 0, 6){
        cout << "Hello"<< " ";
    }

    return 0;
}


问:
How to make an average of every n previous values in R and only if is above zero (excluding "x" value)
I have this matrix:

matrix =

value1
value2
value3
value4
value5
value6
value7
value8
value9
value10

1
0
0
45
6
6
8
3
0
4
5

2
0
0
0
2
9
1
8
3
0
0

n
n
n
n
n
n
n
n
n
n
n

what i want:

roll_aver =

value1
value2
value3
value4
value5
value6
value7
value8
value9
value10

1
0
0
45
25.5
19
16.25
5.75
5.67
5
4

2
0
0
0
2
5.5
4
5
3.5
4
5.5

n
n
n
n
n
n
n
n
n
n
n

I know that I can do a Roll Average by having this:

```<code>roll_aver <- t(apply(matrix, 1, function(x) rollmean(x, k=4, fill = 0, align ="right")))
</code>```

But in this way it makes an roll average including zeroes.

Imagine its a excel equivalent of doing an excel:
averageif(range of last 4 in the row,>0)

答:
We can apply the rollapply from the first non-zero element on the left by looping over the rows.  Then, with the FUN for rollapply, exclude the zero elements, when getting the mean

```<code>library(zoo)
t(apply(matrix, 1, FUN = function(x) {
   i1 <- cumsum(x != 0) > 0
   x[i1] <- rollapply(x[i1], width = 4, fill = 0, align = "right",
    FUN = function(u) mean(u[u!=0]), partial = TRUE)
  x}))
</code>```

-output

```<code>   value1 value2 value3 value4 value5 value6 value7   value8 value9 value10
1      0      0     45   25.5   19.0  16.25   5.75 5.666667      5     4.0
2      0      0      0    2.0    5.5   4.00   5.00 5.250000      4     5.5
</code>```

data

```<code>matrix <- structure(c(0L, 0L, 0L, 0L, 45L, 0L, 6L, 2L, 6L, 9L, 8L, 1L,
3L, 8L, 0L, 3L, 4L, 0L, 5L, 0L), .Dim = c(2L, 10L), .Dimnames = list(
    c("1", "2"), c("value1", "value2", "value3", "value4", "value5",
    "value6", "value7", "value8", "value9", "value10")))
</code>```

Body:
I have this matrix:

matrix =

value1
value2
value3
value4
value5
value6
value7
value8
value9
value10

1
0
0
45
6
6
8
3
0
4
5

2
0
0
0
2
9
1
8
3
0
0

n
n
n
n
n
n
n
n
n
n
n

what i want:

roll_aver =

value1
value2
value3
value4
value5
value6
value7
value8
value9
value10

1
0
0
45
25.5
19
16.25
5.75
5.67
5
4

2
0
0
0
2
5.5
4
5
3.5
4
5.5

n
n
n
n
n
n
n
n
n
n
n

I know that I can do a Roll Average by having this:

roll_aver <- t(apply(matrix, 1, function(x) rollmean(x, k=4, fill = 0, align ="right")))

But in this way it makes an roll average including zeroes.

Imagine its a excel equivalent of doing an excel:
averageif(range of last 4 in the row,>0)

Body:
We can apply the rollapply from the first non-zero element on the left by looping over the rows.  Then, with the FUN for rollapply, exclude the zero elements, when getting the mean

library(zoo)
t(apply(matrix, 1, FUN = function(x) {
   i1 <- cumsum(x != 0) > 0
   x[i1] <- rollapply(x[i1], width = 4, fill = 0, align = "right",
    FUN = function(u) mean(u[u!=0]), partial = TRUE)
  x}))

-output

   value1 value2 value3 value4 value5 value6 value7   value8 value9 value10
1      0      0     45   25.5   19.0  16.25   5.75 5.666667      5     4.0
2      0      0      0    2.0    5.5   4.00   5.00 5.250000      4     5.5

data

matrix <- structure(c(0L, 0L, 0L, 0L, 45L, 0L, 6L, 2L, 6L, 9L, 8L, 1L,
3L, 8L, 0L, 3L, 4L, 0L, 5L, 0L), .Dim = c(2L, 10L), .Dimnames = list(
    c("1", "2"), c("value1", "value2", "value3", "value4", "value5",
    "value6", "value7", "value8", "value9", "value10")))


问:
change windows language by dart
I have some textFields and want to change the language input when the user came to write its data. In my example, I want the user to write his/her name in two different languages. so it's not friendly to change each time when the user wants to write the name, I want to when the textField got focus, automatically system input language changes the language to the one which the field is for.</p>

答:
This is not possible in flutter, this issue is still open

Visit the Issue: https://github.com/flutter/flutter/issues/25841

but you can achieve this by using package available on flutter pub.dev
https://pub.dev/packages/virtual_keyboard_multi_language

Title: change windows language by dart


问:
Is there an accepted "name" for an event that simply reports back a "message"
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

```<code>var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();
</code>```

答:
I would say it is a nice thing to keep the events specialized, as long as they provide the according infrastructure (for example, where DataImporterCompleted's event args would offer nothing more, DataImporterImportedData's would provide the list of row that were just imported).

Other than that, if you want extremely simple functionality with just some status string, you can do something like:

```<code>public event Action<string> StatusUpdate;
</code>```

You raise it with:

```<code>StatusUpdate("some status string");
</code>```

Your handlers will look like:

```<code>void HandleStatusUpdate(string status)
</code>```

Or you can use the standard .NET pattern:

```<code>class MyEventArgs: EventArgs {}

public event EventHandler<MyEventArgs> MyEvent;
</code>```

And so on...

Body:
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();

Body:
I would say it is a nice thing to keep the events specialized, as long as they provide the according infrastructure (for example, where DataImporterCompleted's event args would offer nothing more, DataImporterImportedData's would provide the list of row that were just imported).

Other than that, if you want extremely simple functionality with just some status string, you can do something like:

public event Action<string> StatusUpdate;

You raise it with:

StatusUpdate("some status string");

Your handlers will look like:

void HandleStatusUpdate(string status)

Or you can use the standard .NET pattern:

class MyEventArgs: EventArgs {}

public event EventHandler<MyEventArgs> MyEvent;

And so on...


问:
Java cannot find library in java.library.path
Despite the following printing out the paths it should be looking in the library wolfcrypt_jni is not being found. It worked before today so I am not sure what changed.

SystemExample.java

```<code>package com.examples.system;

public class SystemExample {

    public static void main(String[] args) {
        System.out.println(System.getProperty("java.library.path"));
        System.out.println(System.getenv("LD_LIBRARY_PATH"));

    }
}

</code>```
```<code>/home/andrew/Keiros/Common/external/wolfcrypt_jni/lib:/home/andrew/KeirosPublic/bazel-bin/Network/Client:/usr/java/packages/lib:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
/home/andrew/Keiros/Common/external/wolfcrypt_jni/lib:/home/andrew/KeirosPublic/bazel-bin/Network/Client
</code>```

And then

```<code>ls /home/andrew/Keiros/Common/external/wolfcrypt_jni/lib
</code>```

produces

```<code>jni_aes.o         jni_dh.o              jni_fips.o           jni_rng.o           wolfcrypt-jni.jar
jni_asn.o         jni_ecc.o             jni_hmac.o           jni_rsa.o
jni_chacha.o      jni_ed25519.o         jni_logging.o        jni_sha.o
jni_curve25519.o  jni_error.o           jni_md5.o            **libwolfcryptjni.so**
jni_des3.o        jni_feature_detect.o  jni_native_struct.o  signed
</code>```

But when I run my test program I get the following error.

```<code>java.lang.UnsatisfiedLinkError: no wolfcryptjni in java.library.path: [/home/andrew/.cache/bazel/_bazel_andrew/a291ce2094be2be5cad6bc87a23a0680/sandbox/linux-sandbox/5919/execroot/com_keiros/bazel-out/k8-fastbuild/bin/javatests/com/keiros/reactor/networking/NetworkingReactorTest.runfiles/com_keiros/external/keiros_public/Network/Client, /home/andrew/.cache/bazel/_bazel_andrew/a291ce2094be2be5cad6bc87a23a0680/sandbox/linux-sandbox/5919/execroot/com_keiros/bazel-out/k8-fastbuild/bin/javatests/com/keiros/reactor/networking/NetworkingReactorTest.runfiles/com_keiros/_solib_k8, /home/andrew/.cache/bazel/_bazel_andrew/a291ce2094be2be5cad6bc87a23a0680/sandbox/linux-sandbox/5919/execroot/com_keiros/bazel-out/k8-fastbuild/bin/javatests/com/keiros/reactor/networking/NetworkingReactorTest.runfiles/com_keiros/_solib_k8/_U@wolfssl_S_S_Cwolfssl___Ubuild]
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2670)
    at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:830)
    at java.base/java.lang.System.loadLibrary(System.java:1873)
    at com.wolfssl.wolfcrypt.WolfObject.<clinit>(WolfObject.java:34)
    at com.keiros.security.encryption.EncryptionHelper.<clinit>(EncryptionHelper.java:37)
    at com.keiros.reactor.testing.ReactorTestFixture.beforeClass(ReactorTestFixture.java:134)
    at com.keiros.reactor.networking.NetworkingReactorTest.beforeClass(NetworkingReactorTest.java:25)
</code>```

MinimalExample.java

```<code>package minimal;

import org.junit.*;
import java.util.*;

import com.wolfssl.wolfcrypt.Aes;
public class MinimalExample {
@Test
public void testThis() {
    byte[] CDRIVES = HexFormat.of().parseHex("e04fd020ea3a6910a2d808002b30309d");
    Aes aes = new Aes(CDRIVES, null, Aes.ENCRYPT_MODE);
}
}
</code>```

Here is the failing file.

```<code>package com.wolfssl.wolfcrypt;

/**
 * Loader for the native WolfCrypt implementation.
 * All classes in this package must inherit from it.
 *
 * @author Moisés Guimarães
 * @version 1.0, March 2015
 */
public class WolfObject {

    static {
        System.loadLibrary("wolfcryptjni");
    }

    protected WolfObject() {
    }

}
</code>```

答:
Okay so the problem was relatively simple.

BUILD

```<code>package(default_visibility = ["//visibility:public"])

java_library(
    name = "networking_client",
    srcs = ["NetworkingClient.java"],
    data = [
        "//Network/Client:connection_configs",
        "//Network/Client:networking_client_so",
    ],
    deps = [
        "//Network/Client:networking_client_so",
        "//java/com/keiros/reactor/base:event_and_message",
        "//java/com/keiros/tools/general/strings:hex",
        "@com_google_protobuf//:protobuf_java",
        "@keiros_public//Network/Identity/Proto:ip_java_proto",
        "@keiros_public//Reactor/Proto/Event/Base:event_java_proto",
    ],
)
</code>```

All I had to do was remove "//Network/Client:networking_client_so",
from deps because it was causing bazel to overwrite LD_LIBRARY_PATH

Body:
Despite the following printing out the paths it should be looking in the library wolfcrypt_jni is not being found. It worked before today so I am not sure what changed.

SystemExample.java

package com.examples.system;

public class SystemExample {

    public static void main(String[] args) {
        System.out.println(System.getProperty("java.library.path"));
        System.out.println(System.getenv("LD_LIBRARY_PATH"));

    }
}

/home/andrew/Keiros/Common/external/wolfcrypt_jni/lib:/home/andrew/KeirosPublic/bazel-bin/Network/Client:/usr/java/packages/lib:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
/home/andrew/Keiros/Common/external/wolfcrypt_jni/lib:/home/andrew/KeirosPublic/bazel-bin/Network/Client

And then

ls /home/andrew/Keiros/Common/external/wolfcrypt_jni/lib

produces

jni_aes.o         jni_dh.o              jni_fips.o           jni_rng.o           wolfcrypt-jni.jar
jni_asn.o         jni_ecc.o             jni_hmac.o           jni_rsa.o
jni_chacha.o      jni_ed25519.o         jni_logging.o        jni_sha.o
jni_curve25519.o  jni_error.o           jni_md5.o            **libwolfcryptjni.so**
jni_des3.o        jni_feature_detect.o  jni_native_struct.o  signed

But when I run my test program I get the following error.

java.lang.UnsatisfiedLinkError: no wolfcryptjni in java.library.path: [/home/andrew/.cache/bazel/_bazel_andrew/a291ce2094be2be5cad6bc87a23a0680/sandbox/linux-sandbox/5919/execroot/com_keiros/bazel-out/k8-fastbuild/bin/javatests/com/keiros/reactor/networking/NetworkingReactorTest.runfiles/com_keiros/external/keiros_public/Network/Client, /home/andrew/.cache/bazel/_bazel_andrew/a291ce2094be2be5cad6bc87a23a0680/sandbox/linux-sandbox/5919/execroot/com_keiros/bazel-out/k8-fastbuild/bin/javatests/com/keiros/reactor/networking/NetworkingReactorTest.runfiles/com_keiros/_solib_k8, /home/andrew/.cache/bazel/_bazel_andrew/a291ce2094be2be5cad6bc87a23a0680/sandbox/linux-sandbox/5919/execroot/com_keiros/bazel-out/k8-fastbuild/bin/javatests/com/keiros/reactor/networking/NetworkingReactorTest.runfiles/com_keiros/_solib_k8/_U@wolfssl_S_S_Cwolfssl___Ubuild]
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2670)
    at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:830)
    at java.base/java.lang.System.loadLibrary(System.java:1873)
    at com.wolfssl.wolfcrypt.WolfObject.<clinit>(WolfObject.java:34)
    at com.keiros.security.encryption.EncryptionHelper.<clinit>(EncryptionHelper.java:37)
    at com.keiros.reactor.testing.ReactorTestFixture.beforeClass(ReactorTestFixture.java:134)
    at com.keiros.reactor.networking.NetworkingReactorTest.beforeClass(NetworkingReactorTest.java:25)

MinimalExample.java

package minimal;

import org.junit.*;
import java.util.*;

import com.wolfssl.wolfcrypt.Aes;
public class MinimalExample {
@Test
public void testThis() {
    byte[] CDRIVES = HexFormat.of().parseHex("e04fd020ea3a6910a2d808002b30309d");
    Aes aes = new Aes(CDRIVES, null, Aes.ENCRYPT_MODE);
}
}

Here is the failing file.

package com.wolfssl.wolfcrypt;

/**
 * Loader for the native WolfCrypt implementation.
 * All classes in this package must inherit from it.
 *
 * @author Moisés Guimarães
 * @version 1.0, March 2015
 */
public class WolfObject {

    static {
        System.loadLibrary("wolfcryptjni");
    }

    protected WolfObject() {
    }

}

Body:
Okay so the problem was relatively simple.

BUILD

package(default_visibility = ["//visibility:public"])

java_library(
    name = "networking_client",
    srcs = ["NetworkingClient.java"],
    data = [
        "//Network/Client:connection_configs",
        "//Network/Client:networking_client_so",
    ],
    deps = [
        "//Network/Client:networking_client_so",
        "//java/com/keiros/reactor/base:event_and_message",
        "//java/com/keiros/tools/general/strings:hex",
        "@com_google_protobuf//:protobuf_java",
        "@keiros_public//Network/Identity/Proto:ip_java_proto",
        "@keiros_public//Reactor/Proto/Event/Base:event_java_proto",
    ],
)

All I had to do was remove "//Network/Client:networking_client_so",
from deps because it was causing bazel to overwrite LD_LIBRARY_PATH


问:
flutter: catch TextFormField state
I am using text form field. By using validator I am change the border color around it.

```<code>TextFormField(
  validator: (final p0) {
    if (p0!.isEmpty) return 'No empasspty';
    return null;
  },
),
</code>```

Now when for first time I run form.currentState.validate it's border changed to error state means red.
Now at this time I want to catch the state of TextFormField! means I want to catch error state or something like that to do something else.

Is it possible to get TextFormField state? or Is it possible to get state with FormField ?

答:
I am not quite sure what you are trying to achieve but what you can do is, using the same code.</p>
```<code>TextFormField(
   validator: (final p0) {
    if (p0!.isEmpty){
      // do you work here you want to do on error
      return 'No empasspty';
    }
    return null;
  },
)
</code>```

Title: flutter: catch TextFormField state

Body:
I am using text form field. By using validator I am change the border color around it.

TextFormField(
  validator: (final p0) {
    if (p0!.isEmpty) return 'No empasspty';
    return null;
  },
),

Now when for first time I run form.currentState.validate it's border changed to error state means red.
Now at this time I want to catch the state of TextFormField! means I want to catch error state or something like that to do something else.

Is it possible to get TextFormField state? or Is it possible to get state with FormField ?

Body:
I am not quite sure what you are trying to achieve but what you can do is, using the same code.

TextFormField(
   validator: (final p0) {
    if (p0!.isEmpty){
      // do you work here you want to do on error
      return 'No empasspty';
    }
    return null;
  },
)


问:
JavaScript, difference between date strings
I’m aware of doing this with a library in order to find the current date and use an integer to find the next date, but I’m trying to find the number of days between two date strings in this format

```<code>Date1.value = ‘2022-02-22’;
Date2.value = ‘2022-03-01’;
</code>```

Is there a library I need for this or could I do it with vanilla JS

答:
checkout https://github.com/you-dont-need/You-Dont-Need-Momentjs#difference

let a = Math.ceil(
  (new Date('2022-03-01') - new Date('2022-02-22')) / 1000 / 60 / 60 / 24
);

console.log(a)```

Body:
I’m aware of doing this with a library in order to find the current date and use an integer to find the next date, but I’m trying to find the number of days between two date strings in this format

Date1.value = ‘2022-02-22’;
Date2.value = ‘2022-03-01’;

Is there a library I need for this or could I do it with vanilla JS


问:
React Router v2.7 to v6 onEnter Migration
I am trying to migrate an application running on router v3, using the onEnter attribute for route after auth.

onEnter function in YAMain.jsx

    static onEnter(store) {
        return (nextState, replaceState, callback) => {

            // Check if the user is logged in and allowed to make requests before letting them proceed
            store.dispatch({
                type: IS_LOGGED_IN,
                onLoggedIn: () => {
                    store.dispatch({
                        type: GET_SELECTED_LOCATION_AND_CLASSROOM,
                        onSuccess: callback,
                        onFailure: () => {

                            // Get all of the required information from the store
                            const profile = getProfile(store.getState());
                            const selectedClassroom = getSelectedClassroom(store.getState());
                            const selectedLocation = getSelectedLocation(store.getState());

                            // No location has been selected by an admin, go to the locations page
                            if (profile.get('accessLevel') !== 'E' && !selectedLocation.get('id')) {

                                // Return early if this is the page we are going to
                                if (nextState.location.pathname.startsWith('/location')) {
                                    return callback();
                                }

                                replaceState('/location');
                                return callback();
                            }

                            // No classroom has been selected by a user, go to the classrooms page
                            if (!selectedClassroom.get('id')) {

                                // Return early if this is the page we are going to
                                if (nextState.location.pathname.startsWith('/classroom')) {
                                    return callback();
                                }

                                replaceState('/classroom');
                                return callback();
                            }

                            return callback();
                        }
                    });
                },
                onNotLoggedIn: () => {
                    replaceState('/login');
                    callback();
                },
                onFailure: (error) => {
                    if (isTimeGateError(error)) {
                        replaceState('/locked');
                        callback();
                    }
                }
            });
        };
```
<p>render function in YARouter.jsx, both classes extend component.</p>
<pre class="lang-js prettyprint-override"><code>    render() {
        return (
            <BrowserRouter>
                <Routes>
                    {/* Handles the main logic and renders all but one of the pages */}
                    <Route
                        exact path="/"
                        element={<YAMain/>
                        }
                        onEnter={YAMain.onEnter(this.props.store)}
                    >
                        <Route path="/" element={YADashboard}/>

                        {/* Locations page displays the available list of locations */}
                        <Route
                            path="location"
                            element={YALocations}
                        />

                        {/* Classrooms page displays the available list of classrooms */}
                        <Route
                            path="classroom"
                            element={YAClassrooms}
                        />
</code>```

this is not the entirety of the routing but should be enough  to give you an idea of what's going on.

This is what I have now, I have tried a number of things suggested on various places. I'm trying to understand how I can either make this work so I can move on and work on this and make it proper later, OR make it proper now and fix this issue.

How can I go about ensuring proper redirection for user authentication, I've spent 2 days at work trying to figure anything out and am completely stuck.

Thanks.

答:
If you are just looking for a way to call onEnter when the route is matched and rendered then I think calling it in a mounting useEffect hook in a wrapper component is probably what you are after.

Example:

```<code>const YAMainWrapper = ({ children, onEnter }) => {
  useEffect(() => {
    onEnter();
  }, []);

  return children;
};
</code>```

...

```<code>render() {
  return (
    <BrowserRouter>
      <Routes>
        {/* Handles the main logic and renders all but one of the pages */}
        <Route
          path="/"
          element={(
            <YAMainWrapper onEnter={YAMain.onEnter(this.props.store)}>
              <YAMain />
            </YAMainWrapper>
          )}
        >
          <Route path="/" element={<YADashboard />} />

          {/* Locations page displays the available list of locations */}
          <Route path="location" element={<YALocations />} />

          {/* Classrooms page displays the available list of classrooms */}
          <Route path="classroom" element={<YAClassrooms />} />

          ...

        </Route>
</code>```

Body:
I am trying to migrate an application running on router v3, using the onEnter attribute for route after auth.

onEnter function in YAMain.jsx

    static onEnter(store) {
        return (nextState, replaceState, callback) => {

            // Check if the user is logged in and allowed to make requests before letting them proceed
            store.dispatch({
                type: IS_LOGGED_IN,
                onLoggedIn: () => {
                    store.dispatch({
                        type: GET_SELECTED_LOCATION_AND_CLASSROOM,
                        onSuccess: callback,
                        onFailure: () => {

                            // Get all of the required information from the store
                            const profile = getProfile(store.getState());
                            const selectedClassroom = getSelectedClassroom(store.getState());
                            const selectedLocation = getSelectedLocation(store.getState());

                            // No location has been selected by an admin, go to the locations page
                            if (profile.get('accessLevel') !== 'E' && !selectedLocation.get('id')) {

                                // Return early if this is the page we are going to
                                if (nextState.location.pathname.startsWith('/location')) {
                                    return callback();
                                }

                                replaceState('/location');
                                return callback();
                            }

                            // No classroom has been selected by a user, go to the classrooms page
                            if (!selectedClassroom.get('id')) {

                                // Return early if this is the page we are going to
                                if (nextState.location.pathname.startsWith('/classroom')) {
                                    return callback();
                                }

                                replaceState('/classroom');
                                return callback();
                            }

                            return callback();
                        }
                    });
                },
                onNotLoggedIn: () => {
                    replaceState('/login');
                    callback();
                },
                onFailure: (error) => {
                    if (isTimeGateError(error)) {
                        replaceState('/locked');
                        callback();
                    }
                }
            });
        };

render function in YARouter.jsx, both classes extend component.

    render() {
        return (
            <BrowserRouter>
                <Routes>
                    {/* Handles the main logic and renders all but one of the pages */}
                    <Route
                        exact path="/"
                        element={<YAMain/>
                        }
                        onEnter={YAMain.onEnter(this.props.store)}
                    >
                        <Route path="/" element={YADashboard}/>

                        {/* Locations page displays the available list of locations */}
                        <Route
                            path="location"
                            element={YALocations}
                        />

                        {/* Classrooms page displays the available list of classrooms */}
                        <Route
                            path="classroom"
                            element={YAClassrooms}
                        />

this is not the entirety of the routing but should be enough  to give you an idea of what's going on.

This is what I have now, I have tried a number of things suggested on various places. I'm trying to understand how I can either make this work so I can move on and work on this and make it proper later, OR make it proper now and fix this issue.

How can I go about ensuring proper redirection for user authentication, I've spent 2 days at work trying to figure anything out and am completely stuck.

Thanks.

Body:
If you are just looking for a way to call onEnter when the route is matched and rendered then I think calling it in a mounting useEffect hook in a wrapper component is probably what you are after.

Example:

const YAMainWrapper = ({ children, onEnter }) => {
  useEffect(() => {
    onEnter();
  }, []);

  return children;
};

...

render() {
  return (
    <BrowserRouter>
      <Routes>
        {/* Handles the main logic and renders all but one of the pages */}
        <Route
          path="/"
          element={(
            <YAMainWrapper onEnter={YAMain.onEnter(this.props.store)}>
              <YAMain />
            </YAMainWrapper>
          )}
        >
          <Route path="/" element={<YADashboard />} />

          {/* Locations page displays the available list of locations */}
          <Route path="location" element={<YALocations />} />

          {/* Classrooms page displays the available list of classrooms */}
          <Route path="classroom" element={<YAClassrooms />} />

          ...

        </Route>