问:
to display name,department name,marks of top performer(s) in Software Engineering,ordered by department name in ascending order
Write a query to display the name, department name and marks of the top performer(s)  in Software Engineering , ordered by department name in ascending order.

I have used below query but didn't getting desired result showing me two students from different department with same marks in software engineering

```<code>select distinct a.student_name,b.department_name,c.value from student a
inner join department b on a.department_id=b.department_id
inner join mark c on c.student_id=a.student_id and c.value in
(select max(a.value) from mark a,subject d where a.subject_id=d.subject_id
and d.subject_name='Software Engineering')
order by b.department_name;
</code>```

please refer the schema

答:
This part requires modification:

```<code> and c.value in (
   select max(a.value)
     from mark a, subject d
     where a.subject_id = d.subject_id and d.subject_name='Software Engineering')
</code>```

You need to take only Software Engineer rows from mark table, so please write:

```<code> and (c.subject_id, c.value)
     in (select subject_id, max(a.value)
           from mark a
           join subject d using (subject_id)
           where d.subject_name = 'Software Engineering'
           group by subject_id)
</code>```

demo

You can do it also with analitycal funcions (row_number, max), but I wanted to stay close to yours solution, which you know.

Body:
Write a query to display the name, department name and marks of the top performer(s)  in Software Engineering , ordered by department name in ascending order.

I have used below query but didn't getting desired result showing me two students from different department with same marks in software engineering

select distinct a.student_name,b.department_name,c.value from student a
inner join department b on a.department_id=b.department_id
inner join mark c on c.student_id=a.student_id and c.value in
(select max(a.value) from mark a,subject d where a.subject_id=d.subject_id
and d.subject_name='Software Engineering')
order by b.department_name;

please refer the schema

Body:
This part requires modification:

 and c.value in (
   select max(a.value)
     from mark a, subject d
     where a.subject_id = d.subject_id and d.subject_name='Software Engineering')

You need to take only Software Engineer rows from mark table, so please write:

 and (c.subject_id, c.value)
     in (select subject_id, max(a.value)
           from mark a
           join subject d using (subject_id)
           where d.subject_name = 'Software Engineering'
           group by subject_id)

demo

You can do it also with analitycal funcions (row_number, max), but I wanted to stay close to yours solution, which you know.


来源: stackexchange

问:
how to create a function that gives a prime number + bool value?
I'm struggling since yesterday with this, how to create a function that has a list of prime numbers and returns "prime number + true/false"
ex:

2 true
3 true
4 false
5 true

it's in Swift 5, first func called primecheck is working great, the problem is in the second one PrimeList

```<code>func primecheck (numbers:Int) -> Bool{

    var prime = true

    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }
    if numbers > 2{
        for i in 2...numbers - 1{
            if numbers % i == 0 {
                prime = false

            }

        }
    }
    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }

    if numbers < 0{
        prime = false
    }
    return prime
}

func PrimeList(maxP:Int) -> [(num1:Int, num2:Bool)] {

    var primes: [(num1:Int, num2:Bool)] = []

    for i in 1...maxP {

        if primecheck(numbers:i){
            print(i)
            primes[i - 1] = (i, true)

        } else {
            primes[i - 1] = (i, false)
        }
    }
  //  isPrime[0] = true
  //  isPrime[1] = true

    return primes
}

print(PrimeList(maxP:20))
</code>```

expected output:

```<code>print(primeList(maxP:20))
// 2 true
// 3 true

// 4 false
...
// 20 false
</code>```

but always appears this error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

答:
See bellow answer if it could make sense to you:

```<code>func isPrime(_ number: Int) -> String {

    return "\(number) \(number > 1 && !(2..<number).contains { number % $0 == 0 })"
}

func PrimeList(maxP:Int) {
    var array = [String]()
    for number in 0...maxP {
        array.append(isPrime(number))
    }
    print(array)
}
</code>```

Call method:

PrimeList(maxP: 20)

Ans:

["0 false", "1 false", "2 true", "3 true", "4 false", "5 true", "6
  false", "7 true", "8 false", "9 false", "10 false", "11 true", "12
  false", "13 true", "14 false", "15 false", "16 false", "17 true", "18
  false", "19 true", "20 false"]

ContentLicense: CC BY-SA 4.0

Body:
I'm struggling since yesterday with this, how to create a function that has a list of prime numbers and returns "prime number + true/false"
ex:

2 true
3 true
4 false
5 true

it's in Swift 5, first func called primecheck is working great, the problem is in the second one PrimeList

func primecheck (numbers:Int) -> Bool{

    var prime = true

    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }
    if numbers > 2{
        for i in 2...numbers - 1{
            if numbers % i == 0 {
                prime = false

            }

        }
    }
    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }

    if numbers < 0{
        prime = false
    }
    return prime
}

func PrimeList(maxP:Int) -> [(num1:Int, num2:Bool)] {

    var primes: [(num1:Int, num2:Bool)] = []

    for i in 1...maxP {

        if primecheck(numbers:i){
            print(i)
            primes[i - 1] = (i, true)

        } else {
            primes[i - 1] = (i, false)
        }
    }
  //  isPrime[0] = true
  //  isPrime[1] = true

    return primes
}

print(PrimeList(maxP:20))

expected output:

print(primeList(maxP:20))
// 2 true
// 3 true

// 4 false
...
// 20 false

but always appears this error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Body:
See bellow answer if it could make sense to you:

func isPrime(_ number: Int) -> String {

    return "\(number) \(number > 1 && !(2..<number).contains { number % $0 == 0 })"
}

func PrimeList(maxP:Int) {
    var array = [String]()
    for number in 0...maxP {
        array.append(isPrime(number))
    }
    print(array)
}

Call method:

PrimeList(maxP: 20)

Ans:

["0 false", "1 false", "2 true", "3 true", "4 false", "5 true", "6
  false", "7 true", "8 false", "9 false", "10 false", "11 true", "12
  false", "13 true", "14 false", "15 false", "16 false", "17 true", "18
  false", "19 true", "20 false"]


问:
Understanding path normalization in IIS
I'd like to disable directory traversal like example.com/page/../other-page (even to real pages) in my IIS website. I've tried Request Filtering and URL Rewrites with a custom response.

The Microsoft documentation on the denyUrlSequences part of Request Filtering actually uses .. as an example:

The following example Web.config file will deny access to three URL sequences. The first sequence prevents directory traversal, […]

<configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <denyUrlSequences>
               <add sequence=".." />
               [...]
```

…but it doesn't work; example.com/page/../other-page has already become example.com/other-page before the Deny rule ever runs. You can prove this by setting a Deny rule for page/sub and visiting example.com/page/./sub-page. The normalized path is blocked by the rule, but it wouldn't have matched in the original state.

I've tested this on IIS v7.5 and v10, and I imagine it exists in each intervening version, too.

What is doing the normalization? (Probably this library?)

When does it happen in the request lifecycle?

How do I successfully block the following sequences without opening up some security hole? .., ./, and //

Internet searches only want to tell me about a circa-2000 vulnerability in an old version of IIS, or how to enable MVC routes with dots in them.

Debug note: If you use curl to test this behavior, make sure to add the --path-as-is option, so it doesn't do the normalization in the client. Some browsers also appear to be doing client-side normalization.

Usage note: I'm nominally trying to shut down example.com/clubs-baby-seals/../about-us lest someone take the link's successful load as an endorsement of seal mistreatment.

答:
While I do not know the specific answer to (1) and (2), it turns out for (3) that the original pre-normalization URI path is available in the UNENCODED_URL server variable. This makes it possible to run URL Rewrite rules against it:

<rule name="Block directory traversal attempts" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
        <add input="{UNENCODED_URL}" pattern="\.\." />
        <add input="{UNENCODED_URL}" pattern="\./" />
        <add input="{UNENCODED_URL}" pattern="//" />
    </conditions>
    <action type="CustomResponse" statusCode="404"
            statusReason="Not Found" statusDescription="Page not found" />
</rule>
```

Title: Understanding path normalization in IIS

Body:
I'd like to disable directory traversal like example.com/page/../other-page (even to real pages) in my IIS website. I've tried Request Filtering and URL Rewrites with a custom response.

The Microsoft documentation on the denyUrlSequences part of Request Filtering actually uses .. as an example:

The following example Web.config file will deny access to three URL sequences. The first sequence prevents directory traversal, […]

<configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <denyUrlSequences>
               <add sequence=".." />
               [...]

…but it doesn't work; example.com/page/../other-page has already become example.com/other-page before the Deny rule ever runs. You can prove this by setting a Deny rule for page/sub and visiting example.com/page/./sub-page. The normalized path is blocked by the rule, but it wouldn't have matched in the original state.

I've tested this on IIS v7.5 and v10, and I imagine it exists in each intervening version, too.

What is doing the normalization? (Probably this library?)

When does it happen in the request lifecycle?

How do I successfully block the following sequences without opening up some security hole? .., ./, and //

Internet searches only want to tell me about a circa-2000 vulnerability in an old version of IIS, or how to enable MVC routes with dots in them.

Debug note: If you use curl to test this behavior, make sure to add the --path-as-is option, so it doesn't do the normalization in the client. Some browsers also appear to be doing client-side normalization.

Usage note: I'm nominally trying to shut down example.com/clubs-baby-seals/../about-us lest someone take the link's successful load as an endorsement of seal mistreatment.


问:
Converting a BMP/PNG/JPEG to an SVG file using Python
I'm currently trying to convert BMP files to SVG files using Python. I'm trying to find a Python library that will enable me to convert BMP/PNG/JPEG files to SVG files.

I've already tried using Potrace but the quality is awful. I need the end results to be fairly high-quality. I can't use online converters and must be able to do these conversions on my machine as I'm working with sensitive data.

Any suggestions would be greatly appreciated. Thank you!

Edit: I found out that I wasn't using the correct settings for Potrace in my testing. This is what yielded the "awful" result. Unfortunately, I've also learned that Potrace doesn't support color outputs. I've messed around with Inkscape and Vector Magic and I think they're my best bet at the moment.

答:
I would suggest using potrace for python.

Use this link: https://pypi.org/project/pypotrace/

Here is the documentation: https://pythonhosted.org/pypotrace/ref.html#

Like This:

```<code>from potrace import Bitmap

# Initialize data, for example convert a PIL image to a numpy array
# [...]

bitmap = Bitmap(data)
path = bitmap.trace()
</code>```

Body:
I would suggest using potrace for python.

Use this link: https://pypi.org/project/pypotrace/

Here is the documentation: https://pythonhosted.org/pypotrace/ref.html#

Like This:

from potrace import Bitmap

# Initialize data, for example convert a PIL image to a numpy array
# [...]

bitmap = Bitmap(data)
path = bitmap.trace()


问:
Protecting an specific WordPress page with .htaccess
I have a specific page on my WordPress installation (it's an actual Page in WordPress, just with Pretty URLs) and I want to password-protect it with an .htaccess file provided to me.

For example, the page is http://www.myawesomewebsite.com/members . I want only some users to access it, and their user and password are stored in an .htpasswd file.

The .htaccess file the client sent to me is

```<code>AuthUserFile /put the path to the password file here
AuthGroupFile /dev/null
AuthName RESTRICTED
AuthType Basic

<Limit GET POST>
require valid-user
</Limit>
</code>```

I need to use this parameters to protect this WordPress page. I'm going crazy and my searches are leading to nowhere. Any guesses?

答:
All you need to do is put the .htaccess file in the "members" directory and then point the first line to a password file. To create your password file just do:

```<code>htpasswd -c MyPasswordFile username
htpasswd MyPasswordFile anotherusername
</code>```

Here's a good reference:

http://httpd.apache.org/docs/current/howto/htaccess.html

ContentLicense: CC BY-SA 3.0

Body:
I have a specific page on my WordPress installation (it's an actual Page in WordPress, just with Pretty URLs) and I want to password-protect it with an .htaccess file provided to me.

For example, the page is http://www.myawesomewebsite.com/members . I want only some users to access it, and their user and password are stored in an .htpasswd file.

The .htaccess file the client sent to me is

AuthUserFile /put the path to the password file here
AuthGroupFile /dev/null
AuthName RESTRICTED
AuthType Basic

<Limit GET POST>
require valid-user
</Limit>

I need to use this parameters to protect this WordPress page. I'm going crazy and my searches are leading to nowhere. Any guesses?

Body:
All you need to do is put the .htaccess file in the "members" directory and then point the first line to a password file. To create your password file just do:

htpasswd -c MyPasswordFile username
htpasswd MyPasswordFile anotherusername

Here's a good reference:

http://httpd.apache.org/docs/current/howto/htaccess.html


问:
Different length of sound files with different sampling frequencies
Im currently struggling to understand what is happening. So, I created a sound using the audiowrite function in Matlab (the sound is created using two different sounds but I dont think it matters) first with a sampling frequency of 44100 Hz, and another one, the sound file is the same but the sampling frequency is 48000 Hz. Now I'm observing that the sound produced at 44100Hz is approx. 30sec longer than the other one (48000Hz sampling). It looks like phase shifting of some sort, but I'm not sure. Any help/explanation is appreciated. I also made a amplitude/time plot for better understanding:

(I set the x axis to 350sec to see where the signal ends).

EDIT: here is the code for how I create the sound file:

```<code>[y1,F1] = audioread(cave_file);        %cave and forest files are mp3 files loaded earlier both have samp.freq of 48000Hz
[y2,F2] = audioread(forest_file);
samp_freq=44100;
%samp_freq=48000;
a = max(size(y1),size(y2));
z = [[y1;zeros(abs([a(1),0]-size(y1)))],[y2;zeros(abs([a(1),0]- size(y2)))]]
audiowrite('test_sound.wav', z,samp_freq);
</code>```

答:
What is the storage format? More specifically, is the info about sampling rate and number of channels stored in file meta data? which is then used during playback.

If so, then there are 3 possibilities for this behavior:
1) The sampling rate meta data of the 44.1KHz file is incorrect, while the audio was sampled at the correct rate i.e. 44.1KHz. Because the 44.1KHz file is playing longer than 48KHz, which I'm assuming to be producing the correct sound, and playing for the correct duration, it can be concluded that the sampling rate meta data of 44.1KHz is much lesser than 44.1KHz.
Could you please check the meta data? or attach the files here so that I can try to take a look?
2) The sampling didn't happen at the correct rate, while the meta data has 44.1KHz as the sampling rate.
3) The number of channels is incorrectly stored.

In case the files are raw PCMs, then this probably the correct sampling rate and/or number of channels is not selected when playing the 44.1KHz file.

Hope this helps

Body:
Im currently struggling to understand what is happening. So, I created a sound using the audiowrite function in Matlab (the sound is created using two different sounds but I dont think it matters) first with a sampling frequency of 44100 Hz, and another one, the sound file is the same but the sampling frequency is 48000 Hz. Now I'm observing that the sound produced at 44100Hz is approx. 30sec longer than the other one (48000Hz sampling). It looks like phase shifting of some sort, but I'm not sure. Any help/explanation is appreciated. I also made a amplitude/time plot for better understanding:

(I set the x axis to 350sec to see where the signal ends).

EDIT: here is the code for how I create the sound file:

[y1,F1] = audioread(cave_file);        %cave and forest files are mp3 files loaded earlier both have samp.freq of 48000Hz
[y2,F2] = audioread(forest_file);
samp_freq=44100;
%samp_freq=48000;
a = max(size(y1),size(y2));
z = [[y1;zeros(abs([a(1),0]-size(y1)))],[y2;zeros(abs([a(1),0]- size(y2)))]]
audiowrite('test_sound.wav', z,samp_freq);


问:
NotifyDataSetChanged isn't updating arrayList when called the second time
Why is my question getting negative marks? i do not understand. Please help.

I have 5 lists displaying in the adapter one after another. I have to delete 2 rows when user clicks on a button in the activity. (Remove two options from the list every time the button is clicked) Each list gets the button click only once.
On click of button, NotifyDataSetChanged method does not update the list in the adapter.

For now it is happening for list 1, when 2nd list comes in, the button is clicked, 2 items from arraylist are deleted but notifyDataSetChanged does not update the list in the adapter.

In Activity :
row_number = count that i get from implementing the interface mentioned in adapter

```<code>  private void removeTwoFunctionality() {

    button_removeTwo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (row_number == 1) {
                TextArray1.remove(0);
                TextArray1.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 2) {
                TextArray2.remove(0);
                TextArray2.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 3) {
                TextArray3.remove(0);
                TextArray3.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 4) {
                TextArray4.remove(0);
                TextArray4.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 5) {
                TextArray5.remove(0);
                TextArray5.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
        }
    });
}
</code>```

In ADAPTER onBindViewHolder:
All the conditions are satisfied when next list arrives

```<code>// list 1
    if (!TextArray1.isEmpty()) {
        count = 1;
        holder.name.setText(TextArray1.get(position).getTitle());
    }
// list 2
    if (TextArray1.isEmpty() && TextArray2.size() > 0) {
        count = 2;
        holder.name.setText(TextArray2.get(position).getTitle());
    }
// list 3
    if (TextArray2.isEmpty() && TextArray3.size() > 0) {
        count = 3;
        holder.name.setText(TextArray3.get(position).getTitle());
    }
// list 4
    if (TextArray3.isEmpty() && TextArray4.size() > 0) {
        count = 4;
        holder.name.setText(TextArray4.get(position).getTitle());
    }
// list 5
    if (TextArray4.isEmpty() && TextArray5.size() > 0) {
        count = 5;
        holder.name.setText(TextArray5.get(position).getTitle());
    }
// interface to know the count in the activity
    if (mOnAnswerListener != null) {
        mOnAnswerListener.getRowNumber(count);
    }
</code>```

答:
You should put notifyDataSetChanged after deleting the items :</p>

```<code>  TextArray5.remove(0);
  TextArray5.remove(1);
  adapter.RemoveTwoButtonClicked();
  adapter.notifyDataSetChanged();
</code>```

Body:
Why is my question getting negative marks? i do not understand. Please help.

I have 5 lists displaying in the adapter one after another. I have to delete 2 rows when user clicks on a button in the activity. (Remove two options from the list every time the button is clicked) Each list gets the button click only once.
On click of button, NotifyDataSetChanged method does not update the list in the adapter.

For now it is happening for list 1, when 2nd list comes in, the button is clicked, 2 items from arraylist are deleted but notifyDataSetChanged does not update the list in the adapter.

In Activity :
row_number = count that i get from implementing the interface mentioned in adapter

  private void removeTwoFunctionality() {

    button_removeTwo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (row_number == 1) {
                TextArray1.remove(0);
                TextArray1.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 2) {
                TextArray2.remove(0);
                TextArray2.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 3) {
                TextArray3.remove(0);
                TextArray3.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 4) {
                TextArray4.remove(0);
                TextArray4.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 5) {
                TextArray5.remove(0);
                TextArray5.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
        }
    });
}

In ADAPTER onBindViewHolder:
All the conditions are satisfied when next list arrives

// list 1
    if (!TextArray1.isEmpty()) {
        count = 1;
        holder.name.setText(TextArray1.get(position).getTitle());
    }
// list 2
    if (TextArray1.isEmpty() && TextArray2.size() > 0) {
        count = 2;
        holder.name.setText(TextArray2.get(position).getTitle());
    }
// list 3
    if (TextArray2.isEmpty() && TextArray3.size() > 0) {
        count = 3;
        holder.name.setText(TextArray3.get(position).getTitle());
    }
