问:
LinkedList<LinkedList<String>> output the element side by side?
I have a problem. I cant output my LinkedList side by side. I asked this question but sadly my Teacher told me to not change the method head or use the libary of java like calender. I got many advice of using it or change the method head. I am Depending on the grade and the teacher is very strict.

There must be somehow the possibility to output a 2 Dimensional LinkedList from left to right. I can imagine the way one can say if an element from the Generic of LinkedList is outputed then please go further to the right.

I am struggeling at the implementation of this Idea. I hope you can help me.

Here I just returning a String but for testing I output the string what is get added.

```<code>public String getYearplan(int from, int until) {
    if (from <= until) {
        for (int i = from; i <= until; i++) {
            LinkedList<String> buildedMonth = buildMonth(i);
            this.planlist.add(buildedMonth);
        }
        for (LinkedList<String> months: planlist) {
            for (String s : months) {
                System.out.printf("%24s",s);
            }
     }
}
</code>```

`
In this method buildMonth I am building the Month and return a LinkedList what get added by this.planlist .

```<code> public LinkedList<String> buildMonth(int month) {
            LinkedList<String> monthList = new LinkedList<>();
            StringBuilder sb = new StringBuilder();
            String header = this.monthname[month] + " " + this.year;
            sb.append(header);

            int lengthOfMonth = calender.getLengthOfMonth(jahr, monat);

            for (int day = 1; day <= lengthOfMonth; day++) {

                for (int weekday = 0; weekday < 7; weekday++) {
                    String weDay = kalender.getDayOfWeek(weekday);
                    this.weekDayName = weDay;
                }
                this.daynumber++;
                String dayOfMonth = this.kalender.getTwoLetter(day);

                /*
                  modus = -1 is calender without holiday
                */
               if (this.modus == -1) {
                    sb.append("\n"+this.weekDayName+"|"+dayOfMonth.toString()+"|\t\t|"+daynumber);
                }
            }
            monthList.add(sb.toString());

            return monthList;
        }`
</code>```

This is my output what I get and everything works without some stuff but it is easy to fix. The major problem is that I cant Output it side by side.`The weird thing is that the header of february is moving to left but not the other elements.

```<code>    January 2017
    Sa|01|      |1
    Sa|02|      |2
    Sa|03|      |3
    Sa|04|      |4
    Sa|05|      |5
    Sa|06|      |6
    Sa|07|      |7
    Sa|08|      |8
    Sa|09|      |9
    Sa|10|      |10
    Sa|11|      |11
    Sa|12|      |12
    Sa|13|      |13
    Sa|14|      |14
    Sa|15|      |15
    Sa|16|      |16
    Sa|17|      |17
    Sa|18|      |18
    Sa|19|      |19
    Sa|20|      |20
    Sa|21|      |21
    Sa|22|      |22
    Sa|23|      |23
    Sa|24|      |24
    Sa|25|      |25
    Sa|26|      |26
    Sa|27|      |27
    Sa|28|      |28
    Sa|29|      |29
    Sa|30|      |30
    Sa|31|      |31February 2017
    Sa|01|      |32
    Sa|02|      |33
    Sa|03|      |34
    Sa|04|      |35
    Sa|05|      |36
    Sa|06|      |37
    Sa|07|      |38
    Sa|08|      |39
    Sa|09|      |40
    Sa|10|      |41
    Sa|11|      |42
    Sa|12|      |43
    Sa|13|      |44
    Sa|14|      |45
    Sa|15|      |46
    Sa|16|      |47
    Sa|17|      |48
    Sa|18|      |49
    Sa|19|      |50
    Sa|20|      |51
    Sa|21|      |52
    Sa|22|      |53
    Sa|23|      |54
    Sa|24|      |55
    Sa|25|      |56
    Sa|26|      |57
    Sa|27|      |58
    Sa|28|      |59`
</code>```

Thats is the Output what I try to achieve.`

```<code>  January 2017            February 2017
  So|01|            |1    Mi|01|            |32
  Mo|02|            |2    Do|02|            |33
  Di|03|            |3    Fr|03|            |34
  Mi|04|            |4    Sa|04|            |35
  Do|05|            |5    So|05|            |36
  Fr|06|            |6    Mo|06|            |37
