问:
Efficient data/string reading and copy from file (CSV) c
I have read other posts regarding copying data from files. Let me show you why my case is different.
With C I must read 43 Million input lines from a csv file. The entries have no errors and are in this form:

```<code>int, int , int , variable length string with only alphanumerics and spaces , int \n
</code>```

Thing is I'm copying all data to memory in array and lists to do some very very simple averages on it and then outputting all processed data to a file, nothing fancy.
There are three main areas where I need help:

Regarding the string, (my BIGGEST problem is here) it is first read from the file, then is copied to an array and then passed to another functions which will copy it into dynamic memory only if a condition is met. Ex:

```<code>fileAnalizer(){
  while ( ! EOF ){
    char * s = function_to_read_string_from_file();
    data_to_array(s);
  }
  ....
  ....
  processData(arrays);
  dataToFiles(arrays);

}

void data_to_structures(char * s){
  if ( condition is met)
    char * aux = malloc((strlen(s)+1 )* sizeof(char));
    strcpy(aux,s);
  ....
  ...
}
</code>```

As you can see the string is traveled through 3 times. I'm needing a way to do this process more efficiently, traveling the string fewer times. I have tried reading char by char and counting the string length but the entire process becomes slower.

Efficient reading of input: would you recommend first copying all data into a buffer? If so: what type of buffer, and in many blocks or just one?
This is my current reading program:

```<code>void
csvReader(FILE* f){
    T_structCDT c;
    c.string = malloc(MAX_STRING_LENGHT*sizeof(char));
    while (fscanf(f,"%d,%d,%d,%[^,],%d\n",&c.a, &c.b, &c.vivienda, c.c, &c.d)==5 ){
        data_to_structures(c);
    }
}
</code>```

I then have nearly 500 hundred csv lines of processed data to dump in to other files. How would you recommend the dumping? Line by line or again sending the data to a buffer and then doing the dump? My code now looks something like this.

```<code>void dataToFiles(arrayOfStructs immenseAr1, arrayOfStructs immenseAr2){
  for (iteration over immenseAr1) {
      fprintf(f1, "%d,%d,%s\n", immenseAr1[i].a, immenseAr1[i].b, inmenseAr1[i].string);
  }
  for (iteration over immenseAr2) {
      fprintf(f2, "%d,%d,%s\n", inmenseAr2[i].a, inmenseAr2[i].b, inmenseAr2[i].string);
  }
}
</code>```

I must read all data before dumping it. Would you recommend a different method other than storing all data into memory and then analyzing it and then dumping all the analyzed data?
With the 20 Million lines the program is currently taking more than 40 seconds.
I really need to lower that time.

答:
Try scanning through your big file without storing it all to memory, just keeping one record at a time in a local variables:

```<code>void csvReader(FILE *f) {
    T_structCDT c;
    int count = 0;
    c.string = malloc(1000);
    while (fscanf(f, "%d,%d,%d,%999[^,],%d\n", &c.a, &c.b, &c.vivienda, c.c, &c.d) == 5) {
        // nothing for now
        count++;
    }
    printf("%d records parsed\n");
}
</code>```

Measure the time taken for this simplistic parser:

If it is quick enough, perform the tests for selection and output the few matching records one at a time at they are found during the parse phase. The extra time for these steps should be fairly small since only a few records match.

It the time is too long, you need a more fancy CSV parser, which is a lot of work but can be done and made fast, especially if you can assume your input file to use this simple format for all records.  This is too broad a subject to detail here but the speed achievable should be close to that of cat csvfile > /dev/null or grep a_short_string_not_present csvfile

On my system (average linux server with regular hard disk), it takes less than 20 seconds to parse 40 million lines totalling 2GB from a cold start, and less than 4 seconds the second time: disk I/O seems to be the bottleneck.

If you need to perform this selection very often, you should probably use a different data format, possibly a database system. If the scan is performed occasionally on data whose format is fixed, using faster storage such as SSD will help but don't expect miracles.

EDIT To put words in action, I wrote a simple generator and extractor:

Here is a simple program to generate CSV data:

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

const char *dict[] = {
    "Lorem", "ipsum", "dolor", "sit", "amet;", "consectetur", "adipiscing", "elit;",
    "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et",
    "dolore", "magna", "aliqua.", "Ut", "enim", "ad", "minim", "veniam;",
    "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "ut", "aliquip",
    "ex", "ea", "commodo", "consequat.", "Duis", "aute", "irure", "dolor",
    "in", "reprehenderit", "in", "voluptate", "velit", "esse", "cillum", "dolore",
    "eu", "fugiat", "nulla", "pariatur.", "Excepteur", "sint", "occaecat", "cupidatat",
    "non", "proident;", "sunt", "in", "culpa", "qui", "officia", "deserunt",
    "mollit", "anim", "id", "est", "laborum.",
};

int csvgen(const char *fmt, long lines) {
    char buf[1024];

    if (*fmt == '\0')
        return 1;

    while (lines > 0) {
        size_t pos = 0;
        int count = 0;
        for (const char *p = fmt; *p && pos < sizeof(buf); p++) {
            switch (*p) {
            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
                count = count * 10 + *p - '0';
                continue;
            case 'd':
                if (!count) count = 101;
                pos += snprintf(buf + pos, sizeof(buf) - pos, "%d",
                                rand() % (2 + count - 1) - count + 1);
                count = 0;
                continue;
            case 'u':
                if (!count) count = 101;
                pos += snprintf(buf + pos, sizeof(buf) - pos, "%u",
                                rand() % count);
                count = 0;
                continue;
            case 's':
                if (!count) count = 4;
                count = rand() % count + 1;
                while (count-- > 0 && pos < sizeof(buf)) {
                    pos += snprintf(buf + pos, sizeof(buf) - pos, "%s ",
                                    dict[rand() % (sizeof(dict) / sizeof(*dict))]);
                }
                if (pos < sizeof(buf)) {
                    pos--;
                }
                count = 0;
                continue;
            default:
                buf[pos++] = *p;
                count = 0;
                continue;
            }
        }
        if (pos < sizeof(buf)) {
            buf[pos++] = '\n';
            fwrite(buf, 1, pos, stdout);
            lines--;
        }
    }
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        fprintf(stderr, "usage: csvgen format number\n");
        return 2;
    }
    return csvgen(argv[1], strtol(argv[2], NULL, 0));
}
</code>```

Here is an extractor with 3 different parsing methods:

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

static inline unsigned int getuint(const char *p, const char **pp) {
    unsigned int d, n = 0;
    while ((d = *p - '0') <= 9) {
        n = n * 10 + d;
        p++;
    }
    *pp = p;
    return n;
}

int csvgrep(FILE *f, int method) {
    struct {
        int a, b, c, d;
        int spos, slen;
        char s[1000];
    } c;
    int count = 0, line = 0;

    // select 500 out of 43M
#define select(c)  ((c).a == 100 && (c).b == 100 && (c).c > 74 && (c).d > 50)

    if (method == 0) {
        // default method: fscanf
        while (fscanf(f, "%d,%d,%d,%999[^,],%d\n", &c.a, &c.b, &c.c, c.s, &c.d) == 5) {
            line++;
            if (select(c)) {
                count++;
                printf("%d,%d,%d,%s,%d\n", c.a, c.b, c.c, c.s, c.d);
            }
        }
    } else
    if (method == 1) {
        // use fgets and simple parser
        char buf[1024];
        while (fgets(buf, sizeof(buf), f)) {
            char *p = buf;
            int i;
            line++;
            c.a = strtol(p, &p, 10);
            p += (*p == ',');
            c.b = strtol(p, &p, 10);
            p += (*p == ',');
            c.c = strtol(p, &p, 10);
            p += (*p == ',');
            for (i = 0; *p && *p != ','; p++) {
                c.s[i++] = *p;
            }
            c.s[i] = '\0';
            p += (*p == ',');
            c.d = strtol(p, &p, 10);
            if (*p != '\n') {
                fprintf(stderr, "csvgrep: invalid format at line %d\n", line);
                continue;
            }
            if (select(c)) {
                count++;
                printf("%d,%d,%d,%s,%d\n", c.a, c.b, c.c, c.s, c.d);
            }
        }
    } else
    if (method == 2) {
        // use fgets and hand coded parser, positive numbers only, no string copy
        char buf[1024];
        while (fgets(buf, sizeof(buf), f)) {
            const char *p = buf;
            line++;
            c.a = getuint(p, &p);
            p += (*p == ',');
            c.b = getuint(p, &p);
            p += (*p == ',');
            c.c = getuint(p, &p);
            p += (*p == ',');
            c.spos = p - buf;
            while (*p && *p != ',') p++;
            c.slen = p - buf - c.spos;
            p += (*p == ',');
            c.d = getuint(p, &p);
            if (*p != '\n') {
                fprintf(stderr, "csvgrep: invalid format at line %d\n", line);
                continue;
            }
            if (select(c)) {
                count++;
                printf("%d,%d,%d,%.*s,%d\n", c.a, c.b, c.c, c.slen, buf + c.spos, c.d);
            }
        }
    } else {
        fprintf(stderr, "csvgrep: unknown method: %d\n", method);
        return 1;
    }
    fprintf(stderr, "csvgrep: %d records selected from %d lines\n", count, line);
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc > 2 && strtol(argv[2], NULL, 0)) {
        // non zero second argument -> set a 1M I/O buffer
        setvbuf(stdin, NULL, _IOFBF, 1024 * 1024);
    }
    return csvgrep(stdin, argc > 1 ? strtol(argv[1], NULL, 0) : 0);
}
</code>```

And here are some comparative benchmark figures:

