问:
Plotting data in order of date
The aim is to plot a historical plot in r. using the following data

```<code>      date new_cases
1   22/01/2020        NA
2   23/01/2020         0
3   24/01/2020         1
4   25/01/2020         0
5   26/01/2020         3
6   27/01/2020         0
7   28/01/2020         0
8   29/01/2020         1
9   30/01/2020         0
10  31/01/2020         2

... etc.
</code>```

I have never plotted like this, the only thing I know is using

```<code>plot(data$new_cases)
</code>```

But surely there is a more a aesthetically pleasing way to do this?
Thanks

答:
In base R, you can convert the date column to date (as suggested above) using as.Date. Then, you can plot and label your graph.

```<code>df$date <- as.Date(df$date, "%d/%m/%Y")
plot(new_cases ~ date, df, xaxt = "n", type = "l")
axis(1, df$date, format(df$date, "%d/%m/%Y"), cex.axis = .7)
</code>```

Another option is to use tidyverse and convert the date, then pipe into ggplot2:

```<code>library(tidyverse)

df %>%
  mutate(date = as.Date(date, format =  "%d/%m/%Y")) %>%
  ggplot(aes(date,new_cases)) +
  geom_line()
</code>```

Or if you just want points, then you can do as @Dave2e suggested:

```<code>df$date <- as.Date(df$date, "%d/%m/%Y")

plot(x=df$date, y=df$new_cases)
</code>```

Title: Plotting data in order of date

Body:
The aim is to plot a historical plot in r. using the following data

      date new_cases
1   22/01/2020        NA
2   23/01/2020         0
3   24/01/2020         1
4   25/01/2020         0
5   26/01/2020         3
6   27/01/2020         0
7   28/01/2020         0
8   29/01/2020         1
9   30/01/2020         0
10  31/01/2020         2

... etc.

I have never plotted like this, the only thing I know is using

plot(data$new_cases)

But surely there is a more a aesthetically pleasing way to do this?
Thanks

Body:
In base R, you can convert the date column to date (as suggested above) using as.Date. Then, you can plot and label your graph.

df$date <- as.Date(df$date, "%d/%m/%Y")
plot(new_cases ~ date, df, xaxt = "n", type = "l")
axis(1, df$date, format(df$date, "%d/%m/%Y"), cex.axis = .7)

Another option is to use tidyverse and convert the date, then pipe into ggplot2:

library(tidyverse)

df %>%
  mutate(date = as.Date(date, format =  "%d/%m/%Y")) %>%
  ggplot(aes(date,new_cases)) +
  geom_line()

Or if you just want points, then you can do as @Dave2e suggested:

df$date <- as.Date(df$date, "%d/%m/%Y")

plot(x=df$date, y=df$new_cases)


来源: stackexchange

问:
How to choose between JAX-RS and JAX-WS web services implementation?
In what contexts is it better to use one over the other and why?

Thanks!

答:
JAX-WS is an API for SOAP-based WS, and using it for RESTful WebServices is not the best way to go about things.

So if you're looking to implement a RESTful WebService,  use JAX-RS .

ContentLicense: CC BY-SA 3.0


问:
reacting to message just created
I want to make the bot react to it's own message. I am making a !vote command and it can make a message saying "Cast your vote: " already. I want to make a reaction to that new message, like an example, where it reacts with a checkmark and a red x for people to click on. How can I do this?</p>

答:
Sending a message returns a promise with said message. Resolve it and react to it.

message.channel.send(...)
    .then(msg => msg.react(...));

// or

const newMsg = await message.channel.send(...);
newMsg.react(...);
```

ContentLicense: CC BY-SA 4.0

Title: reacting to message just created


问:
How can I disable Firebase In-App Messaging button action open url
Although I have created a Firebase in-app messaging click listener, it tries to open the android system when the button is clicked.

The url like that : https://site_url/product_id

I want to open this url after a logic operation.

```<code>class MainActivity : AppCompatActivity() : FirebaseInAppMessagingClickListener {

  override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
      ....

     FirebaseInAppMessaging.getInstance().addClickListener(this)
     FirebaseInAppMessaging.getInstance().triggerEvent("main_activity_ready")
}

  override fun messageClicked(message: InAppMessage, action: Action) {
    val url =( action.actionUrl ?: "")
    Log.d(TAG, "in-app messaging url : $url")
    linkParsePresenter.startLinkParse(url, PreviousPage.InAppMessaging) // This is my logic function.

}
}
</code>```

messageClicked function invoked. There is no problem. But the system also trying to open this url. How can I override or disable it?

答:
Firebase In-App Messaging (FIAM) is in Beta and doesn't support actions other than dynamic links as of now. And dynamic links are still links, so it will always try to navigate to the web first. Jumps outside the app then back (which makes it look like a virus)

I think a better alternative is to use Firebase Cloud Messaging instead. The implementation looks more complex, but I highly recommend watching this guy explaining everything in detail: https://www.youtube.com/watch?v=p7aIZ3aEi2w

Benefits of Firebase Cloud Messaging over Firebase In-App Messaging:

Push notifications - if the goal with FIAM was to communicate with users, this gets it done

Custom data - A key/value payload can be sent to the app, so you can customize the click action handler, better than FIAM, where it always opens the dynamic link

Silent messages - if you really want to replicate FIAM without the notifications part, you can send silent messages and handle the payload with custom dialogs in the app (silent messages can only be sent from the server, not through the Firebase Console yet)

FCM can be A/B tested as the FIAM

Hope that helps and hope that Firebase makes FIAM more user-friendly in the future (like with a custom callback to handle the button's click)

Body:
Although I have created a Firebase in-app messaging click listener, it tries to open the android system when the button is clicked.

The url like that : https://site_url/product_id

I want to open this url after a logic operation.

class MainActivity : AppCompatActivity() : FirebaseInAppMessagingClickListener {

  override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
      ....

     FirebaseInAppMessaging.getInstance().addClickListener(this)
     FirebaseInAppMessaging.getInstance().triggerEvent("main_activity_ready")
}

  override fun messageClicked(message: InAppMessage, action: Action) {
    val url =( action.actionUrl ?: "")
    Log.d(TAG, "in-app messaging url : $url")
    linkParsePresenter.startLinkParse(url, PreviousPage.InAppMessaging) // This is my logic function.

}
}

messageClicked function invoked. There is no problem. But the system also trying to open this url. How can I override or disable it?


问:
bootstrap not showing dropdown
I have a bootstrap form that I have added a dropdown list.  When I click on the dropdown I see the list, but when I click on it doesn't show as selected it still shows "select Domain" all the time.  I found this link

https://www.codeply.com/go/pTWA3jYWEv/bootstrap-bootstrap-dropdown-selected-value

I have modified it, but I am missing something cause it is not working for me.

```<code><div class="form-group">
<div class="dropdown">
  <button class="btn btn-primary btn-user btn-block dropdown-toggle" type="button"
          id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select Domain
      <span class="caret"></span>
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item">Corp</a>
    <a class="dropdown-item">Domain2</a>
    <a class="dropdown-item">Domain3</a>
    <a class="dropdown-item">Local</a>
  </div>
</div>
</div>

<script type="text/javascript">
$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.dropdown').find('.btn btn-primary btn-user btn-block dropdown-toggle').html(selText+' <span class="caret"></span>');
});
</script>
</code>```

答:
In order for Bootstrap dropdown to work, add the following CDN references in the HTML document to the project. Additionally select ".dropdown-menu a" to capture the clicked  element. The solution below provides an easy way to change the text of the <button> element whose id is dropdown-button when the dropdown button is clicked.

$(".dropdown-menu a").click( function() {
  console.clear();
  console.log($(this).text());

  var selText = $(this).text();
  $('#dropdown-button').html(`${selText} <span class="caret"></span>`)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.caret {
  display: inline-block;
  width: 13px;
  height: 13px;
  background-color: lightgray;
}</code>```

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

  <button id="dropdown-button" class="btn btn-primary btn-user btn-block dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select Domain

  </button>

    Corp
    Domain2
    Domain3
    Local