</code>```

I hope it was not much, but I wanted to make my question this time clear.
Best Regards
Maskulin

答:
Iterating through the days at a higher dimension than the months I think is the way to go. That way, you can iterate through each day and list them all before going onto the next day for each month.

The below has not been tested but I hope the concept has been exemplified.

```<code>    public String getYearplan(int from, int until) {
        if (from <= until) {
            for (int i = from; i <= until; i++) {
                LinkedList<String> buildedMonth = buildMonth(i);
                this.planlist.add(buildedMonth);
            }
            for (int day = 0; day < 31; day++){
                for (LinkedList<String> month: planlist) {
                    try{
                        System.out.print(month[day]);
                    } catch (Exception e) {
                        System.out.print("\t")
                    }
                }
            }
    }
</code>```

Body:
I have a problem. I cant output my LinkedList side by side. I asked this question but sadly my Teacher told me to not change the method head or use the libary of java like calender. I got many advice of using it or change the method head. I am Depending on the grade and the teacher is very strict.

There must be somehow the possibility to output a 2 Dimensional LinkedList from left to right. I can imagine the way one can say if an element from the Generic of LinkedList is outputed then please go further to the right.

I am struggeling at the implementation of this Idea. I hope you can help me.

Here I just returning a String but for testing I output the string what is get added.

public String getYearplan(int from, int until) {
    if (from <= until) {
        for (int i = from; i <= until; i++) {
            LinkedList<String> buildedMonth = buildMonth(i);
            this.planlist.add(buildedMonth);
        }
        for (LinkedList<String> months: planlist) {
            for (String s : months) {
                System.out.printf("%24s",s);
            }
     }
}

`
In this method buildMonth I am building the Month and return a LinkedList what get added by this.planlist .

 public LinkedList<String> buildMonth(int month) {
            LinkedList<String> monthList = new LinkedList<>();
            StringBuilder sb = new StringBuilder();
            String header = this.monthname[month] + " " + this.year;
            sb.append(header);

            int lengthOfMonth = calender.getLengthOfMonth(jahr, monat);

            for (int day = 1; day <= lengthOfMonth; day++) {

                for (int weekday = 0; weekday < 7; weekday++) {
                    String weDay = kalender.getDayOfWeek(weekday);
                    this.weekDayName = weDay;
                }
                this.daynumber++;
                String dayOfMonth = this.kalender.getTwoLetter(day);

                /*
                  modus = -1 is calender without holiday
                */
               if (this.modus == -1) {
                    sb.append("\n"+this.weekDayName+"|"+dayOfMonth.toString()+"|\t\t|"+daynumber);
                }
            }
            monthList.add(sb.toString());

            return monthList;
        }`

This is my output what I get and everything works without some stuff but it is easy to fix. The major problem is that I cant Output it side by side.`The weird thing is that the header of february is moving to left but not the other elements.

    January 2017
    Sa|01|      |1
    Sa|02|      |2
    Sa|03|      |3
    Sa|04|      |4
    Sa|05|      |5
    Sa|06|      |6
    Sa|07|      |7
    Sa|08|      |8
    Sa|09|      |9
    Sa|10|      |10
    Sa|11|      |11
    Sa|12|      |12
    Sa|13|      |13
    Sa|14|      |14
    Sa|15|      |15
    Sa|16|      |16
    Sa|17|      |17
    Sa|18|      |18
    Sa|19|      |19
    Sa|20|      |20
    Sa|21|      |21
    Sa|22|      |22
    Sa|23|      |23
    Sa|24|      |24
    Sa|25|      |25
    Sa|26|      |26
    Sa|27|      |27
    Sa|28|      |28
    Sa|29|      |29
    Sa|30|      |30
    Sa|31|      |31February 2017
    Sa|01|      |32
    Sa|02|      |33
    Sa|03|      |34
    Sa|04|      |35
    Sa|05|      |36
    Sa|06|      |37
    Sa|07|      |38
    Sa|08|      |39
    Sa|09|      |40
    Sa|10|      |41
    Sa|11|      |42
    Sa|12|      |43
    Sa|13|      |44
    Sa|14|      |45
    Sa|15|      |46
    Sa|16|      |47
    Sa|17|      |48
    Sa|18|      |49
    Sa|19|      |50
    Sa|20|      |51
    Sa|21|      |52
    Sa|22|      |53
    Sa|23|      |54
    Sa|24|      |55
    Sa|25|      |56
    Sa|26|      |57
    Sa|27|      |58
    Sa|28|      |59`

Thats is the Output what I try to achieve.`

  January 2017            February 2017
  So|01|            |1    Mi|01|            |32
  Mo|02|            |2    Do|02|            |33
  Di|03|            |3    Fr|03|            |34
  Mi|04|            |4    Sa|04|            |35
  Do|05|            |5    So|05|            |36
  Fr|06|            |6    Mo|06|            |37

I hope it was not much, but I wanted to make my question this time clear.
Best Regards
Maskulin

Body:
Iterating through the days at a higher dimension than the months I think is the way to go. That way, you can iterate through each day and list them all before going onto the next day for each month.

The below has not been tested but I hope the concept has been exemplified.

    public String getYearplan(int from, int until) {
        if (from <= until) {
            for (int i = from; i <= until; i++) {
                LinkedList<String> buildedMonth = buildMonth(i);
                this.planlist.add(buildedMonth);
            }
            for (int day = 0; day < 31; day++){
                for (LinkedList<String> month: planlist) {
                    try{
                        System.out.print(month[day]);
                    } catch (Exception e) {
                        System.out.print("\t")
                    }
                }
            }
    }


来源: stackexchange

问:
Modifying a const qualified object through a pointer
The following code compiles and runs as I expected.

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

int main(void) {
      const char        C1 = '1';
      char const        C2 = '3';

      printf("%c %c", C1, C2);

      char *pC1 = &C1; *pC1 = 'H';
      char *pC2 = &C2; *pC2 = 'o';

      printf("%c %c", C1, C2);

      return 0;
}
</code>```

This code invokes undefined behaviour?

答:
Yes, this code invokes undefined behavior. According to C standard,

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

ContentLicense: CC BY-SA 3.0

Body:
The following code compiles and runs as I expected.

#include <stdio.h>

int main(void) {
      const char        C1 = '1';
      char const        C2 = '3';

      printf("%c %c", C1, C2);

      char *pC1 = &C1; *pC1 = 'H';
      char *pC2 = &C2; *pC2 = 'o';

      printf("%c %c", C1, C2);

      return 0;
}

This code invokes undefined behaviour?


问:
CSV to directory
I have CSV file which contains information about
     Car and Email

```<code>BMW, person1@mail.com
Mercedes, person2@mail.com
Dodge, person1@mail.com
</code>```

etc.

I'm trying to do the script which makes a dictionary from CSV where email is key and a car is value. Every key can have more values.

```<code>import csv

reader = csv.reader(open('report.csv'))

output = {}
for row in reader:
key = row[1]
value = row[0]
if key in output:
    if row[0] == output.get(key):
        pass
    else:
        output[key].append(value)
output[key] = value

print(output)
</code>```

for every row, I'm trying to check if is the car(value) already value of email(key). If is then pass to next row, if not then add value to the key.

Output should looks like

```<code>{'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}
</code>```

but after compilating error 'str' object has no attribute 'append' comes up

Thank you

答:
Well, You are trying to append a string to a string in output[key].append(value). where output[key] is itself a string.

Use list to add value as [value], so that you can append.

```<code>import csv

reader = csv.reader(open('report.csv'))

output = {}
for row in reader:
    key = row[1]
    value = row[0]
    print key, value

    if key not in output:
        output[key] = [value]

    else:
        output[key].append(value)

print(output)

# output
# {' person2@mail.com': ['Mercedes'], ' person1@mail.com': ['BMW', 'Dodge']}
</code>```

Title: CSV to directory

Body:
I have CSV file which contains information about
     Car and Email

BMW, person1@mail.com
Mercedes, person2@mail.com
Dodge, person1@mail.com

etc.

I'm trying to do the script which makes a dictionary from CSV where email is key and a car is value. Every key can have more values.

import csv

reader = csv.reader(open('report.csv'))

output = {}
for row in reader:
key = row[1]
value = row[0]
if key in output:
    if row[0] == output.get(key):
        pass
    else:
        output[key].append(value)
output[key] = value

print(output)

for every row, I'm trying to check if is the car(value) already value of email(key). If is then pass to next row, if not then add value to the key.

Output should looks like

{'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}

but after compilating error 'str' object has no attribute 'append' comes up

Thank you

Body:
Well, You are trying to append a string to a string in output[key].append(value). where output[key] is itself a string.

Use list to add value as [value], so that you can append.

import csv

reader = csv.reader(open('report.csv'))

output = {}
for row in reader:
    key = row[1]
    value = row[0]
    print key, value

    if key not in output:
        output[key] = [value]

    else:
        output[key].append(value)

print(output)

# output
# {' person2@mail.com': ['Mercedes'], ' person1@mail.com': ['BMW', 'Dodge']}


问:
Server jams at after reaper call
I was working with a TCP server and something ultra weird came up.

When I connect with one client, everythings goes fine.

When two or more client connects, traffic is still fine.

But when any of the clients DISCONNECTS, the server jams right after the reaper call. It just sits there waiting.

I discovered this when I disconnected 1 client out of 2 & tried to reconnect. The reconnecting client does not display any error messages at all, it runs smoothly. Packages CAN be sent to the server, but it piles up inside the server.

The server on the other hand hangs there, waiting for one specific client to disconnect. If that client disconnects, the server will resume function, executing all requests that were piled up inside it.

Below is the barebone code I used for the server structure.

This code also demonstrates the problem stated above.

Can anyone please, please, please point out where the error was made?

```<code>void    reaper(int sig)
{
int status;

while (waitpid(-1, &status, WNOHANG) >= 0)
    /* empty */;
}

int     errexit(const char *format, ...)
{
    va_list args;

    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);
    exit(1);
}

int     errno;

unsigned short  portbase = 0;   /* port base, for non-root servers      */

int     passivesock(const char *service, const char *transport, int qlen)

{
    struct servent  *pse;   /* pointer to service information entry */
    struct protoent *ppe;   /* pointer to protocol information entry*/
    struct sockaddr_in sin; /* an Internet endpoint address         */
    int     s, type;        /* socket descriptor and socket type    */

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;

/* Map service name to port number */
    if ( pse = getservbyname(service, transport) )
            sin.sin_port = htons(ntohs((unsigned short)pse->s_port)
                    + portbase);
    else if ((sin.sin_port=htons((unsigned short)atoi(service))) == 0)
            errexit("can't get \"%s\" service entry\n", service);

/* Map protocol name to protocol number */
    if ( (ppe = getprotobyname(transport)) == 0)
            errexit("can't get \"%s\" protocol entry\n", transport);

/* Use protocol to choose a socket type */
    if (strcmp(transport, "udp") == 0)
            type = SOCK_DGRAM;
    else
            type = SOCK_STREAM;

/* Allocate a socket */
    s = socket(PF_INET, type, ppe->p_proto);
    if (s < 0)
            errexit("can't create socket: %s\n", strerror(s));

/* Bind the socket */
    if (errno=bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
            errexit("can't bind to %s port: %s\n", service,
                    strerror(errno));
    if (type == SOCK_STREAM && listen(s, qlen) < 0)
            errexit("can't listen on %s port: %s\n", service,
                    strerror(type));
    return s;
}

int     passiveTCP(const char *service, int qlen)
{
    return passivesock(service, "tcp", qlen);
}

#define QLEN              32    /* maximum connection queue length      */
#define BUFSIZE         4096

int     TCPechod(int fd);

int main(int argc, char *argv[])
{
    char    *service;      /* service name or port number  */
    struct  sockaddr_in fsin;       /* the address of a client      */
    unsigned int    alen;           /* length of client's address   */
    int     msock;                  /* master server socket         */
    int     ssock;                  /* slave server socket          */

    if (argc !=2)
            errexit("usage: %s port\n", argv[0]);

    service = argv[1];

    msock = passiveTCP(service, QLEN);

    (void) signal(SIGCHLD, reaper);

    while (1) {
            alen = sizeof(fsin);
            ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
            if (ssock < 0) {
                    if (errno == EINTR)
                            continue;
                    errexit("accept: %s\n", strerror(ssock));
            }
            printf("Accept connection %d from %s:%d\n", ssock, inet_ntoa(fsin.sin_addr), (int)ntohs(fsin.sin_port));
            switch (fork()){
            case 0:
                (void) close(msock);
                TCPechod(ssock);
                close(ssock);
                exit(0);
            default:
                close(ssock);
                break;
            case -1:
                errexit("fork: %s\n", strerror(errno));
            }
    }
}

int     TCPechod(int fd)
{
    char    buf[BUFSIZE];
    int     cc;

    while (cc = read(fd, buf, sizeof(buf))) {
            if (cc < 0)
                    errexit("echo read: %s\n", strerror(cc));
            if (errno=write(fd, buf, cc) < 0)
                    errexit("echo write: %s\n", strerror(errno));
    }
    return 0;
}
</code>```

Any heads up would greatly be appreciated.

I thank you in advance.

答:
The problem is how you are calling waitpid, because you are only leave the while when an error occurred (waitpid return < 0 if an error occurred).  When you call waitpid with the WNOHANG flag, it will returns 0 if there is not any child process terminated (really change state: stopped, resumed or terminated).  Try this correction:

```<code>void reaper(int sig)
{
  int status;
  pid_t pid;
  while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
    printf("Proces PID: %d Hash Finished With Status: %d", pid, status);
  if (0 == pid) printf("No More Process Waiting");
  if (pid < 0) printf("An Error Ocurred");
}
</code>```

If you want to use wait the reaper function must be something like:

```<code>void reaper(int sig)
{
  int status;
  pid_t pid;
  pid = wait(&status); // Wait suspend the execution of the current process.
  if (pid > 0) printf("Proces PID: %d Hash Finished With Status: %d", pid, status);
  if (pid < 0) printf("An Error Ocurred");
}
</code>```

For additional information about wait(2) go to: http://linux.die.net/man/2/wait

Title: Server jams at after reaper call

Body:
I was working with a TCP server and something ultra weird came up.

When I connect with one client, everythings goes fine.

When two or more client connects, traffic is still fine.

But when any of the clients DISCONNECTS, the server jams right after the reaper call. It just sits there waiting.

I discovered this when I disconnected 1 client out of 2 & tried to reconnect. The reconnecting client does not display any error messages at all, it runs smoothly. Packages CAN be sent to the server, but it piles up inside the server.

The server on the other hand hangs there, waiting for one specific client to disconnect. If that client disconnects, the server will resume function, executing all requests that were piled up inside it.

Below is the barebone code I used for the server structure.

This code also demonstrates the problem stated above.

Can anyone please, please, please point out where the error was made?

void    reaper(int sig)
{
int status;

while (waitpid(-1, &status, WNOHANG) >= 0)
    /* empty */;
}

int     errexit(const char *format, ...)
{
    va_list args;

    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);
    exit(1);
}

int     errno;

unsigned short  portbase = 0;   /* port base, for non-root servers      */

int     passivesock(const char *service, const char *transport, int qlen)

{
    struct servent  *pse;   /* pointer to service information entry */
    struct protoent *ppe;   /* pointer to protocol information entry*/
    struct sockaddr_in sin; /* an Internet endpoint address         */
    int     s, type;        /* socket descriptor and socket type    */

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;

/* Map service name to port number */
    if ( pse = getservbyname(service, transport) )
            sin.sin_port = htons(ntohs((unsigned short)pse->s_port)
                    + portbase);
    else if ((sin.sin_port=htons((unsigned short)atoi(service))) == 0)
            errexit("can't get \"%s\" service entry\n", service);

/* Map protocol name to protocol number */
    if ( (ppe = getprotobyname(transport)) == 0)
            errexit("can't get \"%s\" protocol entry\n", transport);

/* Use protocol to choose a socket type */
    if (strcmp(transport, "udp") == 0)
            type = SOCK_DGRAM;
    else
            type = SOCK_STREAM;

/* Allocate a socket */
    s = socket(PF_INET, type, ppe->p_proto);
    if (s < 0)
            errexit("can't create socket: %s\n", strerror(s));

/* Bind the socket */
    if (errno=bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
            errexit("can't bind to %s port: %s\n", service,
                    strerror(errno));
    if (type == SOCK_STREAM && listen(s, qlen) < 0)
            errexit("can't listen on %s port: %s\n", service,
                    strerror(type));
    return s;
}

int     passiveTCP(const char *service, int qlen)
{
    return passivesock(service, "tcp", qlen);
}

#define QLEN              32    /* maximum connection queue length      */
#define BUFSIZE         4096

int     TCPechod(int fd);

int main(int argc, char *argv[])
{
    char    *service;      /* service name or port number  */
    struct  sockaddr_in fsin;       /* the address of a client      */
    unsigned int    alen;           /* length of client's address   */
    int     msock;                  /* master server socket         */
    int     ssock;                  /* slave server socket          */

    if (argc !=2)
            errexit("usage: %s port\n", argv[0]);

    service = argv[1];

    msock = passiveTCP(service, QLEN);

    (void) signal(SIGCHLD, reaper);

    while (1) {
            alen = sizeof(fsin);
            ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
            if (ssock < 0) {
                    if (errno == EINTR)
                            continue;
                    errexit("accept: %s\n", strerror(ssock));
            }
            printf("Accept connection %d from %s:%d\n", ssock, inet_ntoa(fsin.sin_addr), (int)ntohs(fsin.sin_port));
            switch (fork()){
            case 0:
                (void) close(msock);
                TCPechod(ssock);
                close(ssock);
                exit(0);
            default:
                close(ssock);
                break;
            case -1:
                errexit("fork: %s\n", strerror(errno));
            }
    }
}

int     TCPechod(int fd)
{
    char    buf[BUFSIZE];
    int     cc;

    while (cc = read(fd, buf, sizeof(buf))) {
            if (cc < 0)
                    errexit("echo read: %s\n", strerror(cc));
            if (errno=write(fd, buf, cc) < 0)
                    errexit("echo write: %s\n", strerror(errno));
    }
    return 0;
}

Any heads up would greatly be appreciated.

I thank you in advance.

Body:
The problem is how you are calling waitpid, because you are only leave the while when an error occurred (waitpid return < 0 if an error occurred).  When you call waitpid with the WNOHANG flag, it will returns 0 if there is not any child process terminated (really change state: stopped, resumed or terminated).  Try this correction:

void reaper(int sig)
{
  int status;
  pid_t pid;
  while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
    printf("Proces PID: %d Hash Finished With Status: %d", pid, status);
  if (0 == pid) printf("No More Process Waiting");
  if (pid < 0) printf("An Error Ocurred");
}

If you want to use wait the reaper function must be something like:

void reaper(int sig)
{
  int status;
  pid_t pid;
  pid = wait(&status); // Wait suspend the execution of the current process.
  if (pid > 0) printf("Proces PID: %d Hash Finished With Status: %d", pid, status);
  if (pid < 0) printf("An Error Ocurred");
}

For additional information about wait(2) go to: http://linux.die.net/man/2/wait

ContentLicense: CC BY-SA 2.5


问:
creating query in C# console (Visual studio 2013)
hello every one when i create querygenerate Assign dollar will be Error how can i fixed </p>

```<code>query = "INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer)"
+ $"VALUES("{name}","{answerList[0]}","{answerList[1]}","{answerList[2]}","{answerList[3]}","{name}");";

Error 1 Unexpected character '$'
Error 2 Invalid expression term ''
Error 3 ; expected
</code>```

答:
```<code> query ="INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer)" + "VALUES("+name+","+answerList[0]+","+answerList[1]+","+answerList[2]+","+answerList[3]+","+name+");";
</code>```

Body:
hello every one when i create querygenerate Assign dollar will be Error how can i fixed

query = "INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer)"
+ $"VALUES("{name}","{answerList[0]}","{answerList[1]}","{answerList[2]}","{answerList[3]}","{name}");";

Error 1 Unexpected character '$'
Error 2 Invalid expression term ''
Error 3 ; expected


问:
Function object called via class attribute fails
I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.

A:

```<code>class Foo(object):
  _callback = None

  @classmethod
  def Register(cls, fn):
    cls._callback = fn

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback()
</code>```

```<code>input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last):   File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)
</code>```

I am not sure why it requires a Foo instance when the function is not a member of Foo.

B:

```<code>class Foo(object):
  _callback = []

  @classmethod
  def Register(cls, fn):
    cls._callback.append(fn)

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback[0]()
</code>```

Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.

答:
You still have your function object. However, calling the function from the class transforms it into an unbound method each time it is accessed via the class:

Note that the transformation from function object to (unbound or
  bound) method object happens each time the attribute is retrieved from
  the class or instance.

(the above is found under user-defined methods of the Python 2 data model documentation)

It is therefore required that the function which is now invoked via a class be passed an instance.

Note that unbound methods only exist in Python 2, so your code is valid and will work in Python 3.

You can retrieve the function object from the unbound method by accessing its im_func attribute:

```<code>Foo._callback.im_func()
# Called
</code>```

The second case stores your function object in a container, it has no direct business with the class and can be retrieved via say indexing and called normally.

Body:
I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.

A:

class Foo(object):
  _callback = None

  @classmethod
  def Register(cls, fn):
    cls._callback = fn

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback()

input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last):   File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)

I am not sure why it requires a Foo instance when the function is not a member of Foo.

B:

class Foo(object):
  _callback = []

  @classmethod
  def Register(cls, fn):
    cls._callback.append(fn)

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback[0]()

Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.

Body:
You still have your function object. However, calling the function from the class transforms it into an unbound method each time it is accessed via the class:

Note that the transformation from function object to (unbound or
  bound) method object happens each time the attribute is retrieved from
  the class or instance.

(the above is found under user-defined methods of the Python 2 data model documentation)

It is therefore required that the function which is now invoked via a class be passed an instance.

Note that unbound methods only exist in Python 2, so your code is valid and will work in Python 3.

You can retrieve the function object from the unbound method by accessing its im_func attribute:

Foo._callback.im_func()
# Called

The second case stores your function object in a container, it has no direct business with the class and can be retrieved via say indexing and called normally.


问:
windows powershell add text to the beginning of each object in a csv file
I have a csv file like this:

```<code>samaccountname,enabled
user1,false
user2,false
</code>```

I want to take each entry in the samaccaountname column and add this exact text:

C:\Users\

then I need to create a new csv file that only contains a single column with the new data like this:

```<code>header
C:\Users\User1
C:\Users\User2
C:\Users\User3
</code>```

what is the best way to accomplish this?

答:
Another way to skin this cat is to use the custom property creation via Select-Object:

```<code>import-csv $yourcsv | Select-Object *,@{Name="fullpath";Expression={"C:\users\$($_.path)"}} | export-csv -notypeinformation $newcsv
</code>```

this time, tested and does work.

Edit:  and if you don't want the original property, just change Select object to select the properties you do want with the custom property included.

Body:
I have a csv file like this:

samaccountname,enabled
user1,false
user2,false

I want to take each entry in the samaccaountname column and add this exact text:

C:\Users\

then I need to create a new csv file that only contains a single column with the new data like this:

header
C:\Users\User1
C:\Users\User2
C:\Users\User3

what is the best way to accomplish this?

Body:
Another way to skin this cat is to use the custom property creation via Select-Object:

import-csv $yourcsv | Select-Object *,@{Name="fullpath";Expression={"C:\users\$($_.path)"}} | export-csv -notypeinformation $newcsv

this time, tested and does work.

Edit:  and if you don't want the original property, just change Select object to select the properties you do want with the custom property included.


问:
How get page title dynamically in PHP
I am getting my main pages title but when it comes to getting inner pages (variable post) it's not working.</p>

```<code>$path=$_SERVER['PHP_SELF'];
$page_title=basename($path);
switch($page_title){
    case 'index.php':
        $title="Welcome to the the website";
        $description="description goes here";
        break;
    case 'about.php':
        $title="Welcome to the the website";
        $description="somehtinfd";
        break;
    case 'career.php':
        $title="Welcome to the the website";
        $description="ome textr";
        break;
    /*IT's NOT WORKING HERE*/
    case 'post.php?post_id=1':$title="graphics design services";
        $description= "about ";
        break;
}
</code>```

答:
```<code><title> <?php echo $title; ?> </title>
<meta type="description" content="<?php echo $description ?."</meta>
</code>```

Title: How get page title dynamically in PHP

Body:
I am getting my main pages title but when it comes to getting inner pages (variable post) it's not working.

$path=$_SERVER['PHP_SELF'];
$page_title=basename($path);
switch($page_title){
    case 'index.php':
        $title="Welcome to the the website";
        $description="description goes here";
        break;
    case 'about.php':
        $title="Welcome to the the website";
        $description="somehtinfd";
        break;
    case 'career.php':
        $title="Welcome to the the website";
        $description="ome textr";
        break;
    /*IT's NOT WORKING HERE*/
    case 'post.php?post_id=1':$title="graphics design services";
        $description= "about ";
        break;
}


问:
Moving data across the appdomain with good performance?

A little background

I'm working on an .net application that's uses plugins heavily, the application can request data from the plugins that is then sent back and displayed by the application.

First I implemented the plugin framework in MEF but feel that it was a bit limited for my purposes, I wanted to be able to isolate plugins and have some versioning and licensing support (since plugins can be written by thirdparty).

Then started looking at MAF which seems support just those scenarios, however I can see one thing that might be a problem, before I invest too much time changing everything to MAF it would be great knowing if someone has experience with this issue since I havent worked much with MAF.

The problem

Currently when  data is sent back to the application you get the actual objects of the data along with an adapter that says which fields the object contains and you can use the adapter on the object to extract the fields you want. The good thing about this is that you don't have to generate any new results objects but can simply query the results data when you want it from each object.

Now with MAF there's the Appdomain issue, I can't freely send all the objects across the app domain and inheriting from marshalbyref for each object isn't viable.

I could generate a result object with the string fields for each object but from a performance standpoint it doesnt seem such a good idea, the interface might only show 10 of hundreds of objects so it seems smarter to do on demand.

The solution I'm thinking might work is generating a sequence of just object id's and let the interface fetch the fields from the plugin through the appdomain through a proxy. So the application says for instance it wants fieldname x from items [y] in the plugin and those strings is sent across the appdomain.

The Question

So my questions are, is this a good way to do it, is there a better way? I'm obviously going to take a little performance hit moving across the appdomain still but since it's on demand and only for a small number of objects it shouldn't be too bad right? How do I go about setting up a proxy object like that?

It's not the easiest question in the world to answer, sorry. I'll really appreciate any insight, the future of the plugin architecture depends on it :)

答:
.NET Remoting is the fastest way to exchange information between code running in two appdomains within the same process. If your appdomains are running in two separate processes, use WCF to
exchange binary over Named Pipes.

This paper (a more recent version of the one I originally wrote ;)) should answer questions about which comms mechanism to use for cross-process and cross-machine perf.


问:
Python functools.reduce, how to reduce a list a return a new one
Answering a question I notice that I don't know how to return a list after doing append inside a reduce, for example

```<code>import functools

futures = [1,2,3]
records = functools.reduce((lambda res, future: res if (res.append(str(future))  == None) else res), futures, [])
</code>```

I want the list ['1', '2', '3'], it is just a minimal example, because I want to do more than map values.

Is there a another way that this horrible if that I put inside the lambda?

答:
You don't have to mutate the result list in your lambda; reduce takes the return value of the function as the result. So your lambda can be as simple as

```<code>lambda res, future: res+[str(future)]
</code>```

Body:
Answering a question I notice that I don't know how to return a list after doing append inside a reduce, for example

import functools

futures = [1,2,3]
records = functools.reduce((lambda res, future: res if (res.append(str(future))  == None) else res), futures, [])

I want the list ['1', '2', '3'], it is just a minimal example, because I want to do more than map values.

Is there a another way that this horrible if that I put inside the lambda?

Body:
You don't have to mutate the result list in your lambda; reduce takes the return value of the function as the result. So your lambda can be as simple as

lambda res, future: res+[str(future)]


问:
side by side div centered using bootstrap 4
I have two div's sitting side by side, but are not centered inside of its div but rather stay on the left of its row. I am trying to make it responsive and centered as the screen size is being adjusted here is my code.

```<code>  <div class="connectdiv">
   <div class="row">
    <div class="col-xs-6 text-center" "col-sm-6" >
     <h2 id="connect"><u>Connect</u></h2>
       <a target="_blank" href="https://www.instagram.com/balt_jitsu19/"><i class="fa fa-instagram fa-lg"></i></a>
       <a href="mailto:baltznunez@gmail.com"><i class="fa fa-envelope fa-lg"></i></a>
       <a target="_blank" href="https://www.freecodecamp.com/armbar1"><i class="fa fa-free-code-camp fa-lg"></i></a>
       <a target="_blank" href="http://github.com/baltz1"><i class="fa fa-github fa-lg"></i></a>
    </div>

  <div class="col-xs-6 text-center" "col-sm-6">
   <h2 id="connect"><u>Made With</u></h2>
     <i class="fa fa-html5 fa-2x"></i>
     <i class="fa fa-css3 fa-2x"></i>
     <a href="https://icons8.com"><img src="https://png.icons8.com/icons8/ios7/32/" title="Icons8" width="32" height="32"></a>
     <img src="https://png.icons8.com/gimp/ios7/25/" title="GIMP" width="25" height="25">
   </div>
  </div>
 </div>
</code>```

My Css

```<code>#connect{
  color:rgb(255, 255, 255);
  font-family:'Oleo Script Swash Caps', cursive;
  text-shadow:5px 1px 0px rgb(0, 0, 0);
  font-size:35px;
}
.connectdiv{
  padding:20px;
  width:100%;
  margin:5px auto;
}
</code>```

if it helps i have here on codepen https://codepen.io/balt1/pen/VbYweZ?editors=0100

答:
You have too many quotes in your div tag after text-center.  Change it to:

```<code><div class="col-xs-6 text-center col-sm-6" >
</code>```

Body:
I have two div's sitting side by side, but are not centered inside of its div but rather stay on the left of its row. I am trying to make it responsive and centered as the screen size is being adjusted here is my code.

Connect

Made With

My Css

#connect{
  color:rgb(255, 255, 255);
  font-family:'Oleo Script Swash Caps', cursive;
  text-shadow:5px 1px 0px rgb(0, 0, 0);
  font-size:35px;
}
.connectdiv{
  padding:20px;
  width:100%;
  margin:5px auto;
}

if it helps i have here on codepen https://codepen.io/balt1/pen/VbYweZ?editors=0100

Body:
You have too many quotes in your div tag after text-center.  Change it to:

<div class="col-xs-6 text-center col-sm-6" >


答:
try this one ... it will work :

```<code> <div class="connectdiv">
 <div class="row">
 <div class="col-xs-6 text-center col-sm-6" >
 <h2 id="connect"><u>Connect</u></h2>
   <a target="_blank" href="https://www.instagram.com/balt_jitsu19/"><i class="fa fa-instagram fa-lg"></i></a>
   <a href="mailto:baltznunez@gmail.com"><i class="fa fa-envelope fa-lg"></i></a>
   <a target="_blank" href="https://www.freecodecamp.com/armbar1"><i class="fa fa-free-code-camp fa-lg"></i></a>
   <a target="_blank" href="http://github.com/baltz1"><i class="fa fa-github fa-lg"></i></a>