```<code>$ time ./csvgen "u,u,u,s,u" 43000000 > 43m
real    0m34.428s    user    0m32.911s    sys     0m1.358s
$ time grep zz 43m
real    0m10.338s    user    0m10.069s    sys     0m0.211s
$ time wc -lc 43m
 43000000 1195458701 43m
real    0m1.043s     user    0m0.839s     sys     0m0.196s
$ time cat 43m > /dev/null
real    0m0.201s     user    0m0.004s     sys     0m0.195s
$ time ./csvgrep 0 < 43m > x0
csvgrep: 508 records selected from 43000000 lines
real    0m14.271s    user    0m13.856s    sys     0m0.341s
$ time ./csvgrep 1 < 43m > x1
csvgrep: 508 records selected from 43000000 lines
real    0m8.235s     user    0m7.856s     sys     0m0.331s
$ time ./csvgrep 2 < 43m > x2
csvgrep: 508 records selected from 43000000 lines
real    0m3.892s     user    0m3.555s     sys     0m0.312s
$ time ./csvgrep 2 1 < 43m > x3
csvgrep: 508 records selected from 43000000 lines
real    0m3.706s     user    0m3.488s     sys     0m0.203s
$ cmp x0 x1
$ cmp x0 x2
$ cmp x0 x3
</code>```

As you can see, specializing the parse method provides a gain of almost 50% and hand coding the integer conversion and string scanning gains another 50%. Using a 1 megabyte buffer instead of the default size offers only a marginal gain of 0.2sec.

To further improve the speed, you can use mmap() to bypass the I/O streaming interface and make stronger assumptions about the file contents.  In the above code, invalid formats are still handled gracefully, but you could remove some tests and shave an extra 5% from the execution time at the cost of reliability.

The above benchmark is performed on a system with an SSD drive and the file 43m fits in RAM, so the timings do not include much disk I/O latency. grep is surprisingly slow, and increasing the search string length makes it even worse... wc -lc set a target for scanning performance, a factor of 4, but cat seems out of reach.

Body:
I have read other posts regarding copying data from files. Let me show you why my case is different.
With C I must read 43 Million input lines from a csv file. The entries have no errors and are in this form:

int, int , int , variable length string with only alphanumerics and spaces , int \n

Thing is I'm copying all data to memory in array and lists to do some very very simple averages on it and then outputting all processed data to a file, nothing fancy.
There are three main areas where I need help:

Regarding the string, (my BIGGEST problem is here) it is first read from the file, then is copied to an array and then passed to another functions which will copy it into dynamic memory only if a condition is met. Ex:

fileAnalizer(){
  while ( ! EOF ){
    char * s = function_to_read_string_from_file();
    data_to_array(s);
  }
  ....
  ....
  processData(arrays);
  dataToFiles(arrays);

}

void data_to_structures(char * s){
  if ( condition is met)
    char * aux = malloc((strlen(s)+1 )* sizeof(char));
    strcpy(aux,s);
  ....
  ...
}

As you can see the string is traveled through 3 times. I'm needing a way to do this process more efficiently, traveling the string fewer times. I have tried reading char by char and counting the string length but the entire process becomes slower.

Efficient reading of input: would you recommend first copying all data into a buffer? If so: what type of buffer, and in many blocks or just one?
This is my current reading program:

void
csvReader(FILE* f){
    T_structCDT c;
    c.string = malloc(MAX_STRING_LENGHT*sizeof(char));
    while (fscanf(f,"%d,%d,%d,%[^,],%d\n",&c.a, &c.b, &c.vivienda, c.c, &c.d)==5 ){
        data_to_structures(c);
    }
}

I then have nearly 500 hundred csv lines of processed data to dump in to other files. How would you recommend the dumping? Line by line or again sending the data to a buffer and then doing the dump? My code now looks something like this.

void dataToFiles(arrayOfStructs immenseAr1, arrayOfStructs immenseAr2){
  for (iteration over immenseAr1) {
      fprintf(f1, "%d,%d,%s\n", immenseAr1[i].a, immenseAr1[i].b, inmenseAr1[i].string);
  }
  for (iteration over immenseAr2) {
      fprintf(f2, "%d,%d,%s\n", inmenseAr2[i].a, inmenseAr2[i].b, inmenseAr2[i].string);
  }
}

I must read all data before dumping it. Would you recommend a different method other than storing all data into memory and then analyzing it and then dumping all the analyzed data?
With the 20 Million lines the program is currently taking more than 40 seconds.
I really need to lower that time.

Body:
Try scanning through your big file without storing it all to memory, just keeping one record at a time in a local variables:

void csvReader(FILE *f) {
    T_structCDT c;
    int count = 0;
    c.string = malloc(1000);
    while (fscanf(f, "%d,%d,%d,%999[^,],%d\n", &c.a, &c.b, &c.vivienda, c.c, &c.d) == 5) {
        // nothing for now
        count++;
    }
    printf("%d records parsed\n");
}

Measure the time taken for this simplistic parser:

If it is quick enough, perform the tests for selection and output the few matching records one at a time at they are found during the parse phase. The extra time for these steps should be fairly small since only a few records match.

It the time is too long, you need a more fancy CSV parser, which is a lot of work but can be done and made fast, especially if you can assume your input file to use this simple format for all records.  This is too broad a subject to detail here but the speed achievable should be close to that of cat csvfile > /dev/null or grep a_short_string_not_present csvfile

On my system (average linux server with regular hard disk), it takes less than 20 seconds to parse 40 million lines totalling 2GB from a cold start, and less than 4 seconds the second time: disk I/O seems to be the bottleneck.

If you need to perform this selection very often, you should probably use a different data format, possibly a database system. If the scan is performed occasionally on data whose format is fixed, using faster storage such as SSD will help but don't expect miracles.

EDIT To put words in action, I wrote a simple generator and extractor:

Here is a simple program to generate CSV data:

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

const char *dict[] = {
    "Lorem", "ipsum", "dolor", "sit", "amet;", "consectetur", "adipiscing", "elit;",
    "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et",
    "dolore", "magna", "aliqua.", "Ut", "enim", "ad", "minim", "veniam;",
    "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "ut", "aliquip",
    "ex", "ea", "commodo", "consequat.", "Duis", "aute", "irure", "dolor",
    "in", "reprehenderit", "in", "voluptate", "velit", "esse", "cillum", "dolore",
    "eu", "fugiat", "nulla", "pariatur.", "Excepteur", "sint", "occaecat", "cupidatat",
    "non", "proident;", "sunt", "in", "culpa", "qui", "officia", "deserunt",
    "mollit", "anim", "id", "est", "laborum.",
};

int csvgen(const char *fmt, long lines) {
    char buf[1024];

    if (*fmt == '\0')
        return 1;

    while (lines > 0) {
        size_t pos = 0;
        int count = 0;
        for (const char *p = fmt; *p && pos < sizeof(buf); p++) {
            switch (*p) {
            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
                count = count * 10 + *p - '0';
                continue;
            case 'd':
                if (!count) count = 101;
                pos += snprintf(buf + pos, sizeof(buf) - pos, "%d",
                                rand() % (2 + count - 1) - count + 1);
                count = 0;
                continue;
            case 'u':
                if (!count) count = 101;
                pos += snprintf(buf + pos, sizeof(buf) - pos, "%u",
                                rand() % count);
                count = 0;
                continue;
            case 's':
                if (!count) count = 4;
                count = rand() % count + 1;
                while (count-- > 0 && pos < sizeof(buf)) {
                    pos += snprintf(buf + pos, sizeof(buf) - pos, "%s ",
                                    dict[rand() % (sizeof(dict) / sizeof(*dict))]);
                }
                if (pos < sizeof(buf)) {
                    pos--;
                }
                count = 0;
                continue;
            default:
                buf[pos++] = *p;
                count = 0;
                continue;
            }
        }
        if (pos < sizeof(buf)) {
            buf[pos++] = '\n';
            fwrite(buf, 1, pos, stdout);
            lines--;
        }
    }
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        fprintf(stderr, "usage: csvgen format number\n");
        return 2;
    }
    return csvgen(argv[1], strtol(argv[2], NULL, 0));
}

Here is an extractor with 3 different parsing methods:

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

static inline unsigned int getuint(const char *p, const char **pp) {
    unsigned int d, n = 0;
    while ((d = *p - '0') <= 9) {
        n = n * 10 + d;
        p++;
    }
    *pp = p;
    return n;
}

int csvgrep(FILE *f, int method) {
    struct {
        int a, b, c, d;
        int spos, slen;
        char s[1000];
    } c;
    int count = 0, line = 0;

    // select 500 out of 43M
#define select(c)  ((c).a == 100 && (c).b == 100 && (c).c > 74 && (c).d > 50)

    if (method == 0) {
        // default method: fscanf
        while (fscanf(f, "%d,%d,%d,%999[^,],%d\n", &c.a, &c.b, &c.c, c.s, &c.d) == 5) {
            line++;
            if (select(c)) {
                count++;
                printf("%d,%d,%d,%s,%d\n", c.a, c.b, c.c, c.s, c.d);
            }
        }
    } else
    if (method == 1) {
        // use fgets and simple parser
        char buf[1024];
        while (fgets(buf, sizeof(buf), f)) {
            char *p = buf;
            int i;
            line++;
            c.a = strtol(p, &p, 10);
            p += (*p == ',');
            c.b = strtol(p, &p, 10);
            p += (*p == ',');
            c.c = strtol(p, &p, 10);
            p += (*p == ',');
            for (i = 0; *p && *p != ','; p++) {
                c.s[i++] = *p;
            }
            c.s[i] = '\0';
            p += (*p == ',');
            c.d = strtol(p, &p, 10);
            if (*p != '\n') {
                fprintf(stderr, "csvgrep: invalid format at line %d\n", line);
                continue;
            }
            if (select(c)) {
                count++;
                printf("%d,%d,%d,%s,%d\n", c.a, c.b, c.c, c.s, c.d);
            }
        }
    } else
    if (method == 2) {
        // use fgets and hand coded parser, positive numbers only, no string copy
        char buf[1024];
        while (fgets(buf, sizeof(buf), f)) {
            const char *p = buf;
            line++;
            c.a = getuint(p, &p);
            p += (*p == ',');
            c.b = getuint(p, &p);
            p += (*p == ',');
            c.c = getuint(p, &p);
            p += (*p == ',');
            c.spos = p - buf;
            while (*p && *p != ',') p++;
            c.slen = p - buf - c.spos;
            p += (*p == ',');
            c.d = getuint(p, &p);
            if (*p != '\n') {
                fprintf(stderr, "csvgrep: invalid format at line %d\n", line);
                continue;
            }
            if (select(c)) {
                count++;
                printf("%d,%d,%d,%.*s,%d\n", c.a, c.b, c.c, c.slen, buf + c.spos, c.d);
            }
        }
    } else {
        fprintf(stderr, "csvgrep: unknown method: %d\n", method);
        return 1;
    }
    fprintf(stderr, "csvgrep: %d records selected from %d lines\n", count, line);
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc > 2 && strtol(argv[2], NULL, 0)) {
        // non zero second argument -> set a 1M I/O buffer
        setvbuf(stdin, NULL, _IOFBF, 1024 * 1024);
    }
    return csvgrep(stdin, argc > 1 ? strtol(argv[1], NULL, 0) : 0);
}

