问:
Can I do a time based progress in awk?
I am currently using awk scripting to censor the console output and I print one dot for each censored line.

I want to update this code to make it avoid printing more than one dot per minute (or something similar). Obviously that if I do not get any progress (streamed new lines), no update is supposed to happen.

Current version of the code is at https://gist.github.com/ssbarnea/f7b72491af524fa364d9fc328cd43f2a

Note: I know that I could print a newline with "mod 10" or similar in order to limit the output but that approach is not good because the lines are not received with a consistent speed, sometimes I get lots of them, sometimes i get only one or two. Due to this I need to use a timer based approach which would do something like "print newline if the last one was printed more than x seconds ago"

答:
With GNU awk for time functions you can print dots no more frequently than once per minute by simply comparing the time in seconds since the epoch when the current input line is being processed with the time when the previous dot was printed:

```<code>awk '
function prtDot() {
    currTime = systime()
    if ( (currTime - prevTime) > 60 ) {
        printf "." | "cat>&2"
        prevTime = currTime
    }
}
{ print $0; prtDot() }
END { print "" | "cat>&2" }
'
</code>```

e.g. printing a . every 10 seconds within a stream of numbers:

```<code>$ cat tst.awk
function prtDot() {
    currTime = systime()
    if ( (currTime - prevTime) > 10 ) {
        printf "." | "cat>&2"
        prevTime = currTime
    }
}
{ printf "%s",$0%10 | "cat>&2"; prtDot() }
END { print "" | "cat>&2" }

$ i=0; while (( i < 50 )); do echo $((++i)); sleep 1; done | awk -f tst.awk
1.2345678901.23456789012.3456789012.34567890123.4567890

$ i=0; while (( i < 50 )); do echo $((++i)); sleep 3; done | awk -f tst.awk
1.2345.6789.0123.4567.8901.2345.6789.0123.4567.8901.2345.6789.0
</code>```

the slight difference between the actual digits printed and expected is due to how long other parts of the while loop add to the overall interval between echos and other small imprecisions affecting when the shell loop is printing numbers and consequently when systime() is getting called in awk.

Title: Can I do a time based progress in awk?

Body:
With GNU awk for time functions you can print dots no more frequently than once per minute by simply comparing the time in seconds since the epoch when the current input line is being processed with the time when the previous dot was printed:

awk '
function prtDot() {
    currTime = systime()
    if ( (currTime - prevTime) > 60 ) {
        printf "." | "cat>&2"
        prevTime = currTime
    }
}
{ print $0; prtDot() }
END { print "" | "cat>&2" }
'

e.g. printing a . every 10 seconds within a stream of numbers:

$ cat tst.awk
function prtDot() {
    currTime = systime()
    if ( (currTime - prevTime) > 10 ) {
        printf "." | "cat>&2"
        prevTime = currTime
    }
}
{ printf "%s",$0%10 | "cat>&2"; prtDot() }
END { print "" | "cat>&2" }

$ i=0; while (( i < 50 )); do echo $((++i)); sleep 1; done | awk -f tst.awk
1.2345678901.23456789012.3456789012.34567890123.4567890

$ i=0; while (( i < 50 )); do echo $((++i)); sleep 3; done | awk -f tst.awk
1.2345.6789.0123.4567.8901.2345.6789.0123.4567.8901.2345.6789.0

the slight difference between the actual digits printed and expected is due to how long other parts of the while loop add to the overall interval between echos and other small imprecisions affecting when the shell loop is printing numbers and consequently when systime() is getting called in awk.


来源: stackexchange

问:
Tips for debugging list comprehensions?
Python list comprehensions are nice, but near impossible to debug.  You guys have any good tips / tools for debugging them?</p>

答:
I use a function that just prints and returns a value at the same time:

```<code>from pprint import pprint

def debug(msg, item):
    print('\n' + msg + ':')
    pprint(item)
    return item
</code>```

It's very handy for debugging any part of a list/dict comprehension:

