问:
Why does my program skip the first function? (Beginner C++)
I don't understand why getAges is being skipped.

```<code>    #include <iostream>
    #include <cctype>
    using namespace std;

    int getAges(int age, const int SIZE);
    char getChoice();
    void displayInOrder(int numbers[], const int SIZE, char choice);
    void displayInReverse(int numbers[], const int SIZE, char choice);

    int main()
    {
        const int SIZE = 5;
        int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
        char answer;
        int age;
        char choice;

            if (toupper(choice) == 'O')
        {
            displayInOrder(numbers, SIZE, choice);

        }
        else if (toupper(choice) == 'R')
        {
            displayInReverse(numbers, SIZE, choice);

        }
        else
        {
            cout << "Invalid entry! - Must be O or R\n\n";

        }
        if (toupper(answer) == 'Y')
        {
            system("cls");

            age = getAges(age, SIZE);
            choice = getChoice();
            displayInOrder(numbers, SIZE, choice);
            displayInReverse(numbers, SIZE, choice);

            cout << "Run program again (Y or N)?  ";
            cin >> answer;
            break;
        }
        else if (toupper(answer) == 'N')
        {
            return 0;
        }
        return 0;
    }

    int getAges(int age, const int SIZE)
    {
        cout << "Enter " << SIZE << " ages: \n\n";
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        return age;
    }

    char getChoice()
    {
        char choice;
        cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
        cin >> choice;

        return choice;

    }

    void displayInOrder(int numbers[], const int SIZE, char answer)
    {
        cout << "Here are the ages in order: \n\n";
        for (int i = 0; i < SIZE; i++)
        {
            cout << numbers[i] << endl;
        }
    }

    void displayInReverse(int numbers[], const int SIZE, char answer)
    {
        cout << "Here are the ages in reverse order: \n\n";
        for (int i = SIZE - 1; i >= 0; i--)
        {
            cout << numbers[i] << endl;
        }
  }
</code>```

答:
I started working on this before the OP updated the title to their original question about "while loops & break statements". However at the time I came across this question the OP had originally removed the while loops. I was looking over the provided functions to get an idea of what the OP was trying to do and this is what I have come up with.

First: while loops are exactly what you want here, but you want a specific type of while loop, a do-while loop in this case.

Next: There is no need for break statements if you know how to structure your do-while loop correctly.

Finally: I made some modifications to the OP's existing functions by changing or removing unnecessary parameter(s), return type(s) & code duplication. I removed a function that was no longer needed. I changed the output formatting of the messages to display a clean looking program. I also removed a bad practice of having using namespace std; in the global scope.

I did this to demonstrate to the OP how a while loop can be constructed without the need of break statements and that they were originally on the right track but needed a little bit of assistance to get on their way.

Here is the source code to a working program on what I think the OP was aiming to do.

```<code>#include <iostream>
#include <cctype>

void getAge( int& age );
void displayInOrder( int numbers[], const int SIZE);
void displayInReverse( int numbers[], const int SIZE );

int main() {
    const int SIZE = 5;
    int numbers[SIZE] = { 0 };
    char answer = '\0';
    int age = 0;
    char choice = '\0';

    std::cout << "========================================================================\n"
              << "This program will have the user enter in "
              << SIZE
              << " Ages. \nThen ask the user in which order to display the list of ages.\n"
              << "Finally the program will ask the user if they want to continue or not.\n"
              << "========================================================================\n\n";

    do {

        for ( int i = 0; i < SIZE; i++ ) {
            getAge( age );
            numbers[i] = age;
        }

        std::cout << "\nPlease enter 'O' for ordered or 'R' for reversed list.\n";
        std::cin >> choice;

        if ( toupper( choice ) == 'O' ) {
            displayInOrder( numbers, SIZE );
        }

        if ( toupper( choice ) == 'R' ) {
            displayInReverse( numbers, SIZE );
        }

        std::cout << "\nDo you want to run program again (Y/N)?";
        std::cin >> answer;

    } while ( toupper( answer ) == 'Y' );

    return 0;
}

void getAge( int& age ) {
    int temp;
    std::cout << "Enter an age: \n";
    std::cin >> temp;
    age = temp;
}

void displayInOrder( int numbers[], const int SIZE ) {
    std::cout << "\nHere are the ages in order: \n";
    for ( int i = 0; i < SIZE; i++ ) {
        std::cout << numbers[i] << std::endl;
    }
}

void displayInReverse( int numbers[], const int SIZE ) {
    std::cout << "\nHere are the ages in reverse order: \n";
    for ( int i = SIZE - 1; i >= 0; i-- ) {
        std::cout << numbers[i] << std::endl;
    }
}
</code>```

Body:
I don't understand why getAges is being skipped.

    #include <iostream>
    #include <cctype>
    using namespace std;

    int getAges(int age, const int SIZE);
    char getChoice();
    void displayInOrder(int numbers[], const int SIZE, char choice);
    void displayInReverse(int numbers[], const int SIZE, char choice);

    int main()
    {
        const int SIZE = 5;
        int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
        char answer;
        int age;
        char choice;

            if (toupper(choice) == 'O')
        {
            displayInOrder(numbers, SIZE, choice);

        }
        else if (toupper(choice) == 'R')
        {
            displayInReverse(numbers, SIZE, choice);

        }
        else
        {
            cout << "Invalid entry! - Must be O or R\n\n";

        }
        if (toupper(answer) == 'Y')
        {
            system("cls");

            age = getAges(age, SIZE);
            choice = getChoice();
            displayInOrder(numbers, SIZE, choice);
            displayInReverse(numbers, SIZE, choice);

            cout << "Run program again (Y or N)?  ";
            cin >> answer;
            break;
        }
        else if (toupper(answer) == 'N')
        {
            return 0;
        }
        return 0;
    }

    int getAges(int age, const int SIZE)
    {
        cout << "Enter " << SIZE << " ages: \n\n";
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        cin >> age;
        cout << endl;
        return age;
    }

    char getChoice()
    {
        char choice;
        cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
        cin >> choice;

        return choice;

    }

    void displayInOrder(int numbers[], const int SIZE, char answer)
    {
        cout << "Here are the ages in order: \n\n";
        for (int i = 0; i < SIZE; i++)
        {
            cout << numbers[i] << endl;
        }
    }

    void displayInReverse(int numbers[], const int SIZE, char answer)
    {
        cout << "Here are the ages in reverse order: \n\n";
        for (int i = SIZE - 1; i >= 0; i--)
        {
            cout << numbers[i] << endl;
        }
  }

Body:
I started working on this before the OP updated the title to their original question about "while loops & break statements". However at the time I came across this question the OP had originally removed the while loops. I was looking over the provided functions to get an idea of what the OP was trying to do and this is what I have come up with.

First: while loops are exactly what you want here, but you want a specific type of while loop, a do-while loop in this case.

Next: There is no need for break statements if you know how to structure your do-while loop correctly.

Finally: I made some modifications to the OP's existing functions by changing or removing unnecessary parameter(s), return type(s) & code duplication. I removed a function that was no longer needed. I changed the output formatting of the messages to display a clean looking program. I also removed a bad practice of having using namespace std; in the global scope.

I did this to demonstrate to the OP how a while loop can be constructed without the need of break statements and that they were originally on the right track but needed a little bit of assistance to get on their way.

Here is the source code to a working program on what I think the OP was aiming to do.

#include <iostream>
#include <cctype>

void getAge( int& age );
void displayInOrder( int numbers[], const int SIZE);
void displayInReverse( int numbers[], const int SIZE );

int main() {
    const int SIZE = 5;
    int numbers[SIZE] = { 0 };
    char answer = '\0';
    int age = 0;
    char choice = '\0';

    std::cout << "========================================================================\n"
              << "This program will have the user enter in "
              << SIZE
              << " Ages. \nThen ask the user in which order to display the list of ages.\n"
              << "Finally the program will ask the user if they want to continue or not.\n"
              << "========================================================================\n\n";

    do {

        for ( int i = 0; i < SIZE; i++ ) {
            getAge( age );
            numbers[i] = age;
        }

        std::cout << "\nPlease enter 'O' for ordered or 'R' for reversed list.\n";
        std::cin >> choice;

        if ( toupper( choice ) == 'O' ) {
            displayInOrder( numbers, SIZE );
        }

        if ( toupper( choice ) == 'R' ) {
            displayInReverse( numbers, SIZE );
        }

        std::cout << "\nDo you want to run program again (Y/N)?";
        std::cin >> answer;

    } while ( toupper( answer ) == 'Y' );

    return 0;
}

