问:
Can't install matplotlib to pycharm
I have recently started to learn python programming using Python Crash Course. I am stuck as I can't get matplotlib to work in pycharm.

I have pip installed.
I have installed matplotlib using pip via command prompt.

Now, when I open pycharm and go file->settings->project interpreter->download packages and find and press install for matplotlib, I get an error: Command "python setup.py egg_info" failed with error code 1 in C:\Users\Tony\AppData\Local\Temp\pip-install-f2h0rvbb\matplotlib\ . When installing on pycharm it says its using cached file from website I didn't download my matplotlib from.

I have tried "pip install matplotlib" from  pycharm terminal and get the same error.

I have tried typing "pip install matplotlib" from cmd and it does so and says its already satisfied.

Any help or guidance would be appreciated, thanks.

答:
Managed to get it to work by typing into pycharm terminal:

pip install updates

Then I went to file->settings->project interpreter-> then found pip via search and updated it again to be more sure. Once pip version on left hand side of column in file->settings->project interpreter showed the version to be the newest 20.0.2 which was == to the right hand side(latest version) column it was 100% updated.  This can be done also by pressing the upgrade button just above the 'show early releases' button which looks like an eye just to the right of the right hand side column when you have already clicked on the package.

To finish I went file->settings->project interpreter-> found matplotlib and installed package successfully.

Overall I think that not having an up to date version of pip being used for pycharm and having to update the one specifically for use in pycharm is responsible not being able to install matplotlib.
Although it could have also been due to having downloaded pip separately elsewhere on my system trying to solve this problem and when I have updated pip before from cmd.exe it didn't update the correct version of pip which I am using for Pycharm.

Title: Can't install matplotlib to pycharm


来源: stackexchange

问:
Stuck on Paper-Scissors-Rock game
While loop iterates two times every time, and CPU only scores point when choosing 'S' for scissors. Another question is, how do I make it toupper and where do I add that function? I have to use characters 'r','s', and 'p', instead of 1,2,3 to accept user input. Not sure how to proceed to fix this</p>

```<code>#include <stdlib.h>
#include<time.h>

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R':
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```
</code>```

答:
I suggest you fix it by making it far less complicated. The winner of Rock-Paper-Scissors can be determined arithmetically.

It is simpler to compare like for like, and using integer values allows a simpler arithmetic solution.  Also arithmetically it is simpler to use 0,1,2 rather than 1,2,3.  So first transform the user input to 0,1,2:

```<code>#define INVALID_SELECTION sizeof(rps)
static const char rps[] = {'r', 'p', 's'} ;
int human = INVALID_SELECTION ;

while( human == INVALID_SELECTION )
{
    printf("\nEnter R for Rock, P for Paper, or S for Scissors: ");

    char ch = 0 ;
    scanf("%c", &ch ) ;
    while( ch != '\n' && getchar() != '\n' ) ;

    for( human = 0;
         human < INVALID_SELECTION && tolower(ch) != rps[human] ;
         human++ )
    {
        // do nothing
    }
}
</code>```

The computer play should then be determined thus :

```<code>srand( (int)time(NULL) ) ;
int computer = rand() % 3 ;
</code>```

though note that you need only call srand() once, so if you put the game in a loop to repeat play, the srand() call should appear before the repeat loop.

You can then report the play thus:

```<code>static const char* play_lookup[] = { "Rock", "Paper", "Scissors" } ;
printf( "Human played %s\n", play_lookup[human] ) ;
printf( "Computer played %s\n", play_lookup[computer] ) ;
</code>```

Then human and computer are directly and arithmetically comparable such that:

```<code>int battle = human - computer ;
if( battle < 0 ) battle += 3 ;
switch( battle )
{
    case 0 : printf( "Draw!\n" ) ; break ;
    case 1 : printf( "Human wins!\n" ) ; break ;
    case 2 : printf( "Computer wins!\n" ) ; break ;
}
</code>```

or (credit to @HAL9000):

```<code>int battle = ((human - computer) + 3) % 3 ;
switch( battle )
...
</code>```

Putting it all together:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

int main()
{
    // Randomize
    srand( (int)time(NULL) ) ;

    // Repeat play indefinitely
    for(;;)
    {
        #define INVALID_SELECTION sizeof(rps)
        static const char rps[] = {'r', 'p', 's'} ;
        int human = INVALID_SELECTION ;

        // While human input is not one of R,P,S,r,p or s...
        while( human == INVALID_SELECTION )
        {
            printf("\nEnter R for Rock, P for Paper, or S for Scissors: ");

            char ch = 0 ;
            scanf("%c", &ch ) ;
            while( ch != '\n' && getchar() != '\n' ) ;

            // Transform input to one of 0,1,2 (for R,P,S respectively)
            for( human = 0;
                 human < INVALID_SELECTION && tolower(ch) != rps[human] ;
                 human++ )
            {
                // do nothing
            }
        }

        // Get computer's play
        int computer = rand() % 3 ;

        // Report human and computer plays in full text
        static const char* play_lookup[] = { "Rock", "Paper", "Scissors" } ;
        printf( "Human played %s\n", play_lookup[human] ) ;
        printf( "Computer played %s\n", play_lookup[computer] ) ;

        // Calculate and report result
        int battle = ((human - computer) + 3) % 3 ;
        switch( battle )
        {
            case 0 : printf( "Draw!\n" ) ; break ;
            case 1 : printf( "Human wins!\n" ) ; break ;
            case 2 : printf( "Computer wins!\n" ) ; break ;
        }
    }

    return 0;
}
</code>```

Example output:

```<code>Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Rock
Draw!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Rock
Draw!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Paper
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Paper
Draw!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Scissors
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Rock
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Scissors
Draw!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Scissors
Draw!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Rock
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: R
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: P
Human played Paper
Computer played Paper
Draw!

Enter R for Rock, P for Paper, or S for Scissors: S
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: xx

Enter R for Rock, P for Paper, or S for Scissors: yy

Enter R for Rock, P for Paper, or S for Scissors: zz

Enter R for Rock, P for Paper, or S for Scissors:

</code>```

ContentLicense: CC BY-SA 4.0

