问:
yielding islice from reading file
Hoping that someone can help me understand the following. Writing a small program to read a csv file in K line chunks. I've seen the other stack questions about this an that's not what I'm asking here. I'm trying to understand why one program terminates and the other never does.

This code never terminates:

```<code>from __future__ import print_function
from itertools import islice
import time
import csv
def gen_csv1(input_file, chunk_size=50):
    try:
        with open(input_file) as in_file:
            csv_reader = csv.reader(in_file)
            while True:
                yield islice(csv_reader, chunk_size)
    except StopIteration:
        pass

gen1 = gen_csv1('./test100.csv')

for chunk in gen1:
    print(list(chunk))
    time.sleep(1)
</code>```

While this works fine. With the only difference being the islice outside the yield from the generator.

```<code>def gen_csv(input_file):
    try:
        with open(input_file) as in_file:
            csv_reader = csv.reader(in_file)
            while True:
                yield next(csv_reader)
    except StopIteration:
        pass

gen = gen_csv('./test100.csv')
for chunk in gen:
    rows = islice(gen, 50)
    print(list(rows))
    time.sleep(1)
</code>```

I'm stumped. Any guidance is hugely appreciated. This is more out of curiosity than for work reasons.

答:
Per the docs,

[islice] works like a slice() on a list but returns an iterator.

When you slice an empty list, an empty list is returned:

```<code>In [118]: [][:3]
Out[118]: []
</code>```

Similarly, when you islice an empty iterator, an empty iterator is returned.
In contrast, calling next on an empty iterator raises StopIteration:

```<code>In [98]: from itertools import islice
In [114]: reader = iter([])

In [115]: list(islice(reader, 3))
Out[115]: []

In [116]: next(reader)
StopIteration:
</code>```

Since islice never raises a StopIteration exception, the first version of the code never terminates.

Title: yielding islice from reading file

Body:
Hoping that someone can help me understand the following. Writing a small program to read a csv file in K line chunks. I've seen the other stack questions about this an that's not what I'm asking here. I'm trying to understand why one program terminates and the other never does.

This code never terminates:

from __future__ import print_function
from itertools import islice
import time
import csv
def gen_csv1(input_file, chunk_size=50):
    try:
        with open(input_file) as in_file:
            csv_reader = csv.reader(in_file)
            while True:
                yield islice(csv_reader, chunk_size)
    except StopIteration:
        pass

gen1 = gen_csv1('./test100.csv')

for chunk in gen1:
    print(list(chunk))
    time.sleep(1)

While this works fine. With the only difference being the islice outside the yield from the generator.

def gen_csv(input_file):
    try:
        with open(input_file) as in_file:
            csv_reader = csv.reader(in_file)
            while True:
                yield next(csv_reader)
    except StopIteration:
        pass

gen = gen_csv('./test100.csv')
for chunk in gen:
    rows = islice(gen, 50)
    print(list(rows))
    time.sleep(1)

I'm stumped. Any guidance is hugely appreciated. This is more out of curiosity than for work reasons.

Body:
Per the docs,

[islice] works like a slice() on a list but returns an iterator.

When you slice an empty list, an empty list is returned:

In [118]: [][:3]
Out[118]: []

Similarly, when you islice an empty iterator, an empty iterator is returned.
In contrast, calling next on an empty iterator raises StopIteration:

In [98]: from itertools import islice
In [114]: reader = iter([])

In [115]: list(islice(reader, 3))
Out[115]: []

In [116]: next(reader)
StopIteration:

Since islice never raises a StopIteration exception, the first version of the code never terminates.


来源: stackexchange

问:
How can I return null or bool from a function
I have this function:

```<code>public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}
</code>```

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

答:
```<code>public bool? GetBoolSetting(Settings setting)
{
    int result = 0;
    if (!int.TryParse(GetStringSetting(setting), out result))
        return null;
    return result == 0 ? false: true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this function:

public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?


问:
fetch request performance issues
I have some serious performance issues when querying a sqlite database with approx. 25k rows.
What I want to do is the following: as the user types something into a textfield I want to give him autocompletition suggestions in a tableview which is the inputAccessoryView of the keyboard. Each time he enters a new character, 4 new queries go off to search for appropriate suggestions. I do this in a seperate thread using GCD and blocks.
However the performance is too low. Here's the code for one query:

```<code>- (void) queryDatabase:(NSString *) searchString
{
[self.fetchedResults removeAllObjects];

dispatch_queue_t fetchQueue = dispatch_queue_create("Fetch Queue", NULL);

dispatch_async(fetchQueue,^{
    NSError *error = nil;
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.undoManager = nil;
    [context setPersistentStoreCoordinator: self.persistentStoreCoordinator];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"reducedTownName like %@", [searchString stringByAppendingString:@"*"]];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Station" inManagedObjectContext:context];
    request.fetchLimit = 20;
    [request setIncludesPropertyValues:NO];
    request.predicate = predicate;
    request.resultType = NSManagedObjectIDResultType;

    NSArray *results = [context executeFetchRequest:request error:&error];
    NSEnumerator *e = [results objectEnumerator];
    NSManagedObjectID *objectId = nil;

    while (objectId = [e nextObject])
    {
        Station *station = (Station *) [self.managedObjectContext objectWithID:objectId];
        if ( ![self.fetchedResults containsObject:station])
            [self.fetchedResults addObject:station];
    }

    dispatch_async(dispatch_get_main_queue(),^{
        [self.tableView reloadData];
    });
    [request release];
    [context release];
});
    //do 3 more queries similar to the first (only predicate changes)
    dispatch_release(fetchQueue);
}
</code>```

I use an NSArray (fetchedResults) to hold the returned Entities and update the tableView with data from this Array.

Does someone see any performance killer in this code, or has some other advice for me?

答:
I think I might have spotted it.

You do your query to get the entities and put it into the results array. That's query number 1 and it's optimized ok (assuming there are no joins etc but it doesn't look like there are)

Then, you go through all the results to remove duplicates that are already in your results. This means that you execute a new query to get each Station NSManagedObject. If you want to avoid duplicates you will have to do it without calling objectWithID because that will et the object from CoreData.

Worst case, to get 20 stations results, you need 21 queries. Not good.

As sqlite3 is single threaded, why don't you just make a large predicate instead of 4 smaller ones - then you can remove your duplicates in the predicate and won't need to go through the array until it's time to draw that station's table view cell.

I've had this problem before with lookups and had to solve it by making a seperate table in the database. In your case this table (called station_search) would only contain the station name (which would be indexed of course) and a stationId. Then I do searches on this table (which would be fast because it's not got lots of data to search through).

Once I've got my results I just use the stationId to get the Station from the main stations table only when I need it i.e. I'm drawing the cell in a table.

I can also use a NSFetchedResultsController to batch my results together.

This has turned into a bit of a ramble - if you have any questions just ask!

Hope it helps,

Sam

ContentLicense: CC BY-SA 2.5

Title: fetch request performance issues

Body:
I have some serious performance issues when querying a sqlite database with approx. 25k rows.
What I want to do is the following: as the user types something into a textfield I want to give him autocompletition suggestions in a tableview which is the inputAccessoryView of the keyboard. Each time he enters a new character, 4 new queries go off to search for appropriate suggestions. I do this in a seperate thread using GCD and blocks.
However the performance is too low. Here's the code for one query:

- (void) queryDatabase:(NSString *) searchString
{
[self.fetchedResults removeAllObjects];

dispatch_queue_t fetchQueue = dispatch_queue_create("Fetch Queue", NULL);

dispatch_async(fetchQueue,^{
    NSError *error = nil;
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.undoManager = nil;
    [context setPersistentStoreCoordinator: self.persistentStoreCoordinator];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"reducedTownName like %@", [searchString stringByAppendingString:@"*"]];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Station" inManagedObjectContext:context];
    request.fetchLimit = 20;
    [request setIncludesPropertyValues:NO];
    request.predicate = predicate;
    request.resultType = NSManagedObjectIDResultType;

    NSArray *results = [context executeFetchRequest:request error:&error];
    NSEnumerator *e = [results objectEnumerator];
    NSManagedObjectID *objectId = nil;

    while (objectId = [e nextObject])
    {
        Station *station = (Station *) [self.managedObjectContext objectWithID:objectId];
        if ( ![self.fetchedResults containsObject:station])
            [self.fetchedResults addObject:station];
    }

    dispatch_async(dispatch_get_main_queue(),^{
        [self.tableView reloadData];
    });
    [request release];
    [context release];
});
    //do 3 more queries similar to the first (only predicate changes)
    dispatch_release(fetchQueue);
}

I use an NSArray (fetchedResults) to hold the returned Entities and update the tableView with data from this Array.

Does someone see any performance killer in this code, or has some other advice for me?


问:
Angular 2 Material Design
I am learning Angular 2 and I have so many problems with that whose one I can't find anything on that on internet. So, I tried easy thing to start : create a sign in form in my app, so I am using Material Design but my input are bad and nothing like in the Material Design Doc. Here so picture :
enter image description here

So as you can see my input are not display and the placeholder is under it.

Here the code :

<form >
    <md-input-container>
      <input mdInput type="email" placeholder="Email" >
    </md-input-container>
    <md-input-container>
      <input mdInput type="password" placeholder="Mot de passe" >
    </md-input-container>

    <button md-button type="submit" >Se connecter</button>
  </form>```

What I missed ? Thank you so much.

Elisa

答:
You added the theme to your app.component.css instead of the global style.css file.

More info about theming can be found here: https://material.angular.io/guide/theming

Title: Angular 2 Material Design

Body:
I am learning Angular 2 and I have so many problems with that whose one I can't find anything on that on internet. So, I tried easy thing to start : create a sign in form in my app, so I am using Material Design but my input are bad and nothing like in the Material Design Doc. Here so picture :
enter image description here

So as you can see my input are not display and the placeholder is under it.

Here the code :