// list 4
    if (TextArray3.isEmpty() && TextArray4.size() > 0) {
        count = 4;
        holder.name.setText(TextArray4.get(position).getTitle());
    }
// list 5
    if (TextArray4.isEmpty() && TextArray5.size() > 0) {
        count = 5;
        holder.name.setText(TextArray5.get(position).getTitle());
    }
// interface to know the count in the activity
    if (mOnAnswerListener != null) {
        mOnAnswerListener.getRowNumber(count);
    }

Body:
You should put notifyDataSetChanged after deleting the items :

  TextArray5.remove(0);
  TextArray5.remove(1);
  adapter.RemoveTwoButtonClicked();
  adapter.notifyDataSetChanged();


问:
Why there can be only one implementation of a typeclass for any given type parameter?
I'm reading the FP for Mortals book which has following line:

There can only be one implementation of a typeclass for any given type parameter, a property known as typeclass coherence. Typeclasses look superficially similar to algebraic interfaces from the previous chapter, but algebras do not have to be coherent.

I do not understand this paragraph fully. Suppose we have following typeclass:

trait Ordering[T] {
  def compare(x: T, y: T): Int
}
```

<p>I can create two implementations for the <code>Int</code> type like this:</p>

<pre class="lang-scala prettyprint-override"><code>val ord1: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) 1 else if (x == y) 0 else -1
}

val ord2: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) -1 else if (x == y) 0 else 1
}
</code>```

What do authors mean when they say that typeclass can have only one implementation? It doesn't apply for instances of the typeclass as we can have multiple ones for the same type. To what it is applied? Also why ADTs are not coherent in that sense?

答:
Instances of a type class are defined as implicits.

```<code>implicit val ord1: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) 1 else if (x == y) 0 else -1
}

implicit val ord2: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) -1 else if (x == y) 0 else 1
}
</code>```

If you ask implicitly[Ordering[Int]] you'll have

```<code>Error: ambiguous implicit values:
 both value ord1 in object App of type => App.Ordering[Int]
 and value ord2 in object App of type => App.Ordering[Int]
 match expected type App.Ordering[Int]
</code>```

Body:
I'm reading the FP for Mortals book which has following line:

There can only be one implementation of a typeclass for any given type parameter, a property known as typeclass coherence. Typeclasses look superficially similar to algebraic interfaces from the previous chapter, but algebras do not have to be coherent.

I do not understand this paragraph fully. Suppose we have following typeclass:

trait Ordering[T] {
  def compare(x: T, y: T): Int
}

I can create two implementations for the Int type like this:

val ord1: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) 1 else if (x == y) 0 else -1
}

val ord2: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) -1 else if (x == y) 0 else 1
}

What do authors mean when they say that typeclass can have only one implementation? It doesn't apply for instances of the typeclass as we can have multiple ones for the same type. To what it is applied? Also why ADTs are not coherent in that sense?

Body:
Instances of a type class are defined as implicits.

implicit val ord1: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) 1 else if (x == y) 0 else -1
}

implicit val ord2: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) -1 else if (x == y) 0 else 1
}

If you ask implicitly[Ordering[Int]] you'll have

Error: ambiguous implicit values:
 both value ord1 in object App of type => App.Ordering[Int]
 and value ord2 in object App of type => App.Ordering[Int]
 match expected type App.Ordering[Int]


问:
making an image within a card fill in the space
I am making a website using react and reactstrap, I have a card containing an image, the card is a square and the image is a rectangle, i want the image to fill in the card in the same fashion as an image set to fill in the background of a screen (cropping the edges to fit, thus avoiding the image getting stretched).

I have tried setting the width to auto while the height is at 100%, but the image only ends up smaller than it's normal size but overflows from the card, and not centered.

```<code><Row ClassName="posts">
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
</Row>
</code>```

I want the resulting image to be contained in the card, centered and filled in like a background image.

答:
You might benefit from adding Bootstrap from NPMJS to your project. You can then utilize the basic styles in the documentation.

All you would have to do is add className="img-fluid" to your img's

```<code><Row ClassName="posts">
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
</Row>
</code>```

Body:
I am making a website using react and reactstrap, I have a card containing an image, the card is a square and the image is a rectangle, i want the image to fill in the card in the same fashion as an image set to fill in the background of a screen (cropping the edges to fit, thus avoiding the image getting stretched).

I have tried setting the width to auto while the height is at 100%, but the image only ends up smaller than it's normal size but overflows from the card, and not centered.

<Row ClassName="posts">
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>

    </Card>
  </Col>
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>

    </Card>
  </Col>
</Row>

I want the resulting image to be contained in the card, centered and filled in like a background image.

Body:
You might benefit from adding Bootstrap from NPMJS to your project. You can then utilize the basic styles in the documentation.

All you would have to do is add className="img-fluid" to your img's

<Row ClassName="posts">
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
</Row>


问:
For loop iterates less times than I expected in Python
I would expect the following loop to iterate six times, instead it iterates three with python3. I don't understand this behavior.
I understand that the list changes as I delete elements but I don't get how that affects the for loop condition.
Why is the loop iterating less than six times?</p>

```<code>a = [1, 2, 3, 4, 5, 6]
for elem in a:
        del a[0]
        print(a)
</code>```

答:
You are deleting the first element in every iteration of the loop by del a[0], so the iterator is emptied in 3 steps, because it moves to the element after the one you removed on the next iteration.
You can check the element the iterator is currently on, and the list status in the code below

```<code>a = [1, 2, 3, 4, 5, 6]
for elem in a:
    print(elem)
    del a[0]
    print(a)
</code>```

The output is

```<code>1
[2, 3, 4, 5, 6]
3
[3, 4, 5, 6]
5
[4, 5, 6]
</code>```

You can think of it as a pointer pointing to the first element of the list, that pointer jumps 2 steps when you delete the first element on each iteration, and it can jump only 3 times for 6 elements.

Generally it is a bad idea to modify the same list you are iterating on.
But if you really want to, you can iterate over the copy of the list a[:] if you really want to delete items

```<code>a = [1, 2, 3, 4, 5, 6]
for elem in a[:]:
    del a[0]
    print(a)
</code>```

The output is

```<code>[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]
</code>```

Body:
I would expect the following loop to iterate six times, instead it iterates three with python3. I don't understand this behavior.
I understand that the list changes as I delete elements but I don't get how that affects the for loop condition.
Why is the loop iterating less than six times?

a = [1, 2, 3, 4, 5, 6]
for elem in a:
        del a[0]
        print(a)

Body:
You are deleting the first element in every iteration of the loop by del a[0], so the iterator is emptied in 3 steps, because it moves to the element after the one you removed on the next iteration.
You can check the element the iterator is currently on, and the list status in the code below

a = [1, 2, 3, 4, 5, 6]
for elem in a:
    print(elem)
    del a[0]
    print(a)

The output is

1
[2, 3, 4, 5, 6]
3
[3, 4, 5, 6]
5
[4, 5, 6]

You can think of it as a pointer pointing to the first element of the list, that pointer jumps 2 steps when you delete the first element on each iteration, and it can jump only 3 times for 6 elements.

Generally it is a bad idea to modify the same list you are iterating on.
But if you really want to, you can iterate over the copy of the list a[:] if you really want to delete items

a = [1, 2, 3, 4, 5, 6]
for elem in a[:]:
    del a[0]
    print(a)

The output is

[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]


问:
Tab Outside Tab Control In Access 2007
My Access 2007 form has a two buttons below a tab control (with a subform on each page).

With a tab-page or button focused, I can "tab" into the subform on that page (putting focus on the first control).  However, once a control in the subform has focus, I cannot "tab" out of the subform.  The focus iterates through the subform controls (not the entire form).

Is there a way to change this behavior?  When the last subform control has focus and the user pushes the tab key, I want the focus to be on the first button.

答:
On the last subform control add an [Event Procedure] to the KeyDown event for the control:

```<code>Private Sub TheSubformControl_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyTab And Shift = 0 Then Me.Parent.ButtonToFocus.SetFocus
End Sub
</code>```

Title: Tab Outside Tab Control In Access 2007

Body:
On the last subform control add an [Event Procedure] to the KeyDown event for the control:

Private Sub TheSubformControl_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyTab And Shift = 0 Then Me.Parent.ButtonToFocus.SetFocus
End Sub


问:
In Android Studio, app is running on emulator but not in physical device
I am using Android studio 3.4.1, In which my projects are not running in real device. but not having any problem in emulator.

After connecting the usb and i have run the app. then getting this error. after that device is not even listed in the available devices.

error got in logs:

```<code>Installation did not succeed.

The application could not be installed.

Installation failed due to: 'device '711KPMZ0603459' not found'

Retry
</code>```

Retry also not working.

I also tried in Android studio Beta 1 and Beta 3. same problem happening.

can any one help me in this?

FYKI:
1. USB debugging enabled.

Tried USB option for File Transfer, USB tethering, No data transfer.

Tried with different cable as well.

Problem identified only after updating 3.4.1 android studio. Also facing in 3.5 Beta 1 and Beta 3.

Same kind of problem already added in Issue Tracker. https://issuetracker.google.com/issues/122892907

答: Activate USB-Debugging in Developer Options and set your USB options from Charge phone to transmit Data.</p>

Body:
I am using Android studio 3.4.1, In which my projects are not running in real device. but not having any problem in emulator.

After connecting the usb and i have run the app. then getting this error. after that device is not even listed in the available devices.

error got in logs:

Installation did not succeed.

The application could not be installed.

Installation failed due to: 'device '711KPMZ0603459' not found'

Retry

Retry also not working.

I also tried in Android studio Beta 1 and Beta 3. same problem happening.

can any one help me in this?

FYKI:
1. USB debugging enabled.

