问:
Caveats of EAV vs. direct table manipulation?
I'm working on a small content management system and the data within it is heavily relational. I've started with a small abstraction, but i'm probably going for a full entity-attribute-value model. However, it occurred to me that i'm building all of this on a relational database (pgsql) and it doesn't make any sense to rebuild the model on top of a powerful engine like that.

This is not very common though, which makes me think someone already thought of this and it might be a trap. Could someone explain to me the caveats of creating and altering tables inside an application to represent your user-customizable data model?

答:
I assume you've looked at all the down-sides of EAV.

You are very terse in describing what you want to achieve, so I'm going to have a guess - you want some way of allowing your developers and/or content administrators to define a schema, and to allow the software to reason about the data based on that schema. For instance, show all entities of type 'article' belonging to category 'architecture' in status 'published' order by 'publication_date' descending.

That's an easy query to write if you have a relational model and know the attributes types at the time of writing the query.

It's a hard query to write using EAV.

It's also a hard query to write in a relational model if you don't know the attributes in advance - you basically have to write a translation layer between your domain model and the relational database. I've worked with CMS systems which did this, and the limitation they usually impose is "forward-only" changes. You can add attributes, but not remove or change them.

This is because the database is the easy bit - it's mapping that data schema to the domain model that's hard, and the generators they use are pretty good at adding new attributes, but get really confused when renaming things, or changing data types, or removing them. For instance, if you remove attribute "publication_date", you'd have to check all the generated files to see if it occurs, and then transitively look for methods depending on those methods etc.

EDIT:

You write that you want content administrators to create new entities, and relationships between those entities. The long and short of it is that relational databases are not great at this. The closest parallel is object-relational-mapping tools which aim to abstract the underlying database from the object-oriented application talking to it. ORMs are firmly aimed at developers, not end users, and introduce their own cognitive overhead; they tend to work really well until you run into an edge case.

You might look at using a document-oriented solution (MySQL supports both XML and JSON natively) instead. You lose some of the validation and scalability features of the pure relational model, but you gain a LOT of simplicity. For instance, you might have a table called "content_item", with all the fixed attributes that apply to all content items and allow you to implement workflow logic, but store the content itself in a JSON document within the content_item table.


来源: stackexchange

问:
argument labels "mkcoordinate" do not match any available overloads swift 4
The code I am using is from xcode 8 swift 3. I want to know what I should do to convert this to xcode 9 swift 4.

```<code>func openInMaps(sender: UIButton) {
    for i in 0...2
    {
    let coordinate = coordinates[i]
    let latitude = coordinate[0]
    let longitude = coordinate[1]
    let coordinates1 = CLLocationCoordinate2DMake(latitude, longitude)

    let regionDistance:CLLocationDistance = 1000;
    let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates1, regionDistance, regionDistance)
</code>```

The first line is where the error occur

```<code>    let options = [MKLaunchOptionsMapCenterKey: NSValue(mkcoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkcoordinatespan: regionSpan.span)]

    let placemark = MKPlacemark(coordinate: coordinates1)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = "destination"
    mapItem.openInMaps(launchOptions: options)
    }
}
</code>```

答:
The easiest way to fix a do not match any available overloads error is to use code completion.

(Re)type NSValue(

You will see (hint: case sensitivity matters):

Alternatively open the documentation and look up the correct spelling of the initializers.

ContentLicense: CC BY-SA 3.0

Body:
The code I am using is from xcode 8 swift 3. I want to know what I should do to convert this to xcode 9 swift 4.

func openInMaps(sender: UIButton) {
    for i in 0...2
    {
    let coordinate = coordinates[i]
    let latitude = coordinate[0]
    let longitude = coordinate[1]
    let coordinates1 = CLLocationCoordinate2DMake(latitude, longitude)

    let regionDistance:CLLocationDistance = 1000;
    let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates1, regionDistance, regionDistance)

The first line is where the error occur

    let options = [MKLaunchOptionsMapCenterKey: NSValue(mkcoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkcoordinatespan: regionSpan.span)]

    let placemark = MKPlacemark(coordinate: coordinates1)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = "destination"
    mapItem.openInMaps(launchOptions: options)
    }
}


问:
Google API PHP client with Composer
I made a WP plugin which depends on the Youtube API. So, to do it well, I use Google API PHP client.

My issue is quite simple: the Google API PHP client is huge (more than 12 000 files), including clients for all Google services, when I just need to use Youtube service. So I'm not confortable committing all those files to the WP plugins repo when most of them are useless in my case.

So, right now, my composer.json looks like this:

```<code>{
    "require": {
        "google/apiclient": "^2.0"
    }
}
</code>```