<form >
    <md-input-container>
      <input mdInput type="email" placeholder="Email" >
    </md-input-container>
    <md-input-container>
      <input mdInput type="password" placeholder="Mot de passe" >
    </md-input-container>

    <button md-button type="submit" >Se connecter</button>
  </form>

What I missed ? Thank you so much.

Elisa


问:
Rotating the Rectangle object in java
Is it possible to rotate the Rectangle object to a certain degree around it's axis? Is it as easy as Rectangle rect = new Rectangle(x,y,w,h,r)?

If it is not possible to rotate the object, what would be a way I could get similar results?

Edit: for clarity here is my dilemma, I have images that rotate but when they colide with other images the collisions only work at 90 and 180 degree rotations because their hit box Rectangle objects don't rotate.

答:
There's also another way to do this (besides createTransformedShape) which creates fewer temporary objects, if that's desirable.

Instead of keeping a Rectangle2D for the bounding box, you can keep a Path2D and then do the transform in place, using Path2D.transform(AffineTransform):

```<code>import java.awt.geom.*;

public class Example {
    private final Path2D hitBox;

    public Example(Rectangle2D initialHitBox) {
        this.hitBox = new Path2D.Double(initialHitBox);
    }

    public void transform(AffineTransform tx) {
        path.transform(tx); // In-place transformation.
    }

    // ...
}
</code>```

This is very similar to what AffineTransform actually does under the hood.

Title: Rotating the Rectangle object in java

Body:
There's also another way to do this (besides createTransformedShape) which creates fewer temporary objects, if that's desirable.

Instead of keeping a Rectangle2D for the bounding box, you can keep a Path2D and then do the transform in place, using Path2D.transform(AffineTransform):

import java.awt.geom.*;

public class Example {
    private final Path2D hitBox;

    public Example(Rectangle2D initialHitBox) {
        this.hitBox = new Path2D.Double(initialHitBox);
    }

    public void transform(AffineTransform tx) {
        path.transform(tx); // In-place transformation.
    }

    // ...
}

This is very similar to what AffineTransform actually does under the hood.


问:
Cannot open Swagger API in browser
I am trying to set up Swagger in a VM/Vagrant box. What I have done is below.

i. Port Forwarding using Vagrantfile

```<code>dev.vm.network "forwarded_port", guest: 3000, host: 3000, host_ip:
"127.0.0.1", auto_correct: true
</code>```

ii. Swagger configuration in a vagrant box

```<code>npm install -g swagger
Create a new swagger project
swagger project create hello-world
</code>```

I tried to open Swagger Editor with command swagger project edit -p 3000 -s, which gives

Starting Swagger Editor. Running Swagger Editor API server. You can
  make GET and PUT calls to http://127.0.0.1:3000/editor/spec

Seems like everything is perfect so just visited browser of local desktop(windows), and visited http://localhost:3000/editor/spec which gives me This site can’t be reached.

curl http://localhost:3000/editor/spec is working fine in the VM/vagrant box.

What wrong am I doing here?

答:
The issue is

calls to http://127.0.0.1:3000/editor/spec

so its not accessible on any network interface other than your localhost.

You need to change this to get started the app on the IP of the server or you can use 0.0.0.0 (special IP so all interfaces can access it)

You need to run as

```<code>swagger project edit --host 0.0.0.0 -p 3000 -s
</code>```

(See the CLI reference guide) - Then you will be able to access from your host at http://localhost:3000

NB: the other option is to assign a static IP either with private network or public network; then start swagger project edit --host <static_ip_from_vagrantfile> -p 3000 -s and access from your host with the static IP and in such case you dont need to forward any port from the guest to the host.

Title: Cannot open Swagger API in browser

Body:
I am trying to set up Swagger in a VM/Vagrant box. What I have done is below.

i. Port Forwarding using Vagrantfile

dev.vm.network "forwarded_port", guest: 3000, host: 3000, host_ip:
"127.0.0.1", auto_correct: true

ii. Swagger configuration in a vagrant box

npm install -g swagger
Create a new swagger project
swagger project create hello-world

I tried to open Swagger Editor with command swagger project edit -p 3000 -s, which gives

Starting Swagger Editor. Running Swagger Editor API server. You can
  make GET and PUT calls to http://127.0.0.1:3000/editor/spec

Seems like everything is perfect so just visited browser of local desktop(windows), and visited http://localhost:3000/editor/spec which gives me This site can’t be reached.

curl http://localhost:3000/editor/spec is working fine in the VM/vagrant box.

What wrong am I doing here?

Body:
The issue is

calls to http://127.0.0.1:3000/editor/spec

so its not accessible on any network interface other than your localhost.

You need to change this to get started the app on the IP of the server or you can use 0.0.0.0 (special IP so all interfaces can access it)

You need to run as

swagger project edit --host 0.0.0.0 -p 3000 -s

(See the CLI reference guide) - Then you will be able to access from your host at http://localhost:3000

NB: the other option is to assign a static IP either with private network or public network; then start swagger project edit --host <static_ip_from_vagrantfile> -p 3000 -s and access from your host with the static IP and in such case you dont need to forward any port from the guest to the host.


问:
I need to create an n-element array a where each index i has a reference to another array of K integers
The value of K varies from array to array.  How to do this?

This is what I have to achieve. Its the hackerrank variable sizedarray question.
https://s3.amazonaws.com/hr-challenge-images/14507/1476906485-2c93045320-variable-length-arrays.png

I've read the solutions but am unable to understand it.
Please explain this line of code : int** seq=new int* [n];

Following is the complete code from which the snippet has been taken.

```<code>int main()
{
    int n,q;
    cin>>n>>q;
    int** seq=new int* [n];
    for(int i=0;i<n;i++)
    {
      int a;
      cin>>a;
      int* b=new int [a];
      for(int j=0;j<a;j++)
        {
          int e;
          cin>>e;
          b[j]=e;
        }
       *(seq+i)=b;
   }

  for(int i=0;i<q;i++)
  {

      int r,s;
      cin>>r>>s;
      cout<<seq[r][s]<<endl;

  }
}
</code>```

I've also read something about using vector to create variable sized array. I don't understand. please explain.

答:
if you write int *p, this means you are defining a pointer which will store the address of an integer.

Similarly, int **p means a pointer to an integer pointer.

Now, let's suppose you create a 1D array like this:

```<code>int *a = new int[10];
</code>```

here the pointer "a" points to the address of the first element, an integer, of the array "new" just created.

To access the individual elements you can use a[i] or simply *(a+i).

now, coming to your question.

```<code>int **seq = new int*[n];
</code>```

the "new" here would create an array of "pointers". So to point to the first element, which is a pointer here, you need to use a pointer to a pointer. That is why **seq.

Body:
The value of K varies from array to array.  How to do this?

This is what I have to achieve. Its the hackerrank variable sizedarray question.
https://s3.amazonaws.com/hr-challenge-images/14507/1476906485-2c93045320-variable-length-arrays.png

I've read the solutions but am unable to understand it.
Please explain this line of code : int** seq=new int* [n];

Following is the complete code from which the snippet has been taken.

int main()
{
    int n,q;
    cin>>n>>q;
    int** seq=new int* [n];
    for(int i=0;i<n;i++)
    {
      int a;
      cin>>a;
      int* b=new int [a];
      for(int j=0;j>e;
          b[j]=e;
        }
       *(seq+i)=b;
   }

  for(int i=0;i<q;i++)
  {

      int r,s;
      cin>>r>>s;
      cout<<seq[r][s]<<endl;

  }
}

I've also read something about using vector to create variable sized array. I don't understand. please explain.

Body:
if you write int *p, this means you are defining a pointer which will store the address of an integer.

Similarly, int **p means a pointer to an integer pointer.

Now, let's suppose you create a 1D array like this:

int *a = new int[10];

here the pointer "a" points to the address of the first element, an integer, of the array "new" just created.

To access the individual elements you can use a[i] or simply *(a+i).

now, coming to your question.

int **seq = new int*[n];

the "new" here would create an array of "pointers". So to point to the first element, which is a pointer here, you need to use a pointer to a pointer. That is why **seq.


问:
My random quote generator button isn't displaying quotes. (not working on CodePen or Sublime, only Stack Overflow)
I've been having a little trouble over this since I started last night. After making this part of the generator, I opened it in the browser to see if it works. Even though the HTML part is all set, the button doesn't display the quotes when I click it.

I am following the 'Make a Quote Generator for Absolute Beginners' tutorial on Medium by Sophanarith Sok. I have looked through to check for any mistakes and compared to the tutorial's code, but the button isn't showing any quotes.

I used Sublime Text 3 and Code Pen to check. However, when I posted the snippets in the Stack Overflow coding feature to check if it ran, it was working perfectly. Any suggestions?

This is the JavaScript section.

```<code>var quotes = [
'To be or not to be, that is the question. -Hamlet',
'Maybe ever\’body in the whole damn world is scared of each other. -Of Mice and Men.',
'Life is to be lived, not controlled; and humanity is won by continuing to play in face of certain defeat. -Invisible Man.',
 'Terror made me cruel -Wuthering Heights.',
 'Some men get the world, some men get ex-hookers and a trip to Arizona. You\'re in with the former, but my God I don\'t envy the blood on your conscience. -LA Confidential.',
 'The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars. -On The Road.',
 'It was a bright cold day in April, and the clocks were striking thirteen. -1984.',
 'We were the people who were not in the papers. We lived in the blank white spaces at the edges of the print. It gave us more freedom. We lived in the gaps between the stories. -A Handmaiden\'s Tale.',
 'It sounds plausible enough tonight, but wait until tomorrow. Wait for the common sense of the morning. -The Time Machine.',
 'It\'s much better to do good in a way that no one knows anything about it. -Anna Karenina.',
 'Life appears to me too short to be spent in nursing animosity or registering wrongs. -Charlotte Bronte.',
  'You forget what you want to remember, and you remember what you want to forget. -The Road.',
  'There is an idea of a Patrick Bateman, some kind of abstraction, but there is no real me, only an entity, something illusory, and though I can hide my cold gaze and you can shake my hand and feel flesh gripping yours and maybe you can even sense our lifestyles are probably comparable: I simply am not there. -American Psycho.',
  'Finally, from so little sleeping and so much reading, his brain dried up and he went completely out of his mind. -Don Quixote.',
   'We cast a shadow on something wherever we stand, and it is no good moving from place to place to save things; because the shadow always follows. Choose a place where you won\'t do harm - yes, choose a place where you won\'t do very much harm and stand in it for all you are worth, facing the sunshine. -A Room with a View.',
    'Memories warm you up from the inside. But they also tear you apart. -Kafka on the Shore.',
    'You are your best thing -Beloved.',
'Some birds are not meant to be caged, that\'s all. Their feathers are too bright, their songs too sweet and wild. So you let them go, or when you open the cage to feed them they somehow fly out past you. And the part of you that knows it was wrong to imprison them in the first place rejoices, but still, the place where you live is that much drabber and empty for their departure. -Shawshank Redemption.'

]

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
</code>```