```

Title: bootstrap not showing dropdown

Body:
I have a bootstrap form that I have added a dropdown list.  When I click on the dropdown I see the list, but when I click on it doesn't show as selected it still shows "select Domain" all the time.  I found this link

https://www.codeply.com/go/pTWA3jYWEv/bootstrap-bootstrap-dropdown-selected-value

I have modified it, but I am missing something cause it is not working for me.

  <button class="btn btn-primary btn-user btn-block dropdown-toggle" type="button"
          id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select Domain

  </button>

    Corp
    Domain2
    Domain3
    Local

Body:
In order for Bootstrap dropdown to work, add the following CDN references in the HTML document to the project. Additionally select ".dropdown-menu a" to capture the clicked <a> element. The solution below provides an easy way to change the text of the <button> element whose id is dropdown-button when the dropdown button is clicked.

$(".dropdown-menu a").click( function() {
  console.clear();
  console.log($(this).text());

  var selText = $(this).text();
  $('#dropdown-button').html(`${selText} <span class="caret"></span>`)
});

.caret {
  display: inline-block;
  width: 13px;
  height: 13px;
  background-color: lightgray;
}

<!-- Add the following CDN references to the project. -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>

<div class="form-group">
<div class="dropdown">
  <!-- Added id attribute to this element. -->
  <button id="dropdown-button" class="btn btn-primary btn-user btn-block dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select Domain
      <span class="caret"></span>
  </button>

  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item">Corp</a>
    <a class="dropdown-item">Domain2</a>
    <a class="dropdown-item">Domain3</a>
    <a class="dropdown-item">Local</a>
  </div>
</div>
</div>


问:
docker build with --build-arg with multiple arguments
According to the documentation, it's possible to define multiple args for the flag --build-arg, but I can't find out how. I tried the following:

```<code>docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 number_of_replicas=2 --no-cache .
</code>```

=> This returns an error.

I also tried:

```<code>docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5,number_of_replicas=2 --no-cache .
</code>```

=> This sets one variable, number_of_shards, to the value "5,number_of_replicas=2"

Any idea how I can define multiple arguments?

答:
A way to pass in build arguments from a file using xargs is as follows:

```<code>cat .MY_ENV_FILE | xargs printf -- '--build-arg %s\n' | xargs docker build -t MY_TAG .
</code>```

Body:
According to the documentation, it's possible to define multiple args for the flag --build-arg, but I can't find out how. I tried the following:

docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 number_of_replicas=2 --no-cache .

=> This returns an error.

I also tried:

docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5,number_of_replicas=2 --no-cache .

=> This sets one variable, number_of_shards, to the value "5,number_of_replicas=2"

Any idea how I can define multiple arguments?

Body:
A way to pass in build arguments from a file using xargs is as follows:

cat .MY_ENV_FILE | xargs printf -- '--build-arg %s\n' | xargs docker build -t MY_TAG .


问:
Visualize Binary tree in bash terminal
When we learn binary trees we first try to understand the structure of what a binary tree looks like. Then we usually implement the tree according to need. We have to draw the tree in hand notes with pen and paper.

Let's take an example array [1,3,4,6,7,8,10,14]. If we construct the array into the Binary tree then the result is

Preoder->  [7, 4, 3, 1, 6, 10, 8, 14]

Inorder->  [1, 3, 4, 6, 7, 8, 10, 14]

PostOder-> [1, 3, 6, 4, 8, 14, 10, 7]

My question is, there is any way or any python package to show the tree in the bash terminal, like this way

```<code>     Preorder tree
         7
        /  \
       /    \
      4      10
     / \    /  \
    3   6  8    14
   /
  1
</code>```

I followed this question. It's drawing like a family tree but I expect the tree as I mentioned above.

答:
I have just built one: it can be definitely improved but should be enough for small trees. If you find any bugs, let me know please.

There is an example on how to use it in the docstring of the TreePrinter class, but just to give you a preview of the final result:

You can build the tree in your question with (it is the same I put in tester.py):

```<code>from printer.tree_printer import Node, TreePrinter

n1 = Node(1)
n3 = Node(3, left=n1)
n6 = Node(6)
n8 = Node(8)
n14 = Node(14)
n4 = Node(4, left=n3, right=n6)
n10 = Node(10, left=n8, right=n14)
n7 = Node(7, left=n4, right=n10)
</code>```

And print it using:

```<code>tv = TreePrinter(n7)
print(tv)
</code>```

The output is:

```<code>        7
        /\
     ---  ---
     |       |
    4       10
    /\      /\
   -  -    -  -
   |   |   |   |
  3   6   8   14
  /
 -
 |
1
</code>```

Title: Visualize Binary tree in bash terminal

Body:
When we learn binary trees we first try to understand the structure of what a binary tree looks like. Then we usually implement the tree according to need. We have to draw the tree in hand notes with pen and paper.

Let's take an example array [1,3,4,6,7,8,10,14]. If we construct the array into the Binary tree then the result is

Preoder->  [7, 4, 3, 1, 6, 10, 8, 14]

Inorder->  [1, 3, 4, 6, 7, 8, 10, 14]

PostOder-> [1, 3, 6, 4, 8, 14, 10, 7]

My question is, there is any way or any python package to show the tree in the bash terminal, like this way

     Preorder tree
         7
        /  \
       /    \
      4      10
     / \    /  \
    3   6  8    14
   /
  1

I followed this question. It's drawing like a family tree but I expect the tree as I mentioned above.

Body:
I have just built one: it can be definitely improved but should be enough for small trees. If you find any bugs, let me know please.

There is an example on how to use it in the docstring of the TreePrinter class, but just to give you a preview of the final result:

You can build the tree in your question with (it is the same I put in tester.py):

from printer.tree_printer import Node, TreePrinter

n1 = Node(1)
n3 = Node(3, left=n1)
n6 = Node(6)
n8 = Node(8)
n14 = Node(14)
n4 = Node(4, left=n3, right=n6)
n10 = Node(10, left=n8, right=n14)
n7 = Node(7, left=n4, right=n10)

And print it using:

tv = TreePrinter(n7)
print(tv)

The output is:

        7
        /\
     ---  ---
     |       |
    4       10
    /\      /\
   -  -    -  -
   |   |   |   |
  3   6   8   14
  /
 -
 |
1


问:
Using AWS Toolkit in Visual Studio 2019 for LocalStack?
Can the AWS Toolkit in Visual Studio 2019 be used to access LocalStack running on my development machine?</p>

答:
I have been trying to do this for a long time now. But unfortunately, I have gone through a significant number of configuration permutations without luck.

I believe that as long as custom endpoints are not allowed on AWS Toolkit, the answer will be "no."

Keep an eye on https://github.com/aws/aws-toolkit-vscode/issues/2007


问:
React: Update a self-contained grandchild from a click even from grandparent
I currently have the following situation:

```<code><GrandParent> // click happens here
<Parent>
<Child> // self-contained with its own state
</code>```

Is there a way to update the react state inside of the child with a click in the GrandParent? I hate having all this Child-specific code in GrandParent.
Right now, the only way I know to make the code functional is to pull all state into GrandParent and make state changes when the click happens, then pass that state into the child (vis useContext hook).

Update:
So I researched this further and yes, I could use solutions like redux, however this feels overkill for a small app. I did find some non-library solutions that might be a good fit for anyone looking at this question in the future.

The following solution uses 'this' binding. It works even if it's a bit janky. But the downside is that you have a global name space pollution and The grandparent has to have access to the grandchild, which I don't (it's on a different 'page').
https://www.codeproject.com/Tips/1215984/Update-State-of-a-Component-from-Another-in-React

This approach uses an event emitter to signal when a state change should happen. It's pretty clean but uses a library, albeit a tiny one. I like this approach, however, it doesn't feel very 'reacty'.
https://medium.com/@krzakmarek88/eventemitter-instead-of-lifting-state-up-f5f105054a5

Finally, I ended up using this solution. The gist is that instead of using a react context for storing state, you use the context to store functions that trigger state changes. Since the callbacks don't change themselves, you avoid unnecessary redraws and the solution stays within the bounds of normal react.
https://javascript.plainenglish.io/dispatch-an-action-to-update-a-sibling-within-react-e98f5b5041f3

答: You could use a top-level state management tool like React Redux: https://react-redux.js.org/introduction/getting-started</p>

Body:
I currently have the following situation:

<GrandParent> // click happens here
<Parent>
<Child> // self-contained with its own state

Is there a way to update the react state inside of the child with a click in the GrandParent? I hate having all this Child-specific code in GrandParent.
Right now, the only way I know to make the code functional is to pull all state into GrandParent and make state changes when the click happens, then pass that state into the child (vis useContext hook).

Update:
So I researched this further and yes, I could use solutions like redux, however this feels overkill for a small app. I did find some non-library solutions that might be a good fit for anyone looking at this question in the future.

The following solution uses 'this' binding. It works even if it's a bit janky. But the downside is that you have a global name space pollution and The grandparent has to have access to the grandchild, which I don't (it's on a different 'page').
https://www.codeproject.com/Tips/1215984/Update-State-of-a-Component-from-Another-in-React

This approach uses an event emitter to signal when a state change should happen. It's pretty clean but uses a library, albeit a tiny one. I like this approach, however, it doesn't feel very 'reacty'.
https://medium.com/@krzakmarek88/eventemitter-instead-of-lifting-state-up-f5f105054a5

Finally, I ended up using this solution. The gist is that instead of using a react context for storing state, you use the context to store functions that trigger state changes. Since the callbacks don't change themselves, you avoid unnecessary redraws and the solution stays within the bounds of normal react.
https://javascript.plainenglish.io/dispatch-an-action-to-update-a-sibling-within-react-e98f5b5041f3


问:
extends number but do not restrict to a specific number
Probably been asked and answered but I didn't find the answer - so I ask.

The workaround is not great as if I want to include more type it will not be as easy to upgrade.
Any better way of doing it ?

declare const max:  (a: A) => (b: A) => A

max (2) (3)     // Argument of type '3' is not assignable to parameter of type '2'
max ('a') ('b') // Argument of type '"b"' is not assignable to parameter of type '"a"'

// Possible workaround but will become clumsy if possible type to extends grow

declare const maxClumsy: {
    (a: number): (b: number) => number
    (a: string): (b: string) => string
}

maxClumsy (2) (3)
maxClumsy ('a') ('b')
```