</div>

 <div class="col-xs-6 text-center col-sm-6">
 <h2 id="connect"><u>Made With</u></h2>
 <i class="fa fa-html5 fa-2x"></i>
 <i class="fa fa-css3 fa-2x"></i>
   <a href="https://icons8.com"><img src="https://png.icons8.com/icons8/ios7/32/" title="Icons8" width="32" height="32"></a>
      <img src="https://png.icons8.com/gimp/ios7/25/" title="GIMP" width="25" height="25">
 </div>
 </div>
</code>```

Title: side by side div centered using bootstrap 4

Body:
try this one ... it will work :

 <div class="connectdiv">
 <div class="row">
 <div class="col-xs-6 text-center col-sm-6" >
 <h2 id="connect"><u>Connect</u></h2>
   <a target="_blank" href="https://www.instagram.com/balt_jitsu19/"><i class="fa fa-instagram fa-lg"></i></a>
   <a href="mailto:baltznunez@gmail.com"><i class="fa fa-envelope fa-lg"></i></a>
   <a target="_blank" href="https://www.freecodecamp.com/armbar1"><i class="fa fa-free-code-camp fa-lg"></i></a>
   <a target="_blank" href="http://github.com/baltz1"><i class="fa fa-github fa-lg"></i></a>
</div>

 <div class="col-xs-6 text-center col-sm-6">
 <h2 id="connect"><u>Made With</u></h2>
 <i class="fa fa-html5 fa-2x"></i>
 <i class="fa fa-css3 fa-2x"></i>
   <a href="https://icons8.com"><img src="https://png.icons8.com/icons8/ios7/32/" title="Icons8" width="32" height="32"></a>
      <img src="https://png.icons8.com/gimp/ios7/25/" title="GIMP" width="25" height="25">
 </div>
 </div>


答: The inner for loop for (i = 0; i<16; i++)... prints 16 numbers, one on each line. This inner for loop is called by the outer one 10 times. 16 lines, 10 times, is 160 numbers. </p>

Title: printf printing more lines in the for loop

Body:
I am having problem with an encryption algorithm in C, I'm encoding an AES criptography, I'm debugging one function, and this function is printing more lines than the for loop count. Below the entire code:

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

int main()
{
    unsigned char key[]   = {
                              0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                              0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
                             };

                              unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

    const unsigned char sbox[256] =
    {
//0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
        0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0
        0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1
        0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2
        0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3
        0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4
        0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5
        0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6
        0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7
        0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8
        0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9
        0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A
        0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B
        0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C
        0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D
        0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E
        0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
    }; //F

    const unsigned char Rcon[10] = {
    0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};

    unsigned char buf1, buf2, buf3, buf4, round, i;
    unsigned char rcon;

      for (round = 0; round < 10; round++){
    //add key + sbox
    for (i = 0; i <16; i++){
      state[i]=sbox[state[i] ^ key[i]];
    }
    for (i = 0; i<16; i++){
      printf("\n%d",state[i]);
    }
  }
}

The print function (as shown above):

   for (round = 0; round < 10; round++){
        //add key + sbox
        for (i = 0; i <16; i++){
          state[i]=sbox[state[i] ^ key[i]];
        }
        for (i = 0; i<16; i++){
          printf("\n%d",state[i]);
        }
      }

The output:

99
202
183
4
9
83
208
81
205
96
224
231
186
112
225
140
251
31
213
197
215
177
246
177
166
249
135
206
78
255
223
236
15
114
14
180
102
141
140
78
228
140
93
166
44
137
62
17
118
143
254
169
170
196
126
59
206
151
91
149
183
95
4
114
56
25
176
172
228
120
188
235
180
11
209
11
234
0
103
255
7
173
55
121
225
255
244
206
101
119
185
99
142
215
249
140
197
145
150
218
217
45
137
221
60
243
109
69
19
87
104
236
166
96
34
53
193
52
115
87
24
45
133
47
192
190
51
17
36
239
183
5
166
199
157
83
202
54
115
54
75
109
39
114
54
40
213
111
58
37
20
32
37
117
182
39
160
208
165
255

Someone knows what is happening?


答:
You haven't applied the col-sm-6 class properly. Currently it's a quoted string precariously applied to the DIV.

Change

class="col-xs-6 text-center" "col-sm-6"

to

class="col-xs-6 col-sm-6 text-center

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="connectdiv">

  <div class="row">
    <div class="col-xs-6 col-sm-6 text-center">

      <h2 id="connect"><u>Connect</u></h2>
      <i class="fa fa-instagram fa-lg"></i>
      <i class="fa fa-envelope fa-lg"></i>
      <i class="fa fa-free-code-camp fa-lg"></i>
      <i class="fa fa-github fa-lg"></i>

    </div>

    <div class="col-xs-6 col-sm-6 text-center">

      <h2 id="connect"><u>Made With</u></h2>
      <i class="fa fa-html5 fa-2x"></i>
      <i class="fa fa-css3 fa-2x"></i>
      <img src="https://png.icons8.com/icons8/ios7/32/" title="Icons8" width="32" height="32">
      <img src="https://png.icons8.com/gimp/ios7/25/" title="GIMP" width="25" height="25">

    </div>
  </div>
</div></code>```

