问:
Correct way to execute a function when I have function name
I have a string "Car.run(true)" or "Car.find('window')", I want to execute the function run or find and also pass respective parameters passed. What is the correct way to do it without using eval?

I tried to split the string, extracted the function name and parameters using regex but issue is with boolean values(it will a string after extraction).

Can anyone guide me to resolve this blocker?

答:
In javascript land, classes are just objects that can be referenced using dictionary lookup syntax

```<code>class Car { run(x) { return x } find(x) { return x }  }
car = new Car()
method_name = 'run'
car[method_name]    # == ƒ run(x) { return x }
car[method_name](1) # == 1
</code>```

In python land you would need hasattr() and getattr()

Body:
In javascript land, classes are just objects that can be referenced using dictionary lookup syntax

class Car { run(x) { return x } find(x) { return x }  }
car = new Car()
method_name = 'run'
car[method_name]    # == ƒ run(x) { return x }
car[method_name](1) # == 1

In python land you would need hasattr() and getattr()


来源: stackexchange

问:
Calling PEM_read_bio_RSAPrivateKey() gives "error:0906D06C:lib(9):func(109):reason(108)"
Reading in a key file, I pass the data to PEM_read_bui_RSAPrivateKey, and am rewarded with:

error:0906D06C:lib(9):func(109):reason(108)

I was able to look up lib 9 (PEM, makes sense), but wasn't able to find anything about the func or reason.  I'm guessing func(109) is PEM_read_bui_RSAPrivateKey(), but it could just as easily be some internal thing.

What am I doing wrong?

答:
I was using the public key file instead of the private key file.

Based on my searches, this is one of several different things that can cause this particular error, but I didn't see any of them mention this particular cause.

ContentLicense: CC BY-SA 4.0


问:
NoSuchMethodError: 'The getter 'uid' was called on null' in flutter
I am pretty new to flutter. And I am getting this NoSuchMethodError: The getter 'uid' was called on null. I have red many posts and it seems like I need to use await with async. But I have no Idea how I can do it. This is happening when I want to pass the current uid of the user.
Here is my code:

```<code>class ProfilePage extends StatefulWidget {
  //final String userProfileId;
  //ProfilePage({this.userProfileId});
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {

  FirebaseUser thecurrentuser;
  profilepicture() {

    return FutureBuilder(

        future: userReference.document(thecurrentuser.uid).get(), // So here I am getting the error
        builder: (context, dataSnapshot) {
        User user = User.fromDocument(dataSnapshot.data);
          if (!dataSnapshot.hasData) {
            return Padding(
            padding: EdgeInsets.all(17.0),
    }
          User user = User.fromDocument(dataSnapshot.data);
          return Padding(
            padding: EdgeInsets.all(17.0),
            child: Column(
              children: <Widget>[
                CircleAvatar(
                    radius: 45.0,
                    backgroundColor: Colors.grey,
                    backgroundImage: NetworkImage(
                        'https://upload.wikimedia.org/wikipedia/commons/9/9a/Mahesh_Babu_in_Spyder_%28cropped%29.jpg')),
                Text(user.username),
                Expanded(
                    flex: 1, child: Column(children: <Widget>[Text("coolbro")]))
              ],
            ),
          );
        });
  }
</code>```

My user model

```<code>class User{
  final String uid;
  final String email;
  final String username;

  User({
    this.uid,
    this.email,
    this.username,
  });

  factory User.fromDocument(DocumentSnapshot doc){
    return User(
      uid: doc['uid'],
      email: doc['email'],
      username: doc['username']    );
  }
}

</code>```

答:
You are not initializing currentUser that's why it is equal to null. You should do the following:

```<code>  Future<DocumentSnapshot> getData() async{
    var firebaseUser = await FirebaseAuth.instance.currentUser();
    return userReference.document(firebaseUser.uid).get();
  }
</code>```

So create a method that returns a Future<DocumentSnapshot> and inside that document you can retrieve the current user and use get() to retrieve the data.

Then inside the FutureBuilder, do the following:

```<code>    return FutureBuilder(
        future: getData(),
</code>```

```<code>      if (!dataSnapshot.hasData) {
        return Padding(
        padding: EdgeInsets.all(17.0),
}
 else if(dataSnapshot.hasData){
      User user = User.fromDocument(dataSnapshot.data);
      return Padding(
        padding: EdgeInsets.all(17.0),
        child: Column(
          children: <Widget>[
            CircleAvatar(
                radius: 45.0,
                backgroundColor: Colors.grey,
                backgroundImage: NetworkImage(
                    'https://upload.wikimedia.org/wikipedia/commons/9/9a/Mahesh_Babu_in_Spyder_%28cropped%29.jpg')),
            Text(user.username),
            Expanded(
                flex: 1, child: Column(children: <Widget>[Text("coolbro")]))
          ],
        ),
      );
    });
 }
</code>```

Body:
I am pretty new to flutter. And I am getting this NoSuchMethodError: The getter 'uid' was called on null. I have red many posts and it seems like I need to use await with async. But I have no Idea how I can do it. This is happening when I want to pass the current uid of the user.
Here is my code:

class ProfilePage extends StatefulWidget {
  //final String userProfileId;
  //ProfilePage({this.userProfileId});
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {

  FirebaseUser thecurrentuser;
  profilepicture() {

    return FutureBuilder(

        future: userReference.document(thecurrentuser.uid).get(), // So here I am getting the error
        builder: (context, dataSnapshot) {
        User user = User.fromDocument(dataSnapshot.data);
          if (!dataSnapshot.hasData) {
            return Padding(
            padding: EdgeInsets.all(17.0),
    }
          User user = User.fromDocument(dataSnapshot.data);
          return Padding(
            padding: EdgeInsets.all(17.0),
            child: Column(
              children: <Widget>[
                CircleAvatar(
                    radius: 45.0,
                    backgroundColor: Colors.grey,
                    backgroundImage: NetworkImage(
                        'https://upload.wikimedia.org/wikipedia/commons/9/9a/Mahesh_Babu_in_Spyder_%28cropped%29.jpg')),
                Text(user.username),
                Expanded(
                    flex: 1, child: Column(children: <Widget>[Text("coolbro")]))
              ],
            ),
          );
        });
  }

My user model

class User{
  final String uid;
  final String email;
  final String username;

  User({
    this.uid,
    this.email,
    this.username,
  });

  factory User.fromDocument(DocumentSnapshot doc){
    return User(
      uid: doc['uid'],
      email: doc['email'],
      username: doc['username']    );
  }
}

Body:
You are not initializing currentUser that's why it is equal to null. You should do the following:

  Future<DocumentSnapshot> getData() async{
    var firebaseUser = await FirebaseAuth.instance.currentUser();
    return userReference.document(firebaseUser.uid).get();
  }

So create a method that returns a Future<DocumentSnapshot> and inside that document you can retrieve the current user and use get() to retrieve the data.

Then inside the FutureBuilder, do the following:

    return FutureBuilder(
        future: getData(),

      if (!dataSnapshot.hasData) {
        return Padding(
        padding: EdgeInsets.all(17.0),
}
 else if(dataSnapshot.hasData){
      User user = User.fromDocument(dataSnapshot.data);
      return Padding(
        padding: EdgeInsets.all(17.0),
        child: Column(
          children: <Widget>[
            CircleAvatar(
                radius: 45.0,
                backgroundColor: Colors.grey,
                backgroundImage: NetworkImage(
                    'https://upload.wikimedia.org/wikipedia/commons/9/9a/Mahesh_Babu_in_Spyder_%28cropped%29.jpg')),
            Text(user.username),
            Expanded(
                flex: 1, child: Column(children: <Widget>[Text("coolbro")]))
          ],
        ),
      );
    });
 }


问:
django @login_required decorator for a superuser
Is there a decorator in django similar to @login_required that also tests if the user is a superuser?

Thanks

答:
To require a superuser on a class based view without writing new code:</p>

```<code>from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

@method_decorator(user_passes_test(lambda u: u.is_superuser), name='dispatch')
class AdminCreateUserView(LoginRequiredMixin, FormView):
    ...
    ...
    ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To require a superuser on a class based view without writing new code:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

@method_decorator(user_passes_test(lambda u: u.is_superuser), name='dispatch')
class AdminCreateUserView(LoginRequiredMixin, FormView):
    ...
    ...
    ...


问:
How to copy instance of RequestSpecification from base class
In my base I have created request specification by providing base URI, header, etc,

```<code>RequestSpecification base = given().baseUri( " http://xyz/" )
                                   .port( 8080 )
                                   .header( "Content-Type", "application/json" );
</code>```

And in my sub classB I copied the base instance and added path param to in sub class

```<code>RequestSpecification classB= base.given()
classB.pathParam("name", "abc" );
</code>```

but when I tried to copy the base to another sub class (which do not need path param) it is throwing exception as Invalid number of path parameters. Expected 1, was 0 ,

while updating path param in ClassB, base class also get mutate, since base and sub class are pointing to the same object.
Is there any way to copy base class object without getting updated .
Your Input Would Be Greatly Appreciated!

答:
Instead of;

```<code>RequestSpecification classB = base.given();
classB.pathParam("name", "abc" );
</code>```

try;

```<code>RequestSpecification classB = given().spec(base);
</code>```

Here spec(RequestSpecification requestSpecification) add the data from pre-defined RequestSpecification object.

Check the documentation

Body:
In my base I have created request specification by providing base URI, header, etc,

RequestSpecification base = given().baseUri( " http://xyz/" )
                                   .port( 8080 )
                                   .header( "Content-Type", "application/json" );

And in my sub classB I copied the base instance and added path param to in sub class

RequestSpecification classB= base.given()
classB.pathParam("name", "abc" );

but when I tried to copy the base to another sub class (which do not need path param) it is throwing exception as Invalid number of path parameters. Expected 1, was 0 ,

while updating path param in ClassB, base class also get mutate, since base and sub class are pointing to the same object.
Is there any way to copy base class object without getting updated .
Your Input Would Be Greatly Appreciated!

Body:
Instead of;

RequestSpecification classB = base.given();
classB.pathParam("name", "abc" );

try;

RequestSpecification classB = given().spec(base);

Here spec(RequestSpecification requestSpecification) add the data from pre-defined RequestSpecification object.

Check the documentation


问:
Python: Is there a simple way to address the component functions of a list/array valued function?
Say I have a function f(t) which returns values in an list. Let me symbolically write the return list as [f0(t),f1(t),...], but this shouldn't mean that I have those component functions f0,f1,... defined anywhere.

I would like to define them however!

Of course one way would be

```<code>def f0(t): return f(t)[0]
def f1(t): return f(t)[1]
...
</code>```

however I suspect that there must be a more elegant way to do this. Is there?

Thanks for suggestions!

(Just as side information: In my case the function f(t) is the solution function of an initial value problem obtained with scipy.integrate.solve_ivp and the dense_output option. link to documentation)

答:
If you are OK repeating the call to f(t) for different values of n, I would just define a two-argument wrapper around f:

```<code>def fresult(t, n):
    return f(t)[n]
</code>```

However, you probably don't want to recompute f(t) many times. In that case, you can cache the return value.

```<code>def make_getter(f):
    cache = {}
    def _(t, n):
        if t not in cache:
            cache[t] = tuple(f(t))
        return cache[t][n]
    return _

fresult = make_getter(f)
assert fresult(t, 1) == f(t)[1]
</code>```

Body:
Say I have a function f(t) which returns values in an list. Let me symbolically write the return list as [f0(t),f1(t),...], but this shouldn't mean that I have those component functions f0,f1,... defined anywhere.

I would like to define them however!

Of course one way would be

def f0(t): return f(t)[0]
def f1(t): return f(t)[1]
...

however I suspect that there must be a more elegant way to do this. Is there?

Thanks for suggestions!

(Just as side information: In my case the function f(t) is the solution function of an initial value problem obtained with scipy.integrate.solve_ivp and the dense_output option. link to documentation)

Body:
If you are OK repeating the call to f(t) for different values of n, I would just define a two-argument wrapper around f:

def fresult(t, n):
    return f(t)[n]

However, you probably don't want to recompute f(t) many times. In that case, you can cache the return value.

def make_getter(f):
    cache = {}
    def _(t, n):
        if t not in cache:
            cache[t] = tuple(f(t))
        return cache[t][n]
    return _

fresult = make_getter(f)
assert fresult(t, 1) == f(t)[1]


问:
Customised ordering in Hive's row_number() over partition by order by window function
I have a table with an identifier column id and another column with string values column_b for which I would like to do customer ordering on column_b. Let's say that column_b consists of values A, B, C, D.

The syntax that can be used in Hive for row_number() over() is:

```<code>SELECT id, column_b, row_number() over(partition by id order by column_b) as row_id
FROM   some_table
</code>```

Example see here for an example

However, I would like to do custom ordering on column_b instead of alphabetic ordering. The above syntax would yield something like:

Instead, I would like to explicitly order by column_b using the order A, C, D, B, that is:

How can I achieve this?

答:
Please use below simple query,</p>

```<code>select id, column_b,row_id from
(select id, column_b,row_id from table order by mod(row_id,2) != 0
union all
select id, column_b,row_id from table order by mod(row_id,2) = 0) qry;
</code>```

Body:
I have a table with an identifier column id and another column with string values column_b for which I would like to do customer ordering on column_b. Let's say that column_b consists of values A, B, C, D.

The syntax that can be used in Hive for row_number() over() is:

SELECT id, column_b, row_number() over(partition by id order by column_b) as row_id
FROM   some_table

Example see here for an example

However, I would like to do custom ordering on column_b instead of alphabetic ordering. The above syntax would yield something like:

Instead, I would like to explicitly order by column_b using the order A, C, D, B, that is:

How can I achieve this?

Body:
Please use below simple query,

select id, column_b,row_id from
(select id, column_b,row_id from table order by mod(row_id,2) != 0
union all
select id, column_b,row_id from table order by mod(row_id,2) = 0) qry;


问:
How do you make websites with Java?
This might be a really trivial question, but I've been writing Java programs at my school and I just found out that I can create websites with Java as well.

How can I do that? Any good books/tutorials for that?

Which is better for Web development, Java or PHP?

Also, when using PHP, MySQL comes into picture and while writing Java programs for desktop, we just use File I/O, so what is better for web dev, File I/O or MySQL?

答:
While a lot of others should be mentioned, Apache Wicket should be preferred.

Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.

OwnerDisplayName: GVRV

Title: How do you make websites with Java?

OwnerDisplayName: Esko

ContentLicense: CC BY-SA 2.5


问:
Replacement for URI.escape that avoids Lint/UriEscapeUnescape warnings?
Not sure how to fix Rubocop's Lint/UriEscapeUnescape warning

Tried replacing URI with CGI thinking that was the "drop in" replacement but that blew up the test suite.

Here's the error followed by the line of code where URI is being used:

```<code>app/models/media_file.rb:76:5: W: Lint/UriEscapeUnescape: URI.escape method is obsolete and should not be used. Instead, use CGI.escape, URI.encode_www_form or URI.encode_www_form_component depending on your specific use case.
    URI ...
    ^^^

    # app/models/media_file.rb
    ...
    def cdn_url(format: nil)
    if format.nil?
      "#{s3_config.cloudfront_endpoint}/#{escape_url(key)}"
    elsif converted_urls.with_indifferent_access[format.to_s]
      filename = converted_urls.with_indifferent_access[format.to_s]
      if URI.parse(escape_url(filename)).host
        filename
      else
        "#{s3_config.cloudfront_endpoint}/#{escape_url(filename)}"
      end
    else
      converted(url)
    end
  end
...
  private

  def escape_url(url)
    URI
      .escape(url)
      .gsub(/\(/, '%28')
      .gsub(/\)/, '%29')
      .gsub(/\[/, '%5B')
      .gsub(/\]/, '%5D')
  end
</code>```

EDIT: Adding sample output of strings escaped with URI and CGI:

```<code>            url: images/medium/test-image.jpg
URI.escape(url): images/medium/test-image.jpg
CGI.escape(url): images%2Fmedium%2Ftest-image.jpg

            url: images/medium/test-image.jpg
URI.escape(url): images/medium/test-image.jpg
CGI.escape(url): images%2Fmedium%2Ftest-image.jpg
</code>```

It would appear CGI is not a drop in replacement for URI as the listing error might have you believe. Thoughts?

答:
Encounter with the same problem, got it fixed by using addressable lib.

escaped_query = URI.escape(search,
            Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

#W: Lint/UriEscapeUnescape: URI.escape method is obsolete and should not be used. Instead, use CGI.escape, URI.encode_www_form or URI.encode_www_form_component depending on your specific use case.
```

<p>Solved by:</p>

<ul>
<li>gem <code>addressable</code> gem in <code>gemspec</code> or <code>Gemfile</code>.</li>
</ul>

```gem 'addressable', '~> 2.7'
```

<ul>
<li><p>require <code>addressable/uri</code></p></li>
<li><p>Add appropriate.</p></li>
</ul>

```escaped_query = Addressable::URI.encode_component(search, Addressable::URI::CharacterClasses::QUERY)

```

Body:
Not sure how to fix Rubocop's Lint/UriEscapeUnescape warning

Tried replacing URI with CGI thinking that was the "drop in" replacement but that blew up the test suite.

Here's the error followed by the line of code where URI is being used:

app/models/media_file.rb:76:5: W: Lint/UriEscapeUnescape: URI.escape method is obsolete and should not be used. Instead, use CGI.escape, URI.encode_www_form or URI.encode_www_form_component depending on your specific use case.
    URI ...
    ^^^

    # app/models/media_file.rb
    ...
    def cdn_url(format: nil)
    if format.nil?
      "#{s3_config.cloudfront_endpoint}/#{escape_url(key)}"
    elsif converted_urls.with_indifferent_access[format.to_s]
      filename = converted_urls.with_indifferent_access[format.to_s]
      if URI.parse(escape_url(filename)).host
        filename
      else
        "#{s3_config.cloudfront_endpoint}/#{escape_url(filename)}"
      end
    else
      converted(url)
    end
  end
...
  private

  def escape_url(url)
    URI
      .escape(url)
      .gsub(/\(/, '%28')
      .gsub(/\)/, '%29')
      .gsub(/\[/, '%5B')
      .gsub(/\]/, '%5D')
  end

EDIT: Adding sample output of strings escaped with URI and CGI:

            url: images/medium/test-image.jpg
URI.escape(url): images/medium/test-image.jpg
CGI.escape(url): images%2Fmedium%2Ftest-image.jpg

            url: images/medium/test-image.jpg
URI.escape(url): images/medium/test-image.jpg
CGI.escape(url): images%2Fmedium%2Ftest-image.jpg

It would appear CGI is not a drop in replacement for URI as the listing error might have you believe. Thoughts?

Body:
Encounter with the same problem, got it fixed by using addressable lib.

escaped_query = URI.escape(search,
            Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

#W: Lint/UriEscapeUnescape: URI.escape method is obsolete and should not be used. Instead, use CGI.escape, URI.encode_www_form or URI.encode_www_form_component depending on your specific use case.

Solved by:

gem addressable gem in gemspec or Gemfile.

gem 'addressable', '~> 2.7'

require addressable/uri

Add appropriate.

escaped_query = Addressable::URI.encode_component(search, Addressable::URI::CharacterClasses::QUERY)


问:
How do I automatically restart a Minecraft Spigot server in the event of a crash or /stop when using screen?
I use screen to run my minecraft spigot server on linux so that I can do other tasks at the same time on the same console.
When using screen, all restart scripts described on the Internet and the Spigot wiki no longer worked. The "/restart" command never worked either.
So how do I restart the server automatically after a short time if it crashes or I shut it down with "/stop" ingame?</p>

答:
Tutorial

A friend wrote a bash script to automatically restart a minecraft (spigot) server in the event of a crash or with the command "/stop" when using screen.
There are several seconds to cancel the restart with Enter.
In addition, the exit codes of the previous session are written to a file, which can be used to understand when and why a server has crashed or restarted.

You need two files:

"start.sh"

#!/bin/sh

screen -d -m -S "mc_spigot_server" ./startserver.sh

```

<ol start="2">
<li>"startserver.sh"</li>
</ol>

<pre class="lang-bash prettyprint-override"><code>
#!/bin/bash

JAR=spigot-1.15.2.jar
MAXRAM=1024M
MINRAM=1024M
TIME=20

while [ true ]; do
    java -Xmx$MAXRAM -Xms$MINRAM -jar $JAR nogui
    if [[ ! -d "exit_codes" ]]; then
        mkdir "exit_codes";
    fi
    if [[ ! -f "exit_codes/server_exit_codes.log" ]]; then
        touch "exit_codes/server_exit_codes.log";
    fi
    echo "[$(date +"%d.%m.%Y %T")] ExitCode: $?" >> exit_codes/server_exit_codes.log
    echo "----- Press enter to prevent the server from restarting in $TIME seconds -----";
    read -t $TIME input;
    if [ $? == 0 ]; then
        break;
    else
        echo "------------------- SERVER RESTARTS -------------------";
    fi
done

</code>```

You can change the start parameters by changing the variables:

JAR = server filename

MAXRAM = maximum RAM

MINRAM = minimum RAM

TIME = time in seconds until server restarts automatically

Execute the following in the directory:

chmod +x start.sh startserver.sh
```

<p>Run your start up script:</p>

<pre class="lang-bash prettyprint-override"><code>./start.sh
</code>```

To leave the minecraft screen press Ctrl + A + D

To reconnect to minecraft screen use screen -r

Did you discover any mistakes or do you disagree? Help me do it better.

Body:
Tutorial

A friend wrote a bash script to automatically restart a minecraft (spigot) server in the event of a crash or with the command "/stop" when using screen.
There are several seconds to cancel the restart with Enter.
In addition, the exit codes of the previous session are written to a file, which can be used to understand when and why a server has crashed or restarted.

You need two files:

"start.sh"

#!/bin/sh

screen -d -m -S "mc_spigot_server" ./startserver.sh

"startserver.sh"

#!/bin/bash

JAR=spigot-1.15.2.jar
MAXRAM=1024M
MINRAM=1024M
TIME=20

while [ true ]; do
    java -Xmx$MAXRAM -Xms$MINRAM -jar $JAR nogui
    if [[ ! -d "exit_codes" ]]; then
        mkdir "exit_codes";
    fi
    if [[ ! -f "exit_codes/server_exit_codes.log" ]]; then
        touch "exit_codes/server_exit_codes.log";
    fi
    echo "[$(date +"%d.%m.%Y %T")] ExitCode: $?" >> exit_codes/server_exit_codes.log
    echo "----- Press enter to prevent the server from restarting in $TIME seconds -----";
    read -t $TIME input;
    if [ $? == 0 ]; then
        break;
    else
        echo "------------------- SERVER RESTARTS -------------------";
    fi
done

You can change the start parameters by changing the variables:

JAR = server filename

MAXRAM = maximum RAM

MINRAM = minimum RAM

TIME = time in seconds until server restarts automatically

Execute the following in the directory:

chmod +x start.sh startserver.sh

Run your start up script:

./start.sh

To leave the minecraft screen press Ctrl + A + D

To reconnect to minecraft screen use screen -r

Did you discover any mistakes or do you disagree? Help me do it better.


问:
how to sort the numbers 1, ... n lexicographically without converting the numbers to string?
Assume I have input n how I can print this sequence without convert the number to string?

i.e:-

n = 100
Output :- 1 10 100 11 12 13 14 15 16 17 18 19 2 20 ...

n = 15 Output :- 1 10 11 12 13 14 15 2 3 4 5 6 7 8 9

n = 20 Output :- 1 10 11 12 13 15 15 16 17 18 19 2 20 3 4 5 6 7 8 9

What is the main factor here?

My initial solution that will print the 1's followed by 0's or 2's followed by 0's

```<code> int n = 100;
    for (int i = 1; i <= n; i++) {
        int x = i;
        while (x <= n) {
            System.out.println(x);
            x *= 10;
        }
    }
</code>```

Body:
Assume I have input n how I can print this sequence without convert the number to string?

i.e:-

n = 100
Output :- 1 10 100 11 12 13 14 15 16 17 18 19 2 20 ...

n = 15 Output :- 1 10 11 12 13 14 15 2 3 4 5 6 7 8 9

n = 20 Output :- 1 10 11 12 13 15 15 16 17 18 19 2 20 3 4 5 6 7 8 9

What is the main factor here?

My initial solution that will print the 1's followed by 0's or 2's followed by 0's

 int n = 100;
    for (int i = 1; i <= n; i++) {
        int x = i;
        while (x <= n) {
            System.out.println(x);
            x *= 10;
        }
    }

Body:
Here a condensed solution in Python based on the OP's own answer:

def genRangeLexiSorted(n, k=1):
  for i in range(k, min(k+10-k%10, n+1)):
    yield i
    for j in genRangeLexiSorted(n, 10*i):
      yield j

def printnums(n):
  print(*list(genRangeLexiSorted(n)))

Then the calls

printnums(1)
printnums(9)
printnums(11)
printnums(20)
printnums(100)

give the following outputs:

1
1 2 3 4 5 6 7 8 9
1 10 11 2 3 4 5 6 7 8 9
1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9
1 10 100 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 27 28 29 3 30 31 32 33 34 35 36 37 38 39 4 40 41 42 43 44 45 46 47 48 49 5 50 51 52 53 54 55 56 57 58 59 6 60 61 62 63 64 65 66 67 68 69 7 70 71 72 73 74 75 76 77 78 79 8 80 81 82 83 84 85 86 87 88 89 9 90 91 92 93 94 95 96 97 98 99


问:
selecting a subset of a matrix
I am new to R and feel a bit stupid asking this question.

Below is my code. Say if my data is a matrix of 100 rows and 3 columns. I want to split my data into train and test data using the first 80 rows as my training data & the last 20 as my testing data.

However running the code below, I can see x_test & y_test both have 100 rows, why?

```<code>data_dim <- dim(data_input)
split_row <- round(data_dim[1] * 0.8)

x_train <- data_input[1:split_row, 1 : data_dim[2]-1]
y_train <- data_input[1:split_row, data_dim[2]]
x_test <- data_input[split_row + 1 : data_dim[1], 1 : data_dim[2]-1]
y_test <- data_input[split_row + 1 : data_dim[1], data_dim[2]]
</code>```

答:
Simplest fix is to add some parens to make it clear what rows you want

set.seed(2020)
data_input <- matrix(runif(300), nrow = 100, ncol = 3)
data_dim <- dim(data_input)
split_row <- round(data_dim[1] * 0.8)

x_train <- data_input[1:split_row, 1 : data_dim[2]-1]
y_train <- data_input[1:split_row, data_dim[2]]
x_test <- data_input[(split_row + 1) : data_dim[1], 1 : data_dim[2]-1]
y_test <- data_input[(split_row + 1) : data_dim[1], data_dim[2]]
```

caret::createDataPartition is a nice tool for this sort of thing.

Title: selecting a subset of a matrix

Body:
I am new to R and feel a bit stupid asking this question.

Below is my code. Say if my data is a matrix of 100 rows and 3 columns. I want to split my data into train and test data using the first 80 rows as my training data & the last 20 as my testing data.

However running the code below, I can see x_test & y_test both have 100 rows, why?

data_dim <- dim(data_input)
split_row <- round(data_dim[1] * 0.8)

x_train <- data_input[1:split_row, 1 : data_dim[2]-1]
y_train <- data_input[1:split_row, data_dim[2]]
x_test <- data_input[split_row + 1 : data_dim[1], 1 : data_dim[2]-1]
y_test <- data_input[split_row + 1 : data_dim[1], data_dim[2]]

Body:
Simplest fix is to add some parens to make it clear what rows you want

set.seed(2020)
data_input <- matrix(runif(300), nrow = 100, ncol = 3)
data_dim <- dim(data_input)
split_row <- round(data_dim[1] * 0.8)

x_train <- data_input[1:split_row, 1 : data_dim[2]-1]
y_train <- data_input[1:split_row, data_dim[2]]
x_test <- data_input[(split_row + 1) : data_dim[1], 1 : data_dim[2]-1]
y_test <- data_input[(split_row + 1) : data_dim[1], data_dim[2]]

caret::createDataPartition is a nice tool for this sort of thing.


问:
How to get the return from Axios.get and Render components dynamically on a Functional Component
I have a Functional Component and I am trying to get data from an axios.get() and render some components dynamically based on the response of the request.

If I console.log the response is Ok, but my problem is how to use the return from axios.get() to create components on the screen.

I've tried with a simple array and using it I can create the components. What I want is to create the components on screen the same way I've done with the array.

I've read a lot of post before posting my own. I would really appreciate some help or guidance.

import React, { createElement, useState, useEffect } from 'react';
import { Text, StyleSheet, View, TouchableOpacity, Image } from 'react-native';
import axios from 'axios';

const HomeScreen = ({ navigation }) => {

  axios.get("http://100.103.16.113:8081/api/checklists", {
  }).then
    (function (response) {
      console.log(response.data);
    }).catch(error => {
      console.log(error);
    })
  const checklists = [{
    "id": 1,
    "checklisT_DESCRIPTION": "CHECKLIST 1"
  },
  {
    "id": 2,
    "checklisT_DESCRIPTION": "CHECKLIST 2"
  },
  {
    "id": 3,
    "checklisT_DESCRIPTION": "CHECKLIST 3"
  }
  ]
  return (
    <View >
      <Text style={styles.text}> Select an Audit</Text>

      <View style={styles.maincontainer}>
        <View style={styles.container}>

          {}
          {checklists.map(r => (

            <TouchableOpacity onPress={() => navigation.navigate('AuditS')} style={styles.button}
            >
              <Image source={require('../assets/icons8-audit-80.png')} style={styles.Image}></Image>
              <Text style={styles.ButtonText}>{r.checklisT_DESCRIPTION}</Text>

            </TouchableOpacity >
          ))}

        </View>
      </View>
      <View style={styles.bottomcontainer}>
        <TouchableOpacity onPress={() => navigation.navigate('Login')}
        >
          <Text style={styles.logout}>LOGOUT</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  text: {
    fontSize: 50,
    fontFamily: 'Comfortaa-Regular',
    alignItems: "center",
    textAlignVertical: "center",
    textAlign: "center",
    justifyContent: "center",
  },
  container: {
    marginTop: 50,
    flexDirection: "row",
    marginLeft: 50,
    width: '100%'
  },
  maincontainer: {
    flexDirection: "column",
    width: '80%',
    alignContent: "center",
    justifyContent: "center",
  },
  bottomcontainer: {
    marginTop: '70%',
    width: '100%',
    alignItems: "center",
    justifyContent: "flex-end",
    alignContent: "flex-end",
  },
  logout: {
    marginTop: 50,
    margin: 15,
    height: 60,
    width: 440,
    borderColor: '#000000',
    backgroundColor: '#000000',
    borderWidth: 2,
    borderRadius: 10,
    fontSize: 18,
    textAlign: "center",
    textAlignVertical: "center",
    color: "#FFFFFF",
    fontFamily: 'Comfortaa-Bold'
  },
  button: {
    backgroundColor: '#0f99f5',
    fontSize: 16,
    color: '#FFF',
    width: 150,
    height: 150,
    borderRadius: 10,
    textAlignVertical: "bottom",
    textAlign: "center",
    marginVertical: 20,
    marginHorizontal: 10,
    fontFamily: 'Comfortaa-Bold'
  },
  ButtonText: {
    textAlignVertical: "bottom",
    textAlign: "center",
    fontSize: 16,
    color: '#FFF',
    marginHorizontal: 10,
    fontFamily: 'Comfortaa-Bold'
  },
  Image: {
    width: "50%",
    height: "50%",
    alignContent: "center",
    alignSelf: "center",
    marginTop: 10,
    marginBottom: 10
  }
});

export default HomeScreen;
```

答:
You need to use a state inside the component.

import React, { createElement, useState, useEffect  } from 'react';

const HomeScreen = ({ navigation }) => {

  const [checkList, setCheckList] = useState([{
                "id": 1,
                "checklisT_DESCRIPTION": "CHECKLIST 1"
              },
              {
                "id": 2,
                "checklisT_DESCRIPTION": "CHECKLIST 2"
              },
              {
                "id": 3,
                "checklisT_DESCRIPTION": "CHECKLIST 3"
              }
            ]);

  useEffect(() => {
    axios.get("http://100.103.16.113:8081/api/checklists", {
                  }).then
                   (function (response) {
                    setCheckList(response.data); // update the state
                  }).catch(error => {
                    console.log(error);
                  })
  }, [])

  return (
```


问:
How do I use arrow functions in React
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

and the error message i'm getting is:

```<code>./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed
</code>```

any assistance will be highly appreciated

答:
You can call it as a function in your jsx like

render(){
  return (

{this.state.apiResponse}

      { this.trial() }

  );
}

```

<p>But I will suggest not doing so. Instead, make it a functional component. You can create it in the same file as this one or on a separate dedicated page. </p>

<p>So your whole code should be like this </p>

<pre class="lang-js prettyprint-override"><code>

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

const Trial = ()=> ( <div>this is my div</div>)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

Hope this helps

Title: How do I use arrow functions in React

Body:
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(

this is my div

    );
  }

render(){
  return (

{this.state.apiResponse}

      <Trial />

  );
}
}

export default App;

and the error message i'm getting is:

./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed

any assistance will be highly appreciated

Body:
You can call it as a function in your jsx like

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      { this.trial() }

    </div>
  );
}

But I will suggest not doing so. Instead, make it a functional component. You can create it in the same file as this one or on a separate dedicated page.

So your whole code should be like this

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

const Trial = ()=> ( <div>this is my div</div>)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;

Hope this helps


问:
SQL - Removing Row Groups
I have a table with the following information:

Is there a way to remove all groups which have multiple IDs? For example group 3 would be removed because it consists of ID 1 and 2.

Thank you!

答:
A simple, portable and efficient approach is not exists:

```<code>select t.*
from mytable t
where not exists (
    select 1
    from mytable t1
    where t1.group = t.group and t1.id <> t.id
)
</code>```

For performance, consider an index on (group, id).

Side note: group is a SQL keyword (as in group by), hence not a good choice for a column name.

Title: SQL - Removing Row Groups

Body:
A simple, portable and efficient approach is not exists:

select t.*
from mytable t
where not exists (
    select 1
    from mytable t1
    where t1.group = t.group and t1.id <> t.id
)

For performance, consider an index on (group, id).

Side note: group is a SQL keyword (as in group by), hence not a good choice for a column name.


问:
How do I decode opus file to pcm file using libavcodec from ffmpeg?
I am trying to decode opus to pcm file using libavcodec.So,I use ffmpeg example from https://ffmpeg.org/doxygen/trunk/decode_audio_8c-example.html .And I change AV_CODEC_ID_MP2 to AV_CODEC_ID_OPUS.But I get an error.

```<code>codec = avcodec_find_decoder((AV_CODEC_ID_MP2);
codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
</code>```

error:

```<code>    codec ./decode_audio ./out.opus ./out.pcm
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
</code>```

So I try to change opus AV_CODEC_ID_OPUS to AV_CODEC_ID_MP3 and try again.

```<code>    codec ./decode_audio ./out.mp3 ./out.pcm
    [mp3float @ 0x7fe564002000] Header missing
    Error submitting the packet to the decoder
</code>```

Why does the example from ffmpeg get error?What should I do ?

答: You can't decode opus this way. Mp3 packets are self-delimiting, opus is not. Which means that opus requires a container (usually ogg). That container must be parsed to determine the start and end of an opus packet that you can then decode. libavformat can be used to read AVPackets from the file.

Body:
I am trying to decode opus to pcm file using libavcodec.So,I use ffmpeg example from https://ffmpeg.org/doxygen/trunk/decode_audio_8c-example.html .And I change AV_CODEC_ID_MP2 to AV_CODEC_ID_OPUS.But I get an error.

codec = avcodec_find_decoder((AV_CODEC_ID_MP2);
codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);

error:

    codec ./decode_audio ./out.opus ./out.pcm
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.
    [opus @ 0x7ff361800000] Error parsing Opus packet header.

So I try to change opus AV_CODEC_ID_OPUS to AV_CODEC_ID_MP3 and try again.

    codec ./decode_audio ./out.mp3 ./out.pcm
    [mp3float @ 0x7fe564002000] Header missing
    Error submitting the packet to the decoder

Why does the example from ffmpeg get error?What should I do ?


答:
You can try simply like below, if you dont want to use eval:

```<code>var functionHolder = "Car.run(true)";
var myTmpFunction = new Function(functionHolder);
myTmpFunction ();  //This would invoke

</code>```

Title: Correct way to execute a function when I have function name

Body:
I have a string "Car.run(true)" or "Car.find('window')", I want to execute the function run or find and also pass respective parameters passed. What is the correct way to do it without using eval?

I tried to split the string, extracted the function name and parameters using regex but issue is with boolean values(it will a string after extraction).

Can anyone guide me to resolve this blocker?

Body:
You can try simply like below, if you dont want to use eval:

var functionHolder = "Car.run(true)";
var myTmpFunction = new Function(functionHolder);
myTmpFunction ();  //This would invoke


问:
get random value from a PHP array, but make it unique
I want to select a random value from a array, but keep it unique as long as possible.

For example if I'm selecting a value 4 times from a array of 4 elements, the selected value should be random, but different every time.

If I'm selecting it 10 times from the same array of 4 elements, then obviously some values will be duplicated.

I have this right now, but I still get duplicate values, even if the loop is running 4 times:

```<code>$arr = $arr_history = ('abc', 'def', 'xyz', 'qqq');

for($i = 1; $i < 5; $i++){
  if(empty($arr_history)) $arr_history = $arr;
  $selected = $arr_history[array_rand($arr_history, 1)];
  unset($arr_history[$selected]);
  // do something with $selected here...
}
</code>```

答:
```<code>$isShowCategory = array();
for ($i=0; $i <5 ; $i++) {
   $myCategory = array_rand($arrTrCategoryApp,1);
   if (!in_array($myCategory, $isShowCategory)) {
      $isShowCategory[] = $myCategory;

      #do something

   }
}
</code>```

Body:
I want to select a random value from a array, but keep it unique as long as possible.

For example if I'm selecting a value 4 times from a array of 4 elements, the selected value should be random, but different every time.

If I'm selecting it 10 times from the same array of 4 elements, then obviously some values will be duplicated.

I have this right now, but I still get duplicate values, even if the loop is running 4 times:

$arr = $arr_history = ('abc', 'def', 'xyz', 'qqq');

for($i = 1; $i < 5; $i++){
  if(empty($arr_history)) $arr_history = $arr;
  $selected = $arr_history[array_rand($arr_history, 1)];
  unset($arr_history[$selected]);
  // do something with $selected here...
}


问:
TypeError: __init__() got multiple values for argument 'executable_path' using Selenium through Python
Error is:

```<code>TypeError: __init__() got multiple values for argument 'executable_path'
</code>```

I can't see what is causing this!

chrome_options = Options() #line 8
chrome_options.add_argument('--headless') #line 9
chrome_options.add_argument('--no-sandbox') #line 10
chrome_options.add_argument('--disable-gpu') #line 11
browser=webdriver.Chrome(chrome_options,executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe') #This is line 12
```

<p>This is the error</p>

```Traceback (most recent call last):
File "main.py", line 12, in <module>
browser = webdriver.Chrome(chrome_options, executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe')
TypeError: __init__() got multiple values for argument 'executable_path'
```

答:
This error message...

```<code>TypeError: __init__() got multiple values for argument 'executable_path'
</code>```

...implies that the argument 'executable_path' was mentioned multiple times while invoking the RemoteWebDriver.

As per the selenium.webdriver.chrome.webdriver.WebDriver Class implementation:

```<code>class selenium.webdriver.chrome.webdriver.WebDriver(executable_path='chromedriver', port=0, options=None, service_args=None, desired_capabilities=None, service_log_path=None, chrome_options=None)
</code>```

Moreover, as per the defination of WebDriver(RemoteWebDriver) for Chrome:

```<code>def __init__(self, executable_path="chromedriver", port=0,
             options=None, service_args=None,
             desired_capabilities=None, service_log_path=None,
             chrome_options=None):
    """
    Creates a new instance of the chrome driver.

    Starts the service and then creates new instance of chrome driver.

    :Args:
     - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
</code>```

So, among the arguments which can be passed to invoke the RemoteWebDriver for ChromeDriver/Chrome executable_path is the first argument and also the default argument, incase the Key is not specified specifically.

Hence in your usecase, as you haven't mentioned the _key_for the first argument, it was considered as the value for executable_path. Then again in the second argument you have mentioned the Key / Value pair of executable_path again. Hence you see the error:

```<code>TypeError: __init__() got multiple values for argument 'executable_path'
</code>```

Solution

Your effective code block can be either of the following:

```<code>chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
browser=webdriver.Chrome(executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe', options=chrome_options)
</code>```

Or

```<code>chrome_options = Options() #line 8
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
browser=webdriver.Chrome(options=chrome_options, executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe')
</code>```

Body:
Error is:

TypeError: __init__() got multiple values for argument 'executable_path'

I can't see what is causing this!

chrome_options = Options() #line 8
chrome_options.add_argument('--headless') #line 9
chrome_options.add_argument('--no-sandbox') #line 10
chrome_options.add_argument('--disable-gpu') #line 11
browser=webdriver.Chrome(chrome_options,executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe') #This is line 12

This is the error

Traceback (most recent call last):
File "main.py", line 12, in <module>
browser = webdriver.Chrome(chrome_options, executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe')
TypeError: __init__() got multiple values for argument 'executable_path'

Body:
This error message...

TypeError: __init__() got multiple values for argument 'executable_path'

...implies that the argument 'executable_path' was mentioned multiple times while invoking the RemoteWebDriver.

As per the selenium.webdriver.chrome.webdriver.WebDriver Class implementation:

class selenium.webdriver.chrome.webdriver.WebDriver(executable_path='chromedriver', port=0, options=None, service_args=None, desired_capabilities=None, service_log_path=None, chrome_options=None)

Moreover, as per the defination of WebDriver(RemoteWebDriver) for Chrome:

def __init__(self, executable_path="chromedriver", port=0,
             options=None, service_args=None,
             desired_capabilities=None, service_log_path=None,
             chrome_options=None):
    """
    Creates a new instance of the chrome driver.

    Starts the service and then creates new instance of chrome driver.

    :Args:
     - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH

So, among the arguments which can be passed to invoke the RemoteWebDriver for ChromeDriver/Chrome executable_path is the first argument and also the default argument, incase the Key is not specified specifically.

Hence in your usecase, as you haven't mentioned the _key_for the first argument, it was considered as the value for executable_path. Then again in the second argument you have mentioned the Key / Value pair of executable_path again. Hence you see the error:

TypeError: __init__() got multiple values for argument 'executable_path'

Solution

Your effective code block can be either of the following:

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
browser=webdriver.Chrome(executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe', options=chrome_options)

Or

chrome_options = Options() #line 8
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
browser=webdriver.Chrome(options=chrome_options, executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe')


问:
Changing datetimepicker background color C#
I have a datetimepicker in my Windows form. This may sound like a silly question with a rather simple answer. However, I just can't find a solution to fit my purpose.

Question > Is there a way in which I can change the back colour of the datetimepicker in the form to a different colour other than the generic white?

Thanks for your help.

答: Set the CalendarMonthBackground property to the color of your choice, but it depends on the theme as well.


问:
mq_open() API return Open Invalid argument
1.this part of code return  "Open queue failed, error Invalid argument" , i don't understand why !!

2.code part

```<code>   struct mq_attr * attr = NULL  ;
   attr = (struct mq_attr * ) malloc (sizeof(struct mq_attr));
   attr->mq_maxmsg   = 100;
   attr->mq_msgsize  = sizeof(upgrademanager_event_t);
   upgrademanager->queue = mq_open("/upgrademanager_mqueue", O_RDWR|O_CREAT|O_EXCL, 0, & attr);
   if (upgrademanager->queue == (mqd_t)-1)
    TRACE_ERROR("Open queue failed, error %s. ", strerror(errno));
</code>```

答:
If your process is not privileged i.e. you are not running it as root then most likely the mq_maxmsg value you are setting i.e. 100 is larger than the default value i.e. 10. Try changing the default value in /proc/sys/fs/mqueue/msg_max

You shouldn't see this issue if you're running as root since HARD_MSGMAX is 65536 (assuming you're running on Linux 3.5 and above).

Quoting from man page for mq_open:

EINVAL O_CREAT was specified in oflag, and attr was not NULL, but attr->mq_maxmsg or attr->mq_msqsize was invalid.  Both of these fields must be greater than  zero.   In  a  process
                that  is unprivileged (does not have the CAP_SYS_RESOURCE capability), attr->mq_maxmsg must be less than or equal to the msg_max limit, and attr->mq_msgsize must be less than
                or equal to the msgsize_max limit.  In addition, even in a privileged process, attr->mq_maxmsg cannot exceed the HARD_MAX limit.  (See mq_overview(7)  for  details  of  these
                limits.)

Quoting from the man page for mq_overview:

/proc/sys/fs/mqueue/msg_max
                This  file can be used to view and change the ceiling value for the maximum number of messages in a queue.  This value acts as a ceiling on the attr->mq_maxmsg argument given
                to mq_open(3).  The default value for msg_max is 10.  The minimum value is 1 (10 in kernels before 2.6.28).  The upper limit is HARD_MSGMAX.  The msg_max limit is ignored for
                privileged processes (CAP_SYS_RESOURCE), but the HARD_MSGMAX ceiling is nevertheless imposed.

Body:
1.this part of code return  "Open queue failed, error Invalid argument" , i don't understand why !!

2.code part

   struct mq_attr * attr = NULL  ;
   attr = (struct mq_attr * ) malloc (sizeof(struct mq_attr));
   attr->mq_maxmsg   = 100;
   attr->mq_msgsize  = sizeof(upgrademanager_event_t);
   upgrademanager->queue = mq_open("/upgrademanager_mqueue", O_RDWR|O_CREAT|O_EXCL, 0, & attr);
   if (upgrademanager->queue == (mqd_t)-1)
    TRACE_ERROR("Open queue failed, error %s. ", strerror(errno));


问:
Java - Check Not Null/Empty else assign default value
I am trying to simplify the following code.

The basic steps that the code should carry out are as follows:

Assign String a default value

Run a method

If the method returns a null/empty string leave the String as default

If the method returns a valid string set the String to this result

A Simple example would be:

```<code>    String temp = System.getProperty("XYZ");
    String result = "default";
    if(temp != null && !temp.isEmpty()){
        result = temp;
    }
</code>```

I have made another attemp using a ternary operator:

```<code>    String temp;
    String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
</code>```

The isNotNullOrEmpty() Method

```<code> private static boolean isNotNullOrEmpty(String str){
    return (str != null && !str.isEmpty());
}
</code>```

Is it possible to do all of this in-line? I know I could do something like this:

```<code>String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";
</code>```

But I am calling the same method twice. I would be something like to do something like this (which doesn't work):

```<code>String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";
</code>```

I would like to initialize the 'temp' String within the same line. Is this possible? Or what should I be doing?

Thank you for your suggestions.

Tim

答:
This is the best solution IMHO.   It covers BOTH null and empty scenario, as is easy to understand when reading the code.   All you need to know is that .getProperty returns a null when system prop is not set:

```<code>String DEFAULT_XYZ = System.getProperty("user.home") + "/xyz";
String PROP = Optional.ofNullable(System.getProperty("XYZ"))
        .filter(s -> !s.isEmpty())
        .orElse(DEFAULT_XYZ);
</code>```

Body:
I am trying to simplify the following code.

The basic steps that the code should carry out are as follows:

Assign String a default value

Run a method

If the method returns a null/empty string leave the String as default

If the method returns a valid string set the String to this result

A Simple example would be:

    String temp = System.getProperty("XYZ");
    String result = "default";
    if(temp != null && !temp.isEmpty()){
        result = temp;
    }

I have made another attemp using a ternary operator:

    String temp;
    String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";

The isNotNullOrEmpty() Method

 private static boolean isNotNullOrEmpty(String str){
    return (str != null && !str.isEmpty());
}

Is it possible to do all of this in-line? I know I could do something like this:

String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";

But I am calling the same method twice. I would be something like to do something like this (which doesn't work):

String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";

I would like to initialize the 'temp' String within the same line. Is this possible? Or what should I be doing?

Thank you for your suggestions.

Tim

Body:
This is the best solution IMHO.   It covers BOTH null and empty scenario, as is easy to understand when reading the code.   All you need to know is that .getProperty returns a null when system prop is not set:

String DEFAULT_XYZ = System.getProperty("user.home") + "/xyz";
String PROP = Optional.ofNullable(System.getProperty("XYZ"))
        .filter(s -> !s.isEmpty())
        .orElse(DEFAULT_XYZ);


问:
Check data is same for one or more records using T SQL
I am having 2 tables with a relation of one to many

For example take example of student and performance tables. Here a student and performance tables have one to many relationship

Student:

Performance:

Now i have to write a stored procedure which takes input as multiple student id, student name and section details as datatable and tells whether all the records passed in datatable have the same values for percentage, subject id, other activities in performance table or not .

Any suggestions are helpful

答:
This query returns no rows if all the students queried have got identical data:

```<code>WITH StudentCount AS (
  SELECT COUNT(*) AS Cnt
  FROM Students
),
RowDataCounts AS (
  SELECT
    p.Percentage,
    p.SubjectId,
    p.OtherActivities,
    Cnt = COUNT(*)
  FROM Performance p
    INNER JOIN Student s
       ON p.StudentID = s.StudentID
      AND p.Name = s.Name
      AND p.Section = s.Section
  GROUP BY
    p.Percentage,
    p.SubjectId,
    p.OtherActivities
)
SELECT r.*
FROM RowDataCounts r
  LEFT JOIN StudentCounts s ON r.Cnt = s.Cnt
WHERE s.Cnt IS NULL
</code>```

If not all the data are identical across all the students, the query will return rows showing the actual pieces of data that aren't the same, as well as how many students have that information.

If you need to use the entire query in a condition like IF EXISTS (…), just transform the CTEs to conventional subselects, i.e. like this:

```<code>SELECT r.*
FROM ( … /* the RowDataCounts subquery here */ ) r
  INNER JOIN ( … /* the StudentCount subquery here */ ) s ON r.Cnt = s.Cnt
WHERE s.Cnt IS NULL
</code>```

UPDATE

Here's a simplified version of the same solution:

```<code>SELECT
  p.Percentage,
  p.SubjectId,
  p.OtherActivities,
  Cnt = COUNT(*)
FROM Performance p
  INNER JOIN Student s
     ON p.StudentID = s.StudentID
    AND p.Name = s.Name
    AND p.Section = s.Section
GROUP BY
  p.Percentage,
  p.SubjectId,
  p.OtherActivities
HAVING COUNT(*) <> (SELECT COUNT(*) FROM Students)
</code>```

Body:
This query returns no rows if all the students queried have got identical data:

WITH StudentCount AS (
  SELECT COUNT(*) AS Cnt
  FROM Students
),
RowDataCounts AS (
  SELECT
    p.Percentage,
    p.SubjectId,
    p.OtherActivities,
    Cnt = COUNT(*)
  FROM Performance p
    INNER JOIN Student s
       ON p.StudentID = s.StudentID
      AND p.Name = s.Name
      AND p.Section = s.Section
  GROUP BY
    p.Percentage,
    p.SubjectId,
    p.OtherActivities
)
SELECT r.*
FROM RowDataCounts r
  LEFT JOIN StudentCounts s ON r.Cnt = s.Cnt
WHERE s.Cnt IS NULL

If not all the data are identical across all the students, the query will return rows showing the actual pieces of data that aren't the same, as well as how many students have that information.

If you need to use the entire query in a condition like IF EXISTS (…), just transform the CTEs to conventional subselects, i.e. like this:

SELECT r.*
FROM ( … /* the RowDataCounts subquery here */ ) r
  INNER JOIN ( … /* the StudentCount subquery here */ ) s ON r.Cnt = s.Cnt
WHERE s.Cnt IS NULL

UPDATE

Here's a simplified version of the same solution:

SELECT
  p.Percentage,
  p.SubjectId,
  p.OtherActivities,
  Cnt = COUNT(*)
FROM Performance p
  INNER JOIN Student s
     ON p.StudentID = s.StudentID
    AND p.Name = s.Name
    AND p.Section = s.Section
GROUP BY
  p.Percentage,
  p.SubjectId,
  p.OtherActivities
HAVING COUNT(*) <> (SELECT COUNT(*) FROM Students)


问:
Python: fetching live chat but too slow
I had to fetch live chat on Youtube and chose to use pytchat instead of Youtube API. There's no problem to fetch the chat, but it was a bit slow.

```<code>from pytchat import LiveChat
from datetime import datetime

chat = LiveChat(video_id = "36YnV9STBqc")
k=[]

while chat.is_alive():
    now2 = datetime.now()
    current_time2 = now2.strftime("%H:%M:%S")
    print("Current Time =", current_time2,"==========")  #A
    try:
        data = chat.get()
        now3 = datetime.now()
        current_time3 = now3.strftime("%H:%M:%S")
        print("Current Time =", current_time3,"~~~~~~~~~~~~~")  #B
        for c in data.items:
            comment=f"[{c.datetime}-{c.message}]"
            k.append(comment)   #I need to use k later
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            print(comment,"Current Time =", current_time,"++++++++++++++++")
            data.tick()
    except KeyboardInterrupt:
        chat.terminate()
        break
</code>```

Below shows the output of a video with 17,649 watching: (B to A took 5 secs)

```<code>Current Time = 18:49:33 ==========   #A
Current Time = 18:49:33 ~~~~~~~~~~~~~  #B
[2020-05-30 18:49:29-hi] Current Time = 18:49:33 ++++++++++++++++  #4 seconds late
[2020-05-30 18:49:32-how are you] Current Time = 18:49:36 ++++++++++++++++
Current Time = 18:49:38 ==========  #A
Current Time = 18:49:38 ~~~~~~~~~~~~~  #B
[2020-05-30 18:49:32-so good] Current Time = 18:49:38 ++++++++++++++++   #6 seconds late
</code>```

Below shows the output of a video with 702 watching: (B to A took at least 10 secs)

```<code>Current Time = 18:49:09 ==========   #A
Current Time = 18:49:10 ~~~~~~~~~~~~~  #B
[2020-05-30 18:49:06-hellp] Current Time = 18:49:10 ++++++++++++++++
[2020-05-30 18:49:07-love the music] Current Time = 18:49:15 ++++++++++++++++
Current Time = 18:49:20 ==========   #A
Current Time = 18:49:20 ~~~~~~~~~~~~~   #B
[2020-05-30 18:49:15-???] Current Time = 18:49:20 ++++++++++++++++
</code>```

I assume that different watching amounts will effect the time? It's also 4 to 6 secs late to fetch every chat, is it possible to solve it? Or it's just how Pytchat works?

答:
This is a specification.

Pytchat gets the chat in exactly the same way as the browser.
If your browser displays the time of the chat and the current time down to the second, you'll get the same results.

The response of the YouTube server is presumably affected by the number of people watching the chat and the number of people posting the chat at any given time.

It needs to be verified, but as you pointed out, I'm guessing that if a lot of chat posts are made, it's taking longer for the YouTube server to process them and return the chats that are retrieved.

(If you comment out the data.tick(), you might get a little better results.)

Title: Python: fetching live chat but too slow

Body:
I had to fetch live chat on Youtube and chose to use pytchat instead of Youtube API. There's no problem to fetch the chat, but it was a bit slow.

from pytchat import LiveChat
from datetime import datetime

chat = LiveChat(video_id = "36YnV9STBqc")
k=[]

while chat.is_alive():
    now2 = datetime.now()
    current_time2 = now2.strftime("%H:%M:%S")
    print("Current Time =", current_time2,"==========")  #A
    try:
        data = chat.get()
        now3 = datetime.now()
        current_time3 = now3.strftime("%H:%M:%S")
        print("Current Time =", current_time3,"~~~~~~~~~~~~~")  #B
        for c in data.items:
            comment=f"[{c.datetime}-{c.message}]"
            k.append(comment)   #I need to use k later
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            print(comment,"Current Time =", current_time,"++++++++++++++++")
            data.tick()
    except KeyboardInterrupt:
        chat.terminate()
        break

Below shows the output of a video with 17,649 watching: (B to A took 5 secs)

Current Time = 18:49:33 ==========   #A
Current Time = 18:49:33 ~~~~~~~~~~~~~  #B
[2020-05-30 18:49:29-hi] Current Time = 18:49:33 ++++++++++++++++  #4 seconds late
[2020-05-30 18:49:32-how are you] Current Time = 18:49:36 ++++++++++++++++
Current Time = 18:49:38 ==========  #A
Current Time = 18:49:38 ~~~~~~~~~~~~~  #B
[2020-05-30 18:49:32-so good] Current Time = 18:49:38 ++++++++++++++++   #6 seconds late

Below shows the output of a video with 702 watching: (B to A took at least 10 secs)

Current Time = 18:49:09 ==========   #A
Current Time = 18:49:10 ~~~~~~~~~~~~~  #B
[2020-05-30 18:49:06-hellp] Current Time = 18:49:10 ++++++++++++++++
[2020-05-30 18:49:07-love the music] Current Time = 18:49:15 ++++++++++++++++
Current Time = 18:49:20 ==========   #A
Current Time = 18:49:20 ~~~~~~~~~~~~~   #B
[2020-05-30 18:49:15-???] Current Time = 18:49:20 ++++++++++++++++

I assume that different watching amounts will effect the time? It's also 4 to 6 secs late to fetch every chat, is it possible to solve it? Or it's just how Pytchat works?


问:
Rally API defect query returning inaccurate results
I'm using Rally API v2.0 to access a list of defects. The criteria is to get all Submitted, Open, or Fixed defects from a specific project. While I am able to get a pretty large list, I don't get every defect. For example I notice there are some defects that are marked as Fixed but also in an Accepted Schedule State. These defects are not returned. I see defects with every other schedule state (Idea, Defined, In-Progress, Released) but not Accepted.

Am I missing something or is this a potential issue?

const query = "(((State%20%3D%20%22Submitted%22)%20OR%20(State%20%3D%20%22Open%22))%20OR%20(State%20%3D%20%22Open%22))";
const _fetch = "Applications,CreationDate,Description,FormattedID,Iteration,LastUpdateDate,Name,ObjectID,Owner,PlanEstimate,Project,ScheduleState,Severity,State";
const start = 1;
const pagesize = 2000;
const project = "https://rally1.rallydev.com/slm/webservice/v2.0/project/<my_actual_project_id>";

// Set header
const headersMeta = {'ZSESSIONID': this.apiKey};
const options = {
    headers: headersMeta
};

// Build the url
const url = "https://rally1.rallydev.com/slm/webservice/v2.0/defect?query=" + query +
    "&fetch=" + _fetch +
    "&start=" + start +
    "&pagesize=" + pagesize +
    "&project=" + project;

fetch(url, options) // more code to handle the response. No issues here.
```

Again, I do receive a response with Open, Submitted, or Fixed defects from my project. I am not getting any in a Schedule State of Accepted.

答:
Well I goofed. My query searches for Open twice and never checked for Fixed. Problem solved.

Leaving the post as an example of running a Rally API call.

Fixed line:

const query = "(((State = %22Submitted%22) OR (State = %22Open%22)) OR (State = %22Fixed%22))";
```

Body:
I'm using Rally API v2.0 to access a list of defects. The criteria is to get all Submitted, Open, or Fixed defects from a specific project. While I am able to get a pretty large list, I don't get every defect. For example I notice there are some defects that are marked as Fixed but also in an Accepted Schedule State. These defects are not returned. I see defects with every other schedule state (Idea, Defined, In-Progress, Released) but not Accepted.

Am I missing something or is this a potential issue?

const query = "(((State%20%3D%20%22Submitted%22)%20OR%20(State%20%3D%20%22Open%22))%20OR%20(State%20%3D%20%22Open%22))";
const _fetch = "Applications,CreationDate,Description,FormattedID,Iteration,LastUpdateDate,Name,ObjectID,Owner,PlanEstimate,Project,ScheduleState,Severity,State";
const start = 1;
const pagesize = 2000;
const project = "https://rally1.rallydev.com/slm/webservice/v2.0/project/<my_actual_project_id>";

// Set header
const headersMeta = {'ZSESSIONID': this.apiKey};
const options = {
    headers: headersMeta
};

// Build the url
const url = "https://rally1.rallydev.com/slm/webservice/v2.0/defect?query=" + query +
    "&fetch=" + _fetch +
    "&start=" + start +
    "&pagesize=" + pagesize +
    "&project=" + project;

fetch(url, options) // more code to handle the response. No issues here.

Again, I do receive a response with Open, Submitted, or Fixed defects from my project. I am not getting any in a Schedule State of Accepted.


问:
Which of these is the proper usage of std::move
I'm trying to change my code to take a vector by value using std::move instead of passing it by reference because I've gathered that would be more efficient. I've seen different ways of doing this though, one having the constructor pass by value and using std::move in the constructor, and the other way being to initialize the class with an std::move and having the constructor take an rvalue (did I get that right?). Some example below:

method 1:

Constructor:

```<code>StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))
{
}
</code>```

in main:

```<code>vector<Wrapper<StatisticsMC>> gathererArray{ meanGatherer, absQuantileGatherer, relVaRGatherer, relESGatherer };
StatisticsCompiler gathererCombiner(gathererArray);
</code>```

method 2.

Constructor:

```<code>StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>>&& Inner_) :Inner(Inner_)
{
}
</code>```

main:

```<code>vector<Wrapper<StatisticsMC>> gathererArray{ meanGatherer, absQuantileGatherer, relVaRGatherer, relESGatherer };
StatisticsCompiler gathererCombiner(std::move(gathererArray));
</code>```

Is there a difference between what's going on here or is it the same thing, the first method "looks" nicer in main but the second method is the way I would intuitively understand it to work from learning about rvalues. If performance wise they're the exact same, then what's standard practice?

答:
```<code>StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))
</code>```

This constructor takes the argument by value. The parameter can either be copy constructed from an lvalue argument, or move constructed from an rvalue. This ability to choose between copying from lvalue and moving from rvalue, combined with the simplicity, is why this approach is recommended.

The member is always moved from that copied or moved argument.

```<code>StatisticsCompiler gathererCombiner(gathererArray);
</code>```

You passed an lvalue; therefore the parameter is copied. You could use the move constructor instead by passing an rvalue:

```<code>StatisticsCompiler gathererCombiner(std::move(gathererArray));
</code>```

Or you could even use a prvalue:

```<code> StatisticsCompiler gathererCombiner({
    meanGatherer,
    absQuantileGatherer,
    relVaRGatherer,
    relESGatherer,
 });
</code>```

```<code>StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>>&& Inner_) :Inner(Inner_)
</code>```

This constructor accepts only rvalue arguments. This is not as flexible as the first suggestion which also can accept lvalues.

This approach always copies the parameter into the member. You might want to move instead:

```<code>Inner(std::move(Inner_))
</code>```

Conclusion: When you want to store an object given as an argument, then passing by value (the first example) is good default choice. If you don't need the passed argument afterwards, then you can choose to move from it.

Body:
I'm trying to change my code to take a vector by value using std::move instead of passing it by reference because I've gathered that would be more efficient. I've seen different ways of doing this though, one having the constructor pass by value and using std::move in the constructor, and the other way being to initialize the class with an std::move and having the constructor take an rvalue (did I get that right?). Some example below:

method 1:

Constructor:

StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))
{
}

in main:

vector<Wrapper<StatisticsMC>> gathererArray{ meanGatherer, absQuantileGatherer, relVaRGatherer, relESGatherer };
StatisticsCompiler gathererCombiner(gathererArray);

method 2.

Constructor:

StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>>&& Inner_) :Inner(Inner_)
{
}

main:

vector<Wrapper<StatisticsMC>> gathererArray{ meanGatherer, absQuantileGatherer, relVaRGatherer, relESGatherer };
StatisticsCompiler gathererCombiner(std::move(gathererArray));

Is there a difference between what's going on here or is it the same thing, the first method "looks" nicer in main but the second method is the way I would intuitively understand it to work from learning about rvalues. If performance wise they're the exact same, then what's standard practice?

Body:
StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))

This constructor takes the argument by value. The parameter can either be copy constructed from an lvalue argument, or move constructed from an rvalue. This ability to choose between copying from lvalue and moving from rvalue, combined with the simplicity, is why this approach is recommended.

The member is always moved from that copied or moved argument.

StatisticsCompiler gathererCombiner(gathererArray);

You passed an lvalue; therefore the parameter is copied. You could use the move constructor instead by passing an rvalue:

StatisticsCompiler gathererCombiner(std::move(gathererArray));

Or you could even use a prvalue:

 StatisticsCompiler gathererCombiner({
    meanGatherer,
    absQuantileGatherer,
    relVaRGatherer,
    relESGatherer,
 });

StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>>&& Inner_) :Inner(Inner_)

This constructor accepts only rvalue arguments. This is not as flexible as the first suggestion which also can accept lvalues.

This approach always copies the parameter into the member. You might want to move instead:

Inner(std::move(Inner_))

Conclusion: When you want to store an object given as an argument, then passing by value (the first example) is good default choice. If you don't need the passed argument afterwards, then you can choose to move from it.


问:
beautiful soup find function to scrape number off google
Ive just finished watching a tutorial on beautiful soup and thought I'd use it to try and scrape some data from google.

I've just googled coronavirus UK and wanted to scrape the current confirmed cases number.

On the upper right hand side of the web page is a box which shows the number of confirmed cases in the UK. Upon inspecting the element I found it to be located in this block:

```<code><td jsname="VBiLTe" class="dZdtsb QmWbpe ZDeom" data-absolute-value="276332" data-is-data-cell="true"
data-per-million-value="4258.258906030955" data-vfs="276332"><div class="amyZLb">Confirmed</div><div
class="m7B03"><div jsname="fUyIqc"><span>276K</span></div><div jsname="KBqmYc" style="display:none">
<span>4,258</span></div></div><div class="h5Hgwe"><div jsname="fUyIqc">+<span>1,570</span></div></div>
</td>
</code>```

The data-vfs key in the above code block holds the value I want to scrape. I thought this code would work to scrape the value.

```<code>from bs4 import BeautifulSoup
import requests

source = requests.get("https://www.google.com/search?q=coronavrius+uk&rlz=1C1CHBF_en-GBGB813GB813&oq=cor&aqs=chrome.0.69i59l2j0j69i57j35i39j69i64j69i60l2.1384j0j4&sourceid=chrome&ie=UTF-8").text
soup = BeautifulSoup(source,'lxml')

test=soup.find("td",class_="dZdtsb QmWbpe ZDeom")
print(test["data-vfs"])
</code>```

However, test is returned as none, (which gives an error upon running the code) implying nothing was found? I've been trying to figure out why for ages but nothing comes to mind. How do I modify the arguments in find to scrape the number?

答:
It is possible that the "jsname" indicates that this block of the web page is loaded dynamically by javascript after the main page loads. BeautifulSoup as you're using it will download the source, but not execute any of the javascript on a page before parsing it.

You might want to look at "Selenium" which is a headless browser, or learn BeautifulSoup with static pages that are from a simpler source. For example, Google is getting that data from somewhere, find the source and scrape that page.

Good Luck!

Body:
Ive just finished watching a tutorial on beautiful soup and thought I'd use it to try and scrape some data from google.

I've just googled coronavirus UK and wanted to scrape the current confirmed cases number.

On the upper right hand side of the web page is a box which shows the number of confirmed cases in the UK. Upon inspecting the element I found it to be located in this block:

Confirmed

276K

4,258

+1,570

The data-vfs key in the above code block holds the value I want to scrape. I thought this code would work to scrape the value.

from bs4 import BeautifulSoup
import requests

source = requests.get("https://www.google.com/search?q=coronavrius+uk&rlz=1C1CHBF_en-GBGB813GB813&oq=cor&aqs=chrome.0.69i59l2j0j69i57j35i39j69i64j69i60l2.1384j0j4&sourceid=chrome&ie=UTF-8").text
soup = BeautifulSoup(source,'lxml')

test=soup.find("td",class_="dZdtsb QmWbpe ZDeom")
print(test["data-vfs"])

However, test is returned as none, (which gives an error upon running the code) implying nothing was found? I've been trying to figure out why for ages but nothing comes to mind. How do I modify the arguments in find to scrape the number?


问:
Python Pandas handling of 308 request
When trying to read England's Covid_19 data into pandas, I've tried to use the URL provided by PHE https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv however, this file needs a http 308 redirect. I have tried the elegant solution:

```<code>import pandas as pd
tabel = pd.read_csv('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv')
</code>```

which trows the error HTTPError: HTTP Error 308: Permanent Redirect

However, the URL works as

```<code>import pandas as pd
import requests
import io
datastr = requests.get('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv',allow_redirects=True).text
data_file = io.StringIO(datastr)
table = pd.read_csv(data_file)
</code>```

gives the desired result.

I would like something similar to the first solution, is this a problem of pandas or am I doing something wrong?

答:
Looking at the Pandas source, it uses urllib.request.urlopen() and the docs suggest it should follow redirects where it makes sense.

However, 308 isn't a defined redirect code according to https://www.rfc-editor.org/rfc/rfc7231, so urllib will throw an exception as it doesn't know what to do. The requests library is a bit more forgiving.

The response says "permanent redirect", but looking at the dodgy hosting, I doubt that's really what is meant.

I think the publisher has messed up, so I wouldn't spend much time with other than the workaround you have.

Note that requests does let you get at the raw stream which you can pass to pd.read_csv():

```<code>r = requests.get('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv', stream=True)
pd.read_csv(r.raw)
</code>```

Title: Python Pandas handling of 308 request

Body:
When trying to read England's Covid_19 data into pandas, I've tried to use the URL provided by PHE https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv however, this file needs a http 308 redirect. I have tried the elegant solution:

import pandas as pd
tabel = pd.read_csv('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv')

which trows the error HTTPError: HTTP Error 308: Permanent Redirect

However, the URL works as

import pandas as pd
import requests
import io
datastr = requests.get('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv',allow_redirects=True).text
data_file = io.StringIO(datastr)
table = pd.read_csv(data_file)

gives the desired result.

I would like something similar to the first solution, is this a problem of pandas or am I doing something wrong?

Body:
Looking at the Pandas source, it uses urllib.request.urlopen() and the docs suggest it should follow redirects where it makes sense.

However, 308 isn't a defined redirect code according to https://www.rfc-editor.org/rfc/rfc7231, so urllib will throw an exception as it doesn't know what to do. The requests library is a bit more forgiving.

The response says "permanent redirect", but looking at the dodgy hosting, I doubt that's really what is meant.

I think the publisher has messed up, so I wouldn't spend much time with other than the workaround you have.

Note that requests does let you get at the raw stream which you can pass to pd.read_csv():

r = requests.get('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv', stream=True)
pd.read_csv(r.raw)


答:
You simply need to save the callback in a state, something like:

```<code>...

const [checklist, setChecklist] = React.useState([]);
useEffect(() => {
axios.get("http://100.103.16.113:8081/api/checklists", {})
  .then
    (function (response) {
      setChecklist(response?.data);
    console.log(response.data);
  }).catch(error => {
    console.log(error);
  })
}, []);
...
</code>```

To avoid null pointer exceptions, I suggest you use optional chaining and block rendering until the promise has been resolved.

Title: How to get the return from Axios.get and Render components dynamically on a Functional Component

Body:
I have a Functional Component and I am trying to get data from an axios.get() and render some components dynamically based on the response of the request.

If I console.log the response is Ok, but my problem is how to use the return from axios.get() to create components on the screen.

I've tried with a simple array and using it I can create the components. What I want is to create the components on screen the same way I've done with the array.

I've read a lot of post before posting my own. I would really appreciate some help or guidance.

import React, { createElement, useState, useEffect } from 'react';
import { Text, StyleSheet, View, TouchableOpacity, Image } from 'react-native';
import axios from 'axios';

const HomeScreen = ({ navigation }) => {

  axios.get("http://100.103.16.113:8081/api/checklists", {
  }).then
    (function (response) {
      console.log(response.data);
    }).catch(error => {
      console.log(error);
    })
  const checklists = [{
    "id": 1,
    "checklisT_DESCRIPTION": "CHECKLIST 1"
  },
  {
    "id": 2,
    "checklisT_DESCRIPTION": "CHECKLIST 2"
  },
  {
    "id": 3,
    "checklisT_DESCRIPTION": "CHECKLIST 3"
  }
  ]
  return (
    <View >
      <Text style={styles.text}> Select an Audit</Text>

      <View style={styles.maincontainer}>
        <View style={styles.container}>

          {}
          {checklists.map(r => (

            <TouchableOpacity onPress={() => navigation.navigate('AuditS')} style={styles.button}
            >
              <Image source={require('../assets/icons8-audit-80.png')} style={styles.Image}></Image>
              <Text style={styles.ButtonText}>{r.checklisT_DESCRIPTION}</Text>

            </TouchableOpacity >
          ))}

        </View>
      </View>
      <View style={styles.bottomcontainer}>
        <TouchableOpacity onPress={() => navigation.navigate('Login')}
        >
          <Text style={styles.logout}>LOGOUT</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  text: {
    fontSize: 50,
    fontFamily: 'Comfortaa-Regular',
    alignItems: "center",
    textAlignVertical: "center",
    textAlign: "center",
    justifyContent: "center",
  },
  container: {
    marginTop: 50,
    flexDirection: "row",
    marginLeft: 50,
    width: '100%'
  },
  maincontainer: {
    flexDirection: "column",
    width: '80%',
    alignContent: "center",
    justifyContent: "center",
  },
  bottomcontainer: {
    marginTop: '70%',
    width: '100%',
    alignItems: "center",
    justifyContent: "flex-end",
    alignContent: "flex-end",
  },
  logout: {
    marginTop: 50,
    margin: 15,
    height: 60,
    width: 440,
    borderColor: '#000000',
    backgroundColor: '#000000',
    borderWidth: 2,
    borderRadius: 10,
    fontSize: 18,
    textAlign: "center",
    textAlignVertical: "center",
    color: "#FFFFFF",
    fontFamily: 'Comfortaa-Bold'
  },
  button: {
    backgroundColor: '#0f99f5',
    fontSize: 16,
    color: '#FFF',
    width: 150,
    height: 150,
    borderRadius: 10,
    textAlignVertical: "bottom",
    textAlign: "center",
    marginVertical: 20,
    marginHorizontal: 10,
    fontFamily: 'Comfortaa-Bold'
  },
  ButtonText: {
    textAlignVertical: "bottom",
    textAlign: "center",
    fontSize: 16,
    color: '#FFF',
    marginHorizontal: 10,
    fontFamily: 'Comfortaa-Bold'
  },
  Image: {
    width: "50%",
    height: "50%",
    alignContent: "center",
    alignSelf: "center",
    marginTop: 10,
    marginBottom: 10
  }
});

export default HomeScreen;

Body:
You simply need to save the callback in a state, something like:

...

const [checklist, setChecklist] = React.useState([]);
useEffect(() => {
axios.get("http://100.103.16.113:8081/api/checklists", {})
  .then
    (function (response) {
      setChecklist(response?.data);
    console.log(response.data);
  }).catch(error => {
    console.log(error);
  })
}, []);
...

To avoid null pointer exceptions, I suggest you use optional chaining and block rendering until the promise has been resolved.


问:
How to mock sqlalchemy execution output inside `with` context manager
I'm trying to write unit tests for my python script which uses sqlalchemy to connect to MySQL.

My function looks like this:

def check_if_table_exists(db):
    with db.connect() as cursor:
        table_exists = cursor.execute(f"SHOW TABLES LIKE '{PRIMARY_TABLE_NAME}';")
        if not table_exists.rowcount:
            cursor.execute(f"CREATE TABLE...
```

I can't find any resources on how to first mock out db.connect(), which in turn also needs to have its execute mocked so that I can test different table_exists scenarios. It's also possible that my code is simply not cohesive to proper unit testing and I need to call the function with a cursor object to begin with.

For reference, db is the output of sqlalchemy.create_engine.

TLDR I need help getting started on unit testing for cases where I get rows back for the SHOW statement and when I don't.

答:
To patch a context manager, you have to patch the return value of __enter__, which is called on entering a context manager. Here is an example for your code:

from unittest import mock
from sqlalchemy import create_engine
from my_project.db_connect import check_if_table_exists

@mock.patch('sqlalchemy.engine.Engine.connect')
def test_dbconnect(engine_mock):
    db = create_engine('sqlite:///:memory:')
    cursor_mock = engine_mock.return_value.__enter__.return_value
    cursor_mock.execute.return_value.rowcount = 0
    check_if_table_exists(db)
    cursor_mock.execute.assert_called_with("CREATE TABLE")
```

In this code engine_mock.return_value is a mocked instance of Engine, and to get the mock for cursor, you need to add __enter__.return_value as described.

Having this, you can now mock the return value of execute - in this case you are only interested in the rowcount attribute which is checked in the code. Note that this will change the return value for all calls of execute - if you need different values for subsequent calls, you can use side_effect instead.

Body:
I'm trying to write unit tests for my python script which uses sqlalchemy to connect to MySQL.

My function looks like this:

def check_if_table_exists(db):
    with db.connect() as cursor:
        table_exists = cursor.execute(f"SHOW TABLES LIKE '{PRIMARY_TABLE_NAME}';")
        if not table_exists.rowcount:
            cursor.execute(f"CREATE TABLE...

I can't find any resources on how to first mock out db.connect(), which in turn also needs to have its execute mocked so that I can test different table_exists scenarios. It's also possible that my code is simply not cohesive to proper unit testing and I need to call the function with a cursor object to begin with.

For reference, db is the output of sqlalchemy.create_engine.

TLDR I need help getting started on unit testing for cases where I get rows back for the SHOW statement and when I don't.

Body:
To patch a context manager, you have to patch the return value of __enter__, which is called on entering a context manager. Here is an example for your code:

from unittest import mock
from sqlalchemy import create_engine
from my_project.db_connect import check_if_table_exists

@mock.patch('sqlalchemy.engine.Engine.connect')
def test_dbconnect(engine_mock):
    db = create_engine('sqlite:///:memory:')
    cursor_mock = engine_mock.return_value.__enter__.return_value
    cursor_mock.execute.return_value.rowcount = 0
    check_if_table_exists(db)
    cursor_mock.execute.assert_called_with("CREATE TABLE")

In this code engine_mock.return_value is a mocked instance of Engine, and to get the mock for cursor, you need to add __enter__.return_value as described.

Having this, you can now mock the return value of execute - in this case you are only interested in the rowcount attribute which is checked in the code. Note that this will change the return value for all calls of execute - if you need different values for subsequent calls, you can use side_effect instead.


问:
Generics inside a delegate or datasource
I'm trying to find a solution to use generics inside a delegate or dataSource protocol.

For now I've declared the following protocol:

```<code>@objc protocol PageViewControllerDelegate {
    optional func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController:UIViewController)
}
</code>```

What I want is a generic protocol like this:

```<code>@objc protocol PageViewControllerDelegate {
    typealias T
    optional func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController:T)
}
</code>```

This results in the following problems:

As I've declared a typealias, I can't use @objc anymore and the optional tag

When I declare the protocol as a property of my non generic class, I get the error "protocol can only be used as a generic constraint because it has self"

I've declared the property as followed:

```<code>class PageViewController: UIViewController, UIScrollViewDelegate {
    var delegate:PageViewControllerDelegate?
}
</code>```

Any help would be welcome.

Oh and, I'm just using this PageViewController case as an example to find out if this is possible. I'm not looking for another way to use the UIPageViewController for example.

答:
First I believe that you intended

```<code>protocol PageViewControllerDelegate {
    associatedtype T: UIViewController
    func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: T)
}
</code>```

although this is an old thread with an older version of Swift, so a typealias may have been utilized in protocols.

It appears that associated types are not supported in Objective-C, so there is no way around providing both an optional protocol implementation and an associated type; however, you can effectively create an optional implementation by leveraging  a protocol requirement that is given a default implementation through an extension as shown:

```<code>protocol PageViewControllerDelegate {
    associatedtype T: UIViewController
    func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: T)
}

extension PageViewControllerDelegate {
    // Does nothing on its own. Note that because this method is a requirement of the protocol, dynamic dispatch is used instead of static dispatch
    func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: T) {}
}

class MyClass: PageViewControllerDelegate {
    typealias T = UIPageViewController

    // No compile-time errors for an effectively optional method

    // Custom implementation
    //func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: UIPageViewController) {
    //
    //}
}
</code>```

You are not allowed to declare a variable to be the type of a protocol with associated types because the declaration is ambiguous. This is similar to how you are not allowed to simply declare a variable to the Array type in Swift: there is no single Array type because of its generic parameters. Associated types are the protocol equivalent of the generic arguments of generic types. See here for further explanation of some other protocol features.

You could try something along these lines

```<code>protocol PageViewControllerDelegate {
    associatedtype T: UIViewController
    func pageViewController(pageViewController: PageViewController<Self>, didScrollToViewController viewController: T)
}

extension PageViewControllerDelegate {
    func pageViewController(pageViewController: PageViewController<Self>, didScrollToViewController viewController: T) {}
}

class PageViewController<Delegate: PageViewControllerDelegate> : UIViewController, UIScrollViewDelegate {
    private var delegate: Delegate?
}

final class MyDelegate: PageViewControllerDelegate {
    typealias T = UIPageViewController

    func pageViewController(pageViewController: PageViewController<MyDelegate>, didScrollToViewController viewController: UIPageViewController) {
        // Do something
    }
}
</code>```

The only drawback is that the delegate must be marked final with the use of Self in the protocol method.

This is an old thread, and by now you may already be well aware of these capabilities and features. Hopefully this helped regardless.

Body:
I'm trying to find a solution to use generics inside a delegate or dataSource protocol.

For now I've declared the following protocol:

@objc protocol PageViewControllerDelegate {
    optional func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController:UIViewController)
}

What I want is a generic protocol like this:

@objc protocol PageViewControllerDelegate {
    typealias T
    optional func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController:T)
}

This results in the following problems:

As I've declared a typealias, I can't use @objc anymore and the optional tag

When I declare the protocol as a property of my non generic class, I get the error "protocol can only be used as a generic constraint because it has self"

I've declared the property as followed:

class PageViewController: UIViewController, UIScrollViewDelegate {
    var delegate:PageViewControllerDelegate?
}

Any help would be welcome.

Oh and, I'm just using this PageViewController case as an example to find out if this is possible. I'm not looking for another way to use the UIPageViewController for example.

Body:
First I believe that you intended

protocol PageViewControllerDelegate {
    associatedtype T: UIViewController
    func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: T)
}

although this is an old thread with an older version of Swift, so a typealias may have been utilized in protocols.

It appears that associated types are not supported in Objective-C, so there is no way around providing both an optional protocol implementation and an associated type; however, you can effectively create an optional implementation by leveraging  a protocol requirement that is given a default implementation through an extension as shown:

protocol PageViewControllerDelegate {
    associatedtype T: UIViewController
    func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: T)
}

extension PageViewControllerDelegate {
    // Does nothing on its own. Note that because this method is a requirement of the protocol, dynamic dispatch is used instead of static dispatch
    func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: T) {}
}