This is the HTML section.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quote Gen</title>
</head>

<body>
    <h1>Simple Quote Generator</h1>
    <div id="quoteDisplay">
    </div>
    <button onclick = "newQuote()">New Quote</button>
    <script src="javascript.js"></script>
</body>

</html>
</code>```

答:
<!DOCTYPE html>

    <title>Quote Gen</title>

Simple Quote Generator

    <button onclick = "newQuote()">New Quote</button>

```

Body:
I've been having a little trouble over this since I started last night. After making this part of the generator, I opened it in the browser to see if it works. Even though the HTML part is all set, the button doesn't display the quotes when I click it.

I am following the 'Make a Quote Generator for Absolute Beginners' tutorial on Medium by Sophanarith Sok. I have looked through to check for any mistakes and compared to the tutorial's code, but the button isn't showing any quotes.

I used Sublime Text 3 and Code Pen to check. However, when I posted the snippets in the Stack Overflow coding feature to check if it ran, it was working perfectly. Any suggestions?

This is the JavaScript section.

var quotes = [
'To be or not to be, that is the question. -Hamlet',
'Maybe ever\’body in the whole damn world is scared of each other. -Of Mice and Men.',
'Life is to be lived, not controlled; and humanity is won by continuing to play in face of certain defeat. -Invisible Man.',
 'Terror made me cruel -Wuthering Heights.',
 'Some men get the world, some men get ex-hookers and a trip to Arizona. You\'re in with the former, but my God I don\'t envy the blood on your conscience. -LA Confidential.',
 'The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars. -On The Road.',
 'It was a bright cold day in April, and the clocks were striking thirteen. -1984.',
 'We were the people who were not in the papers. We lived in the blank white spaces at the edges of the print. It gave us more freedom. We lived in the gaps between the stories. -A Handmaiden\'s Tale.',
 'It sounds plausible enough tonight, but wait until tomorrow. Wait for the common sense of the morning. -The Time Machine.',
 'It\'s much better to do good in a way that no one knows anything about it. -Anna Karenina.',
 'Life appears to me too short to be spent in nursing animosity or registering wrongs. -Charlotte Bronte.',
  'You forget what you want to remember, and you remember what you want to forget. -The Road.',
  'There is an idea of a Patrick Bateman, some kind of abstraction, but there is no real me, only an entity, something illusory, and though I can hide my cold gaze and you can shake my hand and feel flesh gripping yours and maybe you can even sense our lifestyles are probably comparable: I simply am not there. -American Psycho.',
  'Finally, from so little sleeping and so much reading, his brain dried up and he went completely out of his mind. -Don Quixote.',
   'We cast a shadow on something wherever we stand, and it is no good moving from place to place to save things; because the shadow always follows. Choose a place where you won\'t do harm - yes, choose a place where you won\'t do very much harm and stand in it for all you are worth, facing the sunshine. -A Room with a View.',
    'Memories warm you up from the inside. But they also tear you apart. -Kafka on the Shore.',
    'You are your best thing -Beloved.',
'Some birds are not meant to be caged, that\'s all. Their feathers are too bright, their songs too sweet and wild. So you let them go, or when you open the cage to feed them they somehow fly out past you. And the part of you that knows it was wrong to imprison them in the first place rejoices, but still, the place where you live is that much drabber and empty for their departure. -Shawshank Redemption.'

]

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}

This is the HTML section.

<!DOCTYPE html>

    <title>Quote Gen</title>

Simple Quote Generator

    <button onclick = "newQuote()">New Quote</button>

Body:
<!DOCTYPE html>
<html>
<head>
    <title>Quote Gen</title>
</head>

<body>
    <h1>Simple Quote Generator</h1>
    <div id="quoteDisplay">
    </div>
    <button onclick = "newQuote()">New Quote</button>
    <script>
     var quotes = [
'To be or not to be, that is the question. -Hamlet',
'Maybe ever\’body in the whole damn world is scared of each other. -Of Mice and Men.',
'Life is to be lived, not controlled; and humanity is won by continuing to play in face of certain defeat. -Invisible Man.',
 'Terror made me cruel -Wuthering Heights.',
 'Some men get the world, some men get ex-hookers and a trip to Arizona. You\'re in with the former, but my God I don\'t envy the blood on your conscience. -LA Confidential.',
 'The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars. -On The Road.',
 'It was a bright cold day in April, and the clocks were striking thirteen. -1984.',
 'We were the people who were not in the papers. We lived in the blank white spaces at the edges of print. It gave us more freedom. We lived in the gaps between the stories. -A Handmaiden\'s Tale.',
 'It sounds plausible enough tonight, but wait until tomorrow. Wait for the common sense of the morning. -The Time Machine.',
 'It\'s much better to do good in a way that no one knows anything about it. -Anna Karenina.',
 'Life appears to me too short to be spent in nursing animosity or registering wrongs. -Charlotte Bronte.',
  'You forget what you want to remember, and you remember what you want to forget. -The Road.',
  'There is an idea of a Patrick Bateman, some kind of abstraction, but there is no real me, only an entity, something illusory, and though I can hide my cold gaze and you can shake my hand and feel flesh gripping yours and maybe you can even sense our lifestyles are probably comparable: I simply am not there. -American Psycho.',
  'Finally, from so little sleeping and so much reading, his brain dried up and he went completely out of his mind. -Don Quixote.',
   'We cast a shadow on something wherever we stand, and it is no good moving from place to place to save things; because the shadow always follows. Choose a place where you won\'t do harm - yes, choose a place where you won\'t do very much harm, and stand in it for all you are worth, facing the sunshine. -A Room with a View.',
    'Memories warm you up from the inside. But they also tear you apart. -Kafka on the Shore.',
    'You are your best thing -Beloved.',
'Some birds are not meant to be caged, that\'s all. Their feathers are too bright, their songs too sweet and wild. So you let them go, or when you open the cage to feed them they somehow fly out past you. And the part of you that knows it was wrong to imprison them in the first place rejoices, but still, the place where you live is that much more drab and empty for their departure. -Shawshank Redemption.'

]

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}

    </script>
</body>

</html>


问:
Changing Specific Cell color background at JTable
How to change specific cell background on my table?

答:
Posting a full code snippet will enable the community to better assist you.

However, explore using a custom Table cell renderer for this purpose. In which you can use if statements or for loops to manipulate the cells that you'll want to have different background color assigned to.

A sample code for a custom table cell renderer can be found here: Color Renderer class from Java Tutorial TableDialogEdit Demo


问:
F# - Generate Random Subset of List With Sums Of Singles And Pairs
I would like to generate an output list, which is a randomly generated subset of the original input list of size count and separately sum the singles and pairs in the output list, I show three sample output lists and their associated singles and pairs sums in the code below:</p>

```<code>let input = [1; 1; 2; 2; 3; 3; 4; 4; 5; 5; 6; 6; 7; 7; 8; 9; 10; 11]
let count = 11
let random = System.Random()
let output =
    List.map (fun x -> input.[random.Next(input.Length)])
    input
    |> Seq.take(count)
    |> Seq.toList

printfn "%A" output

// Output: [1; 1; 2; 2; 3; 3; 4; 4; 5; 5; 6]

// Sample 1: [1; 1; 2; 2; 3; 3; 4; 5; 8; 9; 11]
// Singles: 5 Pairs: 3
// Sample 2: [1; 2; 2; 3; 4; 5; 5; 6; 6; 7; 7]
// Singles: 3 Pairs: 4
// Sample 3: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11]
// Singles: 11 Pairs: 0
</code>```

答:
You have one error in your code, input should come on the same line as your map, or alternatively pipe into it. Otherwise you can just accomplish what you want with functions:

```<code>let output =
    input
    |> List.map (fun x -> input.[random.Next(input.Length)])
    |> Seq.take(count)
    |> Seq.countBy id |> Seq.groupBy snd |> Seq.map (snd >> Seq.length)
    |> Seq.toList
</code>```

Obviously you have no guarantee that you only will get singles or pairs.

Add 1

Your random function doesn't do what you think it does. It randomly selects elements from your original list, however you have no guarantee that the random number generator won't give you the same number three times in a row for example. So you can end up with [10,10,10] in the list. So for your second comment, in case you just want to shuffle the list, use SortBy. And for your first comment, I just defined a record that keeps the shuffled list and also the count. You would need to add some more error handling logic as depending on the count, it's possible to get a list with only singles or pairs. Also I made output into a function that takes two parameters, the input list and the count. It's more idiomatic and easier to work with.

```<code>type ShuffledList = {
    counts : int list
    original : int list
}

let output input count =
    let original =
        input
        |> List.sortBy (fun _ -> random.Next())
        |> Seq.take(count) |> Seq.toList
    let counts =
        original
        |> Seq.countBy id |> Seq.groupBy snd |> Seq.map (snd >> Seq.length)
        |> Seq.toList
    {counts = counts ; original = original}

output input count
</code>```