void getAge( int& age ) {
    int temp;
    std::cout << "Enter an age: \n";
    std::cin >> temp;
    age = temp;
}

void displayInOrder( int numbers[], const int SIZE ) {
    std::cout << "\nHere are the ages in order: \n";
    for ( int i = 0; i < SIZE; i++ ) {
        std::cout << numbers[i] << std::endl;
    }
}

void displayInReverse( int numbers[], const int SIZE ) {
    std::cout << "\nHere are the ages in reverse order: \n";
    for ( int i = SIZE - 1; i >= 0; i-- ) {
        std::cout << numbers[i] << std::endl;
    }
}


来源: stackexchange

问:
How do I get the Source IP of a SOAP requesting client machine?
how do you get source ip, username, password, etc... of the client machine that sends a soap request? is there any of these details that one can pull for logging purposes?

I am using Java to handle the incoming SOAP requests. The service simply adds 2 numbers and is working, but I just need to get some client details.

Thanks, Lavanya

答:
I have figured the solution like below -

```<code>@Endpoint
public class DataEndpoints {
....
....
     private HttpServletRequest httpServletRequest;

     @Autowired
     public void setRequest(HttpServletRequest request) {
         this.httpServletRequest = request;
     }

     @PayloadRoot(namespace = employeeNS, localPart = "syncRelation")
     @ResponsePayload
     public SyncRelationResponse dataSync(@RequestPayload SyncOrderRelation request) {
            String incoming = "IP Address -> " + this.httpServletRequest.getRemoteAddr();
     }
}
</code>```

By using the following method, I can directly access HttpServletRequest. And then I can access all data i need.

I hope it will help someone in this context.

ContentLicense: CC BY-SA 2.5

Body:
I have figured the solution like below -

@Endpoint
public class DataEndpoints {
....
....
     private HttpServletRequest httpServletRequest;

     @Autowired
     public void setRequest(HttpServletRequest request) {
         this.httpServletRequest = request;
     }

     @PayloadRoot(namespace = employeeNS, localPart = "syncRelation")
     @ResponsePayload
     public SyncRelationResponse dataSync(@RequestPayload SyncOrderRelation request) {
            String incoming = "IP Address -> " + this.httpServletRequest.getRemoteAddr();
     }
}

By using the following method, I can directly access HttpServletRequest. And then I can access all data i need.

I hope it will help someone in this context.

ContentLicense: CC BY-SA 3.0


问:
how to initializing a hash table in C
I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HSZ 127
#define HASHING(x) ((x)%HSZ)

struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

void init(void){
    int i;
    //memset(hash_table,0,sizeof(hash_table));
    for(i=0; i<HSZ; i++){
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
    }
}

void insert_hash(int value){
    int key = HASHING(value);
    struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));

    newNode->val = value;
    newNode->next = NULL;

    if(hash_table[key] == NULL){
        hash_table[key] = newNode;
    } else {
        newNode->next = hash_table[key];
        hash_table[key] = newNode;
    }
}

int delete_hash(int value){
    int key = HASHING(value);
    if (hash_table[key] == NULL)
        return 0;

    struct node_t *delNode = NULL;

    if (hash_table[key]->val == value){
        delNode = hash_table[key];
        hash_table[key] = hash_table[key]->next;
    } else {
        struct node_t *node = &hash_table[key];
        struct node_t *next = hash_table[key]->next;
        while (next){
            if (next->val == value){
                node->next = next->next;
                delNode = next;
                break;
            }
            node = next;
            next = node->next;
        }
    }
    return 1;
    free(delNode);
}
void PrintAllHashData()
{
    printf("###Print All Hash Data###\n");
    for (int i = 0; i < HSZ; i++){
        if (hash_table[i] != NULL){
            printf("idx : %d ", i);
            struct node_t *node = hash_table[i];
            while (node->next){
                printf("%d ", node->val);
                node = node->next;
            }
            printf("%d\n", node->val);
        }
    }
}

int main(void){
    init();
    insert_hash(1);
    insert_hash(3);
    insert_hash(128);
    PrintAllHashData();
}
</code>```

look at this code.

```<code>for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}
</code>```

The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.

then, I changed this line to

```<code>for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}
</code>```

but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'

I think that I don't understand clearly about struct in C.
How to fix this problem?

答:
```<code>struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];
</code>```

when you have *hash_table[HSZ], this varible hash_table is a pointer.   so whatever your action is , use hash_table-> ,syntax for pointer, mean point to somewhere.
a suggestion that when you use pointer you should always allocate memory hash_table[i] = malloc(sizeof(struct node_t));

```<code>struct node_t hash_table;
</code>```

but if you initilize your varible like this, you can use hash_table.val = 0

so the way of assign value depend on how you declare your varibles

Title: how to initializing a hash table in C

Body:
I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HSZ 127
#define HASHING(x) ((x)%HSZ)

struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

void init(void){
    int i;
    //memset(hash_table,0,sizeof(hash_table));
    for(i=0; i<HSZ; i++){
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
    }
}

void insert_hash(int value){
    int key = HASHING(value);
    struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));

    newNode->val = value;
    newNode->next = NULL;

    if(hash_table[key] == NULL){
        hash_table[key] = newNode;
    } else {
        newNode->next = hash_table[key];
        hash_table[key] = newNode;
    }
}

int delete_hash(int value){
    int key = HASHING(value);
    if (hash_table[key] == NULL)
        return 0;

    struct node_t *delNode = NULL;

    if (hash_table[key]->val == value){
        delNode = hash_table[key];
        hash_table[key] = hash_table[key]->next;
    } else {
        struct node_t *node = &hash_table[key];
        struct node_t *next = hash_table[key]->next;
        while (next){
            if (next->val == value){
                node->next = next->next;
                delNode = next;
                break;
            }
            node = next;
            next = node->next;
        }
    }
    return 1;
    free(delNode);
}
void PrintAllHashData()
{
    printf("###Print All Hash Data###\n");
    for (int i = 0; i < HSZ; i++){
        if (hash_table[i] != NULL){
            printf("idx : %d ", i);
            struct node_t *node = hash_table[i];
            while (node->next){
                printf("%d ", node->val);
                node = node->next;
            }
            printf("%d\n", node->val);
        }
    }
}

int main(void){
    init();
    insert_hash(1);
    insert_hash(3);
    insert_hash(128);
    PrintAllHashData();
}

look at this code.

for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}

The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.

then, I changed this line to

for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}

but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'

I think that I don't understand clearly about struct in C.
How to fix this problem?

Body:
struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

when you have *hash_table[HSZ], this varible hash_table is a pointer.   so whatever your action is , use hash_table-> ,syntax for pointer, mean point to somewhere.
a suggestion that when you use pointer you should always allocate memory hash_table[i] = malloc(sizeof(struct node_t));

struct node_t hash_table;

but if you initilize your varible like this, you can use hash_table.val = 0

so the way of assign value depend on how you declare your varibles


问:
ruby/bundler seeming to fail to derive dependencies
I am getting this error when I run "bundle install"

```<code>Could not find gem 'febeling-rubyzip (>= 0, runtime)' in any of the gem sources listed in your Gemfile.
</code>```

My Gemfile looks like this

```<code>source 'http://rubygems.org'

gem 'rails'

gem "authlogic", :git => "git://github.com/binarylogic/authlogic.git"
gem "mechanize"
gem "hpricot"
gem "sqlite3-ruby"
gem "daemons"

gem 'sqlite3-ruby', :require => 'sqlite3'

gem "nokogiri"
gem "roo"
gem "zip"
gem "spreadsheet"
gem "builder"
gem "gimite-google-spreadsheet-ruby"
gem "febeling-rubyzip"

#gem "savon", "=0.7.9"
gem "savon"

#devise is required for rails_admin, but not used
gem 'devise'
gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'

gem 'febeling-rubyzip'

group :development, :test do
  gem "rcov"
  gem "capistrano"
end

group :development do
  gem "ruby-debug"
  gem "httpclient"