playground link

答:
Function overloads are the way to go here, I say. For just two types, your declaration seems fine:

```<code>declare const maxClumsy: {
    (a: number): (b: number) => number
    (a: string): (b: string) => string
}
</code>```

But if you really are concerned with the repetition of string and number, then you can construct this type programmatically; function overloads are equivalent to an intersection of function types, so we can use a distributive conditional type and the UnionToIntersection helper from this other Q&A to transform the union type string | number into the desired type:

```<code>type CurriedUnion<T> = T extends any ? (a: T) => (b: T) => T : never
type UnionToIntersection<T> = (T extends any ? (a: T) => void : never) extends (a: infer U) => void ? U : never
type CurriedOverload<T> = UnionToIntersection<CurriedUnion<T>>
</code>```

Usage:

```<code>// type Test = ((a: string) => (b: string) => string) & ((a: number) => (b: number) => number)
type Test = CurriedOverload<string | number>

declare const coolMax: CurriedOverload<string | number>

// OK
coolMax (2) (3)
// OK
coolMax ('a') ('b')
// error
coolMax (2) ('b')
// error
coolMax ('a') (3)
</code>```

Playground Link

Be forewarned that distributing over union types like this can cause unexpected results when the input types are themselves unions; particularly, boolean is defined as the union type true | false, so this will not do what you want in that case.

Body:
Probably been asked and answered but I didn't find the answer - so I ask.

The workaround is not great as if I want to include more type it will not be as easy to upgrade.
Any better way of doing it ?

declare const max:  (a: A) => (b: A) => A

max (2) (3)     // Argument of type '3' is not assignable to parameter of type '2'
max ('a') ('b') // Argument of type '"b"' is not assignable to parameter of type '"a"'

// Possible workaround but will become clumsy if possible type to extends grow

declare const maxClumsy: {
    (a: number): (b: number) => number
    (a: string): (b: string) => string
}

maxClumsy (2) (3)
maxClumsy ('a') ('b')

<a href="https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEYD2A7AzgF3gWygDwC54AeAQXhDwxBWDXhQFdsAjEGeAH3kxgEsUAcwB88ABRQipAJTwAvKLEspshfFIBYAFDbcecQCZZYgMyz4F+AHor6mIOY0sSAGbwMATwAOCAOQnfeD56FCQsKDQ0PkEUKBYIBAwkeC9YKGwQag5Xd28-A19dfHFfKF9jXxZy61tSe0cUZzdPH3hfACIWdsDghjD4CKiYuIT3ZNSYdMz2eByWv3aobu1tG3gABSRIvniEAHckGABrWCRGWngWRiw9vggIS-AkDMQIZjQPILcvLajd3NaSQoVBodHgghgSD2Ky0oEgsAQyHQWD0AGE3tgPkQAN7aSziSQMZhsGDSIhKIhMVjsVSiKkkvGWCREXgCQRk8TKHgYfhCWnc3mCbQAXxhaIxH0MxjMRTw6PenzEpWqSqq0iAA" rel="nofollow noreferrer">playground link

Body:
Function overloads are the way to go here, I say. For just two types, your declaration seems fine:

declare const maxClumsy: {
    (a: number): (b: number) => number
    (a: string): (b: string) => string
}

But if you really are concerned with the repetition of string and number, then you can construct this type programmatically; function overloads are equivalent to an intersection of function types, so we can use a distributive conditional type and the UnionToIntersection helper from this other Q&A to transform the union type string | number into the desired type:

type CurriedUnion<T> = T extends any ? (a: T) => (b: T) => T : never
type UnionToIntersection<T> = (T extends any ? (a: T) => void : never) extends (a: infer U) => void ? U : never
type CurriedOverload<T> = UnionToIntersection<CurriedUnion<T>>

Usage:

// type Test = ((a: string) => (b: string) => string) & ((a: number) => (b: number) => number)
type Test = CurriedOverload<string | number>

declare const coolMax: CurriedOverload<string | number>

// OK
coolMax (2) (3)
// OK
coolMax ('a') ('b')
// error
coolMax (2) ('b')
// error
coolMax ('a') (3)

<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAwgrgJwQSwgEwKoDtkHssA8AKgHxQC8URUEAHsBFmgM5QCGWIUA-FABRsAXFQCUFMnwBGwomPJlqwrBABuEBAFgAUKEhRseLEVwBJLAwTMIAY2CHiZSn2p0GTVhy68BMuWRW4yGhQSqrqYq6MLPxCUMhYAGbq+n5QAUE8+iFQymqaOuDQ8EioaADyeQA2uGxoDhT6OPjGZhZWtvbFKOgG+A4k2toA9ENQutBEEMzADXw+UNMoWADmqVLCi-Gr4gvAS9sAZPzzWHAAtpLhO+s555cIqacX4drjVFMzlF2lFerVtQRNisoAAfW7PBADLTaNA2SpsBDQaz4aZQZG4SoAWTYtGE33QvwQ-zqQOWoPB9yhw1GZQA0tp0VicfwAExiPgAZhE1KgdIZuAx2No-AA5GwReyRZIJTz1AhcPlGULWZLpdytCMaEgFfzBcy+GKJfwudogA" rel="nofollow noreferrer">Playground Link

Be forewarned that distributing over union types like this can cause unexpected results when the input types are themselves unions; particularly, boolean is defined as the union type true | false, so this will not do what you want in that case.


问:
How to find out what rows are in Pandas DataFrame A only, but not in B (or vice versa), and what rows are in A, as well as in B (or vice versa)?
Ever found yourself wondering what rows are in Pandas DataFrame A only, but not in B (or vice versa), and what rows are in A, as well as in B (or vice versa)?

While there exists pandas.DataFrame.diff() (more like an element-by-element subtraction), pandas.Index.intersection (only work on the index) and pandas.DataFrame.merge() (more like SQL join to merge two DataFrames), none of them does exactly what we need here...

答:
Therefore I wrote these two functions df_diff() and df_overlap() to do exactly that -- see the visual demo and the code below.

Great things about them:

Can compare on any column (not only on the index - default to compare on index if omit arguments on_A and/or on_B)

Can compare on different column combination (like column_this in DataFrame A and column_that in DataFrame B. You can also insert concatenated id columns on your own and then compare on them)

Can handle duplicated/missing ids correctly

They are mainly based on set operations -- super fast

Has error check/handling (will safely return empty DataFrame if found no result or got invalid input)

To use the function(s), simply copy them from below, or visit my GitHub repo for a full use case!

import pandas as pd