And here are some comparative benchmark figures:

$ time ./csvgen "u,u,u,s,u" 43000000 > 43m
real    0m34.428s    user    0m32.911s    sys     0m1.358s
$ time grep zz 43m
real    0m10.338s    user    0m10.069s    sys     0m0.211s
$ time wc -lc 43m
 43000000 1195458701 43m
real    0m1.043s     user    0m0.839s     sys     0m0.196s
$ time cat 43m > /dev/null
real    0m0.201s     user    0m0.004s     sys     0m0.195s
$ time ./csvgrep 0 < 43m > x0
csvgrep: 508 records selected from 43000000 lines
real    0m14.271s    user    0m13.856s    sys     0m0.341s
$ time ./csvgrep 1 < 43m > x1
csvgrep: 508 records selected from 43000000 lines
real    0m8.235s     user    0m7.856s     sys     0m0.331s
$ time ./csvgrep 2 < 43m > x2
csvgrep: 508 records selected from 43000000 lines
real    0m3.892s     user    0m3.555s     sys     0m0.312s
$ time ./csvgrep 2 1 < 43m > x3
csvgrep: 508 records selected from 43000000 lines
real    0m3.706s     user    0m3.488s     sys     0m0.203s
$ cmp x0 x1
$ cmp x0 x2
$ cmp x0 x3

As you can see, specializing the parse method provides a gain of almost 50% and hand coding the integer conversion and string scanning gains another 50%. Using a 1 megabyte buffer instead of the default size offers only a marginal gain of 0.2sec.

To further improve the speed, you can use mmap() to bypass the I/O streaming interface and make stronger assumptions about the file contents.  In the above code, invalid formats are still handled gracefully, but you could remove some tests and shave an extra 5% from the execution time at the cost of reliability.

The above benchmark is performed on a system with an SSD drive and the file 43m fits in RAM, so the timings do not include much disk I/O latency. grep is surprisingly slow, and increasing the search string length makes it even worse... wc -lc set a target for scanning performance, a factor of 4, but cat seems out of reach.


来源: stackexchange

问:
Disable bootstrap tab clicks
I am using bootsrap tabs for a  registration form ,
 I changed navigation of tabs using onclick event of next and previous button .
But still that tabs click works and being able to go the desired page easily Please help how can i stop tab click navigation i only want next previous button navigation
Please find the html code below</p>

```<code> <ul class="nav nav-tabs" id="myTab">
   <li class="active">
     <a href="#home" data-toggle="tab">1.PERSONAL DETAILS</a>
   </li>
   <li>
     <a href="#profile" data-toggle="tab"> 2. CONTACT DETAILS</a>
   </li>
   <li>
     <a href="#messages" data-toggle="tab">3. EDUCATION DETAILS</a>
   </li>
   <li>
     <a href="#course" data-toggle="tab">4. SELECT COURSE</a>
   </li>
   <li>
     <a href="#settings" data-toggle="tab">5. PAYMENT DETAILS</a>
   </li>
 </ul>
 <div class="tab-content">
    <div class="tab-pane active" id="home">Form elements </div>
    <div id="profile">Form elements </div>
    <div id="messages">Form elements </div>
    <div id="settings">Form elements </div>
 </div>
</code>```

答:
I, had this problem for a while.

Remove the data-toggle = ..

to do conditionnaly by javascript
Give tabs, Ids in the  tag
document.getElementById(tabId)[0].setAttribute("data-toggle", "");

ContentLicense: CC BY-SA 3.0

Title: Disable bootstrap tab clicks

Body:
I am using bootsrap tabs for a  registration form ,
 I changed navigation of tabs using onclick event of next and previous button .
But still that tabs click works and being able to go the desired page easily Please help how can i stop tab click navigation i only want next previous button navigation
Please find the html code below

     1.PERSONAL DETAILS

      2. CONTACT DETAILS

     3. EDUCATION DETAILS

     4. SELECT COURSE

     5. PAYMENT DETAILS

Form elements

Form elements

Form elements

Form elements


问:
How to get feature importance in xgboost?
I'm using xgboost to build a model, and try to find the importance of each feature using get_fscore(), but it returns {}

and my train code is:

```<code>dtrain = xgb.DMatrix(X, label=Y)
watchlist = [(dtrain, 'train')]
param = {'max_depth': 6, 'learning_rate': 0.03}
num_round = 200
bst = xgb.train(param, dtrain, num_round, watchlist)
</code>```

So is there any mistake in my train? How to get feature importance in xgboost?

答:
I don't know how to get values certainly, but there is a good way to plot features importance:</p>

```<code>model = xgb.train(params, d_train, 1000, watchlist)
fig, ax = plt.subplots(figsize=(12,18))
xgb.plot_importance(model, max_num_features=50, height=0.8, ax=ax)
plt.show()
</code>```

Body:
I'm using xgboost to build a model, and try to find the importance of each feature using get_fscore(), but it returns {}

and my train code is:

dtrain = xgb.DMatrix(X, label=Y)
watchlist = [(dtrain, 'train')]
param = {'max_depth': 6, 'learning_rate': 0.03}
num_round = 200
bst = xgb.train(param, dtrain, num_round, watchlist)

So is there any mistake in my train? How to get feature importance in xgboost?

Body:
I don't know how to get values certainly, but there is a good way to plot features importance:

model = xgb.train(params, d_train, 1000, watchlist)
fig, ax = plt.subplots(figsize=(12,18))
xgb.plot_importance(model, max_num_features=50, height=0.8, ax=ax)
plt.show()


问:
Char-array to int
I have an array char input[11] = {'0','2','7', '-','1','1','2', ,'0','0','9','5'};

How do I convert input[0,1,2] to int one = 27, input[3,4,5,6] to int two = -112 and input[7,8,9,10] to int three = 95?

thx, JNK

答:
As I understand your comment, you know that the first entry is 3 digits wide, the second and third are 4 digits wide:</p>

```<code>// not beautiful but should work:
char buffer[5];
int  one   = 0;
int  two   = 0;
int  three = 0;
// read ONE
memcpy(buffer, input, 3);
buffer[3] = '\0';
one = atoi(buffer);
// read TWO
input += 3;
memcpy(buffer, input, 4);
buffer[4] = '\0';
two = atoi(buffer);
// read THREE
input += 4;
memcpy(buffer, input, 4);
buffer[4] = '\0';
three = atoi(buffer);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Char-array to int

Body:
As I understand your comment, you know that the first entry is 3 digits wide, the second and third are 4 digits wide:

// not beautiful but should work:
char buffer[5];
int  one   = 0;
int  two   = 0;
int  three = 0;
// read ONE
memcpy(buffer, input, 3);
buffer[3] = '\0';
one = atoi(buffer);
// read TWO
input += 3;
memcpy(buffer, input, 4);
buffer[4] = '\0';
two = atoi(buffer);
// read THREE
input += 4;
memcpy(buffer, input, 4);
buffer[4] = '\0';
three = atoi(buffer);


问:
Is it possible that mutliproccessing causes stream lag?
I have a server that receives audio stream data from a client and then sends it to all other connected clients (via sockets). Since the data stream makes the code stuck on a loop , I decided that I should create processes for each stream (client essentially). I noticed that even with one connected client , the process makes the audio lag. Why is that ? That also happens if I try to use threads.

Code:

```<code>p_r = Process(target=playback_f,
              args=(pass_record, soc, client, port_a, data, c)).start()
</code>```

Where soc is the socket connection of the client in question, data is the initial data and c is the result of:

```<code>c, addr1 = s.accept()
</code>```

The process calls:

```<code>def playback_f(pass_record, soc, client, port_a, data, c):
    try:
        stop_recording = False
        try :
            soc.sendto('playback'.encode('utf-8'),(client,port_a))
        except Exception as e:
            print (e)

        while stop_recording == False:
            if data !=  b'stop_rec':
                try:
                    data = c.recv(1024)
                    soc.sendto(data,(client,port_a))
                except Exception as e:
                    print (e)
            else:
                stop_recording = True

        print('ended')

    except Exception as e:
        print(e)
