问:
Is it good practice to mix yield and return statements in python?
I'd quite like to have the following behaviour:

```<code>def foo(bar=None):
    if bar:
        return other_function(other_thing[bar])
    else:
        for i in other_thing:
            yield other_function(i)
</code>```

The idea being that the function can then be used as a generator to build all instances, or it can be used to return a specific instance. Is this a good way to do this in Python? If not, is there a better way.

答:
A common idiom, to yield multiple items, or return a single item as a special case:

def foo(bar=None):
    if bar:
        yield other_function(other_thing[bar])
    else:
        for i in other_thing:
            yield other_function(i)
```
<p>Or if you like more flattened code:</p>
<pre class="lang-py prettyprint-override"><code>def foo(bar=None):
    if bar:
        yield other_function(other_thing[bar])
        return

    for i in other_thing:
        yield other_function(i)
</code>```

The function foo always returns an iterator:

for item in foo():
    ...
```

Body:
I'd quite like to have the following behaviour:

def foo(bar=None):
    if bar:
        return other_function(other_thing[bar])
    else:
        for i in other_thing:
            yield other_function(i)

The idea being that the function can then be used as a generator to build all instances, or it can be used to return a specific instance. Is this a good way to do this in Python? If not, is there a better way.

Body:
A common idiom, to yield multiple items, or return a single item as a special case:

def foo(bar=None):
    if bar:
        yield other_function(other_thing[bar])
    else:
        for i in other_thing:
            yield other_function(i)

Or if you like more flattened code:

def foo(bar=None):
    if bar:
        yield other_function(other_thing[bar])
        return

    for i in other_thing:
        yield other_function(i)

The function foo always returns an iterator:

for item in foo():
    ...


来源: stackexchange

问:
How do I check if there is a variable inside a 2d list?
I am trying to make code that asks what movie you would like to know about and gives you the movie + the director + a rating.

```<code>movieDirectorRatingList = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P.","Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieSelection = input("What movie would you like to know about?")

if movieSelection in movieDirectorRatingList:
    movieLocation = movieDirectorRatingList.count(movieSelection) - 1
    print(f"{movieSelection} directed by {movieDirectorRatingList[movieLocation][2]}{movieDirectorRatingList[movieLocation][3]}" )

elif movieSelection not in movieDirectorRatingList:
    print("Movie not in list")

else:
    print("An unexpected error has occured")
</code>```

I managed to have it working when I used 1-dimensional lists, but when I use 2 dimensional ones it says the Movie isn't in the list. Thank you in advance for any help.

答:
You need to iterate through each list:

for movie in movieDirectorRatingList:
    title, director, rating = movie # let's unpack these here
    if movieSelection in movie:
        print(f"{movieSelection} directed by {director} {rating}" )
        break # found the movie
else:
    print("Movie selection not found")

```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make code that asks what movie you would like to know about and gives you the movie + the director + a rating.

movieDirectorRatingList = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P.","Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieSelection = input("What movie would you like to know about?")

if movieSelection in movieDirectorRatingList:
    movieLocation = movieDirectorRatingList.count(movieSelection) - 1
    print(f"{movieSelection} directed by {movieDirectorRatingList[movieLocation][2]}{movieDirectorRatingList[movieLocation][3]}" )

elif movieSelection not in movieDirectorRatingList:
    print("Movie not in list")

else:
    print("An unexpected error has occured")

I managed to have it working when I used 1-dimensional lists, but when I use 2 dimensional ones it says the Movie isn't in the list. Thank you in advance for any help.


问:
NoClassDefFoundError: java/time/LocalDateTime
I'm new with Java language. I have developed an example of a maven project and I have added the package LocalDateTime.

The problem is that when I run the program it appears me this error:
NoClassDefFoundError: java/time/LocalDateTime

I have added this line to import the package:

```<code>import java.time.LocalDateTime;
</code>```

I haven't added anything in the pom.xml file because with other packages imports I didn't add anything and it works properly.

Do I need to add some plugin or dependency in pom.xml file regarding to LocalDateTime?

Thanks for your help!

答:
The java.time classes defined in JSR 310 are built into Java 8 and later.

If you are stuck using Java 6 or Java 7, add the ThreeTen-Backport library to your project. This back-port brings much of the java.time functionality. By using a nearly identical API, later converting to java.time proper will be easy.

If doing Android development, Android 26+ has an implementation of java.time built in. For earlier Android, the latest tooling brings most of the functionality via API desugaring. If that does not work for you, add the ThreeTenABP library to your project.

Body:
I'm new with Java language. I have developed an example of a maven project and I have added the package LocalDateTime.

The problem is that when I run the program it appears me this error:
NoClassDefFoundError: java/time/LocalDateTime

I have added this line to import the package:

import java.time.LocalDateTime;

I haven't added anything in the pom.xml file because with other packages imports I didn't add anything and it works properly.

Do I need to add some plugin or dependency in pom.xml file regarding to LocalDateTime?

Thanks for your help!


问:
Vuetify Combobox add new item as object instead of string
I am building a new/edit item form using Vuetify(v2.6.3). My form has multiple combobox's that pull their items from a backend API as objects. I would like to be able to add new items, which the combobox is able to do. However, when I add a new item it's added as a string. Is there a way to add that new item as an object instead?

I only need the new object to have a name key in order to send it to the API to be created

Desired New item from v-combobox:

{
  name: 'New Item',
}
```
<p>Simplified list of items returned from API and available as combobox choices:</p>
<pre class="lang-js prettyprint-override"><code>[
  {
    id: 1,
    name: 'Item 1',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 2,
    name: 'Item 2',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 3,
    name: 'Item 3',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  }
]
</code>```

Here is a simplified version of my Form:

<template>
  <v-card>
    <v-card-title>
      Edit Item
    </v-card-title>
    <v-card-text>
      <v-container>
        <v-row>
          <v-col>
            <v-combobox
              v-model="item"
              :items="items"
              item-text="name"
              item-value="id"
              label="ComboBox"
              return-object
            ></v-combobox>
          </v-col>
        </v-row>
      </v-container>
    </v-card-text>
  </v-card>
</template>

```

In my method which sends the form to the API, I could check the value of each combobox and convert to an object if needed, but I am wondering if it's possible to handle it in the combobox component.

答:
VComboBox doesn't seem to support that, but you could workaround it by using the component's change-event to add a new object with the entry if needed:

Add a change-event handler (e.g., named onChange) on the v-combobox.

In onChange(), lookup the entry in items by name (i.e., corresponding to the VComboBox's item-text prop).

If found, set item to the existing item.

Otherwise, create a new object with that entry, and set item to the newly created object. Note the new object's id (i.e., corresponding to VComboBox's item-value prop) must be unique for VComboBox to create and track it.

<v-combobox
  v-model="item"
  @change="onChange" 1⃣
/>
```
<pre class="lang-js prettyprint-override"><code>let nextId = 1

export default {
  ⋮
  methods: {
    addItem(name) {
      const newItem = {
        id: nextId++,
        name,
      }
      this.items.push(newItem)
      return newItem
    },
    1⃣
    onChange(entry) {
      if (typeof entry === 'string' && entry.trim()) {
        2⃣
        const item = this.items.find(item => item.name === entry)
        if (item) {
          3⃣
          this.item = item
        } else {
          4⃣
          this.item = this.addItem(entry)
        }
      }
    },
  },
}
</code>```

demo

Body:
I am building a new/edit item form using Vuetify(v2.6.3). My form has multiple combobox's that pull their items from a backend API as objects. I would like to be able to add new items, which the combobox is able to do. However, when I add a new item it's added as a string. Is there a way to add that new item as an object instead?

I only need the new object to have a name key in order to send it to the API to be created

Desired New item from v-combobox:

{
  name: 'New Item',
}

Simplified list of items returned from API and available as combobox choices:

[
  {
    id: 1,
    name: 'Item 1',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 2,
    name: 'Item 2',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 3,
    name: 'Item 3',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  }
]

Here is a simplified version of my Form:

<template>
  <v-card>
    <v-card-title>
      Edit Item
    </v-card-title>
    <v-card-text>
      <v-container>
        <v-row>
          <v-col>
            <v-combobox
              v-model="item"
              :items="items"
              item-text="name"
              item-value="id"
              label="ComboBox"
              return-object
            ></v-combobox>
          </v-col>
        </v-row>
      </v-container>
    </v-card-text>
  </v-card>
</template>

In my method which sends the form to the API, I could check the value of each combobox and convert to an object if needed, but I am wondering if it's possible to handle it in the combobox component.

Body:
VComboBox doesn't seem to support that, but you could workaround it by using the component's change-event to add a new object with the entry if needed:

Add a change-event handler (e.g., named onChange) on the v-combobox.

In onChange(), lookup the entry in items by name (i.e., corresponding to the VComboBox's item-text prop).

If found, set item to the existing item.

Otherwise, create a new object with that entry, and set item to the newly created object. Note the new object's id (i.e., corresponding to VComboBox's item-value prop) must be unique for VComboBox to create and track it.

<v-combobox
  v-model="item"
  @change="onChange" 1⃣
/>

let nextId = 1

export default {
  ⋮
  methods: {
    addItem(name) {
      const newItem = {
        id: nextId++,
        name,
      }
      this.items.push(newItem)
      return newItem
    },
    1⃣
    onChange(entry) {
      if (typeof entry === 'string' && entry.trim()) {
        2⃣
        const item = this.items.find(item => item.name === entry)
        if (item) {
          3⃣
          this.item = item
        } else {
          4⃣
          this.item = this.addItem(entry)
        }
      }
    },
  },
}

demo


问:
Why the url of youtube will be changed when I hover mouse on a video?
I was surfing  on youtube and I realized something.

When I hover mouse on a video, then the url will be changed.

Interestingly, this happens in some browsers.
What's the matter?
 Why does string start with &? https://www.youtube.com/?&ab_channel=NASA

What is the benefit to change the URL?

答: the URLs  works in a way  that when the site has started or reloaded, It's going to check for any element that has a href which has a link that has either https://www.youtube.com/watch?v= or https://youtu.be/ basically a YouTube video and then save those links, when one of them i hovered over, It's tell which. This works fine but one downside that I'm currently facing is that new links that are added in after the site has already started or reloaded won't be counted and therefore when I hover them it won't show the links, I'm reffering to comments; for-example if I make a comment that has a link to a video, after i post that comments and hover over that link I posted, It won't show the link. I could make a function which reloads every like 5 seconds but this doesn't seem to be a good idea. Plus what I'm actually working on, realoding every time won't be good.</p>


问:
How to position an image behind autotable in jspdf
I am trying to make my autotables to overlay the images in my document but the available options don't seem to work. I found a way to make it done like this:

```<code>doc.internal.events.subscribe('addPage', function() { doc.addImage(myImage, 'JPG', 5, 265, 20, 30); });
</code>```

But this solution would only apply from the second page ahead. I would like it to work also in the initial page. Is it fine to use this solution? How could I get it to work also in the first page?

Thanks.

答:
I kept digging and I found out that in jsPDF the elements are rendered on top of the previous one, so I just added the image in the beginning of the code specifying the coordinates in the bottom of the page where I wanted it and it worked. Having that information it is easy to position the elements similar as to z-index does.

I hope this is useful to someone else. Thanks!

Body:
I am trying to make my autotables to overlay the images in my document but the available options don't seem to work. I found a way to make it done like this:

doc.internal.events.subscribe('addPage', function() { doc.addImage(myImage, 'JPG', 5, 265, 20, 30); });

But this solution would only apply from the second page ahead. I would like it to work also in the initial page. Is it fine to use this solution? How could I get it to work also in the first page?

Thanks.


问:
Update a DF in Pandas based on condition from different DF
I have df1

```<code>index   state   fin_salary  new_title
5         CA      1          Data Scientist
8         CA      1          Data Scientist
35        CA    150000       Deep Learning Engineer
36        CA    1            Data Analyst
39        CA    1            Data Engineer
43        CA    1            Data Scientist
56        CA    1            Data Scientist
</code>```

And another datfarame df2

```<code>state   new_title                     fin_salary
CA  Artificial Intelligence Engineer    207500.0
CA  Data Analyst                       64729.0
CA  Data Engineer                      146000.0
CA  Data Scientist                     129092.75
CA  Deep Learning Engineer             162500.0
CA  Machine Learning Engineer          133120.0
CA  Python Developer                   96797.0
</code>```

So I want to update df1 with fin_salary from df2 based on condition state and new_title and where fin_salary = 1. So my desired output should be

```<code>index   state   fin_salary           new_title
5         CA      129092.75         Data Scientist
8         CA      129092.75         Data Scientist
35        CA    150000              Deep Learning Engineer
36        CA    64729.0             Data Analyst
39        CA    146000.0             Data Engineer
43        CA    129092.75            Data Scientist
56        CA    129092.75            Data Scientist
</code>```

答:
You can do this:</p>
```<code>DF = df1.merge(df2, on=['state','new_title'], how = 'inner')