Tried USB option for File Transfer, USB tethering, No data transfer.

Tried with different cable as well.

Problem identified only after updating 3.4.1 android studio. Also facing in 3.5 Beta 1 and Beta 3.

Same kind of problem already added in Issue Tracker. https://issuetracker.google.com/issues/122892907


问:
Unable to hide Legend in Chartjs with PrimeFaces7.0
I have a line chart that I created using Chartjs in PrimeFaces 7.0 that I would like to hide the legend.
Thanks for your help. My view and bean is below.

I tried to add the LineChartOptions in the bean but that does not seem to work. I am able to hide the legend if I add the option in an extender. I am using a generic extender function to format the y-axis labels that other charts are using. I dont want to write another extender function just for this chart duplicating the code to format the y-labels and adding the option to hide the legend.

Below is the bean with the LineChartOptions which does not seem to work.

```<code>public LineChartModel createPercentChart() {
        LineChartModel model = new LineChartModel();
        ChartData data = new ChartData();
        LineChartDataSet dataSet = new LineChartDataSet();
        List<Number> values = new ArrayList<>(); // in dollars
        List<String> labels = new ArrayList<>(); // months
        dataSet.setFill(true);
        dataSet.setLabel("return (%)");
        values.add(0.1);
        values.add(0.05);
        values.add(0.5);
        values.add(0.34);
        values.add(0.32);
        values.add(-0.05);
        values.add(-0.01);
        values.add(0.2);
        values.add(0.25);
        values.add(0.33);
        values.add(0.01);
        values.add(0.4);

        labels.add("Jan");
        labels.add("Feb");
        labels.add("Mar");
        labels.add("Apr");
        labels.add("May");
        labels.add("Jun");
        labels.add("Jul");
        labels.add("Aug");
        labels.add("Sep");
        labels.add("Oct");
        labels.add("Nov");
        labels.add("Dec");
        dataSet.setData(values);
        dataSet.setLineTension(0.1);
        dataSet.setPointRadius(0);
        dataSet.setPointHoverRadius(5);
        dataSet.setBorderColor("rgb(150, 200,220)");
        dataSet.setBackgroundColor("rgba(150, 200, 220, 0.2)");

        data.addChartDataSet(dataSet);
        data.setLabels(labels);

        LineChartOptions options = new LineChartOptions();
        Legend legend = new Legend();
        legend.setDisplay(false);
        options.setLegend(legend);
        model.setOptions(options);

        model.setData(data);
        model.setExtender("percentExtender");
        return model;
    }
</code>```

Here is the Extender code I am using in the view

```<code>function percentExtender() {
       var tickColor = "#666";
       var gridlineColor = "rgba(0,0,0,0.1)";

      this.cfg.config.options = {
          tooltips: {
             callbacks: {

                label: function (tooltipItem, data) {
                   return " " + (tooltipItem.yLabel*100).toFixed(1) + "%";
                }
             }
          },
          scales: {
             yAxes: [{
                display: true,
                scaleLabel: {
                   display: true,
                   labelString: 'Return',
                   fontColor: tickColor
                },
                ticks: {
                   // add $ to y axis label
                   callback: function (value, index, values) {
                       value = value * 100;
                      return value + " %";
                   },
                   fontColor: tickColor
                },
                gridLines: {
                   color: gridlineColor
                }
             }]
          }
       };

    };
</code>```

答:
You are overwriting the original JSON with your changes.  You need to store the original JSON values and then merge them back in after your changes like the following:</p>

```<code>function percentExtender() {
       var tickColor = "#666";
       var gridlineColor = "rgba(0,0,0,0.1)";

       //copy the config options into a variable
       var options = $.extend(true, {}, this.cfg.config);

      options = {
          tooltips: {
             callbacks: {

                label: function (tooltipItem, data) {
                   return " " + (tooltipItem.yLabel*100).toFixed(1) + "%";
                }
             }
          },
          scales: {
             yAxes: [{
                display: true,
                scaleLabel: {
                   display: true,
                   labelString: 'Return',
                   fontColor: tickColor
                },
                ticks: {
                   // add $ to y axis label
                   callback: function (value, index, values) {
                       value = value * 100;
                      return value + " %";
                   },
                   fontColor: tickColor
                },
                gridLines: {
                   color: gridlineColor
                }
             }]
          }
       };

       //merge all options into the main chart options
       $.extend(true, this.cfg.config, options);
    };
</code>```

Body:
I have a line chart that I created using Chartjs in PrimeFaces 7.0 that I would like to hide the legend.
Thanks for your help. My view and bean is below.

I tried to add the LineChartOptions in the bean but that does not seem to work. I am able to hide the legend if I add the option in an extender. I am using a generic extender function to format the y-axis labels that other charts are using. I dont want to write another extender function just for this chart duplicating the code to format the y-labels and adding the option to hide the legend.

Below is the bean with the LineChartOptions which does not seem to work.

public LineChartModel createPercentChart() {
        LineChartModel model = new LineChartModel();
        ChartData data = new ChartData();
        LineChartDataSet dataSet = new LineChartDataSet();
        List<Number> values = new ArrayList<>(); // in dollars
        List<String> labels = new ArrayList<>(); // months
        dataSet.setFill(true);
        dataSet.setLabel("return (%)");
        values.add(0.1);
        values.add(0.05);
        values.add(0.5);
        values.add(0.34);
        values.add(0.32);
        values.add(-0.05);
        values.add(-0.01);
        values.add(0.2);
        values.add(0.25);
        values.add(0.33);
        values.add(0.01);
        values.add(0.4);

        labels.add("Jan");
        labels.add("Feb");
        labels.add("Mar");
        labels.add("Apr");
        labels.add("May");
        labels.add("Jun");
        labels.add("Jul");
        labels.add("Aug");
        labels.add("Sep");
        labels.add("Oct");
        labels.add("Nov");
        labels.add("Dec");
        dataSet.setData(values);
        dataSet.setLineTension(0.1);
        dataSet.setPointRadius(0);
        dataSet.setPointHoverRadius(5);
        dataSet.setBorderColor("rgb(150, 200,220)");
        dataSet.setBackgroundColor("rgba(150, 200, 220, 0.2)");

        data.addChartDataSet(dataSet);
        data.setLabels(labels);

        LineChartOptions options = new LineChartOptions();
        Legend legend = new Legend();
        legend.setDisplay(false);
        options.setLegend(legend);
        model.setOptions(options);

        model.setData(data);
        model.setExtender("percentExtender");
        return model;
    }

Here is the Extender code I am using in the view

function percentExtender() {
       var tickColor = "#666";
       var gridlineColor = "rgba(0,0,0,0.1)";

      this.cfg.config.options = {
          tooltips: {
             callbacks: {

                label: function (tooltipItem, data) {
                   return " " + (tooltipItem.yLabel*100).toFixed(1) + "%";
                }
             }
          },
          scales: {
             yAxes: [{
                display: true,
                scaleLabel: {
                   display: true,
                   labelString: 'Return',
                   fontColor: tickColor
                },
                ticks: {
                   // add $ to y axis label
                   callback: function (value, index, values) {
                       value = value * 100;
                      return value + " %";
                   },
                   fontColor: tickColor
                },
                gridLines: {
                   color: gridlineColor
                }
             }]
          }
       };

    };

Body:
You are overwriting the original JSON with your changes.  You need to store the original JSON values and then merge them back in after your changes like the following:

function percentExtender() {
       var tickColor = "#666";
       var gridlineColor = "rgba(0,0,0,0.1)";

       //copy the config options into a variable
       var options = $.extend(true, {}, this.cfg.config);

      options = {
          tooltips: {
             callbacks: {

                label: function (tooltipItem, data) {
                   return " " + (tooltipItem.yLabel*100).toFixed(1) + "%";
                }
             }
          },
          scales: {
             yAxes: [{
                display: true,
                scaleLabel: {
                   display: true,
                   labelString: 'Return',
                   fontColor: tickColor
                },
                ticks: {
                   // add $ to y axis label
                   callback: function (value, index, values) {
                       value = value * 100;
                      return value + " %";
                   },
                   fontColor: tickColor
                },
                gridLines: {
                   color: gridlineColor
                }
             }]
          }
       };

       //merge all options into the main chart options
       $.extend(true, this.cfg.config, options);
    };


问:
R Loop To Make New Vectors
```<code>data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))
</code>```

That is a sample of my data. I want population-weighted counts of the score variable like so:

```<code>count(data, score1, wt = weight1)
count(data, score2, wt = weight2)
count(data, score3, wt = weight3)
count(data, score4, wt = weight4)
count(data, score5, wt = weight5)
</code>```

However I aim to make a loop of a type such that, I can do this for every combination of 'group' and 'type' for scores1-5 and store these in separate vectors such that

```<code>vec1 = weighted score variable for scores1-5 for group = 1 and type = 1
vec2 = weighted score variable for scores1-5 for group = 1 and type = 2
vec3 = weighted score variable for scores1-5 for group = 1 and type = 3
</code>```

and so on and so forth.

答:
We can use map to loop through each of the corresponding 'score', 'weight' and get the count

```<code>library(tidyverse)
out <- map(1:5, ~
       data %>%
         select(group, type, matches(as.character(.x))) %>%
         group_by(group, type) %>%
         count(!! rlang::sym(str_c("score", .x)),
         wt = !! rlang::sym(str_c("weight", .x))))
</code>```

The output would be a list of frequency count tibble.  If we want to create a single data, use map_df with .id

Title: R Loop To Make New Vectors

Body:
data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))

That is a sample of my data. I want population-weighted counts of the score variable like so:

count(data, score1, wt = weight1)
count(data, score2, wt = weight2)
count(data, score3, wt = weight3)
count(data, score4, wt = weight4)
count(data, score5, wt = weight5)