</code>```

答: Ok , I solved it. Basically , the lag was the result of my main code running in loops trying to receive a message , while at the same time , my process was doing the same thing. The way to solve this way to change the code in a way that eliminates this server overload.</p>

Body:
I have a server that receives audio stream data from a client and then sends it to all other connected clients (via sockets). Since the data stream makes the code stuck on a loop , I decided that I should create processes for each stream (client essentially). I noticed that even with one connected client , the process makes the audio lag. Why is that ? That also happens if I try to use threads.

Code:

p_r = Process(target=playback_f,
              args=(pass_record, soc, client, port_a, data, c)).start()

Where soc is the socket connection of the client in question, data is the initial data and c is the result of:

c, addr1 = s.accept()

The process calls:

def playback_f(pass_record, soc, client, port_a, data, c):
    try:
        stop_recording = False
        try :
            soc.sendto('playback'.encode('utf-8'),(client,port_a))
        except Exception as e:
            print (e)

        while stop_recording == False:
            if data !=  b'stop_rec':
                try:
                    data = c.recv(1024)
                    soc.sendto(data,(client,port_a))
                except Exception as e:
                    print (e)
            else:
                stop_recording = True

        print('ended')

    except Exception as e:
        print(e)


问:
How to get Data in List in Ionic hybrid application
I am beginner in Ionic hybrid development.I want to parse data in List in my project.
I am using this webservice:http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt.
I want to show all dates in List.This is json Responce

{
    "earthquakes": [
        {
            "datetime": "2011-03-11 04:46:23",
            "depth": 24.4,
            "lng": 142.369,
            "src": "us",
            "eqid": "c0001xgp",
            "magnitude": 8.8,
            "lat": 38.322
        },
        {
            "datetime": "2012-04-11 06:38:37",
            "depth": 22.9,
            "lng": 93.0632,
            "src": "us",
            "eqid": "c000905e",
            "magnitude": 8.6,
            "lat": 2.311
        },
        {
            "datetime": "2007-09-12 09:10:26",
            "depth": 30,
            "lng": 101.3815,
            "src": "us",
            "eqid": "2007hear",
            "magnitude": 8.4,
            "lat": -4.5172
        }]}

Please suggest the tutorial or post some code its really help me.
Thanks in advance

答:
First, you need data provider earthquakes-provider.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class EarthquakesProvider {

  constructor(public _http: Http) {
    console.log('Hello Earthquakes Provider');
  }

  loadEarthquakes(){
    return this._http.get('http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt')
      .map(res => res.json());
  }

}
</code>```

Second, you need page that will display your JSON data for example in home.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EarthquakesProvider } from '../../providers/earthquakes-provider';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [EarthquakesProvider]
})
export class HomePage {

  public DateList: Array<Object>;

  constructor(public _navCtrl: NavController,
              public _earthquakes: EarthquakesProvider ) {

       this.getEarthquakes();

  }

  getEarthquakes(){
     this._earthquakes.loadEarthquakes().subscribe(res => {
     this.DateList = res.earthquakes;
     console.log(res.earthquakes);
    });
  }

}
</code>```

And finally home.html

```<code><ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Show dates in List</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="content-background">

<ion-list>
  <button ion-item *ngFor="let item of DateList">
    {{ item.datetime }}
  </button>
</ion-list>

</ion-content>
</code>```

P.S. You can use MomentJS to parse, validate, manipulate, and display dates and times

Body:
First, you need data provider earthquakes-provider.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class EarthquakesProvider {

  constructor(public _http: Http) {
    console.log('Hello Earthquakes Provider');
  }

  loadEarthquakes(){
    return this._http.get('http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt')
      .map(res => res.json());
  }

}

Second, you need page that will display your JSON data for example in home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EarthquakesProvider } from '../../providers/earthquakes-provider';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [EarthquakesProvider]
})
export class HomePage {

  public DateList: Array<Object>;

  constructor(public _navCtrl: NavController,
              public _earthquakes: EarthquakesProvider ) {

       this.getEarthquakes();

  }

  getEarthquakes(){
     this._earthquakes.loadEarthquakes().subscribe(res => {
     this.DateList = res.earthquakes;
     console.log(res.earthquakes);
    });
  }

}

And finally home.html

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Show dates in List</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="content-background">

<ion-list>
  <button ion-item *ngFor="let item of DateList">
    {{ item.datetime }}
  </button>
</ion-list>

</ion-content>

P.S. You can use MomentJS to parse, validate, manipulate, and display dates and times


问:
DJANGO REST API ---Javascript function not generating right PK
Working on Django REST API in which a dog is shown to a user based on preferences (age, gender, size).  A user can either like or dislike a dog.  They are then shown the next dog (assuming they haven't seen it yet) based on their set preferences.

The app is showing user the first dog (based on preferences-UserPref model), but when they go to click either like or dislike it is not moving to the next dog and generating a Not Found error like this:

Not Found: /api/dog/undefined/disliked/next

where the undefined should be the PK for the next dog

Therefore either my python logic is not generating the right PK (as noted by 'undefined' in the error code) or for some reason the javascript code is not getting the right formatted number for the PK.  Just not sure what the issue might be.

Here are my models:

```<code>class Dog(models.Model):
    name = models.CharField(max_length=255)
    image_filename = models.CharField(max_length=255, default='')
    breed = models.CharField(max_length=255, default='Unknown Breed')
    age = models.IntegerField()
    gender = models.CharField(choices=GENDER, max_length=1)
    size = models.CharField(choices=SIZE, max_length=2)

    @property
    def get_image_url(self):
        return self.image_filename.name

    def __str__(self):
        return self.name

class UserDog(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    dog = models.ForeignKey(Dog, on_delete=models.CASCADE)
    status = models.CharField(choices=STATUS, max_length=2)

    class Meta:
        unique_together = ('user', 'dog')

    def __str__(self):
        return '{} {} {}'.format(self.user, self.dog, self.get_status_display())

class UserPref(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    age = models.CharField(max_length=7, default='b,y,a,s')
    gender = models.CharField(max_length=3, default='m,f')
    size = models.CharField(max_length=8, default='s,m,l,xl')

    def __str__(self):
        return '{} preferences'.format(self.user)
</code>```

And View corresponding to the Dog Selection for Next

```<code>AGES = {
    'b': list(range(0, 6)),
    'y': list(range(6, 18)),
    'a': list(range(18, 72)),
    's': list(range(72, 192))
}

def get_ages(keys='b,y,a,s'):
    """Returns age ranges in years."""
    data = []
    for key in keys.split(','):
        data.extend(AGES[key])
    return data

class DogFilterView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = serializers.DogSerializer

    def get_ids(self, queryset=None):
        if queryset is not None:
            return [userdog.dog.pk for userdog in queryset]
        return []

    def filter_pref(self, dog_filter, user_prefs):
        userdog_query = models.UserDog.objects.filter(user=user_prefs.user.pk
                                                      ).select_related('dog')
        ages = get_ages(user_prefs.age)
        queryset = models.Dog.objects.filter(
            gender__in = user_prefs.gender.split(','),
            size__in = user_prefs.size.split(','),
            age__in = ages
        )
        if dog_filter not in STATUSES:
            dogs = self.get_ids(userdog_query)
            queryset = queryset.exclude(pk__in=dogs)
        else:
            userdog_query = userdog_query.filter(status=dog_filter[0])
            dogs = self.get_ids(userdog_query)
            queryset = queryset.filter(pk__in=dogs)

        return queryset.order_by('pk')

    def get_queryset(self):
        user = self.request.user
        dog_filter = self.kwargs.get('dog_filter')
        # Get user preferences
        user_prefs = get_object_or_404(models.UserPref, user=user)
        # Get age ranges(months) based on user preference selections
        queryset = self.filter_pref(dog_filter, user_prefs)
        return queryset

    def get_object(self):
        pk = int(self.kwargs.get('pk'))
        # Filter the query for the NEXT dog by pk.
        queryset = self.get_queryset().filter(
            pk__gt=pk
        )
        obj = queryset.first()
        if not obj:
            raise Http404
        return obj
</code>```

And then my REGEX:

```<code>url(r'^api/dog/(?P<pk>-?\d+)/(?P<dog_filter>liked|disliked|undecided)/next/$',
        DogFilterView.as_view(),
        name='dog-filter-detail'),
</code>```

my Serializer for Dog Class:

```<code>class DogSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'name',
            'image_filename',
            'breed',
            'age',
            'gender',
            'size'
        )
        model = models.Dog
</code>```

Also note there is a part of Javascript that I didn't write here that i thought maybe was something to examine but not sure---this is the function that gets next dog:

```<code>getNext: function () {
    this.serverRequest = $.ajax({
      url: `api/dog/${ this.state.details ? this.state.details.id : -1 }/${ this.state.filter }/next/`,
      method: "GET",
      dataType: "json",
      headers: TokenAuth.getAuthHeader()
    }).done(function (data) {
      this.setState({ details: data, message: undefined });
    }.bind(this)).fail(function (response) {
      var message = null;
      if (response.status == 404) {
        if (this.state.filter == "undecided") {
          message = "No dogs matched your preferences.";
        } else {
          message = `You don't have any ${ this.state.filter } dogs.`;
        }
      } else {
        message = response.error;
      }
      this.setState({ message: message, details: undefined });
    }.bind(this));
</code>```

答: So after hours of endlessly looking at this, i figured it out.  I was not passing the 'id' field to the DogSerializer, thus, the pk was not being passed.  Wow, thank god for that.</p>

Body:
Working on Django REST API in which a dog is shown to a user based on preferences (age, gender, size).  A user can either like or dislike a dog.  They are then shown the next dog (assuming they haven't seen it yet) based on their set preferences.

The app is showing user the first dog (based on preferences-UserPref model), but when they go to click either like or dislike it is not moving to the next dog and generating a Not Found error like this:

Not Found: /api/dog/undefined/disliked/next

where the undefined should be the PK for the next dog

Therefore either my python logic is not generating the right PK (as noted by 'undefined' in the error code) or for some reason the javascript code is not getting the right formatted number for the PK.  Just not sure what the issue might be.

Here are my models:

class Dog(models.Model):
    name = models.CharField(max_length=255)
    image_filename = models.CharField(max_length=255, default='')
    breed = models.CharField(max_length=255, default='Unknown Breed')
    age = models.IntegerField()
    gender = models.CharField(choices=GENDER, max_length=1)
    size = models.CharField(choices=SIZE, max_length=2)

    @property
    def get_image_url(self):
        return self.image_filename.name

    def __str__(self):
        return self.name

class UserDog(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    dog = models.ForeignKey(Dog, on_delete=models.CASCADE)
    status = models.CharField(choices=STATUS, max_length=2)

    class Meta:
        unique_together = ('user', 'dog')

    def __str__(self):
        return '{} {} {}'.format(self.user, self.dog, self.get_status_display())

class UserPref(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    age = models.CharField(max_length=7, default='b,y,a,s')
    gender = models.CharField(max_length=3, default='m,f')
    size = models.CharField(max_length=8, default='s,m,l,xl')

    def __str__(self):
        return '{} preferences'.format(self.user)

And View corresponding to the Dog Selection for Next

AGES = {
    'b': list(range(0, 6)),
    'y': list(range(6, 18)),
    'a': list(range(18, 72)),
    's': list(range(72, 192))
}

def get_ages(keys='b,y,a,s'):
    """Returns age ranges in years."""
    data = []
    for key in keys.split(','):
        data.extend(AGES[key])
    return data

class DogFilterView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = serializers.DogSerializer

    def get_ids(self, queryset=None):
        if queryset is not None:
            return [userdog.dog.pk for userdog in queryset]
        return []

    def filter_pref(self, dog_filter, user_prefs):
        userdog_query = models.UserDog.objects.filter(user=user_prefs.user.pk
                                                      ).select_related('dog')
        ages = get_ages(user_prefs.age)
        queryset = models.Dog.objects.filter(
            gender__in = user_prefs.gender.split(','),
            size__in = user_prefs.size.split(','),
            age__in = ages
        )
        if dog_filter not in STATUSES:
            dogs = self.get_ids(userdog_query)
            queryset = queryset.exclude(pk__in=dogs)
        else:
            userdog_query = userdog_query.filter(status=dog_filter[0])
            dogs = self.get_ids(userdog_query)
            queryset = queryset.filter(pk__in=dogs)

        return queryset.order_by('pk')

    def get_queryset(self):
        user = self.request.user
        dog_filter = self.kwargs.get('dog_filter')
        # Get user preferences
        user_prefs = get_object_or_404(models.UserPref, user=user)
        # Get age ranges(months) based on user preference selections
        queryset = self.filter_pref(dog_filter, user_prefs)
        return queryset

    def get_object(self):
        pk = int(self.kwargs.get('pk'))
        # Filter the query for the NEXT dog by pk.
        queryset = self.get_queryset().filter(
            pk__gt=pk
        )
        obj = queryset.first()
        if not obj:
            raise Http404
        return obj

And then my REGEX:

url(r'^api/dog/(?P<pk>-?\d+)/(?P<dog_filter>liked|disliked|undecided)/next/$',
        DogFilterView.as_view(),
        name='dog-filter-detail'),

my Serializer for Dog Class:

class DogSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'name',
            'image_filename',
            'breed',
            'age',
            'gender',
            'size'
        )
        model = models.Dog

Also note there is a part of Javascript that I didn't write here that i thought maybe was something to examine but not sure---this is the function that gets next dog:

getNext: function () {
    this.serverRequest = $.ajax({
      url: `api/dog/${ this.state.details ? this.state.details.id : -1 }/${ this.state.filter }/next/`,
      method: "GET",
      dataType: "json",
      headers: TokenAuth.getAuthHeader()
    }).done(function (data) {
      this.setState({ details: data, message: undefined });
    }.bind(this)).fail(function (response) {
      var message = null;
      if (response.status == 404) {
        if (this.state.filter == "undecided") {
          message = "No dogs matched your preferences.";
        } else {
          message = `You don't have any ${ this.state.filter } dogs.`;
        }
      } else {
        message = response.error;
      }
      this.setState({ message: message, details: undefined });
    }.bind(this));