df_final = DF[DF['fin_salary']==1]
</code>```

Body:
I have df1

index   state   fin_salary  new_title
5         CA      1          Data Scientist
8         CA      1          Data Scientist
35        CA    150000       Deep Learning Engineer
36        CA    1            Data Analyst
39        CA    1            Data Engineer
43        CA    1            Data Scientist
56        CA    1            Data Scientist

And another datfarame df2

state   new_title                     fin_salary
CA  Artificial Intelligence Engineer    207500.0
CA  Data Analyst                       64729.0
CA  Data Engineer                      146000.0
CA  Data Scientist                     129092.75
CA  Deep Learning Engineer             162500.0
CA  Machine Learning Engineer          133120.0
CA  Python Developer                   96797.0

So I want to update df1 with fin_salary from df2 based on condition state and new_title and where fin_salary = 1. So my desired output should be

index   state   fin_salary           new_title
5         CA      129092.75         Data Scientist
8         CA      129092.75         Data Scientist
35        CA    150000              Deep Learning Engineer
36        CA    64729.0             Data Analyst
39        CA    146000.0             Data Engineer
43        CA    129092.75            Data Scientist
56        CA    129092.75            Data Scientist

Body:
You can do this:

DF = df1.merge(df2, on=['state','new_title'], how = 'inner')

df_final = DF[DF['fin_salary']==1]


问:
Getmem (out of memory)
I'm translating codes from C++ source code to delphi language. There is a partition allocated to memory in C++ source code and when I allocate the same partition in delphi I get an error. Where am I doing wrong? I've used getmem, setlength and all the others.

C++ code (work) :

```<code>int main()
{

    char* data = reinterpret_cast<char*>(malloc(938278912));
    data[938278911]='m';
    printf ("%c \n",data[938278911]);
    return 0;
}
</code>```

Delphi code (not work):

```<code>  procedure TMainForm.UnpackButton1Click(Sender: TObject);
  var
  tmpbuf : Pointer;
  begin
  GetMem(tmpbuf,938278912);
  end
</code>```

Where am i doing wrong ?

答:
As you explain in your comments you are compiling as a 32 bit process. And you are asking for a memory block of around 1gb. The system is failing to allocate this because it so happens that your process doesn't have a free contiguous memory block of that size.

This is entirely to be expected in a 32 bit process which has a total address space of either 2gb or 4gb depending on whether or not your process is large address aware. It's entirely possible that in some scenarios the C++ code would fail similarly.

You cannot expect to reliably allocate such memory blocks in 32 bit process. Either use a 64 bit process or allocate multiple smaller blocks of memory.

Title: Getmem (out of memory)

Body:
I'm translating codes from C++ source code to delphi language. There is a partition allocated to memory in C++ source code and when I allocate the same partition in delphi I get an error. Where am I doing wrong? I've used getmem, setlength and all the others.

C++ code (work) :

int main()
{

    char* data = reinterpret_cast<char*>(malloc(938278912));
    data[938278911]='m';
    printf ("%c \n",data[938278911]);
    return 0;
}

Delphi code (not work):

  procedure TMainForm.UnpackButton1Click(Sender: TObject);
  var
  tmpbuf : Pointer;
  begin
  GetMem(tmpbuf,938278912);
  end

Where am i doing wrong ?


问:
Rails - calculate with the use of sha384
I need to make something like this:

Checksum of parameters:
{"sessionId":"str","merchantId":int,"amount":int,"currency":"str","crc":"str"}

calculated with the use of sha384

My code:

```<code>   sha3 = Digest::SHA384.hexdigest(

      session_.to_s + @config['seller_id'].to_s + @account['amount'].to_s +
      currency.to_s + APP_CONFIG['payment']['pin'].to_s

    )

    sha3_ = sha3
</code>```

Where:

```<code>session_ = 9c64637ebfa5ef0b3ed42a64d2ebfce7

@config['seller_id'] = 12345

@account['amount'] = 2000

currency = 'PLN'

APP_CONFIG['payment']['pin'] = 1234567890
</code>```

Doing it wrong or right? Payment company said that my sha3_ is wrong.

答: I bet you need to calculate JSON checksum.</p>

Body:
I need to make something like this:

Checksum of parameters:
{"sessionId":"str","merchantId":int,"amount":int,"currency":"str","crc":"str"}

calculated with the use of sha384

My code:

   sha3 = Digest::SHA384.hexdigest(

      session_.to_s + @config['seller_id'].to_s + @account['amount'].to_s +
      currency.to_s + APP_CONFIG['payment']['pin'].to_s

    )

    sha3_ = sha3

Where:

session_ = 9c64637ebfa5ef0b3ed42a64d2ebfce7

@config['seller_id'] = 12345

@account['amount'] = 2000

currency = 'PLN'

APP_CONFIG['payment']['pin'] = 1234567890

Doing it wrong or right? Payment company said that my sha3_ is wrong.


问:
PowerShell add a function to a custom object
I try to add an existing function as a method to a new created object.
Writing an inline function works:

```<code>$myObject | Add-Member ScriptMethod -name Calc -value{param([int]$a,[int]$b;$a+$b}
</code>```

Having a function:

```<code>function get-Calc{param([int]$a,[int]$b) $a +$b}
</code>```

this doesn't work:

```<code>$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)
</code>```

答:
Defined functions are stored in the special function:\ drive.

To reference a function definition using variable syntax:

```<code>$myObject | Add-Member ScriptMethod -name Calc -Value ${function:get-Calc}
</code>```

Body:
I try to add an existing function as a method to a new created object.
Writing an inline function works:

$myObject | Add-Member ScriptMethod -name Calc -value{param([int]$a,[int]$b;$a+$b}

Having a function:

function get-Calc{param([int]$a,[int]$b) $a +$b}

this doesn't work:

$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)

Body:
Defined functions are stored in the special function:\ drive.

To reference a function definition using variable syntax:

$myObject | Add-Member ScriptMethod -name Calc -Value ${function:get-Calc}


问:
how to exclude digits using regular expression in VBA
Hello I need to exclude sequence of digits from 890000 till 890001;

890002 to 899999 is acceptable

Is it possible doing using regular expression?

答:
Ok, if you insist on using regex (may be for learning purpose):

In this simple case it is actually easier to exclude those two number and match the rest:

```<code>^89(?!000[12])\d{4}$
</code>```

Explanation:

^ match from start of text

89match 89

(?!000[12]) negative look ahead for 3 times zero and one of characters in the character group (1 or 2). If this doesn't block the match:

\d{4} match 4 digits

$ match end of text.

Body:
Ok, if you insist on using regex (may be for learning purpose):

In this simple case it is actually easier to exclude those two number and match the rest:

^89(?!000[12])\d{4}$

Explanation:

^ match from start of text

89match 89

(?!000[12]) negative look ahead for 3 times zero and one of characters in the character group (1 or 2). If this doesn't block the match:

\d{4} match 4 digits

$ match end of text.


问:
Order two tables from one excel sheet with Pandas
I received the following tables besides each other in one excel file and need to order them  into one table with the column names Name, Blue, Green, Year.
The names are the same for both tables and the indicator is the same in the whole column
. There is one empty column between these tables.

This is the sheet I received:

Name
Indicator
2016
2017
2018

Name
Indicator
2016
2017
2018

Name 1
blue
524
108
387

Name 1
green
92
872
90

Name 2
blue
77
274
50

Name 2
green
402
312
528

Name 3
blue
201
774
18

Name 3
green
457
827
20

Name 4
blue
35
100
129

Name 4
green
183
428
510

This is how it should look like:

Name
Blue
Green
Year

Name 1
524
92
2016

Name 1
108
872
2017

Name 1
387
90
2018

Name 2
77
402
2016

Name 2
274
312
2017

Name 2
50
528
2018

Name 3
201
457
2016

Name 3
774
827
2017

Name 3
18
20
2018

...
...
...
...

Is there any way to do this with pandas?

答:
you can use merge on in pandas to do this.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html

seperate the data into two dataframes.

call one df_one and another df_two then merge.

```<code>merged_df = df_one.merge(df_two, how = "right")
</code>```

Body:
you can use merge on in pandas to do this.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html

seperate the data into two dataframes.

call one df_one and another df_two then merge.

merged_df = df_one.merge(df_two, how = "right")


问:
What is the another way to write methods instead of streamapi
For example : Method addBook(Book book) – adds book to the collection;
Method countAvailableBooks() – counts and returns all available books;
Method getBookWithMostPages() – finds and returns title of the book with most pages;
Method countUniqueAuthors() – counts and returns how many authors there are in the collection;
Method getAuthorsByCountry(country) – counts and returns how many authors from the given country there are in the collection;
Method sortByTitle() – orders the collection by book title;
Method sortByAuthorsFirstName() – orders the collection by author’s first name;

How can i write these methods without using streamApi?

```<code>import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Library {

    private String name;

    private List<Book> books = new ArrayList<>();

    public Library(String name) {
        this.name = name;
    }

    public void addBook(Book book) {
        if (book == null) {
            throw new NullPointerException();
        }
        books.add(book);
    }

    public long countAvailableBooks() {
        return books.stream()
                .filter(Book::isAvailable)
                .count();
    }

    public String getBookWithMostPages() {
        if (books.isEmpty()) {
            return null;
        }

        return books.stream()
                .max(Comparator.comparingInt(Book::getPages))
                .get()
                .getTitle();
    }

    public int countUniqueAuthors() {
        return books.stream()
                .map(Book::getAuthor)
                .collect(Collectors.toSet())
                .size();
    }

    public int getAuthorsByCountry(String country) {
        return books.stream()
                .map(Book::getAuthor)
                .filter(author -> author.getCountry().equals(country))
                .collect(Collectors.toSet())
                .size();
    }

    public List<String> sortByTitle() {
        books.sort(Comparator.comparing(Book::getTitle));
        return books.stream()
                .map(Book::getTitle)
                .collect(Collectors.toList());
    }

    public List<String> sortByAuthorsFirstName() {
        books.sort(Comparator.comparing(book -> {
             return book.getAuthor().getFirstName();
        }));
        return books.stream()
                .map(Book::getTitle)
                .collect(Collectors.toList());
    }

    @Override
    public String toString() {
        return "Library{" +
                "name='" + name + '\'' +
                ", books=" + books +
                '}';
    }
}
</code>```

答:
You can use loops</p>
```<code>public void addBook(Book book) {
    if (book == null) {
        throw new NullPointerException();
    }
    books.add(book);
}