However I aim to make a loop of a type such that, I can do this for every combination of 'group' and 'type' for scores1-5 and store these in separate vectors such that

vec1 = weighted score variable for scores1-5 for group = 1 and type = 1
vec2 = weighted score variable for scores1-5 for group = 1 and type = 2
vec3 = weighted score variable for scores1-5 for group = 1 and type = 3

and so on and so forth.

Body:
We can use map to loop through each of the corresponding 'score', 'weight' and get the count

library(tidyverse)
out <- map(1:5, ~
       data %>%
         select(group, type, matches(as.character(.x))) %>%
         group_by(group, type) %>%
         count(!! rlang::sym(str_c("score", .x)),
         wt = !! rlang::sym(str_c("weight", .x))))

The output would be a list of frequency count tibble.  If we want to create a single data, use map_df with .id


问:
How to verify if a IP address is valid on Java?
I want to verify an IP address in java, how can I do that?
The IP Address needs to be in this format: xxx.xxx.xxx.xxx
Each octet range must be 0 ~ 255.

Since the IP is verified, the code must show a message telling that the IP is valid or not. If not, the user must type the IP again.

I've done the method to convert an IP string to an array of integers so far...

public static void verify() {
        Scanner input = new Scanner(System.in);
        System.out.println("IP: (xxx.xxx.xxx.xxx)");
        String ipAddress = input.nextLine();
        int[] arrayIpAddress = Arrays.stream(ipAddress.split("\\.")).mapToInt(Integer::parseInt).toArray();
}

```

答:
In your specific scenario, you can add a filter and check the resulting arrays length:

String ipAddress = input.nextLine();
boolean ipValid = Arrays
  .stream(ipAddress.split("\\."))
  .mapToInt(Integer::parseInt)
  .filter(x -> x >= 0 && x <= 255) // remove invalid numbers
  .toArray().length == 4; // if the resulting length is 4, the ip is valid
```

Note: your approach will fail if Integer.parseInt throws an exception (i.e. if the user enters some letters), and will consider an IP valid even if there is some extra dot (like 192.168.0.1.)

Body:
In your specific scenario, you can add a filter and check the resulting arrays length:

String ipAddress = input.nextLine();
boolean ipValid = Arrays
  .stream(ipAddress.split("\\."))
  .mapToInt(Integer::parseInt)
  .filter(x -> x >= 0 && x <= 255) // remove invalid numbers
  .toArray().length == 4; // if the resulting length is 4, the ip is valid

Note: your approach will fail if Integer.parseInt throws an exception (i.e. if the user enters some letters), and will consider an IP valid even if there is some extra dot (like 192.168.0.1.)


问:
Grid shows up for split second and then immediately disappears
I'm making a small project with wxpython and I'm having some trouble with wx.grid.Grid. The grid is nested in a sizer which is nested in another sizer (here's a photo). However, when it's like that, the grid shows up for a split second and disappears. It didn't disappear when it was just inside one sizer.

I've tried changing the sizer type and various properties of the sizer and the grid with no avail. I've also tried changing parts of code but realized that it has nothing to do with it since the grid doesn't even show inside wxGlade.

Here's a part of .py generated by wxGlade:

```<code>class frameRozvrh(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: frameRozvrh.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((640, 480))
        self.statusbar = self.CreateStatusBar(1)
        self.buttonPrev = wx.Button(self, wx.ID_ANY, "<<")
        self.dateWeek = wx.adv.DatePickerCtrl(self, wx.ID_ANY, style=wx.adv.DP_DEFAULT)
        self.buttonNext = wx.Button(self, wx.ID_ANY, ">>")
        self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1))

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: frameRozvrh.__set_properties
        self.SetTitle("Rozvrh hodin")
        self.statusbar.SetStatusWidths([-1])

        # statusbar fields
        statusbar_fields = [u"Aktuální týden"]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)
        self.dateWeek.Enable(False)
        self.gridRozvrh.CreateGrid(0, 0)
        self.gridRozvrh.EnableEditing(0)
        self.gridRozvrh.EnableDragColSize(0)
        self.gridRozvrh.EnableDragRowSize(0)
        self.gridRozvrh.EnableDragGridSize(0)
        self.gridRozvrh.SetFocus()
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: frameRozvrh.__do_layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_1 = wx.GridBagSizer(0, 0)
        sizer_1.Add(self.buttonPrev, (0, 0), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        sizer_1.Add(self.dateWeek, (0, 1), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        sizer_1.Add(self.buttonNext, (0, 2), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        sizer_1.AddGrowableCol(0)
        sizer_1.AddGrowableCol(1)
        sizer_1.AddGrowableCol(2)
        sizer.Add(sizer_1, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 10)
        sizer_2.Add(self.gridRozvrh, 0, wx.ALL | wx.EXPAND, 5)
        sizer.Add(sizer_2, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 10)
        self.SetSizer(sizer)
        self.Layout()
</code>```

I'd like the grid to stay visible, not disappear.

答:
There are two problems in your code

Problem 1 is in this line:

```<code>self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1))
</code>```

With this line your creating a grid with 1 pixel wide and 1 pixel height. Change it to:

```<code>self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(100, 100))
</code>```

or any other size.

Problem 2 is in this line:

```<code>self.gridRozvrh.CreateGrid(0, 0)
</code>```

With this line you are creating a grid with 0 rows and 0 columns. Change this to:

```<code>self.gridRozvrh.CreateGrid(10, 10)
</code>```

or any other numbers as needed.

Body:
I'm making a small project with wxpython and I'm having some trouble with wx.grid.Grid. The grid is nested in a sizer which is nested in another sizer (here's a photo). However, when it's like that, the grid shows up for a split second and disappears. It didn't disappear when it was just inside one sizer.

I've tried changing the sizer type and various properties of the sizer and the grid with no avail. I've also tried changing parts of code but realized that it has nothing to do with it since the grid doesn't even show inside wxGlade.

Here's a part of .py generated by wxGlade:

class frameRozvrh(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: frameRozvrh.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((640, 480))
        self.statusbar = self.CreateStatusBar(1)
        self.buttonPrev = wx.Button(self, wx.ID_ANY, "<<")
        self.dateWeek = wx.adv.DatePickerCtrl(self, wx.ID_ANY, style=wx.adv.DP_DEFAULT)
        self.buttonNext = wx.Button(self, wx.ID_ANY, ">>")
        self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1))

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: frameRozvrh.__set_properties
        self.SetTitle("Rozvrh hodin")
        self.statusbar.SetStatusWidths([-1])

        # statusbar fields
        statusbar_fields = [u"Aktuální týden"]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)
        self.dateWeek.Enable(False)
        self.gridRozvrh.CreateGrid(0, 0)
        self.gridRozvrh.EnableEditing(0)
        self.gridRozvrh.EnableDragColSize(0)
        self.gridRozvrh.EnableDragRowSize(0)
        self.gridRozvrh.EnableDragGridSize(0)
        self.gridRozvrh.SetFocus()
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: frameRozvrh.__do_layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_1 = wx.GridBagSizer(0, 0)
        sizer_1.Add(self.buttonPrev, (0, 0), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        sizer_1.Add(self.dateWeek, (0, 1), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        sizer_1.Add(self.buttonNext, (0, 2), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        sizer_1.AddGrowableCol(0)
        sizer_1.AddGrowableCol(1)
        sizer_1.AddGrowableCol(2)
        sizer.Add(sizer_1, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 10)
        sizer_2.Add(self.gridRozvrh, 0, wx.ALL | wx.EXPAND, 5)
        sizer.Add(sizer_2, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 10)
        self.SetSizer(sizer)
        self.Layout()

I'd like the grid to stay visible, not disappear.

Body:
There are two problems in your code

Problem 1 is in this line:

self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1))

With this line your creating a grid with 1 pixel wide and 1 pixel height. Change it to:

self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(100, 100))

or any other size.

Problem 2 is in this line:

self.gridRozvrh.CreateGrid(0, 0)

With this line you are creating a grid with 0 rows and 0 columns. Change this to:

self.gridRozvrh.CreateGrid(10, 10)

or any other numbers as needed.


问:
How to delete a record without immediate database effect
In a precedent question, I was looking for the BaseModel.new method to behave like the create method from ORM, but without writing changes in the database.

Does the same method exist, but acting like unlink? I would like to delete a record from my recordset in an onchange call. I don't want the record to be delete at once, but only when the user will press the Save button.

Thank you a lot in advance!

For more information about why I want this feature:

I am using the stock module of Odoo. In a Picking, I want to dynamically change the reserved products (tracked by unique serial number) which means add some new move_lines and delete some of the existing ones.