def df_diff(df_A: pd.DataFrame, df_B: pd.DataFrame, on_A: str = "", on_B: str = "") -> pd.DataFrame:
    """
    Function: Compare DataFrame "A" and "B" to find rows only in "A" but not in "B"
    Input:
        df_A: DataFrame "A" ("left table")
        df_B: DataFrame "B" ("right table")
        on_A: column name in DataFrame "A" to compare on. If not provided/valid, will default to using df_A's index
        on_B: column name in DataFrame "B" to compare on. If not provided/valid, will default to using df_B's index

    Output:
        DataFrame containing diff result (all rows only in df_A but not in df_B, and same columns as df_A)
        If find zero rows, will return a DataFrame of 0 row and same columns as df_A (can be checked by `df_output.empty and df_output.shape[1] != 0`)
        If input is not valid DataFrame, will return a DataFrame of 0 row and 0 column (can be checked by `df_output.empty and df_output.shape[1] == 0`)

    Dependency: `import pandas as pd`
    History: 2022-02-07 Developed by frank-yifei-wang@GitHub
    """

    if type(df_A) != pd.core.frame.DataFrame or type(df_B) != pd.core.frame.DataFrame:
        return pd.DataFrame()

    if on_A != "" and on_A in df_A.columns:
        id_col_A = df_A[on_A]
    else:
        id_col_A = df_A.index
    if on_B != "" and on_B in df_B.columns:
        id_col_B = df_B[on_B]
    else:
        id_col_B = df_B.index

    id_set_A = set(id_col_A)
    id_set_B = set(id_col_B)

    id_set_diff = id_set_A.difference(id_set_B)
    df_output = df_A[id_col_A.isin(id_set_diff)].copy()

    return df_output

def df_overlap(df_A: pd.DataFrame, df_B: pd.DataFrame, on_A: str = "", on_B: str = "") -> pd.DataFrame:
    """
    Function: Compare DataFrame "A" and "B" to find rows in "A" and also in "B"
    Input:
        df_A: DataFrame "A" ("left table")
        df_B: DataFrame "B" ("right table")
        on_A: column name in DataFrame "A" to compare on. If not provided/valid, will default to using df_A's index
        on_B: column name in DataFrame "B" to compare on. If not provided/valid, will default to using df_B's index

    Output:
        DataFrame containing overlap result (all rows in df_A and also in df_B, and same columns as df_A)
        Note: result of df_overlap(df_A, df_B) (= a slice of df_A) is different from df_overlap(df_B, df_A) (= a slice of df_B)
        If find zero rows, will return a DataFrame of 0 row and same columns as df_A (can be checked by `df_output.empty and df_output.shape[1] != 0`)
        If input is not valid DataFrame, will return a DataFrame of 0 row and 0 column (can be checked by `df_output.empty and df_output.shape[1] == 0`)

    Dependency: `import pandas as pd`
    History: 2022-02-07 Developed by frank-yifei-wang@GitHub
    """

    if type(df_A) != pd.core.frame.DataFrame or type(df_B) != pd.core.frame.DataFrame:
        return pd.DataFrame()

    if on_A != "" and on_A in df_A.columns:
        id_col_A = df_A[on_A]
    else:
        id_col_A = df_A.index
    if on_B != "" and on_B in df_B.columns:
        id_col_B = df_B[on_B]
    else:
        id_col_B = df_B.index

    id_set_A = set(id_col_A)
    id_set_B = set(id_col_B)

    id_set_overlap = id_set_A.intersection(id_set_B)
    df_output = df_A[id_col_A.isin(id_set_overlap)].copy()

    return df_output
```


问:
XSLT changing a node via a named template call from within a different node
Edit: the error was in a wrong when condition.

Source xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<mainNode>
   <levelOneNodes>
      <levelOneNode>
         <value name="triggeringValue">
            <levelTwoNodes>
               <levelTwoNode attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B1" attributeTwo="B1" attributeThree="B1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C1" attributeTwo="C1" attributeThree="C1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
      <levelOneNode>
         <value name="anotherValue">
            <levelTwoNodes>
               <levelTwoNode attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B2" attributeTwo="B2" attributeThree="B2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C2" attributeTwo="C2" attributeThree="C2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
    </levelOneNodes>
</mainNode>
</code>```

Expected trasnformed xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<mainNode>
   <levelOneNodes>
      <levelOneNode>
         <value name="triggeringValue">
            <levelTwoNodes>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="B1" attributeTwo="B1" attributeThree="B1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="C1" attributeTwo="C1" attributeThree="C1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
      <levelOneNode>
         <value name="anotherValue">
            <levelTwoNodes>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B2" attributeTwo="B2" attributeThree="B2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C2" attributeTwo="C2" attributeThree="C2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
    </levelOneNodes>
</mainNode>
</code>```

That is, when a levelTwoNode node nested into a value node with attribute name "triggeringValue" is encountered, all the levelTwoNode nodes in the document with the same attributeOne and attributeTwo as the triggering node's should be injected with the attribute injectedAttribute="triggeringValue".

I am using this xslt:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

    <xsl:output encoding="Windows-1252" method="xml" indent="no" omit-xml-declaration="no" />

    <!-- Copy the whole output -->
    <xsl:template match="@* |node() ">
        <xsl:copy>
            <xsl:apply-templates select="@* |node() "/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//levelOneNodes/levelOneNode/value/levelTwoNodes/levelTwoNode" >

        <xsl:call-template name="myTemplate">

            <xsl:with-param name="myAttrOne" select=" current()/@attributeOne " />
            <xsl:with-param name="myAttrTwo" select=" current()/@attributeTwo " />
            <xsl:with-param name="myValue" select=" current()/../../@name " />

        </xsl:call-template>

    </xsl:template>

    <xsl:template name="myTemplate">

        <xsl:param name="myAttrOne" />
        <xsl:param name="myAttrTwo" />
        <xsl:param name="myValue" />

        <xsl:choose>

            <xsl:when test="boolean(//levelTwoNode[(@attributeOne = $myAttrOne) and (@attributeTwo = $myAttrTwo)]) and boolean($myValue = 'triggeringValue')">

                <xsl:copy>

                    <xsl:attribute name="injectedAttribute"><xsl:value-of select="$myValue"/></xsl:attribute>
                    <xsl:apply-templates select="@* |node() "/>

                </xsl:copy>

            </xsl:when>

            <xsl:otherwise>

                <xsl:copy>

                    <xsl:apply-templates select="@* |node() "/>

                </xsl:copy>

            </xsl:otherwise>
        </xsl:choose>

    </xsl:template>

</xsl:stylesheet>
</code>```

that results in this xml:

```<code><?xml version="1.0" encoding="Windows-1252"?><mainNode>
   <levelOneNodes>
      <levelOneNode>
         <value name="triggeringValue">
            <levelTwoNodes>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="B1" attributeTwo="B1" attributeThree="B1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="C1" attributeTwo="C1" attributeThree="C1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
      <levelOneNode>
         <value name="anotherValue">
            <levelTwoNodes>
               <levelTwoNode attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B2" attributeTwo="B2" attributeThree="B2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C2" attributeTwo="C2" attributeThree="C2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
    </levelOneNodes>
</mainNode>
</code>```

where the new attribute injectedAttribute is not injected into the first levelTwoNode of the second levelOneNode (the one with the child node value with attribute name "anotherValue") even though it has the same attributeOne and attributeTwo (with value "A") of one of the levelTwoNode nodes inside the first levelOneNode node (the one with the child node value with attribute name "triggeringValue"). The attribute injectedAttribute is injected only in all the levelTwoNode nodes inside the triggeringValue value node.

Why does this condition:

```<code><xsl:when test="boolean(//levelTwoNode[(@attributeOne = $myAttrOne) and (@attributeTwo = $myAttrTwo)]) and boolean($myValue = 'triggeringValue')">
</code>```

is limited in the scope of the calling node? The query //levelTwoNode[(@attributeOne = $myAttrOne) and (@attributeTwo = $myAttrTwo)] should fetch all levelTwoNode nodes with the passed attributes and the condition $myValue = 'triggeringValue' should not limit that query.

What am I missing?

Thanks for any help.