Body:
I would like to generate an output list, which is a randomly generated subset of the original input list of size count and separately sum the singles and pairs in the output list, I show three sample output lists and their associated singles and pairs sums in the code below:

let input = [1; 1; 2; 2; 3; 3; 4; 4; 5; 5; 6; 6; 7; 7; 8; 9; 10; 11]
let count = 11
let random = System.Random()
let output =
    List.map (fun x -> input.[random.Next(input.Length)])
    input
    |> Seq.take(count)
    |> Seq.toList

printfn "%A" output

// Output: [1; 1; 2; 2; 3; 3; 4; 4; 5; 5; 6]

// Sample 1: [1; 1; 2; 2; 3; 3; 4; 5; 8; 9; 11]
// Singles: 5 Pairs: 3
// Sample 2: [1; 2; 2; 3; 4; 5; 5; 6; 6; 7; 7]
// Singles: 3 Pairs: 4
// Sample 3: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11]
// Singles: 11 Pairs: 0

Body:
You have one error in your code, input should come on the same line as your map, or alternatively pipe into it. Otherwise you can just accomplish what you want with functions:

let output =
    input
    |> List.map (fun x -> input.[random.Next(input.Length)])
    |> Seq.take(count)
    |> Seq.countBy id |> Seq.groupBy snd |> Seq.map (snd >> Seq.length)
    |> Seq.toList

Obviously you have no guarantee that you only will get singles or pairs.

Add 1

Your random function doesn't do what you think it does. It randomly selects elements from your original list, however you have no guarantee that the random number generator won't give you the same number three times in a row for example. So you can end up with [10,10,10] in the list. So for your second comment, in case you just want to shuffle the list, use SortBy. And for your first comment, I just defined a record that keeps the shuffled list and also the count. You would need to add some more error handling logic as depending on the count, it's possible to get a list with only singles or pairs. Also I made output into a function that takes two parameters, the input list and the count. It's more idiomatic and easier to work with.

type ShuffledList = {
    counts : int list
    original : int list
}

let output input count =
    let original =
        input
        |> List.sortBy (fun _ -> random.Next())
        |> Seq.take(count) |> Seq.toList
    let counts =
        original
        |> Seq.countBy id |> Seq.groupBy snd |> Seq.map (snd >> Seq.length)
        |> Seq.toList
    {counts = counts ; original = original}

output input count


问:
Antlr4 expressions are chaining
from what i have read the way i defined my 'expression' this should provide me with the following:

This is my input:

```<code>xyz = a + b + c + d
</code>```

This should be my output:

```<code>xyz = ( ( a + b ) + ( c + d) )
</code>```

But instead i get:

```<code>xyz = ( a + (b + (c + d) ) )
</code>```

I bet this has been solved before and i just wasnt able to find the solution.

```<code>statementList       : s=statement sl=statementList  #multipleStatementList
                    | s=statement                   #singleStatementList
                    ;

statement           : statementAssign
                    | statementIf
                    ;

statementAssign     : var=VAR ASSIGN expr=expression        #overwriteStatementAssign
                    | var=VAR PLUS ASSIGN expr=expression   #addStatementAssign
                    | var=VAR MINUS ASSIGN expr=expression  #subStatementAssign
                    ;

                    ;

expression          : BRACKET_OPEN expr=expression BRACKET_CLOSE                    #priorityExp
                    | left=expression operand=('*'|'/') right=expression            #mulDivExp
                    | left=expression operand=('+'|'-') right=expression            #addSubExp
                    | <assoc=right> left=expression POWER right=expression          #powExp
                    | variable=VAR                                                  #varExp
                    | number=NUMBER                                                 #numExp
                    ;

BRACKET_OPEN        : '(' ;
BRACKET_CLOSE       : ')' ;

ASTERISK            : '*' ;
SLASH               : '/' ;
PLUS                : '+' ;
MINUS               : '-' ;
POWER               : '^' ;
MODULO              : '%' ;

ASSIGN              : '=' ;

NUMBER              : [0-9]+ ;

VAR                 : [a-z][a-zA-Z0-9\-]* ;

WS                  : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
</code>```

答:
If you want the expression

```<code> xyz = ( ( a + b ) + ( c + d) )
</code>```

Then you'll need to control the binding of the + operator with parentheses just as you've done in your expected output.  Otherwise, with

```<code> xyz = ( a + (b + (c + d) ) )
</code>```

is the way the parser is going to parse it because  all the + operators have the same precedence, and the parser continues parsing until it reaches the end of the expression.

It recursively applies

```<code>left=expression operand=('+'|'-') right=expression
</code>```

until the expression is completed.

and you get the grouping you got.  So use those parentheses, that's what they're for if you want to force the order of expression evaluation.  ;)

If you change your input to

xyz = a * b + c + d

you'll see what I mean about the precedence, because the multiplication rule appears before the addition rule -- and hence binds earlier -- which is a mathematical convention (lacking parentheses to group terms.)

You're doing it right and the parser is too.  Just group what you want if you want a specific binding order.

Title: Antlr4 expressions are chaining

Body:
from what i have read the way i defined my 'expression' this should provide me with the following:

This is my input:

xyz = a + b + c + d

This should be my output:

xyz = ( ( a + b ) + ( c + d) )

But instead i get:

xyz = ( a + (b + (c + d) ) )

I bet this has been solved before and i just wasnt able to find the solution.

statementList       : s=statement sl=statementList  #multipleStatementList
                    | s=statement                   #singleStatementList
                    ;

statement           : statementAssign
                    | statementIf
                    ;

statementAssign     : var=VAR ASSIGN expr=expression        #overwriteStatementAssign
                    | var=VAR PLUS ASSIGN expr=expression   #addStatementAssign
                    | var=VAR MINUS ASSIGN expr=expression  #subStatementAssign
                    ;

                    ;

expression          : BRACKET_OPEN expr=expression BRACKET_CLOSE                    #priorityExp
                    | left=expression operand=('*'|'/') right=expression            #mulDivExp
                    | left=expression operand=('+'|'-') right=expression            #addSubExp
                    | <assoc=right> left=expression POWER right=expression          #powExp
                    | variable=VAR                                                  #varExp
                    | number=NUMBER                                                 #numExp
                    ;

BRACKET_OPEN        : '(' ;
BRACKET_CLOSE       : ')' ;

ASTERISK            : '*' ;
SLASH               : '/' ;
PLUS                : '+' ;
MINUS               : '-' ;
POWER               : '^' ;
MODULO              : '%' ;

ASSIGN              : '=' ;

NUMBER              : [0-9]+ ;

VAR                 : [a-z][a-zA-Z0-9\-]* ;

WS                  : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

Body:
If you want the expression

 xyz = ( ( a + b ) + ( c + d) )

Then you'll need to control the binding of the + operator with parentheses just as you've done in your expected output.  Otherwise, with

 xyz = ( a + (b + (c + d) ) )

is the way the parser is going to parse it because  all the + operators have the same precedence, and the parser continues parsing until it reaches the end of the expression.

It recursively applies

left=expression operand=('+'|'-') right=expression

until the expression is completed.

and you get the grouping you got.  So use those parentheses, that's what they're for if you want to force the order of expression evaluation.  ;)

If you change your input to

xyz = a * b + c + d

you'll see what I mean about the precedence, because the multiplication rule appears before the addition rule -- and hence binds earlier -- which is a mathematical convention (lacking parentheses to group terms.)

You're doing it right and the parser is too.  Just group what you want if you want a specific binding order.


问:
Android start activity when app started
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);
</code>```

My guess is that to create intent about view.
but not sure how to do it

答:
Find out the first activity which is displayed to the user when he starts the app from your Manifest.xml .

In this activity's onCreate() method add:

```<code>TextView tvURL = (TextView)findViewById(R.id.txtURL);
String url = tvURL.getText().toString();
Log.i("URL", "Opening URL with WebView :" + url);
final long startTime = System.currentTimeMillis();
WebView webView = (WebView)findViewById(R.id.webView);
//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.loadUrl(url);
</code>```

Use intent inside onCreate() , if you want to launch your activity

Otherwise you can make any activity as starting activity of your app by using intent-filter tag in Manifest.xml.

Title: Android start activity when app started

Body:
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);

My guess is that to create intent about view.
but not sure how to do it

Body:
Find out the first activity which is displayed to the user when he starts the app from your Manifest.xml .

In this activity's onCreate() method add:

TextView tvURL = (TextView)findViewById(R.id.txtURL);
String url = tvURL.getText().toString();
Log.i("URL", "Opening URL with WebView :" + url);
final long startTime = System.currentTimeMillis();
WebView webView = (WebView)findViewById(R.id.webView);
//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.loadUrl(url);

Use intent inside onCreate() , if you want to launch your activity

Otherwise you can make any activity as starting activity of your app by using intent-filter tag in Manifest.xml.


问:
Async threadsafe Get from MemoryCache
I have created a async cache that uses .NET MemoryCache underneath.
This is the code:

```<code>public async Task<T> GetAsync(string key, Func<Task<T>> populator, TimeSpan expire, object parameters)
{
    if(parameters != null)
        key += JsonConvert.SerializeObject(parameters);

    if(!_cache.Contains(key))
    {
        var data = await populator();
        lock(_cache)
        {
            if(!_cache.Contains(key)) //Check again but locked this time
                _cache.Add(key, data, DateTimeOffset.Now.Add(expire));
        }
    }

    return (T)_cache.Get(key);
}
</code>```

I think the only downside is that I need to do the await outside the lock so the populator isn't thread safe, but since the await can't reside inside a lock I guess this is the best way. Are there any pitfalls that I have missed?

Update: A version of Esers answer that is also threadsafe when another thread invalidates the cache:

```<code>public async Task<T> GetAsync(string key, Func<Task<T>> populator, TimeSpan expire, object parameters)
{
    if(parameters != null)
        key += JsonConvert.SerializeObject(parameters);

    var lazy = new Lazy<Task<T>>(populator, true);
    _cache.AddOrGetExisting(key, lazy, DateTimeOffset.Now.Add(expire));
    return ((Lazy<Task<T>>) _cache.Get(key)).Value;
}
</code>```

It can however be slower because it creates Lazy instances that never will be executed and it uses Lazy in full threadsafe mode LazyThreadSafetyMode.ExecutionAndPublication

Update with new benchmark (Higher is better)

```<code>Lazy with lock      42535929
Lazy with GetOrAdd  41070320 (Only solution that is completely thread safe)
Semaphore           64573360
</code>```

答:
The current answers use the somewhat outdated System.Runtime.Caching.MemoryCache. They also contain subtle race conditions (see comments). Finally, not all of them allow the timeout to be dependent on the value to be cached.

Here's my attempt using the new Microsoft.Extensions.Caching.Memory (used by ASP.NET Core):

```<code>//Add NuGet package: Microsoft.Extensions.Caching.Memory

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;

MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

public Task<T> GetOrAddAsync<T>(
        string key, Func<Task<T>> factory, Func<T, TimeSpan> expirationCalculator)
{
    return _cache.GetOrCreateAsync(key, async cacheEntry =>
    {
        var cts = new CancellationTokenSource();
        cacheEntry.AddExpirationToken(new CancellationChangeToken(cts.Token));
        var value = await factory().ConfigureAwait(false);
        cts.CancelAfter(expirationCalculator(value));
        return value;
    });
}
</code>```

Sample usage:

```<code>await GetOrAddAsync("foo", () => Task.Run(() => 42), i  => TimeSpan.FromMilliseconds(i)));
</code>```

Note that it is not guaranteed for the factory method to be called only once (see https://github.com/aspnet/Caching/issues/240).

ContentLicense: CC BY-SA 4.0

Title: Async threadsafe Get from MemoryCache

Body:
I have created a async cache that uses .NET MemoryCache underneath.
This is the code:

public async Task<T> GetAsync(string key, Func<Task<T>> populator, TimeSpan expire, object parameters)
{
    if(parameters != null)
        key += JsonConvert.SerializeObject(parameters);

    if(!_cache.Contains(key))
    {
        var data = await populator();
        lock(_cache)
        {
            if(!_cache.Contains(key)) //Check again but locked this time
                _cache.Add(key, data, DateTimeOffset.Now.Add(expire));
        }
    }

    return (T)_cache.Get(key);
}

I think the only downside is that I need to do the await outside the lock so the populator isn't thread safe, but since the await can't reside inside a lock I guess this is the best way. Are there any pitfalls that I have missed?

Update: A version of Esers answer that is also threadsafe when another thread invalidates the cache:

public async Task<T> GetAsync(string key, Func<Task<T>> populator, TimeSpan expire, object parameters)
{
    if(parameters != null)
        key += JsonConvert.SerializeObject(parameters);

    var lazy = new Lazy<Task<T>>(populator, true);
    _cache.AddOrGetExisting(key, lazy, DateTimeOffset.Now.Add(expire));
    return ((Lazy<Task<T>>) _cache.Get(key)).Value;
}

It can however be slower because it creates Lazy instances that never will be executed and it uses Lazy in full threadsafe mode LazyThreadSafetyMode.ExecutionAndPublication

Update with new benchmark (Higher is better)

Lazy with lock      42535929
Lazy with GetOrAdd  41070320 (Only solution that is completely thread safe)
Semaphore           64573360

Body:
The current answers use the somewhat outdated System.Runtime.Caching.MemoryCache. They also contain subtle race conditions (see comments). Finally, not all of them allow the timeout to be dependent on the value to be cached.

Here's my attempt using the new Microsoft.Extensions.Caching.Memory (used by ASP.NET Core):

//Add NuGet package: Microsoft.Extensions.Caching.Memory

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;

MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

public Task<T> GetOrAddAsync<T>(
        string key, Func<Task<T>> factory, Func<T, TimeSpan> expirationCalculator)
{
    return _cache.GetOrCreateAsync(key, async cacheEntry =>
    {
        var cts = new CancellationTokenSource();
        cacheEntry.AddExpirationToken(new CancellationChangeToken(cts.Token));
        var value = await factory().ConfigureAwait(false);
        cts.CancelAfter(expirationCalculator(value));
        return value;
    });
}

Sample usage:

await GetOrAddAsync("foo", () => Task.Run(() => 42), i  => TimeSpan.FromMilliseconds(i)));

Note that it is not guaranteed for the factory method to be called only once (see https://github.com/aspnet/Caching/issues/240).


问:
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?

答:
From Wikipedia:

The value returned from the main function becomes the exit status of the process, though the C standard only ascribes specific meaning to two values: EXIT_SUCCESS (traditionally zero) and EXIT_FAILURE. The meaning of other possible return values is implementation-defined.

OwnerDisplayName: kasperasky

OwnerDisplayName: Bbetances


问:
php search help
following are my posted variables from search form:

```<code>$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];
</code>```

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

```<code>if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....
</code>```

i need some professional approach for this.

答:
Something like this should do:

```<code>$fields = array('city', 'location' /* ... */);
$conditions = array();

foreach ($fields as $field) {
    if (!empty($_REQUEST[$field])) {
        $conditions[] = 'column LIKE "%'.mysql_real_escape_string($_REQUEST[$field]).'%"';
    }
}

$query = 'SELECT row FROM table WHERE '.implode(' OR ', $conditions);
</code>```

You need to adjust this to suit your needs (OR or AND for example).

Title: php search help

Body:
following are my posted variables from search form:

$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....

i need some professional approach for this.

Body:
Something like this should do:

$fields = array('city', 'location' /* ... */);
$conditions = array();

foreach ($fields as $field) {
    if (!empty($_REQUEST[$field])) {
        $conditions[] = 'column LIKE "%'.mysql_real_escape_string($_REQUEST[$field]).'%"';
    }
}

$query = 'SELECT row FROM table WHERE '.implode(' OR ', $conditions);

You need to adjust this to suit your needs (OR or AND for example).


问:
Adding a response header in an ExceptionFilterAttribute in ASP .Net Core
I'm trying to add a header to responses from a .Net core Web API when an exception occurs.

I'm using an ExceptionFilterAttribute...

```<code>public class ExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
        base.OnException(context);
    }
}
</code>```

For some reason the header is not sent to the client. I'm guessing this is something to do with responses already being formed at this point so they can't be changed?

I've got a custom middleware that adds a correlation id to the request context and then outputs it into the response headers. This doesn't fire when an exception occurs though so I need another way of doing it hence trying to use the filter.

What should I change to get this to work?

答:
Explicitly set context.Result to write output from an exception filter:

```<code>public override void OnException(ExceptionContext context)
{
    context.HttpContext.Response.Headers.Add("CorrelationId", new string[] { "12345" });

    context.Result = new ObjectResult(null) { StatusCode = 500 };
    context.ExceptionHandled = true;

    base.OnException(context);
}
</code>```

This will add the header to the actual response.

Body:
I'm trying to add a header to responses from a .Net core Web API when an exception occurs.

I'm using an ExceptionFilterAttribute...

public class ExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
        base.OnException(context);
    }
}

For some reason the header is not sent to the client. I'm guessing this is something to do with responses already being formed at this point so they can't be changed?

I've got a custom middleware that adds a correlation id to the request context and then outputs it into the response headers. This doesn't fire when an exception occurs though so I need another way of doing it hence trying to use the filter.

What should I change to get this to work?

Body:
Explicitly set context.Result to write output from an exception filter:

public override void OnException(ExceptionContext context)
{
    context.HttpContext.Response.Headers.Add("CorrelationId", new string[] { "12345" });

    context.Result = new ObjectResult(null) { StatusCode = 500 };
    context.ExceptionHandled = true;

    base.OnException(context);
}

This will add the header to the actual response.


问:
show dialog in rcp 4 eclipse
I'm new in the eclipse rcp development. I'd like to create a method that show a dialog windows. I created a a dialog in Application.e4xmi and I'm not able to show that using command with execute method.

Somebody can help me?

答:
Use of the MDialog (and MWizard) class is not recommended as they are due to be reworked (see bug 460826).

Just use a 'traditional' JFace Dialog (or one of the derived classes).

Title: show dialog in rcp 4 eclipse


问:
nicescroll, need to resize automatically when div changes it size
I have
 tag, which contains lot of text and it's usually showed with a jquery nicescroll beside, but if it contains an element which can change height 'some collapsable element) of the
 tag and nicescroll doesn't want to reload.

my code:

```<code><article class="item">
  <div class="reference">some text</div>
  <a href="#long-2" data-toggle="collapse" class="reference-long arr_down"></a>
  <div id="long-2" class="collapse">some text</div>