public long countAvailableBooks() {
    long availableBooksCounter = 0;

    for (Book book : books) {
        if (book.isAvailable()) {
            availableBooksCounter++;
        }
    }

    return availableBooksCounter;
}

public String getBookWithMostPages() {
    if (books.isEmpty()) {
        return null;
    }

    Book theBiggestBook = null;

    for (Book book : books) {
        if (theBiggestBook == null || book.getPages() > theBiggestBook.getPages()) {
            theBiggestBook = book;
        }
    }

    return theBiggestBook.getTitle();
}

public int countUniqueAuthors() {
    Set<Author> uniqueAuthors = new HashSet<>();

    for (Book book : books) {
        uniqueAuthors.add(book.getAuthor());
    }

    return uniqueAuthors.size();
}

public int getAuthorsByCountry(String country) {
    Set<Author> authors = new HashSet<>();

    for (Book book : books) {
        if (book.getAuthor().getCountry().equals(country)) {
            authors.add(book.getAuthor());
        }
    }

    return authors.size();
}

public List<String> sortByTitle() {
    List<String> sortedTitles = new ArrayList<>();

    books.sort(Comparator.comparing(Book::getTitle));

    for (Book book : books) {
        sortedTitles.add(book.getTitle());
    }

    return sortedTitles;
}