Title: Stuck on Paper-Scissors-Rock game

Body:
While loop iterates two times every time, and CPU only scores point when choosing 'S' for scissors. Another question is, how do I make it toupper and where do I add that function? I have to use characters 'r','s', and 'p', instead of 1,2,3 to accept user input. Not sure how to proceed to fix this

#include <stdlib.h>
#include<time.h>

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R':
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```

Body:
I suggest you fix it by making it far less complicated. The winner of Rock-Paper-Scissors can be determined arithmetically.

It is simpler to compare like for like, and using integer values allows a simpler arithmetic solution.  Also arithmetically it is simpler to use 0,1,2 rather than 1,2,3.  So first transform the user input to 0,1,2:

#define INVALID_SELECTION sizeof(rps)
static const char rps[] = {'r', 'p', 's'} ;
int human = INVALID_SELECTION ;

while( human == INVALID_SELECTION )
{
    printf("\nEnter R for Rock, P for Paper, or S for Scissors: ");

    char ch = 0 ;
    scanf("%c", &ch ) ;
    while( ch != '\n' && getchar() != '\n' ) ;

    for( human = 0;
         human < INVALID_SELECTION && tolower(ch) != rps[human] ;
         human++ )
    {
        // do nothing
    }
}

The computer play should then be determined thus :

srand( (int)time(NULL) ) ;
int computer = rand() % 3 ;

though note that you need only call srand() once, so if you put the game in a loop to repeat play, the srand() call should appear before the repeat loop.

You can then report the play thus:

static const char* play_lookup[] = { "Rock", "Paper", "Scissors" } ;
printf( "Human played %s\n", play_lookup[human] ) ;
printf( "Computer played %s\n", play_lookup[computer] ) ;

Then human and computer are directly and arithmetically comparable such that:

int battle = human - computer ;
if( battle < 0 ) battle += 3 ;
switch( battle )
{
    case 0 : printf( "Draw!\n" ) ; break ;
    case 1 : printf( "Human wins!\n" ) ; break ;
    case 2 : printf( "Computer wins!\n" ) ; break ;
}

or (credit to @HAL9000):

int battle = ((human - computer) + 3) % 3 ;
switch( battle )
...

Putting it all together:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

int main()
{
    // Randomize
    srand( (int)time(NULL) ) ;

    // Repeat play indefinitely
    for(;;)
    {
        #define INVALID_SELECTION sizeof(rps)
        static const char rps[] = {'r', 'p', 's'} ;
        int human = INVALID_SELECTION ;

        // While human input is not one of R,P,S,r,p or s...
        while( human == INVALID_SELECTION )
        {
            printf("\nEnter R for Rock, P for Paper, or S for Scissors: ");

            char ch = 0 ;
            scanf("%c", &ch ) ;
            while( ch != '\n' && getchar() != '\n' ) ;

            // Transform input to one of 0,1,2 (for R,P,S respectively)
            for( human = 0;
                 human < INVALID_SELECTION && tolower(ch) != rps[human] ;
                 human++ )
            {
                // do nothing
            }
        }

        // Get computer's play
        int computer = rand() % 3 ;

        // Report human and computer plays in full text
        static const char* play_lookup[] = { "Rock", "Paper", "Scissors" } ;
        printf( "Human played %s\n", play_lookup[human] ) ;
        printf( "Computer played %s\n", play_lookup[computer] ) ;

        // Calculate and report result
        int battle = ((human - computer) + 3) % 3 ;
        switch( battle )
        {
            case 0 : printf( "Draw!\n" ) ; break ;
            case 1 : printf( "Human wins!\n" ) ; break ;
            case 2 : printf( "Computer wins!\n" ) ; break ;
        }
    }

    return 0;
}

Example output:

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Rock
Draw!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Rock
Draw!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: r
Human played Rock
Computer played Paper
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Paper
Draw!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Scissors
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: p
Human played Paper
Computer played Rock
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Scissors
Draw!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Scissors
Draw!

Enter R for Rock, P for Paper, or S for Scissors: s
Human played Scissors
Computer played Rock
Computer wins!

Enter R for Rock, P for Paper, or S for Scissors: R
Human played Rock
Computer played Scissors
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: P
Human played Paper
Computer played Paper
Draw!

Enter R for Rock, P for Paper, or S for Scissors: S
Human played Scissors
Computer played Paper
Human wins!

Enter R for Rock, P for Paper, or S for Scissors: xx

Enter R for Rock, P for Paper, or S for Scissors: yy

Enter R for Rock, P for Paper, or S for Scissors: zz

Enter R for Rock, P for Paper, or S for Scissors:


问:
If a browser can shows Accept-Encoding of deflate, can it handle .NET gzipped responses?
I'm looking at this method in this HTTPCombiner:

```<code>private bool CanGZip(HttpRequest request)
{
    string acceptEncoding = request.Headers["Accept-Encoding"];
    if (!string.IsNullOrEmpty(acceptEncoding) &&
         (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
        return true;
    return false;
}
</code>```

If this returns true then the response is compressed using a GZipStream. Is this right?

答: Typically most of the browsers understand GZip and Deflate. They tell the server by specifying it in the request header as Accept-Encoding:gzip, deflate. The HTTPCombiner gives preference to GZip. If both the types are present then GZip is given the preference. HttpCombiner will send the content only if the browser requests for Defalte only.

ContentLicense: CC BY-SA 3.0

Body:
I'm looking at this method in this HTTPCombiner:

private bool CanGZip(HttpRequest request)
{
    string acceptEncoding = request.Headers["Accept-Encoding"];
    if (!string.IsNullOrEmpty(acceptEncoding) &&
         (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
        return true;
    return false;
}

If this returns true then the response is compressed using a GZipStream. Is this right?


问:
Prevent an aws account from going into using on-demand

   We have a purchased a fleet of reserved instances in our AWS account which we use for out EMR cluster. Multiple developers create EMR clusters pulling reserved instances out of our AWS account and if it goes over the limit it goes into on-demand mode which makes it very expensive. We want to able to prevent this from happening. Anyway we can query our AWS account to make sure that no on-demand instances are being used?

答:
There is no way to 'prevent' usage of non-Reserved Instances.

Reserved Instances are a billing discount calculated when charges are applied. There is no facility to 'block' the use of serves that are not covered by Reserved Instance discounts.

There are some Reserved Instance (RI) Reporting capabilities in the Cost and Usage Report that can indicate whether you are taking advantage of all RIs (eg not using them at night).

I recall hearing that Netflix had written a utility to encourage Amazon EMR users to use an existing cluster or to launch a cluster using "unused RIs". The system would launch the clusters on behalf of users, rather than allowing users to directly launch clusters, so there was an opportunity to check utilization or prompt for confirmation before launching the resources. You could write something similar, that checks for existing EC2 usage and launches the cluster on the user's behalf if there is spare RI capacity.


问:
Can't get Extra data via Intent
I'm trying to put extra data (string) in an intent. I use startActivity to get my extra string data on the other side.
But I can't get why it doesn't work! Here's my code :
This is the destination Activity from where I want to parse my extra data -- Recipe Activity :

```<code>class RecipeActivity : AppCompatActivity() {
    for (k in 0..name_arr.size-1) {
        if(temp_arr[position]==name_arr[k]){
            //to parse the id number of the selected recipe by the user to the next activity
            val i = Intent(baseContext, ResRecActivity::class.java)
            i.putExtra("ItemPosition",k)
            startActivity(i)
        }
    }
}
</code>```

This is the Target Activity for successful parsing of extra data -- ResRecActivity :

```<code>class ResRecActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_res_rec)
        setSupportActionBar(toolbar)

        var posit : String = intent.getStringExtra("ItemPosition") //wanting to get the extra data

        //BELOW LINE IS THE ERROR LINE
        *readJson(posit.toInt())* //Intending to parse the extra data in Integer datatype to readJson Function
    }
}
</code>```

Error that I am getting is :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testarca/com.example.arca.ResRecActivity}: kotlin.KotlinNullPointerException
    Caused by: *kotlin.KotlinNullPointerException*
        at com.example.arca.ResRecActivity.onCreate(ResRecActivity.kt:37)
</code>```