Body:
You haven't applied the col-sm-6 class properly. Currently it's a quoted string precariously applied to the DIV.

Change

class="col-xs-6 text-center" "col-sm-6"

to

class="col-xs-6 col-sm-6 text-center

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');

<div class="connectdiv">

  <div class="row">
    <div class="col-xs-6 col-sm-6 text-center">

      <h2 id="connect"><u>Connect</u></h2>
      <a target="_blank" href="https://www.instagram.com/balt_jitsu19/"><i class="fa fa-instagram fa-lg"></i></a>
      <a href="mailto:baltznunez@gmail.com"><i class="fa fa-envelope fa-lg"></i></a>
      <a target="_blank" href="https://www.freecodecamp.com/armbar1"><i class="fa fa-free-code-camp fa-lg"></i></a>
      <a target="_blank" href="http://github.com/baltz1"><i class="fa fa-github fa-lg"></i></a>

    </div>

    <div class="col-xs-6 col-sm-6 text-center">

      <h2 id="connect"><u>Made With</u></h2>
      <i class="fa fa-html5 fa-2x"></i>
      <i class="fa fa-css3 fa-2x"></i>
      <a href="https://icons8.com"><img src="https://png.icons8.com/icons8/ios7/32/" title="Icons8" width="32" height="32"></a>
      <img src="https://png.icons8.com/gimp/ios7/25/" title="GIMP" width="25" height="25">

    </div>
  </div>