public List<String> sortByAuthorsFirstName() {
    List<String> sortedTitles = new ArrayList<>();

    books.sort(Comparator.comparing(book -> book.getAuthor().getFirstName()));

    for (Book book : books) {
        sortedTitles.add(book.getTitle());
    }

    return sortedTitles;
}
</code>```

Body:
For example : Method addBook(Book book) – adds book to the collection;
Method countAvailableBooks() – counts and returns all available books;
Method getBookWithMostPages() – finds and returns title of the book with most pages;
Method countUniqueAuthors() – counts and returns how many authors there are in the collection;
Method getAuthorsByCountry(country) – counts and returns how many authors from the given country there are in the collection;
Method sortByTitle() – orders the collection by book title;
Method sortByAuthorsFirstName() – orders the collection by author’s first name;

How can i write these methods without using streamApi?

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Library {

    private String name;

    private List<Book> books = new ArrayList<>();

    public Library(String name) {
        this.name = name;
    }

    public void addBook(Book book) {
        if (book == null) {
            throw new NullPointerException();
        }
        books.add(book);
    }

    public long countAvailableBooks() {
        return books.stream()
                .filter(Book::isAvailable)
                .count();
    }

    public String getBookWithMostPages() {
        if (books.isEmpty()) {
            return null;
        }

        return books.stream()
                .max(Comparator.comparingInt(Book::getPages))
                .get()
                .getTitle();
    }

    public int countUniqueAuthors() {
        return books.stream()
                .map(Book::getAuthor)
                .collect(Collectors.toSet())
                .size();
    }

    public int getAuthorsByCountry(String country) {
        return books.stream()
                .map(Book::getAuthor)
                .filter(author -> author.getCountry().equals(country))
                .collect(Collectors.toSet())
                .size();
    }

    public List<String> sortByTitle() {
        books.sort(Comparator.comparing(Book::getTitle));
        return books.stream()
                .map(Book::getTitle)
                .collect(Collectors.toList());
    }

    public List<String> sortByAuthorsFirstName() {
        books.sort(Comparator.comparing(book -> {
             return book.getAuthor().getFirstName();
        }));
        return books.stream()
                .map(Book::getTitle)
                .collect(Collectors.toList());
    }

    @Override
    public String toString() {
        return "Library{" +
                "name='" + name + '\'' +
                ", books=" + books +
                '}';
    }
}

Body:
You can use loops

public void addBook(Book book) {
    if (book == null) {
        throw new NullPointerException();
    }
    books.add(book);
}

public long countAvailableBooks() {
    long availableBooksCounter = 0;

    for (Book book : books) {
        if (book.isAvailable()) {
            availableBooksCounter++;
        }
    }

    return availableBooksCounter;
}

public String getBookWithMostPages() {
    if (books.isEmpty()) {
        return null;
    }

    Book theBiggestBook = null;

    for (Book book : books) {
        if (theBiggestBook == null || book.getPages() > theBiggestBook.getPages()) {
            theBiggestBook = book;
        }
    }

    return theBiggestBook.getTitle();
}

public int countUniqueAuthors() {
    Set<Author> uniqueAuthors = new HashSet<>();

    for (Book book : books) {
        uniqueAuthors.add(book.getAuthor());
    }

    return uniqueAuthors.size();
}

public int getAuthorsByCountry(String country) {
    Set<Author> authors = new HashSet<>();

    for (Book book : books) {
        if (book.getAuthor().getCountry().equals(country)) {
            authors.add(book.getAuthor());
        }
    }

    return authors.size();
}

public List<String> sortByTitle() {
    List<String> sortedTitles = new ArrayList<>();

    books.sort(Comparator.comparing(Book::getTitle));

    for (Book book : books) {
        sortedTitles.add(book.getTitle());
    }

    return sortedTitles;
}

public List<String> sortByAuthorsFirstName() {
    List<String> sortedTitles = new ArrayList<>();

    books.sort(Comparator.comparing(book -> book.getAuthor().getFirstName()));

    for (Book book : books) {
        sortedTitles.add(book.getTitle());
    }

    return sortedTitles;
}


问:
What is the impact of not calling the arguments while calling a function
My question is about the difference between two ways to pass the the arguments of a function

for instance

```<code>function1(obj1, obj2, obj3, obj4, obj5)
</code>```

or

```<code>function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)
</code>```

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?

答:
In functional programming like R, there can be thirty or something parameters for a function. In that case, argument names are handy with default parameter values.

Other than that, especially for short list of parameters, argument names do not make good sense.

ContentLicense: CC BY-SA 3.0

Body:
My question is about the difference between two ways to pass the the arguments of a function

for instance

function1(obj1, obj2, obj3, obj4, obj5)

or

function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?


问:
Manifest merger failed : android:exported needs to be explicitly specified for <receiver>

Merging Errors: Error: android:exported needs to be explicitly specified for element
<receiver#com.instacart.library.truetime.BootCompletedBroadcastReceiver>.
Apps targeting Android 12 and higher are required to specify an
explicit value for android:exported when the corresponding component
has an intent filter defined. See
https://developer.android.com/guide/topics/manifest/activity-element#exported
for details. test.app main manifest (this file), line 19

I don't even know what to do. I struggled with this mistake for a whole week, but I couldn't.

Here is my sdk version

```<code>compileSdkVersion 32
    defaultConfig {
        multiDexEnabled true
        applicationId "com.example.app"
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 53
        versionName "2.0.4"
        ndk.abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
</code>```

Wrote android:exported on all intent-filter, service, and provider. Ah, I don't have the receiver mentioned in this error.

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    implementation "com.android.billingclient:billing:4.0.0"

    implementation "com.google.firebase:firebase-messaging:23.0.0"
    implementation "com.google.firebase:firebase-crashlytics:18.2.7"
    implementation "com.google.firebase:firebase-analytics:20.0.2"
    implementation "com.google.firebase:firebase-perf:20.0.4"
    implementation "com.google.firebase:firebase-dynamic-links:21.0.0"

    implementation 'com.google.firebase:firebase-core:20.0.2'
    implementation 'com.google.firebase:firebase-database:20.0.3'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-config:21.0.1'
    implementation "com.facebook.android:facebook-login:9.0.0"
    implementation "com.facebook.android:facebook-share:[5,6)"
    implementation "com.linecorp:linesdk:5.0.1"

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.10'

    implementation "com.squareup.retrofit2:retrofit:2.8.1"
    implementation "com.squareup.retrofit2:converter-gson:2.8.1"
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
    implementation 'io.reactivex:rxandroid:1.2.1'

    implementation 'com.google.code.gson:gson:2.8.6'

    implementation 'com.sun.easysnackbar:easysnackbar:1.0.1'

    implementation 'com.romandanylyk:pageindicatorview:1.0.3@aar'

    implementation 'com.google.android.exoplayer:exoplayer:2.16.1'

    //MULTI DEX
    implementation "androidx.multidex:multidex:2.0.1"

    implementation 'com.google.android:flexbox:2.0.1'

    implementation 'com.github.florent37:diagonallayout:1.0.9'

    implementation('io.socket:socket.io-client:1.0.0') {
        exclude group: 'org.json', module: 'json'
    }

    implementation 'com.github.instacart.truetime-android:library:3.4'
    implementation 'com.github.instacart.truetime-android:library-extension-rx:3.4'

    implementation "androidx.navigation:navigation-fragment-ktx:2.4.0"
    implementation "androidx.navigation:navigation-ui-ktx:2.4.0"

    implementation "com.github.bumptech.glide:glide:4.12.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.12.0"

    implementation "de.hdodenhof:circleimageview:3.1.0"

    implementation "com.pixplicity.easyprefs:library:1.9.0"

    implementation "com.jakewharton.timber:timber:4.7.1"

    implementation "com.airbnb.android:lottie:3.4.0"

    implementation 'com.github.jinatonic.confetti:confetti:1.1.2'

    implementation "com.nabinbhandari.android:permissions:3.8"

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation "com.github.YarikSOffice:lingver:1.2.1"

    implementation 'com.github.mreram:showcaseview:1.2.0'
    implementation 'com.github.shripal17:MaterialIntroView-v2:2.2.0'

    implementation 'com.github.unsplash:unsplash-photopicker-android:1.0.0'

    implementation 'com.giphy.sdk:ui:2.1.0'

    testImplementation 'junit:junit:4.13.2'
    testImplementation 'androidx.test:core:1.4.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.test.ext:junit:1.1.3"
}
</code>```

答:
Found the issue with instacart.truetime library. You're using 3.4 version & they resolved this error in 3.5 as mentioned here: https://github.com/instacart/truetime-android/releases/tag/3.5

So you need to update these dependencies to the new version of 3.5

```<code>    implementation 'com.github.instacart.truetime-android:library:3.5'
    implementation 'com.github.instacart.truetime-android:library-extension-rx:3.5'
</code>```

Build the app & it resolves the issue

Body:
Merging Errors: Error: android:exported needs to be explicitly specified for element
<receiver#com.instacart.library.truetime.BootCompletedBroadcastReceiver>.
Apps targeting Android 12 and higher are required to specify an
explicit value for android:exported when the corresponding component
has an intent filter defined. See
https://developer.android.com/guide/topics/manifest/activity-element#exported
for details. test.app main manifest (this file), line 19

I don't even know what to do. I struggled with this mistake for a whole week, but I couldn't.

Here is my sdk version

compileSdkVersion 32
    defaultConfig {
        multiDexEnabled true
        applicationId "com.example.app"
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 53
        versionName "2.0.4"
        ndk.abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

Wrote android:exported on all intent-filter, service, and provider. Ah, I don't have the receiver mentioned in this error.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    implementation "com.android.billingclient:billing:4.0.0"

    implementation "com.google.firebase:firebase-messaging:23.0.0"
    implementation "com.google.firebase:firebase-crashlytics:18.2.7"
    implementation "com.google.firebase:firebase-analytics:20.0.2"
    implementation "com.google.firebase:firebase-perf:20.0.4"
    implementation "com.google.firebase:firebase-dynamic-links:21.0.0"

    implementation 'com.google.firebase:firebase-core:20.0.2'
    implementation 'com.google.firebase:firebase-database:20.0.3'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-config:21.0.1'
    implementation "com.facebook.android:facebook-login:9.0.0"
    implementation "com.facebook.android:facebook-share:[5,6)"
    implementation "com.linecorp:linesdk:5.0.1"

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.10'

    implementation "com.squareup.retrofit2:retrofit:2.8.1"
    implementation "com.squareup.retrofit2:converter-gson:2.8.1"
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
    implementation 'io.reactivex:rxandroid:1.2.1'

    implementation 'com.google.code.gson:gson:2.8.6'

    implementation 'com.sun.easysnackbar:easysnackbar:1.0.1'

    implementation 'com.romandanylyk:pageindicatorview:1.0.3@aar'

    implementation 'com.google.android.exoplayer:exoplayer:2.16.1'

    //MULTI DEX
    implementation "androidx.multidex:multidex:2.0.1"

    implementation 'com.google.android:flexbox:2.0.1'

    implementation 'com.github.florent37:diagonallayout:1.0.9'

    implementation('io.socket:socket.io-client:1.0.0') {
        exclude group: 'org.json', module: 'json'
    }

    implementation 'com.github.instacart.truetime-android:library:3.4'
    implementation 'com.github.instacart.truetime-android:library-extension-rx:3.4'

    implementation "androidx.navigation:navigation-fragment-ktx:2.4.0"
    implementation "androidx.navigation:navigation-ui-ktx:2.4.0"

    implementation "com.github.bumptech.glide:glide:4.12.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.12.0"

    implementation "de.hdodenhof:circleimageview:3.1.0"

    implementation "com.pixplicity.easyprefs:library:1.9.0"

    implementation "com.jakewharton.timber:timber:4.7.1"

    implementation "com.airbnb.android:lottie:3.4.0"

    implementation 'com.github.jinatonic.confetti:confetti:1.1.2'

    implementation "com.nabinbhandari.android:permissions:3.8"

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation "com.github.YarikSOffice:lingver:1.2.1"

    implementation 'com.github.mreram:showcaseview:1.2.0'
    implementation 'com.github.shripal17:MaterialIntroView-v2:2.2.0'

    implementation 'com.github.unsplash:unsplash-photopicker-android:1.0.0'

    implementation 'com.giphy.sdk:ui:2.1.0'

    testImplementation 'junit:junit:4.13.2'
    testImplementation 'androidx.test:core:1.4.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.test.ext:junit:1.1.3"
}

Body:
Found the issue with instacart.truetime library. You're using 3.4 version & they resolved this error in 3.5 as mentioned here: https://github.com/instacart/truetime-android/releases/tag/3.5

So you need to update these dependencies to the new version of 3.5

    implementation 'com.github.instacart.truetime-android:library:3.5'
    implementation 'com.github.instacart.truetime-android:library-extension-rx:3.5'

Build the app & it resolves the issue


问:
Referencing SNS Topic that already exists in CDK?
I have an SNS topic that already exists in our AWS environment. Instead of creating a new SNS topic, I want to simply reference the already-existing topic and publish a message to it.

Right now, I have the following:

const topic = new sns.Topic(this, 'AggregateSNS', {

      contentBasedDeduplication: false,
      displayName: 'Customer subscription topic',
      fifo: true,
      topicName: 'MySNSTopic',

      //how to reference existing topics?
    });
```

My understanding is this will create a new SNS topic, but as I said above, I want to reference an existing SNS topic.
How do I do I reference an existing SNS topic in CDK?

答:
You get a read-only reference to an existing SNS topic with the static fromTopicArn method.  A common reason to do this is adding an existing topic as an event source.

const topic = sns.Topic.fromTopicArn(this, 'MyTopic', <topic-arn>);

func.addEventSource(new sources.SnsEventSource(topic));
```

If you need use the publish API from your CDK app (to send a notification upon certain deploy lifecycle events, for instance), you would use a custom resource.  The AwsCustomResource construct makes it easy to make SDK calls as part of the deploy process.

Body:
I have an SNS topic that already exists in our AWS environment. Instead of creating a new SNS topic, I want to simply reference the already-existing topic and publish a message to it.

Right now, I have the following:

const topic = new sns.Topic(this, 'AggregateSNS', {

      contentBasedDeduplication: false,
      displayName: 'Customer subscription topic',
      fifo: true,
      topicName: 'MySNSTopic',

      //how to reference existing topics?
    });

My understanding is this will create a new SNS topic, but as I said above, I want to reference an existing SNS topic.
How do I do I reference an existing SNS topic in CDK?

Body:
You get a read-only reference to an existing SNS topic with the static fromTopicArn method.  A common reason to do this is adding an existing topic as an event source.

const topic = sns.Topic.fromTopicArn(this, 'MyTopic', <topic-arn>);

func.addEventSource(new sources.SnsEventSource(topic));

If you need use the publish API from your CDK app (to send a notification upon certain deploy lifecycle events, for instance), you would use a custom resource.  The AwsCustomResource construct makes it easy to make SDK calls as part of the deploy process.


问:
How to get values on line charts
I would to plot corresponding values on line charts. Can you please let me know how can I do that?

```<code>import matplotlib.pyplot as plt
x = [1,2,3]
y = [3,4,5]
z = [6,7,8]

plt.plot(x, y)
plt.plot(x, z)
plt.show()
</code>```

Thanks.

答:
You can add value tag to the point by using a for loop over the data points in cartesian coordinate.

```<code>import matplotlib.pyplot as plt
x = [1,2,3]
y = [3,4,5]
z = [6,7,8]

plt.plot(x, y, '*--')
for a,b in zip(x, y):
    plt.text(a, b, str(b),fontsize=20)
plt.plot(x, z, '*--')
for a,b in zip(x, z):
    plt.text(a, b, str(b),fontsize=20)

plt.ylim(0, 10)
plt.show()
</code>```

Title: How to get values on line charts

Body:
I would to plot corresponding values on line charts. Can you please let me know how can I do that?

import matplotlib.pyplot as plt
x = [1,2,3]
y = [3,4,5]
z = [6,7,8]

plt.plot(x, y)
plt.plot(x, z)
plt.show()

Thanks.

Body:
You can add value tag to the point by using a for loop over the data points in cartesian coordinate.

import matplotlib.pyplot as plt
x = [1,2,3]
y = [3,4,5]
z = [6,7,8]

plt.plot(x, y, '*--')
for a,b in zip(x, y):
    plt.text(a, b, str(b),fontsize=20)
plt.plot(x, z, '*--')
for a,b in zip(x, z):
    plt.text(a, b, str(b),fontsize=20)

plt.ylim(0, 10)
plt.show()


问:
Help with MySQL JOIN statement
I have 2 tables:

Table A is a category table. Columns are cid, catname.

Table B is a relationship table. Columns are cid, parent (parent is another cid).

Here's where I am so far:

```<code>"SELECT c.cid, c.catname AS catname, r.parent AS parent FROM tableA AS c JOIN tableB AS r ON r.cid=c.cid";
</code>```

I know I'll get 3 columns (2 from tableA and one from tableB) but I also want to get the catname value from the parent in tableA If I were to do a second query, it would look like this (assuming we put the result into a $row variable):

```<code>"SELECT catname FROM tableA WHERE cid='".$row['parent']."'";
</code>```

That way I can display it as text.

What do I add, and where? Is there a second JOIN?

答:
You can join a table multiple times:</p>

```<code>SELECT a.cid AS acid, a.catname AS aname,
       b.cid AS bcid, b.catname AS bname
FROM relationships AS r
     JOIN categories AS a ON (r.cid = a.cid)
     JOIN categories AS b ON (r.parent = b.cid)
</code>```

Title: Help with MySQL JOIN statement

Body:
I have 2 tables:

Table A is a category table. Columns are cid, catname.

Table B is a relationship table. Columns are cid, parent (parent is another cid).

Here's where I am so far:

"SELECT c.cid, c.catname AS catname, r.parent AS parent FROM tableA AS c JOIN tableB AS r ON r.cid=c.cid";

I know I'll get 3 columns (2 from tableA and one from tableB) but I also want to get the catname value from the parent in tableA If I were to do a second query, it would look like this (assuming we put the result into a $row variable):

"SELECT catname FROM tableA WHERE cid='".$row['parent']."'";

That way I can display it as text.

What do I add, and where? Is there a second JOIN?

Body:
You can join a table multiple times:

SELECT a.cid AS acid, a.catname AS aname,
       b.cid AS bcid, b.catname AS bname
FROM relationships AS r
     JOIN categories AS a ON (r.cid = a.cid)
     JOIN categories AS b ON (r.parent = b.cid)


问:
Js Node Selenium Try-Catch Js Error not working
I'm trying to simulate clicking on an element that is rendered after a certain iteration of document.readyState='complete'. To get around the readyState issue, I thought of try-catching the executeScript command to just make it retry until it works.

But for some reason Node / Selenium just stops working entirely from the resulting Js error:

Cannot read properties of undefined (reading 'parentElement')

Any ideas on how I should solve this? Here's part of my code. It'll open up the supplied url (item) and should execute the command as soon as the element icon-download is rendered.

```<code>async function getFileFromUrl(item) {
  var command = "document.getElementsByClassName('icon-download')[0].parentElement.click()";
  driver.get(item);
  do {
    await delay(500);
    try{
      driver.executeScript(command);
    } catch (e) {
      continue;
    }
    break;
  } while (true);
  await delay(3000);
}
</code>```

答:
Ok so I managed to fix it by prefixing the driver-commands with Await. If they return an exception it's recognized by Node now. Code below:</p>
```<code>async function getFileFromUrl(item) {
  var command = "document.getElementsByClassName('icon-fpk icon-download-xls')[0].parentElement.click()";
  await driver.get(item);
  do {
    await delay(500);
    try{
      await driver.executeScript(command);
    } catch {
      continue;
    }
    break;
  } while (true);
  await delay(3500);
}
</code>```

Body:
I'm trying to simulate clicking on an element that is rendered after a certain iteration of document.readyState='complete'. To get around the readyState issue, I thought of try-catching the executeScript command to just make it retry until it works.

But for some reason Node / Selenium just stops working entirely from the resulting Js error:

Cannot read properties of undefined (reading 'parentElement')

Any ideas on how I should solve this? Here's part of my code. It'll open up the supplied url (item) and should execute the command as soon as the element icon-download is rendered.

async function getFileFromUrl(item) {
  var command = "document.getElementsByClassName('icon-download')[0].parentElement.click()";
  driver.get(item);
  do {
    await delay(500);
    try{
      driver.executeScript(command);
    } catch (e) {
      continue;
    }
    break;
  } while (true);
  await delay(3000);
}

Body:
Ok so I managed to fix it by prefixing the driver-commands with Await. If they return an exception it's recognized by Node now. Code below:

async function getFileFromUrl(item) {
  var command = "document.getElementsByClassName('icon-fpk icon-download-xls')[0].parentElement.click()";
  await driver.get(item);
  do {
    await delay(500);
    try{
      await driver.executeScript(command);
    } catch {
      continue;
    }
    break;
  } while (true);
  await delay(3500);
}


问:
Object is of type 'unknown'.ts(2571) in generic component
I have a Table component with generics and I use a static component inside the Table to compose columns, also with generics.

The problem is that I would like the Column component to inherit the generic type passed to the Table when executing the data function, which gets the result passed to it.

I know typing explicitly will work, for example:

<Table.Column<TableItem> data={(item) => item.name} />

The real question is: Is it possible to perform this type inference from my Table component and pass it to the static Column component? So that I don't have to add the type explicitly to each column...

SANDBOX TO REPRODUCE, ONLY TABLE AND COLUMN COMPONENTS:

https://codesandbox.io/s/generic-table-column-r54lh?file=/src/App.tsx

答:
You can specify the type for item:

```<code><Table.Column<TableItem> data={(item:[type goes here]) => item.name} />
</code>```

Few examples :

```<code><Table.Column<TableItem> data={(item:any) => item.name} />

// or even
<Table.Column<TableItem> data={(item:{name:string;}) => item.name} />

</code>```

Body:
You can specify the type for item:

<Table.Column<TableItem> data={(item:[type goes here]) => item.name} />

Few examples :

<Table.Column<TableItem> data={(item:any) => item.name} />

// or even
<Table.Column<TableItem> data={(item:{name:string;}) => item.name} />


问:
Unable to return variable from one function and use it in another function
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.</p>
```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()
</code>```

答:
You could try doing:

def main():
    add_coins(choose_coins())
```
<p>instead of</p>
<pre class="lang-py prettyprint-override"><code>def main():

    choose_coins()
    add_coins(coin_tokens)
</code>```

In your version the functions aren't connected and you're probably getting an error like NameError: name 'coin_tokens' is not defined

Body:
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()

Body:
You could try doing:

def main():
    add_coins(choose_coins())

instead of

def main():

    choose_coins()
    add_coins(coin_tokens)

In your version the functions aren't connected and you're probably getting an error like NameError: name 'coin_tokens' is not defined


问:
Impala - Check if a string is a number
Is there any way to check if a string is a number in Impala?
like is_numeric is SQL?

答:
The 'regep_like' function is helpful here. For instance, the following will select integers:</p>
```<code>select * from table where regexp_like(field,'^[[:digit:]]+$')
</code>```

Title: Impala - Check if a string is a number

Body:
The 'regep_like' function is helpful here. For instance, the following will select integers:

select * from table where regexp_like(field,'^[[:digit:]]+$')


问:
Fortran mwPointer error: "Unclassifiable statement"
I am trying to integrate to an existing Fortran code mycode.F a mwPointer. My mycode.F compiled correctly before any change I tried to make. Here's an extract:

```<code>  subroutine mycode(t1,t2,action,p1,p2,Q,flag)

  implicit none

  integer IZERO, IUN, IDEUX, ITROIS
  double precision  DZERO,DUN,DDEUX,DTROIS,flag
  parameter (IUN=1,IZERO=0,IDEUX=2,ITROIS=3,DZERO=0.0d0,DUN=0.1D1,DDEUX=0.2D1,DTROIS=0.3D1)

  double precision action, t1, t2, p1, p2, Q
  double precision Q2(10),D(10),time(10),G1(10),G(10,2),F(51)

  integer i

  print *, 'Lorem'

  end
</code>```

In order to use the engOpen function  and following this Mathworks page, I modified my code to this:

```<code>#include         "fintrf.h"
#include         "engine.h"

      subroutine mycode(t1,t2,action,p1,p2,Q,flag,engOpen)

      implicit none

      integer IZERO, IUN, IDEUX, ITROIS
      double precision  DZERO,DUN,DDEUX,DTROIS,flag
      parameter (IUN=1,IZERO=0,IDEUX=2,ITROIS=3,DZERO=0.0d0,DUN=0.1D1,DDEUX=0.2D1,DTROIS=0.3D1)

      double precision action, t1, t2, p1, p2, Q
      double precision Q2(10),D(10),time(10),G1(10),G(10,2),F(51)!

      integer i

      mwPointer engOpen

      print *, 'Lorem'

      end
</code>```

But when I compile, I get the following error:

```<code>mwPointer engOpen
1
Error: Unclassifiable statement at (1)
Error: Symbol 'engopen' at (1) has no IMPLICIT type
</code>```

Would anyone know how to solve this?

Thanks for your help

答:
The Mathworks page gave you bad, or at least incomplete advice. It is assuming that your Fortran source will be run through a cpp-style preprocessor, which is not standard in Fortran. With most Fortran compilers on UNIX/Linux style systems, the use of a .F (capital F) file type would run the source through a preprocessor first, but that doesn't necessarily happen everywhere. (You did not say which compiler and operating system you are using.)

Study your compiler's documentation and, if available, enable the option to have the source run through a preprocessor before compilation.

Body:
I am trying to integrate to an existing Fortran code mycode.F a mwPointer. My mycode.F compiled correctly before any change I tried to make. Here's an extract:

  subroutine mycode(t1,t2,action,p1,p2,Q,flag)

  implicit none

  integer IZERO, IUN, IDEUX, ITROIS
  double precision  DZERO,DUN,DDEUX,DTROIS,flag
  parameter (IUN=1,IZERO=0,IDEUX=2,ITROIS=3,DZERO=0.0d0,DUN=0.1D1,DDEUX=0.2D1,DTROIS=0.3D1)

  double precision action, t1, t2, p1, p2, Q
  double precision Q2(10),D(10),time(10),G1(10),G(10,2),F(51)

  integer i

  print *, 'Lorem'

  end

In order to use the engOpen function  and following this Mathworks page, I modified my code to this:

#include         "fintrf.h"
#include         "engine.h"

      subroutine mycode(t1,t2,action,p1,p2,Q,flag,engOpen)

      implicit none

      integer IZERO, IUN, IDEUX, ITROIS
      double precision  DZERO,DUN,DDEUX,DTROIS,flag
      parameter (IUN=1,IZERO=0,IDEUX=2,ITROIS=3,DZERO=0.0d0,DUN=0.1D1,DDEUX=0.2D1,DTROIS=0.3D1)

      double precision action, t1, t2, p1, p2, Q
      double precision Q2(10),D(10),time(10),G1(10),G(10,2),F(51)!

      integer i

      mwPointer engOpen

      print *, 'Lorem'

      end

But when I compile, I get the following error:

mwPointer engOpen
1
Error: Unclassifiable statement at (1)
Error: Symbol 'engopen' at (1) has no IMPLICIT type

Would anyone know how to solve this?

Thanks for your help


问:
How to influence div with checked input if div is far away and not a relative?
A have CSS-code:

```<code> .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}
</code>```

It allows me to manipulate div next to label next to checked input.

It works fine, but is there a way, that I can manipulate div with checked/unchecked that is far away from input?

My div has class "dropdown-menu" and it is not related to input in any way and like 50 lines of code after the input.

Can I connect checked value with my "dropdown-menu" div in any way with CSS?

答:
There is no way to do that. It would be possible if there were a parent combinator in CSS, but there isn't.
The solution is very simple with JS-code:
Here it is:

```<code><script>
function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
     x.style.display = "block";
  } else {
     x.style.display = "none";
  }
}
</script>
</code>```

Add this within  container in HTML (of into JS-file if you know how to do that).

And add id to whatever block in div you are trying to hide/show.
ID in JS and ID in div should be the same
Also, remember that if you have basic value of display:block - everything works.
But if your basic display:FLEX, or INLINE, or else - you should change 4-th line of code (with BLOCK) to whatever value you need.

Body:
A have CSS-code:

 .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}