Main Aim :
I just want to parse the Integer "position" (in my case "k") from "RecipeActivity" to "ResRecActivity", for using that integer position in another function named "readJson" as a parameter to the function.
And I am trying to achieve that using Intent property for Handling between the activities.

Note: Also give me a similar solution to parse an ArrayList data from one activity to another using intent.

答:
When you use i.putExtra("ItemPosition",k), you're putting an Int into your extras.

Therefore you must use getIntExtra to retrieve it:

```<code>val posit = intent.getIntExtra("ItemPosition", 0)
</code>```

Title: Can't get Extra data via Intent

Body:
I'm trying to put extra data (string) in an intent. I use startActivity to get my extra string data on the other side.
But I can't get why it doesn't work! Here's my code :
This is the destination Activity from where I want to parse my extra data -- Recipe Activity :

class RecipeActivity : AppCompatActivity() {
    for (k in 0..name_arr.size-1) {
        if(temp_arr[position]==name_arr[k]){
            //to parse the id number of the selected recipe by the user to the next activity
            val i = Intent(baseContext, ResRecActivity::class.java)
            i.putExtra("ItemPosition",k)
            startActivity(i)
        }
    }
}

This is the Target Activity for successful parsing of extra data -- ResRecActivity :

class ResRecActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_res_rec)
        setSupportActionBar(toolbar)

        var posit : String = intent.getStringExtra("ItemPosition") //wanting to get the extra data

        //BELOW LINE IS THE ERROR LINE
        *readJson(posit.toInt())* //Intending to parse the extra data in Integer datatype to readJson Function
    }
}

Error that I am getting is :

E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testarca/com.example.arca.ResRecActivity}: kotlin.KotlinNullPointerException
    Caused by: *kotlin.KotlinNullPointerException*
        at com.example.arca.ResRecActivity.onCreate(ResRecActivity.kt:37)

Main Aim :
I just want to parse the Integer "position" (in my case "k") from "RecipeActivity" to "ResRecActivity", for using that integer position in another function named "readJson" as a parameter to the function.
And I am trying to achieve that using Intent property for Handling between the activities.

Note: Also give me a similar solution to parse an ArrayList data from one activity to another using intent.

Body:
When you use i.putExtra("ItemPosition",k), you're putting an Int into your extras.

Therefore you must use getIntExtra to retrieve it:

val posit = intent.getIntExtra("ItemPosition", 0)


问:
Editing ngx-datatable styling issues
I'm following the themeing setup for ngx-datatable.

First I npm installed ngx-datatable 10.4.0 since this is compatible with Angular 4 and an earlier version of rxjs.

My problem is with the styling of the table.

My template file looks like this:

    <ngx-datatable
        [rows]="rows"
        [columns]="columns"
        [columnMode]="'standard'"
        class="material"
        fixed-header
        [headerHeight]="50"
        [scrollbarV]="true">
    </ngx-datatable>

```
</div>
</div>
</p>

<p>Inside of my scss file:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import '~@swimlane/ngx-datatable/release/index.css';
@import '~@swimlane/ngx-datatable/release/themes/material.css';
@import '~@swimlane/ngx-datatable/release/themes/bootstrap.css';
@import '~@swimlane/ngx-datatable/release/assets/icons.css';</code>```

And I can confirm that the material styling works to a certain extent:

I wish to add a border-bottom under my header, but to no avail.

If you check the demo: http://swimlane.github.io/ngx-datatable/#filter

There is always a border-bottom for the sample tables.

How do I configure the table to insert a border-bottom beneath the header?

Is there a problem with my ngx-datatable setup?

答:
Any styling of this component should be done in the global styles.scss file.

styles.scss:

```<code>/* You can add global styles to this file, and also import other style files */
@import '~@swimlane/ngx-datatable/index.css';
@import '~@swimlane/ngx-datatable/themes/bootstrap.scss';
@import '~@swimlane/ngx-datatable/themes/material.scss';
@import '~@swimlane/ngx-datatable/themes/dark.scss';
@import '~@swimlane/ngx-datatable/assets/icons.css';

/* Preferably put any custom styles for ngx-datatable into your own "_datatable.scss" file
   and @import it into global styles, but this is a simple working example */

.ngx-datatable {
  border: 1px solid #dddddd;
  ...
}
</code>```