end
</code>```

Any thoughts/tips would be greatly appreciarted.

Thanks, Chris

PS I am using rvm with per project gemsets.  Whats probably quite pertinent is that I just did a "rvm gemset empty" and remove Gemfile.lock to do a clean install of the project's gems - things seemed ok prior to that :(

答: Replace 'febeling-rubyzip' with 'rubyzip'. The new way of naming the gems has changed and it does not have the creator's username (github username) attached to it. </p>

Body:
I am getting this error when I run "bundle install"

Could not find gem 'febeling-rubyzip (>= 0, runtime)' in any of the gem sources listed in your Gemfile.

My Gemfile looks like this

source 'http://rubygems.org'

gem 'rails'

gem "authlogic", :git => "git://github.com/binarylogic/authlogic.git"
gem "mechanize"
gem "hpricot"
gem "sqlite3-ruby"
gem "daemons"

gem 'sqlite3-ruby', :require => 'sqlite3'

gem "nokogiri"
gem "roo"
gem "zip"
gem "spreadsheet"
gem "builder"
gem "gimite-google-spreadsheet-ruby"
gem "febeling-rubyzip"

#gem "savon", "=0.7.9"
gem "savon"

#devise is required for rails_admin, but not used
gem 'devise'
gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'

gem 'febeling-rubyzip'

group :development, :test do
  gem "rcov"
  gem "capistrano"
end

group :development do
  gem "ruby-debug"
  gem "httpclient"
end

Any thoughts/tips would be greatly appreciarted.

Thanks, Chris

PS I am using rvm with per project gemsets.  Whats probably quite pertinent is that I just did a "rvm gemset empty" and remove Gemfile.lock to do a clean install of the project's gems - things seemed ok prior to that :(


问:
Confusing documentation of flock(2)

If a process uses open(2) (or similar) to obtain more than one
  descriptor for the same file, these descriptors are treated
  independently by flock(). An attempt to lock the file using one of
  these file descriptors may be denied by a lock that the calling
  process has already placed via another descriptor.

If flock() treats the descriptors independently, why locking the file using one of the file descriptors would be denied by a lock placed via another descriptor? What does independent here mean?

Also if I unlock one of the descriptor, would other descriptors unlock as well?

答:
treated independently by flock() means that flock() will not "ask" one descriptor, when attempting to modify the other. However, it doesn't mean they are truly independent. If flock() tries to lock one, while the other is already locked, this attempt may block.

Think of it as 2-levels mechanism. flock() looks at only one descriptor at a time, but eventually, upon the lock attempt, the system tries to move to the dipper level and actually lock, and there the problem occurs.

Also if I unlock one of the descriptor, would other descriptors unlock as well?

I'm not sure. This quote (below) states that this indeed is the case if a file has multiple descriptors from fork(2), dup(2). However there is nothing that says so in the 2nd paragraph that treats multiple open(2) which leads me to believe that it is just not a good thing to do :)

From here:

Locks created by flock() are associated with an open file description
         (see open(2)).  This means that duplicate file descriptors (created
         by, for example, fork(2) or dup(2)) refer to the same lock, and this
         lock may be modified or released using any of these file descriptors.
         Furthermore, the lock is released either by an explicit LOCK_UN
         operation on any of these duplicate file descriptors, or when all
         such file descriptors have been closed.

If a process uses open(2) (or similar) to obtain more than one file
         descriptor for the same file, these file descriptors are treated
         independently by flock().  An attempt to lock the file using one of
         these file descriptors may be denied by a lock that the calling
         process has already placed via another file descriptor.

Title: Confusing documentation of flock(2)


问:
Laravel is not working with my server php version by .htaccess file
My server default php version is 5.6. But my laravel version is working with php 7.0

My hosting provider gives me a .htaccess file

```<code><IfModule mime_module>
  AddType application/x-httpd-ea-php70 .php .php7 .phtml
</IfModule>
</code>```

if I place this file in domain root and phpinfo() showing my server version is 7.0

if I remove this .htaccess file server back to my default version php 5.6

But when I make command composer update for laravel. An error message showing like:

your php version is 5.6. laravel need php 7.0

that means laravel cannot read my .htaccess file

thanks in advance.

答:
first you have to locate where is php7 located. Try whereis php

It would provide you lists of php binaries. Find one which most looks like php7 (could be like /opt/bin/7.0/bin/php)

Create an alias with shell command `alias php='/opt/bin/7.0/bin/php'

Try it

If it works - just add this shell command to your ~/.bashrc

Body:
My server default php version is 5.6. But my laravel version is working with php 7.0

My hosting provider gives me a .htaccess file

<IfModule mime_module>
  AddType application/x-httpd-ea-php70 .php .php7 .phtml
</IfModule>

if I place this file in domain root and phpinfo() showing my server version is 7.0

if I remove this .htaccess file server back to my default version php 5.6

But when I make command composer update for laravel. An error message showing like:

your php version is 5.6. laravel need php 7.0

that means laravel cannot read my .htaccess file

thanks in advance.


问:
how to prevent service to run again if already running android
On click of a button I want to start service using method startService(new Intent(currentActivity.this,MyService.class)) but if service is running I don't want to call  this method to avoid run service that is already running.How this is possible.I am using both Intent service and Service in same project and want to apply same condition for both.

答:
Whenever we start any service from any activity , Android system calls the service's onStartCommand() method And If the service is not already running, the system first calls onCreate(), and then it calls onStartCommand().

So mean to say is that android service start's only once in its lifecycle and keep it running till stopped.if any other client want to start it again then only onStartCommand() method will invoked all the time.


问:
Fast row deletion in numpy
I am working with a big numpy matrix (approximately 75k rows of 2 integers each) from which I have to delete some rows. I would like to know if there is a fast way to delete a row without regenerating the whole array i.e. is there a function the change just the "mask" (or whatever is called) of the matrix, without effectively delete the row in memory? I could then regenerate a clean matrix after I delete all the proper rows.</p>

答:
The fast way to select rows from an array is with a slice, which produces a view.  But that requires a regular pattern like 'every-nth' row.  Any other select produces a copy.

```<code>x[::10,:]   # view
x[[1,3,6,10,20],:]   # copy
x[[True,False,False,True,False,...],:]   # copy
</code>```

np.delete lets you specify which rows to remove, but it ends up, one or other, making a copy that contains the remaining rows.  It's a complex function using different methods depending on what you specify.  But in many cases it constructs a mask as @jakevdp demonstrates.

So the fastest way  to delete a bunch of rows is to delete them (or select their complement) all at once.  Deleting one at a time is the slow way.

Title: Fast row deletion in numpy

Body:
The fast way to select rows from an array is with a slice, which produces a view.  But that requires a regular pattern like 'every-nth' row.  Any other select produces a copy.

x[::10,:]   # view
x[[1,3,6,10,20],:]   # copy
x[[True,False,False,True,False,...],:]   # copy

np.delete lets you specify which rows to remove, but it ends up, one or other, making a copy that contains the remaining rows.  It's a complex function using different methods depending on what you specify.  But in many cases it constructs a mask as @jakevdp demonstrates.

So the fastest way  to delete a bunch of rows is to delete them (or select their complement) all at once.  Deleting one at a time is the slow way.


问:
Backspace is not clearing the field in mozilla browser
I have the input box which allows only numeric.In chrome and firefox it allows only numeric but can't delete the number in using backspace in mozilla.