```<code>new_lines = [
    debug('CUR UPDATED LINE', change(line))
    for line
    in debug('ALL LINES', get_lines_from_file(filename))
    if debug('CUR LINE EMPTY?', not_empty(line))
    ]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Tips for debugging list comprehensions?

Body:
I use a function that just prints and returns a value at the same time:

from pprint import pprint

def debug(msg, item):
    print('\n' + msg + ':')
    pprint(item)
    return item

It's very handy for debugging any part of a list/dict comprehension:

new_lines = [
    debug('CUR UPDATED LINE', change(line))
    for line
    in debug('ALL LINES', get_lines_from_file(filename))
    if debug('CUR LINE EMPTY?', not_empty(line))
    ]

ContentLicense: CC BY-SA 4.0


问:
Correlation in R of two columns of complete cases - only returning first element of vector?
I'm new to R and trying to complete the following prompt:

Write a function that takes a directory of data files and a threshold for complete cases and calculates the correlation between sulfate and nitrate for monitor locations where the number of completely observed cases (on all variables) is greater than the threshold. The function should return a vector of correlations for the monitors that meet the threshold requirement. If no monitors meet the threshold requirement, then the function should return a numeric vector of length 0. A prototype of this function follows:

```<code>corr <- function(directory, threshold = 0) {
## 'directory' is a character vector of length 1 indicating the location of
## the CSV files

## 'threshold' is a numeric vector of length 1 indicating the number of
        ## completely observed observations (on all variables) required to compute
        ## the correlation between nitrate and sulfate; the default is 0

## Return a numeric vector of correlations

spectdata<- list.files(pattern= ".csv") #creates vector with list of filenames
corr<-function(directory,threshold =0, id = 1:332){
  info<-list()
  for(i in id){
    info<-read.csv(directory[i], header=TRUE)
    NOBS<-sum(complete.cases(info))
    if (NOBS>threshold){
      return(cor(info$nitrate,info$sulfate,use="complete.obs"))
    }

  }
  corr<-sapply(spectdata,corr)
  corr<-unlist(corr[!sapply(corr,is.null)])
  return(corr)
}
cr<-corr(spectdata,threshold =150)
head(cr)
</code>```

It looks like the program works, but only returns the first element on a 5 element vector:

```<code>> cr<-corr(spectdata,threshold =150)
> head(cr)
[1] -0.01895754
</code>```

what it should be:

```<code>cr <- corr("specdata", 150)
head(cr)
## [1] -0.01895754 -0.14051254 -0.04389737 -0.06815956 -0.12350667 -0.07588814
</code>```

Anybody have any thoughts? I am quite new to R and am stumped. If I try to define the vector to be longer, I get the same answer (0.01895754 NA NA NA NA), for example.

答:
You're unlikely to get the full answer for free, but assuming you want to learn, your function has a lot of issues.

First you define the function twice:

```<code>### corr defined here
corr <- function(directory, threshold = 0) {
             spectdata<- list.files(pattern= ".csv")
             ### corr defined here again!!
             corr<-function(directory,threshold =0, id = 1:332) {
</code>```

Second you don't specify where list.files should look:

```<code>spectdata<- list.files(pattern= ".csv") # you should add directory
                                        # I'll leave it to you to add it
</code>```

Third Your function returns multiple arguments:

```<code>return(cor(info$nitrate,info$sulfate,use="complete.obs")) # 1st return
return(corr)                                              # 2nd return
</code>```

Fourth You repeat variable names. Your function is called corr and you define a local variable as corr:

```<code>corr <- sapply(spectdata, corr)      ## local variable
</code>```

MY SUGGESTIONS given what you've provided as code

First  Stick with 1 function definition the first one is fine

Second  Specify the directory where list.files should look

Third  Return only a single argument.

```<code>You can make a vector of elements with a for loop like so:

info <- NULL
for (i in 1:4) {
    info <- c(info, i)
}
</code>```

Fourth  You don't need sapply or unlist. Try to make it work without them.

Fifth  Use a different variable name for the local variable that conflicts with the function name.

MOST IMPORTANTLY Run each command line-by-line and look at each output.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to R and trying to complete the following prompt:

Write a function that takes a directory of data files and a threshold for complete cases and calculates the correlation between sulfate and nitrate for monitor locations where the number of completely observed cases (on all variables) is greater than the threshold. The function should return a vector of correlations for the monitors that meet the threshold requirement. If no monitors meet the threshold requirement, then the function should return a numeric vector of length 0. A prototype of this function follows:

corr <- function(directory, threshold = 0) {
## 'directory' is a character vector of length 1 indicating the location of
## the CSV files

## 'threshold' is a numeric vector of length 1 indicating the number of
        ## completely observed observations (on all variables) required to compute
        ## the correlation between nitrate and sulfate; the default is 0

## Return a numeric vector of correlations

spectdata<- list.files(pattern= ".csv") #creates vector with list of filenames
corr<-function(directory,threshold =0, id = 1:332){
  info<-list()
  for(i in id){
    info<-read.csv(directory[i], header=TRUE)
    NOBS<-sum(complete.cases(info))
    if (NOBS>threshold){
      return(cor(info$nitrate,info$sulfate,use="complete.obs"))
    }

  }
  corr<-sapply(spectdata,corr)
  corr<-unlist(corr[!sapply(corr,is.null)])
  return(corr)
}
cr<-corr(spectdata,threshold =150)
head(cr)

It looks like the program works, but only returns the first element on a 5 element vector:

> cr<-corr(spectdata,threshold =150)
> head(cr)
[1] -0.01895754

what it should be:

cr <- corr("specdata", 150)
head(cr)
## [1] -0.01895754 -0.14051254 -0.04389737 -0.06815956 -0.12350667 -0.07588814

Anybody have any thoughts? I am quite new to R and am stumped. If I try to define the vector to be longer, I get the same answer (0.01895754 NA NA NA NA), for example.

Body:
You're unlikely to get the full answer for free, but assuming you want to learn, your function has a lot of issues.

First you define the function twice:

### corr defined here
corr <- function(directory, threshold = 0) {
             spectdata<- list.files(pattern= ".csv")
             ### corr defined here again!!
             corr<-function(directory,threshold =0, id = 1:332) {

Second you don't specify where list.files should look:

spectdata<- list.files(pattern= ".csv") # you should add directory
                                        # I'll leave it to you to add it

Third Your function returns multiple arguments:

return(cor(info$nitrate,info$sulfate,use="complete.obs")) # 1st return
return(corr)                                              # 2nd return

Fourth You repeat variable names. Your function is called corr and you define a local variable as corr:

corr <- sapply(spectdata, corr)      ## local variable

MY SUGGESTIONS given what you've provided as code

First  Stick with 1 function definition the first one is fine

Second  Specify the directory where list.files should look

Third  Return only a single argument.

You can make a vector of elements with a for loop like so:

info <- NULL
for (i in 1:4) {
    info <- c(info, i)
}

Fourth  You don't need sapply or unlist. Try to make it work without them.

Fifth  Use a different variable name for the local variable that conflicts with the function name.

MOST IMPORTANTLY Run each command line-by-line and look at each output.


问:
What is double plus in regular expressions?
I have been seeing this in some PHP script:

```<code>[a-zA-Z0-9_]++
</code>```

What does the double plus mean?

答:
That's a Possessive Quantifier.

It basically means that if the regex engine fails matching later, it will not go back and try to undo the matches it made here. In most cases, it allows the engine to fail much faster, and can give you some control where you need it - which is very rare for most uses.

Body:
I have been seeing this in some PHP script:

[a-zA-Z0-9_]++

What does the double plus mean?


问:
How do you annotate a chart from a pivot-table dataframe column?
I have a dataset

```<code>a   b   c   d
10-Apr-86   Jimmy   1   this is
11-Apr-86   Minnie  2   the way
12-Apr-86   Jimmy   3   the world
13-Apr-86   Minnie  4   ends
14-Apr-86   Jimmy   5   this is the
15-Apr-86   Eliot   6   way
16-Apr-86   Jimmy   7   the world ends
17-Apr-86   Eliot   8   not with a bang
18-Apr-86   Minnie  9   but a whimper
</code>```

I want to make a chart in matplotlib that looks like this

I've figure out how to get just the dots (no annotations) using the following code:

```<code>df = (pd.read_csv('python.csv'))
df_wanted = pd.pivot_table(
    df,
    index='a',
    columns='b',
    values='c')

df_wanted.index = pd.to_datetime(df_wanted.index)

plt.scatter(df_wanted.index, df_wanted['Jimmy'])
plt.scatter(df_wanted.index,df_wanted['Minnie'])
plt.scatter(df_wanted.index,df_wanted['Eliot'])
</code>```

I think that to annotate, I need a list of values (as demonstrated here ) on the final column of my pivot table

My problem is: how do I get that final column 'd' of the original dataset to become the final column of my pivot table?

I tried dat1 = pd.concat([df_wanted, df['d']], axis = 1) - but this created a new set of rows underneath the rows of my dataframe.  I realized the axis wasn't the same, so I tried to make a new pivot table with the d column as values - but got the error message No numeric types to aggregate.

I tried df_wanted2.append(df['d']) - but this made a new column for every element in column d.

Any advice?  Ultimately, I want to make it so the data labels appear when one rolls over the point with the mouse

答:
In this specific case, it doesn't seem you need to set column d as the final column of your pivot table.

```<code>plt.scatter(df_wanted.index, df_wanted['Jimmy'])
plt.scatter(df_wanted.index,df_wanted['Minnie'])
plt.scatter(df_wanted.index,df_wanted['Eliot'])
plt.legend(loc=0)

for k, v in df.set_index('a').iterrows():
    plt.text(k, v['c'], v['d']) # or: plt.annotate(xy=(k, v['c']), s=v['d'])
</code>```

Body:
I have a dataset

a   b   c   d
10-Apr-86   Jimmy   1   this is
11-Apr-86   Minnie  2   the way
12-Apr-86   Jimmy   3   the world
13-Apr-86   Minnie  4   ends
14-Apr-86   Jimmy   5   this is the
15-Apr-86   Eliot   6   way
16-Apr-86   Jimmy   7   the world ends
17-Apr-86   Eliot   8   not with a bang
18-Apr-86   Minnie  9   but a whimper

I want to make a chart in matplotlib that looks like this

I've figure out how to get just the dots (no annotations) using the following code:

df = (pd.read_csv('python.csv'))
df_wanted = pd.pivot_table(
    df,
    index='a',
    columns='b',
    values='c')

df_wanted.index = pd.to_datetime(df_wanted.index)

plt.scatter(df_wanted.index, df_wanted['Jimmy'])
plt.scatter(df_wanted.index,df_wanted['Minnie'])
plt.scatter(df_wanted.index,df_wanted['Eliot'])

I think that to annotate, I need a list of values (as demonstrated here ) on the final column of my pivot table

My problem is: how do I get that final column 'd' of the original dataset to become the final column of my pivot table?

I tried dat1 = pd.concat([df_wanted, df['d']], axis = 1) - but this created a new set of rows underneath the rows of my dataframe.  I realized the axis wasn't the same, so I tried to make a new pivot table with the d column as values - but got the error message No numeric types to aggregate.

I tried df_wanted2.append(df['d']) - but this made a new column for every element in column d.

Any advice?  Ultimately, I want to make it so the data labels appear when one rolls over the point with the mouse

Body:
In this specific case, it doesn't seem you need to set column d as the final column of your pivot table.

plt.scatter(df_wanted.index, df_wanted['Jimmy'])
plt.scatter(df_wanted.index,df_wanted['Minnie'])
plt.scatter(df_wanted.index,df_wanted['Eliot'])
plt.legend(loc=0)

for k, v in df.set_index('a').iterrows():
    plt.text(k, v['c'], v['d']) # or: plt.annotate(xy=(k, v['c']), s=v['d'])


问:
Priority Queue with Doubly Linked List Insertion
I am implementing a priority queue waitlist using a doubly linked list. My method creates a new node (priority and student id). Depending on the node priority the method will sort the node into the queue.

```<code>what I get is                                what I should get

Waitlisted:             109 in 2123      |   Waitlisted:             109 in 2123
Current waitlist:       109              |   Current waitlist:       109
                                         |
Waitlisted:             105 in 2123      |   Waitlisted:             105 in 2123
Current waitlist:       105              |   Current waitlist:       105 109
                                         |
Waitlisted:             108 in 2123      |   Waitlisted:             108 in 2123
Current waitlist:       109 105          |   Current waitlist:       105 108 109
                                         |
Waitlisted:             106 in 2123      |   Waitlisted:             106 in 2123
Current waitlist:       106              |   Current waitlist:       105 106 108 109
                                         |
Waitlisted:             107 in 2123      |   Waitlisted:             107 in 2123
Current waitlist:       109 106          |   Current waitlist:       105 106 107 108 109
</code>```

I am able to insert a new node when the queue is empty on the first loop. Starting from the 2nd run the return values of the queue are wrong.

Code

```<code>void enqueue( PQNode** ppFront, WaitlistEntry info ){
    /* create a new node to store the info */
    PQNode *temp = (PQNode*)malloc(sizeof(PQNode)); //create a new node to store the info
    temp->info = info;
    temp->pNext = NULL;
    temp->pPrev = NULL;

    /* check if the LL is empty and add the new node to the front if it is */
    if(*ppFront == NULL){
        *ppFront = temp;
        return;
    }

    /* check if the new node should come before the first node in the LL */
    if(temp->info.iPriority > (*ppFront)->info.iPriority){
        temp->pNext = *ppFront;
        (*ppFront)->pPrev = temp;
        *ppFront = temp;
        return;
    }

    /* walk back through the previous nodes in the LL until the correct insertion point is found */
    /* remember to also check whether the previous node is NULL */
    while((*ppFront)->pNext != NULL && temp->info.iPriority <= (*ppFront)->info.iPriority){
        *ppFront = (*ppFront)->pNext;
    }

    /* insert the new node into the place you found with your loop */
    /* note you may need a special case for when the previous node is NULL */
    if((*ppFront)->pNext == NULL){
        (*ppFront)->pNext = temp;
        temp->pPrev = *ppFront;
        return;
    }
    temp->pPrev = *ppFront;
    temp->pNext = (*ppFront)->pNext;
    (*ppFront)->pNext->pPrev = temp;
    (*ppFront)->pNext = temp;
    return;
}
</code>```

Structs

```<code>typedef struct{
    int iPriority;          /* Priority of the student to be enrolled */
    int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode {
    WaitlistEntry info;     /* WaitlistEntry stored in the node (sorted with largest priority first) */
    struct PQNode* pNext;   /* Pointer to next node in the LL */
    struct PQNode* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct{
    int iCourseNumber;      /* Course number of the course */
    int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
    int iNumEnrolled;       /* Number of Students currently enrolled in course */
    int iMaxEnrolled;       /* Max number of Students that can enroll in the course */
    PQNode* pFront;         /* Priority queue representing the waitlist for the course */
} Course;
</code>```

I've managed to fix up the code some, but I'm still stuck.

答:
As BLUEPIXY mentioned, the last bit of the function is a bit wrong (//edit you've changed your code in the meantime, I'm referring to your original code). When you go through the list in the while block, and then you realize that curr is the tail, you fail to check whether you got there because either temps priority is greater than the tail's or you've reached the end of the list and temp should become the new tail.

Also, the very last part you are inserting temp at the wrong side.

The last part of your code should like this

// edit posting the whole code, I only changed the last bit of your function, and the parameters for enqueue, much easier to write test code for this.

```<code>void print_queue(PQNode *queue)
{
    if(queue == NULL)
    {
        puts("empty queue");
        return;
    }

    for(;;)
    {
        printf("%d (priority %d)", queue->info.iStudentID, queue->info.iPriority);
        queue = queue->pNext;

        if(queue == NULL)
        {
            puts("");
            return;
        }

        printf(" <--> ");
    }
}

void enqueue( PQNode** ppFront, int id, int prio ){
    /* create a new node to store the info */
    PQNode *temp = (PQNode*)malloc(sizeof(PQNode)); //create a new node to store the info
    temp->info.iStudentID = id;
    temp->info.iPriority = prio;
    temp->pNext = NULL;
    temp->pPrev = NULL;
    PQNode *curr = *ppFront;

    /* check if the LL is empty and add the new node to the front if it is */
    if(curr == NULL){
        *ppFront = temp;
        return;
    }

    /* check if the new node should come before the first node in the LL */
    if(temp->info.iPriority > curr->info.iPriority){
        temp->pNext = *ppFront;
        (*ppFront)->pPrev = temp;
        *ppFront = temp;
        return;
    }

    /* walk back through the previous nodes in the LL until the correct insertion point is found */
    /* remember to also check whether the previous node is NULL */
    while(curr->pNext != NULL && temp->info.iPriority <= curr->info.iPriority){
        curr = curr->pNext;
    }

    /* insert the new node into the place you found with your loop */
    /* note you may need a special case for when the previous node is NULL */
    if(curr->pNext == NULL){
        // we don't know whether the while stopped because it reached the
        // final node or the priority was greater, we have to check it
        if(temp->info.iPriority <= curr->info.iPriority)
        {
            // the priority is smaller, temp should be the tail
            curr->pNext = temp;
            temp->pPrev = curr;
            return;
        } else {
            // the priority is bigger, curr should the the tail
            // this case is handled by the next section
        }
    }

    temp->pPrev = curr->pPrev;
    temp->pNext = curr;
    curr->pPrev->pNext = temp;
    curr->pPrev = temp;
}

int main(void)
{
    PQNode *queue = NULL;

    enqueue(&queue, 109, 10);
    enqueue(&queue, 105, 40);
    enqueue(&queue, 108, 20);
    enqueue(&queue, 110, 30);
    enqueue(&queue, 911, 11);
    enqueue(&queue, 219, 25);

    print_queue(queue);

    return 0;
}
</code>```

I get

```<code>105 (priority 40) <--> 110 (priority 30) <--> 219 (priority 25) <--> 108 (priority 20) <--> 911 (priority 11) <--> 109 (priority 10)
</code>```

Body:
I am implementing a priority queue waitlist using a doubly linked list. My method creates a new node (priority and student id). Depending on the node priority the method will sort the node into the queue.

what I get is                                what I should get

Waitlisted:             109 in 2123      |   Waitlisted:             109 in 2123
Current waitlist:       109              |   Current waitlist:       109
                                         |
Waitlisted:             105 in 2123      |   Waitlisted:             105 in 2123
Current waitlist:       105              |   Current waitlist:       105 109
                                         |
Waitlisted:             108 in 2123      |   Waitlisted:             108 in 2123
Current waitlist:       109 105          |   Current waitlist:       105 108 109
                                         |
Waitlisted:             106 in 2123      |   Waitlisted:             106 in 2123
Current waitlist:       106              |   Current waitlist:       105 106 108 109
                                         |
Waitlisted:             107 in 2123      |   Waitlisted:             107 in 2123
Current waitlist:       109 106          |   Current waitlist:       105 106 107 108 109

I am able to insert a new node when the queue is empty on the first loop. Starting from the 2nd run the return values of the queue are wrong.

Code

void enqueue( PQNode** ppFront, WaitlistEntry info ){
    /* create a new node to store the info */
    PQNode *temp = (PQNode*)malloc(sizeof(PQNode)); //create a new node to store the info
    temp->info = info;
    temp->pNext = NULL;
    temp->pPrev = NULL;

    /* check if the LL is empty and add the new node to the front if it is */
    if(*ppFront == NULL){
        *ppFront = temp;
        return;
    }

    /* check if the new node should come before the first node in the LL */
    if(temp->info.iPriority > (*ppFront)->info.iPriority){
        temp->pNext = *ppFront;
        (*ppFront)->pPrev = temp;
        *ppFront = temp;
        return;
    }

    /* walk back through the previous nodes in the LL until the correct insertion point is found */
    /* remember to also check whether the previous node is NULL */
    while((*ppFront)->pNext != NULL && temp->info.iPriority <= (*ppFront)->info.iPriority){
        *ppFront = (*ppFront)->pNext;
    }

    /* insert the new node into the place you found with your loop */
    /* note you may need a special case for when the previous node is NULL */
    if((*ppFront)->pNext == NULL){
        (*ppFront)->pNext = temp;
        temp->pPrev = *ppFront;
        return;
    }
    temp->pPrev = *ppFront;
    temp->pNext = (*ppFront)->pNext;
    (*ppFront)->pNext->pPrev = temp;
    (*ppFront)->pNext = temp;
    return;
}

Structs

typedef struct{
    int iPriority;          /* Priority of the student to be enrolled */
    int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode {
    WaitlistEntry info;     /* WaitlistEntry stored in the node (sorted with largest priority first) */
    struct PQNode* pNext;   /* Pointer to next node in the LL */
    struct PQNode* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct{
    int iCourseNumber;      /* Course number of the course */
    int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
    int iNumEnrolled;       /* Number of Students currently enrolled in course */
    int iMaxEnrolled;       /* Max number of Students that can enroll in the course */
    PQNode* pFront;         /* Priority queue representing the waitlist for the course */
} Course;

I've managed to fix up the code some, but I'm still stuck.

Body:
As BLUEPIXY mentioned, the last bit of the function is a bit wrong (//edit you've changed your code in the meantime, I'm referring to your original code). When you go through the list in the while block, and then you realize that curr is the tail, you fail to check whether you got there because either temps priority is greater than the tail's or you've reached the end of the list and temp should become the new tail.

Also, the very last part you are inserting temp at the wrong side.

The last part of your code should like this

// edit posting the whole code, I only changed the last bit of your function, and the parameters for enqueue, much easier to write test code for this.

void print_queue(PQNode *queue)
{
    if(queue == NULL)
    {
        puts("empty queue");
        return;
    }

    for(;;)
    {
        printf("%d (priority %d)", queue->info.iStudentID, queue->info.iPriority);
        queue = queue->pNext;

        if(queue == NULL)
        {
            puts("");
            return;
        }

        printf(" <--> ");
    }
}

void enqueue( PQNode** ppFront, int id, int prio ){
    /* create a new node to store the info */
    PQNode *temp = (PQNode*)malloc(sizeof(PQNode)); //create a new node to store the info
    temp->info.iStudentID = id;
    temp->info.iPriority = prio;
    temp->pNext = NULL;
    temp->pPrev = NULL;
    PQNode *curr = *ppFront;

    /* check if the LL is empty and add the new node to the front if it is */
    if(curr == NULL){
        *ppFront = temp;
        return;
    }

    /* check if the new node should come before the first node in the LL */
    if(temp->info.iPriority > curr->info.iPriority){
        temp->pNext = *ppFront;
        (*ppFront)->pPrev = temp;
        *ppFront = temp;
        return;
    }

    /* walk back through the previous nodes in the LL until the correct insertion point is found */
    /* remember to also check whether the previous node is NULL */
    while(curr->pNext != NULL && temp->info.iPriority <= curr->info.iPriority){
        curr = curr->pNext;
    }

    /* insert the new node into the place you found with your loop */
    /* note you may need a special case for when the previous node is NULL */
    if(curr->pNext == NULL){
        // we don't know whether the while stopped because it reached the
        // final node or the priority was greater, we have to check it
        if(temp->info.iPriority <= curr->info.iPriority)
        {
            // the priority is smaller, temp should be the tail
            curr->pNext = temp;
            temp->pPrev = curr;
            return;
        } else {
            // the priority is bigger, curr should the the tail
            // this case is handled by the next section
        }
    }

    temp->pPrev = curr->pPrev;
    temp->pNext = curr;
    curr->pPrev->pNext = temp;
    curr->pPrev = temp;
}

int main(void)
{
    PQNode *queue = NULL;

    enqueue(&queue, 109, 10);
    enqueue(&queue, 105, 40);
    enqueue(&queue, 108, 20);
    enqueue(&queue, 110, 30);
    enqueue(&queue, 911, 11);
    enqueue(&queue, 219, 25);

    print_queue(queue);

    return 0;
}

I get

105 (priority 40) <--> 110 (priority 30) <--> 219 (priority 25) <--> 108 (priority 20) <--> 911 (priority 11) <--> 109 (priority 10)


问:
The sandbox is not in sync with the Podfile.lock-ios
I have got the following errors after trying multiple answers from the google.

```<code>PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-
    iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh
        cd "/Users/apple/Downloads/FoodSpot 2"
        /bin/sh -c /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh

    diff: /../Podfile.lock: No such file or directory
    diff: /Manifest.lock: No such file or directory
    error: The sandbox is not in sync with the Podfile.lock.
    Run 'pod   install' or update your CocoaPods installation.
</code>```

I have updated and installed many times, but they are of no use.

答: I had the same issue. Turned out the cocoapods version on Manifest.lock was higher than what I had on my mac. I had to do a 'sudo gem install cocoapods', to get the version of the cocoapods upto what was specified on the Manifest.lock file. This fixed the issue and I had no errors on building the project. </p>

Body:
I have got the following errors after trying multiple answers from the google.

PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-
    iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh
        cd "/Users/apple/Downloads/FoodSpot 2"
        /bin/sh -c /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh

    diff: /../Podfile.lock: No such file or directory
    diff: /Manifest.lock: No such file or directory
    error: The sandbox is not in sync with the Podfile.lock.
    Run 'pod   install' or update your CocoaPods installation.

I have updated and installed many times, but they are of no use.


问:
Safe to run Airflow upgradedb command on same Airflow version?
Airflow has an upgradedb command that needs to be run when upgrading Airflow versions. I wonder if it's safe to run even if the version is the same</p>

答:
The way it works is in db.py they use the alembic command module to check the checked in files in the migrations directory https://github.com/apache/incubator-airflow/tree/master/airflow/migrations/versions, and only make the changes if the commit version differs. But these files only get changed/added once we change the version so the upgrade db step does nothing when it's the same version/whl.
Adding it as a default step since I've verified it's safe to do so.</p>


问:
Neo4j 3.2 Cypher low performance
Without getting unnecessarily too specific, I'm facing the following issue with Cyper in Neo4j 3.2. Let's say we have a database with 3 entities: User, Comment, Like.

For whatever reason, I'm trying to run the following query:

```<code>MATCH (n:USER) WHERE n.name = "name"
WITH n
MATCH (o:USER)
WITH n, o, "2000" as number
MATCH (n)<-[:CREATED_BY]-(:COMMENT)-[:HAS]->(l:LIKE)-[:CREATED_BY]->(o)
RETURN n, o, number, count(l)
</code>```

The query takes minutes to complete. However, if I simply remove the "2000" as number part, it completes within tens of milliseconds.

Does anybody have an explanation why?

EDIT:
Top image, with "2000" as number part; bottom, without it.

答:
You're going to have to clean up your query, right now you're not using indexes (so the initial match with the specific name is slow), and then you perform a cartesian product against all :User nodes, then create strings for each row.

So first, create an index on :USER(name) so you can find your start node fast.

Then we'll have to clean up the rest of the match.

Try something like this instead:

```<code>MATCH (n:USER) WHERE n.name = "name"
WITH n, "2000" as number
MATCH (n)<-[:CREATED_BY]-(:COMMENT)-[:HAS]->(l:LIKE)-[:CREATED_BY]->(o:User)
RETURN n, o, number, count(l)
</code>```

You should see a similar plan with this query as in the query without the "2000".

The reason for this is that although your plan has a cartesian product with your match to o, the planner was intelligent enough to realize there was an additional restriction for o in that it had to occur in the pattern in your last match, and its optimization for that situation let you avoid performing a cartesian product.

Introduction of a new variable number, however, prevented the planner from recognizing that this was basically the same situation, so the planner did not optimize out the cartesian product.

For now, try to be explicit about how you want the query to be performed, and try to avoid cartesian products in your queries.

In this particular case, it's important to realize that when you have MATCH (o:User) on the third line, that's not declaring that the type of o is a :User in the later match, it's instead saying that for every row in your results so far, perform a cartesian product against all :User nodes, and then for each of those user nodes, see which ones exist in the pattern provided. That is a lot of unnecessary work, compared to simply expanding the pattern provided and getting whatever :User nodes you find at the other end of the pattern.

EDIT

As far as getting both :LIKE and :DISLIKE node counts, maybe try something like this:

```<code>MATCH (n:USER) WHERE n.name = "name"
WITH n, "2000" as number
MATCH (n)<-[:CREATED_BY]-(:COMMENT)-[:HAS]->(likeDislike)-[:CREATED_BY]->(o:User)
WITH n, o, number, head(labels(likeDislike)) as type, count(likeDislike) as cnt
WITH n, o, number, CASE WHEN type = "LIKE" THEN cnt END as likeCount, CASE WHEN type = "DISLIKE" THEN cnt END as dislikeCount
RETURN n, o, number, sum(likeCount) as likeCount, sum(dislikeCount) as dislikeCount
</code>```

Assuming you still need that number variable in there.

Title: Neo4j 3.2 Cypher low performance

Body:
Without getting unnecessarily too specific, I'm facing the following issue with Cyper in Neo4j 3.2. Let's say we have a database with 3 entities: User, Comment, Like.

For whatever reason, I'm trying to run the following query:

MATCH (n:USER) WHERE n.name = "name"
WITH n
MATCH (o:USER)
WITH n, o, "2000" as number
MATCH (n)<-[:CREATED_BY]-(:COMMENT)-[:HAS]->(l:LIKE)-[:CREATED_BY]->(o)
RETURN n, o, number, count(l)

The query takes minutes to complete. However, if I simply remove the "2000" as number part, it completes within tens of milliseconds.

Does anybody have an explanation why?

EDIT:
Top image, with "2000" as number part; bottom, without it.

Body:
You're going to have to clean up your query, right now you're not using indexes (so the initial match with the specific name is slow), and then you perform a cartesian product against all :User nodes, then create strings for each row.

So first, create an index on :USER(name) so you can find your start node fast.

Then we'll have to clean up the rest of the match.

Try something like this instead:

MATCH (n:USER) WHERE n.name = "name"
WITH n, "2000" as number
MATCH (n)<-[:CREATED_BY]-(:COMMENT)-[:HAS]->(l:LIKE)-[:CREATED_BY]->(o:User)
RETURN n, o, number, count(l)

You should see a similar plan with this query as in the query without the "2000".

The reason for this is that although your plan has a cartesian product with your match to o, the planner was intelligent enough to realize there was an additional restriction for o in that it had to occur in the pattern in your last match, and its optimization for that situation let you avoid performing a cartesian product.

Introduction of a new variable number, however, prevented the planner from recognizing that this was basically the same situation, so the planner did not optimize out the cartesian product.

For now, try to be explicit about how you want the query to be performed, and try to avoid cartesian products in your queries.

In this particular case, it's important to realize that when you have MATCH (o:User) on the third line, that's not declaring that the type of o is a :User in the later match, it's instead saying that for every row in your results so far, perform a cartesian product against all :User nodes, and then for each of those user nodes, see which ones exist in the pattern provided. That is a lot of unnecessary work, compared to simply expanding the pattern provided and getting whatever :User nodes you find at the other end of the pattern.

EDIT

As far as getting both :LIKE and :DISLIKE node counts, maybe try something like this:

MATCH (n:USER) WHERE n.name = "name"
WITH n, "2000" as number
MATCH (n)<-[:CREATED_BY]-(:COMMENT)-[:HAS]->(likeDislike)-[:CREATED_BY]->(o:User)
WITH n, o, number, head(labels(likeDislike)) as type, count(likeDislike) as cnt
WITH n, o, number, CASE WHEN type = "LIKE" THEN cnt END as likeCount, CASE WHEN type = "DISLIKE" THEN cnt END as dislikeCount
RETURN n, o, number, sum(likeCount) as likeCount, sum(dislikeCount) as dislikeCount

Assuming you still need that number variable in there.


问:
How do I tokenize a string in C++?
Java has a convenient split method:

```<code>String str = "The quick brown fox";
String[] results = str.split(" ");
</code>```

Is there an easy way to do this in C++?

答:
Check this example. It might help you..</p>

```<code>#include <iostream>
#include <sstream>

using namespace std;

int main ()
{
    string tmps;
    istringstream is ("the dellimiter is the space");
    while (is.good ()) {
        is >> tmps;
        cout << tmps << "\n";
    }
    return 0;
}
</code>```

OwnerDisplayName: Bill the Lizard

Title: How do I tokenize a string in C++?

Body:
Java has a convenient split method:

String str = "The quick brown fox";
String[] results = str.split(" ");

Is there an easy way to do this in C++?

Body:
Check this example. It might help you..

#include <iostream>
#include <sstream>

using namespace std;

int main ()
{
    string tmps;
    istringstream is ("the dellimiter is the space");
    while (is.good ()) {
        is >> tmps;
        cout << tmps << "\n";
    }
    return 0;
}


问:
Select SQL by group
I try to select with calculate by group but I get this error:

Msg 8120, Level 16, State 1, Line 1
  Column 'dbo.LN0617.RATE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Can someone help me?

```<code>SELECT
    NT4                AS nt,
    LN0617.OFFCR       AS OfficeCode,
    ln0617.RATE * 100  AS LaiSuat,
    SUM( ln0617.CBAL ) AS SoDu,
    ln0617.RATE * 100 * sum( ln0617.CBAL ) AS LS1
FROM
    [dbo].[SIL_CM]
    JOIN [dbo].[LN0617] ON
    (
        ln0617.ACCTNO = SIL_CM.TK
        AND
        ln0617.CBAL <> 0
        AND
        SIL_CM.TKTYPE='L'
    )
GROUP BY
    sil_cm.NT4,
    LN0617.OFFCR,
    ln0617.RATE * 100
ORDER BY
    LN0617.OFFCR,
    ln0617.RATE * 100
</code>```

答:
The only possible problem I see in your select list is the following line:

```<code>ln0617.RATE*100*sum(ln0617.CBAL) as LS1
</code>```

SQL Server may be complaining about ln0617.RATE because it is being mixed with an aggregate function.  One option here would be to move ln0617.RATE inside the summation:

```<code>select
    NT4 as nt,
    LN0617.OFFCR as OfficeCode,
    ln0617.RATE*100 as LaiSuat,
    sum(ln0617.CBAL) as SoDu,
    100*sum(ln0617.RATE * ln0617.CBAL) as LS1
from [dbo].[SIL_CM]
...
</code>```

This should work because multiplication is commutative.

Title: Select SQL by group

Body:
I try to select with calculate by group but I get this error:

Msg 8120, Level 16, State 1, Line 1
  Column 'dbo.LN0617.RATE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Can someone help me?

SELECT
    NT4                AS nt,
    LN0617.OFFCR       AS OfficeCode,
    ln0617.RATE * 100  AS LaiSuat,
    SUM( ln0617.CBAL ) AS SoDu,
    ln0617.RATE * 100 * sum( ln0617.CBAL ) AS LS1
FROM
    [dbo].[SIL_CM]
    JOIN [dbo].[LN0617] ON
    (
        ln0617.ACCTNO = SIL_CM.TK
        AND
        ln0617.CBAL <> 0
        AND
        SIL_CM.TKTYPE='L'
    )
GROUP BY
    sil_cm.NT4,
    LN0617.OFFCR,
    ln0617.RATE * 100
ORDER BY
    LN0617.OFFCR,
    ln0617.RATE * 100

Body:
The only possible problem I see in your select list is the following line:

ln0617.RATE*100*sum(ln0617.CBAL) as LS1

SQL Server may be complaining about ln0617.RATE because it is being mixed with an aggregate function.  One option here would be to move ln0617.RATE inside the summation:

select
    NT4 as nt,
    LN0617.OFFCR as OfficeCode,
    ln0617.RATE*100 as LaiSuat,
    sum(ln0617.CBAL) as SoDu,
    100*sum(ln0617.RATE * ln0617.CBAL) as LS1
from [dbo].[SIL_CM]
...

This should work because multiplication is commutative.


问:
Github API Approved Pull Request
Github has a new feature that users can approve pull requests. Does anyone know where to find the Pull Request approved stats in the Github API?</p>

答: It's now possible to review pull requests using the GitHub API. See Submit a pull request review in the API docs.</p>

Title: Github API Approved Pull Request


问:
Extensible registry of types
I have a program that can read multiple audio formats. A shared module could provide a trait, AudioFileReader, that has common methods for reading audio data as well as a registry for associating readers to file extensions.

Rather than have all the possible audio format readers built into the module, it would be useful for this module to be extensible, so that clients of the module can provide AudioFileReaders for new formats (either when linked into an executable or via a plug-in system).

What would be a conventional Rust way to build a system like this? Is there a way to avoid needing a global static registry while without losing extensibility?

答:
You can build such a registry by using a lazy_static global, which contains a map of extension name to Box<AudioFileReader>.

You would have to list them all in main (or have main call init functions). There's no way to automatically do this, Rust has no life before main.

Title: Extensible registry of types


问:
How to consume Page<Entity> response using Spring RestTemplate
I'm using spring data (mongoDb) and I've got my repository:

```<code>public interface StoriesRepository extends PagingAndSortingRepository<Story, String> {}
</code>```

Then i have a controller:

```<code>@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Page<StoryResponse>> getStories(Pageable pageable) {
    Page<StoryResponse> stories = storiesRepository.findAll(pageable).map(StoryResponseMapper::toStoryResponse);
    return ResponseEntity.ok(stories);
}
</code>```

Everything works fine, but I can't consume my endpoint using RestTemplate getForEntity method:

```<code>def entity = restTemplate.getForEntity(getLocalhost("/story"), new TypeReference<Page<StoryResponse>>(){}.class)
</code>```

What class should I provide to successfully deserialize my Page of entities?

答:
I know this thread is a little old, but hopefully someone will benefit from this.

@Ali Dehghani's answer is good, except that it re-implements what PageImpl<T> has already done. I considered this to be rather needless. I found a better solution by creating a class that extends PageImpl<T> and specifies a @JsonCreator constructor:

```<code>import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.company.model.HelperModel;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;

public class HelperPage extends PageImpl<HelperModel> {

    @JsonCreator
    // Note: I don't need a sort, so I'm not including one here.
    // It shouldn't be too hard to add it in tho.
    public HelperPage(@JsonProperty("content") List<HelperModel> content,
                      @JsonProperty("number") int number,
                      @JsonProperty("size") int size,
                      @JsonProperty("totalElements") Long totalElements) {
        super(content, new PageRequest(number, size), totalElements);
    }
}
</code>```

Then:

```<code>HelperPage page = restTemplate.getForObject(url, HelperPage.class);
</code>```

This is the same as creating a CustomPageImpl<T> class but allows us to take advantage of all the code that's already in PageImpl<T>.

Body:
I'm using spring data (mongoDb) and I've got my repository:

public interface StoriesRepository extends PagingAndSortingRepository<Story, String> {}

Then i have a controller:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Page<StoryResponse>> getStories(Pageable pageable) {
    Page<StoryResponse> stories = storiesRepository.findAll(pageable).map(StoryResponseMapper::toStoryResponse);
    return ResponseEntity.ok(stories);
}

Everything works fine, but I can't consume my endpoint using RestTemplate getForEntity method:

def entity = restTemplate.getForEntity(getLocalhost("/story"), new TypeReference<Page<StoryResponse>>(){}.class)

What class should I provide to successfully deserialize my Page of entities?

Body:
I know this thread is a little old, but hopefully someone will benefit from this.

@Ali Dehghani's answer is good, except that it re-implements what PageImpl<T> has already done. I considered this to be rather needless. I found a better solution by creating a class that extends PageImpl<T> and specifies a @JsonCreator constructor:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.company.model.HelperModel;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;

public class HelperPage extends PageImpl<HelperModel> {

    @JsonCreator
    // Note: I don't need a sort, so I'm not including one here.
    // It shouldn't be too hard to add it in tho.
    public HelperPage(@JsonProperty("content") List<HelperModel> content,
                      @JsonProperty("number") int number,
                      @JsonProperty("size") int size,
                      @JsonProperty("totalElements") Long totalElements) {
        super(content, new PageRequest(number, size), totalElements);
    }
}

Then:

HelperPage page = restTemplate.getForObject(url, HelperPage.class);

This is the same as creating a CustomPageImpl<T> class but allows us to take advantage of all the code that's already in PageImpl<T>.


问:
How to create a BizTalk Application btaproj
I am using BizTalk 2016 and I want to enable build from VSTS.

Build fails because it asks for some *.json files.

After some investigation I reached the conclusion that I have to create
a btaproj file. Add a BizTalk Server application to Visual Studio Team Services

I installed Feature Pack 1 but there is no option for BizTalk Application project.

How can I create a btaproj file?

答:
Did you select .NET Framework 4.6.1 in create new project dialog?

fr step by step instructions, please follow https://www.codit.eu/blog/2017/05/02/bts-2016-feature-pack-i-continuous-deployment-walkthrough/


问:
How to filter queryset with exclude and ForeignKey
I have two models

```<code>class Entry(models.Model):
    properties = here

class ReadedEntries(models.Model):
    entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

How can I get the no readed entries from a user?

I try:

```<code>not_looked_videos = Entry.objects.exclude(ReadedEntries.objects.filter(user=request.user))
</code>```

but I get:

```<code>ValueError: need more than 0 values to unpack
</code>```

答:
1, Filter ~Q(id__in = ids)

where ids = ReadedEntries.objects.filter(user=request.user).values_list('id', flat=True)

2.I am still in process to complete it...

Body:
I have two models

class Entry(models.Model):
    properties = here

class ReadedEntries(models.Model):
    entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

How can I get the no readed entries from a user?

I try:

not_looked_videos = Entry.objects.exclude(ReadedEntries.objects.filter(user=request.user))

but I get:

ValueError: need more than 0 values to unpack


问:
Understanding a pseudocode of Knapsack in recrusive
```<code>int knapsack(i, k){

    if(i=N){

        val= 0; //end of recrusive

        return val;
    }

    if (w[i]>k) // no space anymore

        val= knapsack(i+1, k);

    else {

        a = knapsack(i+1, k) // i don't take with

        b = knapsack(i+1, k-w[i]) + v[i]; //i take with

        val= max(a,b);

    }

    return val;
}
</code>```

My question is, what is N in this case ? In my Program for variables I have weight, value, maxweight and a LinkedList. Anyone can help me out ? Thanks

答:
N is the number of elements in the input array/list.
The first recursive call is knapsack(0,k), and each recursive call increments i , until it reaches N and the recursion ends.

Body:
int knapsack(i, k){

    if(i=N){

        val= 0; //end of recrusive

        return val;
    }

    if (w[i]>k) // no space anymore

        val= knapsack(i+1, k);

    else {

        a = knapsack(i+1, k) // i don't take with

        b = knapsack(i+1, k-w[i]) + v[i]; //i take with

        val= max(a,b);

    }

    return val;
}

My question is, what is N in this case ? In my Program for variables I have weight, value, maxweight and a LinkedList. Anyone can help me out ? Thanks


问:
How create bug work item in visual studio online from wpf app or some other web app?
I have a bugs list managed in a WPF app. I would like to create the bug in the VSO work item. Is there an API available to create work items like bug or task in Visual Studio Online?</p>

答:
Yes, there has the REST API to create a work item. The example code as:

```<code>using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;

...

public void CreateBug()
{
   string _personalAccessToken = "your personal access token";
   string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _personalAccessToken)));

   Object[] patchDocument = new Object[4];

   patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
   patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
   patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
   patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };

   //use the httpclient
   using (var client = new HttpClient())
   {
       //set our headers
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
       client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);

       //serialize the fields array into a json string
       var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");

       var method = new HttpMethod("PATCH");
       var request = new HttpRequestMessage(method, "https://accountname.visualstudio.com/fabrikam/_apis/wit/workitems/$Bug?api-version=2.2") { Content = patchValue };
       var response = client.SendAsync(request).Result;

       //if the response is successfull, set the result to the workitem object
       if (response.IsSuccessStatusCode)
       {
           var result = response.Content.ReadAsStringAsync().Result;
       }
   }
}
</code>```

More details, you can refer create bug.

Body:
Yes, there has the REST API to create a work item. The example code as:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;

...

public void CreateBug()
{
   string _personalAccessToken = "your personal access token";
   string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _personalAccessToken)));

   Object[] patchDocument = new Object[4];

   patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
   patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
   patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
   patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };

   //use the httpclient
   using (var client = new HttpClient())
   {
       //set our headers
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
       client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);

       //serialize the fields array into a json string
       var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");

       var method = new HttpMethod("PATCH");
       var request = new HttpRequestMessage(method, "https://accountname.visualstudio.com/fabrikam/_apis/wit/workitems/$Bug?api-version=2.2") { Content = patchValue };
       var response = client.SendAsync(request).Result;

       //if the response is successfull, set the result to the workitem object
       if (response.IsSuccessStatusCode)
       {
           var result = response.Content.ReadAsStringAsync().Result;
       }
   }
}