class MyClass: PageViewControllerDelegate {
    typealias T = UIPageViewController

    // No compile-time errors for an effectively optional method

    // Custom implementation
    //func pageViewController(pageViewController: PageViewController, didScrollToViewController viewController: UIPageViewController) {
    //
    //}
}

You are not allowed to declare a variable to be the type of a protocol with associated types because the declaration is ambiguous. This is similar to how you are not allowed to simply declare a variable to the Array type in Swift: there is no single Array type because of its generic parameters. Associated types are the protocol equivalent of the generic arguments of generic types. See here for further explanation of some other protocol features.

You could try something along these lines

protocol PageViewControllerDelegate {
    associatedtype T: UIViewController
    func pageViewController(pageViewController: PageViewController<Self>, didScrollToViewController viewController: T)
}

extension PageViewControllerDelegate {
    func pageViewController(pageViewController: PageViewController<Self>, didScrollToViewController viewController: T) {}
}

class PageViewController<Delegate: PageViewControllerDelegate> : UIViewController, UIScrollViewDelegate {
    private var delegate: Delegate?
}

final class MyDelegate: PageViewControllerDelegate {
    typealias T = UIPageViewController

    func pageViewController(pageViewController: PageViewController<MyDelegate>, didScrollToViewController viewController: UIPageViewController) {
        // Do something
    }
}

The only drawback is that the delegate must be marked final with the use of Self in the protocol method.

This is an old thread, and by now you may already be well aware of these capabilities and features. Hopefully this helped regardless.