If you haven't used the global styles file yet, make sure it exists at src/styles.scss. Ensure that it is included in angular.json under architect/build/options/styles:

```<code>...
"styles": [
  "src/styles.scss",
  ...
]
</code>```

Angular CLI apps should have all of this built out by default.

It's too bad the docs don't mention this, but view encapsulation on your component will block the styles from bleeding down into any nested components. This is actually preferable so that your styles don't get bashed when you build a component for someone else to install and you use the same class names by accident.

Title: Editing ngx-datatable styling issues

Body:
I'm following the themeing setup for ngx-datatable.

First I npm installed ngx-datatable 10.4.0 since this is compatible with Angular 4 and an earlier version of rxjs.

My problem is with the styling of the table.

My template file looks like this:

    <ngx-datatable
        [rows]="rows"
        [columns]="columns"
        [columnMode]="'standard'"
        class="material"
        fixed-header
        [headerHeight]="50"
        [scrollbarV]="true">
    </ngx-datatable>

Inside of my scss file:

@import '~@swimlane/ngx-datatable/release/index.css';
@import '~@swimlane/ngx-datatable/release/themes/material.css';
@import '~@swimlane/ngx-datatable/release/themes/bootstrap.css';
@import '~@swimlane/ngx-datatable/release/assets/icons.css';

And I can confirm that the material styling works to a certain extent:

I wish to add a border-bottom under my header, but to no avail.

If you check the demo: http://swimlane.github.io/ngx-datatable/#filter

There is always a border-bottom for the sample tables.

How do I configure the table to insert a border-bottom beneath the header?

Is there a problem with my ngx-datatable setup?

Body:
Any styling of this component should be done in the global styles.scss file.

styles.scss:

/* You can add global styles to this file, and also import other style files */
@import '~@swimlane/ngx-datatable/index.css';
@import '~@swimlane/ngx-datatable/themes/bootstrap.scss';
@import '~@swimlane/ngx-datatable/themes/material.scss';
@import '~@swimlane/ngx-datatable/themes/dark.scss';
@import '~@swimlane/ngx-datatable/assets/icons.css';

/* Preferably put any custom styles for ngx-datatable into your own "_datatable.scss" file
   and @import it into global styles, but this is a simple working example */

.ngx-datatable {
  border: 1px solid #dddddd;
  ...
}

If you haven't used the global styles file yet, make sure it exists at src/styles.scss. Ensure that it is included in angular.json under architect/build/options/styles:

...
"styles": [
  "src/styles.scss",
  ...
]

Angular CLI apps should have all of this built out by default.

It's too bad the docs don't mention this, but view encapsulation on your component will block the styles from bleeding down into any nested components. This is actually preferable so that your styles don't get bashed when you build a component for someone else to install and you use the same class names by accident.


问:
In java selenium i am trying to send backspace character ('\uE003') or (\u0008) to a textbox to clear existing text
```<code>textboxElement.sendKeys("\uE003");
(or)
textboxElement.sendKeys("\u0008");

</code>```

But instead of removing the existing text in the textbox,   003 or 0008 is getting  added to the textbox. i cant use Keys.BACK_SPACE because it is not working on Ubuntu server.

答:
Try applying the usual control a, then delete. This will clear the whole text in a textfield.</p>

```<code>textboxElement.sendKeys(Keys.CONTROL + "a");
textboxElement.sendKeys(Keys.DELETE);
</code>```

Body:
textboxElement.sendKeys("\uE003");
(or)
textboxElement.sendKeys("\u0008");

But instead of removing the existing text in the textbox,   003 or 0008 is getting  added to the textbox. i cant use Keys.BACK_SPACE because it is not working on Ubuntu server.

Body:
Try applying the usual control a, then delete. This will clear the whole text in a textfield.

textboxElement.sendKeys(Keys.CONTROL + "a");
textboxElement.sendKeys(Keys.DELETE);


问:
How to solve privileges issues when restore PostgreSQL Database
I have dumped a clean, no owner backup for Postgres Database with the command

pg_dump sample_database -O -c -U

Later, when I restore the database with

psql -d sample_database -U app_name

However, I encountered several errors which prevents me from restoring the data:

```<code>ERROR:  must be owner of extension plpgsql
ERROR:  must be owner of schema public
ERROR:  schema "public" already exists
ERROR:  must be owner of schema public
CREATE EXTENSION
ERROR:  must be owner of extension plpgsql
</code>```

I digged into the plain-text SQL pg_dump generates and I found it contains SQL

```<code>CREATE SCHEMA public;
COMMENT ON SCHEMA public IS 'standard public schema';
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
</code>```

I think the causes are that the user app_name doesn't have the privileges to alter the public schema and plpgsql.

How could I solve this issue?

答:
For people using AWS, the COMMENT ON EXTENSION is possible only as superuser, and as we know by the docs, RDS instances are managed by Amazon. As such, to prevent you from breaking things like replication, your users - even the root user you set up when you create the instance - will not have full superuser privileges:

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

When you create a DB instance, the master user system account that you
create is assigned to the rds_superuser role. The rds_superuser role
is a pre-defined Amazon RDS role similar to the PostgreSQL superuser
role (customarily named postgres in local instances), but with some
restrictions. As with the PostgreSQL superuser role, the rds_superuser
role has the most privileges on your DB instance and you should not
assign this role to users unless they need the most access to the DB
instance.

In order to fix this error, just use -- to comment out the lines of SQL that contains COMMENT ON EXTENSION

EDIT 1: As suggested by Dmitrii I., you can also omit comments when dumping: pg_dump --no-comments

Body:
I have dumped a clean, no owner backup for Postgres Database with the command

pg_dump sample_database -O -c -U

Later, when I restore the database with

psql -d sample_database -U app_name

However, I encountered several errors which prevents me from restoring the data:

ERROR:  must be owner of extension plpgsql
ERROR:  must be owner of schema public
ERROR:  schema "public" already exists
ERROR:  must be owner of schema public
CREATE EXTENSION
ERROR:  must be owner of extension plpgsql