问:
Rails - modify text of %p with dynamic variable
I have a basic form that, when submitted, triggers a Create request to an external API. On submit, a stage value with progress bar appears instead of the Submit button. The creation process takes time on the external API, so I had to run a couple of Show requests each second using while status == 'inactive' and stop when the Show request response has status: 'active'.
Every Show request response also contains a 'stage' attribute which shows the stage of the creation process (Connecting, Creating, Fetching, Finishing etc.). With every request, the current stage is stored in the @stage variable, which can be accessed with ApiRequest.stage. Every API related stuff is in a service file.

My coffeescript that changes the Submit button with the stage+progress bar:

```<code>$('#new_connection').on 'submit', ->
    button = $('#submit_button')
    progress = $('.loading')
    button.fadeOut 500
    setTimeout (->
      if button.is(':hidden')
        progress.fadeIn 500
      return
    ), 509
    return
</code>```

And the stage+progress bar partial:

```<code>.loading
  %p.center-align#stage <!-- This should display the stage in real time -->
  .progress <!-- This is a materializecss progress bar -->
    .indeterminate
</code>```

How can I update the text inside #stage with ApiRequest.status every time the value changes in real-time staying on the same page, from the moment the form is submitted until the end (it will redirect to create.html when all the stuff in the background is done anyway)?

答:
Ok so all you do is create a method in the controller that reads the variable: @stage = your method here.

Write a respond_to do |format| with format.json { render json: { stage: @stage } }.

Now you have to create a route for this custom controller method: get '/your/link', to: 'controller#custom_method', as: 'stage'.

All that is left is to trigger this method through Ajax:

```<code>$.get({
  url: "your/link.json",
  success: function(data) {
    $('#your_paragraph_id').text(data['stage]);
    },
});
</code>```

You can put this Ajax call in a setInterval function.

Body:
I have a basic form that, when submitted, triggers a Create request to an external API. On submit, a stage value with progress bar appears instead of the Submit button. The creation process takes time on the external API, so I had to run a couple of Show requests each second using while status == 'inactive' and stop when the Show request response has status: 'active'.
Every Show request response also contains a 'stage' attribute which shows the stage of the creation process (Connecting, Creating, Fetching, Finishing etc.). With every request, the current stage is stored in the @stage variable, which can be accessed with ApiRequest.stage. Every API related stuff is in a service file.

My coffeescript that changes the Submit button with the stage+progress bar:

$('#new_connection').on 'submit', ->
    button = $('#submit_button')
    progress = $('.loading')
    button.fadeOut 500
    setTimeout (->
      if button.is(':hidden')
        progress.fadeIn 500
      return
    ), 509
    return

And the stage+progress bar partial:

.loading
  %p.center-align#stage
  .progress
    .indeterminate

How can I update the text inside #stage with ApiRequest.status every time the value changes in real-time staying on the same page, from the moment the form is submitted until the end (it will redirect to create.html when all the stuff in the background is done anyway)?

Body:
Ok so all you do is create a method in the controller that reads the variable: @stage = your method here.

Write a respond_to do |format| with format.json { render json: { stage: @stage } }.

Now you have to create a route for this custom controller method: get '/your/link', to: 'controller#custom_method', as: 'stage'.

All that is left is to trigger this method through Ajax:

$.get({
  url: "your/link.json",
  success: function(data) {
    $('#your_paragraph_id').text(data['stage]);
    },
});

You can put this Ajax call in a setInterval function.


问:
SQL- How to combine rows?
I have about a dozen or so devices I need to search on, and some of them have a variant. For example, if I do a GROUP BY device, it looks something like this:

```<code>Device Amount
X1     10
X2     2
X2-A   6
X3     9
X3-A   3
X4     8
X5     11
etc...
</code>```

Personally, I don't care about the variants, so after I search I have to go into Excel and manually add the rows for X2 and X2A. Is there a way to combine them in my search query?

答:
if the variants begin with '-', We will remove the text to the right of '-'

PostgreSQL

```<code>SELECT SUBSTRING(Device FROM  1, (LENGTH(Device)-POSITION('-' IN Device))) AS DeviceSub, sum(Amount)
FROM t
GROUP BY DeviceSub;
</code>```

Oracle

```<code>SELECT SUBSTR(Device, INSTR(Device, '-', 1), (LENGTH(Device)-INSTR(Device, '-', 1))) AS DeviceSub, sum(Amount)
    FROM t
    GROUP BY DeviceSub;
</code>```

Title: SQL- How to combine rows?

Body:
I have about a dozen or so devices I need to search on, and some of them have a variant. For example, if I do a GROUP BY device, it looks something like this:

Device Amount
X1     10
X2     2
X2-A   6
X3     9
X3-A   3
X4     8
X5     11
etc...

Personally, I don't care about the variants, so after I search I have to go into Excel and manually add the rows for X2 and X2A. Is there a way to combine them in my search query?

Body:
if the variants begin with '-', We will remove the text to the right of '-'

PostgreSQL

SELECT SUBSTRING(Device FROM  1, (LENGTH(Device)-POSITION('-' IN Device))) AS DeviceSub, sum(Amount)
FROM t
GROUP BY DeviceSub;

Oracle

SELECT SUBSTR(Device, INSTR(Device, '-', 1), (LENGTH(Device)-INSTR(Device, '-', 1))) AS DeviceSub, sum(Amount)
    FROM t
    GROUP BY DeviceSub;


问:
Finding the path to a pdf-viewer
I am only given the name of some pdf-viewer.

1) I want to check, if this pdf-viewer exists.

2) If this pdf-viewer exists, I want to find the path to it.

I am not sure how I have to approach.

答:
If you are in Linux, you can use terminal commands. If the PDF viewer has a command-line tool you could do something simple like so:

```<code>import subprocess
check = subprocess.check_output(['which', 'ls'])
print check
</code>```

Otherwise, you could run an OS independent walk and search filenames like so:

```<code>import os

matches = []
for root, dirs, files in os.walk(os.path.join('path', 'to', 'search'):
    for file in files:
        if 'pdf-viewer' in file.lower():
            filepath = os.path.join(root, file)
            matches.append(filepath)

print matches
</code>```