答:
This is very confusing. I could not understand your code at all. If I understand your description correctly (which is a VERY big if), then you want to do something like:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="trigger" match="value[@name='triggeringValue']/levelTwoNodes/levelTwoNode" use="concat(@attributeOne, '|', @attributeTwo)" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="levelTwoNode[key('trigger', concat(@attributeOne, '|', @attributeTwo))]">
    <xsl:copy>
        <xsl:attribute name="injectedAttribute">triggeringValue</xsl:attribute>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

The way this works is it indexes all levelTwoNode elements that are descendants of <value name="triggeringValue">. Then, any levelTwoNode element that has the same two attribute values as one of the indexed elements (incl. the indexed elements themselves) is modified by adding the injectedAttribute attribute.

Body:
Edit: the error was in a wrong when condition.

Source xml:

<?xml version="1.0" encoding="UTF-8"?>
<mainNode>
   <levelOneNodes>
      <levelOneNode>
         <value name="triggeringValue">
            <levelTwoNodes>
               <levelTwoNode attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B1" attributeTwo="B1" attributeThree="B1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C1" attributeTwo="C1" attributeThree="C1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
      <levelOneNode>
         <value name="anotherValue">
            <levelTwoNodes>
               <levelTwoNode attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B2" attributeTwo="B2" attributeThree="B2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C2" attributeTwo="C2" attributeThree="C2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
    </levelOneNodes>
</mainNode>

Expected trasnformed xml:

<?xml version="1.0" encoding="UTF-8"?>
<mainNode>
   <levelOneNodes>
      <levelOneNode>
         <value name="triggeringValue">
            <levelTwoNodes>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="B1" attributeTwo="B1" attributeThree="B1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="C1" attributeTwo="C1" attributeThree="C1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
      <levelOneNode>
         <value name="anotherValue">
            <levelTwoNodes>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B2" attributeTwo="B2" attributeThree="B2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C2" attributeTwo="C2" attributeThree="C2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
    </levelOneNodes>
</mainNode>

That is, when a levelTwoNode node nested into a value node with attribute name "triggeringValue" is encountered, all the levelTwoNode nodes in the document with the same attributeOne and attributeTwo as the triggering node's should be injected with the attribute injectedAttribute="triggeringValue".

I am using this xslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

    <xsl:output encoding="Windows-1252" method="xml" indent="no" omit-xml-declaration="no" />

    <xsl:template match="@* |node() ">
        <xsl:copy>
            <xsl:apply-templates select="@* |node() "/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//levelOneNodes/levelOneNode/value/levelTwoNodes/levelTwoNode" >

        <xsl:call-template name="myTemplate">

            <xsl:with-param name="myAttrOne" select=" current()/@attributeOne " />
            <xsl:with-param name="myAttrTwo" select=" current()/@attributeTwo " />
            <xsl:with-param name="myValue" select=" current()/../../@name " />

        </xsl:call-template>

    </xsl:template>

    <xsl:template name="myTemplate">

        <xsl:param name="myAttrOne" />
        <xsl:param name="myAttrTwo" />
        <xsl:param name="myValue" />

        <xsl:choose>

            <xsl:when test="boolean(//levelTwoNode[(@attributeOne = $myAttrOne) and (@attributeTwo = $myAttrTwo)]) and boolean($myValue = 'triggeringValue')">

                <xsl:copy>

                    <xsl:attribute name="injectedAttribute"><xsl:value-of select="$myValue"/></xsl:attribute>
                    <xsl:apply-templates select="@* |node() "/>

                </xsl:copy>

            </xsl:when>

            <xsl:otherwise>

                <xsl:copy>

                    <xsl:apply-templates select="@* |node() "/>

                </xsl:copy>

            </xsl:otherwise>
        </xsl:choose>

    </xsl:template>

</xsl:stylesheet>

that results in this xml:

<?xml version="1.0" encoding="Windows-1252"?><mainNode>
   <levelOneNodes>
      <levelOneNode>
         <value name="triggeringValue">
            <levelTwoNodes>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="B1" attributeTwo="B1" attributeThree="B1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode injectedAttribute="triggeringValue" attributeOne="C1" attributeTwo="C1" attributeThree="C1">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
      <levelOneNode>
         <value name="anotherValue">
            <levelTwoNodes>
               <levelTwoNode attributeOne="A" attributeTwo="A" attributeThree="A">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="B2" attributeTwo="B2" attributeThree="B2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
               <levelTwoNode attributeOne="C2" attributeTwo="C2" attributeThree="C2">
                  <textData>This is some text.</textData>
               </levelTwoNode>
            </levelTwoNodes>
         </value>
      </levelOneNode>
    </levelOneNodes>
</mainNode>

where the new attribute injectedAttribute is not injected into the first levelTwoNode of the second levelOneNode (the one with the child node value with attribute name "anotherValue") even though it has the same attributeOne and attributeTwo (with value "A") of one of the levelTwoNode nodes inside the first levelOneNode node (the one with the child node value with attribute name "triggeringValue"). The attribute injectedAttribute is injected only in all the levelTwoNode nodes inside the triggeringValue value node.

Why does this condition:

<xsl:when test="boolean(//levelTwoNode[(@attributeOne = $myAttrOne) and (@attributeTwo = $myAttrTwo)]) and boolean($myValue = 'triggeringValue')">

is limited in the scope of the calling node? The query //levelTwoNode[(@attributeOne = $myAttrOne) and (@attributeTwo = $myAttrTwo)] should fetch all levelTwoNode nodes with the passed attributes and the condition $myValue = 'triggeringValue' should not limit that query.

What am I missing?

Thanks for any help.

Body:
This is very confusing. I could not understand your code at all. If I understand your description correctly (which is a VERY big if), then you want to do something like:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="trigger" match="value[@name='triggeringValue']/levelTwoNodes/levelTwoNode" use="concat(@attributeOne, '|', @attributeTwo)" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="levelTwoNode[key('trigger', concat(@attributeOne, '|', @attributeTwo))]">
    <xsl:copy>
        <xsl:attribute name="injectedAttribute">triggeringValue</xsl:attribute>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

The way this works is it indexes all levelTwoNode elements that are descendants of <value name="triggeringValue">. Then, any levelTwoNode element that has the same two attribute values as one of the indexed elements (incl. the indexed elements themselves) is modified by adding the injectedAttribute attribute.


问:
Printing date from Year, Month and Day columns in Pandas
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
First 5 rows of the dataframe
As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:

```<code>df['Year'] = pd.to_datetime(df[['Year','Month','Day']])
</code>```

But, I keep getting the error as below:

```<code>ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)
</code>```

It would be great if I can get any help for the same.

答:
try this:</p>
```<code>df.apply(lambda x:'%s %s %s' % (x['year'],x['month'], x['day']),axis=1)
</code>```

Body:
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
First 5 rows of the dataframe
As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:

df['Year'] = pd.to_datetime(df[['Year','Month','Day']])

But, I keep getting the error as below:

ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)

It would be great if I can get any help for the same.

Body:
try this:

df.apply(lambda x:'%s %s %s' % (x['year'],x['month'], x['day']),axis=1)


问:
Error when setting the attribute on a styled component
I get an "Object(...)(...).attrs is not a function" error when I try setting the attribute of a styled input component, like so

```<code>import styled from '@emotion/styled'

const DateInput = styled.input.attrs({
    type: 'date'
  })`
    width: 360px;
    border: 1px solid #ccc;
    border-radius: 5px;
    height: 100%;
    padding: 0px 12px 0px 20px;
`
</code>```

Any idea of what I'm doing wrong?

答:
Use:

```<code> import styled from "styled-components";
</code>```

instead of:

```<code> '@emotion/styled'
</code>```

Body:
I get an "Object(...)(...).attrs is not a function" error when I try setting the attribute of a styled input component, like so

import styled from '@emotion/styled'

const DateInput = styled.input.attrs({
    type: 'date'
  })`
    width: 360px;
    border: 1px solid #ccc;
    border-radius: 5px;
    height: 100%;
    padding: 0px 12px 0px 20px;
`

Any idea of what I'm doing wrong?

Body:
Use:

 import styled from "styled-components";

instead of:

 '@emotion/styled'


问:
can't access data from URL in pandas/jupyter notebook - Programming noob
I'm new to python.
I started using jupyter notebook on a project that i'm doing to get into programming school
I wanted to work with covid data. I took the raw data from John Hopskins Git hub via URLs
i got data for confirmed cases, deaths and recovered cases. Each set of data is on a different url
Everything works fine except recovered cases. apparently i can't access the data since in my code, it returns NaN values for every country. I pushed my code on github so a friend could take a look and he can access some data (not a lot), when i can't
I don't get why...