$(document).ready(function () {
$('#price').keypress(function(event) {
  if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
   event.preventDefault();
  }
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'></code>```

答:
Usually keypress only detects the printable keys, but the current version of Mozilla is able to detect backspace as well. Use the keydown event instead.

Demo

$(document).ready(function() {
  $('#price').keydown(function(event) {
    console.log(event.which);
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
      event.preventDefault();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'></code>```

Another approach Important!

Using above approach you will also have to check for other special keys like arrow keys and delete keys, not to mention if . is placed correctly and only once.

Another approach could be to simply remove non-numeric characters from the string on keyup

$(document).ready(function() {
  $('#price').keyup(function(event) {
     this.value = this.value.replace( /[^0-9.]/g, "" );
     this.value = this.value.split(".").reduce((a,b,i)=> i > 1 ? a+b : a+"."+b );
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'></code>```

Body:
I have the input box which allows only numeric.In chrome and firefox it allows only numeric but can't delete the number in using backspace in mozilla.

$(document).ready(function () {
$('#price').keypress(function(event) {
  if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
   event.preventDefault();
  }
 });
});

<input type='text' id='price'>

Body:
Usually keypress only detects the printable keys, but the current version of Mozilla is able to detect backspace as well. Use the keydown event instead.

Demo

$(document).ready(function() {
  $('#price').keydown(function(event) {
    console.log(event.which);
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
      event.preventDefault();
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>

Another approach Important!

Using above approach you will also have to check for other special keys like arrow keys and delete keys, not to mention if . is placed correctly and only once.

Another approach could be to simply remove non-numeric characters from the string on keyup

$(document).ready(function() {
  $('#price').keyup(function(event) {
     this.value = this.value.replace( /[^0-9.]/g, "" );
     this.value = this.value.split(".").reduce((a,b,i)=> i > 1 ? a+b : a+"."+b );
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>


问:
Duplicate some lines with some replaced word in the same file by vim
I have a text file with some lines, I want to duplicate all lines at the end of file with some replaced word.

for example:

This is my text:

```<code>This is the first line
This is the second line
This is the third line
This is the forth line
This is the fifth line
</code>```

I would like to duplicate the lines 2, 3 and 4 and replace the word the with my in these lines.

So I would like it to be this text instead:

```<code>This is the first line
This is the second line
This is the third line
This is the forth line
This is the fifth line
This is the first line
This is my second line
This is my third line
This is my forth line
This is the fifth line
</code>```

Is this possible to do in vim ?

答:
Step one copy the text.  Place your cursor over the first line and in command mode (not insert mode) press

```<code>y5y
</code>```

Which yanks 5 line, then press

```<code>G
</code>```

Which will take you to the bottom line and press

```<code>p
</code>```

To put the yanked text below the current line.

Then

```<code>:7,9s/the/my/g
</code>```

This will look at lines 8-11 and replace the word 'the' with 'my'.

As always with vim there are many ways to do a job, but for your question this would be one way, it's kind of simplistic, so if  there are a few more details about the use case, this answer can be augmented to suit the needs.

Body:
I have a text file with some lines, I want to duplicate all lines at the end of file with some replaced word.

for example:

This is my text:

This is the first line
This is the second line
This is the third line
This is the forth line
This is the fifth line

I would like to duplicate the lines 2, 3 and 4 and replace the word the with my in these lines.

So I would like it to be this text instead:

This is the first line
This is the second line
This is the third line
This is the forth line
This is the fifth line
This is the first line
This is my second line
This is my third line
This is my forth line
This is the fifth line

Is this possible to do in vim ?

Body:
Step one copy the text.  Place your cursor over the first line and in command mode (not insert mode) press

y5y

Which yanks 5 line, then press

G

Which will take you to the bottom line and press

p

To put the yanked text below the current line.

Then

:7,9s/the/my/g

This will look at lines 8-11 and replace the word 'the' with 'my'.

As always with vim there are many ways to do a job, but for your question this would be one way, it's kind of simplistic, so if  there are a few more details about the use case, this answer can be augmented to suit the needs.


问:
Extend touch area on iPhone X in landscape mode
If a UIViewController is launched in landscape mode, even though the home indicator is not on the right side, still the rightmost 44 points on the screen do not respond to touches. I am wondering what is the purpose of disabling those pixels for touches and is there a way to extend the touch area on the right?

答:
safearealayoutguide

When the view is visible onscreen, this guide reflects the portion of
  the view that is not covered by navigation bars, tab bars, toolbars,
  and other ancestor views. (In tvOS, the safe area reflects the area
  not covered the screen's bezel.) If the view is not currently
  installed in a view hierarchy, or is not yet visible onscreen, the
  layout guide edges are equal to the edges of the view.

As you try to add objects beyond safe area your content get chance clip by Device Bazels.

Example:
When you add button outside safe area as

```<code>let buttonOutsideSafeArea = UIButton(frame: CGRect(x: 0, y: 100, width: 44, height: 40))
buttonOutsideSafeArea.backgroundColor = .red
self.view.addSubview(buttonOutsideSafeArea)
</code>```

When you rotate right on device.

But it will get clipped(by Top Notch) when you rotate left

Hence try to avoid adding objects beyond safe Area

Body:
safearealayoutguide

When the view is visible onscreen, this guide reflects the portion of
  the view that is not covered by navigation bars, tab bars, toolbars,
  and other ancestor views. (In tvOS, the safe area reflects the area
  not covered the screen's bezel.) If the view is not currently
  installed in a view hierarchy, or is not yet visible onscreen, the
  layout guide edges are equal to the edges of the view.

As you try to add objects beyond safe area your content get chance clip by Device Bazels.

Example:
When you add button outside safe area as

let buttonOutsideSafeArea = UIButton(frame: CGRect(x: 0, y: 100, width: 44, height: 40))
buttonOutsideSafeArea.backgroundColor = .red
self.view.addSubview(buttonOutsideSafeArea)

When you rotate right on device.

But it will get clipped(by Top Notch) when you rotate left

Hence try to avoid adding objects beyond safe Area


问:
Not able to run my cucumber script through command Prompt
I have written a script to run my web application.Below is the structure of my project

Feature: It has the code which will run the program in Web application.

Objects: It contains all the objects.

Reusable: It contains all the reusable code.

Runner: It contains Runner file which will run the feature.

User Story: Which contains all the ".feature" file.

I want to run this code in Command Prompt.. Can anyone help me on this? I am new to this

答:
You can use the CLI runner, see the documentation here

From the documentation:

```<code>Usage: java cucumber.api.cli.Main [options] [[[FILE|DIR][:LINE[:LINE]*] ]+ | @FILE ]

Options:

  -g, --glue PATH                        Where glue code (step definitions, hooks

Feature path examples:
  <path>                                 Load the files with the extension ".feature"
                                         for the directory <path
                                         and its sub directories.
  <path>/<name>.feature                  Load the feature file <path>/<name>.feature
                                         from the file system.
  classpath:<path>/<name>.feature        Load the feature file <path>/<name>.feature
                                         from the classpath.
  <path>/<name>.feature:3:9              Load the scenarios on line 3 and line 9 in
                                         the file <path>/<name>.feature.
  @<path>/<file>                         Parse <path>/<file> for feature paths generated
                                         by the rerun formatter.
</code>```

Body:
You can use the CLI runner, see the documentation here

From the documentation:

Usage: java cucumber.api.cli.Main [options] [[[FILE|DIR][:LINE[:LINE]*] ]+ | @FILE ]

Options:

  -g, --glue PATH                        Where glue code (step definitions, hooks

Feature path examples:
  <path>                                 Load the files with the extension ".feature"
                                         for the directory <path
                                         and its sub directories.
  <path>/<name>.feature                  Load the feature file <path>/<name>.feature
                                         from the file system.
  classpath:<path>/<name>.feature        Load the feature file <path>/<name>.feature
                                         from the classpath.
  <path>/<name>.feature:3:9              Load the scenarios on line 3 and line 9 in
                                         the file <path>/<name>.feature.
  @<path>/<file>                         Parse <path>/<file> for feature paths generated
                                         by the rerun formatter.


问:
Adding Overlays to Videos export as a video in android
So i have a video for eg. a race car video and i created a overlay view (transparent relative layout) which includes some progress bar related to speed and performance now i need to export full video as seen in this view so can anyone please help me i have gone through ffmpeg,opencv but no success.

Similar Ios Overlay

答:
You will be able to achieve using opencv org.bytedeco.javacpp, i used FFmpegFrameGrabber for garbing frame and FFmpegFrameRecorder recording this images back to mp4 with the same audio codex.

Dependencies needed:

```<code>    compile group: 'org.bytedeco', name: 'javacv', version: '1.4'
    compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.0-1.4', classifier: 'android-arm'
    compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.4.1-1.4', classifier: 'android-arm'
</code>```

Body:
You will be able to achieve using opencv org.bytedeco.javacpp, i used FFmpegFrameGrabber for garbing frame and FFmpegFrameRecorder recording this images back to mp4 with the same audio codex.

Dependencies needed:

    compile group: 'org.bytedeco', name: 'javacv', version: '1.4'
    compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.0-1.4', classifier: 'android-arm'
    compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.4.1-1.4', classifier: 'android-arm'


问:
Why doesn't this crash?
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

```<code>static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}
</code>```

I'm expecting this code to crash.  Instead, it logs:

```<code>2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:
</code>```

However, if I change the NSLog() to:

```<code>NSLog(@"static: %s", [staticString UTF8String]);
</code>```

Then it does crash.

edit a bit more info:

After draining the pool:

```<code>NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes
</code>```

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...

答:
My best guess for what you're seeing is that NSLog() copies the format string (probably as a mutable copy), and then parses the arguments. Since you've dealloc'd staticString, it just so happens that the copy of the format string is being placed into the same location. This is causing you to see the "static: static: " output that you described. Of course, this behavior is undefined - there's no guarantee it will always use the same memory location for this.

On the other hand, your NSLog(@"static: %s", [staticString UTF8String]) is accessing staticString before the format string copy happens, which means it's accessing garbage memory.

Title: Why doesn't this crash?

Body:
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}

I'm expecting this code to crash.  Instead, it logs:

2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:

However, if I change the NSLog() to:

NSLog(@"static: %s", [staticString UTF8String]);

Then it does crash.

edit a bit more info:

After draining the pool:

NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...


问:
vba code for copying a string if it contains a certain value
Hi I'm looking on how to edit my code so that instead of turning the font colour of the start of the string red and bold, it pastes these strings into another worksheet, however ever time I try to edit it I always end up with a run time error. Any help would be appreciated, here is my current code:</p>

```<code>Sub colorText()

    Dim cl As Range
    Dim startPos As Integer
    Dim totalLen As Integer
    Dim searchText As String
    Dim endPos As Integer
    Dim testPos As Integer

     ' specify text to search.
     searchText = "(9)"

    ' loop trough all cells in selection/range
     For Each cl In Range("A:A")
      totalLen = Len(searchText)
      startPos = InStr(cl, searchText)
      testPos = 0

      Do While startPos > testPos
         With cl.Characters(startPos, totalLen).Font
          .FontStyle = "Bold"
          .ColorIndex = 3
         End With

    endPos = startPos + totalLen
    testPos = testPos + endPos
     startPos = InStr(testPos, cl, searchText, vbTextCompare)
  Loop

Next cl

End Sub
</code>```

答:
So according to what you said I assume this is what you are looking for?
Your current code doesn't really make sense if the position of the SearchString within the String to search is not relevant as you said.

Sub CopyMatchedValuesToSheet()

Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRowSource As Long, i As Long
Dim SearchString As String
Dim cell As Range

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")

SearchString = "2" ' Set SearchString value or use the one below if you want to change it each time

'SearchString = Application.InputBox("Give a string", "SearchString", Type:=2)

i = 1

With ws1
    LastRowSource = .Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row

    For Each cell In .Range("A1:A" & LastRowSource) ' Change to A2 if it has header
        If InStr(cell.Value, SearchString) > 0 Then
            ws2.Cells(i + 1, 1).Value = cell.Value
            i = i + 1
        End If
    Next cell
End With

End Sub```
</div>
</div>
</p>

<p>You can use the following to clear the Sheet2 each time just change the code to:</p>

```Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
ws2.Cells.Clear
```

Body:
Hi I'm looking on how to edit my code so that instead of turning the font colour of the start of the string red and bold, it pastes these strings into another worksheet, however ever time I try to edit it I always end up with a run time error. Any help would be appreciated, here is my current code:

Sub colorText()

    Dim cl As Range
    Dim startPos As Integer
    Dim totalLen As Integer
    Dim searchText As String
    Dim endPos As Integer
    Dim testPos As Integer

     ' specify text to search.
     searchText = "(9)"

    ' loop trough all cells in selection/range
     For Each cl In Range("A:A")
      totalLen = Len(searchText)
      startPos = InStr(cl, searchText)
      testPos = 0

      Do While startPos > testPos
         With cl.Characters(startPos, totalLen).Font
          .FontStyle = "Bold"
          .ColorIndex = 3
         End With

    endPos = startPos + totalLen
    testPos = testPos + endPos
     startPos = InStr(testPos, cl, searchText, vbTextCompare)
  Loop

Next cl

End Sub

Body:
So according to what you said I assume this is what you are looking for?
Your current code doesn't really make sense if the position of the SearchString within the String to search is not relevant as you said.

Sub CopyMatchedValuesToSheet()

Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRowSource As Long, i As Long
Dim SearchString As String
Dim cell As Range

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")

SearchString = "2" ' Set SearchString value or use the one below if you want to change it each time

'SearchString = Application.InputBox("Give a string", "SearchString", Type:=2)

i = 1

With ws1
    LastRowSource = .Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row

    For Each cell In .Range("A1:A" & LastRowSource) ' Change to A2 if it has header
        If InStr(cell.Value, SearchString) > 0 Then
            ws2.Cells(i + 1, 1).Value = cell.Value
            i = i + 1
        End If
    Next cell
End With

End Sub

You can use the following to clear the Sheet2 each time just change the code to:

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
ws2.Cells.Clear


问:
cannot access the classes in the package
I have the following directory structure :

MessManagement is the parent directory.

Under that i have 3 directories :
student , messconvener,messmanager

The student directory contains the Student.java and Student.class files. The messconvener contains the MessConvener.java this requires the Student class as MessConvener is extended from Student itself.

How should i do the packaging of the classes....??

What i have tried so far.

Code :

This is Student.java

```<code>package MessManagement;
import java.sql.*;

public class Student
{

}
</code>```

This is MessConvener.java

```<code>package MessManagement;
import MessManagement.student.Student;
public class MessConvener extends Student
{

}
</code>```

But this does not seem to work.Error Meesage :

MessConvener.java:2: error: package MessManagement.student does not exist
import MessManagement.student.Student;
                             ^
MessConvener.java:3: error: cannot find symbol
public class MessConvener extends Student
                                  ^
  symbol: class Student
2 errors

答: I recently had this issue and it was because I had a class file in the same directory as the java file that I was compiling. You need to delete all .class files in that directory. </p>

Body:
I have the following directory structure :

MessManagement is the parent directory.

Under that i have 3 directories :
student , messconvener,messmanager

The student directory contains the Student.java and Student.class files. The messconvener contains the MessConvener.java this requires the Student class as MessConvener is extended from Student itself.

How should i do the packaging of the classes....??

What i have tried so far.

Code :

This is Student.java

package MessManagement;
import java.sql.*;

public class Student
{

}

This is MessConvener.java

package MessManagement;
import MessManagement.student.Student;
public class MessConvener extends Student
{

}

But this does not seem to work.Error Meesage :

MessConvener.java:2: error: package MessManagement.student does not exist
import MessManagement.student.Student;
                             ^
MessConvener.java:3: error: cannot find symbol
public class MessConvener extends Student
                                  ^
  symbol: class Student
2 errors


问:
How to group subarray data using multiple column values and individually sum the remaining column values?
How can I group by Source and date then SUM Pageviews and revenue this array below

```<code>Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6000
            [Pageviews] => 12,214
            [Revenue] => 25
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1015
            [Revenue] => 10
        )
    [2] => Array
          (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )

    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )

    [4] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 1600
            [Pageviews] => 11,445
            [Revenue] => 5
        )
     [5] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 700
            [Pageviews] => 7,445
            [Revenue] => 8
        )
)
</code>```

Expected Result

```<code>Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6600
            [Pageviews] => 13,229
            [Revenue] => 35
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )
    [2] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )
    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 2,300
            [Pageviews] => 18,890
            [Revenue] => 35
        )
)
</code>```

答:
Here is the function you need. Cheers...</p>

```<code>function combineAndSumUp ($myArray = []) {

    $finalArray = Array ();

    foreach ($myArray as $nkey => $nvalue) {

        $has = false;
        $fk = false;

        // Remove comma from numbers
        $nvalue['Pageviews'] = str_replace(",","",$nvalue["Pageviews"]);

        foreach ($finalArray as $fkey => $fvalue) {
            if ( ($fvalue['Date'] == $nvalue['Date']) && ($fvalue['Source'] == $nvalue['Source']) ) {
                $has = true;
                $fk = $fkey;
                break;
            }
        }

        if ( $has === false ) {
            $finalArray[] = $nvalue;
        } else {
            $finalArray[$fk]['visits'] += $nvalue['visits'];
            $finalArray[$fk]['Pageviews'] += $nvalue['Pageviews'];
            $finalArray[$fk]['Revenue'] += $nvalue['Revenue'];
        }

    }

    return $finalArray;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I group by Source and date then SUM Pageviews and revenue this array below

Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6000
            [Pageviews] => 12,214
            [Revenue] => 25
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1015
            [Revenue] => 10
        )
    [2] => Array
          (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )

    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )

    [4] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 1600
            [Pageviews] => 11,445
            [Revenue] => 5
        )
     [5] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 700
            [Pageviews] => 7,445
            [Revenue] => 8
        )
)

Expected Result

Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6600
            [Pageviews] => 13,229
            [Revenue] => 35
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )
    [2] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )
    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 2,300
            [Pageviews] => 18,890
            [Revenue] => 35
        )
)

Body:
Here is the function you need. Cheers...

function combineAndSumUp ($myArray = []) {

    $finalArray = Array ();

    foreach ($myArray as $nkey => $nvalue) {

        $has = false;
        $fk = false;

        // Remove comma from numbers
        $nvalue['Pageviews'] = str_replace(",","",$nvalue["Pageviews"]);

        foreach ($finalArray as $fkey => $fvalue) {
            if ( ($fvalue['Date'] == $nvalue['Date']) && ($fvalue['Source'] == $nvalue['Source']) ) {
                $has = true;
                $fk = $fkey;
                break;
            }
        }

        if ( $has === false ) {
            $finalArray[] = $nvalue;
        } else {
            $finalArray[$fk]['visits'] += $nvalue['visits'];
            $finalArray[$fk]['Pageviews'] += $nvalue['Pageviews'];
            $finalArray[$fk]['Revenue'] += $nvalue['Revenue'];
        }

    }

    return $finalArray;
}


答:
It's happening because you using a wrong way to avoid backspace. There backspace 8 as key code so you have avoided this in prevent default.use this code instead.</p>

```<code>$(document).ready(function () {
$('#price').keypress(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});
</code>```

Title: Backspace is not clearing the field in mozilla browser

Body:
It's happening because you using a wrong way to avoid backspace. There backspace 8 as key code so you have avoided this in prevent default.use this code instead.

$(document).ready(function () {
$('#price').keypress(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});


问:
Use Connect or pass data as props to children
I am new to react and redux. I have a scenario where there are nested components like this.

A > B > C > D

There is a property used in A component and it will be used in D component. So, I have two approaches:

Get state from redux store in component A and then pass it along as props to all it's child components even though it will be used only in D component.

I should connect to redux store in component D and fetch that property from there.

What is the correct approach?

答:
As Dan Abramov, author of redux says in this issue

Both approaches of passing props down to children or connecting them
  to the store are appropriate, however having nested connect()
  components is actually going to give you more performance. The
  downside is they're slightly more coupled to the application and
  slightly harder to test, but that may not be a big issue.

He has also articulated a nice rule of thumb to follow on reddit

I do it this way:

Start by using one container and several presentational components

As presentational component tree grows, “middle” components start to    pass too many props down

At this point, I wrap some leaf components into containers so that    “middle” components don’t need to accept and pass down props that are
  completely unrelated to them

Repeat

He has even tweeted regarding this:

Try to keep your presentation components separate. Create container
  components by connecting them when it’s convenient.Whenever you feel like you’re duplicating code in parent components to provide data for same kinds of children, time to extract a container.

So in simple words:

You can use connect() at any level. Doing so makes the component smart, since it knows where its props come from. A dumb component just has props, and they could come from anywhere. A smart component is coupled to redux; a dumb component is not.

UPDATE: react-redux v7 and above

The same concept applies to useSelectors too. You can receive data in a container component and pass on to your presentational components, if multiple of its children make use of the same data

If however the data used by the children is different, you can choose to use useSelector individually within the child component. This will make sure that only those components re-render which actually need to


问:
Disable layout in ASP.NET MVC?
In MonoRail you can just CancelLayout() to not render the layout. In ASP.NET MVC, the only way to affect the layout seems to be to pass the layout name into the View() method like View("myview", "mylayout"); only it seems that passing null or an empty string doesn't do what I'd want.

I ended up creating an empty layout that just rendered the content, but that seems silly.

"Not Render the layout" means exactly that. In the web forms view engine they call layouts "master pages". I want to render just my action's view and not surround it with the master page.

答:
In MVC 3, you can remove the master layout code with:</p>

```<code>   @{
    Layout = "";
    }
</code>```

OwnerDisplayName: aaronjensen

Title: Disable layout in ASP.NET MVC?

LastEditorDisplayName: aaronjensen

Body:
In MVC 3, you can remove the master layout code with:

   @{
    Layout = "";
    }


问:
Creating asymmetric keys in SQL Server 2014 for unsafe assemblies
I have 2 DLLs signed in Visual Studio (VS) 2015. A former employee created an asymmetric key and login and I ran one of the assemblies in UNSAFE mode correctly.

I get the following error with the second one:

Msg 10327, Level 14, State 1, Line 27

     CREATE ASSEMBLY for assembly 'TableFile' failed because assembly 'TableFile' is not authorized for PERMISSION_SET = UNSAFE.  The assembly is authorized when either of the following is true: the database owner (DBO) has UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission.

I can't ask the former employee so how do I find out how to get this to run?  I tried this too:

```<code>USE master;
GO

CREATE ASYMMETRIC KEY AProjectKey FROM EXECUTABLE FILE = 'E:\sqldlls\TableFile.dll'
CREATE LOGIN AProjectLogin FROM ASYMMETRIC KEY AProjectKey ;
GRANT UNSAFE ASSEMBLY TO AProjectLogin ;
GO
</code>```

This gives the following errors:

Msg 15396, Level 16, State 1, Line 9

   An asymmetric key with name 'AProjectKey' already exists or this asymmetric key already has been added to the database.

Msg 15151, Level 16, State 1, Line 10

  Cannot find the asymmetric key 'AProjectKey', because it does not exist or you do not have permission.

Msg 15151, Level 16, State 1, Line 11

  Cannot find the login 'AProjectLogin', because it does not exist or you do not have permission.

How do I get both these assemblies running in unsafe mode? Thanks in advance.

答:
Regarding those 3 error messages:

The first could be due to the Asymmetric Key already existing, but under a different name. Keys and Certificates need to be unique in terms of their public key, not just the name (though that obviously needs to be unique as well). Each Key and Certificate has a hash of the public key which is referred to as the "thumbprint". The thumbprints of existing Keys / Certificates are checked when creating a new one and will prevent the creation, even of a differently named Key / Certificate, if the thumbprint already exists. That is what the error message means by "or this asymmetric key already has been added to the database".

OR:

It could mean that a different Asymmetric Key (i.e. different "thumbprint") exists in master, but with the name AProjectKey

Because you couldn't create the same key under a different name, no Asymmetric Key exists with that new name, hence you can't create a Login from it (since, again, the CREATE ASYMMETRIC KEY statement failed).

Because you couldn't create the Login, it doesn't exist to be granted any permissions.

Error # 2 helps narrow down the issue. If Error # 1 was caused by an existing Asymmetric Key having the same name but different "thumbprint", then you either would have been able to create the Login (if it did not already exist), or you would have gotten an error stating that the Login (i.e. "server principal") already exists. But the error is that an Asymmetric Key by that name cannot be found. This should mean that the Asymmetric Key itself does already exist, but under a different name. You can see what Asymmetric Keys have been created by executing the following:

SELECT * FROM sys.asymmetric_keys;
```

<p>But that doesn't tell you which one came from that Assembly (or an Assembly signed with the same Strong Name Key used to sign this one). For that you need to know the "thumbprint", and for that you need to open a Command Prompt (preferably a "Developer Command Prompt" which Visual Studio sets up when installed, as it has the correct path set up upon opening it). Then, run the following:</p>

<pre class="lang-none prettyprint-override"><code>CD /D E:\sqldlls\
sn -T TableFile.dll
</code>```

You should see:

Public key token is XXXXXXXXXXXXXXXX
```

<p>Copy and paste that XXXXX "token" (i.e. thumbprint) into the following query:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT ak.[name], ak.[sid]
FROM   sys.asymmetric_keys ak
WHERE  ak.[thumbprint] = 0x{XXXXXXXXXXXXXXXX}; -- remove the { and }
</code>```

Assuming that you get a row returned, we need to see if the Login exists. Simply trying to create a Login from the Asymmetric Key won't get us the Login's name if it does exist since you can only have 1 Login created per Key / Certificate, and the error message only reports back the name you are trying to create as the one that already exists, even though it can be a different name for the same Key. So, take the SID from the returned row and paste it in the following query:

SELECT sp.*
FROM   sys.server_principals sp
WHERE  sp.[sid] = 0x{SID_from_sys_asymmetric_keys}; -- remove the { and }
```

If no row is returned then you should create a Login from that Asymmetric Key.

At this point a Login should exist, so grant it the UNSAFE ASSEMBLY permission.

Now try creating the Assembly again.

Body:
I have 2 DLLs signed in Visual Studio (VS) 2015. A former employee created an asymmetric key and login and I ran one of the assemblies in UNSAFE mode correctly.

I get the following error with the second one:

Msg 10327, Level 14, State 1, Line 27

     CREATE ASSEMBLY for assembly 'TableFile' failed because assembly 'TableFile' is not authorized for PERMISSION_SET = UNSAFE.  The assembly is authorized when either of the following is true: the database owner (DBO) has UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission.

I can't ask the former employee so how do I find out how to get this to run?  I tried this too:

USE master;
GO

CREATE ASYMMETRIC KEY AProjectKey FROM EXECUTABLE FILE = 'E:\sqldlls\TableFile.dll'
CREATE LOGIN AProjectLogin FROM ASYMMETRIC KEY AProjectKey ;
GRANT UNSAFE ASSEMBLY TO AProjectLogin ;
GO

This gives the following errors:

Msg 15396, Level 16, State 1, Line 9

   An asymmetric key with name 'AProjectKey' already exists or this asymmetric key already has been added to the database.

Msg 15151, Level 16, State 1, Line 10

  Cannot find the asymmetric key 'AProjectKey', because it does not exist or you do not have permission.

Msg 15151, Level 16, State 1, Line 11

  Cannot find the login 'AProjectLogin', because it does not exist or you do not have permission.

How do I get both these assemblies running in unsafe mode? Thanks in advance.

Body:
Regarding those 3 error messages:

The first could be due to the Asymmetric Key already existing, but under a different name. Keys and Certificates need to be unique in terms of their public key, not just the name (though that obviously needs to be unique as well). Each Key and Certificate has a hash of the public key which is referred to as the "thumbprint". The thumbprints of existing Keys / Certificates are checked when creating a new one and will prevent the creation, even of a differently named Key / Certificate, if the thumbprint already exists. That is what the error message means by "or this asymmetric key already has been added to the database".

OR:

It could mean that a different Asymmetric Key (i.e. different "thumbprint") exists in master, but with the name AProjectKey

Because you couldn't create the same key under a different name, no Asymmetric Key exists with that new name, hence you can't create a Login from it (since, again, the CREATE ASYMMETRIC KEY statement failed).

Because you couldn't create the Login, it doesn't exist to be granted any permissions.

Error # 2 helps narrow down the issue. If Error # 1 was caused by an existing Asymmetric Key having the same name but different "thumbprint", then you either would have been able to create the Login (if it did not already exist), or you would have gotten an error stating that the Login (i.e. "server principal") already exists. But the error is that an Asymmetric Key by that name cannot be found. This should mean that the Asymmetric Key itself does already exist, but under a different name. You can see what Asymmetric Keys have been created by executing the following:

SELECT * FROM sys.asymmetric_keys;

But that doesn't tell you which one came from that Assembly (or an Assembly signed with the same Strong Name Key used to sign this one). For that you need to know the "thumbprint", and for that you need to open a Command Prompt (preferably a "Developer Command Prompt" which Visual Studio sets up when installed, as it has the correct path set up upon opening it). Then, run the following:

CD /D E:\sqldlls\
sn -T TableFile.dll

You should see:

Public key token is XXXXXXXXXXXXXXXX

Copy and paste that XXXXX "token" (i.e. thumbprint) into the following query:

SELECT ak.[name], ak.[sid]
FROM   sys.asymmetric_keys ak
WHERE  ak.[thumbprint] = 0x{XXXXXXXXXXXXXXXX}; -- remove the { and }

Assuming that you get a row returned, we need to see if the Login exists. Simply trying to create a Login from the Asymmetric Key won't get us the Login's name if it does exist since you can only have 1 Login created per Key / Certificate, and the error message only reports back the name you are trying to create as the one that already exists, even though it can be a different name for the same Key. So, take the SID from the returned row and paste it in the following query:

SELECT sp.*
FROM   sys.server_principals sp
WHERE  sp.[sid] = 0x{SID_from_sys_asymmetric_keys}; -- remove the { and }

If no row is returned then you should create a Login from that Asymmetric Key.

At this point a Login should exist, so grant it the UNSAFE ASSEMBLY permission.

Now try creating the Assembly again.


问:
Is it possible to use `ng-click` inside of `.append`
I am trying to call one method using angular which is placed inside of .append.
But the method is not called.Can I use ng-click inside .append?otherwise is there any alternative way to append element in angular?

```<code>var app=angular
.module('myApp',[])
.controller('myController',function($scope){

  $scope.clickMe = function(){
        $('.paragraph').append('<span ng-click="closeMe()"><i class="fa fa-times" aria-hidden="true"></i></span>');
  }
  $scope.closeMe = function(){
    alert("closed")
  }
})
</code>```

Sample: https://jsfiddle.net/fjhbbnno/

答:
First you'll have to do dynamic compilation to bind the angular directives like ng-click to your controller scope, something like

```<code>var el = '<span ng-click="closeMe()"><i class="fa fa-times" aria-hidden="true"></i></span>';
var compiledElement = $compile(el)($scope);
</code>```

Now you can append this like

```<code>$('.paragraph').append(compiledElement )
</code>```

Don't forget to inject $compile service in your controller

Body:
I am trying to call one method using angular which is placed inside of .append.
But the method is not called.Can I use ng-click inside .append?otherwise is there any alternative way to append element in angular?

var app=angular
.module('myApp',[])
.controller('myController',function($scope){

  $scope.clickMe = function(){
        $('.paragraph').append('');
  }
  $scope.closeMe = function(){
    alert("closed")
  }
})

Sample: https://jsfiddle.net/fjhbbnno/

Body:
First you'll have to do dynamic compilation to bind the angular directives like ng-click to your controller scope, something like

var el = '<span ng-click="closeMe()"><i class="fa fa-times" aria-hidden="true"></i></span>';
var compiledElement = $compile(el)($scope);

Now you can append this like

$('.paragraph').append(compiledElement )

Don't forget to inject $compile service in your controller


问:
how to select Table View row selection with custom checkbox button?
How to select tableview row with custom button . i have another button called select all its outside of the table view my question is while clicking outside of the tableview button how to select and deselect inside tableview rows? At the same time i could able to select single row in the tableview ? how to do it in swift 3? This is my code in cellforrow method</p>

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let identifier = "Custom"
    var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    if cell == nil {
        tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    }
    print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
    var localDic :NSDictionary!

    localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary

    Common.sharedInstance.StopActivity()
    cell.profile_img.image = self.image
    cell.name_lbl.text = localDic["student_name"] as? String
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell

}
</code>```

答:
Thats how you can programatically select all rows of a single section

```<code>@IBAction func didTapSelectAllButton(sender: UIButton) {
        let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
        for row in 0..<totalRows {
            let indexPath = IndexPath(row: row, section: 0)
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }
</code>```

If you don't want to use default check box of tableView then disable multipleSelection from tableView and implement logic using an extra global array.

```<code>var selectedArrayIndex = [Int]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        selectedArrayIndex.remove(at: selectedArrayIndex.index(of: indexPath.row)!)
    }else {
        selectedArrayIndex.append(indexPath.row)
    }
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        // Enable You Check
        cell.checkBoxView.isHidden = false
    }else {
        cell.checkBoxView.isHidden = true
    }
}
@IBAction func didTapSelectAllButton(sender: UIButton) {
    let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
    selectedArrayIndex.removeAll()
    for row in 0..<totalRows {
        selectedArrayIndex.append(row)
    }
}
</code>```

Body:
How to select tableview row with custom button . i have another button called select all its outside of the table view my question is while clicking outside of the tableview button how to select and deselect inside tableview rows? At the same time i could able to select single row in the tableview ? how to do it in swift 3? This is my code in cellforrow method

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let identifier = "Custom"
    var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    if cell == nil {
        tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    }
    print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
    var localDic :NSDictionary!

    localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary

    Common.sharedInstance.StopActivity()
    cell.profile_img.image = self.image
    cell.name_lbl.text = localDic["student_name"] as? String
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell

}

Body:
Thats how you can programatically select all rows of a single section

@IBAction func didTapSelectAllButton(sender: UIButton) {
        let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
        for row in 0..<totalRows {
            let indexPath = IndexPath(row: row, section: 0)
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }

If you don't want to use default check box of tableView then disable multipleSelection from tableView and implement logic using an extra global array.

var selectedArrayIndex = [Int]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        selectedArrayIndex.remove(at: selectedArrayIndex.index(of: indexPath.row)!)
    }else {
        selectedArrayIndex.append(indexPath.row)
    }
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        // Enable You Check
        cell.checkBoxView.isHidden = false
    }else {
        cell.checkBoxView.isHidden = true
    }
}
@IBAction func didTapSelectAllButton(sender: UIButton) {
    let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
    selectedArrayIndex.removeAll()
    for row in 0..<totalRows {
        selectedArrayIndex.append(row)
    }
}


问:
Adjust QCheckbox into QTableWidget : Qt
I am facing issues when I adjust QCheckbox into QTableWidget.

It is working as expected in Mac and Linux but creating problem in Windows.

I have googled it and tried out different solutions, but it did not solve my problem.

Code:

```<code>QWidget* cellWidget = new QWidget();
QCheckBox *box = new QCheckBox();
box->setCheckState(Qt::Unchecked);
QHBoxLayout* layout = new QHBoxLayout(cellWidget);
layout->addWidget(box);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
cellWidget->setLayout(layout);
ui->twidget_header->setCellWidget(0, 0, cellWidget);
</code>```

Mac OS O/P : As Expected

Win OS O/P : Problem with Checkbox size and alignment

.

My app is created in Qt 5.9 for Mac, Win and Linux platform.
Let me know if you required more info about the problem.

答:
The problem can happen with any QWidget while you create Qt app and support different resolutions.

To overcome the size of the QWidget (QCheckbox/QRadiobutton), you just need to overwrite the QWidget class.

Create customcheckbox.h file and overwrite the QCheckbox widget.

```<code>class CustomCheckBox : public QCheckBox
{
  Q_OBJECT
public:
    CustomCheckBox(QWidget *parent=NULL);

private:
    bool m_isChecked;

public slots:
    void emitToggleSignal(bool);
};
</code>```

Implement customcheckbox.cpp file as per your requirement.

By doing this, QCheckbox will automatically adjust size on respective resolution.

Hope this will save someone's time in future.

Thanks.

Title: Adjust QCheckbox into QTableWidget : Qt

Body:
I am facing issues when I adjust QCheckbox into QTableWidget.

It is working as expected in Mac and Linux but creating problem in Windows.

I have googled it and tried out different solutions, but it did not solve my problem.

Code:

QWidget* cellWidget = new QWidget();
QCheckBox *box = new QCheckBox();
box->setCheckState(Qt::Unchecked);
QHBoxLayout* layout = new QHBoxLayout(cellWidget);
layout->addWidget(box);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
cellWidget->setLayout(layout);
ui->twidget_header->setCellWidget(0, 0, cellWidget);

Mac OS O/P : As Expected

Win OS O/P : Problem with Checkbox size and alignment

.

My app is created in Qt 5.9 for Mac, Win and Linux platform.
Let me know if you required more info about the problem.

Body:
The problem can happen with any QWidget while you create Qt app and support different resolutions.

To overcome the size of the QWidget (QCheckbox/QRadiobutton), you just need to overwrite the QWidget class.

Create customcheckbox.h file and overwrite the QCheckbox widget.

class CustomCheckBox : public QCheckBox
{
  Q_OBJECT
public:
    CustomCheckBox(QWidget *parent=NULL);

private:
    bool m_isChecked;

public slots:
    void emitToggleSignal(bool);
};

Implement customcheckbox.cpp file as per your requirement.

By doing this, QCheckbox will automatically adjust size on respective resolution.

Hope this will save someone's time in future.

Thanks.


问:
Prevent wrapping in CSS Flexbox
I have a re-sizable sidebar using Javascript. The problem is when the size of the sidebar is less than the content's wrapping occurs. (i think because of flex-box).

My grid is based on Rows and Columns kinda like Bootstrap.

```<code>.column {
    flex-basis: 0;
    max-width: 100%;
    flex-grow: 1;
}

.row {
    display: flex;
    flex-wrap: nowrap;
    margin: 0 -1rem;
}
</code>```

What I want to achieve is truncating the content (without shrinking) indicating that there is more.

Here is a fiddle with what i achieved so far.

答:
You need to use text-overflow property along with other properties inside a media query or per your needs.

e.g

.list {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 48px; /* just for test */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="list">
  this is a ver long list this is a ver long list this is a ver long list.
</div></code>```

Hope this will help you out.

Title: Prevent wrapping in CSS Flexbox

Body:
I have a re-sizable sidebar using Javascript. The problem is when the size of the sidebar is less than the content's wrapping occurs. (i think because of flex-box).

My grid is based on Rows and Columns kinda like Bootstrap.

.column {
    flex-basis: 0;
    max-width: 100%;
    flex-grow: 1;
}

.row {
    display: flex;
    flex-wrap: nowrap;
    margin: 0 -1rem;
}

What I want to achieve is truncating the content (without shrinking) indicating that there is more.

Here is a fiddle with what i achieved so far.

Body:
You need to use text-overflow property along with other properties inside a media query or per your needs.

e.g

.list {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 48px; /* just for test */
}

<div class="list">
  this is a ver long list this is a ver long list this is a ver long list.
</div>

Hope this will help you out.


问:
Android app for a web application without an API
Is it possible to create an Android app for an existing web application which doesn't provide any API?

Webview just provides a crude view of the same web app in Android, but interface with webview looks crappy.

答: If you want your web page to have the look and feel of a native android app without creating the native app, you'll need to do so using javascript on your served page.  Take a look at http://jquerymobile.com/ which seems to do a lot of the leg work.  You can use that javascript and a little elbow grease to accomplish what you describe.</p>


问:
jQuery Validate isn't giving error messages - only HTML5 required
I have set up this form. My jQuery and heading tags is as follows:

```<code>    <head>
    <title>Contact - The Old Thatch Inn</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="css/styles.css" rel="stylesheet" type="text/css"/>
    <link href="https://fonts.googleapis.com/css?family=Satisfy|Yesteryear|Exo+2" rel="stylesheet">
    <link href="css/fonts.css" rel="stylesheet" type="text/css"/>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
           $('form').validate();
        });
    </script>