</div>
</code>```

if I click on a, the article becomes bigger but I need to reload the nice scroll, when the collapsed item is clossed again, I need do the same.

jquery, which works just sometimes and doesn't work in the Safari browser:

```<code>$(document).ready(
function() {
$("article").niceScroll({cursorcolor:"#fff",autohidemode:false, zindex: 999});
}
);
$(function() {
$('.reference-long').click(function(){
    $("article").getNiceScroll().remove();
    $("article").niceScroll({cursorcolor:"#fff",autohidemode:false, zindex: 999});
  });
});
</code>```

答:
this is the solution

```<code>$("article").getNiceScroll().resize();
</code>```

but note that if you are using any animation, you must allow the animation to be completed before calling the .resize() function.

Example:

```<code>$('.reference-long').click(function(){
    $("#long-2").slideToggle(function(){
        $("article").getNiceScroll().resize();
    });
});
</code>```

Body:
I have
 tag, which contains lot of text and it's usually showed with a jquery nicescroll beside, but if it contains an element which can change height 'some collapsable element) of the
 tag and nicescroll doesn't want to reload.

my code:

some text

some text

if I click on a, the article becomes bigger but I need to reload the nice scroll, when the collapsed item is clossed again, I need do the same.

jquery, which works just sometimes and doesn't work in the Safari browser:

$(document).ready(
function() {
$("article").niceScroll({cursorcolor:"#fff",autohidemode:false, zindex: 999});
}
);
$(function() {
$('.reference-long').click(function(){
    $("article").getNiceScroll().remove();
    $("article").niceScroll({cursorcolor:"#fff",autohidemode:false, zindex: 999});
  });
});

Body:
this is the solution

$("article").getNiceScroll().resize();

but note that if you are using any animation, you must allow the animation to be completed before calling the .resize() function.

Example:

$('.reference-long').click(function(){
    $("#long-2").slideToggle(function(){
        $("article").getNiceScroll().resize();
    });
});


问:
How to label duplicate groups in pandas?
I have a DataFrame:

```<code>>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar
</code>```

I need to find all the duplicate groups and label them with sequential dgroup_id's:

```<code>>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2
</code>```

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

```<code>import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))
</code>```

This leads to:

```<code>>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0
</code>```

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

答:
```<code>df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})
key_set = set(df['A'])
df_a = pd.DataFrame(list(key_set))
df_a['dgroup_id'] = df_a.index
result = pd.merge(df,df_a,left_on='A',right_on=0,how='left')

In [32]: result.drop(0,axis=1)
Out[32]:
     A  dgroup_id
0  foo        2
1  bar        0
2  foo        2
3  baz        1
4  foo        2
5  bar        0
</code>```

Body:
I have a DataFrame:

>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar

I need to find all the duplicate groups and label them with sequential dgroup_id's:

>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))

This leads to:

>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.


问:
Laravel 5.4 + jQuery CORS Request
I have two laravel applications, one that acts as an admin panel and the other as an API server.

I am trying to do a jQuery AJAX Post request to the API but the behaviour of the responses seem totally weird.

I am using barryvdh/laravel-cors to enable CORS on the API. I also tried to disable it and add the "options" request manually but I still get the same behaviour.

The issue appears to be with the requests that are made after the preflight request. Here is the order of how they are sent (note that the inital request is a POST):

The preflight request (OPTIONS - works fine)

A GET request to the API endpoint (no idea why it does it). It returns a 302 Found redirect back to the referer (to the client)

A POST request to the API endpoint. Same 302 redirect back.

An OPTIONS request to the admin url from which the request is sent (Which fails because of no CORS on the admin app).

Here is an image with the flow of the request:
Request Flow (Chrome network panel)

I have to mention that I do not do any redirects in the controller nor added any middleware that would do it.

答:
So aparently, none of the methods that determine if the request must be answered as JSON worked in this case, specifically $request->ajax() and $request->wantsJSON();

I fixed the issue by overriding the function buildFailedValidationResponse on my base ApiController by making it always return a JSON response.

```<code>protected function buildFailedValidationResponse(Request $request, array $errors)
{
    return new JsonResponse($errors, 422);
}
</code>```

Title: Laravel 5.4 + jQuery CORS Request

Body:
So aparently, none of the methods that determine if the request must be answered as JSON worked in this case, specifically $request->ajax() and $request->wantsJSON();

I fixed the issue by overriding the function buildFailedValidationResponse on my base ApiController by making it always return a JSON response.

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    return new JsonResponse($errors, 422);
}


问:
Naming of parse string and assign value
Sometimes I have this kind of code, Any advise to improve the readability
of result[0], result[1]...event the naming of result</p>

```<code>var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};
</code>```

答:
Create Extension Method On The String Class Which Will Do The Split and Return an Object Of ProductData Class </p>

```<code>public static YourProductClass GetProductFromString(this string CompinedString)
{
   // Do You Splitting Stuff Here and Assign The Values From String To NewProduct
   return NewProduct;
}
</code>```

<p>Then In You Code </p>

```<code>var ProductData  = "Egg 1.24 1.36".GetProductFromString();
</code>```

Title: Naming of parse string and assign value

Body:
Sometimes I have this kind of code, Any advise to improve the readability
of result[0], result[1]...event the naming of result

var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};

Body:
Create Extension Method On The String Class Which Will Do The Split and Return an Object Of ProductData Class

public static YourProductClass GetProductFromString(this string CompinedString)
{
   // Do You Splitting Stuff Here and Assign The Values From String To NewProduct
   return NewProduct;
}

Then In You Code

var ProductData  = "Egg 1.24 1.36".GetProductFromString();


问:
How to fix the image to a div when it's height is greater than its width?
In Facebook, when we post any size images, it shows perfectly on the timeline. How do they do this?

I have tried following.

Setting the image as background of the div.

CSS - width: 100%; height:auto;

Both did not work, All over the stack overflow there is no option for this,finally decided to add this.

答:
Asides from all the answers, stating about the css used on actual  tags.

Facebook will also run all uploads through a server side script which will do the resizing and compression.

They probably have their own in house code for doing this however you could use Imagemagick to do the same thing, including sizing and cropping uploads, so as to always maintain the same width to height ratios (at least for thumbnails).

Some examples can be found here: http://php.net/manual/en/book.imagick.php

For a pure css option you could look into the background image property while utilising the positioning arguments.

Here's a snippet taken from w3cschools.

```<code>div {
Width:100px;
Height:100px;
background-image:url('smiley.gif');
background-repeat:no-repeat;
background-position:50% 50%;
}
</code>```

https://www.w3schools.com/cssref/pr_background-position.asp

Body:
Asides from all the answers, stating about the css used on actual <img> tags.

Facebook will also run all uploads through a server side script which will do the resizing and compression.

They probably have their own in house code for doing this however you could use Imagemagick to do the same thing, including sizing and cropping uploads, so as to always maintain the same width to height ratios (at least for thumbnails).

Some examples can be found here: http://php.net/manual/en/book.imagick.php

For a pure css option you could look into the background image property while utilising the positioning arguments.

Here's a snippet taken from w3cschools.

div {
Width:100px;
Height:100px;
background-image:url('smiley.gif');
background-repeat:no-repeat;
background-position:50% 50%;
}

https://www.w3schools.com/cssref/pr_background-position.asp


问:
MVC - @Html.Dropdown not populating values from ViewBag
I'm pretty new to MVC.

I'm trying to develop an MVC webpage. I'm trying to use @HtmlDropDownList(), which would have to populate values from my web.config, using  a ViewBag. The page is getting rendered with the correct values, however on the output screen, there is no output. The dropdown shows only empty values on screen. Can someone please help!

Webconfig code:

```<code><add key="ddlStreams" value="Las Vegas|India|Australia"/>
</code>```

Controller code:

```<code> public ActionResult Index()
        {
            string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
            ViewBag.ddlStreamsVB =  reportTypes.Split('|')
                .Select((value) => new SelectListItem { Value = value.ToString() });
            GetData getdata = new GetData();
            return View(getdata.GetDataFromTable());
        }
</code>```

This is my view:

```<code><div >
    <div class="form-control">
        <div class="row">

            <div class="col-sm-4">
                @Html.Label("Stream name")
            </div>
            <div class="col-md-8">
                @Html.DropDownList("ddlStreamsVB1", ViewBag.ddlStreamsVB as IEnumerable<SelectListItem>)
            </div>
        </div>
    </div></div>
</code>```

The rendered HTML on clicking on View source:

```<code><div >
        <div class="form-control">
            <div class="row">

                <div class="col-sm-4">
                    <label for="Stream_name">Stream name</label>
                </div>
                <div class="col-md-8">
                    <select id="ddlStreamsVB1" name="ddlStreamsVB1"><option value="Las Vegas"></option>
<option value="India"></option>
<option value="Australia"></option>
</select>
                </div>
            </div>
        </div>

    </div>
</code>```

The final output :(
Final output here!!

答:
Issue is you are not setting Text prop of SelectListItem, update as below:</p>

```<code>ViewBag.ddlStreamsVB =  reportTypes.Split('|')
            .Select((value) => new SelectListItem
            { Value= value.ToString(),
             Text = value
            });