I have another issue; i tried to make a figure with different curves showing the progression of the covid cases in France (i picked France beacuse i'm french)
and there's several issues with those curves.

the "recovered"(green) and "deaths"(orange) curves are flat. I was expecting it for the recovered cases since i can't access the data, but i don't get why it would happen witht the deaths cases, since i have values
Also, i've been trying to find another way to display the dates (on the y axis). There are so many values, (1 entry a day for the whole covid crisis) that they overlap each other. I put them on vertical but it's not enough

My code is available at : https://github.com/aaanoushka/Projet-OCR-Covid19/blob/main/Analyse_covid19_pays.ipynb?fbclid=IwAR3cjmCze1vJQ101l8wlD4tAx_slhOZQ1YgJ8jpnmso05CLmYoyFL2DofXc

I'd appreciate so much if someone wold be willing to take a look!
Feel free to ask me anything, i'll try my best to give you any detail needed

Thank you

答:
the "recovered"(green) and "deaths"(orange) curves are flat.

There are two issues here.

The data source you are using has discontinued publishing the 'recovery' statistic. You can read the details here. It seems that their concern is that there isn't really a globally consistent definition of 'recovery.' Some places only count confirmed recoveries. Other places say that if a patient is not reported as dead, then they must have recovered.

You may be able to find another source of this data elsewhere.

The death count is not flat on that plot. It is just very hard to see. If you comment out the confirmed case count plotting, you'll see what I mean:

Another way to check this is to compare the last element of confirmed and the last element of deaths:

print("Most recent death count in France", deaths_fr.iloc[-1])
print("Most recent case count in France", confirmed_fr.iloc[-1])
```
<p>Output:</p>
```Most recent death count in France 135264
Most recent case count in France 21511997
```
<p>If you plot these two on the same scale, the death count will be squished - there are about 100 times more cases than deaths.</p>
</li>
</ol>
<blockquote>
<p>Also, i've been trying to find another way to display the dates (on the y axis)</p>
</blockquote>
<p>It looks like the indexes of the dataframes are defined as strings, and not as dates. Try converting them to dates:</p>
<pre class="lang-py prettyprint-override"><code>deaths_fr.index = pd.to_datetime(deaths_fr.index)
recovered_fr.index = pd.to_datetime(recovered_fr.index)
confirmed_fr.index = pd.to_datetime(confirmed_fr.index)
</code>```

I get more reasonable axis labels when I do that.

Body:
the "recovered"(green) and "deaths"(orange) curves are flat.

There are two issues here.

The data source you are using has discontinued publishing the 'recovery' statistic. You can read the details here. It seems that their concern is that there isn't really a globally consistent definition of 'recovery.' Some places only count confirmed recoveries. Other places say that if a patient is not reported as dead, then they must have recovered.

You may be able to find another source of this data elsewhere.

The death count is not flat on that plot. It is just very hard to see. If you comment out the confirmed case count plotting, you'll see what I mean:

Another way to check this is to compare the last element of confirmed and the last element of deaths:

print("Most recent death count in France", deaths_fr.iloc[-1])
print("Most recent case count in France", confirmed_fr.iloc[-1])

Output:

Most recent death count in France 135264
Most recent case count in France 21511997

If you plot these two on the same scale, the death count will be squished - there are about 100 times more cases than deaths.

Also, i've been trying to find another way to display the dates (on the y axis)

It looks like the indexes of the dataframes are defined as strings, and not as dates. Try converting them to dates:

deaths_fr.index = pd.to_datetime(deaths_fr.index)
recovered_fr.index = pd.to_datetime(recovered_fr.index)
confirmed_fr.index = pd.to_datetime(confirmed_fr.index)

I get more reasonable axis labels when I do that.


问:
How to unzip files recursively in Java?
I have zip file which contains some other zip files.

For example, the mail file is abc.zip and it contains xyz.zip, class1.java, class2.java. And xyz.zip contains the file class3.java and class4.java.

So I need to extract the zip file using Java to a folder that should contain class1.java, class2.java, class3.java and class4.java.

答:
Warning, the code here is ok for trusted zip files, there's no path validation before write which may lead to security vulnerability as described in zip-slip-vulnerability if you use it to deflate an uploaded zip file from unknown client.

This solution is very similar to the previous solutions already posted, but this one recreates the proper folder structure on unzip.

```<code>public static void extractFolder(String zipFile) throws IOException {
int buffer = 2048;
File file = new File(zipFile);

try (ZipFile zip = new ZipFile(file)) {
  String newPath = zipFile.substring(0, zipFile.length() - 4);

  new File(newPath).mkdir();
  Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

  // Process each entry
  while (zipFileEntries.hasMoreElements()) {
    // grab a zip file entry
    ZipEntry entry = zipFileEntries.nextElement();
    String currentEntry = entry.getName();
    File destFile = new File(newPath, currentEntry);
    File destinationParent = destFile.getParentFile();

    // create the parent directory structure if needed
    destinationParent.mkdirs();

    if (!entry.isDirectory()) {
      BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
      int currentByte;
      // establish buffer for writing file
      byte[] data = new byte[buffer];

      // write the current file to disk
      FileOutputStream fos = new FileOutputStream(destFile);
      try (BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {

        // read and write until last byte is encountered
        while ((currentByte = is.read(data, 0, buffer)) != -1) {
          dest.write(data, 0, currentByte);
        }
        dest.flush();
        is.close();
      }
    }

    if (currentEntry.endsWith(".zip")) {
      // found a zip file, try to open
      extractFolder(destFile.getAbsolutePath());
    }
  }
}
</code>```

}

OwnerDisplayName: Anish

Title: How to unzip files recursively in Java?

Body:
Warning, the code here is ok for trusted zip files, there's no path validation before write which may lead to security vulnerability as described in zip-slip-vulnerability if you use it to deflate an uploaded zip file from unknown client.

This solution is very similar to the previous solutions already posted, but this one recreates the proper folder structure on unzip.

public static void extractFolder(String zipFile) throws IOException {
int buffer = 2048;
File file = new File(zipFile);

try (ZipFile zip = new ZipFile(file)) {
  String newPath = zipFile.substring(0, zipFile.length() - 4);

  new File(newPath).mkdir();
  Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

  // Process each entry
  while (zipFileEntries.hasMoreElements()) {
    // grab a zip file entry
    ZipEntry entry = zipFileEntries.nextElement();
    String currentEntry = entry.getName();
    File destFile = new File(newPath, currentEntry);
    File destinationParent = destFile.getParentFile();

    // create the parent directory structure if needed
    destinationParent.mkdirs();

    if (!entry.isDirectory()) {
      BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
      int currentByte;
      // establish buffer for writing file
      byte[] data = new byte[buffer];

      // write the current file to disk
      FileOutputStream fos = new FileOutputStream(destFile);
      try (BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {

        // read and write until last byte is encountered
        while ((currentByte = is.read(data, 0, buffer)) != -1) {
          dest.write(data, 0, currentByte);
        }
        dest.flush();
        is.close();
      }
    }

    if (currentEntry.endsWith(".zip")) {
      // found a zip file, try to open
      extractFolder(destFile.getAbsolutePath());
    }
  }
}

}


问:
Canvas - Keeping aspect ratio while also keeping pixel amount
I have a canvas like so:

But when resizing the window and redrawing, you can get anything in between.

I keep the aspect ratio with this code:

function setCanvasSize(){
    ctx.canvas.width = (window.innerWidth)*0.8;
    ctx.canvas.height= (window.innerWidth)*0.5;
}
setCanvasSize()
$(window).resize(function(){
    setCanvasSize()
})
```
<p>and that keeps it nice and clean, the same-looking size, but how many pixels are in there changes, so when my program draws, it's always in a different spot, although the aspect is the same, so it looks really weird.</p>
<p>Any way that I can somehow tweak how I draw things, or a way to keep how many pixels there are?</p>
<p>Edit: code snippet to reproduce</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const ctx = document.getElementById('game').getContext("2d");

$('#game').css('width', '100%');
$(window).resize(function(){
    $('#game').height($('#game').width() / 2.031);
 });

 const imageAt=((href,x,y,sizex,sizey)=>{
      var img = new Image();
      img.addEventListener('load', function() {
          ctx.drawImage(img, x, y, sizex, sizey);
      }, false);
      img.src = href
  })
imageAt('https://b.thumbs.redditmedia.com/bZedgr0gq7RQBBnVYVc-Nmzdr-5vEUg4Dj8nTrMb7yA.png',0,0,50,50)</code>```

#game{
    padding-left: 0;
    padding-right: 0;
    display: block;
    margin: 0;
    border:5px solid green;
    padding:0;
}