</div>


问:
Less Blur with `Visual Effect View with Blur`?
Title pretty much asks it all...

I'm playing with the iOS8 Visual Effect View with Blur. It's over a UIImageView that shows a user choosable background photo. The view placed in the contentView itself is my own custom view, shows a sort of graph/calendar. Most of said calendar graph is transparent. The blur it applies to the photo behind it is really heavy. I'd like to let more of the detail leak through. But Apple only seems to give three canned values:

```<code>typedef enum {
    UIBlurEffectStyleExtraLight,
    UIBlurEffectStyleLight,
    UIBlurEffectStyleDark
} UIBlurEffectStyle;
</code>```

I've monkied around with different alphas and background colors of the UIVisualEffectView (even though the documentation warns against that), but that doesn't do anything but make it worse.

答:
You can add a UIBlurEffect over the image. And that will do the trick.

Here is an example of a UIImageView with blur effect on it. Remember to add a Image to the UIImageView.

Adjust blur amount with blurEffectView.alpha = 0.8 (from 0 to 1)

```<code>import UIKit

class BlurEffectImageView: UIImageView {

override func awakeFromNib() {
    super.awakeFromNib()
    addBlurEffect()
}

private func addBlurEffect() {
    let blurEffect = UIBlurEffect(style: .light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.alpha = 0.8

    blurEffectView.translatesAutoresizingMaskIntoConstraints = false
    addSubview(blurEffectView)

    NSLayoutConstraint(item: blurEffectView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: blurEffectView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: blurEffectView, attribute: .height,  relatedBy: .equal, toItem: self, attribute: .height,  multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: blurEffectView, attribute: .width,   relatedBy: .equal, toItem: self, attribute: .width,   multiplier: 1.0, constant: 0).isActive = true
  }

}
</code>```

Body:
Title pretty much asks it all...

I'm playing with the iOS8 Visual Effect View with Blur. It's over a UIImageView that shows a user choosable background photo. The view placed in the contentView itself is my own custom view, shows a sort of graph/calendar. Most of said calendar graph is transparent. The blur it applies to the photo behind it is really heavy. I'd like to let more of the detail leak through. But Apple only seems to give three canned values:

typedef enum {
    UIBlurEffectStyleExtraLight,
    UIBlurEffectStyleLight,
    UIBlurEffectStyleDark
} UIBlurEffectStyle;

I've monkied around with different alphas and background colors of the UIVisualEffectView (even though the documentation warns against that), but that doesn't do anything but make it worse.

Body:
You can add a UIBlurEffect over the image. And that will do the trick.

Here is an example of a UIImageView with blur effect on it. Remember to add a Image to the UIImageView.

Adjust blur amount with blurEffectView.alpha = 0.8 (from 0 to 1)

import UIKit