This will walk all the directories starting at '/path/to/search' on Mac/Linux, or \path\to\search on PC. It will search all filenames within each directory for a match, ignoring case in this example. If a match is found, it will recreate the absolute path of the current directory and matched filename, and append it to your matches list. Then you can do what you want with the list of matches.

There's lots of info on how to use the os.Walk() function, but if you are on Python 2.7 I would recommend installing ScanDir, which is much faster (default for Python 3).

Title: Finding the path to a pdf-viewer

Body:
If you are in Linux, you can use terminal commands. If the PDF viewer has a command-line tool you could do something simple like so:

import subprocess
check = subprocess.check_output(['which', 'ls'])
print check

Otherwise, you could run an OS independent walk and search filenames like so:

import os

matches = []
for root, dirs, files in os.walk(os.path.join('path', 'to', 'search'):
    for file in files:
        if 'pdf-viewer' in file.lower():
            filepath = os.path.join(root, file)
            matches.append(filepath)

print matches

This will walk all the directories starting at '/path/to/search' on Mac/Linux, or \path\to\search on PC. It will search all filenames within each directory for a match, ignoring case in this example. If a match is found, it will recreate the absolute path of the current directory and matched filename, and append it to your matches list. Then you can do what you want with the list of matches.

There's lots of info on how to use the os.Walk() function, but if you are on Python 2.7 I would recommend installing ScanDir, which is much faster (default for Python 3).


问:
How to set a background for whole application in Android?
In my application I have a lot of layers and instead of setting a background image to each of them, I want to set a background once and for all. How can I do that? </p>

答:
Add android:windowBackground to your theme:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@color/colorPrimaryDark</item>
</style>
</code>```

And of course make sure your manifest uses the theme for you application:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest package="com.package.name"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>
</code>```

Body:
Add android:windowBackground to your theme:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@color/colorPrimaryDark</item>
</style>

And of course make sure your manifest uses the theme for you application:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.package.name"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>


问:
Search in all files in a project in Sublime Text 3
Is there a way to search for a string in all files inside a project in Sublime Text 3? The string is not a method.</p>

答: Here's the easiest way : File -> Find in files


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
I would use something like this:</p>

```<code>// the username
$username = "foo";

// find all users like foo%
$q = mysql_query("SELECT * FROM users WHERE username LIKE '".$username."%' ORDER BY id DESC");

// no users
if (mysql_num_rows($q) == 0) {
    // create $username
}
else {

    $last_num = 0;

    // find all foo users
    while ($row = mysql_fetch_array($q)) {

        // match foo + number
        if (preg_match("/^".preg_quote($username)."+([0-9]+)$/i", $row['username'], $match)) {

            // extract the number part
            $num = (int) $match[1];

            // set the highest number
            if ($num > $last_num) $last_num = $num;
        }
    }

    // append the highest number to the username
    if ($last_num > 0) $username .= $last_num + 1;

    // create $username
}
</code>```

Body:
I would use something like this:

// the username
$username = "foo";

// find all users like foo%
$q = mysql_query("SELECT * FROM users WHERE username LIKE '".$username."%' ORDER BY id DESC");

// no users
if (mysql_num_rows($q) == 0) {
    // create $username
}
else {

    $last_num = 0;

    // find all foo users
    while ($row = mysql_fetch_array($q)) {

        // match foo + number
        if (preg_match("/^".preg_quote($username)."+([0-9]+)$/i", $row['username'], $match)) {

            // extract the number part
            $num = (int) $match[1];

            // set the highest number
            if ($num > $last_num) $last_num = $num;
        }
    }

    // append the highest number to the username
    if ($last_num > 0) $username .= $last_num + 1;

    // create $username
}


问:
Spearman's Correlation Test: "Object not Found"
I have been using R for quite some time, and have used it to do all of the stats for my Master's thesis. I have one more thing to do before I am done with my thesis, and I cannot figure out why R is giving me this code.

I am trying to run a Spearman's correlation test, and have attached a CSV file into RStudio. Here is the code I have entered, and the error that R gives me:

```<code>littersize=read.csv(file.choose())
littersize
cor.test(littersize, progesterone, method = "spearman")
</code>```

Error in cor.test.default(littersize, progesterone, method =
  "spearman") :    object 'progesterone' not found

I have gotten this code before, and have been able to fix it without much issue, but for some reason it is just not working. I have checked spelling, I've checked the CSV file for errors, I have done everything I can think of. Can anyone help me figure out what R wants me to do??? Thanks!

答:
Based on the code above (and complete lack of any data)it is hard to say.

However, you have not attached an object littersize into your rStudio work space.

You have loaded a data frame in your working environment assigning it the name littersize.

If you use

search()

you will see a list of everything you have attached; libraries, tools, your GlobalEnv...if "littersize" is not in there it is not attached.

This means that you cannot address columns in it directly.

So if progesterone is a column, of littersize then you must use one of the accepted method for doing so:

littersize$progesterone

or

with(littersize, cor.test(progesterone, x, method="spearman"))

Here progesterone and x are the two fields you are looking to test for correlations, both of which should be in data frame littersize if you intend to address it this way. And it is not clear if you have two separate fields to compare in your code (is one named littersize and one progesterone, both in the object littersize or did you load progesterone separately and not say or are you correlating one variable?).

If they are in different frames you must expressly call them with:

cor.test(littersize$progesterone, otherframe$x, method="spearman")

Or attach both objects and verify with search() and use the field names directly

If in fact the file is littersize and one of the columns is also littersize, then using attached addressing could become problematic, because you will have two objects of the same name attached, the frame and the column...in which case you should expressly ask for the columns with $.

littersize$littersize

Or you could rename the attached file and you will need to detach littersize because changes to an attached object do not occur while it is attached.You would simply be adding a second copy with a new name, with the original with the original name still lingering causing problems.

detach(littersize)

In general, it is best NOT to attach files, to instead use a data frame with appropriate data frame addressing. And if you can, create naming paradigms which help avoid issues if there is redundancy, like:

data frame names always start with a capital Littersize

field/column/variable names are lower-case and dotted or underscored:
litter_size or littersize or litter.size

objects in the environment always use camelCase: litterSize

If you are consistent about how you choose and use names, then you can have redundancy in an attached object and work through it, but it is probably still better to use a data frame and avoid the issues completely.

Body:
I have been using R for quite some time, and have used it to do all of the stats for my Master's thesis. I have one more thing to do before I am done with my thesis, and I cannot figure out why R is giving me this code.

I am trying to run a Spearman's correlation test, and have attached a CSV file into RStudio. Here is the code I have entered, and the error that R gives me:

littersize=read.csv(file.choose())
littersize
cor.test(littersize, progesterone, method = "spearman")

Error in cor.test.default(littersize, progesterone, method =
  "spearman") :    object 'progesterone' not found

I have gotten this code before, and have been able to fix it without much issue, but for some reason it is just not working. I have checked spelling, I've checked the CSV file for errors, I have done everything I can think of. Can anyone help me figure out what R wants me to do??? Thanks!


问:
How to display array of objects php in angular js table?
I am getting started with Angular and PHP. I have a JSON array, this send the PHP file to AngularJS function through $http call, but i cant get JSON array values in function js.

the json result with console log is:

php function:

```<code>foreach ($result as $row) {
   $out[] = $row;
}

echo json_encode($out);
</code>```

js:

```<code>app.controller('controllerJs', ['$scope', '$http', function($scope,$http){
$scope.clients = [];

$scope.All = function(){
   $http.get('/App/getAll.php')
           .then(function(data){
              $scope.clients = data;
           });
}

}]);
</code>```

php table:

```<code> <tbody>
    <tr ng-repeat="item in clients">
      <td>{{item.nombre}}</td>
      <td>{{item.especialidad}}</td>
    </tr>
 </tbody>
</code>```

答:
You should access the data property of the response,

```<code>$scope.All = function(){
   $http.get('/App/getAll.php')
           .then(function(data){
       $scope.clients = data.data;
   });
}
</code>```

Body:
I am getting started with Angular and PHP. I have a JSON array, this send the PHP file to AngularJS function through $http call, but i cant get JSON array values in function js.

the json result with console log is:

php function:

foreach ($result as $row) {
   $out[] = $row;
}

echo json_encode($out);

js:

app.controller('controllerJs', ['$scope', '$http', function($scope,$http){
$scope.clients = [];

$scope.All = function(){
   $http.get('/App/getAll.php')
           .then(function(data){
              $scope.clients = data;
           });
}

}]);

php table:

      {{item.nombre}}
      {{item.especialidad}}

Body:
You should access the data property of the response,

$scope.All = function(){
   $http.get('/App/getAll.php')
           .then(function(data){
       $scope.clients = data.data;
   });
}


问:
gulp-uglify events.js unhandled 'error' event
I'm getting this error. Running gulp yesterday worked perfectly fine, but this morning (changed NO code) and I'm getting this error.

```<code>$ gulp
[08:54:10] Using gulpfile C:\Source\Source2\bunny-meadows\gulpfile.js
[08:54:10] Starting 'scripts'...
[08:54:10] 'scripts' errored after 11 ms
[08:54:10] TypeError: listener must be a function
    at TypeError (<anonymous>)
    at DestroyableTransform.addListener (events.js:130:11)
    at DestroyableTransform.Readable.on (C:\Source\Source2\bunny-meadows\node_mo
dules\gulp-uglify\node_modules\through2\node_modules\readable-stream\lib\_stream
_readable.js:729:33)
    at Gulp.<anonymous> (C:\Source\Source2\bunny-meadows\gulpfile.js:37:10)
    at module.exports (C:\Source\Source2\bunny-meadows\node_modules\gulp\node_mo
dules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:\Source\Source2\bunny-meadows\node_modules\
gulp\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (C:\Source\Source2\bunny-meadows\node_modules\
gulp\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (C:\Source\Source2\bunny-meadows\node_modules\gul
p\node_modules\orchestrator\index.js:134:8)
    at c:\Users\hschillig.SCDL\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js
:129:20
    at process._tickCallback (node.js:419:13)

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error
    at new JS_Parse_Error (C:\Source\Source2\bunny-meadows\node_modules\gulp-ugl
ify\node_modules\uglify-js\lib\parse.js:196:18)
    at js_error (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_m
odules\uglify-js\lib\parse.js:204:11)
    at croak (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_modu
les\uglify-js\lib\parse.js:675:9)
    at token_error (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\nod
e_modules\uglify-js\lib\parse.js:683:9)
    at expect_token (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:696:9)
    at expect (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_mod
ules\uglify-js\lib\parse.js:699:36)
    at function_ (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:959:9)
    at expr_atom (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:1188:24)
    at maybe_unary (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\nod
e_modules\uglify-js\lib\parse.js:1358:19)
    at expr_ops (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_m
odules\uglify-js\lib\parse.js:1393:24)
    at maybe_conditional (C:\Source\Source2\bunny-meadows\node_modules\gulp-ugli
fy\node_modules\uglify-js\lib\parse.js:1398:20)
    at maybe_assign (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:1422:20)
</code>```

My gulpfile.js looks like this:

```<code>var gulp = require('gulp');

// Include Our Plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var livereload = require('gulp-livereload');

var paths = {
    // using framework version of jquery
    scripts: [
        'public/assets/js/jquery.min.js',
        'public/assets/plugins/mustachejs/mustache.js',
        'public/assets/js/modernizr.js',
        'public/assets/js/bootstrap.min.js',
        'public/assets/js/placeholders.min.js',
        'public/assets/plugins/bootstrap-wysiwyg/bootstrap3-wysihtml5.all.min.js',
        'public/assets/plugins/bootstrap-wysiwyg/bootstrap3-wysihtml5.min.js',
        'public/assets/plugins/responsiveslides/responsiveslides.min.js',
        'public/assets/plugins/bxslider/jquery.bxslider.min.js',
        'public/assets/plugins/magnific-popup/magnific-popup.js',
        'public/assets/js/jquery.autocomplete.min.js',
        'public/assets/js/plugins/additems.js',
        'public/assets/js/plugins/farm/farm.js',
        'public/assets/js/plugins/plusminus.js',
        'public/assets/js/core.js'
    ]
};

// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src(paths.scripts)
        .pipe(concat('all.js'))
        .pipe(gulp.dest('public/assets/js'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .on('error')
        .pipe(gulp.dest('public/assets/js'))
        .pipe(livereload());
});

// Watch Files For Changes
gulp.task('watch', function() {
    livereload.listen();
    gulp.watch(paths.scripts, ['scripts']);
});

// Default Task
gulp.task('default', ['scripts', 'watch']);
</code>```

Again I didn't change anything so I don't get why all of a sudden this morning it doesn't want to work.

答:
The best way to understand errors in a Gulp pipeline is to use a helper module, such as pump. As explained in the Gulp documentation Why Use Pump? you can get the correct errors by wrapping your pipeline.

```<code>gulp.task('scripts', function(cb) {
    pump([
        gulp.src(paths.scripts),
        concat('all.js'),
        gulp.dest('public/assets/js'),
        rename('all.min.js'),
        uglify(),
        gulp.dest('public/assets/js'),
        livereload()
    ], cb);
});
</code>```

Attaching an error handler to the UglifyJS part of the pipeline won't tell you about errors in the others, and it won't properly signal an error to Gulp's task running system.

Body:
I'm getting this error. Running gulp yesterday worked perfectly fine, but this morning (changed NO code) and I'm getting this error.

$ gulp
[08:54:10] Using gulpfile C:\Source\Source2\bunny-meadows\gulpfile.js
[08:54:10] Starting 'scripts'...
[08:54:10] 'scripts' errored after 11 ms
[08:54:10] TypeError: listener must be a function
    at TypeError (<anonymous>)
    at DestroyableTransform.addListener (events.js:130:11)
    at DestroyableTransform.Readable.on (C:\Source\Source2\bunny-meadows\node_mo
dules\gulp-uglify\node_modules\through2\node_modules\readable-stream\lib\_stream
_readable.js:729:33)
    at Gulp.<anonymous> (C:\Source\Source2\bunny-meadows\gulpfile.js:37:10)
    at module.exports (C:\Source\Source2\bunny-meadows\node_modules\gulp\node_mo
dules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:\Source\Source2\bunny-meadows\node_modules\
gulp\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (C:\Source\Source2\bunny-meadows\node_modules\
gulp\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (C:\Source\Source2\bunny-meadows\node_modules\gul
p\node_modules\orchestrator\index.js:134:8)
    at c:\Users\hschillig.SCDL\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js
:129:20
    at process._tickCallback (node.js:419:13)

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error
    at new JS_Parse_Error (C:\Source\Source2\bunny-meadows\node_modules\gulp-ugl
ify\node_modules\uglify-js\lib\parse.js:196:18)
    at js_error (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_m
odules\uglify-js\lib\parse.js:204:11)
    at croak (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_modu
les\uglify-js\lib\parse.js:675:9)
    at token_error (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\nod
e_modules\uglify-js\lib\parse.js:683:9)
    at expect_token (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:696:9)
    at expect (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_mod
ules\uglify-js\lib\parse.js:699:36)
    at function_ (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:959:9)
    at expr_atom (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:1188:24)
    at maybe_unary (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\nod
e_modules\uglify-js\lib\parse.js:1358:19)
    at expr_ops (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\node_m
odules\uglify-js\lib\parse.js:1393:24)
    at maybe_conditional (C:\Source\Source2\bunny-meadows\node_modules\gulp-ugli
fy\node_modules\uglify-js\lib\parse.js:1398:20)
    at maybe_assign (C:\Source\Source2\bunny-meadows\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:1422:20)

My gulpfile.js looks like this:

var gulp = require('gulp');

// Include Our Plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var livereload = require('gulp-livereload');

var paths = {
    // using framework version of jquery
    scripts: [
        'public/assets/js/jquery.min.js',
        'public/assets/plugins/mustachejs/mustache.js',
        'public/assets/js/modernizr.js',
        'public/assets/js/bootstrap.min.js',
        'public/assets/js/placeholders.min.js',
        'public/assets/plugins/bootstrap-wysiwyg/bootstrap3-wysihtml5.all.min.js',
        'public/assets/plugins/bootstrap-wysiwyg/bootstrap3-wysihtml5.min.js',
        'public/assets/plugins/responsiveslides/responsiveslides.min.js',
        'public/assets/plugins/bxslider/jquery.bxslider.min.js',
        'public/assets/plugins/magnific-popup/magnific-popup.js',
        'public/assets/js/jquery.autocomplete.min.js',
        'public/assets/js/plugins/additems.js',
        'public/assets/js/plugins/farm/farm.js',
        'public/assets/js/plugins/plusminus.js',
        'public/assets/js/core.js'
    ]
};

// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src(paths.scripts)
        .pipe(concat('all.js'))
        .pipe(gulp.dest('public/assets/js'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .on('error')
        .pipe(gulp.dest('public/assets/js'))
        .pipe(livereload());
});

// Watch Files For Changes
gulp.task('watch', function() {
    livereload.listen();
    gulp.watch(paths.scripts, ['scripts']);
});

// Default Task
gulp.task('default', ['scripts', 'watch']);

Again I didn't change anything so I don't get why all of a sudden this morning it doesn't want to work.

Body:
The best way to understand errors in a Gulp pipeline is to use a helper module, such as pump. As explained in the Gulp documentation Why Use Pump? you can get the correct errors by wrapping your pipeline.

gulp.task('scripts', function(cb) {
    pump([
        gulp.src(paths.scripts),
        concat('all.js'),
        gulp.dest('public/assets/js'),
        rename('all.min.js'),
        uglify(),
        gulp.dest('public/assets/js'),
        livereload()
    ], cb);
});

Attaching an error handler to the UglifyJS part of the pipeline won't tell you about errors in the others, and it won't properly signal an error to Gulp's task running system.


问:
Unable to load controller within $routeProvider in AngularJS
This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage printed in the template. All I see is {{ greetingMessage }} instead of "Welcome!". What am I missing?

Error

```<code>Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController
</code>```

App Structure

```<code>app
   conponents
      home
         HomeView.html
         HomeController.js
      ...
   ...
index.js
index.html
</code>```

index.html

```<code><body ng-app="myApp">

    <h3>AngularJS</h3>
    <hr />
    <p><a href="#!">Home</a></p>

    <div ng-view></div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
    <script src="index.js"></script>

</body>
</code>```

index.js

```<code>var module = angular.module('myApp', ['ngRoute']);

module.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'components/home/HomeView.html',
            controller: 'HomeController'
            // I tried -> controller: 'components/home/HomeController'
        })
        .otherwise({
            redirectTo: '/'
        });
});
</code>```

HomeView.html

```<code><div ng-controller="HomeController">
    <h4>Home</h4>
    <p>{{ greetingMessage }}</p>
</div>
</code>```

HomeController.js

```<code>var module = angular.module('myApp', []);
module.controller('HomeController', [
    '$scope',
    function(
        $scope
    ) {
        $scope.greetingMessage = 'Welcome!';
    }]);
</code>```

答:
The main reason is you haven't referred homeController.js on index.html, it should place right after index.js. This will not solve your issue. The other thing I'd like to mention is, you shouldn't be creating myApp module again while registering your controller with your myApp module. By declaring new module will flush out former registered component. So just use module getter like angular.module('myApp') and append further components to it.

```<code><script src="components/home/HomeController.js">
</code>```

Code

```<code>angular.module('myApp')
.controller('HomeController', [ '$scope',
    function($scope) {
        $scope.greetingMessage = 'Welcome!';
    }
]);
</code>```

Body:
This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage printed in the template. All I see is {{ greetingMessage }} instead of "Welcome!". What am I missing?

Error

Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController

App Structure

app
   conponents
      home
         HomeView.html
         HomeController.js
      ...
   ...
index.js
index.html

index.html

AngularJS

Home

index.js

var module = angular.module('myApp', ['ngRoute']);

module.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'components/home/HomeView.html',
            controller: 'HomeController'
            // I tried -> controller: 'components/home/HomeController'
        })
        .otherwise({
            redirectTo: '/'
        });
});