I digged into the plain-text SQL pg_dump generates and I found it contains SQL

CREATE SCHEMA public;
COMMENT ON SCHEMA public IS 'standard public schema';
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';

I think the causes are that the user app_name doesn't have the privileges to alter the public schema and plpgsql.

How could I solve this issue?


问:
Using xpath with c#, help
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

```<code>XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);
</code>```

```<code><ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>
</code>```

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

答:
Use XmlDocument instance and load your XML into it, and then use SelectNodes method passing your xpath query as an input parameter.

```<code>        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlText);
        var gg = xmlDocument.SelectNodes("//MAX/MINRANGE");
</code>```

This will give you a collection of nodes you can iterate through.

Title: Using xpath with c#, help

Body:
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);

<ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

Body:
Use XmlDocument instance and load your XML into it, and then use SelectNodes method passing your xpath query as an input parameter.

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlText);
        var gg = xmlDocument.SelectNodes("//MAX/MINRANGE");

This will give you a collection of nodes you can iterate through.


问:
d3.js + react.js --> cant access the state
could someone please tell me why I cant access the react.state in my d3.js function.
I really cant figure out why.

```<code>import React, { Component } from 'react'
import * as d3 from 'd3';

class Treemap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      test: 1
    }
this.drawTreeMap = this.drawTreeMap.bin(this)
  }

  componentDidMount() {
    this.drawTreeMap();
    console.log(this.state.test) // works fine
  }

  drawTreeMap() {
    Promise.all([
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json")
    ])
    .then(function(data) {
      let kickstarter = data[0];
      let movie = data[1];
      let videoGamesSaleData = data[2];

      console.log(this.state.test)  // does not work (Unhandled Rejection (TypeError): Cannot read property 'state' of undefined)

</code>```

The first console.log(this.state.test) in the lifecycle method works, but the second one does not work.
Is it because d3 does not cooperate with react state, or did i make a foolish mistake?

Best regards!!!

答:
Can you try to return the Promise respond, as you can see on example : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all </p>

```<code>let promis = Promise.all([
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json")
    ])
    .then(function(data) {
      return data;
    });

console.log(promis[0]);
console.log(this.state.test)
</code>```

Body:
could someone please tell me why I cant access the react.state in my d3.js function.
I really cant figure out why.

import React, { Component } from 'react'
import * as d3 from 'd3';

class Treemap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      test: 1
    }
this.drawTreeMap = this.drawTreeMap.bin(this)
  }

  componentDidMount() {
    this.drawTreeMap();
    console.log(this.state.test) // works fine
  }

  drawTreeMap() {
    Promise.all([
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json")
    ])
    .then(function(data) {
      let kickstarter = data[0];
      let movie = data[1];
      let videoGamesSaleData = data[2];

      console.log(this.state.test)  // does not work (Unhandled Rejection (TypeError): Cannot read property 'state' of undefined)

The first console.log(this.state.test) in the lifecycle method works, but the second one does not work.
Is it because d3 does not cooperate with react state, or did i make a foolish mistake?

Best regards!!!

Body:
Can you try to return the Promise respond, as you can see on example : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

let promis = Promise.all([
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json")
    ])
    .then(function(data) {
      return data;
    });

console.log(promis[0]);
console.log(this.state.test)


问:
_curses.error: prefresh() returned ERR
```<code>for j in range(10):
    for i in range(0, 20000, conf.batch_size):
        x1 = Xtrain[0][i:i + conf.batch_size]
        x2 = Xtrain[1][i:i + conf.batch_size]
        y = ytrain[i:i + conf.batch_size]
        _, summaries, accc, loss = sess.run([train_step, train_summary_op, acc, cost],
                feed_dict={input_1: x1, input_2: x2, input_3: y, dropout_keep_prob: 1.0})
        time_str = datetime.datetime.now().isoformat()
        print("{}: loss {:g}, acc {:g}".format(time_str, loss, accc))
        train_summary_writer.add_summary(summaries)
    print("\nEvaluation:")
    accc = sess.run(acc, feed_dict={input_1: Xtest[0], input_2: Xtest[1], input_3: ytest, dropout_keep_prob: 1.0})
    print("test accuracy:", accc)
</code>```

Error：

Traceback (most recent call last):
    File "F:/python_workspace/intel/MPCNN/train.py", line 124, in
      feed_dict={input_1: x1, input_2: x2, input_3: y, dropout_keep_prob: 1.0})
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\wrappers\framework.py", line 411, in run
      self._run_call_count))
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\wrappers\local_cli_wrapper.py", line 212, in
  on_run_start
      self._run_start_response = self._launch_cli()
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\wrappers\local_cli_wrapper.py", line 366, in
  _launch_cli
      title_color=self._title_color)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 460, in run_ui
      self._dispatch_command(init_command)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 699, in _dispatch_com
  mand
      self._display_output(screen_output)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 1044, in _display_out
  put
      self._scroll_output(_SCROLL_HOME)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 1282, in _scroll_outp
  ut
      self._screen_render_nav_bar()
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 1295, in _screen_rend
  er_nav_bar
      self._max_x)
  _curses.error: prefresh() returned ERR

I don't know how to deal with it,please help me.

答: I don't know if it's the same thing, but for me the error was because Curses was trying to output beyond the range of the terminal window. By expanding my window, I no longer had the error. Now for the other errors....</p>

Title: _curses.error: prefresh() returned ERR

Body:
for j in range(10):
    for i in range(0, 20000, conf.batch_size):
        x1 = Xtrain[0][i:i + conf.batch_size]
        x2 = Xtrain[1][i:i + conf.batch_size]
        y = ytrain[i:i + conf.batch_size]
        _, summaries, accc, loss = sess.run([train_step, train_summary_op, acc, cost],
                feed_dict={input_1: x1, input_2: x2, input_3: y, dropout_keep_prob: 1.0})
        time_str = datetime.datetime.now().isoformat()
        print("{}: loss {:g}, acc {:g}".format(time_str, loss, accc))
        train_summary_writer.add_summary(summaries)
    print("\nEvaluation:")
    accc = sess.run(acc, feed_dict={input_1: Xtest[0], input_2: Xtest[1], input_3: ytest, dropout_keep_prob: 1.0})
    print("test accuracy:", accc)