</head>
</code>```

The html5 required field shows up instead of anything else. See the site here: http://adonnelly759.students.cs.qub.ac.uk/thatch/sample.php

答:
Issues here is with jQuery conflict because of multiple jQuery libraries. I have removed last external script and I can see error messages right under each fields.

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>

    <!-- MODIFICATION HERE -->
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> -->
</code>```

Body:
I have set up this form. My jQuery and heading tags is as follows:

    <title>Contact - The Old Thatch Inn</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="css/styles.css" rel="stylesheet" type="text/css"/>
    <link href="https://fonts.googleapis.com/css?family=Satisfy|Yesteryear|Exo+2" rel="stylesheet">
    <link href="css/fonts.css" rel="stylesheet" type="text/css"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

The html5 required field shows up instead of anything else. See the site here: http://adonnelly759.students.cs.qub.ac.uk/thatch/sample.php

Body:
Issues here is with jQuery conflict because of multiple jQuery libraries. I have removed last external script and I can see error messages right under each fields.

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>

    <!-- MODIFICATION HERE -->
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> -->


问:
Pythonic way to loop over dictionary
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

```<code>directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}
</code>```

```<code># My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]
</code>```

Which way is more "Pythonic"? Or is there a better way to approach this?

答:
You could use:

```<code>columns = [len(dataframe.columns) for dataframe in dataframes.values()]
</code>```

As @piRSquared mentioned if your only objective is to get the number of columns in the dataframe you shouldn't read the entire csv file, instead use the nrows keyword argument of the read_csv function.

Title: Pythonic way to loop over dictionary

Body:
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}

# My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]

Which way is more "Pythonic"? Or is there a better way to approach this?

Body:
You could use:

columns = [len(dataframe.columns) for dataframe in dataframes.values()]

As @piRSquared mentioned if your only objective is to get the number of columns in the dataframe you shouldn't read the entire csv file, instead use the nrows keyword argument of the read_csv function.


答:
As you have not shared full code with us, it will be difficult for us to provide you working solution. But you can add this css to your code with you want to truncate.

width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;```

This will help you with text truncate with "..."

Title: Prevent wrapping in CSS Flexbox

Body:
As you have not shared full code with us, it will be difficult for us to provide you working solution. But you can add this css to your code with you want to truncate.

width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

This will help you with text truncate with "..."