#vertical-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: black;
  padding:0;
}

body{
  background-color: black;
  padding:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <title>Tiled Canvas Engine Test 1</title>
        <meta name="viewport" content="width=device-width, initial-scale=0.75">
        <link rel="stylesheet" href="./index.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="engine.js"></script>
        <script defer src="script.js"></script>
    </head>
    <body>
        <div id="vertical-center">
            <canvas id="game"></canvas>
        </div>
    </body>
</html></code>```

答:
In order to render properly the canvas element needs to have its width and height attributes set explicitly. This will define the viewport into which graphics will be draw. The style attributes for width and height which is what jQuery sets via the width() and height() functions will only stretch the viewport to fit. (Note: for high DPI displays, i.e. Retina, you will want to double the dimensions when specifying the attributes).

The critical change is this:

```<code>  // Updates the actual width and height attributes
  canvas.width = $('#game').width() * window.devicePixelRatio;
  canvas.height = $('#game').height() * window.devicePixelRatio;
</code>```

The snippet below also handles clearing the canvas, redrawing the image, and saving the Image once loaded:

const ctx = document.getElementById('game').getContext("2d");

$('#game').css('width', '100%');
$(document).ready(handleResize);
$(window).resize(handleResize);

function handleResize() {
  // sets the style.height and style.width for the canvas
  $('#game').height($('#game').width() / 2.031);
  let canvas = $('#game').get(0);

  // Updates the actual width and height attributes
  canvas.width = $('#game').width() * window.devicePixelRatio;
  canvas.height = $('#game').height() * window.devicePixelRatio;

  // redraw
  if (img) {
    redraw();
  }
}

var img;
const imageAt = ((href, x, y, sizex, sizey) => {
  img = new Image();
  img.addEventListener('load', function() {
    ctx.drawImage(img, x, y, sizex, sizey);
  }, false);
  img.src = href
})
imageAt('https://b.thumbs.redditmedia.com/bZedgr0gq7RQBBnVYVc-Nmzdr-5vEUg4Dj8nTrMb7yA.png', 0, 0, 50 * window.devicePixelRatio, 50 * window.devicePixelRatio)

function redraw() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ctx.drawImage(img, 0, 0, 50 * window.devicePixelRatio, 50 * window.devicePixelRatio);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#game {
  padding-left: 0;
  padding-right: 0;
  display: block;
  margin: 0;
  border: 5px solid green;
  padding: 0;
}

#vertical-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: black;
  padding: 0;
}

body {
  background-color: black;
  padding: 0;
}</code>```

  <title>Tiled Canvas Engine Test 1</title>
  <meta name="viewport" content="width=device-width, initial-scale=0.75">
  <link rel="stylesheet" href="./index.css">

    <canvas id="game"></canvas>

```

Body:
I have a canvas like so:

But when resizing the window and redrawing, you can get anything in between.

I keep the aspect ratio with this code:

function setCanvasSize(){
    ctx.canvas.width = (window.innerWidth)*0.8;
    ctx.canvas.height= (window.innerWidth)*0.5;
}
setCanvasSize()
$(window).resize(function(){
    setCanvasSize()
})

and that keeps it nice and clean, the same-looking size, but how many pixels are in there changes, so when my program draws, it's always in a different spot, although the aspect is the same, so it looks really weird.

Any way that I can somehow tweak how I draw things, or a way to keep how many pixels there are?

Edit: code snippet to reproduce

const ctx = document.getElementById('game').getContext("2d");

$('#game').css('width', '100%');
$(window).resize(function(){
    $('#game').height($('#game').width() / 2.031);
 });

 const imageAt=((href,x,y,sizex,sizey)=>{
      var img = new Image();
      img.addEventListener('load', function() {
          ctx.drawImage(img, x, y, sizex, sizey);
      }, false);
      img.src = href
  })
imageAt('https://b.thumbs.redditmedia.com/bZedgr0gq7RQBBnVYVc-Nmzdr-5vEUg4Dj8nTrMb7yA.png',0,0,50,50)

#game{
    padding-left: 0;
    padding-right: 0;
    display: block;
    margin: 0;
    border:5px solid green;
    padding:0;
}

#vertical-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: black;
  padding:0;
}

body{
  background-color: black;
  padding:0;
}

        <title>Tiled Canvas Engine Test 1</title>
        <meta name="viewport" content="width=device-width, initial-scale=0.75">
        <link rel="stylesheet" href="./index.css">

            <canvas id="game"></canvas>

Body:
In order to render properly the canvas element needs to have its width and height attributes set explicitly. This will define the viewport into which graphics will be draw. The style attributes for width and height which is what jQuery sets via the width() and height() functions will only stretch the viewport to fit. (Note: for high DPI displays, i.e. Retina, you will want to double the dimensions when specifying the attributes).

The critical change is this:

  // Updates the actual width and height attributes
  canvas.width = $('#game').width() * window.devicePixelRatio;
  canvas.height = $('#game').height() * window.devicePixelRatio;

The snippet below also handles clearing the canvas, redrawing the image, and saving the Image once loaded:

const ctx = document.getElementById('game').getContext("2d");

$('#game').css('width', '100%');
$(document).ready(handleResize);
$(window).resize(handleResize);

function handleResize() {
  // sets the style.height and style.width for the canvas
  $('#game').height($('#game').width() / 2.031);
  let canvas = $('#game').get(0);

  // Updates the actual width and height attributes
  canvas.width = $('#game').width() * window.devicePixelRatio;
  canvas.height = $('#game').height() * window.devicePixelRatio;

  // redraw
  if (img) {
    redraw();
  }
}

var img;
const imageAt = ((href, x, y, sizex, sizey) => {
  img = new Image();
  img.addEventListener('load', function() {
    ctx.drawImage(img, x, y, sizex, sizey);
  }, false);
  img.src = href
})
imageAt('https://b.thumbs.redditmedia.com/bZedgr0gq7RQBBnVYVc-Nmzdr-5vEUg4Dj8nTrMb7yA.png', 0, 0, 50 * window.devicePixelRatio, 50 * window.devicePixelRatio)

function redraw() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ctx.drawImage(img, 0, 0, 50 * window.devicePixelRatio, 50 * window.devicePixelRatio);
}

#game {
  padding-left: 0;
  padding-right: 0;
  display: block;
  margin: 0;
  border: 5px solid green;
  padding: 0;
}

#vertical-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: black;
  padding: 0;
}

body {
  background-color: black;
  padding: 0;
}

<html>

<head>
  <title>Tiled Canvas Engine Test 1</title>
  <meta name="viewport" content="width=device-width, initial-scale=0.75">
  <link rel="stylesheet" href="./index.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="engine.js"></script>
  <script defer src="script.js"></script>
</head>

<body>
  <div id="vertical-center">
    <canvas id="game"></canvas>
  </div>
</body>

</html>


问:
SwiftUI @MainActor loses global actor
I've got an ObservableObject class that I am calling to via @StateObject from my view. Inside that class is a function and the entire class is marked @MainActor. In my view there is a TextField with an onChange modifier that has a perform calling to that function via viewModel.funcname.

Xcode is complaining with an error of:

```<code>Converting function value of type '@MainActor (String) -> Void' to '(String) -> Void' loses global actor 'MainActor'
</code>```

I've been researching this for hours now and have found little to nothing. Even Apple's own docs say to simply use await but that doesn't work, at least not the many ways I've tried it.

This is the code within my view:

```<code>    TextField("", text: $viewModel.username)
        .onChange(of: viewModel.username, perform: viewModel.editingChanged) // This is where the error occurs
</code>```

This is the function in my class (remember that the entire class is marked @MainActor):

```<code>func editingChanged(_ value: String) {

    let jsonFetchUserExistsURL = URL(string: "https://blah.com")
    let jsonFetchUserExistsTask = jsonFetch(jsonFetchUserExistsURL, defaultValue: [UserExists]())

    guard isNetworkActive else { loadingAlert = true; return }
        Task {
            jsonFetchUserExistsTask.sink (receiveCompletion: { completion in
                switch completion {
                    case .failure:
                        self.loadingState = .failed
                    case .finished:
                        self.checkUser()
                }
            },
            receiveValue: { loadedUserExists in
                self.userExists = loadedUserExists
            }).store(in: &requests)
        }
    }
}
</code>```

I have tried modifying the onChange to read as follows:

```<code>.onChange(of: viewModel.username, perform: await viewModel.editingChanged)
.onChange(of: viewModel.username, perform: Task { await viewModel.editingChanged })
.onChange(of: viewModel.username, perform: Task.detached { await viewModel.editingChanged })
.onChange(of: viewModel.username, perform: DispatchQueue.main.async { viewModel.editingChanged })
</code>```

The entire reason I marked the class @MainActor is because Xcode complained that the function wasn't running on the main thread. It compiled but froze after it complained a few times in the console.

Nothing I've tried seems to change anything. Hoping someone can shed some light on this.

答:
See my comment on the question about whether or not the @MainActor strategy is the right way to address an underlying issue, but to directly address your compilation error, you can use this syntax, which compiles fine:

```<code>.onChange(of: viewModel.username) { viewModel.editingChanged($0) }
</code>```

Title: SwiftUI @MainActor loses global actor

Body:
I've got an ObservableObject class that I am calling to via @StateObject from my view. Inside that class is a function and the entire class is marked @MainActor. In my view there is a TextField with an onChange modifier that has a perform calling to that function via viewModel.funcname.

Xcode is complaining with an error of:

Converting function value of type '@MainActor (String) -> Void' to '(String) -> Void' loses global actor 'MainActor'

I've been researching this for hours now and have found little to nothing. Even Apple's own docs say to simply use await but that doesn't work, at least not the many ways I've tried it.

This is the code within my view:

    TextField("", text: $viewModel.username)
        .onChange(of: viewModel.username, perform: viewModel.editingChanged) // This is where the error occurs

This is the function in my class (remember that the entire class is marked @MainActor):

func editingChanged(_ value: String) {

    let jsonFetchUserExistsURL = URL(string: "https://blah.com")
    let jsonFetchUserExistsTask = jsonFetch(jsonFetchUserExistsURL, defaultValue: [UserExists]())

    guard isNetworkActive else { loadingAlert = true; return }
        Task {
            jsonFetchUserExistsTask.sink (receiveCompletion: { completion in
                switch completion {
                    case .failure:
                        self.loadingState = .failed
                    case .finished:
                        self.checkUser()
                }
            },
            receiveValue: { loadedUserExists in
                self.userExists = loadedUserExists
            }).store(in: &requests)
        }
    }
}

I have tried modifying the onChange to read as follows:

.onChange(of: viewModel.username, perform: await viewModel.editingChanged)
.onChange(of: viewModel.username, perform: Task { await viewModel.editingChanged })
.onChange(of: viewModel.username, perform: Task.detached { await viewModel.editingChanged })
.onChange(of: viewModel.username, perform: DispatchQueue.main.async { viewModel.editingChanged })

The entire reason I marked the class @MainActor is because Xcode complained that the function wasn't running on the main thread. It compiled but froze after it complained a few times in the console.

Nothing I've tried seems to change anything. Hoping someone can shed some light on this.

Body:
See my comment on the question about whether or not the @MainActor strategy is the right way to address an underlying issue, but to directly address your compilation error, you can use this syntax, which compiles fine:

.onChange(of: viewModel.username) { viewModel.editingChanged($0) }


问:
system design for concurrent requests on a ecommerce platform
Suppose you have 1 item in stock but at any instance 1 million requests came to purchase the product how will you design a system that will prevent selling of product more than once?</p>

答:
The answer to this question depends on a lot of factors driven by the business & technical details.
There's a good discussion already on this topic here.

Also, if you're asking this from a Systems Design interview's perspective, then the interviewer is more interested in having a discussion of the sort mentioned in the link shared before than just expecting a "correct" answer.


问:
Entity Framework DateTime and UTC
Is it possible to have Entity Framework (I am using the Code First Approach with CTP5 currently) store all DateTime values as UTC in the database?

Or is there maybe a way to specify it in the mapping, for example in this one for the last_login column:

```<code>modelBuilder.Entity<User>().Property(x => x.Id).HasColumnName("id");
modelBuilder.Entity<User>().Property(x => x.IsAdmin).HasColumnName("admin");
modelBuilder.Entity<User>().Property(x => x.IsEnabled).HasColumnName("enabled");
modelBuilder.Entity<User>().Property(x => x.PasswordHash).HasColumnName("password_hash");
modelBuilder.Entity<User>().Property(x => x.LastLogin).HasColumnName("last_login");
</code>```

答: There is no way to specify the DataTimeKind in the Entity Framework. You may decide to convert the date time values to utc before storing to db and always assume the data retrived from db as UTC. But the DateTime objects materalized during query will always be "Unspecified". You could also evalualte using DateTimeOffset object instead of DateTime.</p>

Title: Entity Framework DateTime and UTC

Body:
Is it possible to have Entity Framework (I am using the Code First Approach with CTP5 currently) store all DateTime values as UTC in the database?

Or is there maybe a way to specify it in the mapping, for example in this one for the last_login column:

modelBuilder.Entity<User>().Property(x => x.Id).HasColumnName("id");
modelBuilder.Entity<User>().Property(x => x.IsAdmin).HasColumnName("admin");
modelBuilder.Entity<User>().Property(x => x.IsEnabled).HasColumnName("enabled");
modelBuilder.Entity<User>().Property(x => x.PasswordHash).HasColumnName("password_hash");
modelBuilder.Entity<User>().Property(x => x.LastLogin).HasColumnName("last_login");


问:
Could not determine the dependencies of task ':app:lintVitalRelease' flutter build error
output after building apk:

```<code>    FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':app:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':app:debugAndroidTestCompileClasspath'.
   > Could not find com.google.firebase:firebase-analytics:.
     Required by:
         project :app