Any way to use only the Youtube API client (using composer if it's possible)?

答:
Unfortunately, I don't think this is possible without manually including the relevant files in your project (which is a really bad idea).

The reason why its impossible, is because Google places all service APIs for the PHP library in a single GitHub repository found here:

https://github.com/google/google-api-php-client-services

If Google does split them into multiple repositories, then it could be possible to include a single repo.

For now, though, all services are under one composer project and one repo. Maybe its worth making a GitHub issue to ask Google about this?

Title: Google API PHP client with Composer

Body:
I made a WP plugin which depends on the Youtube API. So, to do it well, I use Google API PHP client.

My issue is quite simple: the Google API PHP client is huge (more than 12 000 files), including clients for all Google services, when I just need to use Youtube service. So I'm not confortable committing all those files to the WP plugins repo when most of them are useless in my case.

So, right now, my composer.json looks like this:

{
    "require": {
        "google/apiclient": "^2.0"
    }
}

Any way to use only the Youtube API client (using composer if it's possible)?


问:
Convert string local date with zoneId to UTC Offsetdate JAVA
I'm trying to convert a Brazil local date to UTC format. I have developed my solution but I'm sure that it can be improved. I have been searching for others questions but without success.

My problem is that when I process the Date object with:

```<code>Instant endDateTime = questionDate.toInstant();
</code>```

I receive a UTC date as "2017-11-16T00:00:00Z" but this should be Brazil local date (not correct because it has a trailing "Z") and when I try to convert to UTC, I receive the same output.

In another hand, if I use ZoneDateTime class and build the date with LocalDateTime object I lose the seconds in the output: "2017-11-16T02:00Z". This happens when I use:

```<code>LocalTime.of(hour, minutes, seconds);
</code>```

I search into LocalTime class and I think this is because minutes or seconds are 0 but I'm not sure of it.

Problems of the solution:

The response hasn't seconds

I hope Java 8 has a set of functions to make this more simple and clear

Precondition:

I can't use Joda library

Result has to be OffsetDateTime class

Input: Date "2017-11-16"

Output: "2017-11-16T02:00:00Z"

This is my solution:

```<code>private static OffsetDateTime processDate(Date questionDate) {
  Instant endDateTime = questionDate.toInstant();
  ZoneId zoneId = ZoneId.of(ZONEID);
  String [] date = endDateTime.toString().split("T");
  LocalDateTime localDateTime = convertLocalTimeToUtc(date);
  ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
  ZonedDateTime utcDate = zonedDateTime.withZoneSameInstant(ZoneOffset.UTC);
  return utcDate.toOffsetDateTime();
}

private static LocalDateTime convertLocalTimeToUtc(String[] dateFromCountry) {
  LocalDate date = processDate(dateFromCountry[0]);
  LocalTime time = processTime(dateFromCountry[1]);
  return  LocalDateTime.of(date, time);
}

private static LocalDate processDate(String dateFromCountry) {
  String [] partsOfDate = dateFromCountry.split("-");
  int year = Integer.parseInt(partsOfDate[0]);
  int month = Integer.parseInt(partsOfDate[1]);
  int day = Integer.parseInt(partsOfDate[2]);
  return LocalDate.of(year, month, day);
}

private static LocalTime processTime(String dateFromCountry) {
  String [] partsOfTime = dateFromCountry.split(":");
  int hour = Integer.parseInt(partsOfTime[0]);
  int minutes = Integer.parseInt(partsOfTime[1]);
  int seconds = Integer.parseInt(partsOfTime[2].substring(0,1));
  return LocalTime.of(hour,minutes,seconds);
}
</code>```

答:
If your input is a java.util.Date, you can get rid of all the string manipulation:

```<code>//simulate your input
Instant input = Instant.parse("2017-11-16T00:00:00Z");
Date d = Date.from(input);

//transformation code starts here
Instant instant = d.toInstant();

ZonedDateTime localInstant = instant.atZone(ZoneOffset.UTC);
ZonedDateTime sameLocalInBrazil = utcInstant.withZoneSameLocal(ZoneId.of("Brazil/East"));
OffsetDateTime sameInstantUtc = sameLocalInBrazil.toOffsetDateTime()
                                      .withOffsetSameInstant(ZoneOffset.UTC);
</code>```

This return an OffsetDateTime with value 2017-11-16T02:00Z as you expect.

Note that an OffsetDateTime has no formatting - so the object does know that its seconds are set to 0 but the default toString method doesn't print them. If you want to print it with seconds, you can use a formatter:

```<code>//Formatting
System.out.println(sameInstantUtc.format(DateTimeFormatter.ISO_INSTANT));
</code>```

which prints 2017-11-16T02:00:00Z

If your input is a java.sql.Date, you can use a slightly different strategy:

```<code>LocalDate d = sqlDate.toLocalDate();
ZonedDateTime localInstant = d.atStartOfDay(ZoneOffset.UTC);
</code>```

The rest of the code would be the same.

Body:
I'm trying to convert a Brazil local date to UTC format. I have developed my solution but I'm sure that it can be improved. I have been searching for others questions but without success.

My problem is that when I process the Date object with:

Instant endDateTime = questionDate.toInstant();

I receive a UTC date as "2017-11-16T00:00:00Z" but this should be Brazil local date (not correct because it has a trailing "Z") and when I try to convert to UTC, I receive the same output.

In another hand, if I use ZoneDateTime class and build the date with LocalDateTime object I lose the seconds in the output: "2017-11-16T02:00Z". This happens when I use:

LocalTime.of(hour, minutes, seconds);

I search into LocalTime class and I think this is because minutes or seconds are 0 but I'm not sure of it.

Problems of the solution:

The response hasn't seconds

I hope Java 8 has a set of functions to make this more simple and clear

Precondition:

I can't use Joda library

Result has to be OffsetDateTime class

Input: Date "2017-11-16"

Output: "2017-11-16T02:00:00Z"

This is my solution:

private static OffsetDateTime processDate(Date questionDate) {
  Instant endDateTime = questionDate.toInstant();
  ZoneId zoneId = ZoneId.of(ZONEID);
  String [] date = endDateTime.toString().split("T");
  LocalDateTime localDateTime = convertLocalTimeToUtc(date);
  ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
  ZonedDateTime utcDate = zonedDateTime.withZoneSameInstant(ZoneOffset.UTC);
  return utcDate.toOffsetDateTime();
}

private static LocalDateTime convertLocalTimeToUtc(String[] dateFromCountry) {
  LocalDate date = processDate(dateFromCountry[0]);
  LocalTime time = processTime(dateFromCountry[1]);
  return  LocalDateTime.of(date, time);
}

private static LocalDate processDate(String dateFromCountry) {
  String [] partsOfDate = dateFromCountry.split("-");
  int year = Integer.parseInt(partsOfDate[0]);
  int month = Integer.parseInt(partsOfDate[1]);
  int day = Integer.parseInt(partsOfDate[2]);
  return LocalDate.of(year, month, day);
}

private static LocalTime processTime(String dateFromCountry) {
  String [] partsOfTime = dateFromCountry.split(":");
  int hour = Integer.parseInt(partsOfTime[0]);
  int minutes = Integer.parseInt(partsOfTime[1]);
  int seconds = Integer.parseInt(partsOfTime[2].substring(0,1));
  return LocalTime.of(hour,minutes,seconds);
}

Body:
If your input is a java.util.Date, you can get rid of all the string manipulation:

//simulate your input
Instant input = Instant.parse("2017-11-16T00:00:00Z");
Date d = Date.from(input);

//transformation code starts here
Instant instant = d.toInstant();

ZonedDateTime localInstant = instant.atZone(ZoneOffset.UTC);
ZonedDateTime sameLocalInBrazil = utcInstant.withZoneSameLocal(ZoneId.of("Brazil/East"));
OffsetDateTime sameInstantUtc = sameLocalInBrazil.toOffsetDateTime()
                                      .withOffsetSameInstant(ZoneOffset.UTC);

This return an OffsetDateTime with value 2017-11-16T02:00Z as you expect.

Note that an OffsetDateTime has no formatting - so the object does know that its seconds are set to 0 but the default toString method doesn't print them. If you want to print it with seconds, you can use a formatter:

//Formatting
System.out.println(sameInstantUtc.format(DateTimeFormatter.ISO_INSTANT));

which prints 2017-11-16T02:00:00Z

If your input is a java.sql.Date, you can use a slightly different strategy:

LocalDate d = sqlDate.toLocalDate();
ZonedDateTime localInstant = d.atStartOfDay(ZoneOffset.UTC);

The rest of the code would be the same.


问:
How can I pop this letter if it exists based on this algorithm?
I'm trying to pop any letters given by the user, for example if they give you a keyword "ROSES" then these letters should be popped out of the list.

Note: I have a lot more explanation after the SOURCE CODE

SOURCE CODE

```<code>  alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        encrypted_message = []
        key_word = str(input("Please enter a word:"))
        key_word = list(key_word)
        #print(key_word)

        check_for_dup = 0

        for letter in key_word:
            for character in alphabet:
                if letter in character:
                    check_for_dup +=1
                    alphabet.pop(check_for_dup)

        print(alphabet)
        print(encrypted_message)
</code>```

SAMPLE INPUT

Let's say keyword is "Roses"

this what it gives me a list of the following ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

But that's wrong It should of just removed the characters that existed in the keyword given by the user, like the word "Roses" each letter should of been removed and not in the list being popped. as you can see in the list the letters "B","D","F","H",etc were gone. What I'm trying to do is pop the index of the alphabet letters that the keyword exists.

this is what should of happened.

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

The letters of the keyword "ROSES" were deleted of the list

答:
Try this:

```<code>import string
key_word = set(input("Please enter a word:").lower())
print(sorted(set(string.ascii_lowercase) - key_word))
</code>```

Explanation:

When checking for (in)existence, it's better to use set. https://docs.python.org/3/tutorial/datastructures.html#sets

Instead of iterating over it N times (N = number of input characters), you hash the character N times and check if there's already something at the result hash or not.
If you check the speed, try with "WXYZZZYW" and you'll see that it'll be a lot slower than if it were "ABCDDDCA" with the list way. With set, it will be always the same time.

The rest is pretty trivial. Casting to lowercase (or uppercase), to make sure it hits a match, case insensitive.

And then, we end by doing a set difference (-). It's all the items that are in the first set but not in the second one.

Body:
I'm trying to pop any letters given by the user, for example if they give you a keyword "ROSES" then these letters should be popped out of the list.

Note: I have a lot more explanation after the SOURCE CODE

SOURCE CODE

  alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        encrypted_message = []
        key_word = str(input("Please enter a word:"))
        key_word = list(key_word)
        #print(key_word)

        check_for_dup = 0

        for letter in key_word:
            for character in alphabet:
                if letter in character:
                    check_for_dup +=1
                    alphabet.pop(check_for_dup)

        print(alphabet)
        print(encrypted_message)

SAMPLE INPUT

Let's say keyword is "Roses"

this what it gives me a list of the following ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

But that's wrong It should of just removed the characters that existed in the keyword given by the user, like the word "Roses" each letter should of been removed and not in the list being popped. as you can see in the list the letters "B","D","F","H",etc were gone. What I'm trying to do is pop the index of the alphabet letters that the keyword exists.

this is what should of happened.

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

The letters of the keyword "ROSES" were deleted of the list

Body:
Try this:

import string
key_word = set(input("Please enter a word:").lower())
print(sorted(set(string.ascii_lowercase) - key_word))

Explanation:

When checking for (in)existence, it's better to use set. https://docs.python.org/3/tutorial/datastructures.html#sets

Instead of iterating over it N times (N = number of input characters), you hash the character N times and check if there's already something at the result hash or not.
If you check the speed, try with "WXYZZZYW" and you'll see that it'll be a lot slower than if it were "ABCDDDCA" with the list way. With set, it will be always the same time.

The rest is pretty trivial. Casting to lowercase (or uppercase), to make sure it hits a match, case insensitive.

And then, we end by doing a set difference (-). It's all the items that are in the first set but not in the second one.


问:
Log4View not showing any messages
I'm trying to open our log-file in Log4View but it doesn't show any messages.

A sample logfile entry looks like this:

15.11.2017 07:56:45.555    Normal    BaseSessionHandler              3x1r0p5hk3utkd1i2iqyqufg        Aktuelle Anzahl Sessions: 6

I've set Log4View up to use a Pattern Layout:
%d [%t] %level %logger [%x] - %m but unfortunately that doesnt work...

Do you have an idea why it doesn't show any messages?

Thanks in advance

答:
Well, it seems like the pattern layout you use has got not much in common with your actual message structure.

Assuming BaseSessionHandler is a logger and 3x1r0p5hk3utkd1i2iqyqufg is a thread, you should use a pattern similar to this:

%date{dd.MM.yyyy HH:mm:ss.fff} %level %logger %x %m

Check out this documentation on the elements of a layout pattern.

Title: Log4View not showing any messages


答:
Sets are unordered, which makes a direct solution problematic. However, assuming you created the set for the sake of eliminating duplicates in what was originally a list, you can use a different method of duplicate removal, combined with zipping as Francisco's answer suggests, though without the filter that mismatches the items:

```<code>a = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'test1', 'test', '', '', '', '', '', '', '', '', '', '']
b_list = ["18", "17", "16", "15", "14", "13", "12", "11", "21", "22", "23", "24", "25", "26", "27", "28","48", "47", "46", "45", "44", "43", "42", "41", "31", "32", "33", "34", "35", "36", "37", "38", "18", "17"]
# added hypothetical duplicates to b for the sake of showing how they're removed below
b = sorted(set(b_list), key=lambda x: b_list.index(x))

c = dict(zip(a, b))
del c['']  # removes the erroneous '' key
</code>```

Outputs exactly what you want:

```<code>{'44': 'test1', '43': 'test'}
</code>```

Title: Combine dictionary according to index

Body:
Let us Assume, I have a key value pair in python, such as the following.

a = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'test1', 'test', '', '', '', '', '', '', '', '', '', '']

now I want to combine these values with:

b = {"18", "17", "16", "15", "14", "13", "12", "11", "21", "22", "23", "24", "25", "26", "27", "28","48", "47", "46", "45", "44", "43", "42", "41", "31", "32", "33", "34", "35", "36", "37", "38"}

Is there any way where I can combine the values from variable a against the \ b like result shown below:

c = {'44': ['test1'], '43': ['test2']}

thank you.

Body:
Sets are unordered, which makes a direct solution problematic. However, assuming you created the set for the sake of eliminating duplicates in what was originally a list, you can use a different method of duplicate removal, combined with zipping as Francisco's answer suggests, though without the filter that mismatches the items:

a = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'test1', 'test', '', '', '', '', '', '', '', '', '', '']
b_list = ["18", "17", "16", "15", "14", "13", "12", "11", "21", "22", "23", "24", "25", "26", "27", "28","48", "47", "46", "45", "44", "43", "42", "41", "31", "32", "33", "34", "35", "36", "37", "38", "18", "17"]
# added hypothetical duplicates to b for the sake of showing how they're removed below
b = sorted(set(b_list), key=lambda x: b_list.index(x))