class BlurEffectImageView: UIImageView {

override func awakeFromNib() {
    super.awakeFromNib()
    addBlurEffect()
}

private func addBlurEffect() {
    let blurEffect = UIBlurEffect(style: .light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.alpha = 0.8

    blurEffectView.translatesAutoresizingMaskIntoConstraints = false
    addSubview(blurEffectView)

    NSLayoutConstraint(item: blurEffectView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: blurEffectView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: blurEffectView, attribute: .height,  relatedBy: .equal, toItem: self, attribute: .height,  multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: blurEffectView, attribute: .width,   relatedBy: .equal, toItem: self, attribute: .width,   multiplier: 1.0, constant: 0).isActive = true
  }

}

ContentLicense: CC BY-SA 4.0


问:
Algorithm to make a mutation waterfall plot (coded in R)
Suppose I have m genes of interest and n samples. I score a mutation of a gene as a 1 and non-mutation as zero, so that I have an m x n matrix. I want an algorithm that orders the data so that I can reproduce the matrix plot below. I'm coding this up in R, so code is welcome but not necessary.

Clearly I start by ordering the rows such that the row with the most mutations across all samples is top:

```<code>data.mutations <- data.mutations[order(rowSums(data.mutations), decreasing = TRUE), ]
</code>```

I can't figure out how to sort the columns though. The first step is easy, I sort the columns by the first row:

```<code>data.mutations <- data.mutations[ , order(data.mutations[1, ], decreasing = TRUE)]
</code>```

Now I get stuck tough. A naive approach would require a lot of loops. There must be a nicer solution.

答:
A column A should appear to the left of a column B if A[1] > B[1]. In case of a tie, compare A[2] to B[2], and so on and so forth. In other words, a comparison operator is defined on the columns by comparing their values in decreasing order of row number. This can be encoded in a single scalar value by assigning a value sum[r=1 to n] C[n]*2^(1-r). (In a language other than R, this could be done by creating an integer whose bits correspond to the values of the column). Then the columns should be sorted in decreasing value of this encoded scalar. In R,</p>

```<code>n <- 15
m <- 20
p <- 0.15
mat <- matrix(0,n,m)
for (i in 1:n) {
  for (j in 1:n) {
    mat[i,j] = rbinom(1,1,0.15)
  }
}
print(mat)

# Order by row
mat <- mat[order(rowSums(mat),decreasing=TRUE),]

# Order by column
code <- function(column) {
  n <- length(column)
  pow <- 2^-(0:(n-1))
  return (column %*% pow)
}
mat <- mat[,order(apply(mat,2,code),decreasing=TRUE)]

print(mat)
</code>```

Body:
Suppose I have m genes of interest and n samples. I score a mutation of a gene as a 1 and non-mutation as zero, so that I have an m x n matrix. I want an algorithm that orders the data so that I can reproduce the matrix plot below. I'm coding this up in R, so code is welcome but not necessary.

Clearly I start by ordering the rows such that the row with the most mutations across all samples is top:

data.mutations <- data.mutations[order(rowSums(data.mutations), decreasing = TRUE), ]

I can't figure out how to sort the columns though. The first step is easy, I sort the columns by the first row:

data.mutations <- data.mutations[ , order(data.mutations[1, ], decreasing = TRUE)]

Now I get stuck tough. A naive approach would require a lot of loops. There must be a nicer solution.

Body:
A column A should appear to the left of a column B if A[1] > B[1]. In case of a tie, compare A[2] to B[2], and so on and so forth. In other words, a comparison operator is defined on the columns by comparing their values in decreasing order of row number. This can be encoded in a single scalar value by assigning a value sum[r=1 to n] C[n]*2^(1-r). (In a language other than R, this could be done by creating an integer whose bits correspond to the values of the column). Then the columns should be sorted in decreasing value of this encoded scalar. In R,

n <- 15
m <- 20
p <- 0.15
mat <- matrix(0,n,m)
for (i in 1:n) {
  for (j in 1:n) {
    mat[i,j] = rbinom(1,1,0.15)
  }
}
print(mat)

# Order by row
mat <- mat[order(rowSums(mat),decreasing=TRUE),]

# Order by column
code <- function(column) {
  n <- length(column)
  pow <- 2^-(0:(n-1))
  return (column %*% pow)
}
mat <- mat[,order(apply(mat,2,code),decreasing=TRUE)]

print(mat)


问:
Designate Order for Some Columns, Alphabetize the rest
I have a very wide data.frame in R. In order to make it easier to read, I'd like the variables in a certain order.
ID
NAME
GENDER
EVERYTHING ELSE (ordered by alpha)

The below works, but seems clunky and I need something that can generalize ( i have more than 3 columns i need to set at the beginning).  Is there an easier way to accomplish this or am I stuck doing it this way?

```<code># Columns
A <- c(100, 200, 100)
name <- c("Tim", "Jim", "Kim")
C <- c(2, 2, 1)
ID <- c(110, 111, 112)
B <- c(300, 330, 320)
gender = c("M", "M", "F")
# Data.frame
have <- data.frame(A, name, C, ID, B, gender)
# Alpha
want <- have[, order(names(have))]
# Move columns
want <- want[,c(which(colnames(want)=="gender"), which(colnames(want)!="gender"))]
want <- want[,c(which(colnames(want)=="name"), which(colnames(want)!="name"))]
want <- want[,c(which(colnames(want)=="id"), which(colnames(want)!="id"))]
</code>```

答:
You can easily do it like this (assuming you already sorted it):

```<code>mycol <- c("ID","name","gender")
want <-  want[,c(mycol,setdiff(names(want),mycol))]
</code>```

As I said, It can be done as simple as that but I missed using for in R:

```<code>mycol <- c("gender","name","ID") #in the reverse order that you want the first columns

for (i in 1:3){
    want <-  want[,c(mycol[i],setdiff(names(want),mycol[i]))]
}
</code>```

Result would be:

```<code>> (want)

#    ID name gender   A   B C
# 1 110  Tim      M 100 300 2
# 2 111  Jim      M 200 330 2
# 3 112  Kim      F 100 320 1
</code>```

Body:
I have a very wide data.frame in R. In order to make it easier to read, I'd like the variables in a certain order.
ID
NAME
GENDER
EVERYTHING ELSE (ordered by alpha)

The below works, but seems clunky and I need something that can generalize ( i have more than 3 columns i need to set at the beginning).  Is there an easier way to accomplish this or am I stuck doing it this way?

# Columns
A <- c(100, 200, 100)
name <- c("Tim", "Jim", "Kim")
C <- c(2, 2, 1)
ID <- c(110, 111, 112)
B <- c(300, 330, 320)
gender = c("M", "M", "F")
# Data.frame
have <- data.frame(A, name, C, ID, B, gender)
# Alpha
want <- have[, order(names(have))]
# Move columns
want <- want[,c(which(colnames(want)=="gender"), which(colnames(want)!="gender"))]
want <- want[,c(which(colnames(want)=="name"), which(colnames(want)!="name"))]
want <- want[,c(which(colnames(want)=="id"), which(colnames(want)!="id"))]

Body:
You can easily do it like this (assuming you already sorted it):

mycol <- c("ID","name","gender")
want <-  want[,c(mycol,setdiff(names(want),mycol))]

As I said, It can be done as simple as that but I missed using for in R:

mycol <- c("gender","name","ID") #in the reverse order that you want the first columns

for (i in 1:3){
    want <-  want[,c(mycol[i],setdiff(names(want),mycol[i]))]
}

Result would be:

> (want)

#    ID name gender   A   B C
# 1 110  Tim      M 100 300 2
# 2 111  Jim      M 200 330 2
# 3 112  Kim      F 100 320 1


问:
php - preg_replace to highlight formatted phone numbers
I'm having a hard time trying to highlight a search result for a formatted phone number.

```<code>$search_txt='5678'; // user generated (can be anything)
$phone_number='(123) 456-7890'; // always in this format
</code>```

I'm trying this to get the highlighted string:

```<code>$highlighted = preg_replace('#'. preg_quote($search_txt) .'#i', '<span style="background-color:#ff0;">\\0</span>', $phone_number);
</code>```

The $search_txt could be anything. "7890" works, "456-7890", works, but "5678" doesn't work due to the "-" in $phone_number.

I've also tried stripping the format of $phone_number (i.e. "1234567890"), but if they enter alpha characters "56-78", I have the same issue.

If I strip both $phone_number ("1234567890") and $search_txt ("5678"), the highlighting works and returns 1234567890, but I don't know how to re-introduce the formatting with the highlight code in the string.

The final string needs to be a phone number format "(123) 456-7890" with highlighting HTML included.

Option #1: Can I format a phone number while ignoring HTML tags within the number?

i.e. 1234567890

becomes (123) 456-7890

Option #2: Can I ignore the alpha characters in $phone_number when matching, but include them in the replaced string?

i.e. "5678" would match "(123) 456-7890"

and return (123) 456-7890.

答:
Assuming your  tags have no numeric values as a clear example:

$phone = "1234567890";
$pattern = '/(\D*\d\D*\d\D*\d)(\D*\d\D*\d\D*\d)(\D*\d\D*\d\D*\d\D*\d\D*)/';
$replace = '($1) $2-$3';
echo "\n\n".preg_replace($pattern, $replace, $phone);

produces:

(123) 456-7890

basically I'm capturing zero-or-more of non-numeric values before each digit and once after the last.  This assumes you have reduced both the search string and the target phone number to simple number strings ("4567" and "1234567890") and then performed your search-and-replace to place the HTML tags.

If you must have numbers in your HTML tags, then you must replace \D with something like <[^>]*>.

$pattern = '/((?:<[^>]*>)*\d(?:<[^>]*>)*\d(?:<[^>]*>)*\d)...

The (?:...) construct groups items without capturing them.  Use the {} construct to add a bit of elegance and you have:

$pattern = '/((?:(?:<[^>]*>)*\d){3})((?:(?:<[^>]*>)*\d){3})((?:(?:<[^>]*>)*\d){4}(?:<[^>]*>)*)/';

Body:
I'm having a hard time trying to highlight a search result for a formatted phone number.

$search_txt='5678'; // user generated (can be anything)
$phone_number='(123) 456-7890'; // always in this format

I'm trying this to get the highlighted string:

$highlighted = preg_replace('#'. preg_quote($search_txt) .'#i', '\\0', $phone_number);

The $search_txt could be anything. "7890" works, "456-7890", works, but "5678" doesn't work due to the "-" in $phone_number.

I've also tried stripping the format of $phone_number (i.e. "1234567890"), but if they enter alpha characters "56-78", I have the same issue.

If I strip both $phone_number ("1234567890") and $search_txt ("5678"), the highlighting works and returns 1234567890, but I don't know how to re-introduce the formatting with the highlight code in the string.

The final string needs to be a phone number format "(123) 456-7890" with highlighting HTML included.

Option #1: Can I format a phone number while ignoring HTML tags within the number?

i.e. 1234567890

becomes (123) 456-7890

Option #2: Can I ignore the alpha characters in $phone_number when matching, but include them in the replaced string?

i.e. "5678" would match "(123) 456-7890"

and return (123) 456-7890.

Body:
Assuming your  tags have no numeric values as a clear example:

$phone = "1234<span>5678</span>90";
$pattern = '/(\D*\d\D*\d\D*\d)(\D*\d\D*\d\D*\d)(\D*\d\D*\d\D*\d\D*\d\D*)/';
$replace = '($1) $2-$3';
echo "\n\n".preg_replace($pattern, $replace, $phone);

produces:

(123) 4<span>56-78</span>90

basically I'm capturing zero-or-more of non-numeric values before each digit and once after the last.  This assumes you have reduced both the search string and the target phone number to simple number strings ("4567" and "1234567890") and then performed your search-and-replace to place the HTML tags.

If you must have numbers in your HTML tags, then you must replace \D with something like <[^>]*>.

$pattern = '/((?:<[^>]*>)*\d(?:<[^>]*>)*\d(?:<[^>]*>)*\d)...

The (?:...) construct groups items without capturing them.  Use the {} construct to add a bit of elegance and you have:

$pattern = '/((?:(?:<[^>]*>)*\d){3})((?:(?:<[^>]*>)*\d){3})((?:(?:<[^>]*>)*\d){4}(?:<[^>]*>)*)/';


问:
C# - WCF Message Inspector Doesn't Run
I'm working on refactoring a project that has about 5 different web services, and each web service had a ton of identical code, including adding a message inspector onto the client endpoint behaviors so we could see the request and response data.

Part of the refactoring was to come up with a cleaner model for the web services (e.g. one abstract base service model that did all the common setup, including the addition of the message inspector).

Now, when I make the service calls (invoked via reflection), the service call works perfectly fine, and if I add a breakpoint right after the response comes back, I can see that there are 3 behaviors added to the client's endpoint:

```<code>[0] Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior
[1] System.ServiceModel.Description.ClientCredentials
[2] MyProject.MyMessageInspector
</code>```

...but the message inspector code doesn't seem to get called at all anymore. The inspector code is currently identical to the MSDN example here (except for the class name):
https://msdn.microsoft.com/en-us/library/ms733786(v=vs.110).aspx

The primary difference is that I'm now using generic methods for setting up the client, which looks like this:

```<code>...sanity checks, etc...
TClient client = Activator.CreateInstance(typeof(TClient), binding, new EndpointAddress(url)) as TClient;
ClientBase<TInterface> _clientBase = client as ClientBase<TInterface>;
...credentials, timeout, etc...
MyEndpointBehavior _inspector = new MyEndpointBehavior()
_clientBase.Endpoint.Behaviors.Add(_inspector);
</code>```

Then, when I make a call, I use this code that is located in the new abstract base class (the original code did it this way, and so far the only difference is the use of generics):

```<code>ClientBase<TInterface> _clientBase = _client as ClientBase<TInterface>;
using (new OperationContextScope(_clientBase.InnerChannel))
{
  // Get the method
  MethodInfo mi = _client.GetType().GetMethod(APICall);

  // Make the call and return the result if successful
  object response = mi.Invoke(_client, APICallParameters);
  return response;
}
</code>```

Any ideas why this worked prior to the switchover to generic methods and not now?

答:
I'm not sure why this made a difference, but I re-ordered the code to move the inspector addition to happen immediately after the client creation, so the code now looks like this:

```<code>...sanity checks, etc...
TClient client = Activator.CreateInstance(typeof(TClient), binding, new
EndpointAddress(url)) as TClient;
ClientBase<TInterface> _clientBase = client as ClientBase<TInterface>;
MyEndpointBehavior _inspector = new MyEndpointBehavior()
_clientBase.Endpoint.Behaviors.Add(_inspector);
...credentials, timeout, etc...
</code>```

The inspector now seems to work as expected. Strange.

Title: C# - WCF Message Inspector Doesn't Run

Body:
I'm working on refactoring a project that has about 5 different web services, and each web service had a ton of identical code, including adding a message inspector onto the client endpoint behaviors so we could see the request and response data.

Part of the refactoring was to come up with a cleaner model for the web services (e.g. one abstract base service model that did all the common setup, including the addition of the message inspector).

Now, when I make the service calls (invoked via reflection), the service call works perfectly fine, and if I add a breakpoint right after the response comes back, I can see that there are 3 behaviors added to the client's endpoint:

[0] Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior
[1] System.ServiceModel.Description.ClientCredentials
[2] MyProject.MyMessageInspector

...but the message inspector code doesn't seem to get called at all anymore. The inspector code is currently identical to the MSDN example here (except for the class name):
https://msdn.microsoft.com/en-us/library/ms733786(v=vs.110).aspx

The primary difference is that I'm now using generic methods for setting up the client, which looks like this:

...sanity checks, etc...
TClient client = Activator.CreateInstance(typeof(TClient), binding, new EndpointAddress(url)) as TClient;
ClientBase<TInterface> _clientBase = client as ClientBase<TInterface>;
...credentials, timeout, etc...
MyEndpointBehavior _inspector = new MyEndpointBehavior()
_clientBase.Endpoint.Behaviors.Add(_inspector);

Then, when I make a call, I use this code that is located in the new abstract base class (the original code did it this way, and so far the only difference is the use of generics):

ClientBase<TInterface> _clientBase = _client as ClientBase<TInterface>;
using (new OperationContextScope(_clientBase.InnerChannel))
{
  // Get the method
  MethodInfo mi = _client.GetType().GetMethod(APICall);

  // Make the call and return the result if successful
  object response = mi.Invoke(_client, APICallParameters);
  return response;
}

Any ideas why this worked prior to the switchover to generic methods and not now?

Body:
I'm not sure why this made a difference, but I re-ordered the code to move the inspector addition to happen immediately after the client creation, so the code now looks like this:

...sanity checks, etc...
TClient client = Activator.CreateInstance(typeof(TClient), binding, new
EndpointAddress(url)) as TClient;
ClientBase<TInterface> _clientBase = client as ClientBase<TInterface>;
MyEndpointBehavior _inspector = new MyEndpointBehavior()
_clientBase.Endpoint.Behaviors.Add(_inspector);
...credentials, timeout, etc...

The inspector now seems to work as expected. Strange.


问:
Visual analytic with graphs, maps etc from my user data?
I have lot of data stored about my users and now I can build user analytics from this data to provide meaningful data back to my users. I can output this as normal text which is ok but I want to display bargraphs, charts, world maps, etc...

So the question is how do i take all the data from my tables and add in all these graphs /maps? Do i need some software packages or do i need to "code" the graphs/maps? If software packages then are there any open source I can use?

The data saved includes user logs like visits, browsers etc along with lot of business activity details so i want to show my users like top 10 clients, top countries they came from, top products, top customers etc.

My platform is: MySQL and codeignitor PHP.
I do not have a data wearhouse built but that can be done once i have a plan for how I can output all this data visually so it looks good.

答: your choices are vast and almost limitless. Assuming you don't want to write your own library, consider the Google Chart API or the rGraph library I use rhraph a bit more but fellow coders prefer the Google Chart API...</p>


问:
bash no parameters for $(function parameters)
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters

```<code>function promp() {
    echo $*
    read response
    echo $response
}
function confirm() {
    echo $*
    read -rp $'(y/N) : ' -ei $'N' key;
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE
</code>```

Expected:

```<code>SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text
</code>```

Obtained:

```<code>(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text
</code>```

I know the problem is the echo within the function is part of the variable data, but I want to get this printed.

How can I do this or which is the best way to do this

答:
Use the prompts in the read commands instead of echo:

```<code>#!/bin/bash
function promp() {
    read -p "$*"$'\n' response
    echo $response
}
function confirm() {
    read -rp "$*"$'\n'"(y/N) : " -ei $'N' key
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE
</code>```

Results:

```<code>$ ./test.sh
SOME QUESTION
(y/N) : N
WRITE SOMETHING
something
false
something
</code>```

Body:
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters

function promp() {
    echo $*
    read response
    echo $response
}
function confirm() {
    echo $*
    read -rp $'(y/N) : ' -ei $'N' key;
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE

Expected:

SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text

Obtained:

(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text

I know the problem is the echo within the function is part of the variable data, but I want to get this printed.

How can I do this or which is the best way to do this

Body:
Use the prompts in the read commands instead of echo:

#!/bin/bash
function promp() {
    read -p "$*"$'\n' response
    echo $response
}
function confirm() {
    read -rp "$*"$'\n'"(y/N) : " -ei $'N' key
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE

Results:

$ ./test.sh
SOME QUESTION
(y/N) : N
WRITE SOMETHING
something
false
something


问:
Unable to call @Html.Action() in jQuery
I'm trying to get the html from one of my partial views into a div tag with the id "searchpage" in my main view. However, when I follow the syntax in this answer, How to append an Html.Action to the jquery, I get the error in chrome developer tools,

```<code>Uncaught SyntaxError: Invalid or unexpected token
</code>```

The code is

```<code>$("#searchbutton").click(function () {
    $("#searchpage").html('@Html.Action("Search", "Employees")');
});
</code>```

The error is highlighted at (' specifically.

答:
@Url.Action:  Returns only an url.

@Html.Action: Invokes the specified controller name and action and returns as a html string

You can not use $("#yourid").html('@Html.Action()') because this executes Html.Action and returns data but jquery can not see it as a variable and can not interpret it as we expected.

There are good two options to achieve your goal:

First one is using jquery ajax with @UrlAction or string url and then parsing result value into target div.

```<code>$('#searchbutton').on('click', function() {
    $("#target").load("/Employees/Search");
});
</code>```

Second one is using jquery load function to get result  of your partial view with model data into target div.

```<code>// jquery
$('#searchbutton').on('click', function() {
    var $detailDiv = $('#searchpage');
    var url = '@Url.Action("Search", "Employees")';

    $.get(url, function(data) {
        $detailsDiv.replaceWith(data);
    });
});
</code>```

// controller

```<code>public ActionResult Search()
{
    var model = GetModel(); // your function to get your model
    return PartialView( "Search", model );
}
</code>```

// html

```<code><div id="searchpage">
    <!-- ...content... -->
</div>
</code>```

Title: Unable to call @Html.Action() in jQuery

Body:
I'm trying to get the html from one of my partial views into a div tag with the id "searchpage" in my main view. However, when I follow the syntax in this answer, How to append an Html.Action to the jquery, I get the error in chrome developer tools,

Uncaught SyntaxError: Invalid or unexpected token

The code is

$("#searchbutton").click(function () {
    $("#searchpage").html('@Html.Action("Search", "Employees")');
});

The error is highlighted at (' specifically.

Body:
@Url.Action:  Returns only an url.

@Html.Action: Invokes the specified controller name and action and returns as a html string

You can not use $("#yourid").html('@Html.Action()') because this executes Html.Action and returns data but jquery can not see it as a variable and can not interpret it as we expected.

There are good two options to achieve your goal:

First one is using jquery ajax with @UrlAction or string url and then parsing result value into target div.

$('#searchbutton').on('click', function() {
    $("#target").load("/Employees/Search");
});

Second one is using jquery load function to get result  of your partial view with model data into target div.

// jquery
$('#searchbutton').on('click', function() {
    var $detailDiv = $('#searchpage');
    var url = '@Url.Action("Search", "Employees")';

    $.get(url, function(data) {
        $detailsDiv.replaceWith(data);
    });
});

// controller

public ActionResult Search()
{
    var model = GetModel(); // your function to get your model
    return PartialView( "Search", model );
}

// html

<div id="searchpage">
    <!-- ...content... -->
</div>


问:
ViewModel and Data Binding
Android has recently introduced Architecture Components and in particular a ViewModel, which is

designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations

In example provided by Google, ViewModel is used like this:

```<code>public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}
</code>```

Question: How does ViewModel suppose to correlate with the Data Binding?

I mean, in case of data binding there is going to be a binding which provides data for the UI.

Is it going to look like this:

```<code>...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...
</code>```

答:
You can declare a variable of your viewmodel type in your layout xml file.
In your viewmodel class implement public methods through which data will be bind to ui.

Then you only need to set view model into binding in onCreate. When you set view model instance in databinding, the data which is already loaded in viewmodel will be set to recreated layout.

In case there is a recycler view in your layout you can implement some public method like initRecyclerView() in your view model class and call it in onCreate() after setting view model in binding or adapter can be set from view model through databinding as well.

Title: ViewModel and Data Binding

Body:
Android has recently introduced Architecture Components and in particular a ViewModel, which is

designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations

In example provided by Google, ViewModel is used like this:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

Question: How does ViewModel suppose to correlate with the Data Binding?

I mean, in case of data binding there is going to be a binding which provides data for the UI.

Is it going to look like this:

...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...


答:
you cot some of these " too much
try

```<code><div class="col-xs-6 text-center col-sm-6">
</code>```

instead of

```<code><div class="col-xs-6 text-center" "col-sm-6">
</code>```

Body:
I have two div's sitting side by side, but are not centered inside of its div but rather stay on the left of its row. I am trying to make it responsive and centered as the screen size is being adjusted here is my code.

Connect

Made With

My Css

#connect{
  color:rgb(255, 255, 255);
  font-family:'Oleo Script Swash Caps', cursive;
  text-shadow:5px 1px 0px rgb(0, 0, 0);
  font-size:35px;
}
.connectdiv{
  padding:20px;
  width:100%;
  margin:5px auto;
}

if it helps i have here on codepen https://codepen.io/balt1/pen/VbYweZ?editors=0100

Body:
you cot some of these " too much
try

<div class="col-xs-6 text-center col-sm-6">

instead of

<div class="col-xs-6 text-center" "col-sm-6">


问:
Null keys in Java collections that are not sorted
Can please someone explain me the following:

it is clear for me why null keys (values) are prohibited in Java sorted collections
But why they are not allowed in HashTable, ConcurrentHashMap and ... Properties

Does it relates somehow to thread-safety?

Is null value allowed/prohibited in CopyOnWriteArrayList? Why?

Thank you

答:
There are 2 questions here. Both can be answered by reading the docs.

1 - Why HashTable, ConcurrentHashMap and Properties cannot receive "null" as a key?

HashTable:

https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

ConcurrentHashMap:

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html

Conversely, because keys and values in the map are never null, null serves as a reliable atomic indicator of the current lack of any result.

The Properties class extends HashTable, so you already got the reason.

2 - Is null value allowed/prohibited in CopyOnWriteArrayList? Why?

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

All elements are permitted, including null.

There is no further explanation on why is that, but I believe it's a design decision.


问:
How to count how many times certain values appear in a table in SQL and return that number in a column?
I've used the COUNT function to determine how many rows there are in a table or how often a value appears in a table.

However, I want to return the 'count' for multiple values in a table as a seperate column.

Say we a have a customer table with columns; Customer ID #, Name, Phone Number.

Say we also have a sales table with columns: Customer ID, Item Purchased, Date

I would like my query to return a column for customer ID and a column for # of times that customer ID appeared in the sales table.  I would like to do this for all of my customer IDs at once--any tips?

答:
You want to use GROUP BY

```<code>Select Count(*), CustomerID
from Sales
GROUP BY CustomerID
</code>```

Body:
You want to use GROUP BY

Select Count(*), CustomerID
from Sales
GROUP BY CustomerID


问:
#Linq adds LIKE @p__linq__0 ESCAPE '~'
I am working on a .Net application using Reverse POCO Generated Classes and trying to write a linq query which would retrieve values from the Microsoft Sql Server database  when a partial match is found from the users input.
ex:users input:12345
would yield the results
123456,
3434123456,
12345,
123456789001010,
etc

but using .contains in the linq query evaluates to a sql statement and adds something as shown below to the end of the statement.:
 LIKE @p__linq__0 ESCAPE '~'}

This ESCAPE '~' adds 14-30secs of execution time and results in timeout issues.

It would be great if somebody could help me with this.

答:
When using a variable in .contains() such as .contains(inputVariable), the filter is escaped. You can either put a constant in the filter such as: .contains('12345')
or you can use SqlMethods.Like() to perform the comparison instead of .contains().

Here is a link to the docs for SqlMethods.Like: SqlMethods.Like

Title: #Linq adds LIKE @p__linq__0 ESCAPE '~'


答:
You can use group by:

```<code>select   customer_id,
         count(*)
from     sales
group by customer_id
</code>```

This will return a row by customer ID with the count of how many matching items.

Title: How to count how many times certain values appear in a table in SQL and return that number in a column?

Body:
I've used the COUNT function to determine how many rows there are in a table or how often a value appears in a table.

However, I want to return the 'count' for multiple values in a table as a seperate column.

Say we a have a customer table with columns; Customer ID #, Name, Phone Number.

Say we also have a sales table with columns: Customer ID, Item Purchased, Date

I would like my query to return a column for customer ID and a column for # of times that customer ID appeared in the sales table.  I would like to do this for all of my customer IDs at once--any tips?

Body:
You can use group by:

select   customer_id,
         count(*)
from     sales
group by customer_id

This will return a row by customer ID with the count of how many matching items.


问:
Bootstrap Dropdown and Bootstrap Tagsinput not working when integrating with angular 2
Bootstrap dropdown code works fine (without angular 2) but same code is integrated with angular 2, it fails to work as expected.

HTML and CSS Code: [Dropdown is working.]

```<code><div class="collapse navbar-collapse">
     <ul class="nav navbar-nav navbar-right">
         <li class="dropdown">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                     <i class="ti-user"></i>
                     <p>You can</p>
                     <b class="caret"></b>
               </a>
               <ul class="dropdown-menu">
                 <li><a href="login.html">Login</a></li>
                 <li><a href="signup.html">Signup</a></li>
               </ul>
         </li>
      </ul>
 </div>
</code>```

HTML and CSS with Angular 2 [Dropdown is not working.]

```<code><div class="collapse navbar-collapse">
     <ul class="nav navbar-nav navbar-right">
         <li class="dropdown">
               <a class="dropdown-toggle" data-toggle="dropdown">
                     <i class="ti-user"></i>
                     <p>You can</p>
                     <b class="caret"></b>
               </a>
               <ul class="dropdown-menu">
                 <li><a [routerLink]="['/login']">Login</a></li>
                 <li><a [routerLink]="['/signup']">Signup</a></li>
               </ul>
         </li>
     </ul>
 </div>
</code>```

答:
```<code><ul class="dropdown-menu">
                 <li><a routerLink='login'>Login</a></li>
                 <li><a routerLink='signup'>Signup</a></li>
               </ul>
</code>```

Try this.. with final version, routerLink shouldn't be used as biniding unless you have path params.

Then in router file

```<code>RouterModule.forRoot([
{path:"login", component : },
{path: "signup", component: }
])
</code>```

Body:
Bootstrap dropdown code works fine (without angular 2) but same code is integrated with angular 2, it fails to work as expected.

HTML and CSS Code: [Dropdown is working.]

You can

Login

Signup

HTML and CSS with Angular 2 [Dropdown is not working.]

You can

Login

Signup

Body:
<ul class="dropdown-menu">
                 <li><a routerLink='login'>Login</a></li>
                 <li><a routerLink='signup'>Signup</a></li>
               </ul>

Try this.. with final version, routerLink shouldn't be used as biniding unless you have path params.

Then in router file

RouterModule.forRoot([
{path:"login", component : },
{path: "signup", component: }
])


问:
how to get title of of row selected in UITableview
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

but how can i get that title of that row ?

thanks in advance

regards

答:
Once you've registered one of your classes as a delegate via the UITableView delegate property you simply implement the tableView:didSelectRowAtIndexPath: method, which would be called when the user selected a row. (See the UITableViewDelegate Protocol Reference for more information.)

You could then extract the label text from the selected cell via...

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *cellLabelText = cell.textLabel.text;
    }
</code>```

..if this is really what you require.

Body:
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

but how can i get that title of that row ?

thanks in advance

regards

Body:
Once you've registered one of your classes as a delegate via the UITableView delegate property you simply implement the tableView:didSelectRowAtIndexPath: method, which would be called when the user selected a row. (See the UITableViewDelegate Protocol Reference for more information.)

You could then extract the label text from the selected cell via...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *cellLabelText = cell.textLabel.text;
    }

..if this is really what you require.


问:
WooCommerce Product image is not displaying. display: none !important;
I am using WooCommerce, with the theme Seos Video. I have the plugins, Page Builder by SiteOrigin, SiteOrigin CSS, SiteOrigin Widgets Bundle, WooCommerce, WooCommerce Display Products by Tags, and WooCommerce Products Carousel all in one installed.

I have loaded in three products so far, they all load and display correctly in a carousel sidebar, in the product thumbnails, and searches. When a product is selected and the main product page loads, it will not always display the image. In two of the products when I checked the css for that section it shows the image as loaded, but has

style="display:none !important"

This is directly added in at some point during the load cycle and I have been unable to track down the main culprit. The second product I loaded is working as intended.

I have tried with several themes, and the issue persists regardless of which theme I pick. I am certain that there is an underlying issue that is causing it, as the page is still laid out as if the image were there. It registers and loads the image on each page, but then the display takes over and it cannot be removed, even manually with the debugger manually changing the line. It reverts after the line is disabled or changed.

答:
I was able to resolve my issue using the plugin

https://wordpress.org/plugins/regenerate-thumbnails/

After the regeneration everything worked as intended.


问:
Converting a working SQL NOT IN
I have some SQL to tell me the superheroes who don't ever wield a sword.

Creating the table

First, here is the (MySQL) script to create and populate the table.

```<code>CREATE TABLE IF NOT EXISTS `mydb`.`weaponry` (
  `hero` VARCHAR(20) NULL,
  `weapon` VARCHAR(20) NULL)
ENGINE = InnoDB

insert into weaponry (hero, weapon) values ('Wonder Woman', 'Lasso of truth');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Sword');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Shield');
insert into weaponry (hero, weapon) values ('Spider Man', 'Web');
insert into weaponry (hero, weapon) values ('Gamora', 'Sword');
insert into weaponry (hero, weapon) values ('Gamora', 'Daggar');
insert into weaponry (hero, weapon) values ('Batman', 'Batarang');
insert into weaponry (hero, weapon) values ('Batman', 'Batgrapple');
insert into weaponry (hero, weapon) values ('Batman', 'Tranquilizer gun');
</code>```

Working code using a NOT IN and a subselect

```<code>select distinct hero from weaponry
  where hero not in
  (select hero from weaponry where weapon = 'Sword')
</code>```

This correctly returns Spider Man and Batman, who don't wield a sword.

Alternative 1: Using NOT EXISTS

I would like to implement the same query using NOT EXISTS.
I looked at https://stackoverflow.com/a/5231731/509840.
I tried this:

```<code>select distinct hero from weaponry
  where not exists
  (select * from weaponry where weapon = 'Sword')
</code>```

Unfortunately, this returns no rows.

Alternative 2: Using LEFT JOIN

I also took a look at this answer: https://stackoverflow.com/a/17413996/509840 .
I was curious to try replacing the NOT IN with a LEFT JOIN.

```<code>  select * from weaponry a
    left join weaponry b on a.hero=b.hero and a.weapon=b.weapon
    where a.weapon <> 'Sword'
</code>```

But this just returns all non-sword heroes (including Wonder Woman and Gamora), since all wield weapons other than swords.

Would you please help me rewrite the NOT IN query with either the NOT EXISTS or the LEFT JOIN?

EDIT: Left Join and the correlated subquery

@JeffUK suggested in his comments that one could understand the correlated subquery better by removing the WHERE clause. Here's a small modification to the select with the where removed.

```<code>select distinct a.hero, weaponryInner.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero
</code>```

The results are two columns of heroes, some of which are NULL.

```<code>-------------------------------
Hero          |  Hero
-------------------------------
Wonder Woman  |  Wonder Woman
Gamora        |  Gamora
Spider Man    |  <null>
Batman        |  <null>
-------------------------------
</code>```

So adding the final where weaponryInner.Weapon is null will return just Spider Man and Batman.

答:
First one you are checking for the existence of any sword wielding heros, you need to check only for the 'current' hero wielding a sword.

```<code>select distinct hero from weaponry as a
  where not exists
  (select * from weaponry as b where b.weapon = 'Sword' and b.hero = a.hero )
</code>```

The second won't work for you, a join works on each row independently, so will do exactly what you're seeing. You could do something like this, a bit more complex but does the job.

We find only the heros with swords in the subquery, and join that to all heros,  any heros with a 'NULL' weren't found in the subquery, therefore never wield swords.

```<code>select distinct a.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero
where weaponryInner.Weapon is null
</code>```

Title: Converting a working SQL NOT IN

Body:
I have some SQL to tell me the superheroes who don't ever wield a sword.

Creating the table

First, here is the (MySQL) script to create and populate the table.

CREATE TABLE IF NOT EXISTS `mydb`.`weaponry` (
  `hero` VARCHAR(20) NULL,
  `weapon` VARCHAR(20) NULL)
ENGINE = InnoDB

insert into weaponry (hero, weapon) values ('Wonder Woman', 'Lasso of truth');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Sword');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Shield');
insert into weaponry (hero, weapon) values ('Spider Man', 'Web');
insert into weaponry (hero, weapon) values ('Gamora', 'Sword');
insert into weaponry (hero, weapon) values ('Gamora', 'Daggar');
insert into weaponry (hero, weapon) values ('Batman', 'Batarang');
insert into weaponry (hero, weapon) values ('Batman', 'Batgrapple');
insert into weaponry (hero, weapon) values ('Batman', 'Tranquilizer gun');

Working code using a NOT IN and a subselect

select distinct hero from weaponry
  where hero not in
  (select hero from weaponry where weapon = 'Sword')

This correctly returns Spider Man and Batman, who don't wield a sword.

Alternative 1: Using NOT EXISTS

I would like to implement the same query using NOT EXISTS.
I looked at https://stackoverflow.com/a/5231731/509840.
I tried this:

select distinct hero from weaponry
  where not exists
  (select * from weaponry where weapon = 'Sword')

Unfortunately, this returns no rows.

Alternative 2: Using LEFT JOIN

I also took a look at this answer: https://stackoverflow.com/a/17413996/509840 .
I was curious to try replacing the NOT IN with a LEFT JOIN.

  select * from weaponry a
    left join weaponry b on a.hero=b.hero and a.weapon=b.weapon
    where a.weapon <> 'Sword'

But this just returns all non-sword heroes (including Wonder Woman and Gamora), since all wield weapons other than swords.

Would you please help me rewrite the NOT IN query with either the NOT EXISTS or the LEFT JOIN?

EDIT: Left Join and the correlated subquery

@JeffUK suggested in his comments that one could understand the correlated subquery better by removing the WHERE clause. Here's a small modification to the select with the where removed.

select distinct a.hero, weaponryInner.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero

The results are two columns of heroes, some of which are NULL.

-------------------------------
Hero          |  Hero
-------------------------------
Wonder Woman  |  Wonder Woman
Gamora        |  Gamora
Spider Man    |  <null>
Batman        |  <null>
-------------------------------

So adding the final where weaponryInner.Weapon is null will return just Spider Man and Batman.

Body:
First one you are checking for the existence of any sword wielding heros, you need to check only for the 'current' hero wielding a sword.

select distinct hero from weaponry as a
  where not exists
  (select * from weaponry as b where b.weapon = 'Sword' and b.hero = a.hero )

The second won't work for you, a join works on each row independently, so will do exactly what you're seeing. You could do something like this, a bit more complex but does the job.

We find only the heros with swords in the subquery, and join that to all heros,  any heros with a 'NULL' weren't found in the subquery, therefore never wield swords.

select distinct a.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero
where weaponryInner.Weapon is null