I cannot simply change the lot_id as some move_lines with this lot_id may be reserved in another Picking (or at least, I didn't find how to do this neatly).

By changing the lot_id or doing selected_move_id.move_line_ids.new({...}) in my onchange method, I can add the new ones. Now I would like to delete the existing ones that I don't need anymore. I would like to delete them the same way as if the user would have press the trash icon on the corresponding line.

答:
I tried something similar in Odoo 12 and it worked fine:

# I change the partner for testing different cases
@api.onchange('partner_id')
def onchage_p(self):
    """ remove moves have less then 5 units"""
    # create empty record set to hold valid records
    new_recs = self.env['stock.move']
    for move in self.move_ids_without_package:
        # keep only record that greater than 5
        if move.product_uom_qty > 5:
            new_recs += move

    # reassign it to the field.
    self.move_ids_without_package = new_recs
```

When I debugged the write call on stock.picking the delete cammand
was passed for all saved moves: [...,[2, move_id, False]]

The framework is able to detect that a record was removed from the original recordset and this is why the command was added.

So the basic Idea is create a new recordset that contains valid records assign it again to the one2many field.

Body:
I tried something similar in Odoo 12 and it worked fine:

# I change the partner for testing different cases
@api.onchange('partner_id')
def onchage_p(self):
    """ remove moves have less then 5 units"""
    # create empty record set to hold valid records
    new_recs = self.env['stock.move']
    for move in self.move_ids_without_package:
        # keep only record that greater than 5
        if move.product_uom_qty > 5:
            new_recs += move

    # reassign it to the field.
    self.move_ids_without_package = new_recs

When I debugged the write call on stock.picking the delete cammand
was passed for all saved moves: [...,[2, move_id, False]]

The framework is able to detect that a record was removed from the original recordset and this is why the command was added.

So the basic Idea is create a new recordset that contains valid records assign it again to the one2many field.


问:
Why does the order of route mapping matter when mixing MVC and webforms?
Curious why declaring a MapPageRoute before the default MVC route causes problems with UrlHelper.GenerateUrl.

I started with this in my Global.asax.cs:

```<code>public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute( "MyApp", "home/my-app", new { controller = "Home", action = "MyApp" } );
    routes.MapPageRoute( "MyOldWebForm", "oldform.aspx", "~/WebForms/OldForm.aspx" );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Site", action = "Index", id = UrlParameter.Optional } );
}
</code>```

Any reference in a view to a default declaration like @Html.BeginForm(), or a controller call result like RedirectToAction("Index", "Errors", new {fault = "itemMissing"} ); would yield the URL "oldform.aspx".

When I swap the order of the default MVC route with the page route, it works as expected.

答:
This is for asp.net web forms routing.
you can see

http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.mappageroute.aspx

Body:
Curious why declaring a MapPageRoute before the default MVC route causes problems with UrlHelper.GenerateUrl.

I started with this in my Global.asax.cs:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute( "MyApp", "home/my-app", new { controller = "Home", action = "MyApp" } );
    routes.MapPageRoute( "MyOldWebForm", "oldform.aspx", "~/WebForms/OldForm.aspx" );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Site", action = "Index", id = UrlParameter.Optional } );
}

Any reference in a view to a default declaration like @Html.BeginForm(), or a controller call result like RedirectToAction("Index", "Errors", new {fault = "itemMissing"} ); would yield the URL "oldform.aspx".

When I swap the order of the default MVC route with the page route, it works as expected.


问:
How to submit Mechanical Turk ExternalQuestions with boto3
I am trying to programmatically create a question on mechanical turk using boto3, but I seem to be doing something wrong, since the ExternalQuestion data structure that is required for create_hit seems to be missing.

I try to create the HIT like so:

```<code>import boto3

#...

client = boto3.client(
    'mturk',
    endpoint_url=endpoint_url,
    region_name=region_name,
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
)

question = ExternalQuestion(external_url=question_target, frame_height=800)

response = client.create_hit(
        MaxAssignments=10,
        Title='Test',
        Description='This is a test of ExternalQuestion',
        Question=question,
        AssignmentDurationInSeconds=60,
        LifetimeInSeconds=24 * 60 * 60,
        Reward=0.01)
</code>```

Which fails:

```<code>Traceback (most recent call last):
  File "createTask.py", line 21, in <module>
    question = ExternalQuestion(external_url=question_target, frame_height=800)
NameError: name 'ExternalQuestion' is not defined
</code>```

Any advice on how to proceed is highly appreciated.

答:
If you still have the older version of boto installed, the easiest thing is to use the get_as_xml() method of ExternalQuestion:

import boto3
from boto.mturk.question import ExternalQuestion

mturk = boto3.client(
    'mturk',
    endpoint_url='https://mturk-requester-sandbox.us-east-1.amazonaws.com',
    region_name='us-east-1',
    aws_access_key_id='your_access_key',
    aws_secret_access_key='your_secret_key',
)

question = ExternalQuestion("https://example.com/mypage.html", frame_height=600)
new_hit = mturk.create_hit(
    Title='Answer a simple question',
    Description='Help research a topic',
    Keywords='question, answer, research',
    Reward='0.15',
    MaxAssignments=1,
    LifetimeInSeconds=172800,
    AssignmentDurationInSeconds=600,
    AutoApprovalDelayInSeconds=14400,
    Question=question.get_as_xml(),   # <--- this does the trick
)
print "HITID = " + new_hit['HIT']['HITId']
```

<p>If you take a look at the output of <code>question.get_as_xml()</code>, you will see it's pretty straightforward and you can generate it yourself: </p>

<pre class="lang-xml prettyprint-override"><code><ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd">
   <ExternalURL>https://example.com/mypage.html</ExternalURL>
   <FrameHeight>600</FrameHeight>
</ExternalQuestion>
</code>```

You will need to make sure to escape characters in your question URL so that it's a valid XML file.

Body:
I am trying to programmatically create a question on mechanical turk using boto3, but I seem to be doing something wrong, since the ExternalQuestion data structure that is required for create_hit seems to be missing.

I try to create the HIT like so:

import boto3

#...

client = boto3.client(
    'mturk',
    endpoint_url=endpoint_url,
    region_name=region_name,
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
)

question = ExternalQuestion(external_url=question_target, frame_height=800)

response = client.create_hit(
        MaxAssignments=10,
        Title='Test',
        Description='This is a test of ExternalQuestion',
        Question=question,
        AssignmentDurationInSeconds=60,
        LifetimeInSeconds=24 * 60 * 60,
        Reward=0.01)

Which fails:

Traceback (most recent call last):
  File "createTask.py", line 21, in <module>
    question = ExternalQuestion(external_url=question_target, frame_height=800)
NameError: name 'ExternalQuestion' is not defined

Any advice on how to proceed is highly appreciated.

Body:
If you still have the older version of boto installed, the easiest thing is to use the get_as_xml() method of ExternalQuestion:

import boto3
from boto.mturk.question import ExternalQuestion

mturk = boto3.client(
    'mturk',
    endpoint_url='https://mturk-requester-sandbox.us-east-1.amazonaws.com',
    region_name='us-east-1',
    aws_access_key_id='your_access_key',
    aws_secret_access_key='your_secret_key',
)

question = ExternalQuestion("https://example.com/mypage.html", frame_height=600)
new_hit = mturk.create_hit(
    Title='Answer a simple question',
    Description='Help research a topic',
    Keywords='question, answer, research',
    Reward='0.15',
    MaxAssignments=1,
    LifetimeInSeconds=172800,
    AssignmentDurationInSeconds=600,
    AutoApprovalDelayInSeconds=14400,
    Question=question.get_as_xml(),   # <--- this does the trick
)
print "HITID = " + new_hit['HIT']['HITId']

If you take a look at the output of question.get_as_xml(), you will see it's pretty straightforward and you can generate it yourself:

<ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd">
   <ExternalURL>https://example.com/mypage.html</ExternalURL>
   <FrameHeight>600</FrameHeight>
</ExternalQuestion>

You will need to make sure to escape characters in your question URL so that it's a valid XML file.


问:
How to create an upload folder for a web app in Kubernetes?
we're experimenting Kubernetes and thinking about migrating our webapp, currently hosted in a classic public cloud with vps and load balancing.

I'd like to know how to manage an upload folder (with write/read privileged) inside our dockerized app in which  files uploaded by our users are stored.

As we use lot of file uploading in our apps, would it be possible to have a persistent data storage in which the webapp can upload files in and manage them via webapp? Do I have to change the code of my app and save files to external object storages or there's a faster way to do it via local filesystem?

Thank you !

答:
The persistent volume is the right way to go. You can read about it more in the link provided by Veerendra. For ease you can use some managed Kubernetes Engine like GKE/EKS/AKS as PV part is simplified there. You can find a good guide from GCP here.

About rewriting the application - probably there will be some small changes to do because you will need to use Pod level database. It will also be a more suitable solution as you will get an easy way to scale up and down with your app based on the load and couple of other features of Kubernetes.

I would not worry about LoadBalancer here. First you will dockerize your app then put it inside of a Pod which will be then a part of a Deployment then abstract the storage as PV. To get a grasp of how this all work you can start with this simple lab Deploying PHP Guestbook application with Redis. You can find another useful resource about using PV with Deployments and StatefulSets here.


问:
Intersect with row dynamically
I am trying to intersect a target range with some row, changing dynamically:
I was using this :

```<code>If Not intersect ([1:7],target) Is Nothing Then
</code>```

And it works, but :

```<code>Dim n as Integer : n = 7
If Not intersect ([1:n],target) Is Nothing Then
</code>```

Returns Error 424

答:
Try:</p>

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim n As Integer: n = 7

    If Not Intersect(Target, Rows("1:" & n)) Is Nothing Then
        MsgBox "in"
    End If

End Sub
</code>```

Title: Intersect with row dynamically

Body:
I am trying to intersect a target range with some row, changing dynamically:
I was using this :

If Not intersect ([1:7],target) Is Nothing Then

And it works, but :

Dim n as Integer : n = 7
If Not intersect ([1:n],target) Is Nothing Then

Returns Error 424

Body:
Try:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim n As Integer: n = 7

    If Not Intersect(Target, Rows("1:" & n)) Is Nothing Then
        MsgBox "in"
    End If

End Sub


问:
Are there any 'hard and fast rules' in terms of structuring HTML for the purposes of a collapsible menu?
Looking into responsive navigation components, such as provided by the React-md library, I see that the Side navigation is a
 that is added to the DOM just under the header, and displayed in position via an animation.

So in this case the structure of the navigation is:

```<code><div>
  <header />
  <div id="nav" />
</div>
</code>```

Are there any hard / fast rules regarding how to structure a navigation pane? For example, it could be possible to structure like so:

```<code><div>
  <header>
    <navPane style={left: -200px, display static}>
  </hader>
</div>
</code>```

Is there an 'optimal' approach to structuring a UI shell / navigation drawer that an experienced developer would probably know to choose?

答:
It really depends on what your page should look like on which devices.

Where should it be scrollable if content is to much?