c = dict(zip(a, b))
del c['']  # removes the erroneous '' key

Outputs exactly what you want:

{'44': 'test1', '43': 'test'}


答:
You can do something like this....</p>

```<code>import string
alphabet = list(string.ascii_lowercase)

user_word = 'Roses'
user_word = user_word.lower()

letters_to_remove = set(list(user_word)) # Create a unique set of characters to remove

for letter in letters_to_remove:
  alphabet.remove(letter)
</code>```

Title: How can I pop this letter if it exists based on this algorithm?

Body:
You can do something like this....

import string
alphabet = list(string.ascii_lowercase)

user_word = 'Roses'
user_word = user_word.lower()

letters_to_remove = set(list(user_word)) # Create a unique set of characters to remove

for letter in letters_to_remove:
  alphabet.remove(letter)


问:
c queue linked list - printing queue changes value of pointers?
I have created a linked-list queue in C. my structs are as such:

```<code>typedef struct Node{
    int *data;
    struct Node *next;
} node;

typedef struct Queue{
    node *front, *rear;
} queue;
</code>```

In my main() function, I am getting a user input determining the length of the queue, creating an array of this length, and getting a user input for each element of the array. I then call a function called runQueue().

```<code>void runQueue(int array[], int len){
    queue *q = (queue *)malloc(sizeof(queue));
    q->front = q->rear = NULL;
    for(int i = len - 1; i >= 0; i--){ //len-1, user doesn't input 0-based index
        enQueue(q, array[i]);
    }
    printQueue(q);
    enQueue(q,4);
    printQueue(q);
    queueMenu(q);
}
</code>```

In this function I am calling a function enQueue() in a loop to enqueue all the nodes into the queue from the array. I am then calling printQueue().

```<code>void enQueue(queue *q, int data){
    node *tmp = (node *) malloc(sizeof(node));
    tmp->data = data;
    tmp->next = NULL;

    if (q->rear == NULL){
        q->front = q->rear = tmp;
        return;
    }

    q->rear->next = tmp;
    q->rear = tmp;
}

void printQueue(queue *q){
    int iterator = 0;
    queue *tmp = (queue *)malloc(sizeof(queue));
    tmp = q;
    while(tmp->front->next != tmp->rear->next && tmp->front != NULL){
        iterator += 1;
        //printf("in loop, i = %d\n",iterator);
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->front->data, tmp->front, tmp->front->next);
        tmp->front = tmp->front->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->front->data, tmp->front, tmp->front->next);
    free(tmp);
}
</code>```

The problem is as such: I can run this, and the enqueue function seems to work fine. The first time I call printQueue(), the function will print the correct result. However, after printing the queue, the values of the front and rear pointer change, and printing trying to perform any more operations on the queue of course results in a segfault since it's trying to access different areas of memory than those it is supposed to. How is it that the values of the pointers is being changed? I have copied the queue to a temporary queue before preceding to change pointer values, so why are the actual queue's pointers changing?

EDIT:
as an example of how the array is input to the queue -

```<code>int array[3] = {4,3,2};
runQueue(array,3);
</code>```

then within runQueue(), the for loop is decrementing through the array and calling enQueue() for each element in the array. In this case, calling enQueue(q,2) followed by enQueue(q,3) then enQueue(q,4).

EDIT 2:
I tried Thomas Blanquet's suggestion by changing the function to this:

```<code>void printQueue(queue *q){
    int iterator = 0;
    node *tmp = (node *)malloc(sizeof(node));
    tmp = q->front;
    while(tmp != NULL){
        iterator += 1;
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->data, tmp, tmp->next);
        tmp = tmp->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);
    free(tmp);
}
</code>```

After making this change, the pointers are correct, but I am still getting a segfault before exiting the function.

EDIT 3:
I tried commenting out free(tmp), but I am still getting a segfault. However I found the problem! Somehow I had a printf() outside the loop which I didn't notice:

```<code>printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);
</code>```

Removing this now stops the segfault and all the pointers are correct. Many thanks!

答:
To fix the problem...

I changed my tmp variable from a reference of the queue structure to
a reference of the head node of the queue and iterated through the
queue (tmp = tmp->next)

I removed the line free(tmp) since it was freeing the location of
the actual queue hence deleting part of my queue!

I removed the extra printf() which was outside of the loop which I
accidentally put there!

The code now looks like this:

```<code>void printQueue(queue *q){
    int iterator = 0;
    node *tmp = q->front;
    while(tmp != NULL){
        iterator += 1;
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->data, tmp, tmp->next);
        tmp = tmp->next;
    }
}
</code>```

Many thanks to Thomas Blanquet.

Body:
I have created a linked-list queue in C. my structs are as such:

typedef struct Node{
    int *data;
    struct Node *next;
} node;

typedef struct Queue{
    node *front, *rear;
} queue;

In my main() function, I am getting a user input determining the length of the queue, creating an array of this length, and getting a user input for each element of the array. I then call a function called runQueue().

void runQueue(int array[], int len){
    queue *q = (queue *)malloc(sizeof(queue));
    q->front = q->rear = NULL;
    for(int i = len - 1; i >= 0; i--){ //len-1, user doesn't input 0-based index
        enQueue(q, array[i]);
    }
    printQueue(q);
    enQueue(q,4);
    printQueue(q);
    queueMenu(q);
}

In this function I am calling a function enQueue() in a loop to enqueue all the nodes into the queue from the array. I am then calling printQueue().

void enQueue(queue *q, int data){
    node *tmp = (node *) malloc(sizeof(node));
    tmp->data = data;
    tmp->next = NULL;

    if (q->rear == NULL){
        q->front = q->rear = tmp;
        return;
    }

    q->rear->next = tmp;
    q->rear = tmp;
}

void printQueue(queue *q){
    int iterator = 0;
    queue *tmp = (queue *)malloc(sizeof(queue));
    tmp = q;
    while(tmp->front->next != tmp->rear->next && tmp->front != NULL){
        iterator += 1;
        //printf("in loop, i = %d\n",iterator);
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->front->data, tmp->front, tmp->front->next);
        tmp->front = tmp->front->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->front->data, tmp->front, tmp->front->next);
    free(tmp);
}

The problem is as such: I can run this, and the enqueue function seems to work fine. The first time I call printQueue(), the function will print the correct result. However, after printing the queue, the values of the front and rear pointer change, and printing trying to perform any more operations on the queue of course results in a segfault since it's trying to access different areas of memory than those it is supposed to. How is it that the values of the pointers is being changed? I have copied the queue to a temporary queue before preceding to change pointer values, so why are the actual queue's pointers changing?

EDIT:
as an example of how the array is input to the queue -

int array[3] = {4,3,2};
runQueue(array,3);

then within runQueue(), the for loop is decrementing through the array and calling enQueue() for each element in the array. In this case, calling enQueue(q,2) followed by enQueue(q,3) then enQueue(q,4).

EDIT 2:
I tried Thomas Blanquet's suggestion by changing the function to this:

void printQueue(queue *q){
    int iterator = 0;
    node *tmp = (node *)malloc(sizeof(node));
    tmp = q->front;
    while(tmp != NULL){
        iterator += 1;
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->data, tmp, tmp->next);
        tmp = tmp->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);
    free(tmp);
}

After making this change, the pointers are correct, but I am still getting a segfault before exiting the function.

EDIT 3:
I tried commenting out free(tmp), but I am still getting a segfault. However I found the problem! Somehow I had a printf() outside the loop which I didn't notice:

printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);

Removing this now stops the segfault and all the pointers are correct. Many thanks!

Body:
To fix the problem...