</code>```

Body:
I'm pretty new to MVC.

I'm trying to develop an MVC webpage. I'm trying to use @HtmlDropDownList(), which would have to populate values from my web.config, using  a ViewBag. The page is getting rendered with the correct values, however on the output screen, there is no output. The dropdown shows only empty values on screen. Can someone please help!

Webconfig code:

<add key="ddlStreams" value="Las Vegas|India|Australia"/>

Controller code:

 public ActionResult Index()
        {
            string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
            ViewBag.ddlStreamsVB =  reportTypes.Split('|')
                .Select((value) => new SelectListItem { Value = value.ToString() });
            GetData getdata = new GetData();
            return View(getdata.GetDataFromTable());
        }

This is my view:

                @Html.Label("Stream name")

                @Html.DropDownList("ddlStreamsVB1", ViewBag.ddlStreamsVB as IEnumerable<SelectListItem>)

The rendered HTML on clicking on View source:

                    Stream name

                    <select id="ddlStreamsVB1" name="ddlStreamsVB1"><option value="Las Vegas"></option>
<option value="India"></option>
<option value="Australia"></option>
</select>

The final output :(
Final output here!!

Body:
Issue is you are not setting Text prop of SelectListItem, update as below:

ViewBag.ddlStreamsVB =  reportTypes.Split('|')
            .Select((value) => new SelectListItem
            { Value= value.ToString(),
             Text = value
            });


问:
Custom form of progress bar
I want to create app in which will be free-form progressbar like this:

Tell me please how can this be done? Perhaps some kind of example.

Thanks.

答:
you can start from this simple custom view (the main idea is to use PathMeasure#getSegment() method):

```<code>class V extends View implements View.OnClickListener {
    Path segment = new Path();
    Paint paint = new Paint();
    PathMeasure pm;

    public V(Context context) {
        super(context);
        setOnClickListener(this);
        paint.setColor(0xaa00ff00);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(48);
        paint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Path src = new Path();

        src.moveTo(16.000000f, 1.630000f);
        src.lineTo(22.030001f, 1.630000f);
        src.cubicTo(23.420000f, 1.620000f, 24.770000f, 2.390000f, 25.469999f, 3.590000f);
        src.lineTo(31.469999f, 14.030000f);
        src.cubicTo(32.169998f, 15.240000f, 32.169998f, 16.790001f, 31.469999f, 18.000000f);
        src.lineTo(25.440001f, 28.440001f);
        src.cubicTo(24.740000f, 29.629999f, 23.379999f, 30.379999f, 22.000000f, 30.379999f);
        src.lineTo(9.970000f, 30.379999f);
        src.cubicTo(8.580000f, 30.379999f, 7.230000f, 29.610001f, 6.530000f, 28.410000f);
        src.lineTo(0.530000f, 17.969999f);
        src.cubicTo(-0.170000f, 16.760000f, -0.170000f, 15.210000f, 0.530000f, 14.000000f);
        src.lineTo(6.560000f, 3.560000f);
        src.cubicTo(7.260000f, 2.370000f, 8.620000f, 1.620000f, 10.000000f, 1.630000f);
        src.close();

        Matrix m = new Matrix();
        RectF srcRect = new RectF(0, 0, 32, 32);
        RectF dstRect = new RectF(0, 0, w, h);
        dstRect.inset(paint.getStrokeWidth() / 2, paint.getStrokeWidth() / 2);
        m.setRectToRect(srcRect, dstRect, Matrix.ScaleToFit.CENTER);
        Path dst = new Path();
        src.transform(m, dst);
        pm = new PathMeasure(dst, true);
        pm.getSegment(0, pm.getLength() / 2, segment, true);
        segment.rLineTo(0, 0);
    }

    void setProgress(float progress) {
        segment.reset();
        float length = pm.getLength();
        float start = progress % length;
        float end = (progress + length / 2) % length;
        if (start < end) {
            pm.getSegment(start, end, segment, true);
        } else {
            pm.getSegment(start, length, segment, true);
            pm.getSegment(0, end, segment, true);
        }
        segment.rLineTo(0, 0);
        invalidate();
    }

    @Override
    public void onClick(View v) {
        ObjectAnimator.ofFloat(this, "progress", 0, 10 * pm.getLength()).setDuration(10 * 2500).start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(segment, paint);
    }
}
</code>```

~

Title: Custom form of progress bar

Body:
you can start from this simple custom view (the main idea is to use PathMeasure#getSegment() method):

class V extends View implements View.OnClickListener {
    Path segment = new Path();
    Paint paint = new Paint();
    PathMeasure pm;

    public V(Context context) {
        super(context);
        setOnClickListener(this);
        paint.setColor(0xaa00ff00);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(48);
        paint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Path src = new Path();

        src.moveTo(16.000000f, 1.630000f);
        src.lineTo(22.030001f, 1.630000f);
        src.cubicTo(23.420000f, 1.620000f, 24.770000f, 2.390000f, 25.469999f, 3.590000f);
        src.lineTo(31.469999f, 14.030000f);
        src.cubicTo(32.169998f, 15.240000f, 32.169998f, 16.790001f, 31.469999f, 18.000000f);
        src.lineTo(25.440001f, 28.440001f);
        src.cubicTo(24.740000f, 29.629999f, 23.379999f, 30.379999f, 22.000000f, 30.379999f);
        src.lineTo(9.970000f, 30.379999f);
        src.cubicTo(8.580000f, 30.379999f, 7.230000f, 29.610001f, 6.530000f, 28.410000f);
        src.lineTo(0.530000f, 17.969999f);
        src.cubicTo(-0.170000f, 16.760000f, -0.170000f, 15.210000f, 0.530000f, 14.000000f);
        src.lineTo(6.560000f, 3.560000f);
        src.cubicTo(7.260000f, 2.370000f, 8.620000f, 1.620000f, 10.000000f, 1.630000f);
        src.close();

        Matrix m = new Matrix();
        RectF srcRect = new RectF(0, 0, 32, 32);
        RectF dstRect = new RectF(0, 0, w, h);
        dstRect.inset(paint.getStrokeWidth() / 2, paint.getStrokeWidth() / 2);
        m.setRectToRect(srcRect, dstRect, Matrix.ScaleToFit.CENTER);
        Path dst = new Path();
        src.transform(m, dst);
        pm = new PathMeasure(dst, true);
        pm.getSegment(0, pm.getLength() / 2, segment, true);
        segment.rLineTo(0, 0);
    }

    void setProgress(float progress) {
        segment.reset();
        float length = pm.getLength();
        float start = progress % length;
        float end = (progress + length / 2) % length;
        if (start < end) {
            pm.getSegment(start, end, segment, true);
        } else {
            pm.getSegment(start, length, segment, true);
            pm.getSegment(0, end, segment, true);
        }
        segment.rLineTo(0, 0);
        invalidate();
    }

    @Override
    public void onClick(View v) {
        ObjectAnimator.ofFloat(this, "progress", 0, 10 * pm.getLength()).setDuration(10 * 2500).start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(segment, paint);
    }
}

~


问:
clang -cc1 and system includes
I have the following file foo.cpp:

```<code>#include <vector>

struct MyClass
{
  std::vector<int> v;
};
</code>```

It can be successfully compiled with clang (I'm using clang 3.3 on Ubuntu 13.04 32bit):

```<code>clang++ -c foo.cpp
</code>```

Now I want to print AST:

```<code>clang++ -cc1 -ast-print foo.cpp
</code>```

and I've got the following error

```<code>foo.cpp:1:10: fatal error: 'vector' file not found
#include <vector>
         ^
struct MyClass {
};
1 error generated.
</code>```

It looks like clang++ -cc1 doesn't know about system include files etc.
I'm wondering how to set up includes for clang++ -cc1?

答:
@john is correct.  For posterity, the relevant portions of the FAQ are (with names tweaked to match the question) :

clang -cc1 is the frontend, clang is the driver. The driver invokes the frontend with options appropriate for your system. To see these options, run:

```<code>$ clang++ -### -c foo.cpp
</code>```

Some clang command line options are driver-only options, some are frontend-only options. Frontend-only options are intended to be used only by clang developers. Users should not run clang -cc1 directly, because -cc1 options are not guaranteed to be stable.

If you want to use a frontend-only option (“a -cc1 option”), for example -ast-dump, then you need to take the clang -cc1 line generated by the driver and add the option you need. Alternatively, you can run clang -Xclang <option> ... to force the driver [to] pass <option> to clang -cc1.

I did the latter (-Xclang) for emitting precompiled headers:

```<code>/usr/bin/clang++ -x c++-header foo.hpp -Xclang -emit-pch -o foo.hpp.pch <other options>
                                       ^^^^^^^
</code>```

Without the -Xclang, clang++ ignored the -emit-pch.  When I tried -cc1, I had the same problem as the OP — clang++ accepted -emit-pch but didn't have the other options the driver normally provides.

Title: clang -cc1 and system includes

Body:
I have the following file foo.cpp:

#include <vector>

struct MyClass
{
  std::vector<int> v;
};

It can be successfully compiled with clang (I'm using clang 3.3 on Ubuntu 13.04 32bit):

clang++ -c foo.cpp

Now I want to print AST:

clang++ -cc1 -ast-print foo.cpp

and I've got the following error

foo.cpp:1:10: fatal error: 'vector' file not found
#include <vector>
         ^
struct MyClass {
};
1 error generated.

It looks like clang++ -cc1 doesn't know about system include files etc.
I'm wondering how to set up includes for clang++ -cc1?

Body:
@john is correct.  For posterity, the relevant portions of the FAQ are (with names tweaked to match the question) :

clang -cc1 is the frontend, clang is the driver. The driver invokes the frontend with options appropriate for your system. To see these options, run:

$ clang++ -### -c foo.cpp

Some clang command line options are driver-only options, some are frontend-only options. Frontend-only options are intended to be used only by clang developers. Users should not run clang -cc1 directly, because -cc1 options are not guaranteed to be stable.

If you want to use a frontend-only option (“a -cc1 option”), for example -ast-dump, then you need to take the clang -cc1 line generated by the driver and add the option you need. Alternatively, you can run clang -Xclang <option> ... to force the driver [to] pass <option> to clang -cc1.

I did the latter (-Xclang) for emitting precompiled headers:

/usr/bin/clang++ -x c++-header foo.hpp -Xclang -emit-pch -o foo.hpp.pch <other options>
                                       ^^^^^^^

Without the -Xclang, clang++ ignored the -emit-pch.  When I tried -cc1, I had the same problem as the OP — clang++ accepted -emit-pch but didn't have the other options the driver normally provides.


问:
How to create an action from selecting a row from an NSTableView
When I select a row from NSTableView, it is not running the code from tableViewSelectionDidChange method. I had put break points in this method and it is not even going into the method.

Any ideas? Am I missing something in my initialiser?

PersonController.h

```<code>#import <Foundation/Foundation.h>

@interface Person : NSObject {
  IBOutlet NSTableView *personsTable;
  NSMutableArray *personsList;
  NSMutableArray *personCollection;

  IBOutlet NSTextField *selectedPersonName;
  IBOutlet NSTextField *selectedPersonGender;
@private

}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification;

@end
</code>```

PersonController.m

```<code>#import "PersonController.h"
#import "Person.h"

@implementation PersonController