More details, you can refer create bug.


问:
Blaze template helper only returning on in a Spacebars each loop in Meteor/Mongo
I have a helper which should find all events that correspond to a given month and year argument and return them as an array for the template to loop through. It appears my helper is only returning for the first instance of year though rather than looping and I don't understand why.

Here's the template:

```<code>  <template name="list">
  <ul id="ulShell">
    {{#each year in getYears}}
      <li class="liYear">
        <h2>{{year}}</h2>
      </li>
      <ul class="ulSubShell">
        {{#each month in (getMonths year)}}
          <li class="liMonth">
            <h3>{{month}}</h3>
          </li>
          <ul>
            {{#each event in (getEvents month year)}}
              <li>
                <h4>{{dayOfWeek event.start}} – {{formatDate event.start}}</h4>
                <div class="divEvent">{{event.title}} <span class="spanDep pull-right">{{event.department}}</span></div>
              </li>
            {{/each}}
          </ul>
        {{/each}}
      </ul>
    {{/each}}
  </ul>
  </template>
</code>```

and here's the logic:

```<code>  let monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];

  let today = new Date();
  //today.setDate(today.getDate());

  let upcoming = {
    start: {
      $gt: today.toISOString()
    }
  }

  let findYears = function(){
    var selectedDep = Session.get('selectedDep');
    var distinctYears = _.uniq(Events.find( { $and: [ upcoming, selectedDep ] }, {
      sort: {start: 1}, fields: {start: true}
    }).fetch().map(function(x) {
      var d = Number(x.start.substring(0, 4));
      return d;
    }), true);
    return distinctYears;
  };

  let findMonths = function(year){
    var selectedDep = Session.get('selectedDep');
    var query = {
      start: {
        $gt: new Date(year - 1, 11, 31, 21, 59, 59, 999).toISOString(),
        $lt: new Date(year + 1, 0, 0, 22, 00, 00, 001).toISOString()
      }
    }
    var distinctMonths = _.uniq(Events.find( { $and: [ upcoming, query, selectedDep ] }, {
      sort: {start: 1}, fields: {start: true}
    }).fetch().map(function(x) {
        var d = Number(x.start.substring(5, 7));
        return monthNames[d];
    }), true);
    return distinctMonths;
  };

  ///////////  I think this is where the problem is. Maybe with the forEach() function?
  let findEvents = function(month, year){
    var selectedDep = Session.get('selectedDep');
    var events = Events.find( { $and: [ upcoming, selectedDep ] }, {sort: {start: 1}}).fetch();
    var finalEvents = new Array();
    events.forEach(function(event){
      var mDigits = monthNames.indexOf(month);
      mDigits += 1
      mDigits = mDigits.toString();
      var yearMonthSlice;
      if(mDigits.length === 1){
        yearMonthSlice = year+"-"+"0"+mDigits;
      }else if(mDigits.length === 2){
        yearMonthSlice = year+"-"+mDigits;
      }
      var getStart = event.start.substring(0, 7);
      if(yearMonthSlice === getStart){
        finalEvents.push(event);
      }
    });
    return finalEvents;
  };

  Template.list.onCreated( () => {
    let template = Template.instance();
    template.subscribe( 'events' );
  });

  Template.list.helpers({
    getYears() {
      foundYears = findYears();
      return foundYears;
    },
    getMonths(year) {
      foundMonthNames = findMonths(year);
      return foundMonthNames;
    },
    getEvents(month, year) {
      var foundEvents = findEvents(month, year);
      return foundEvents;
    },
    formatDate(start) {
      var dayNumber = start.substring(8, 10);
      return dayNumber;
    },
    dayOfWeek(start) {
      var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
      var x = Number(new Date(start).getDay());
      var dayName = days[x];
      return dayName;
    }
  });
</code>```