I changed my tmp variable from a reference of the queue structure to
a reference of the head node of the queue and iterated through the
queue (tmp = tmp->next)

I removed the line free(tmp) since it was freeing the location of
the actual queue hence deleting part of my queue!

I removed the extra printf() which was outside of the loop which I
accidentally put there!

The code now looks like this:

void printQueue(queue *q){
    int iterator = 0;
    node *tmp = q->front;
    while(tmp != NULL){
        iterator += 1;
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->data, tmp, tmp->next);
        tmp = tmp->next;
    }
}

Many thanks to Thomas Blanquet.


问:
Expand a div to fill the remaining width
I want a two-column div layout, where each one can have variable width e.g.

div {
  float: left;
}

.second {
  background: #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Tree</div>
<div class="second">View</div></code>```

I want the 'view' div to expand to the whole width available after 'tree' div has filled needed space.

Currently, my 'view' div is resized to content it contains
It will also be good if both divs take up the whole height.

Not duplicate disclaimer:

Expand div to max width when float:left is set
because there the left one has a fixed width.

Help with div - make div fit the remaining width
because I need two columns both aligned to left

答:
Tree

View

View

    <div style="width: <=100% getTreeWidth()100 %>">Tree

Tree

View

```

ContentLicense: CC BY-SA 4.0

Body:
I want a two-column div layout, where each one can have variable width e.g.

div {
  float: left;
}

.second {
  background: #ccc;
}

Tree

View

I want the 'view' div to expand to the whole width available after 'tree' div has filled needed space.

Currently, my 'view' div is resized to content it contains
It will also be good if both divs take up the whole height.

Not duplicate disclaimer:

Expand div to max width when float:left is set
because there the left one has a fixed width.

Help with div - make div fit the remaining width
because I need two columns both aligned to left

Body:
<html>

<head>
  <style type="text/css">
    div.box {
      background: #EEE;
      height: 100px;
      width: 500px;
    }
    div.left {
      background: #999;
      float: left;
      height: 100%;
      width: auto;
    }
    div.right {
      background: #666;
      height: 100%;
    }
    div.clear {
      clear: both;
      height: 1px;
      overflow: hidden;
      font-size: 0pt;
      margin-top: -1px;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="left">Tree</div>
    <div class="right">View</div>
    <div class="right">View</div>
    <div style="width: <=100% getTreeWidth()100 %>">Tree</div>
    <div class="clear" />
  </div>
  <div class="ColumnWrapper">
    <div class="ColumnOneHalf">Tree</div>
    <div class="ColumnOneHalf">View</div>
  </div>

</body>

</html>


问:
making dropdown boxes links that open in a new window
So I found this code here:

```<code><select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>
</code>```

And it works just fine for what it's intended, it makes dropdown box items into links. I was wondering if there's a way to make those links open in a new windows, rather then just redirecting?  I'm just getting into coding/programming, so I struggle with a lot of the easy things that most experienced programmers just take for granted. Thanks!

答:
```<code>document.getElementById('my_selection').onchange = function() {
window.open (this.children[this.selectedIndex].getAttribute('href'));
}
</code>```

This should be what you're looking for, it opens the link in a new tab/window.

Body:
So I found this code here:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

And it works just fine for what it's intended, it makes dropdown box items into links. I was wondering if there's a way to make those links open in a new windows, rather then just redirecting?  I'm just getting into coding/programming, so I struggle with a lot of the easy things that most experienced programmers just take for granted. Thanks!

Body:
document.getElementById('my_selection').onchange = function() {
window.open (this.children[this.selectedIndex].getAttribute('href'));
}

This should be what you're looking for, it opens the link in a new tab/window.


答:
```<code>alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

# this can be accepted as a user input as well
userinput = "ROSES"

# creates a list with unique values in uppercase
l = set(list(userinput.upper()))

# iterates over items in l to remove
# the corresponding items in alphabet
for x in l:
    alphabet.remove(x)
</code>```


问:
How to define variable names dynamically in Perl 6?

I have a name which I'd like to give to a variable, in another string variable:
my $name = '$a'; or simply my $name = 'a'; How to make the variable and to use it? I mean something like this (but it doesn't work):

my $name = '$a';
my {$name} = 1; # Doesn't work
say $a; # should be 1
```

A more general case. I have a list of variable names, say my @names = '$aa' ... '$cc'; How to declare and use the variable, whose name will be e.g. @names[2]?

答:
According to documentation the lexical pad (symbol table) is immutable after compile time. Also (according to the same docs) it means EVAL cannot be used to introduce lexical symbols into the surrounding scope.

I suggest you use package variables, instead of lexical variable as suggested in the comments.

However, a workaround is possible: You can create your own lexical pad at run time (for the module requiring) using for example require MODULE:

```<code>my $name = '$a';
spurt 'MySymbols.pm6', "unit module MySymbols; use v6; my $name = 1; say \"\\$name = $name\"";
use lib '.';
require MySymbols;
</code>```

Output:

```<code>$a = 1
</code>```

Body:
I have a name which I'd like to give to a variable, in another string variable:
my $name = '$a'; or simply my $name = 'a'; How to make the variable and to use it? I mean something like this (but it doesn't work):

my $name = '$a';
my {$name} = 1; # Doesn't work
say $a; # should be 1

A more general case. I have a list of variable names, say my @names = '$aa' ... '$cc'; How to declare and use the variable, whose name will be e.g. @names[2]?

Body:
According to documentation the lexical pad (symbol table) is immutable after compile time. Also (according to the same docs) it means EVAL cannot be used to introduce lexical symbols into the surrounding scope.

I suggest you use package variables, instead of lexical variable as suggested in the comments.

However, a workaround is possible: You can create your own lexical pad at run time (for the module requiring) using for example require MODULE:

my $name = '$a';
spurt 'MySymbols.pm6', "unit module MySymbols; use v6; my $name = 1; say \"\\$name = $name\"";
use lib '.';
require MySymbols;

Output:

$a = 1


答:
There is some shortcomings in your code here is an implementation that works:

```<code>alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
key_word = str(input("Please enter a word:"))

for letter in key_word.upper():
    if letter in alphabet:
        alphabet.remove(letter)

print(alphabet)
</code>```

Explanations

You can iterate on a string, no need to cast it as a list

Use remove since you can use the str type directly

You need to .upper() the input because you want to remove A if the user input a

Note that I did not handle encrypted_message since it is unused at the moment.

Also, as some comments says you could use a set instead of a list since lookups are faster for sets.

```<code>alphabet = {"A","B","C","D",...}
</code>```

EDIT

```<code>alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
key_word = str(input("Please enter a word:"))
encrypted_message = []
for letter in key_word.upper():
    if letter in alphabet:
        alphabet.remove(letter)
        encrypted_message.append(letter)

encrypted_message.extend(alphabet)
</code>```

This is a new implementation with the handling of your encrypted_message. This will keep the order of the alphabet after the input of the user. Also, if you're wondering why there's no duplicate, you will be appending only if letter is in alphabet which means the second time it won't be in alphabet and therefore not added to your encrypted_message.

Body:
There is some shortcomings in your code here is an implementation that works:

alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
key_word = str(input("Please enter a word:"))

for letter in key_word.upper():
    if letter in alphabet:
        alphabet.remove(letter)

print(alphabet)

Explanations

You can iterate on a string, no need to cast it as a list

Use remove since you can use the str type directly

You need to .upper() the input because you want to remove A if the user input a

Note that I did not handle encrypted_message since it is unused at the moment.

Also, as some comments says you could use a set instead of a list since lookups are faster for sets.

alphabet = {"A","B","C","D",...}

EDIT

alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
key_word = str(input("Please enter a word:"))
encrypted_message = []
for letter in key_word.upper():
    if letter in alphabet:
        alphabet.remove(letter)
        encrypted_message.append(letter)

encrypted_message.extend(alphabet)

This is a new implementation with the handling of your encrypted_message. This will keep the order of the alphabet after the input of the user. Also, if you're wondering why there's no duplicate, you will be appending only if letter is in alphabet which means the second time it won't be in alphabet and therefore not added to your encrypted_message.


问:
Install uploadprogress in XAMPP (Ubuntu 10.04)
I would like to install uploadprogress extension in XAMPP 1.7.1 (using Ubuntu 10.04).

Please let me know what I'm doing wrong:

1) I've downloaded uploadedprogress-1.0.1.tgz to desktop

2) I've run tar zxvf uploadprogress-1.0.1.tgz to extract the archive in the folder.

3) cd uploadprogress-1.0.1

4) /opt/lampp/bin/phpize-5.2.9 (in this step... although I'm pointing to the right folder of php.. I get no info about PHP Api Version, zend module api, etc.
Here the output

```<code>grep: /opt/lampp/include/php/main/php.h: No such file or directory
grep: /opt/lampp/include/php/Zend/zend_modules.h: No such file or directory
grep: /opt/lampp/include/php/Zend/zend_extensions.h: No such file or directory
Configuring for:
PHP Api Version:
Zend Module Api No:
Zend Extension Api No:
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_static_works, ...): suspicious cache-id, must contain _cv_ to be cached
../../lib/autoconf/general.m4:1998: AC_CACHE_VAL is expanded from...
../../lib/autoconf/general.m4:2019: AC_CACHE_CHECK is expanded from...
aclocal.m4:3535: AC_LIBTOOL_LINKER_OPTION is expanded from...
aclocal.m4:5473: _LT_AC_LANG_C_CONFIG is expanded from...
aclocal.m4:5472: AC_LIBTOOL_LANG_C_CONFIG is expanded from...
aclocal.m4:2952: AC_LIBTOOL_SETUP is expanded from...
aclocal.m4:2932: _AC_PROG_LIBTOOL is expanded from...
aclocal.m4:2895: AC_PROG_LIBTOOL is expanded from...
configure.in:144: the top level
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:3490: AC_LIBTOOL_COMPILER_OPTION is expanded from...
aclocal.m4:7600: AC_LIBTOOL_PROG_COMPILER_PIC is expanded from...
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works_CXX, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:5586: _LT_AC_LANG_CXX_CONFIG is expanded from...
aclocal.m4:5585: AC_LIBTOOL_LANG_CXX_CONFIG is expanded from...
aclocal.m4:4621: _LT_AC_TAGCONFIG is expanded from...
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_static_works, ...): suspicious cache-id, must contain _cv_ to be cached
../../lib/autoconf/general.m4:1998: AC_CACHE_VAL is expanded from...
../../lib/autoconf/general.m4:2019: AC_CACHE_CHECK is expanded from...
aclocal.m4:3535: AC_LIBTOOL_LINKER_OPTION is expanded from...
aclocal.m4:5473: _LT_AC_LANG_C_CONFIG is expanded from...
aclocal.m4:5472: AC_LIBTOOL_LANG_C_CONFIG is expanded from...
aclocal.m4:2952: AC_LIBTOOL_SETUP is expanded from...
aclocal.m4:2932: _AC_PROG_LIBTOOL is expanded from...
aclocal.m4:2895: AC_PROG_LIBTOOL is expanded from...
configure.in:144: the top level
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:3490: AC_LIBTOOL_COMPILER_OPTION is expanded from...
aclocal.m4:7600: AC_LIBTOOL_PROG_COMPILER_PIC is expanded from...
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works_CXX, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:5586: _LT_AC_LANG_CXX_CONFIG is expanded from...
aclocal.m4:5585: AC_LIBTOOL_LANG_CXX_CONFIG is expanded from...
aclocal.m4:4621: _LT_AC_TAGCONFIG is expanded from...
</code>```

5) ./configure --with-php-config=/opt/lampp/bin/php-config-5.2.9

6) make

I'm a newbie so please someone guide me through this process. Thanks!

答: I didn't install XAMPP 'devel' package. After installing it, everything went ok. Two last things: sudo make install & edit the php.ini

ContentLicense: CC BY-SA 2.5

Body:
I would like to install uploadprogress extension in XAMPP 1.7.1 (using Ubuntu 10.04).

Please let me know what I'm doing wrong:

1) I've downloaded uploadedprogress-1.0.1.tgz to desktop

2) I've run tar zxvf uploadprogress-1.0.1.tgz to extract the archive in the folder.

3) cd uploadprogress-1.0.1

4) /opt/lampp/bin/phpize-5.2.9 (in this step... although I'm pointing to the right folder of php.. I get no info about PHP Api Version, zend module api, etc.
Here the output

grep: /opt/lampp/include/php/main/php.h: No such file or directory
grep: /opt/lampp/include/php/Zend/zend_modules.h: No such file or directory
grep: /opt/lampp/include/php/Zend/zend_extensions.h: No such file or directory
Configuring for:
PHP Api Version:
Zend Module Api No:
Zend Extension Api No:
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_static_works, ...): suspicious cache-id, must contain _cv_ to be cached
../../lib/autoconf/general.m4:1998: AC_CACHE_VAL is expanded from...
../../lib/autoconf/general.m4:2019: AC_CACHE_CHECK is expanded from...
aclocal.m4:3535: AC_LIBTOOL_LINKER_OPTION is expanded from...
aclocal.m4:5473: _LT_AC_LANG_C_CONFIG is expanded from...
aclocal.m4:5472: AC_LIBTOOL_LANG_C_CONFIG is expanded from...
aclocal.m4:2952: AC_LIBTOOL_SETUP is expanded from...
aclocal.m4:2932: _AC_PROG_LIBTOOL is expanded from...
aclocal.m4:2895: AC_PROG_LIBTOOL is expanded from...
configure.in:144: the top level
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:3490: AC_LIBTOOL_COMPILER_OPTION is expanded from...
aclocal.m4:7600: AC_LIBTOOL_PROG_COMPILER_PIC is expanded from...
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works_CXX, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:5586: _LT_AC_LANG_CXX_CONFIG is expanded from...
aclocal.m4:5585: AC_LIBTOOL_LANG_CXX_CONFIG is expanded from...
aclocal.m4:4621: _LT_AC_TAGCONFIG is expanded from...
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_static_works, ...): suspicious cache-id, must contain _cv_ to be cached
../../lib/autoconf/general.m4:1998: AC_CACHE_VAL is expanded from...
../../lib/autoconf/general.m4:2019: AC_CACHE_CHECK is expanded from...
aclocal.m4:3535: AC_LIBTOOL_LINKER_OPTION is expanded from...
aclocal.m4:5473: _LT_AC_LANG_C_CONFIG is expanded from...
aclocal.m4:5472: AC_LIBTOOL_LANG_C_CONFIG is expanded from...
aclocal.m4:2952: AC_LIBTOOL_SETUP is expanded from...
aclocal.m4:2932: _AC_PROG_LIBTOOL is expanded from...
aclocal.m4:2895: AC_PROG_LIBTOOL is expanded from...
configure.in:144: the top level
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:3490: AC_LIBTOOL_COMPILER_OPTION is expanded from...
aclocal.m4:7600: AC_LIBTOOL_PROG_COMPILER_PIC is expanded from...
configure.in:144: warning: AC_CACHE_VAL(lt_prog_compiler_pic_works_CXX, ...): suspicious cache-id, must contain _cv_ to be cached
aclocal.m4:5586: _LT_AC_LANG_CXX_CONFIG is expanded from...
aclocal.m4:5585: AC_LIBTOOL_LANG_CXX_CONFIG is expanded from...
aclocal.m4:4621: _LT_AC_TAGCONFIG is expanded from...

5) ./configure --with-php-config=/opt/lampp/bin/php-config-5.2.9

6) make

I'm a newbie so please someone guide me through this process. Thanks!


问:
Apply a vector-valued function to a vector. Result not as expected
In Matloff's The Art of R programming, he uses the function below (z12) to demonstrate the use of a vector-valued function.

My question is: When applying the function to 1:8, why does it return 1 2 3 4 ... 1 4 9 16 ... and not 1, 1, 2, 4, 3, 9 ...? After all, isn't z^2 right next to z in the return statement?

答:
An alternative would be to use rep and recycling.

```<code>zN <-  function(x) rep(x, each=2)^c(1:2)
</code>```

Now, give it a try.

```<code>zN(1:8)
 [1]  1  1  2  4  3  9  4 16  5 25  6 36  7 49  8 64
</code>```

Or, with the desired order

```<code>zN2 <-  function(x) x^rep(1:2, each=length(x))
zN2(1:8)
 [1]  1  2  3  4  5  6  7  8  1  4  9 16 25 36 49 64
</code>```

Body:
An alternative would be to use rep and recycling.

zN <-  function(x) rep(x, each=2)^c(1:2)

Now, give it a try.

zN(1:8)
 [1]  1  1  2  4  3  9  4 16  5 25  6 36  7 49  8 64

Or, with the desired order

zN2 <-  function(x) x^rep(1:2, each=length(x))
zN2(1:8)
 [1]  1  2  3  4  5  6  7  8  1  4  9 16 25 36 49 64


问:
Change multiple string in a list
I have a list

```<code>task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
</code>```

the result i want is

```<code>task_list = ['1A1.wakeup', '1A2.brush','2B1.route','2B2.breakfast']
</code>```

I use a for loop:

```<code>new_task_list = task_list[:]
for task in new_task_list:
    task.replace('A', '1A')
    task.replace('B','1B')

In [61]: new_task_list
Out[61]: ['A1.wakeup', 'A2.brush', 'B1.route', 'B2.breakfast']
</code>```

It does not change, What's the problem?

答:
str.replace does not work in-place (pun unintended).

You can create a mapping of the replacements and use a list comprehension to build the new list looking up values from the mapping an prepending those to each string:

```<code>mapping = {'A': '1', 'B': '2'}
new_list = [mapping[x[0]]+x for x in task_list]
print(new_list)
# ['1A1.wakeup', '1A2.brush', '2B1.route', '2B2.breakfast']
</code>```

Title: Change multiple string in a list

Body:
I have a list

task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']

the result i want is

task_list = ['1A1.wakeup', '1A2.brush','2B1.route','2B2.breakfast']

I use a for loop:

new_task_list = task_list[:]
for task in new_task_list:
    task.replace('A', '1A')
    task.replace('B','1B')

In [61]: new_task_list
Out[61]: ['A1.wakeup', 'A2.brush', 'B1.route', 'B2.breakfast']

It does not change, What's the problem?

Body:
str.replace does not work in-place (pun unintended).

You can create a mapping of the replacements and use a list comprehension to build the new list looking up values from the mapping an prepending those to each string:

mapping = {'A': '1', 'B': '2'}
new_list = [mapping[x[0]]+x for x in task_list]
print(new_list)
# ['1A1.wakeup', '1A2.brush', '2B1.route', '2B2.breakfast']


问:
Is a UIWebView the best way to display formatted text in iOS?
I want to display formatted text in my iOS app and I have a lot of it (about as much text as a medium sized wikipedia entry) is a WebView with html the best way to display formatted text or is there a better way? I read on stackOverflow that WebViews suck a lot of memory, is that true? How does wikipedia display all of its text in its iOS app?</p>

答: I ended up using a WKWebView with a contrained height and width. That way I could load the HTML without any additional set up and I didn't run into any problems with the web views bounds. </p>


问:
How Can I pass Start and end date parameter in Powerbi URL
How can I pass the start and end date parameter in the URL so that the report gets sorted out as I need to be. How to show the data in between those date parameters.</p>

答: You mean something like this https://learn.microsoft.com/en-us/power-bi/service-url-filters ?</p>


问:
ResultSet to jTable = java.sql.SQLException: The prepared statement has been finalized
Friends of StackOverFlow!

I Try "return" a ResultSet in select statement and have erros...
I Search in Google and StackOverFlow, but nothing Solve This Problem!

The Statement Insert Work OK! But the Select not Work...

Database Layer:

```<code>package Database;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBConnection {
    private static Connection               conn = null;
    private static ResultSet                rs = null;
    private static Statement                stmt = null;
    private static PreparedStatement        pst = null;

    private static final String             DATABASE_PATH_NAME="jdbc:sqlite:MiraReal.Xitano";

    private Connection Connect()
    {
        try
        {
            Class.forName("org.sqlite.JDBC");

            conn                            = DriverManager.getConnection(DATABASE_PATH_NAME);

            return conn;
        }
        catch (Exception ex)
        {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);

            return null;
        }
    }

    public boolean RunQuery(String sql)
    {
        Statement                           stmt;
        try {
            Connect();

            stmt                            = conn.createStatement();

            stmt.execute(sql);

            Disconnect();

            return true;

        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        // create a new table
    }

    public ResultSet RunSelect(String sql){
        try {
            Connect();

            stmt                            = conn.createStatement();

            rs                              = stmt.executeQuery(sql);
            //rs..moveToFirst();
            Disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rs;
    }

    public int RunCount(String sql, String where)
    {
        return 1;
    }

    private void Disconnect()
    {
        try
        {
            DBConnection.conn.close();
            DBConnection.conn               = null;
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

Actions Layer:

```<code>package Actions;

import Models.CustomersModels;
import java.sql.ResultSet;
import java.util.logging.Logger;

public class CustomersActions extends CustomersModels {
    protected String sqlInsert = "INSERT INTO customers (uuid, fullname, email, created_at, updated_at) VALUES ('%s', '%s', '%s', '%s', '%s') ";
    protected String sqlUpdate = "UPDATE customers SET fullname='%s' WHERE uuid='%s'";
    protected String sqlDelete = "DELETE FROM customers WHERE uuid='%s'";
    protected String sqlSelect = "SELECT %s FROM customers %s %s %s";

    public boolean insert()
    {
        String sql = String.format(sqlInsert, this.getUuid(),
                this.getFullname(), this.getEmail(), this.getCreatedAt(),
                this.getUpdatedAt());

        return this.RunQuery(sql);
    }

    public boolean update()
    {
        String sql = String.format(sqlUpdate, this.getFullname(), this.getUuid());

        return this.RunQuery(sql);
    }

    public boolean delete()
    {
        String sql = String.format(sqlDelete, this.getUuid());

        return this.RunQuery(sql);
    }

    public ResultSet select(String columns, String where, String order, String limit)
    {
        String sql = String.format(sqlSelect, columns, where, order, limit);

        System.out.println(sql);

        return this.RunSelect(sql);
    }

}
</code>```

Try use it (Result Set to jTable using net.proteanit.sql.DbUtils):

```<code>Customers customers = new Customers();

        String customersColumns = "*";
        String customersWhere = "";
        String customersOrder = "";
        String customersLimit = "";

        ResultSet dsCustomers = customers.select(customersColumns, customersWhere, customersOrder, customersLimit);

        this.jTable1.setModel(DbUtils.resultSetToTableModel(dsCustomers));
</code>```

Error:

```<code>run:
SELECT * FROM customers
java.sql.SQLException: The prepared statement has been finalized
    at org.sqlite.core.NativeDB.throwex(NativeDB.java:471)
    at org.sqlite.core.NativeDB.column_name_utf8(Native Method)
    at org.sqlite.core.NativeDB.column_name(NativeDB.java:232)
    at org.sqlite.jdbc3.JDBC3ResultSet.getColumnName(JDBC3ResultSet.java:721)
    at org.sqlite.jdbc3.JDBC3ResultSet.getColumnLabel(JDBC3ResultSet.java:714)
    at net.proteanit.sql.DbUtils.resultSetToTableModel(DbUtils.java:21)
    at Frames.MiraReal.seederCustomers(MiraReal.java:142)
    at Frames.MiraReal.<init>(MiraReal.java:37)
    at Frames.MiraReal$2.run(MiraReal.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Frames.MiraReal.seederCustomers(MiraReal.java:142)
    at Frames.MiraReal.<init>(MiraReal.java:37)
    at Frames.MiraReal$2.run(MiraReal.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
CONSTRUÍDO COM SUCESSO (tempo total: 2 segundos)
</code>```

What i do?

Thank You!

答:
Please re-read carefully the Javadoc for Statement (superclass of PreparedStatement).

Note:When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

What is happening is that the PreparedStatement is declared in RunQuery, and it goes out of scope when that method ends, at which point the ResultSet is no longer valid.

You cannot structure the code as you currently have it. The PreparedStatement must be defined in the execution scope where the ResultSet is used.

Body:
Friends of StackOverFlow!

I Try "return" a ResultSet in select statement and have erros...
I Search in Google and StackOverFlow, but nothing Solve This Problem!

The Statement Insert Work OK! But the Select not Work...

Database Layer:

package Database;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBConnection {
    private static Connection               conn = null;
    private static ResultSet                rs = null;
    private static Statement                stmt = null;
    private static PreparedStatement        pst = null;

    private static final String             DATABASE_PATH_NAME="jdbc:sqlite:MiraReal.Xitano";

    private Connection Connect()
    {
        try
        {
            Class.forName("org.sqlite.JDBC");

            conn                            = DriverManager.getConnection(DATABASE_PATH_NAME);

            return conn;
        }
        catch (Exception ex)
        {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);

            return null;
        }
    }

    public boolean RunQuery(String sql)
    {
        Statement                           stmt;
        try {
            Connect();

            stmt                            = conn.createStatement();

            stmt.execute(sql);

            Disconnect();

            return true;

        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        // create a new table
    }

    public ResultSet RunSelect(String sql){
        try {
            Connect();

            stmt                            = conn.createStatement();

            rs                              = stmt.executeQuery(sql);
            //rs..moveToFirst();
            Disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rs;
    }

    public int RunCount(String sql, String where)
    {
        return 1;
    }

    private void Disconnect()
    {
        try
        {
            DBConnection.conn.close();
            DBConnection.conn               = null;
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Actions Layer:

package Actions;

import Models.CustomersModels;
import java.sql.ResultSet;
import java.util.logging.Logger;

public class CustomersActions extends CustomersModels {
    protected String sqlInsert = "INSERT INTO customers (uuid, fullname, email, created_at, updated_at) VALUES ('%s', '%s', '%s', '%s', '%s') ";
    protected String sqlUpdate = "UPDATE customers SET fullname='%s' WHERE uuid='%s'";
    protected String sqlDelete = "DELETE FROM customers WHERE uuid='%s'";
    protected String sqlSelect = "SELECT %s FROM customers %s %s %s";

    public boolean insert()
    {
        String sql = String.format(sqlInsert, this.getUuid(),
                this.getFullname(), this.getEmail(), this.getCreatedAt(),
                this.getUpdatedAt());

        return this.RunQuery(sql);
    }

    public boolean update()
    {
        String sql = String.format(sqlUpdate, this.getFullname(), this.getUuid());

        return this.RunQuery(sql);
    }

    public boolean delete()
    {
        String sql = String.format(sqlDelete, this.getUuid());

        return this.RunQuery(sql);
    }

    public ResultSet select(String columns, String where, String order, String limit)
    {
        String sql = String.format(sqlSelect, columns, where, order, limit);

        System.out.println(sql);

        return this.RunSelect(sql);
    }

}

Try use it (Result Set to jTable using net.proteanit.sql.DbUtils):

Customers customers = new Customers();

        String customersColumns = "*";
        String customersWhere = "";
        String customersOrder = "";
        String customersLimit = "";

        ResultSet dsCustomers = customers.select(customersColumns, customersWhere, customersOrder, customersLimit);

        this.jTable1.setModel(DbUtils.resultSetToTableModel(dsCustomers));

Error:

run:
SELECT * FROM customers
java.sql.SQLException: The prepared statement has been finalized
    at org.sqlite.core.NativeDB.throwex(NativeDB.java:471)
    at org.sqlite.core.NativeDB.column_name_utf8(Native Method)
    at org.sqlite.core.NativeDB.column_name(NativeDB.java:232)
    at org.sqlite.jdbc3.JDBC3ResultSet.getColumnName(JDBC3ResultSet.java:721)
    at org.sqlite.jdbc3.JDBC3ResultSet.getColumnLabel(JDBC3ResultSet.java:714)
    at net.proteanit.sql.DbUtils.resultSetToTableModel(DbUtils.java:21)
    at Frames.MiraReal.seederCustomers(MiraReal.java:142)
    at Frames.MiraReal.<init>(MiraReal.java:37)
    at Frames.MiraReal$2.run(MiraReal.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Frames.MiraReal.seederCustomers(MiraReal.java:142)
    at Frames.MiraReal.<init>(MiraReal.java:37)
    at Frames.MiraReal$2.run(MiraReal.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
CONSTRUÍDO COM SUCESSO (tempo total: 2 segundos)

What i do?

Thank You!


问:
Binary indicatory between start dates and and end dates in R
I have the below dataframe where I am trying to obtain the below-expected output. I am trying to compare EST_INST_ST_DATE with the ST_DATE if it matches I want to keep the IS_WITHIN_30DAYS  column indicator 1 else if EST_INST_ST_DATE lies between the month I want to have 1 for the next 2 consecutive months

```<code> INPUT
ID ST_DATE     ND_DATE        EST_INST_ST_DATE
1   2016-01-04   2016-02-03     2016-01-04
1   2016-02-04   2016-03-03     2016-01-04
2   2016-01-04   2016-02-03     2016-01-12
2   2016-02-04   2016-03-03     2016-01-12
2   2016-03-04   2016-04-03     2016-01-12

Expected output
ID     ST_DATE       ND_DATE     EST_INST_ST_DATE     IS_WITHIN_30DAYS
1     2016-01-04   2016-02-03     2016-01-04               1
1     2016-02-04   2016-03-03     2016-01-04               0
2     2016-01-04   2016-02-03     2016-01-12               1
2     2016-02-04   2016-03-03     2016-01-12               1
2     2016-03-04   2016-04-03     2016-01-12               0
</code>```

I am trying the below code but I am getting error

```<code>chargefmv5<- chargefmv5 %>%
  mutate(IS_WITHIN_30DAYS=ifelse((EST_INST_ST_DATE == ST_DATE),1,
                                 ifelse((EST_INST_ST_DATE > ST_DATE & EST_INST_ST_DATE <ND_DATE)),1,0))

Error in ifelse((EST_INST_ST_DATE == ST_DATE), 1, ifelse((EST_INST_ST_DATE >  :
  unused arguments (1, 0)
</code>```

答:
You closed your second ifelse early. Try:

```<code>chargefmv5 <- chargefmv5 %>%
mutate(IS_WITHIN_30DAYS=ifelse(
  (EST_INST_ST_DATE == ST_DATE),
  1,
  ifelse(
    (EST_INST_ST_DATE > ST_DATE & EST_INST_ST_DATE <ND_DATE),
    1,
    0
  )
)
)
</code>```

Body:
I have the below dataframe where I am trying to obtain the below-expected output. I am trying to compare EST_INST_ST_DATE with the ST_DATE if it matches I want to keep the IS_WITHIN_30DAYS  column indicator 1 else if EST_INST_ST_DATE lies between the month I want to have 1 for the next 2 consecutive months

 INPUT
ID ST_DATE     ND_DATE        EST_INST_ST_DATE
1   2016-01-04   2016-02-03     2016-01-04
1   2016-02-04   2016-03-03     2016-01-04
2   2016-01-04   2016-02-03     2016-01-12
2   2016-02-04   2016-03-03     2016-01-12
2   2016-03-04   2016-04-03     2016-01-12

Expected output
ID     ST_DATE       ND_DATE     EST_INST_ST_DATE     IS_WITHIN_30DAYS
1     2016-01-04   2016-02-03     2016-01-04               1
1     2016-02-04   2016-03-03     2016-01-04               0
2     2016-01-04   2016-02-03     2016-01-12               1
2     2016-02-04   2016-03-03     2016-01-12               1
2     2016-03-04   2016-04-03     2016-01-12               0

I am trying the below code but I am getting error

chargefmv5<- chargefmv5 %>%
  mutate(IS_WITHIN_30DAYS=ifelse((EST_INST_ST_DATE == ST_DATE),1,
                                 ifelse((EST_INST_ST_DATE > ST_DATE & EST_INST_ST_DATE <ND_DATE)),1,0))

Error in ifelse((EST_INST_ST_DATE == ST_DATE), 1, ifelse((EST_INST_ST_DATE >  :
  unused arguments (1, 0)

Body:
You closed your second ifelse early. Try:

chargefmv5 <- chargefmv5 %>%
mutate(IS_WITHIN_30DAYS=ifelse(
  (EST_INST_ST_DATE == ST_DATE),
  1,
  ifelse(
    (EST_INST_ST_DATE > ST_DATE & EST_INST_ST_DATE <ND_DATE),
    1,
    0
  )
)
)


问:
window.performance.memory is not giving updated data but it should give
I am trying to get memory used by a particular tab in the browser using JavaScript code.
I have tried using window.performance.memory in Chrome. It gives me the JS heap size data but the data returned by it everytime is constant. I am creating new objects in my code (hence, memory usage should increase) but still it returns the same data everytime.
I have also used --enable-precise-memory-info argument to open my Chrome. Still same results.

Is there a way to get updated data from window.performance.memory?
Also is there any other way I can get memory usage data of a particular tab opened in the browser? I want this data to be exported in a text file so that I can use it for further analysis.
(I have tried using Chrome's task manager and Memory Manager extension also. But I want data in a text file.)

答: Try window.performance.memory after opening chrome in administrator mode.</p>


问:
How to find second highest salary in mysql
How to find second highest salary in mysql.
All record find in second highest salary.

```<code>Table : Employee
ID    salary      emp_name
1     400         A
2     800         B
3     300         C
4     400         D
4     400         C

*** Mysql Query: ***
SELECT * FROM employee ORDER by salary DESC LIMIT 1,2
</code>```

This return two record.I do not know how many record in second highest salary.

答:
SELECT sal
FROM emp
ORDER BY sal DESC
LIMIT 1, 1;
```

You will get only the second max salary.

And if you need any 3rd or 4th or Nth value you can increase the first value followed by LIMIT (n-1) ie. for 4th salary: LIMIT 3, 1;

Body:
How to find second highest salary in mysql.
All record find in second highest salary.

Table : Employee
ID    salary      emp_name
1     400         A
2     800         B
3     300         C
4     400         D
4     400         C

*** Mysql Query: ***
SELECT * FROM employee ORDER by salary DESC LIMIT 1,2

This return two record.I do not know how many record in second highest salary.

Body:
SELECT sal
FROM emp
ORDER BY sal DESC
LIMIT 1, 1;

You will get only the second max salary.

And if you need any 3rd or 4th or Nth value you can increase the first value followed by LIMIT (n-1) ie. for 4th salary: LIMIT 3, 1;


问:
why copy constructor is called when passing temporary by const reference?
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

```<code>class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}
</code>```

As expected, when I change the main to:

```<code>A a(1);
f(a);
</code>```

it works.

EDIT: the compiler is gcc 4.1.2

答:
Because a(1) calls the constructor A(int i) and then A(const A&) is called in the call to void f(const A&).

Make the A(int i) constructor  explicit and you should not face this error.

Edit: I think i misunderstood the question. I might delete this.

Body:
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}

As expected, when I change the main to:

A a(1);
f(a);

it works.

EDIT: the compiler is gcc 4.1.2


问:
Filling xAxis for all nights in Highcharts
Is there a way to fill the datetime on xAxis for each night ?

I managed to do it for one night, but would like to do that for every night which is displayed. As a must, it would be nice to calculate the real sunrise and sunset and allow the display only when the scale allow to see it. Over a week, it has no sense.

```<code>xAxis: {
        type: 'datetime',
        plotBands: [{
        color:'rgba(156,156,156,.15)',
        from: Date.UTC(2017, 10, 13,19),
        to: Date.UTC(2017, 10, 14,5),
            label: {
            text: '☾',
            style : {color : '#D9B11D',
            fill : '#D9B11D',
            fontSize :'20px' },
            align: 'left',
            x: 10,y: 30
        }
    }]
</code>```

Thanks,

答:
You can process the data for plot bands like this:

```<code>  chart: {
    events: {
      load: function() {
        var xAxis = this.xAxis[0],
            ex = xAxis.getExtremes(),
          start = ex.min,
          plotBands = [];

          while (start + nightLength < ex.max) {

            plotBands.push({
              from: start,
              to: start + nightLength,
              color: 'rgba(156,156,156,.15)',
              label: {
                text: '☾',
                style: {
                  color: '#D9B11D',
                  fill: '#D9B11D',
                  fontSize: '20px'
                },
                align: 'left',
                y: 30
              }
            });
            start += day;

          }
          xAxis.update({
            plotBands: plotBands
          });
      }
    }
  }
</code>```

Live demo: http://jsfiddle.net/kkulig/cpk59waw/

An important part of the code is the chart extremes constraint (so that there're only as much plot bands as needed):

```<code> while (start + nightLength < ex.max)
</code>```

I implemented very simplified case here. The assumptions are that the night has a constant length and the sunrise always happens on the same time.

If you want to have real values for sunrise and sunset you should find some data source for it.

Body:
Is there a way to fill the datetime on xAxis for each night ?

I managed to do it for one night, but would like to do that for every night which is displayed. As a must, it would be nice to calculate the real sunrise and sunset and allow the display only when the scale allow to see it. Over a week, it has no sense.

xAxis: {
        type: 'datetime',
        plotBands: [{
        color:'rgba(156,156,156,.15)',
        from: Date.UTC(2017, 10, 13,19),
        to: Date.UTC(2017, 10, 14,5),
            label: {
            text: '☾',
            style : {color : '#D9B11D',
            fill : '#D9B11D',
            fontSize :'20px' },
            align: 'left',
            x: 10,y: 30
        }
    }]

Thanks,

Body:
You can process the data for plot bands like this:

  chart: {
    events: {
      load: function() {
        var xAxis = this.xAxis[0],
            ex = xAxis.getExtremes(),
          start = ex.min,
          plotBands = [];

          while (start + nightLength < ex.max) {

            plotBands.push({
              from: start,
              to: start + nightLength,
              color: 'rgba(156,156,156,.15)',
              label: {
                text: '☾',
                style: {
                  color: '#D9B11D',
                  fill: '#D9B11D',
                  fontSize: '20px'
                },
                align: 'left',
                y: 30
              }
            });
            start += day;

          }
          xAxis.update({
            plotBands: plotBands
          });
      }
    }
  }

Live demo: http://jsfiddle.net/kkulig/cpk59waw/

An important part of the code is the chart extremes constraint (so that there're only as much plot bands as needed):

 while (start + nightLength < ex.max)

I implemented very simplified case here. The assumptions are that the night has a constant length and the sunrise always happens on the same time.

If you want to have real values for sunrise and sunset you should find some data source for it.


问:
Delete a folder on SD card
I tried File.delete() but it doesn't work. How to delete a directory on SD card?

I'm working on Android 2.1.

答:
It worked for me:</p>

```<code>Add in manifest-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

private boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            if (files == null) {
                return false;
            }
            for(File file : files) {
                if(file.isDirectory()) {
                    deleteDirectory(file);
                }
                else {
                file.delete();
                }
            }
        }
        return path.exists()?path.delete():false;
    }
</code>```

Title: Delete a folder on SD card

Body:
It worked for me:

Add in manifest-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

private boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            if (files == null) {
                return false;
            }
            for(File file : files) {
                if(file.isDirectory()) {
                    deleteDirectory(file);
                }
                else {
                file.delete();
                }
            }
        }
        return path.exists()?path.delete():false;
    }


问:
Is it possible to connect to an On-Premise LDAP using the IBM Bluemix Secure Gateway?
IBM Secure Gateway is a kind of VPN connectivity tool. I need to query an LDAP in an on-premise intranet network.

There is also an another VPN service offered by IBM Bluemix named IPSec.

Which of the two would be more feasible?

答:
It depends on what kind of resources your application needs,
if you are using PaaS services (former Bluemix) you can use the Secure Gateway. If you are using IaaS services (baremetal or VMs) than I would suggest Vyatta rather than IPSec, because the latter doen't offer a connecction suitable for production, while Vyatta provides a lot of functionalities among which also an enterprise grade VPN termination bidirectional.</p>

```<code>https://knowledgelayer.softlayer.com/topic/ipsec-vpn
https://knowledgelayer.softlayer.com/procedure/how-configure-ipsec-vyatta
https://www.ibm.com/blogs/bluemix/2015/03/bluemix-secure-gateway-yes-can-get/
</code>```

Body:
It depends on what kind of resources your application needs,
if you are using PaaS services (former Bluemix) you can use the Secure Gateway. If you are using IaaS services (baremetal or VMs) than I would suggest Vyatta rather than IPSec, because the latter doen't offer a connecction suitable for production, while Vyatta provides a lot of functionalities among which also an enterprise grade VPN termination bidirectional.

https://knowledgelayer.softlayer.com/topic/ipsec-vpn
https://knowledgelayer.softlayer.com/procedure/how-configure-ipsec-vyatta
https://www.ibm.com/blogs/bluemix/2015/03/bluemix-secure-gateway-yes-can-get/


答:
task in your for loop is just a variable updated on each loop iteration, task.replace('A', '1A') doesn't change the list value inplace.

I would suggest the following solution with re module:

```<code>import re

task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
new_task_list = [ re.sub(r'^(A|B)', lambda m: ('1' if m.group(1) == 'A' else '2') + m.group(1), t)
                  for t in task_list]

print(new_task_list)
</code>```

The output:

```<code>['1A1.wakeup', '1A2.brush', '2B1.route', '2B2.breakfast']
</code>```

Or even simpler:

```<code>task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
search = {'A':'1', 'B':'2'}
new_task_list = [ (search[t[0]] if t[0] in search else '') + t for t in task_list]
print(new_task_list)
</code>```

Title: Change multiple string in a list

Body:
task in your for loop is just a variable updated on each loop iteration, task.replace('A', '1A') doesn't change the list value inplace.

I would suggest the following solution with re module:

import re

task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
new_task_list = [ re.sub(r'^(A|B)', lambda m: ('1' if m.group(1) == 'A' else '2') + m.group(1), t)
                  for t in task_list]

print(new_task_list)

The output:

['1A1.wakeup', '1A2.brush', '2B1.route', '2B2.breakfast']

Or even simpler:

task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
search = {'A':'1', 'B':'2'}
new_task_list = [ (search[t[0]] if t[0] in search else '') + t for t in task_list]
print(new_task_list)


问:
jQuery - toggle & removeClass
An easy one, but I can't figure it out. I have a link called #title and when you click it it toggles div called #content. This works perfectly, but in addition I'm adding "active" class to my #title link and I can't get rid of it, even with removeClass.

See code above and example link (the title should be red ONLY when the #content is expanded, not all the time).

```<code>$('#title').click(function() {
    $(this).addClass('active');
    $('#content').toggle();
}), function() {
    $(this).removeClass('active');
};
</code>```

http://jsfiddle.net/vY3WY/

答:
I think that this is the most appropriate way to do it.

$(this).toggleClass('active').siblings().removeClass('active');

Title: jQuery - toggle & removeClass

Body:
An easy one, but I can't figure it out. I have a link called #title and when you click it it toggles div called #content. This works perfectly, but in addition I'm adding "active" class to my #title link and I can't get rid of it, even with removeClass.

See code above and example link (the title should be red ONLY when the #content is expanded, not all the time).

$('#title').click(function() {
    $(this).addClass('active');
    $('#content').toggle();
}), function() {
    $(this).removeClass('active');
};

http://jsfiddle.net/vY3WY/


问:
Finding compiler vendor / version using qmake
Is there any way to get the version and vendor of the compiler used by the user through qmake? What I need is to disable building some targets of my project when g++ 3.x is used and enable them when g++ 4.x is used.

Update: Most answers targeted the preprocessor. This is something that I want to avoid. I don't want a target to be build for a specific compiler version and I want this decision to be made by the build system.

答:
My answer is based on dismine's answer

We can simply extract the major version number using $$str_member

```<code>gcc | clang {
    COMPILER_VERSION = $$system($$QMAKE_CXX " -dumpversion")
    COMPILER_MAJOR_VERSION = $$str_member($$COMPILER_VERSION)
    greaterThan(COMPILER_MAJOR_VERSION, 3): message("gcc 4 or later")
    greaterThan(COMPILER_MAJOR_VERSION, 4): message("gcc 5 or later")
    greaterThan(COMPILER_MAJOR_VERSION, 5): message("gcc 6 or later")
    greaterThan(COMPILER_MAJOR_VERSION, 6): message("gcc 7 or later")
}
</code>```

Body:
My answer is based on dismine's answer

We can simply extract the major version number using $$str_member

gcc | clang {
    COMPILER_VERSION = $$system($$QMAKE_CXX " -dumpversion")
    COMPILER_MAJOR_VERSION = $$str_member($$COMPILER_VERSION)
    greaterThan(COMPILER_MAJOR_VERSION, 3): message("gcc 4 or later")
    greaterThan(COMPILER_MAJOR_VERSION, 4): message("gcc 5 or later")
    greaterThan(COMPILER_MAJOR_VERSION, 5): message("gcc 6 or later")
    greaterThan(COMPILER_MAJOR_VERSION, 6): message("gcc 7 or later")
}