It allows me to manipulate div next to label next to checked input.

It works fine, but is there a way, that I can manipulate div with checked/unchecked that is far away from input?

My div has class "dropdown-menu" and it is not related to input in any way and like 50 lines of code after the input.

Can I connect checked value with my "dropdown-menu" div in any way with CSS?

Body:
There is no way to do that. It would be possible if there were a parent combinator in CSS, but there isn't.
The solution is very simple with JS-code:
Here it is:

<script>
function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
     x.style.display = "block";
  } else {
     x.style.display = "none";
  }
}
</script>

Add this within  container in HTML (of into JS-file if you know how to do that).

And add id to whatever block in div you are trying to hide/show.
ID in JS and ID in div should be the same
Also, remember that if you have basic value of display:block - everything works.
But if your basic display:FLEX, or INLINE, or else - you should change 4-th line of code (with BLOCK) to whatever value you need.


问:
Scrapy: How to visit several subpages and extract all the text?
I would like to perform three simple tasks that should work for most of the pages.

Get all the links on the main page https://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/

Visit the extracted subpages (e.g. https://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/heliosgelaende)

Just get all the text found on the subpages

My approach is:

```<code>import scrapy

class StadtKoelnSpider(scrapy.Spider):
    name = "stadt_koeln"

    def start_requests(self):
        urls = ['http://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/']

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # 1. Get all links
        for url in response.xpath('body//a/@href').getall():

            # 2. Visit each subpage
            yield scrapy.Request(url.get(), callback=self.parse_subpage)

    def parse_subpage(self, response):
        # 3. Get text on each subpage
        text = response.xpath("//p/text()").extract()

        yield {
            'Subpage_Text': text
        }
</code>```

No output is generated. Any idea how to make this work? There are several ways to follow links in Scrapy, but I didn't find a working example for my case.

I also get an error. I guess it means that only a part of the url is extracted and not the complete one.

```<code>AttributeError: 'str' object has no attribute 'get'
</code>```

答:
You can use scrapy crawl spider. See sample below. Please note that this will return all the text in all the elements on the page

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class StadtKoelnSpider(CrawlSpider):
    name = 'stadt_koeln'
    allowed_domains = ['www.stadt-koeln.de']
    start_urls = ['https://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/']

    rules = (
        Rule(LinkExtractor(allow=r"politik-und-verwaltung\/stadtentwicklung"), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        all_text = response.xpath("//*/text()").getall()
        yield {
            "Subpage_Text": " ".join(all_text)
        }
```

Body:
I would like to perform three simple tasks that should work for most of the pages.

Get all the links on the main page https://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/

Visit the extracted subpages (e.g. https://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/heliosgelaende)

Just get all the text found on the subpages

My approach is:

import scrapy

class StadtKoelnSpider(scrapy.Spider):
    name = "stadt_koeln"

    def start_requests(self):
        urls = ['http://www.stadt-koeln.de/politik-und-verwaltung/stadtentwicklung/']

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # 1. Get all links
        for url in response.xpath('body//a/@href').getall():

            # 2. Visit each subpage
            yield scrapy.Request(url.get(), callback=self.parse_subpage)

    def parse_subpage(self, response):
        # 3. Get text on each subpage
        text = response.xpath("//p/text()").extract()

        yield {
            'Subpage_Text': text
        }

No output is generated. Any idea how to make this work? There are several ways to follow links in Scrapy, but I didn't find a working example for my case.

I also get an error. I guess it means that only a part of the url is extracted and not the complete one.

AttributeError: 'str' object has no attribute 'get'


答:
You're returning a value, but you're not assigning it to a variable.</p>
```<code>my_coins = choose_coins()
add_coins(my_coins)
</code>```

Title: Unable to return variable from one function and use it in another function

Body:
You're returning a value, but you're not assigning it to a variable.

my_coins = choose_coins()
add_coins(my_coins)


问:
How to create multiple subplots, with the date column as the x -axis and the sum of the rest columns as the y-axis?
I have this dataframe and I want to create a subplot for each exercise, depicting the sum of sets for each date in a trend line format.

This is the jupyter notebook : https://github.com/TheoPallis/Portfolio/blob/Site/Workout_Project/Workout.ipynb.

I have tried the following code :

```<code> grp = df.groupby('Date').sum()
    melted = pd.melt(grp, var_name="Exercise", ignore_index=False)
    print(melted)
        px.line(melted,
            y='value',
            facet_col='Exercise',
            facet_col_spacing=0.1)
</code>```

but I get this unelegant output. .

Ideally, the sublots would be arranged in a grid format :

First row : 3 subplots
Second row : 3 subplots
Third row : 2 subplots (and 1 blank?)

答:
```<code>grp = data.groupby('Date').sum()
melted = pd.melt(grp, var_name="Exercise", ignore_index=False)

# define exercises list
exercises = melted.reset_index()
exercises = set(melted['Exercise'])

# define plot grid
fig, axs = plt.subplots(nrows=3, ncols=3, figsize=(15, 12))
plt.subplots_adjust(hspace=0.5)

# loop over grid and exercises
for exercises, ax in zip(exercises, axs.ravel()):
    melted[melted["Exercise"] == exercises].plot(ax=ax)
</code>```

Body:
I have this dataframe and I want to create a subplot for each exercise, depicting the sum of sets for each date in a trend line format.

This is the jupyter notebook : https://github.com/TheoPallis/Portfolio/blob/Site/Workout_Project/Workout.ipynb.

I have tried the following code :

 grp = df.groupby('Date').sum()
    melted = pd.melt(grp, var_name="Exercise", ignore_index=False)
    print(melted)
        px.line(melted,
            y='value',
            facet_col='Exercise',
            facet_col_spacing=0.1)

but I get this unelegant output. .

Ideally, the sublots would be arranged in a grid format :

First row : 3 subplots
Second row : 3 subplots
Third row : 2 subplots (and 1 blank?)


问:
How to add bootstrap scripts to django admin template?

I want to use some **Boostrap** elements into the **django admin** interface.

For that purpose, I have overided the *admin/base.html* template. I want to add the links to bootstrap javascripts (the two lines of code you have to put just before the `` in order to use bootstrap) into that template.

As it is out of any `{% block %}` in the original *admin/base.html*, is there a nice way to do that without copying the entire  section ?

答:
in your admin/base.html file add bootstrap style and js scripts using CDN as below;

```<code><head>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</code>```

I hope this will help you as it works for me. Please try and if you have any queries related to this please add a comment.

Getting started with Bootstrap

Body:
in your admin/base.html file add bootstrap style and js scripts using CDN as below;

<head>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>

I hope this will help you as it works for me. Please try and if you have any queries related to this please add a comment.

Getting started with Bootstrap


问:
How to extend the range of stratification beyond the maximum value in a data frame?
Suppose we start with the following data frame, with the generating code beneath it:

```<code>> stratData
  ID  Period Values
1  1 2020-03     -5
2  1 2020-04     25
3  2 2020-01     35
4  2 2020-02     45
5  2 2020-03     55
6  2 2020-04     87
7  3 2020-02     10
8  3 2020-03     20
9  3 2020-04     30

stratData <-
   data.frame(
     ID = c(1,1,2,2,2,2,3,3,3),
     Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-02", "2020-03", "2020-04"),
     Values = c(-5, 25, 35, 45, 55, 87, 10, 20, 30)
     )
</code>```

I have a Shiny app that allows the user to stratify certain values in the data frame by different criteria, including the size of stratification bands. At the bottom is the stratification MWE code. The problem I'm having is the stratification range not properly labeling the maximum value in the range. As shown below, the maximum range shows NA, instead of the correct (85,90] to encompass the maximum from the stratData data frame. How can this be solved?

```<code># A tibble: 7 x 5
  Range   Count Values Count_pct Values_pct
  <fct>   <dbl>  <dbl>     <dbl>      <dbl>
1 [25,35]     2     55      66.7       38.7
2 (35,45]     0      0       0          0
3 (45,55]     0      0       0          0
4 (55,65]     0      0       0          0
5 (65,75]     0      0       0          0
6 (75,85]     0      0       0          0
7 NA          1     87      33.3       61.3
</code>```

Here is the MWE code to generate the above table (there are vestiges from the more complete App; I thought about making the max = round(value, -1) or something like that but a difficulty is the user has the ability to input different ranges in order to customize the stratification):

```<code>custom_min <- function(x) {if (length(x)>0) min(x, na.rm=TRUE) else Inf}
custom_max <- function(x) {if (length(x)>0) max(x, na.rm=TRUE) else Inf}

filter_exp1 <- parse(text=paste0("Period",  "==", "'","2020-04", "'"))
stratData_1 <- stratData %>% filter(eval(filter_exp1))

min <- custom_min(stratData_1[[3]])
max <- custom_max(stratData_1[[3]])
breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, by = 10) # < in full code, the 10 is a variable the user can change via Shiny

tmp <- stratData %>%
  filter(eval(filter_exp1)) %>%
  mutate(Range = cut(!!sym("Values"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
  group_by(Range) %>%
  summarise(Count = n(),Values = sum(!!sym("Values"))) %>%
  complete(Range, fill = list(Count = 0,Values = 0)) %>%
  ungroup %>%
  mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
  dplyr::select(everything(), Count, Count_pct, Values, Values_pct)
tmp
</code>```

答:
You need to use e.g. seq(min, max, length.out = 5). The by argument must not be used here, because max=87 is not a multiple of 10:

min <- 25
max <- 87
# does not include the max
seq(min, max, by = 10)
#> [1] 25 35 45 55 65 75 85
# does include the max
seq(min, max, length.out = 5)
#> [1] 25.0 40.5 56.0 71.5 87.0
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
Suppose we start with the following data frame, with the generating code beneath it:

> stratData
  ID  Period Values
1  1 2020-03     -5
2  1 2020-04     25
3  2 2020-01     35
4  2 2020-02     45
5  2 2020-03     55
6  2 2020-04     87
7  3 2020-02     10
8  3 2020-03     20
9  3 2020-04     30

stratData <-
   data.frame(
     ID = c(1,1,2,2,2,2,3,3,3),
     Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-02", "2020-03", "2020-04"),
     Values = c(-5, 25, 35, 45, 55, 87, 10, 20, 30)
     )

I have a Shiny app that allows the user to stratify certain values in the data frame by different criteria, including the size of stratification bands. At the bottom is the stratification MWE code. The problem I'm having is the stratification range not properly labeling the maximum value in the range. As shown below, the maximum range shows NA, instead of the correct (85,90] to encompass the maximum from the stratData data frame. How can this be solved?

# A tibble: 7 x 5
  Range   Count Values Count_pct Values_pct
  <fct>   <dbl>  <dbl>     <dbl>      <dbl>
1 [25,35]     2     55      66.7       38.7
2 (35,45]     0      0       0          0
3 (45,55]     0      0       0          0
4 (55,65]     0      0       0          0
5 (65,75]     0      0       0          0
6 (75,85]     0      0       0          0
7 NA          1     87      33.3       61.3

Here is the MWE code to generate the above table (there are vestiges from the more complete App; I thought about making the max = round(value, -1) or something like that but a difficulty is the user has the ability to input different ranges in order to customize the stratification):

custom_min <- function(x) {if (length(x)>0) min(x, na.rm=TRUE) else Inf}
custom_max <- function(x) {if (length(x)>0) max(x, na.rm=TRUE) else Inf}

filter_exp1 <- parse(text=paste0("Period",  "==", "'","2020-04", "'"))
stratData_1 <- stratData %>% filter(eval(filter_exp1))

min <- custom_min(stratData_1[[3]])
max <- custom_max(stratData_1[[3]])
breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, by = 10) # < in full code, the 10 is a variable the user can change via Shiny

tmp <- stratData %>%
  filter(eval(filter_exp1)) %>%
  mutate(Range = cut(!!sym("Values"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
  group_by(Range) %>%
  summarise(Count = n(),Values = sum(!!sym("Values"))) %>%
  complete(Range, fill = list(Count = 0,Values = 0)) %>%
  ungroup %>%
  mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
  dplyr::select(everything(), Count, Count_pct, Values, Values_pct)
tmp

Body:
You need to use e.g. seq(min, max, length.out = 5). The by argument must not be used here, because max=87 is not a multiple of 10:

min <- 25
max <- 87
# does not include the max
seq(min, max, by = 10)
#> [1] 25 35 45 55 65 75 85
# does include the max
seq(min, max, length.out = 5)
#> [1] 25.0 40.5 56.0 71.5 87.0

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?
When I double-click on pycharm.sh, Ubuntu lets me choose between "Run in Terminal" and "Run". What is the difference between these options?</p>

答:
I did the edit and added the PATH for my Pycharm in .bashrc but I was still getting the error "pycharm.sh: command not found".
After trying several other things the following command resolved the issue which creates a symbolic link.

sudo ln -s /snap/pycharm-community/267/bin/pycharm.sh /usr/local/bin/pycharm

The first is location to the exact path to pycharm.sh and the second is user bin which should be on PATH env by default


问:
`f :: a -> IO ()` evaluation in do thread : Haskell
This is a repost of my previous question(deleted by myself) since I considered it would be adequate to change the focus by presenting the sample code below.

Basically, I try to implement a Functor that takes a function such as id, \a -> a + 1 or even print .

So the function type can be

f :: a -> b

f :: a -> IO ()

```<code>module Main where

import Control.Monad.Primitive (PrimMonad (PrimState))
import qualified Data.Vector.Mutable as M
import System.IO.Error (isDoesNotExistErrorType)

main :: IO ()
main = do
  let ioA = io (5 :: Int)
  let f = print
  --  f = \a -> a + 1
  let ioB = someFunctor f ioA

  ioB

  print "done"

data R a = R
  { val :: M.MVector (PrimState IO) a
  }

io :: a -> IO (R a)
io = \a -> do
  val <- M.new 1
  M.write val 0 a
  return $ R val

_val :: R a -> IO a
_val = \ra -> M.read (val ra) 0

someFunctor :: Show a => (a -> b) -> IO (R a) -> IO (R b)
someFunctor = \f -> \ioA -> do
  print "-- someFunctor"

  val <- ioA >>= _val
  print val --works    5
  let ioB = io $ f val

  --here, I want to actually `print val` when `f == print`
  return $ f val

  ioB
</code>```

Output

```<code>"-- someFunctor"
5
"done"
</code>```

The current sample code woks without errors, and what  I want to achieve is to evaluate

f val

where

f val is the value wrapped into the new container ioB: io $ f val

However, due to the lazy-evaluation strategy of Haskell or some other reason, when f == print, this is not actually performed, so the val is not printed against my expectation.

So far, I did return $ f val, but this does not work unlike the working print val.

Just f val in do thread doesn't go well because f can be id and in that case, it's not IO type. Type mismatch. The compiler smartly generates an error here thanksfully.

So, my question is what is the generic way to implement f val to be evaluated when f == print f :: a -> IO ()?

答:
If you want to do IO, you have to admit you're doing IO.

```<code>someFunctor :: Show a => (a -> IO b) -> IO (R a) -> IO (R b)
someFunctor = \f -> \ioA -> do
    {- ... -}
    b <- f val
    io b
</code>```

You can lift non-IO functions to IO ones with return, as in

```<code>someFunctor (return . id)
</code>```

Body:
This is a repost of my previous question(deleted by myself) since I considered it would be adequate to change the focus by presenting the sample code below.

Basically, I try to implement a Functor that takes a function such as id, \a -> a + 1 or even print .

So the function type can be

f :: a -> b

f :: a -> IO ()

module Main where

import Control.Monad.Primitive (PrimMonad (PrimState))
import qualified Data.Vector.Mutable as M
import System.IO.Error (isDoesNotExistErrorType)

main :: IO ()
main = do
  let ioA = io (5 :: Int)
  let f = print
  --  f = \a -> a + 1
  let ioB = someFunctor f ioA

  ioB

  print "done"

data R a = R
  { val :: M.MVector (PrimState IO) a
  }

io :: a -> IO (R a)
io = \a -> do
  val <- M.new 1
  M.write val 0 a
  return $ R val

_val :: R a -> IO a
_val = \ra -> M.read (val ra) 0

someFunctor :: Show a => (a -> b) -> IO (R a) -> IO (R b)
someFunctor = \f -> \ioA -> do
  print "-- someFunctor"

  val <- ioA >>= _val
  print val --works    5
  let ioB = io $ f val

  --here, I want to actually `print val` when `f == print`
  return $ f val

  ioB

Output

"-- someFunctor"
5
"done"

The current sample code woks without errors, and what  I want to achieve is to evaluate

f val

where

f val is the value wrapped into the new container ioB: io $ f val

However, due to the lazy-evaluation strategy of Haskell or some other reason, when f == print, this is not actually performed, so the val is not printed against my expectation.

So far, I did return $ f val, but this does not work unlike the working print val.

Just f val in do thread doesn't go well because f can be id and in that case, it's not IO type. Type mismatch. The compiler smartly generates an error here thanksfully.

So, my question is what is the generic way to implement f val to be evaluated when f == print f :: a -> IO ()?

Body:
If you want to do IO, you have to admit you're doing IO.

someFunctor :: Show a => (a -> IO b) -> IO (R a) -> IO (R b)
someFunctor = \f -> \ioA -> do
    {- ... -}
    b <- f val
    io b

You can lift non-IO functions to IO ones with return, as in

someFunctor (return . id)


问:
JPA : how to generate a common id?
I need to allocate a same unique id (batchid) for each row inserted in a BD during a batch execution as illustrated below.

```<code>| id | batchid |
| -- | ------- |
| 1  | 1       |
| 2  | 1       |
| 3  | 2       |
| 4  | 2       |
| 5  | 2       |
| 6  | 3       |
</code>```

Was wondering if there is an automated way to do it with jpa annotation, like with a sequence ?

答:
Did it for now this way:

@Repository
public interface SeqRepository extends JpaRepository<CsvEntity, Long> {
    @Query(value = "SELECT nextval('batch_id_seq')", nativeQuery = true)
    Integer getNextBatchId();
}
```
<p>schema.sql</p>
<pre class="lang-sql prettyprint-override"><code>CREATE SEQUENCE IF NOT EXISTS batch_id_seq
INCREMENT 1
START 1;
</code>```

Title: JPA : how to generate a common id?

Body:
I need to allocate a same unique id (batchid) for each row inserted in a BD during a batch execution as illustrated below.

| id | batchid |
| -- | ------- |
| 1  | 1       |
| 2  | 1       |
| 3  | 2       |
| 4  | 2       |
| 5  | 2       |
| 6  | 3       |

Was wondering if there is an automated way to do it with jpa annotation, like with a sequence ?

Body:
Did it for now this way:

@Repository
public interface SeqRepository extends JpaRepository<CsvEntity, Long> {
    @Query(value = "SELECT nextval('batch_id_seq')", nativeQuery = true)
    Integer getNextBatchId();
}

schema.sql

CREATE SEQUENCE IF NOT EXISTS batch_id_seq
INCREMENT 1
START 1;


问:
How to filter a string list containing specific characters in python
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]
</code>```

Does anybody have an idea of how to do that?

Thank you in advance!

答:
You are almost there, you just need to tweak your all condition a bit.

all(word for letter in letters if letter in word) -> this would return True as long as any word is True which would always be the case.

What we want to check is that "all letters in the word are part of letters", letter in letters in the following code would return True/False if a letter is in letters. So with all, it would only return True if all letter in letters checks return True.

```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']
dictionary = ['REPORT', 'INVALID', 'ROPE']
final_list = [word for word in dictionary if all(letter in letters for letter in word)]
print(final_list)
</code>```

outputs -

```<code>['REPORT', 'ROPE']
</code>```

Body:
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]

Does anybody have an idea of how to do that?

Thank you in advance!

Body:
You are almost there, you just need to tweak your all condition a bit.

all(word for letter in letters if letter in word) -> this would return True as long as any word is True which would always be the case.

What we want to check is that "all letters in the word are part of letters", letter in letters in the following code would return True/False if a letter is in letters. So with all, it would only return True if all letter in letters checks return True.

letters = ['R', 'E', 'T', 'O', 'P', 'A']
dictionary = ['REPORT', 'INVALID', 'ROPE']
final_list = [word for word in dictionary if all(letter in letters for letter in word)]
print(final_list)

outputs -

['REPORT', 'ROPE']


问:
How to compare two children of Firebase Realtime Database?
Based on the result of data.key === "high_temp_coil", I am printing the data into my webpage with data.val() as shown below:

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on('child_added', function(data) {
  if (data.key === 'high_temp_coil') {
    $('#high_temp_coil .value').html(data.val())
  }
  if (data.key === 'low_temp_coil') {
    $('#low_temp_coil .value').html(data.val());
  }
}
```
<p>In my code <code>high_temp_coil</code> represents the high temperature of the coil and <code>low_temp_coil</code> represents the low temperature of the coil, each with their own fields in my database. However, due to a manufacturing issue, sometimes the high temp and low temps are backwards and I need to figure this out before printing the data. This is how I was trying to do that but it doesn't work:</p>
<pre class="lang-js prettyprint-override"><code>if (data.key === "high_temp_coil"){
  let valueh= data.val();
  if (data.key === "low_temp_coil"){
    let valuel= data.val()
    console.log(valueh);
    console.log(valuel);
  }
}
</code>```

This is what the data looks like in my database:

{
  "MachineNo": {
    "water": "value"
    "high_temp_coil": "value"
    "low_temp_coil": "value"
  }
}
```

答:
When you use a child_added event listener, your callback will be invoked whenever one of the children under that database location changes. Using this, you would need to store high_temp_coil and low_temp_coil in variables outside of the function so that you can compare them properly. Because you store the result in an element, you could pull the current values from there.

Note: In the below snippets I follow the convention of naming the DataSnapshot object as snapshot, reserving data for the plain JavaScript object returned by snapshot.val(). This aids in preventing confusion later on, especially when not using TypeScript.

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on('child_added', function(snapshot) {
  if (snapshot.key === 'high_temp_coil') {
    const newHighTempValue = snapshot.val();
    const lowTempValue = $('#low_temp_coil .value').html();
    if (Number(newHighTempValue) >= Number(lowTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      // new value is higher than current value
      $('#high_temp_coil .value').html(newHighTempValue)
    } else {
      // new value is lower than current value, swap places
      $('#high_temp_coil .value').html(lowTempValue)
      $('#low_temp_coil .value').html(newHighTempValue)
    }
  }
  if (snapshot.key === 'low_temp_coil') {
    const newLowTempValue = snapshot.val();
    const highTempValue = $('#high_temp_coil .value').html();
    if (Number(newLowTempValue) < Number(highTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      // new value is lower than current value
      $('#low_temp_coil .value').html(newLowTempValue)
    } else {
      // new value is higher than current value, swap places
      $('#low_temp_coil .value').html(highTempValue)
      $('#high_temp_coil .value').html(newLowTempValue)
    }
  }
}
```
<p>The main issue with the above code is that the <code>child_added</code> events would fire once on page load, and not get live updates from any sensors updating the data because these changes would fire <code>child_changed</code> events.</p>
<p>However, for your data structure, you can greatly simplify your code by listening to <code>value</code> events instead. These listeners will be fired each time any of the data under that location is updated - including when a machine is created and any changes to the temperatures. Also, because the data is one level higher in the tree, you have access to the latest <code>high_temp_coil</code> and <code>low_temp_coil</code> values right in the snapshot. The trade-off for this listener is that you need to make sure to handle when the data does not exist (<code>snapshot.exists()===false</code>) because <code>child_added</code> listeners would only be invoked when data is created where it is guaranteed to exist.</p>
<pre class="lang-js prettyprint-override"><code>var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on(
  'value',
  function(snapshot) {
    if (!snapshot.exists()) {
      // TODO: handle machine does not exist
      console.error(`Machine ${localStorage.getItem('machineid')} does not exist in database`);
      return;
    }

    const data = snapshot.val();
    const highTempValue = data.high_temp_coil;
    const lowTempValue = data.low_temp_coil;

    if (Number(highTempValue) >= Number(lowTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      $('#high_temp_coil .value').html(highTempValue)
      $('#low_temp_coil .value').html(lowTempValue)
    } else {
      $('#high_temp_coil .value').html(lowTempValue)
      $('#low_temp_coil .value').html(highTempValue)
    }
  },
  (error) => {
    // TODO: implement better error handling
    console.error("Listener was cancelled due to an error:", error);
  }
);
</code>```

Body:
Based on the result of data.key === "high_temp_coil", I am printing the data into my webpage with data.val() as shown below:

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on('child_added', function(data) {
  if (data.key === 'high_temp_coil') {
    $('#high_temp_coil .value').html(data.val())
  }
  if (data.key === 'low_temp_coil') {
    $('#low_temp_coil .value').html(data.val());
  }
}

In my code high_temp_coil represents the high temperature of the coil and low_temp_coil represents the low temperature of the coil, each with their own fields in my database. However, due to a manufacturing issue, sometimes the high temp and low temps are backwards and I need to figure this out before printing the data. This is how I was trying to do that but it doesn't work:

if (data.key === "high_temp_coil"){
  let valueh= data.val();
  if (data.key === "low_temp_coil"){
    let valuel= data.val()
    console.log(valueh);
    console.log(valuel);
  }
}

This is what the data looks like in my database:

{
  "MachineNo": {
    "water": "value"
    "high_temp_coil": "value"
    "low_temp_coil": "value"
  }
}

Body:
When you use a child_added event listener, your callback will be invoked whenever one of the children under that database location changes. Using this, you would need to store high_temp_coil and low_temp_coil in variables outside of the function so that you can compare them properly. Because you store the result in an element, you could pull the current values from there.

Note: In the below snippets I follow the convention of naming the DataSnapshot object as snapshot, reserving data for the plain JavaScript object returned by snapshot.val(). This aids in preventing confusion later on, especially when not using TypeScript.

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on('child_added', function(snapshot) {
  if (snapshot.key === 'high_temp_coil') {
    const newHighTempValue = snapshot.val();
    const lowTempValue = $('#low_temp_coil .value').html();
    if (Number(newHighTempValue) >= Number(lowTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      // new value is higher than current value
      $('#high_temp_coil .value').html(newHighTempValue)
    } else {
      // new value is lower than current value, swap places
      $('#high_temp_coil .value').html(lowTempValue)
      $('#low_temp_coil .value').html(newHighTempValue)
    }
  }
  if (snapshot.key === 'low_temp_coil') {
    const newLowTempValue = snapshot.val();
    const highTempValue = $('#high_temp_coil .value').html();
    if (Number(newLowTempValue) < Number(highTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      // new value is lower than current value
      $('#low_temp_coil .value').html(newLowTempValue)
    } else {
      // new value is higher than current value, swap places
      $('#low_temp_coil .value').html(highTempValue)
      $('#high_temp_coil .value').html(newLowTempValue)
    }
  }
}

The main issue with the above code is that the child_added events would fire once on page load, and not get live updates from any sensors updating the data because these changes would fire child_changed events.

However, for your data structure, you can greatly simplify your code by listening to value events instead. These listeners will be fired each time any of the data under that location is updated - including when a machine is created and any changes to the temperatures. Also, because the data is one level higher in the tree, you have access to the latest high_temp_coil and low_temp_coil values right in the snapshot. The trade-off for this listener is that you need to make sure to handle when the data does not exist (snapshot.exists()===false) because child_added listeners would only be invoked when data is created where it is guaranteed to exist.

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on(
  'value',
  function(snapshot) {
    if (!snapshot.exists()) {
      // TODO: handle machine does not exist
      console.error(`Machine ${localStorage.getItem('machineid')} does not exist in database`);
      return;
    }

    const data = snapshot.val();
    const highTempValue = data.high_temp_coil;
    const lowTempValue = data.low_temp_coil;

    if (Number(highTempValue) >= Number(lowTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      $('#high_temp_coil .value').html(highTempValue)
      $('#low_temp_coil .value').html(lowTempValue)
    } else {
      $('#high_temp_coil .value').html(lowTempValue)
      $('#low_temp_coil .value').html(highTempValue)
    }
  },
  (error) => {
    // TODO: implement better error handling
    console.error("Listener was cancelled due to an error:", error);
  }
);