The list is rending in my browser like this:

Any help would be very much appreciated. I'm new to all of this especially Blaze/Spacebars/Meteor/MongoDB

答:
Let's simplify your example down to the bare minimum in blaze assuming that dates are stored as dates instead of strings!

We're going to:

Find the list of unique years corresponding to all the events

Find the list of unique month numbers corresponding to the year we are looking at

Find all the events that are in that month and year combination

Do as little date math as possible and no string manipulations

html:

```<code><template name="list">
  {{#each year in getYears}}
    {{year}}
    {{#each monthNumber in getMonths}}
      {{monthName monthNumber}}
      {{#each event in (getEvents monthNumber year)}}
        {{start}}
      {{/each}}
    {{/each}}
   {{/each}}
</template>
</code>```

js:

```<code>Template.list.helpers({
  getYears(){
    const years = Events.find({},{sort: {start: 1}}).map(event=>event.start.getFullYear()));
    return _.uniq(years)
  },
  getMonths(year){
    const months = Events.find(
      {start: {$gte: new Date(year,0,1), $lt: new Date(year+1,0,1)}},
      {sort: {start: 1}})
      .map(event=>event.start.getMonth()));
    return _.uniq(months); // this returns integers in [0,11]
  },
  getEvents(monthNumber,year){
    return Events.find(
      {start: {$gte: new Date(year,monthNumber,1), $lt: new Date(year,monthNumber+1,1)}},
      {sort: {start: 1}});
  },
  monthName(month){
    return monthNames[month];
});
</code>```