HomeView.html

Home

{{ greetingMessage }}

HomeController.js

var module = angular.module('myApp', []);
module.controller('HomeController', [
    '$scope',
    function(
        $scope
    ) {
        $scope.greetingMessage = 'Welcome!';
    }]);

Body:
The main reason is you haven't referred homeController.js on index.html, it should place right after index.js. This will not solve your issue. The other thing I'd like to mention is, you shouldn't be creating myApp module again while registering your controller with your myApp module. By declaring new module will flush out former registered component. So just use module getter like angular.module('myApp') and append further components to it.

<script src="components/home/HomeController.js">

Code

angular.module('myApp')
.controller('HomeController', [ '$scope',
    function($scope) {
        $scope.greetingMessage = 'Welcome!';
    }
]);


问:
coloring buttons
i want to color the text inside the button
how can i do that?
i made that code:

```<code>for(int i=0; i<10 ;i++)
    {
        arr[i]=new Button(""+i);
        arr[i].
        arr[i].setBackground(Color.LIGHT_GRAY);
        p1.add(arr[i]);
        this.arr[i].addActionListener(this);
    }
</code>```

the buttons text color is black.
if i want to color the text in the button from black to blue what i need to write?

答:
Wrap up the text for every button in HTML. For example,

```<code>JButton button = new new JButton("<html><font color=#ffffdd>Caption</font></html>");
</code>```