Error：

Traceback (most recent call last):
    File "F:/python_workspace/intel/MPCNN/train.py", line 124, in
      feed_dict={input_1: x1, input_2: x2, input_3: y, dropout_keep_prob: 1.0})
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\wrappers\framework.py", line 411, in run
      self._run_call_count))
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\wrappers\local_cli_wrapper.py", line 212, in
  on_run_start
      self._run_start_response = self._launch_cli()
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\wrappers\local_cli_wrapper.py", line 366, in
  _launch_cli
      title_color=self._title_color)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 460, in run_ui
      self._dispatch_command(init_command)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 699, in _dispatch_com
  mand
      self._display_output(screen_output)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 1044, in _display_out
  put
      self._scroll_output(_SCROLL_HOME)
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 1282, in _scroll_outp
  ut
      self._screen_render_nav_bar()
    File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\debug\cli\curses_ui.py", line 1295, in _screen_rend
  er_nav_bar
      self._max_x)
  _curses.error: prefresh() returned ERR

I don't know how to deal with it,please help me.


问:
MongoDB/Mongoose query: How to get different sets of data based on a field's value
I'm using nodejs with mongoose library for my mongoDB interaction.

I'm building a landing page query (think Netflix page) and need to get ~15 results for each categories (think Comedy, Horror, Drama, ...).

It seems not like a great solution to send a query for each "category" and deal with the callback issues as well as a heavy request on the database for a simple page load...as illustrated below:

```<code>const categories = ['horror','drama','comedy']
let counterCallback = 0
let allShows = []
categories.map(category =>{
    Show.find({category: category},{limit: 15}, (err, shows)=>{
       if(shows){ allShows.push(shows)}
       allShows++
       if(allShows === categories.length){ return res.json(allShows) }
    })
})
</code>```

I was thinking maybe of making an $or request, but I can't limit for the number for each "or"s ...

```<code>const categories = ['horror','drama','comedy']
Show.find({
    $or:categories.map(category=> {return {category: category} })
},{limit: 10})
</code>```

How can I achieve a request that limits the number of results per "category"?

Thanks

答:
You can take advantage of MongoDB's aggregation-framework to run complex queries, try below query :

```<code>var categories = ['horror', 'comedy', 'drama']

Show.aggregate([
    /** This $match would help to  limit docs to particular categories, as each pipeline in facet stage has to iterate to all docs in collection for thrice as 3 categories given, So at least limiting docs to needed categories. */
    { $match: { category: { $in: categories } } },
    {
        $facet: {
            'horror': [{ $match: { category: 'horror' } }, { $limit: 1 }],
            'comedy': [{ $match: { category: 'comedy' } }, { $limit: 1 }],
            'drama': [{ $match: { category: 'drama' } }, { $limit: 1 }]
        }
    }])
</code>```

Test : MongoDB-Playground

Alternatively you can achieve that using $group as well :

```<code>Show.aggregate([
    { $match: { category: { $in: categories } } },
    { $group: { _id: '$category', shows: { $push: '$$ROOT' } } },
    { $project: { category: '$_id', _id: 0, shows: { $slice: ['$shows', 1] } } },
    /** Below two stages are optional  */
    { $group: { _id: '', data: { $push: '$$ROOT' } } },
    { $project: { _id: 0 } }
])
</code>```

Test : MongoDB-Playground

Body:
I'm using nodejs with mongoose library for my mongoDB interaction.

I'm building a landing page query (think Netflix page) and need to get ~15 results for each categories (think Comedy, Horror, Drama, ...).

It seems not like a great solution to send a query for each "category" and deal with the callback issues as well as a heavy request on the database for a simple page load...as illustrated below:

const categories = ['horror','drama','comedy']
let counterCallback = 0
let allShows = []
categories.map(category =>{
    Show.find({category: category},{limit: 15}, (err, shows)=>{
       if(shows){ allShows.push(shows)}
       allShows++
       if(allShows === categories.length){ return res.json(allShows) }
    })
})

I was thinking maybe of making an $or request, but I can't limit for the number for each "or"s ...

const categories = ['horror','drama','comedy']
Show.find({
    $or:categories.map(category=> {return {category: category} })
},{limit: 10})

How can I achieve a request that limits the number of results per "category"?

Thanks

Body:
You can take advantage of MongoDB's aggregation-framework to run complex queries, try below query :

var categories = ['horror', 'comedy', 'drama']

Show.aggregate([
    /** This $match would help to  limit docs to particular categories, as each pipeline in facet stage has to iterate to all docs in collection for thrice as 3 categories given, So at least limiting docs to needed categories. */
    { $match: { category: { $in: categories } } },
    {
        $facet: {
            'horror': [{ $match: { category: 'horror' } }, { $limit: 1 }],
            'comedy': [{ $match: { category: 'comedy' } }, { $limit: 1 }],
            'drama': [{ $match: { category: 'drama' } }, { $limit: 1 }]
        }
    }])

Test : MongoDB-Playground

Alternatively you can achieve that using $group as well :

Show.aggregate([
    { $match: { category: { $in: categories } } },
    { $group: { _id: '$category', shows: { $push: '$$ROOT' } } },
    { $project: { category: '$_id', _id: 0, shows: { $slice: ['$shows', 1] } } },
    /** Below two stages are optional  */
    { $group: { _id: '', data: { $push: '$$ROOT' } } },
    { $project: { _id: 0 } }
])

Test : MongoDB-Playground


问:
Explaining Python's '__enter__' and '__exit__'
I saw this in someone's code. What does it mean?

```<code>    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()
</code>```

```<code>from __future__ import with_statement#for python2.5

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s

print s
</code>```

答:
This is called context manager and I just want to add that similar approaches exist for other programming languages. Comparing them could be helpful in understanding the context manager in python.
Basically, a context manager is used when we are dealing with some resources (file, network, database) that need to be initialized and at some point, tear downed (disposed). In Java 7 and above we have automatic resource management that takes the form of:

```<code>//Java code
try (Session session = new Session())
{
  // do stuff
}
</code>```

Note that Session needs to implement AutoClosable or one of its (many) sub-interfaces.

In C#, we have using statements for managing resources that takes the form of:

```<code>//C# code
using(Session session = new Session())
{
  ... do stuff.
}
</code>```

In which Session should implement IDisposable.

In python, the class that we use should implement __enter__ and __exit__. So it takes the form of:

```<code>#Python code
with Session() as session:
    #do stuff
</code>```

And as others pointed out, you can always use try/finally statement in all the languages to implement the same mechanism. This is just syntactic sugar.

Body:
I saw this in someone's code. What does it mean?

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

from __future__ import with_statement#for python2.5

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s

print s

Body:
This is called context manager and I just want to add that similar approaches exist for other programming languages. Comparing them could be helpful in understanding the context manager in python.
Basically, a context manager is used when we are dealing with some resources (file, network, database) that need to be initialized and at some point, tear downed (disposed). In Java 7 and above we have automatic resource management that takes the form of:

//Java code
try (Session session = new Session())
{
  // do stuff
}

Note that Session needs to implement AutoClosable or one of its (many) sub-interfaces.

In C#, we have using statements for managing resources that takes the form of:

//C# code
using(Session session = new Session())
{
  ... do stuff.
}

In which Session should implement IDisposable.

In python, the class that we use should implement __enter__ and __exit__. So it takes the form of:

#Python code
with Session() as session:
    #do stuff

And as others pointed out, you can always use try/finally statement in all the languages to implement the same mechanism. This is just syntactic sugar.


问:
Git hook to detect if fetched repo contains file and stop merge
Although not ideal, our build process leaves our remote git repo in an "out-of-sync" state for a few minutes, where the source code doesn't match the compiled code / DB schema dump, which are committed to git.  We've explored ways to prevent this, but it's not possible to do it in the near future.

We'd like to implement a simple git hook that warns any developer when they've pulled down the repo in this state. It can be done simply by detecting the presence of one or more files. How would we implement a hook that runs on git merge (and thereby also git pull), which will stop the merge and print a terminal message if any of these files exist in the repo?

答:
There isn't a way to implement a hook which fails a merge in the general case.  There is a pre-merge-commit hook, but that only applies when the merge is not a fast forward.  Since most of your developers are probably going to be doing a fast-forward merge into their master branch, there's not going to be a way to perform this action.  There are likewise no hooks you can use to abort checkout, in case you were thinking of that.

You could use a server-side hook or CI check to prevent the submission of the code in this bad state, or you could make your local development environment setup or build script fail in this state as an alternative.


问:
pairing one picture to multiple pictures in folder
I have some pictures in the folder I want to pair so I can add them to my slide with iterative fashion. I want to pair pictures ending with mp ones to bp ones. One caveat is that there are multiple pictures ending with bp and bp so that adding logical check would be feasible.

lets say we have a pictures in the folder

I want to pair 1_birds_bp.png to other pictures starting with 1 and ending with mp

so that the pair should look like #expected result

```<code>('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_hawk_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_owl_mp.png')
</code>```

and for reptile group

```<code>('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_crocodile_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_snake_mp.png')
</code>```

So by following this post
I tried

```<code>def image_pairs(folder):
    bp, mp = [], []

    for image_path in glob.glob(folder + '/*.png'):
        if "bp" in image_path:
            bp.append(image_path)

        elif "mp" in image_path:
            mp.append(image_path)
    for pair in zip(bp, mp):
        print(pair)
        #yield pair
</code>```

but I can pair the only

```<code>('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\1_hawk_mp.png')
</code>```

how can achieve this ?

答:
You can check all combinations and pick the ones that match:

```<code>from itertools import combinations
from pathlib import Path
files = Path(folder).glob('*.png')
list_of_pairs = [(a, b) for a, b in combinations(files, 2)
                 if (a.name.startswith(b.name[0]) and (('mp' in a.name and 'bp' in b.name) or ('bp' in a.name and 'mp' in b.name))]
</code>```

Even better, use filter on itertools.combinations for custom pairwise checks.

Body:
I have some pictures in the folder I want to pair so I can add them to my slide with iterative fashion. I want to pair pictures ending with mp ones to bp ones. One caveat is that there are multiple pictures ending with bp and bp so that adding logical check would be feasible.

lets say we have a pictures in the folder

I want to pair 1_birds_bp.png to other pictures starting with 1 and ending with mp

so that the pair should look like #expected result

('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_hawk_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_owl_mp.png')

and for reptile group

('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_crocodile_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_snake_mp.png')

So by following this post
I tried

def image_pairs(folder):
    bp, mp = [], []

    for image_path in glob.glob(folder + '/*.png'):
        if "bp" in image_path:
            bp.append(image_path)

        elif "mp" in image_path:
            mp.append(image_path)
    for pair in zip(bp, mp):
        print(pair)
        #yield pair

but I can pair the only

('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\1_hawk_mp.png')

how can achieve this ?

Body:
You can check all combinations and pick the ones that match:

from itertools import combinations
from pathlib import Path
files = Path(folder).glob('*.png')
list_of_pairs = [(a, b) for a, b in combinations(files, 2)
                 if (a.name.startswith(b.name[0]) and (('mp' in a.name and 'bp' in b.name) or ('bp' in a.name and 'mp' in b.name))]

Even better, use filter on itertools.combinations for custom pairwise checks.


问:
How to remove None when iterating through a list in python
I have this two unequal lists and i'm using itertools to loop through them and i'm trying to use the filter function to  remove the None generated in List1 so that at the end of the day a contains only two elements instead of three (counting the none) but i keep getting this error: Type error: NoneType object is not iterable</p>

```<code>import itertools

List1  = [['a'],['b']]
List2 = ['A','b','C']

l = list(itertools.chain(*List1))
print(l)

for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
    filter(None, a)
    print(a,b)
</code>```

答:
```<code>import itertools as it

def grouper(inputs, n, fillvalue=None):
    iters = [iter(inputs)] * n
    interim = it.zip_longest(*iters, fillvalue=fillvalue)
    return interim

nums = range(23)
results = (list(grouper(nums, 4)))

finalanswer = []
for zipped in results:
    # non_none = tuple(filter(None, zipped))
    # unfortunately the line above filters 0 which is incorrect so instead use:
    non_none = tuple(filter(lambda x: x is not None, zipped))
    finalanswer.append(non_none)
print(finalanswer)
</code>```

The code above uses zip_longest to illustrate generating zipped iterations of 'n' lists, irrespective of whether a corresponding entry exists in a given list or not --- and then strips out 'None' values --- noting that FILTER considers None and 0 as equivalent, so you have to use the 'lambda' version.

Body:
I have this two unequal lists and i'm using itertools to loop through them and i'm trying to use the filter function to  remove the None generated in List1 so that at the end of the day a contains only two elements instead of three (counting the none) but i keep getting this error: Type error: NoneType object is not iterable

import itertools

List1  = [['a'],['b']]
List2 = ['A','b','C']

l = list(itertools.chain(*List1))
print(l)

for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
    filter(None, a)
    print(a,b)

Body:
import itertools as it

def grouper(inputs, n, fillvalue=None):
    iters = [iter(inputs)] * n
    interim = it.zip_longest(*iters, fillvalue=fillvalue)
    return interim

nums = range(23)
results = (list(grouper(nums, 4)))

finalanswer = []
for zipped in results:
    # non_none = tuple(filter(None, zipped))
    # unfortunately the line above filters 0 which is incorrect so instead use:
    non_none = tuple(filter(lambda x: x is not None, zipped))
    finalanswer.append(non_none)
print(finalanswer)

The code above uses zip_longest to illustrate generating zipped iterations of 'n' lists, irrespective of whether a corresponding entry exists in a given list or not --- and then strips out 'None' values --- noting that FILTER considers None and 0 as equivalent, so you have to use the 'lambda' version.


问:
How can we find out that if a replication job or normal replication is running at a particular time
How can we find out that if a replication job or normal replication is running at a particular time. Please,help to figure out.</p>

答:
In order to monitor replication you need to use the Replication Monitor tool.

The following article describes how to use this tool.

http://msdn.microsoft.com/en-us/library/ms151780(SQL.90).aspx

Cheers, John

OwnerDisplayName: John Sansom

ContentLicense: CC BY-SA 2.5


问:
The best way to store the following temporal data in DB
Imagine we have a set of entities each of which has its state: free, busy or broken. The state is specified for a day, for example, today on 2011-05-17 an entity E1 is free and tomorrow on 2011-05-18 it is busy.

There is a need to store ~10^5 entities for 1000 days. Which is the best way to do so?

I am thinking about 2 options:

represent each day as a character "0", "1" or "2" and store for every entity a string of 1000 characters

store each day with entity's state in a row, i.e. 1000 rows for an entity

The most important query for such data is: given start date and end date identify which entities are free.

Performance is of higher priority than storage.

All suggestions and comments are welcome.

答:
Depending on whether entities are more often free or not just store the dates when an entity is free or not.

Assuming you store the dates when the entity is not free then the search is where start date <= date and end_date >= date and any row matching that means that the entity is not free for that period


问:
Why can I not unpack two lists into a format string within a for loop?
I was trying to do a basic spinning animation using "\|/-" which went fine, but I wanted two on the same updating line. With one spinning clockwise and one spinning anti-clockwise.

Here is what I came up with:

```<code>animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1, animation_2:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()
</code>```

Which get the output:

"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1, animation_2:
ValueError: too many values to unpack (expected 2)"
```

<p>This example:</p>

```animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()
```

<p>Gets the output:</p>

<pre class="lang-none prettyprint-override"><code>"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1:
ValueError: not enough values to unpack (expected 2, got 1)"
</code>```

And this error massage I do understand. But I don't understand why I get an error message from the first example.

This example works fine:

```<code>animation_1 = ['\\', '|', '/', '-']
# animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1 in animation_1:
        print(f'\r      {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()
</code>```

Can some kind soul explain to me way the first code example doesn't work? Or if I'm missing some basic understanding of some concept of the language?
"too many values to unpack (expected 2)", it did get 2? What am I missing?

答:
I don't understand why I get an error message from the first example.

OK, let's walk through it. The relevant parts are that you have two lists of length 4, and then you tried to iterate over both of them with something like this:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

for i, j in a, b:
    ...
```

I'll use this code as an example because it's a bit simpler. There are two key points:

a, b creates a tuple containing the two lists. It's the same as if you wrote (a, b).

for i, j in something only works if each element of something is a sequence of length 2.

From there, it's quite straightforward: the elements of the tuple (a, b) are simply a and b themselves, which are sequences of length 4, not sequences of length 2. So, that's why there are too many values to unpack: 4 is too many.

Body:
I was trying to do a basic spinning animation using "\|/-" which went fine, but I wanted two on the same updating line. With one spinning clockwise and one spinning anti-clockwise.

Here is what I came up with:

animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1, animation_2:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()

Which get the output:

"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1, animation_2:
ValueError: too many values to unpack (expected 2)"

This example:

animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()

Gets the output:

"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1:
ValueError: not enough values to unpack (expected 2, got 1)"

And this error massage I do understand. But I don't understand why I get an error message from the first example.

This example works fine:

animation_1 = ['\\', '|', '/', '-']
# animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1 in animation_1:
        print(f'\r      {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()

Can some kind soul explain to me way the first code example doesn't work? Or if I'm missing some basic understanding of some concept of the language?
"too many values to unpack (expected 2)", it did get 2? What am I missing?

Body:
I don't understand why I get an error message from the first example.

OK, let's walk through it. The relevant parts are that you have two lists of length 4, and then you tried to iterate over both of them with something like this:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

for i, j in a, b:
    ...

I'll use this code as an example because it's a bit simpler. There are two key points:

a, b creates a tuple containing the two lists. It's the same as if you wrote (a, b).

for i, j in something only works if each element of something is a sequence of length 2.

From there, it's quite straightforward: the elements of the tuple (a, b) are simply a and b themselves, which are sequences of length 4, not sequences of length 2. So, that's why there are too many values to unpack: 4 is too many.