Note that the javascript Date() class is smart enough to wrap the year when month > 11 - ditto for the remaining date fields.

Body:
I have a helper which should find all events that correspond to a given month and year argument and return them as an array for the template to loop through. It appears my helper is only returning for the first instance of year though rather than looping and I don't understand why.

Here's the template:

  <template name="list">

    {{#each year in getYears}}

{{year}}

        {{#each month in (getMonths year)}}

{{month}}

            {{#each event in (getEvents month year)}}

{{dayOfWeek event.start}} – {{formatDate event.start}}

{{event.title}} {{event.department}}

            {{/each}}

        {{/each}}

    {{/each}}

  </template>

and here's the logic:

  let monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];

  let today = new Date();
  //today.setDate(today.getDate());

  let upcoming = {
    start: {
      $gt: today.toISOString()
    }
  }

  let findYears = function(){
    var selectedDep = Session.get('selectedDep');
    var distinctYears = _.uniq(Events.find( { $and: [ upcoming, selectedDep ] }, {
      sort: {start: 1}, fields: {start: true}
    }).fetch().map(function(x) {
      var d = Number(x.start.substring(0, 4));
      return d;
    }), true);
    return distinctYears;
  };

  let findMonths = function(year){
    var selectedDep = Session.get('selectedDep');
    var query = {
      start: {
        $gt: new Date(year - 1, 11, 31, 21, 59, 59, 999).toISOString(),
        $lt: new Date(year + 1, 0, 0, 22, 00, 00, 001).toISOString()
      }
    }
    var distinctMonths = _.uniq(Events.find( { $and: [ upcoming, query, selectedDep ] }, {
      sort: {start: 1}, fields: {start: true}
    }).fetch().map(function(x) {
        var d = Number(x.start.substring(5, 7));
        return monthNames[d];
    }), true);
    return distinctMonths;
  };

  ///////////  I think this is where the problem is. Maybe with the forEach() function?
  let findEvents = function(month, year){
    var selectedDep = Session.get('selectedDep');
    var events = Events.find( { $and: [ upcoming, selectedDep ] }, {sort: {start: 1}}).fetch();
    var finalEvents = new Array();
    events.forEach(function(event){
      var mDigits = monthNames.indexOf(month);
      mDigits += 1
      mDigits = mDigits.toString();
      var yearMonthSlice;
      if(mDigits.length === 1){
        yearMonthSlice = year+"-"+"0"+mDigits;
      }else if(mDigits.length === 2){
        yearMonthSlice = year+"-"+mDigits;
      }
      var getStart = event.start.substring(0, 7);
      if(yearMonthSlice === getStart){
        finalEvents.push(event);
      }
    });
    return finalEvents;
  };

  Template.list.onCreated( () => {
    let template = Template.instance();
    template.subscribe( 'events' );
  });

  Template.list.helpers({
    getYears() {
      foundYears = findYears();
      return foundYears;
    },
    getMonths(year) {
      foundMonthNames = findMonths(year);
      return foundMonthNames;
    },
    getEvents(month, year) {
      var foundEvents = findEvents(month, year);
      return foundEvents;
    },
    formatDate(start) {
      var dayNumber = start.substring(8, 10);
      return dayNumber;
    },
    dayOfWeek(start) {
      var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
      var x = Number(new Date(start).getDay());
      var dayName = days[x];
      return dayName;
    }
  });

The list is rending in my browser like this:

Any help would be very much appreciated. I'm new to all of this especially Blaze/Spacebars/Meteor/MongoDB

Body:
Let's simplify your example down to the bare minimum in blaze assuming that dates are stored as dates instead of strings!

We're going to:

Find the list of unique years corresponding to all the events

Find the list of unique month numbers corresponding to the year we are looking at

Find all the events that are in that month and year combination

Do as little date math as possible and no string manipulations

html:

<template name="list">
  {{#each year in getYears}}
    {{year}}
    {{#each monthNumber in getMonths}}
      {{monthName monthNumber}}
      {{#each event in (getEvents monthNumber year)}}
        {{start}}
      {{/each}}
    {{/each}}
   {{/each}}
</template>

js:

Template.list.helpers({
  getYears(){
    const years = Events.find({},{sort: {start: 1}}).map(event=>event.start.getFullYear()));
    return _.uniq(years)
  },
  getMonths(year){
    const months = Events.find(
      {start: {$gte: new Date(year,0,1), $lt: new Date(year+1,0,1)}},
      {sort: {start: 1}})
      .map(event=>event.start.getMonth()));
    return _.uniq(months); // this returns integers in [0,11]
  },
  getEvents(monthNumber,year){
    return Events.find(
      {start: {$gte: new Date(year,monthNumber,1), $lt: new Date(year,monthNumber+1,1)}},
      {sort: {start: 1}});
  },
  monthName(month){
    return monthNames[month];
});

Note that the javascript Date() class is smart enough to wrap the year when month > 11 - ditto for the remaining date fields.


问:
How to move the data to the next line based on spaces in sqlserver 2008 R2
Input : Keep the column value into next line if word to word space is 3 space and length of the word is >9 .

```<code>declare @Table table(CL1 varchar(50))
    INSERT INTO @Table
    SELECT 'Ohh   my GOD'
    UNION ALL
    SELECT 'hindunewspaer is no1 paper'

select * from @Table
</code>```

o/p :

    CL1

```<code>ohh
my god
hindunewpaer
is no1 paper
</code>```

答:
Used a Split/Parse function.  Can be inline if needed.

EDIT - Switch to a Parser which is not limited to 8K because the final
  string could easily be larger than 8K

Example

```<code>;with cte0 as (
        Select Seq=Row_Number() over (Order by (Select null)),RetSeq,RetVal
         From  @Table A
         Cross Apply (
                      Select RetSeq
                            ,RetVal=case when len(RetVal)>9 then '~~~' else '' end+RetVal+case when len(RetVal)>9 then '~~~' else '' end
                       From  [dbo].[udf-Str-Parse](Replace(CL1,'   ','~~~ '),' ')
                    ) B ),
      cte1 as ( Select S=Stuff((Select ' '+RetVal From  cte0 Order by Seq For XML Path ('')),1,1,'') )
Select CL1 = RetVal
 From  cte1 A
 Cross Apply [dbo].[udf-Str-Parse](A.S,'~~~') B
 Order By RetSeq
</code>```

Returns

```<code>CL1
Ohh
my GOD
hindunewspaer
is no1 paper
</code>```

The Split/Parse Function if Needed

```<code>CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')
</code>```

Body:
Input : Keep the column value into next line if word to word space is 3 space and length of the word is >9 .

declare @Table table(CL1 varchar(50))
    INSERT INTO @Table
    SELECT 'Ohh   my GOD'
    UNION ALL
    SELECT 'hindunewspaer is no1 paper'

select * from @Table

o/p :

    CL1

ohh
my god
hindunewpaer
is no1 paper

Body:
Used a Split/Parse function.  Can be inline if needed.

EDIT - Switch to a Parser which is not limited to 8K because the final
  string could easily be larger than 8K

Example

;with cte0 as (
        Select Seq=Row_Number() over (Order by (Select null)),RetSeq,RetVal
         From  @Table A
         Cross Apply (
                      Select RetSeq
                            ,RetVal=case when len(RetVal)>9 then '~~~' else '' end+RetVal+case when len(RetVal)>9 then '~~~' else '' end
                       From  [dbo].[udf-Str-Parse](Replace(CL1,'   ','~~~ '),' ')
                    ) B ),
      cte1 as ( Select S=Stuff((Select ' '+RetVal From  cte0 Order by Seq For XML Path ('')),1,1,'') )
Select CL1 = RetVal
 From  cte1 A
 Cross Apply [dbo].[udf-Str-Parse](A.S,'~~~') B
 Order By RetSeq

Returns

CL1
Ohh
my GOD
hindunewspaer
is no1 paper

The Split/Parse Function if Needed

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')


问:
Oracle ADF Production Project integeration
we need to develop a web application using Oracle ADF and jdeveloper 12c.
we have 10 modules.
Each module has developed by each member(Each member is using different system with same environment. Jdeveloper 12c).
Finally developing all the 10 modules how we can combine all the 10 modules as a single application.
How we can modify bindings , page flows and connection details.
By using Reusablity components?.
That means how?
For Eg:- In Sales Modules i have Sales & Sales Return pages both are designing by two seperate members how to integerate these two as single project like Sales.</p>

答:
As mentioned ADF libraries are a good way to package and compose an ADF application.
One thing to note though is that you could have multiple developers working in the same project, you should use a version management system such as Git to help merge changes in such a scenario.</p>


问:
How to use links in php mvc?
First problem:

Main url: site-test

1. I clicked on the link tasks -> url: site-test/tasks

2. i click next link next page (Where "tasks" - contoller, "page" - action, "2" - action value) -> url: site-test/tasks/page/2

3. i pressed again tasks and url -> site-test/tasks/page/tasks instead site-test/tasks/ what i need.

tasks is located in template view.

Second problem:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

My route:

```<code>static function start()
    {
        $controller_name = 'add_task';
        $action_name = 'index';

        $routes = explode('/', $_SERVER['REQUEST_URI']);

        if ( !empty($routes[1]) )
        {
            $controller_name = $routes[1];
        }

        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }

        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;

        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }

        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }

        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
            if ( !empty($routes[3]) )
            {
                $controller->$action($routes[3]);
            }
            else{
                $controller->$action();
            }
        }

    }
</code>```

My controller:

```<code>class Controller_tasks extends Controller
{
    function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

    function action_index()
    {
        $data = $this->model->get_data_from_server();
        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }

    function action_page($page = 1)
    {
        var_dump($page);
        $data = $this->model->get_data_from_server($page);

        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }
}
</code>```

Thx for any help, coz im rly confused.

答:
use base_url() in the link.

```<code><a href="<?php echo base_url() ?>tasks/">tasks</a>
<a href="<?php echo base_url() ?>tasks/page/2">next page</a>
</code>```

before that set base url to the root of your framework folder in the config page

eg: if u r using codeigniter. config.php file is located at codeigniter/aplication/config.php

set this in that page
$config['base_url'] = 'http://localhost/codeigniter';// change the path according to yours.

Ithink this will solve your first problem.
may be it could be the solution for the second problem also.(using base_url in all links)

Title: How to use links in php mvc?

Body:
First problem:

Main url: site-test

1. I clicked on the link tasks -> url: site-test/tasks

2. i click next link next page (Where "tasks" - contoller, "page" - action, "2" - action value) -> url: site-test/tasks/page/2

3. i pressed again tasks and url -> site-test/tasks/page/tasks instead site-test/tasks/ what i need.

tasks is located in template view.

Second problem:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

My route:

static function start()
    {
        $controller_name = 'add_task';
        $action_name = 'index';

        $routes = explode('/', $_SERVER['REQUEST_URI']);

        if ( !empty($routes[1]) )
        {
            $controller_name = $routes[1];
        }

        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }

        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;

        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }

        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }

        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
            if ( !empty($routes[3]) )
            {
                $controller->$action($routes[3]);
            }
            else{
                $controller->$action();
            }
        }

    }

My controller:

class Controller_tasks extends Controller
{
    function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

    function action_index()
    {
        $data = $this->model->get_data_from_server();
        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }

    function action_page($page = 1)
    {
        var_dump($page);
        $data = $this->model->get_data_from_server($page);

        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }
}

Thx for any help, coz im rly confused.

Body:
use base_url() in the link.

<a href="<?php echo base_url() ?>tasks/">tasks</a>
<a href="<?php echo base_url() ?>tasks/page/2">next page</a>

before that set base url to the root of your framework folder in the config page

eg: if u r using codeigniter. config.php file is located at codeigniter/aplication/config.php

set this in that page
$config['base_url'] = 'http://localhost/codeigniter';// change the path according to yours.

Ithink this will solve your first problem.
may be it could be the solution for the second problem also.(using base_url in all links)


问:
Unity3d: No Drag&Drop has been setup
I was working on a Unity 2D game project on OS X 10.10, and I can't drag file or folder, it will show this error.

```<code>No Drag&Drop has been setup. Please
UnityEditor.DockArea:OnGUI()
</code>```

I have tried:

save project and then restart

click Assets folder and choose Reimport All

But it seems not work, how to fix it?

答:
Based on @user3130047's answer, this is another version. Mac Only.

Quit Unity.

In console, put this command and execute it.

ps aux | grep pboard | grep -v grep | awk '{print $2}' | xargs kill -9 | launchctl start com.apple.pboard

Open Unity.

That's it.

But, this may cause your another opened applications copy&paste doesn't work. So, you need to restart them.

Title: Unity3d: No Drag&Drop has been setup

Body:
I was working on a Unity 2D game project on OS X 10.10, and I can't drag file or folder, it will show this error.

No Drag&Drop has been setup. Please
UnityEditor.DockArea:OnGUI()

I have tried:

save project and then restart

click Assets folder and choose Reimport All

But it seems not work, how to fix it?


问:
Rselenium - How to disable images in Firefox profile
How can image downloading be disabled when using Firefox in Rselenium? I want to see if doing so makes a scraping script faster.

I've read the Reselnium package manual including the sections on getFirefoxProfile & makeFirefoxProfile.

I've found this link that shows how to handle chromedriver.

I can disable images for a Firefox instance that I manually open in Windows 10 but Rselenium does not appear to use that same profile.

答:
Previously you would need to set the appropriate preference (in this case
permissions.default.image) however there is now an issue with firefox resetting this value see:

https://github.com/seleniumhq/selenium/issues/2171

a work around is given:

https://github.com/gempesaw/Selenium-Remote-Driver/issues/248

implementing this in RSelenium:

```<code>library(RSelenium)
fprof <- makeFirefoxProfile(list(permissions.default.image = 2L,
                                 browser.migration.version = 9999L))
rD <- rsDriver(browser = "firefox", extraCapabilities = fprof)
remDr <- rD$client
remDr$navigate("http://www.google.com/ncr")
remDr$screenshot(display = TRUE)

# clean up
rm(rD)
gc()
</code>```

Body:
Previously you would need to set the appropriate preference (in this case
permissions.default.image) however there is now an issue with firefox resetting this value see:

https://github.com/seleniumhq/selenium/issues/2171

a work around is given:

https://github.com/gempesaw/Selenium-Remote-Driver/issues/248

implementing this in RSelenium:

library(RSelenium)
fprof <- makeFirefoxProfile(list(permissions.default.image = 2L,
                                 browser.migration.version = 9999L))
rD <- rsDriver(browser = "firefox", extraCapabilities = fprof)
remDr <- rD$client
remDr$navigate("http://www.google.com/ncr")
remDr$screenshot(display = TRUE)

# clean up
rm(rD)
gc()


问:
What ports should I open for Firebase cloud messaging in my rails server?
What I'm trying to do:
HTTP messaging to my android app

Rails server on AWS -> HTTP request to Firebase with fcm gem -> HTTP Response

In this flow, what port should I open to Firebase server?

I've opened 5228~5230 as FCM docs said, but it didn't work.
(My server retunrs 500, execution expired error)
Only when I open all ports open to whole world, it worked.

What ports should I open..?

答:
5228~5230 ports are used to receive messages.

To send messages you only need to be able to open connections to

```<code>https://fcm.googleapis.com/fcm/send
</code>```

Depending on your configuration this might not require any change (usually connections open from the server don't require firewall changes) or it might require to open the standard HTTPS port: 443

Body:
5228~5230 ports are used to receive messages.

To send messages you only need to be able to open connections to

https://fcm.googleapis.com/fcm/send

Depending on your configuration this might not require any change (usually connections open from the server don't require firewall changes) or it might require to open the standard HTTPS port: 443


问:
getchar() is not called when the program is executed via nvim in C
I am a novice C programmer currently designing simple programs based on books to get more knowledge.
Right now, I am studying "The C Programming Language" (Brian Kernighan, Dennis Ritchie) and I'm hitting the section discussing about input/output programming.

Here is the code I am trying to run (almost exact copy from K&R):

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

int main (int argc, char** argv)
{
    int c;

    printf("Input character:\n");

    while ((c = getchar()) != EOF){
        putchar(c);
    }

    printf("End of code\n");

    return 0;

}
</code>```

I use nvim as my IDE. I set my nvim shortcuts as follow for the compilation:

```<code>nnoremap <leader>cc :!gcc -Wall % -o %:r && ./%:r<CR>
</code>```

Now back to the code. When I compile this one using the shortcut showed above, it works just fine. the code compiles. However, my program ends without asking me for any input (as the call to getchar() should do):

```<code>:!gcc -Wall inputoutput.c -o inputoutput && ./inputoutput

Input character:
End of code
</code>```

Typing the command directly in nvim, without any subsitution:

```<code>:gcc -Wall inputoutput.c -o inputoutput && ./inputoutput
</code>```

Gives me the same output as before.

However, when I execute the compiled program outside nvim, I get the expected behavior:

```<code>nxr: ~/scratch/c - ./inputouput
Input character:
a
a
** <CTRL-d> **
End of code

nxr: ~/scratch/c -
</code>```

My questions are:

Why the behavior within nvim and outside is different when I try running the code?

What should I change in my C code or my nvim macro in order to obtain the expected behavior when running the program within nvim?

答:
In gvim, :!gcc -Wall inputoutput.c -o inputoutput && ./inputoutput
works for me and runs the program in the lower screen.

Not sure what the nnoremap is doing, but there must be some control character getting introduced.  I usually don't use editor remaps like that.  Suggest writing a Makefile and just make run

Body:
I am a novice C programmer currently designing simple programs based on books to get more knowledge.
Right now, I am studying "The C Programming Language" (Brian Kernighan, Dennis Ritchie) and I'm hitting the section discussing about input/output programming.

Here is the code I am trying to run (almost exact copy from K&R):

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

int main (int argc, char** argv)
{
    int c;

    printf("Input character:\n");

    while ((c = getchar()) != EOF){
        putchar(c);
    }

    printf("End of code\n");

    return 0;

}

I use nvim as my IDE. I set my nvim shortcuts as follow for the compilation:

nnoremap <leader>cc :!gcc -Wall % -o %:r && ./%:r<CR>

Now back to the code. When I compile this one using the shortcut showed above, it works just fine. the code compiles. However, my program ends without asking me for any input (as the call to getchar() should do):

:!gcc -Wall inputoutput.c -o inputoutput && ./inputoutput

Input character:
End of code

Typing the command directly in nvim, without any subsitution:

:gcc -Wall inputoutput.c -o inputoutput && ./inputoutput

Gives me the same output as before.

However, when I execute the compiled program outside nvim, I get the expected behavior:

nxr: ~/scratch/c - ./inputouput
Input character:
a
a
** <CTRL-d> **
End of code

nxr: ~/scratch/c -

My questions are:

Why the behavior within nvim and outside is different when I try running the code?

What should I change in my C code or my nvim macro in order to obtain the expected behavior when running the program within nvim?


问:
Fastest way to determine if record exists
As the title suggests... I'm trying to figure out the fastest way with the least overhead to determine if a record exists in a table or not.

Sample query:

```<code>SELECT COUNT(*) FROM products WHERE products.id = ?;

    vs

SELECT COUNT(products.id) FROM products WHERE products.id = ?;

    vs

SELECT products.id FROM products WHERE products.id = ?;
</code>```

Say the ? is swapped with 'TB100'... both the first and second queries will return the exact same result (say... 1 for this conversation). The last query will return 'TB100' as expected, or nothing if the id is not present in the table.

The purpose is to figure out if the id is in the table or not. If not, the program will next insert the record, if it is, the program will skip it or perform an UPDATE query based on other program logic outside the scope of this question.

Which is faster and has less overhead? (This will be repeated tens of thousands of times per program run, and will be run many times a day).

(Running this query against M$ SQL Server from Java via the M$ provided JDBC driver)

答:
Don't think anyone has mentioned it yet, but if you are sure the data won't change underneath you, you may want to also apply the NoLock hint to ensure it is not blocked when reading.</p>

```<code>SELECT CASE WHEN EXISTS (SELECT 1
                     FROM dbo.[YourTable] WITH (NOLOCK)
                     WHERE [YourColumn] = [YourValue])
        THEN CAST (1 AS BIT)
        ELSE CAST (0 AS BIT) END
</code>```

Body:
As the title suggests... I'm trying to figure out the fastest way with the least overhead to determine if a record exists in a table or not.

Sample query:

SELECT COUNT(*) FROM products WHERE products.id = ?;

    vs

SELECT COUNT(products.id) FROM products WHERE products.id = ?;

    vs

SELECT products.id FROM products WHERE products.id = ?;

Say the ? is swapped with 'TB100'... both the first and second queries will return the exact same result (say... 1 for this conversation). The last query will return 'TB100' as expected, or nothing if the id is not present in the table.

The purpose is to figure out if the id is in the table or not. If not, the program will next insert the record, if it is, the program will skip it or perform an UPDATE query based on other program logic outside the scope of this question.

Which is faster and has less overhead? (This will be repeated tens of thousands of times per program run, and will be run many times a day).

(Running this query against M$ SQL Server from Java via the M$ provided JDBC driver)

Body:
Don't think anyone has mentioned it yet, but if you are sure the data won't change underneath you, you may want to also apply the NoLock hint to ensure it is not blocked when reading.

SELECT CASE WHEN EXISTS (SELECT 1
                     FROM dbo.[YourTable] WITH (NOLOCK)
                     WHERE [YourColumn] = [YourValue])
        THEN CAST (1 AS BIT)
        ELSE CAST (0 AS BIT) END


问:
Why Clang supports dereferencing uninitialized pointer
I am trying to understand what happened to my knowledge of C programming. Let's start with a CLASSICAL problem (dereferencing uninitialized pointer):

```<code>int main( void ) {
    char *p;
    *p = 'a';
    printf( "%c\n", *p );
    return 0;
}
</code>```

This is obviously WRONG! I know it. However, when I ran this on my MacOS 10.12 with LLVM Clang 8.1.0 implemented as compiler, it not only failed to detect uninitialized pointer, but also displayed the character 'a' on the screen, as if nothing was wrong. At least I expect something like "Segmentation Fault".

Please hold your thought and bear with me a moment to see the following code:

```<code>int main( void ) {
    int i;
    char **strPtr;
    char *string = "Hello, world!";

    *strPtr = string;

    printf( "%s", *strPtr );
    return 0;
}
</code>```

This time, I ran the code with GCC-4.8.5 which has successfully detected the segmentation fault in the first code. To my dismay, the string "Hello, world!" appeared on the screen after I ran the code as if nothing was wrong with it.

I wonder, since strPtr is also a pointer (though a pointer to pointer), by dereferencing and assigning value to strPtr, shouldn't I commit the same fault as I did in the first code?

答:
It doesn't support it; it's just that the compiler assumes that you know what you are doing.

It's just that the behaviour on dereferencing an unintialised pointer is undefined.

It appearing to work is a manifestation of that undefined behaviour.

Remember the old maxim: C gives you the ability to shoot yourself in the foot.

Body:
I am trying to understand what happened to my knowledge of C programming. Let's start with a CLASSICAL problem (dereferencing uninitialized pointer):

int main( void ) {
    char *p;
    *p = 'a';
    printf( "%c\n", *p );
    return 0;
}

This is obviously WRONG! I know it. However, when I ran this on my MacOS 10.12 with LLVM Clang 8.1.0 implemented as compiler, it not only failed to detect uninitialized pointer, but also displayed the character 'a' on the screen, as if nothing was wrong. At least I expect something like "Segmentation Fault".

Please hold your thought and bear with me a moment to see the following code:

int main( void ) {
    int i;
    char **strPtr;
    char *string = "Hello, world!";

    *strPtr = string;

    printf( "%s", *strPtr );
    return 0;
}

This time, I ran the code with GCC-4.8.5 which has successfully detected the segmentation fault in the first code. To my dismay, the string "Hello, world!" appeared on the screen after I ran the code as if nothing was wrong with it.

I wonder, since strPtr is also a pointer (though a pointer to pointer), by dereferencing and assigning value to strPtr, shouldn't I commit the same fault as I did in the first code?