- (id)init
{
    self = [super init];
    if (self) {
        personsList = [[NSMutableArray alloc] init];
        Person *person = [[Person alloc] init];

        // Create person 1
        person.name = @"Bob";
        person.gender = @"male";

        // Append to array
        [personsList addObject:person];
        [person release];

        // Create person 2
        person = [[Person alloc] init];
        person.name = @"Fred";
        person.gender = @"Unknown";

        // Append to array
        [personsList addObject:person];
        [person release];

        [personsTable reloadData];
    }

    return self;
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [personsList count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    Person *person = [personsList objectAtIndex:row];
    NSString *identifier = [tableColumn identifier];

    return [person valueForKey:identifier];
}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    NSInteger selectedRow = [personsTable selectedRow];
    if (selectedRow == -1)
    {
        // these should be localized, but use string constants here for clarity
        [selectedPersonName setStringValue:@"No selection"];
        [selectedPersonGender setStringValue:@"No selection"];
    }
    else
    {
        Person *selectedPerson = [personCollection objectAtIndex:selectedRow];

        [selectedPersonName setStringValue:[selectedPerson name]];
        [selectedPersonGender setStringValue:[selectedPerson gender]];
    }
}

- (void)dealloc
{
    [super dealloc];
}

@end
</code>```

答:
Solution in Swift 3 for most of the events:

Inside tableview view controller :

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    tableView.target = self
    tableView.action = #selector(tableViewDidClick)
}

func tableViewDidClick(){
    let row = tableView.clickedRow
    let column = tableView.clickedColumn
    let unselected = -1

    if row == unselected && column == unselected{
        tableViewDidDeselectRow()
        return
    }else if row != unselected && column != unselected{
        tableViewDidSelectRow(row)
        return
    }else if column != unselected && row == unselected{
        tableviewDidSelectHeader(column)
    }
}

private func tableViewDidDeselectRow() {
    // clicked outside row
}

private func tableViewDidSelectRow(_ row : Int){
    // row did select
}

private func tableviewDidSelectHeader(_ column : Int){
    // header did select
}
</code>```

Body:
When I select a row from NSTableView, it is not running the code from tableViewSelectionDidChange method. I had put break points in this method and it is not even going into the method.

Any ideas? Am I missing something in my initialiser?

PersonController.h

#import <Foundation/Foundation.h>

@interface Person : NSObject {
  IBOutlet NSTableView *personsTable;
  NSMutableArray *personsList;
  NSMutableArray *personCollection;

  IBOutlet NSTextField *selectedPersonName;
  IBOutlet NSTextField *selectedPersonGender;
@private

}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification;

@end

PersonController.m

#import "PersonController.h"
#import "Person.h"

@implementation PersonController

- (id)init
{
    self = [super init];
    if (self) {
        personsList = [[NSMutableArray alloc] init];
        Person *person = [[Person alloc] init];

        // Create person 1
        person.name = @"Bob";
        person.gender = @"male";

        // Append to array
        [personsList addObject:person];
        [person release];

        // Create person 2
        person = [[Person alloc] init];
        person.name = @"Fred";
        person.gender = @"Unknown";

        // Append to array
        [personsList addObject:person];
        [person release];

        [personsTable reloadData];
    }

    return self;
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [personsList count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    Person *person = [personsList objectAtIndex:row];
    NSString *identifier = [tableColumn identifier];

    return [person valueForKey:identifier];
}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    NSInteger selectedRow = [personsTable selectedRow];
    if (selectedRow == -1)
    {
        // these should be localized, but use string constants here for clarity
        [selectedPersonName setStringValue:@"No selection"];
        [selectedPersonGender setStringValue:@"No selection"];
    }
    else
    {
        Person *selectedPerson = [personCollection objectAtIndex:selectedRow];

        [selectedPersonName setStringValue:[selectedPerson name]];
        [selectedPersonGender setStringValue:[selectedPerson gender]];
    }
}

- (void)dealloc
{
    [super dealloc];
}

@end

Body:
Solution in Swift 3 for most of the events:

Inside tableview view controller :

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.target = self
    tableView.action = #selector(tableViewDidClick)
}

func tableViewDidClick(){
    let row = tableView.clickedRow
    let column = tableView.clickedColumn
    let unselected = -1

    if row == unselected && column == unselected{
        tableViewDidDeselectRow()
        return
    }else if row != unselected && column != unselected{
        tableViewDidSelectRow(row)
        return
    }else if column != unselected && row == unselected{
        tableviewDidSelectHeader(column)
    }
}

private func tableViewDidDeselectRow() {
    // clicked outside row
}

private func tableViewDidSelectRow(_ row : Int){
    // row did select
}

private func tableviewDidSelectHeader(_ column : Int){
    // header did select
}


问:
IIS 7 Custom Error Page without Web.config
Is there any way to set a custom error page in IIS 7 without creating a web.config?

Unfortunately researching this particular topic has been very difficult because there are SO many articles on how to do it with a web.config.  What I'm looking for is either buried beneath the 8 million results I don't want or it's not possible.

答:
Darin already gave the correct answer, but I want to go into a little more depth.

In any ASP.NET application, given it is Web Forms, MVC, or raw ASP.NET, you can always use Application_Error Global.asax. If your ASP.NET application does not have a Global.asax, all you need to do is right-click your project in Solution Explorer, Add New Item, and choose Global Application Class. You should only have this option available if you don't already have one.

In your Global.asax, if you don't already see it, you can add Application_Error as shown below:

```<code>protected void Application_Error(object sender, EventArgs e) {

}
</code>```

This will be called automatically by ASP.NET whenever there is an error. But as stated here, this is not perfect. Specifically:

An error handler that is defined in the Global.asax file will only
  catch errors that occur during processing of requests by the ASP.NET
  runtime. For example, it will catch the error if a user requests an
  .aspx file that does not occur in your application. However, it does
  not catch the error if a user requests a nonexistent .htm file. For
  non-ASP.NET errors, you can create a custom handler in Internet
  Information Services (IIS). The custom handler will also not be called
  for server-level errors.

In Application_Error you can process the uncaught exception with Server.GetLastError(). This will provide you the Exception that was thrown, or null. I am not sure why this handler would be called if an exception didn't occur, but I believe that it is possible.

To redirect the user, use Response.Redirect(). Whatever you pass for the url is going to be sent directly to the browser without any further processing, so you can't use application-relative paths. To do that I would use this method in combination with VirtualPathUtility.ToAbsolute(). For example:

```<code>Response.Redirect( VirtualPathUtility.ToAbsolute( "~/Error.aspx" ) );
</code>```

This redirect will be a 302 (temporary redirect) rather than a 301 (permanent), which is what you want in the case of handling errors. It's worth noting that this overload of Response.Redirect is the same as calling the overload Response.Redirect(url, endResponse: true). This method works by throwing an exception, which is not ideal in terms of performance. Instead, call Response.Redirect(url, false) immediately followed by Response.CompleteRequest().

If you're using ASP.NET MVC, [HandleError] is also an option. Place this attribute on your Controller or on an Action within a controller. When this attribute is present, MVC will display the Error view, found in the ~/Views/Shared folder.

But you can make this even easier for yourself. You can automatically add this attribute to call Controllers in your project by creating a FilterConfig class in your project. Example:

```<code>public class FilterConfig {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
        filters.Add(new HandleErrorAttribute());
    }
}
</code>```

And then add FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters ); to your Application_Start() in Global.asax.

You can read more about the HandleErrorAttribute at https://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute(v=vs.118).aspx.

But as stated above, both of these methods will never cover absolutely all errors that can occur during the processing of your application. It's not possible to provide the best user experience for all possible errors without using Web.config or configuring IIS manually.

Body:
Darin already gave the correct answer, but I want to go into a little more depth.

In any ASP.NET application, given it is Web Forms, MVC, or raw ASP.NET, you can always use Application_Error Global.asax. If your ASP.NET application does not have a Global.asax, all you need to do is right-click your project in Solution Explorer, Add New Item, and choose Global Application Class. You should only have this option available if you don't already have one.

In your Global.asax, if you don't already see it, you can add Application_Error as shown below:

protected void Application_Error(object sender, EventArgs e) {

}

This will be called automatically by ASP.NET whenever there is an error. But as stated here, this is not perfect. Specifically:

An error handler that is defined in the Global.asax file will only
  catch errors that occur during processing of requests by the ASP.NET
  runtime. For example, it will catch the error if a user requests an
  .aspx file that does not occur in your application. However, it does
  not catch the error if a user requests a nonexistent .htm file. For
  non-ASP.NET errors, you can create a custom handler in Internet
  Information Services (IIS). The custom handler will also not be called
  for server-level errors.

In Application_Error you can process the uncaught exception with Server.GetLastError(). This will provide you the Exception that was thrown, or null. I am not sure why this handler would be called if an exception didn't occur, but I believe that it is possible.

To redirect the user, use Response.Redirect(). Whatever you pass for the url is going to be sent directly to the browser without any further processing, so you can't use application-relative paths. To do that I would use this method in combination with VirtualPathUtility.ToAbsolute(). For example:

Response.Redirect( VirtualPathUtility.ToAbsolute( "~/Error.aspx" ) );

This redirect will be a 302 (temporary redirect) rather than a 301 (permanent), which is what you want in the case of handling errors. It's worth noting that this overload of Response.Redirect is the same as calling the overload Response.Redirect(url, endResponse: true). This method works by throwing an exception, which is not ideal in terms of performance. Instead, call Response.Redirect(url, false) immediately followed by Response.CompleteRequest().

If you're using ASP.NET MVC, [HandleError] is also an option. Place this attribute on your Controller or on an Action within a controller. When this attribute is present, MVC will display the Error view, found in the ~/Views/Shared folder.

But you can make this even easier for yourself. You can automatically add this attribute to call Controllers in your project by creating a FilterConfig class in your project. Example:

public class FilterConfig {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
        filters.Add(new HandleErrorAttribute());
    }
}

And then add FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters ); to your Application_Start() in Global.asax.

You can read more about the HandleErrorAttribute at https://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute(v=vs.118).aspx.

But as stated above, both of these methods will never cover absolutely all errors that can occur during the processing of your application. It's not possible to provide the best user experience for all possible errors without using Web.config or configuring IIS manually.