</code>```

here is my build.gradle file in the app directory:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
   def keystorePropertiesFile = rootProject.file('key.properties')
   if (keystorePropertiesFile.exists()) {
       keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
   }

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.XXXX.XXXXX"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 7
        versionName "1.2.8"
        multiDexEnabled true
    }

        signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }
   buildTypes {
       release {
           profile {
                matchingFallbacks = ['debug', 'release']
            }
           signingConfig signingConfigs.release
       }
   }

}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics'
}
apply plugin: 'com.google.gms.google-services'
</code>```

And here is my build.gradle in the android directory:

```<code>buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.10'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

how can I solve this issue, I tried upgrading gradle versions but nothing worked and also updated all my packages still the same. Any help is appreciated - my flutter version is 2.8.1.

答:
I have implemented Firebase in my project and got the same error when trying to make a release and I went in android/app/build.gradle and I added this, and it worked fine:</p>
```<code>kotlinOptions {
    jvmTarget = '1.8'
}

lintOptions {
    disable 'InvalidPackage'
    checkReleaseBuilds false
}
</code>```

Body:
output after building apk:

    FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':app:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':app:debugAndroidTestCompileClasspath'.
   > Could not find com.google.firebase:firebase-analytics:.
     Required by:
         project :app

here is my build.gradle file in the app directory:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
   def keystorePropertiesFile = rootProject.file('key.properties')
   if (keystorePropertiesFile.exists()) {
       keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
   }

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.XXXX.XXXXX"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 7
        versionName "1.2.8"
        multiDexEnabled true
    }

        signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }
   buildTypes {
       release {
           profile {
                matchingFallbacks = ['debug', 'release']
            }
           signingConfig signingConfigs.release
       }
   }

}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics'
}
apply plugin: 'com.google.gms.google-services'

And here is my build.gradle in the android directory:

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.10'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

how can I solve this issue, I tried upgrading gradle versions but nothing worked and also updated all my packages still the same. Any help is appreciated - my flutter version is 2.8.1.

Body:
I have implemented Firebase in my project and got the same error when trying to make a release and I went in android/app/build.gradle and I added this, and it worked fine:

kotlinOptions {
    jvmTarget = '1.8'
}

lintOptions {
    disable 'InvalidPackage'
    checkReleaseBuilds false
}