Should it be rendering fast on scrolling the content? onscroll animation positioning then isn't a good idea.

I only would put the navPane in the header, if the navPane should be horizontal and not a vertical drawer.

These are, in my opinion, the most useful cascading basics. Number 3 and 4 are my favorites, giving the best "native app" feeling from desktop over tablet to mobile, you could have a sticky header and the nav/sidebar could slide over the content on mobile.

the following is pseudo HTML, so i don't need classes or divs, the sidebar could contain e.g. a nav-drawer. the wireframes are tablet/desktop

1. Header and footer in full width above/under sidebar and main-content

<content>
    <sidebar/>

</content>

```

<h2>2. Sidebar in full height, header only over main content, footer in full-width below sidebar and content</h2>

<p><img src="https://i.stack.imgur.com/jhlqn.png" alt="enter image description here"></p>

<pre class="lang-html prettyprint-override"><code><sidebar/>
<content>
    <header/>
    <main/>
</content>
<footer/>
</code>```

3. Header in full width, sidebar in full height to main-content wrapper, footer below actual main-content

<content>
    <sidebar/>

</content>
```

<h2>4. Sidebar in full height, header and footer above/under main-content</h2>

<p><img src="https://i.stack.imgur.com/i7OeK.png" alt="enter image description here"></p>

<pre class="lang-html prettyprint-override"><code><sidebar/>
<content>
    <header/>
    <main/>
    <footer/>
</content>
</code>```

Where will it scroll?

An image example of what's possible with 3.

Header stays at top

Sidebar and content are independently scrollable.

Footer is on bottom of content, but not over content - when content is big enough to be scrollable

Screen a little bigger in height, no scrolling.

More height, footer still at bottom of page.

Nothing is positioned through position: fixed, only sidebar-over-content on mobile would be needing fixed. The scrolling is controlled through setting display: flex; min-height: 100vh on first wrapping div, in the next ones display: flex; overflow: auto; with mostly height: 100%.

display: flex and overflow: auto leverages the scrolling down the tree, so not the whole page scrolls.

Wireframe for image example:

It is a little more complex then 3 alone, but it is based on 3.

It got boundaries for displaying loading, error states (and so on). Those are content-pane, content, editor-pane, the editor-panes could have n sidebars and contains the actual content with footer.

Body:
Looking into responsive navigation components, such as provided by the React-md library, I see that the Side navigation is a
 that is added to the DOM just under the header, and displayed in position via an animation.

So in this case the structure of the navigation is:

Are there any hard / fast rules regarding how to structure a navigation pane? For example, it could be possible to structure like so:

    <navPane style={left: -200px, display static}>
  </hader>

Is there an 'optimal' approach to structuring a UI shell / navigation drawer that an experienced developer would probably know to choose?

Body:
It really depends on what your page should look like on which devices.

Where should it be scrollable if content is to much?

Should it be rendering fast on scrolling the content? onscroll animation positioning then isn't a good idea.

I only would put the navPane in the header, if the navPane should be horizontal and not a vertical drawer.

These are, in my opinion, the most useful cascading basics. Number 3 and 4 are my favorites, giving the best "native app" feeling from desktop over tablet to mobile, you could have a sticky header and the nav/sidebar could slide over the content on mobile.

the following is pseudo HTML, so i don't need classes or divs, the sidebar could contain e.g. a nav-drawer. the wireframes are tablet/desktop

1. Header and footer in full width above/under sidebar and main-content

<header/>
<content>
    <sidebar/>
    <main/>
</content>
<footer/>

2. Sidebar in full height, header only over main content, footer in full-width below sidebar and content

<sidebar/>
<content>
    <header/>
    <main/>
</content>
<footer/>

3. Header in full width, sidebar in full height to main-content wrapper, footer below actual main-content

<header/>
<content>
    <sidebar/>
    <main-wrapper>
        <main/>
        <footer/>
    </main-wrapper>
</content>

4. Sidebar in full height, header and footer above/under main-content

<sidebar/>
<content>
    <header/>
    <main/>
    <footer/>
</content>

Where will it scroll?

An image example of what's possible with 3.

Header stays at top

Sidebar and content are independently scrollable.

Footer is on bottom of content, but not over content - when content is big enough to be scrollable

Screen a little bigger in height, no scrolling.

More height, footer still at bottom of page.

Nothing is positioned through position: fixed, only sidebar-over-content on mobile would be needing fixed. The scrolling is controlled through setting display: flex; min-height: 100vh on first wrapping div, in the next ones display: flex; overflow: auto; with mostly height: 100%.

display: flex and overflow: auto leverages the scrolling down the tree, so not the whole page scrolls.

Wireframe for image example:

It is a little more complex then 3 alone, but it is based on 3.

It got boundaries for displaying loading, error states (and so on). Those are content-pane, content, editor-pane, the editor-panes could have n sidebars and contains the actual content with footer.


问:
Creating function to get means based on column levels
I'm trying to create a function that gives me the means based on another column's levels. I know that R has plenty of functions that do this same thing, but since I'm planning to use the boot package, as I could see I need to provide a function to be used (this package appears not to have pre defined functions such as "FUN=mean"). Sorry for such a basic question!

I searched on pages about the basics of function creation in R but couldn't find what I want. Here an example what I want using iris dataset and tapply:

```<code>data(iris)
with(iris, tapply(Sepal.Length, Species, mean))
</code>```

So, I want a function that gives me the means (Sepal.Length) of each level (Species) of a X data.table (in this case, iris).

```<code>setosa versicolor  virginica
 5.006    5.936      6.588
</code>```

答:
You can make a wrapper function around tapply and use that, setting FUN to mean. Something like:

```<code>func <- function(data, x, y) {
  tapply(data[[x]], data[[y]], mean)
}
</code>```

And then you use it like:

```<code>func(iris, 'Sepal.Length', 'Species')
#    setosa versicolor  virginica
#     5.006      5.936      6.588
</code>```

Body:
I'm trying to create a function that gives me the means based on another column's levels. I know that R has plenty of functions that do this same thing, but since I'm planning to use the boot package, as I could see I need to provide a function to be used (this package appears not to have pre defined functions such as "FUN=mean"). Sorry for such a basic question!

I searched on pages about the basics of function creation in R but couldn't find what I want. Here an example what I want using iris dataset and tapply:

data(iris)
with(iris, tapply(Sepal.Length, Species, mean))

So, I want a function that gives me the means (Sepal.Length) of each level (Species) of a X data.table (in this case, iris).

setosa versicolor  virginica
 5.006    5.936      6.588

Body:
You can make a wrapper function around tapply and use that, setting FUN to mean. Something like:

func <- function(data, x, y) {
  tapply(data[[x]], data[[y]], mean)
}

And then you use it like:

func(iris, 'Sepal.Length', 'Species')
#    setosa versicolor  virginica
#     5.006      5.936      6.588


问:
Default query params not getting passed in axios request
I'm using axios.create() to pass in a baseURL and some default query params like this

```<code>axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});
</code>```

When I use

```<code>axios.get('/search', {
    params: {
        q: 'word'
    }
});
</code>```

the default params do not get merged in the GET call.

What I get is
http://somebigurlhere/search?q=word

instead of
http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd

I tried putting the configuration in many other ways but it still doesn't work.
Am i doing something wrong here ?

I tried the same in other projects and it is working there. Just created a new react app with create-react-app and this doesn't seem to work anymore.

答:
Just create a config object and pass it to your Axios.get request.

```<code>const config = {
    baseURL: 'www.someurl.com',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
    }
</code>```

    }

```<code>axios.get('/waffles', config);
</code>```

Example:

const config = {
    baseURL: 'https://reqres.in',
    params: {
        per_page: 3
    }
}

axios.get('/api/users?page=1', config).then(response => {console.log(response)}).catch(err => {console.log(err)});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/axios/dist/axios.min.js"></script></code>```

If you would like to use axios.create you need to assign it to a variable as an axios instance object and then run your request against that instance.

var instance = axios.create({
    baseURL: 'https://reqres.in',
    params: {
        per_page: 5
    }
});
instance.get('/api/users?page=1').then(response => {console.log(response)}).catch(err => {console.log(err)});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/axios/dist/axios.min.js"></script></code>```

So for your exact example, as I said, assign axios.create to a variable then issue your .get from that.

```<code>var instance = axios.create({
        baseURL: 'http://somebigurlhere',
        params: {
            part: 'part',
            maxResults: 5,
            key: 'key'
        }
    });

instance.get('/search', {
    params: {
        q: 'word'
    }
});
</code>```

Bigger Edit
This edit shows how to do this in react per OPs comment in my answer. The actual sandbox demonstrating htis can be found here:
https://codesandbox.io/embed/cranky-aryabhata-2773d?fontsize=14

//axios_control.js file

```<code>import axios from "axios";
export const instance = axios.create({
  baseURL: "https://reqres.in",
  params: {
    per_page: 5
  }
});
</code>```

// index.js file
Take note of the import from axios_control and the usage to log the return data right before the render.