More information can be found here.

Title: coloring buttons

Body:
i want to color the text inside the button
how can i do that?
i made that code:

for(int i=0; i<10 ;i++)
    {
        arr[i]=new Button(""+i);
        arr[i].
        arr[i].setBackground(Color.LIGHT_GRAY);
        p1.add(arr[i]);
        this.arr[i].addActionListener(this);
    }

the buttons text color is black.
if i want to color the text in the button from black to blue what i need to write?

Body:
Wrap up the text for every button in HTML. For example,

JButton button = new new JButton("<html><font color=#ffffdd>Caption</font></html>");

More information can be found here.


问:
Joining CSV fields
I need to convert

```<code>Name | Org
a    | 5
a    | 6
b    | 5
c    | 7
</code>```

into

```<code>Name | Org
a    | 5,6
b    |  5
c    |  7
</code>```

my first attempt was with this code

```<code>    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1
</code>```

which just ends up with the result

```<code>Name | Org
a    |
b    |
c    |
</code>```

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

答:
Here's a solution using collections.OrderedDict:

```<code>import csv
from collections import OrderedDict

data = OrderedDict()
with open('test.csv') as f:
    reader = csv.reader(f)
    for i, line in enumerate(reader):
        if i == 0:
            continue

        if line[0] not in data:
            data[line[0]] = []

        data[line[0]].append(line[1])

for k, v in data.items():
    print(k, '|', ', '.join(v))
</code>```

An OrderedDict retains its order. The keys are the Names, and the values are lists of all Orgs associated with it.

Output:

```<code>a | 5, 6
b | 5
c | 7
</code>```

If your csv has different delimiters from comma, then you'll have to specify that delimiter. I've assumed commas in my example.

Here's a much simpler solution with pandas:

```<code>In [443]: df.head()
Out[443]:
  Name  Org
0    a    5
1    a    6
2    b    5
3    c    7

In [445]: for k, v in df.groupby('Name').apply(lambda x: list(x['Org'])).iteritems():
     ...:     print(k, '|', ', '.join(map(str, v)))
     ...:
a | 5, 6
b | 5
c | 7
</code>```

Title: Joining CSV fields

Body:
I need to convert

Name | Org
a    | 5
a    | 6
b    | 5
c    | 7

into

Name | Org
a    | 5,6
b    |  5
c    |  7

my first attempt was with this code

    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1

which just ends up with the result

Name | Org
a    |
b    |
c    |

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

Body:
Here's a solution using collections.OrderedDict:

import csv
from collections import OrderedDict

data = OrderedDict()
with open('test.csv') as f:
    reader = csv.reader(f)
    for i, line in enumerate(reader):
        if i == 0:
            continue

        if line[0] not in data:
            data[line[0]] = []

        data[line[0]].append(line[1])

for k, v in data.items():
    print(k, '|', ', '.join(v))

An OrderedDict retains its order. The keys are the Names, and the values are lists of all Orgs associated with it.

Output:

a | 5, 6
b | 5
c | 7

If your csv has different delimiters from comma, then you'll have to specify that delimiter. I've assumed commas in my example.

Here's a much simpler solution with pandas:

In [443]: df.head()
Out[443]:
  Name  Org
0    a    5
1    a    6
2    b    5
3    c    7

In [445]: for k, v in df.groupby('Name').apply(lambda x: list(x['Org'])).iteritems():
     ...:     print(k, '|', ', '.join(map(str, v)))
     ...:
a | 5, 6
b | 5
c | 7


问:
Have an HTML link always prompt Complete Action With on Android
I have looked around and cannot find anything helpful.

I have a web app I've been working on that lets you play video files, mainly mp4.  Depending on the mobile browser, when clicking the link, it will open in a new tab and play using HTML5 (Firefox does this), download it (Chrome does this sometimes), or ask what to do (Internet does this all the time, Chrome sometimes).

Can I force the Complete Action With dialog to come up when the link is clicked?

On top of this, I'm using drop-downs for linking because it looks neater.  The values are pulled for the options using PHP, so I have the option of detecting the browser through that if necessary.  I don't like JavaScript, but I'll use it if I have to.

My code in PHP:

```<code><select width="100%" onchange="location = this.options[this.selectedIndex].value;">
    <option selected disabled>Choose Video Quality</option>
<?php
    foreach($show[additionalMedia] as $addt){
?>
    <option value="<?=$addt[url] ?>"><?=$addt[role] ?></option>
<?php
    }
?>
</select>
</code>```

My code as rendered HTML:

```<code><select width="100%" onchange="location = this.options[this.selectedIndex].value;">
    <option selected disabled>Choose Video Quality</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil577.mp4">Source</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil150.m4v">Blip SD</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil599.mp4">Blip LD</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil515.m4v">Blip HD 720</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil642.m3u8">Blip HLS</option>
</select>
</code>```

I won't post the json_decoded array that the data came from, but suffice it to say that $addt[url] is the video URL and that $addt[role] is the URL description.

Any help?

答:
Revisiting my old questions with some Android experience under my belt, I'm not sure this is possible.  The action chooser uses MIME-type to determine what application to use, and will display all Android applications that can handle that type.  The chooser won't display if the user has set a preference.

Hypothetically, the PHP could provide functionality to download the file with various MIME-types, "lying" to the Android device, to expand the number of available Open With options, but as it stands, Android will do the best it can to open whatever file is thrown at it.

Hack-y solution using false MIME types:

```<code><select width="100%" onchange="location = '/download.php?mime=' + document.getElementById("mimetype").value + '&file=' + this.options[this.selectedIndex].value;">
</code>```

Body:
I have looked around and cannot find anything helpful.

I have a web app I've been working on that lets you play video files, mainly mp4.  Depending on the mobile browser, when clicking the link, it will open in a new tab and play using HTML5 (Firefox does this), download it (Chrome does this sometimes), or ask what to do (Internet does this all the time, Chrome sometimes).

Can I force the Complete Action With dialog to come up when the link is clicked?

On top of this, I'm using drop-downs for linking because it looks neater.  The values are pulled for the options using PHP, so I have the option of detecting the browser through that if necessary.  I don't like JavaScript, but I'll use it if I have to.

My code in PHP:

<select width="100%" onchange="location = this.options[this.selectedIndex].value;">
    <option selected disabled>Choose Video Quality</option>
<?php
    foreach($show[additionalMedia] as $addt){
?>
    <option value="<?=$addt[url] ?>"><?=$addt[role] ?></option>
<?php
    }
?>
</select>

My code as rendered HTML:

<select width="100%" onchange="location = this.options[this.selectedIndex].value;">
    <option selected disabled>Choose Video Quality</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil577.mp4">Source</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil150.m4v">Blip SD</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil599.mp4">Blip LD</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil515.m4v">Blip HD 720</option>
    <option value="http://blip.tv/file/get/NostalgiaCritic-AdventureTimeVlogsMortalRecoil642.m3u8">Blip HLS</option>
</select>

I won't post the json_decoded array that the data came from, but suffice it to say that $addt[url] is the video URL and that $addt[role] is the URL description.

Any help?

Body:
Revisiting my old questions with some Android experience under my belt, I'm not sure this is possible.  The action chooser uses MIME-type to determine what application to use, and will display all Android applications that can handle that type.  The chooser won't display if the user has set a preference.

Hypothetically, the PHP could provide functionality to download the file with various MIME-types, "lying" to the Android device, to expand the number of available Open With options, but as it stands, Android will do the best it can to open whatever file is thrown at it.

Hack-y solution using false MIME types:

<select width="100%" onchange="location = '/download.php?mime=' + document.getElementById("mimetype").value + '&file=' + this.options[this.selectedIndex].value;">


问:
Message app with node.js and socket.io
I am making a chat app with node.js and socket.io and need to save messages sent so anybody who did not see the chat can see it if they log on later. I only want the messages to be saved for 5 hours. Any Ideas</p>

答: A possible solution is using Redis. Here is a client for node from GitHub.</p>

Title: Message app with node.js and socket.io