```<code>import React from "react";
import ReactDOM from "react-dom";
import { instance } from "./axios_control";

import "./styles.css";

function App() {
  instance.get("/api/users").then(response => {
    console.log(response);
  });

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

Body:
I'm using axios.create() to pass in a baseURL and some default query params like this

axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});

When I use

axios.get('/search', {
    params: {
        q: 'word'
    }
});

the default params do not get merged in the GET call.

What I get is
http://somebigurlhere/search?q=word

instead of
http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd

I tried putting the configuration in many other ways but it still doesn't work.
Am i doing something wrong here ?

I tried the same in other projects and it is working there. Just created a new react app with create-react-app and this doesn't seem to work anymore.

Body:
Just create a config object and pass it to your Axios.get request.

const config = {
    baseURL: 'www.someurl.com',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
    }

    }

axios.get('/waffles', config);

Example:

const config = {
    baseURL: 'https://reqres.in',
    params: {
        per_page: 3
    }
}

axios.get('/api/users?page=1', config).then(response => {console.log(response)}).catch(err => {console.log(err)});

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

If you would like to use axios.create you need to assign it to a variable as an axios instance object and then run your request against that instance.

var instance = axios.create({
    baseURL: 'https://reqres.in',
    params: {
        per_page: 5
    }
});
instance.get('/api/users?page=1').then(response => {console.log(response)}).catch(err => {console.log(err)});

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

So for your exact example, as I said, assign axios.create to a variable then issue your .get from that.

var instance = axios.create({
        baseURL: 'http://somebigurlhere',
        params: {
            part: 'part',
            maxResults: 5,
            key: 'key'
        }
    });

instance.get('/search', {
    params: {
        q: 'word'
    }
});

Bigger Edit
This edit shows how to do this in react per OPs comment in my answer. The actual sandbox demonstrating htis can be found here:
https://codesandbox.io/embed/cranky-aryabhata-2773d?fontsize=14

//axios_control.js file

import axios from "axios";
export const instance = axios.create({
  baseURL: "https://reqres.in",
  params: {
    per_page: 5
  }
});

// index.js file
Take note of the import from axios_control and the usage to log the return data right before the render.

import React from "react";
import ReactDOM from "react-dom";
import { instance } from "./axios_control";

import "./styles.css";

function App() {
  instance.get("/api/users").then(response => {
    console.log(response);
  });

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


问:
How to make a numpy array field in django?
I want a numpy array field in django so that I can do something like this

```<code>from example.models import Series
import numpy as np
array = np.array([1, 2, 3])
model = Series.objects.create(id=1, array=array)
model = Series.objects.get(id=1)
assert np.array_equal(array, model.array)
</code>```

Essentially, the field should serialize the numpy array to binary and deserialize it automatically. Currently, I'm just doing this:

```<code>import base64
import numpy as np
from django.db import models

class Series(models.Model):
    id = models.IntegerField(primary_key=True, unique=True)
    array = models.BinaryField()

    def get_array():
        return np.frombuffer(base64.decodebytes(self.array), dtype=np.float32)

    def set_array(array):
        self.array = base64.b64encode(array)
</code>```

I'd prefer it if this were a reusable field because I have many models that will need to store a numpy array. For example:

```<code>class Series(models.Model):
    array = NumpyArrayField(dtype=np.float32)
</code>```

So, how can I write a NumpyArrayField class that accomplishes this?

I tried doing the following (copying the source code for BinaryField)

```<code>import base64

import numpy as np
from django.db import models

class NumpyArrayField(models.Field):
    empty_values = [None]

    def __init__(self, dtype, *args, **kwargs):
        self.dtype = dtype
        super(NumpyArrayField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(NumpyArrayField, self).deconstruct()
        kwargs['dtype'] = self.dtype
        return name, path, args, kwargs

    def get_internal_type(self):
        return 'NumpyArrayField'

    def get_placeholder(self, value, compiler, connection):
        return connection.ops.binary_placeholder_sql(value)

    def get_default(self):
        if self.has_default() and not callable(self.default):
            return self.default
        default = super(NumpyArrayField, self).get_default()
        if default == '':
            return b''
        return default

    def get_db_prep_value(self, value, connection, prepared=False):
        value = super(NumpyArrayField, self).get_db_prep_value(value, connection, prepared)
        value = base64.b64encode(value)
        if value is not None:
            return connection.Database.Binary(value)
        return value

    def value_to_string(self, obj):
        return base64.b64encode(obj).decode('ascii')

    def to_python(self, value):
        return np.frombuffer(base64.decodebytes(value), dtype=self.dtype)

class Series(models.Model):
    id = models.IntegerField(primary_key=True, unique=True)
    array = NumpyArrayField(dtype=np.int32)
</code>```

And the migrations ran fine, but I got a django.db.utils.OperationalError: table example_series has no column named array error.

答:
I saved the numpy array to Django model with MySQL, here's:

set the field to Django BinaryField

from django.db import models

np_field = models.BinaryField()

transform numpy array to python byte using pickle dumps, then encoded by  base64

np_bytes = pickle.dumps(np_array)

np_base64 = base64.b64encode(np_bytes)

model.np_field = np_base64

get the numpy array from django model

np_bytes = base64.b64decode(model.np_field)

np_array = pickle.loads(np_bytes)

Body:
I want a numpy array field in django so that I can do something like this

from example.models import Series
import numpy as np
array = np.array([1, 2, 3])
model = Series.objects.create(id=1, array=array)
model = Series.objects.get(id=1)
assert np.array_equal(array, model.array)

Essentially, the field should serialize the numpy array to binary and deserialize it automatically. Currently, I'm just doing this:

import base64
import numpy as np
from django.db import models

class Series(models.Model):
    id = models.IntegerField(primary_key=True, unique=True)
    array = models.BinaryField()

    def get_array():
        return np.frombuffer(base64.decodebytes(self.array), dtype=np.float32)

    def set_array(array):
        self.array = base64.b64encode(array)

I'd prefer it if this were a reusable field because I have many models that will need to store a numpy array. For example:

class Series(models.Model):
    array = NumpyArrayField(dtype=np.float32)

So, how can I write a NumpyArrayField class that accomplishes this?

I tried doing the following (copying the source code for BinaryField)

import base64

import numpy as np
from django.db import models

class NumpyArrayField(models.Field):
    empty_values = [None]

    def __init__(self, dtype, *args, **kwargs):
        self.dtype = dtype
        super(NumpyArrayField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(NumpyArrayField, self).deconstruct()
        kwargs['dtype'] = self.dtype
        return name, path, args, kwargs

    def get_internal_type(self):
        return 'NumpyArrayField'

    def get_placeholder(self, value, compiler, connection):
        return connection.ops.binary_placeholder_sql(value)

    def get_default(self):
        if self.has_default() and not callable(self.default):
            return self.default
        default = super(NumpyArrayField, self).get_default()
        if default == '':
            return b''
        return default

    def get_db_prep_value(self, value, connection, prepared=False):
        value = super(NumpyArrayField, self).get_db_prep_value(value, connection, prepared)
        value = base64.b64encode(value)
        if value is not None:
            return connection.Database.Binary(value)
        return value

    def value_to_string(self, obj):
        return base64.b64encode(obj).decode('ascii')

    def to_python(self, value):
        return np.frombuffer(base64.decodebytes(value), dtype=self.dtype)

class Series(models.Model):
    id = models.IntegerField(primary_key=True, unique=True)
    array = NumpyArrayField(dtype=np.int32)

And the migrations ran fine, but I got a django.db.utils.OperationalError: table example_series has no column named array error.


问:
AspNetUsers link to another table. How to create object (1-1relationship)
I'm trying to create a table with additional User info, and link it with User one-to-one relationship. I tried a few things found on stackOverflow, but still I can't properly link both tables (create object)

Idea of application is to review and rate beauty therapist.
User can choose if he wants to have an extended account as therapist (with extra info and possibility to be rated).

I'm learning asp.net mvc so I'm open for any help or suggestions how to create this app.

When user is logged in and I try to create Therapist object, I have an error (looks like I must deliver user object).
Not sure how to solve it or even if this solution for my idea is good.

```<code>public class Therapist
{
        public int IdTherapist { get; set; }

        [Key, ForeignKey("User")]
        [Required]
        public string UserId { get; set; }

        public virtual  ApplicationUser User { get; set; }

        [Required]
        [Display(Name = "Name")]
        public string TherapistName { get; set; }

        [Display(Name = "Surname")]
        public string TherapistSurname { get; set; }

        [Display(Name = "City")]
        public string City { get; set; } }

public class ApplicationUser : IdentityUser
{

        public virtual Therapist Therapist { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {

            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            return userIdentity;
        }
    }

//Therapist Controller

public ActionResult Create(Therapist therapist)
   if (therapist.UserId == null)
               therapist.UserId = User.Identity.GetUserId();

                    _context.Therapists.Add(therapist);
                            context.SaveChanges();

                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            return View(therapist);
</code>```

After run this code, I have

"System.Data.Entity.Validation.DbEntityValidationException", look closer: "ErrorMessage    "The User field is required."

  (not User.Id)

答: Try add a TherapistId property in User class.</p>

Body:
I'm trying to create a table with additional User info, and link it with User one-to-one relationship. I tried a few things found on stackOverflow, but still I can't properly link both tables (create object)

Idea of application is to review and rate beauty therapist.
User can choose if he wants to have an extended account as therapist (with extra info and possibility to be rated).

I'm learning asp.net mvc so I'm open for any help or suggestions how to create this app.

When user is logged in and I try to create Therapist object, I have an error (looks like I must deliver user object).
Not sure how to solve it or even if this solution for my idea is good.

public class Therapist
{
        public int IdTherapist { get; set; }

        [Key, ForeignKey("User")]
        [Required]
        public string UserId { get; set; }

        public virtual  ApplicationUser User { get; set; }

        [Required]
        [Display(Name = "Name")]
        public string TherapistName { get; set; }

        [Display(Name = "Surname")]
        public string TherapistSurname { get; set; }

        [Display(Name = "City")]
        public string City { get; set; } }

public class ApplicationUser : IdentityUser
{

        public virtual Therapist Therapist { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {

            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            return userIdentity;
        }
    }

//Therapist Controller

public ActionResult Create(Therapist therapist)
   if (therapist.UserId == null)
               therapist.UserId = User.Identity.GetUserId();

                    _context.Therapists.Add(therapist);
                            context.SaveChanges();

                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            return View(therapist);

After run this code, I have

"System.Data.Entity.Validation.DbEntityValidationException", look closer: "ErrorMessage    "The User field is required."

  (not User.Id)