问:
Reusing DTO for various request/response types vs explicitness of what is required / what should be returned
I started wondering on whether I am not falling into an antipattern here, so please advise on the best practices.

I am designing a REST API with a set of various endpoints and I wanted to wrap the request & response parameters into nice DTO.

For example, a few endpoints:

```<code>public async Task<JobStateResponse> GetJobState(JobStateRequest request);
public async Task<JobDownloadRespose> DownloadJob(JobDownloadRequest request);
public async Task<CreateJobResponse> CreateJob(CreateJobRequest request);
</code>```

The problem is that these requests and responses are relatively similar DTO, for example:

```<code>public class JobStateResponse{
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public State State {get;set;}
}
public class JobDownloadResponse {
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public string JobContent {get;set;}
}
</code>```

I thought about creating a base class for these and inheriting, but in some cases some of the properties can be redundant...
Which means that the methods don't clearly indicate what parameters are needed for them to work OK.

I mean, exposing an API endpoint with a DTO parameter that has 7 properties but only really needs 2 sounds pretty bad...

On the other hand, maintaining separate DTOs for most of the endpoints seems like an overkill as well, and also a maintenance hell.

And also the last thing I want is a complex relationship of several base-base classes for the requests as this may be an even worse maintentance problem.

So, what is the proper approach for request<>response handling?

EDIT:
Regarding the 'opinion based' flags - I am looking for best practice for handling this. I know it can be done in multiple ways, but I want to avoid a landmine / antipattern. Also, I gotta say I am pretty happy with the answers so far.

答:
Separate, simple DTOs will make your life infinitely easier.  It will require more code, but it will be boring, simple code, that is easily tested, and allows your interfaces to change and evolve independently.

Make a DTO for each request endpoint and a separate DTO for each response.  Otherwise, you will eventually be sad.

If you find elements that are common to multiple endpoints, extract them into their own object, and include them in both.

And yes, using inheritance here would be wrong.  Stick to compositional patterns and you will be fine.

Body:
I started wondering on whether I am not falling into an antipattern here, so please advise on the best practices.

I am designing a REST API with a set of various endpoints and I wanted to wrap the request & response parameters into nice DTO.

For example, a few endpoints:

public async Task<JobStateResponse> GetJobState(JobStateRequest request);
public async Task<JobDownloadRespose> DownloadJob(JobDownloadRequest request);
public async Task<CreateJobResponse> CreateJob(CreateJobRequest request);

The problem is that these requests and responses are relatively similar DTO, for example:

public class JobStateResponse{
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public State State {get;set;}
}
public class JobDownloadResponse {
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public string JobContent {get;set;}
}

I thought about creating a base class for these and inheriting, but in some cases some of the properties can be redundant...
Which means that the methods don't clearly indicate what parameters are needed for them to work OK.

I mean, exposing an API endpoint with a DTO parameter that has 7 properties but only really needs 2 sounds pretty bad...

On the other hand, maintaining separate DTOs for most of the endpoints seems like an overkill as well, and also a maintenance hell.

And also the last thing I want is a complex relationship of several base-base classes for the requests as this may be an even worse maintentance problem.

So, what is the proper approach for request<>response handling?

EDIT:
Regarding the 'opinion based' flags - I am looking for best practice for handling this. I know it can be done in multiple ways, but I want to avoid a landmine / antipattern. Also, I gotta say I am pretty happy with the answers so far.


来源: stackexchange

问:
How to wrap Web Worker response messages in futures?
Please consider a scala.js application which runs in the browser and consists of a main program and a web worker.

The main thread delegates long running operations to the web worker by passing messages that contain the names of methods and the parameters required to invoke them.  The worker passes method return values back to the main thread in the form of response messages.

In simpler terms, this program abstracts web worker messaging so that code in the main thread can call methods in the worker thread in idiomatic and asynchronous Scala syntax.

Because web workers do not associate messages with their responses in any way, the abstraction relies on a registry, an intermediary object, that governs each cross context method call to associate the invocation with the result.  This singleton could also bind callback functions but is there a way to accomplish this with futures instead of callbacks?

How can I build an abstraction over this registry that allows programmers to use it with the standard asynchronous programming structures in Scala: futures and promises?

How should I write this functionality so that scala programmers can interact with it in the canonical way?  For example:

```<code>// long running method in the web worker
val f: Future[String] = Registry.ultimateQuestion(42) // async

f onSuccess { case q => println("The ultimate question is: " + q) }
</code>```

I'm new to futures and promises, but it seems like they usually complete when some execution block terminates.  In this case, receiving a response from the web worker signifies completion of the future.  Is there a way to write a custom future that delegates its completion status to an external process?  Is there another way to link the web worker response message to the status of the future?

Can/Should I extend the Future trait?  Is this possible in Scala.js?  Is there a concrete class that I should extend?  Is there some other way to encapsulate these cross context web worker method calls in existing asynchronous Scala functionality?

Thank you for your consideration.

答:
Hmm. Just spitballing here (I haven't used workers yet), but it seems like associating the request with the Future is fairly easy in the single-threaded JavaScript world you're working in.

Here's a hypothetical design. Say that each request/response to the worker is automatically wrapped in an Envelope; the Envelope contains a RequestId. So the send side looks something like (this is pseudo-code, but real-ish):

```<code>def sendRequest[R](msg:Message):Future[R] = {
  val promise = Promise[R]
  val id = nextRequestId()
  val envelope = Envelope(id, msg)
  register(id, promise)
  sendToWorker(envelope)
  promise.future
}
</code>```

The worker processes msg, wraps the result in another Envelope, and the result gets handled back in the main thread with something like:

```<code>def handleResult(resultEnv:Envelope):Unit = {
  val promise = findRegistered(resultEnv.id)
  val result = resultEnv.msg
  promise.success(result)
}
</code>```

That needs some filling in, and some thought about what the types like R should be, but that sort of outline would probably work decently well. If this was the JVM you'd have to worry about all sorts of race conditions, but in the single-threaded JS world it probably can be as simple as using an autoincrementing integer for the request ID, and storing away the Promise...

ContentLicense: CC BY-SA 3.0

Body:
Please consider a scala.js application which runs in the browser and consists of a main program and a web worker.

The main thread delegates long running operations to the web worker by passing messages that contain the names of methods and the parameters required to invoke them.  The worker passes method return values back to the main thread in the form of response messages.

In simpler terms, this program abstracts web worker messaging so that code in the main thread can call methods in the worker thread in idiomatic and asynchronous Scala syntax.

Because web workers do not associate messages with their responses in any way, the abstraction relies on a registry, an intermediary object, that governs each cross context method call to associate the invocation with the result.  This singleton could also bind callback functions but is there a way to accomplish this with futures instead of callbacks?

How can I build an abstraction over this registry that allows programmers to use it with the standard asynchronous programming structures in Scala: futures and promises?

How should I write this functionality so that scala programmers can interact with it in the canonical way?  For example:

// long running method in the web worker
val f: Future[String] = Registry.ultimateQuestion(42) // async

f onSuccess { case q => println("The ultimate question is: " + q) }

I'm new to futures and promises, but it seems like they usually complete when some execution block terminates.  In this case, receiving a response from the web worker signifies completion of the future.  Is there a way to write a custom future that delegates its completion status to an external process?  Is there another way to link the web worker response message to the status of the future?

Can/Should I extend the Future trait?  Is this possible in Scala.js?  Is there a concrete class that I should extend?  Is there some other way to encapsulate these cross context web worker method calls in existing asynchronous Scala functionality?

Thank you for your consideration.

Body:
Hmm. Just spitballing here (I haven't used workers yet), but it seems like associating the request with the Future is fairly easy in the single-threaded JavaScript world you're working in.

Here's a hypothetical design. Say that each request/response to the worker is automatically wrapped in an Envelope; the Envelope contains a RequestId. So the send side looks something like (this is pseudo-code, but real-ish):

def sendRequest[R](msg:Message):Future[R] = {
  val promise = Promise[R]
  val id = nextRequestId()
  val envelope = Envelope(id, msg)
  register(id, promise)
  sendToWorker(envelope)
  promise.future
}

The worker processes msg, wraps the result in another Envelope, and the result gets handled back in the main thread with something like:

def handleResult(resultEnv:Envelope):Unit = {
  val promise = findRegistered(resultEnv.id)
  val result = resultEnv.msg
  promise.success(result)
}

That needs some filling in, and some thought about what the types like R should be, but that sort of outline would probably work decently well. If this was the JVM you'd have to worry about all sorts of race conditions, but in the single-threaded JS world it probably can be as simple as using an autoincrementing integer for the request ID, and storing away the Promise...


问:
How to read a character from standard input in DOS such that redirection works?
I am currently writing a DOS program. In this program, I use service 21/AH=01 to read a character from standard input. However, it appears that when I redirect standard input from a file, EOF detection does not work as expected. I wrote this sample program in nasm syntax to illustrate the issue:

```<code>    org 0x100

    ; read characters and sum them up
main:   xor bx,bx

.1: mov ah,1
    int 0x21
    xor ah,ah
    add bx,ax
    cmp al,0x1a       ; eof reached?
    jnz .1

    mov cx,4
.2: mov si,bx
    shr si,12
    mov dl,[hextab+si] ; convert to hex
    mov ah,2
    int 0x21
    shl bx,4
    loop .2

    ret

hextab: db '0123456789ABCDEF'
</code>```

When I redirect standard input from a file, the program hangs unless that file contains a ^Z somewhere. I was under the impression that EOF is marked with service 21/AH=01 returning ^Z in DOS, however, that does not seem to be the case.

How do I read a character from standard input in DOS in a way that works with redirected stdin such that the character is echoed to the screen in case input is not redirected and such that I can detect an EOF condition? Ideally, I would like to have something that behaves like the getchar() function.

答:
You should use the MS-DOS "read" function instead.  In general you want to avoid the old obsolete MS-DOS 1.x API functions.  The output functions (AH=1, AH=9) are usually OK, but most of the rest shouldn't be used unless you need your program to run under MS-DOS 1. MS-DOS 2.0 introduced a whole new set of Unix-like file functions that for the most part work just like the equivalent Unix function. So in this case MS-DOS read function, just like the Unix read system call, takes three parameters: a file handle, the address of a buffer and the number of characters to read. Just like with Unix, file handle 0 is for standard input, 1 is for standard output and 2 is for standard error.

So you could rewrite your example to use the MS-DOS read (AH=3Fh) and write (AH=40h) functions like this:

```<code>    ORG 0x100

main:
    xor di, di
    mov bp, buf
    mov dx, bp
    mov cx, 1

loopchar:
    mov ah, 0x3f
    int 21h
    jc  error
    dec ax
    js  eof           ; EOF reached?
    cmp BYTE [bp], 0x1a
    je  eof
    add di, [bp]
    jmp loopchar

eof:
    inc cx
    mov ax, di
    mov al, ah
    call printhex1
    jc  error
    xchg ax, di

printhex1:
    mov bx, hextab
    aam 16
    xlat
    mov [bp + 1], al
    mov al, ah
    xlat
    mov [bp], al
    mov bx, 1
    mov ah, 0x40
    int 21h

error:
    ret

buf db  0, 0

hextab: db '0123456789ABCDEF'
</code>```

Body:
I am currently writing a DOS program. In this program, I use service 21/AH=01 to read a character from standard input. However, it appears that when I redirect standard input from a file, EOF detection does not work as expected. I wrote this sample program in nasm syntax to illustrate the issue:

    org 0x100

    ; read characters and sum them up
main:   xor bx,bx

.1: mov ah,1
    int 0x21
    xor ah,ah
    add bx,ax
    cmp al,0x1a       ; eof reached?
    jnz .1

    mov cx,4
.2: mov si,bx
    shr si,12
    mov dl,[hextab+si] ; convert to hex
    mov ah,2
    int 0x21
    shl bx,4
    loop .2

    ret

hextab: db '0123456789ABCDEF'

When I redirect standard input from a file, the program hangs unless that file contains a ^Z somewhere. I was under the impression that EOF is marked with service 21/AH=01 returning ^Z in DOS, however, that does not seem to be the case.

How do I read a character from standard input in DOS in a way that works with redirected stdin such that the character is echoed to the screen in case input is not redirected and such that I can detect an EOF condition? Ideally, I would like to have something that behaves like the getchar() function.

Body:
You should use the MS-DOS "read" function instead.  In general you want to avoid the old obsolete MS-DOS 1.x API functions.  The output functions (AH=1, AH=9) are usually OK, but most of the rest shouldn't be used unless you need your program to run under MS-DOS 1. MS-DOS 2.0 introduced a whole new set of Unix-like file functions that for the most part work just like the equivalent Unix function. So in this case MS-DOS read function, just like the Unix read system call, takes three parameters: a file handle, the address of a buffer and the number of characters to read. Just like with Unix, file handle 0 is for standard input, 1 is for standard output and 2 is for standard error.

So you could rewrite your example to use the MS-DOS read (AH=3Fh) and write (AH=40h) functions like this:

    ORG 0x100

main:
    xor di, di
    mov bp, buf
    mov dx, bp
    mov cx, 1

loopchar:
    mov ah, 0x3f
    int 21h
    jc  error
    dec ax
    js  eof           ; EOF reached?
    cmp BYTE [bp], 0x1a
    je  eof
    add di, [bp]
    jmp loopchar

eof:
    inc cx
    mov ax, di
    mov al, ah
    call printhex1
    jc  error
    xchg ax, di

printhex1:
    mov bx, hextab
    aam 16
    xlat
    mov [bp + 1], al
    mov al, ah
    xlat
    mov [bp], al
    mov bx, 1
    mov ah, 0x40
    int 21h

error:
    ret

buf db  0, 0

hextab: db '0123456789ABCDEF'


问:
clean up the header of csv files with awk
I have a bunch of csv files that look like this:

```<code>Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

And I want to transform it to:

```<code>Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

The units are not necessarily identical across files (i.e. there might be (ms),(µV) etc.)

I got as far as removing the blank line (which is always line no. 3) with awk 'FNR!=3' but cutting the 2nd row arguments and pasting them behind the first row fields is beyond my capacity ;(

Please help me out!
Motivation: there are lots of these files. Doing it by hand is not feasible…

EDIT:
First of all: thanks for helping me out. As there seems to be the same issue with 2 of your answers, there might be a problem in my file potentially? I suspect the empty line to somehow cause trouble?

the shell-script gives me the error 'xpected empty line, read '

the perl-script and the awk-script give me a faulty first line:

```<code> (V) (s),Channel A
0.00000000,0.58058560
</code>```

If it helps, I uploaded a sample infile.

答:
Should you decide to stay in bash, here's a script that will perform error checking for you

```<code>#!/usr/bin/env bash

function Error() { 1>&2 echo "$@"; }

function cleanup_csv() {
    IFS=$',\r' read -a Header || { Error "could not read header"; return 1; }
    IFS=$',\r' read -a Units || { Error "could not read units"; return 1; }
    declare -r NCols=${#Header[@]}
    declare -r n_units=${#Units[@]}

    [[ $NCols -eq $n_units ]] || {
        Error "number of columns in Header ($NCols) not equal to Units ($n_units)"
        return 1
    }

    if IFS=$' \t\r' read -a words; then
        if [[ $(echo "${words[*]}") ]]; then
            Error "expected empty line, read '${words[*]}'"
            return 1
        fi
    else
        Error "could not read line 3, expected empty line"
        return 1
    fi

    local i= sep=
    for ((i=0; i<NCols; ++i)); do
        printf "%s" "$sep${Header[i]} ${Units[i]}"
        sep=,
    done
    printf "\n"
    cat
}

cleanup_csv "$@"
</code>```

Given a file 'in' with your sample input

```<code>Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

and invoked like this

```<code>./cleanup_csv.sh < in
</code>```

it produces the desired output

```<code>Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

I also tested it with more than two columns

```<code>Time,Channel A,Channel B
(s),(V),(mV)

0.00000000,0.58058560,12.34
0.00666667,0.58913630,3.1415
0.02000002,0.58058560,0.913
</code>```

And that works as well

```<code>Time (s),Channel A (V),Channel B (mV)
0.00000000,0.58058560,12.34
0.00666667,0.58913630,3.1415
0.02000002,0.58058560,0.913
</code>```

Edit:

I updated the reading and detection of the empty line because your input has Windows style line endings (CRLF).  You can see the carriage return using od -xc.  I went ahead and added tab characters to the set of characters to use as field separators (IFS), I then look to see if any non-whitespace characters are left after echo.

Here's the hex dump of the input I tested (with added space and tab in the 'empty' line):

```<code>$ od -xc in.csv
0000000    6954    656d    432c    6168    6e6e    6c65    4120    0a0d
          T   i   m   e   ,   C   h   a   n   n   e   l       A  \r  \n
0000020    7328    2c29    5628    0d29    200a    2009    0d20    300a
          (   s   )   ,   (   V   )  \r  \n      \t          \r  \n   0
0000040    302e    3030    3030    3030    2c30    2e30    3835    3530
          .   0   0   0   0   0   0   0   0   ,   0   .   5   8   0   5
0000060    3538    3036    0a0d    2e30    3030    3636    3636    3736
          8   5   6   0  \r  \n   0   .   0   0   6   6   6   6   6   7
0000100    302c    352e    3938    3331    3336    0d30    300a    302e
          ,   0   .   5   8   9   1   3   6   3   0  \r  \n   0   .   0
0000120    3331    3333    3333    2c34    2e30    3835    3530    3538
          1   3   3   3   3   3   4   ,   0   .   5   8   0   5   8   5
0000140    3036    0a0d    2e30    3230    3030    3030    3230    302c
          6   0  \r  \n   0   .   0   2   0   0   0   0   0   2   ,   0
0000160    352e    3038    3835    3635    0d30    300a    302e    3632
          .   5   8   0   5   8   5   6   0  \r  \n   0   .   0   2   6
0000200    3636    3636    2c39    2e30    3835    3139    3633    3033
          6   6   6   6   9   ,   0   .   5   8   9   1   3   6   3   0
0000220    0a0d    2e30    3330    3333    3333    3633    302c    352e
         \r  \n   0   .   0   3   3   3   3   3   3   6   ,   0   .   5
0000240    3938    3331    3336    0d30    300a    302e    3034    3030
          8   9   1   3   6   3   0  \r  \n   0   .   0   4   0   0   0
0000260    3030    2c33    2e30    3835    3139    3633    3033    0a0d
          0   0   3   ,   0   .   5   8   9   1   3   6   3   0  \r  \n
0000300
</code>```

Body:
I have a bunch of csv files that look like this:

Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

And I want to transform it to:

Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

The units are not necessarily identical across files (i.e. there might be (ms),(µV) etc.)

I got as far as removing the blank line (which is always line no. 3) with awk 'FNR!=3' but cutting the 2nd row arguments and pasting them behind the first row fields is beyond my capacity ;(

Please help me out!
Motivation: there are lots of these files. Doing it by hand is not feasible…

EDIT:
First of all: thanks for helping me out. As there seems to be the same issue with 2 of your answers, there might be a problem in my file potentially? I suspect the empty line to somehow cause trouble?

the shell-script gives me the error 'xpected empty line, read '

the perl-script and the awk-script give me a faulty first line:

 (V) (s),Channel A
0.00000000,0.58058560

If it helps, I uploaded a sample infile.

Body:
Should you decide to stay in bash, here's a script that will perform error checking for you

#!/usr/bin/env bash

function Error() { 1>&2 echo "$@"; }

function cleanup_csv() {
    IFS=$',\r' read -a Header || { Error "could not read header"; return 1; }
    IFS=$',\r' read -a Units || { Error "could not read units"; return 1; }
    declare -r NCols=${#Header[@]}
    declare -r n_units=${#Units[@]}

    [[ $NCols -eq $n_units ]] || {
        Error "number of columns in Header ($NCols) not equal to Units ($n_units)"
        return 1
    }

    if IFS=$' \t\r' read -a words; then
        if [[ $(echo "${words[*]}") ]]; then
            Error "expected empty line, read '${words[*]}'"
            return 1
        fi
    else
        Error "could not read line 3, expected empty line"
        return 1
    fi

    local i= sep=
    for ((i=0; i<NCols; ++i)); do
        printf "%s" "$sep${Header[i]} ${Units[i]}"
        sep=,
    done
    printf "\n"
    cat
}

cleanup_csv "$@"

Given a file 'in' with your sample input

Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

and invoked like this

./cleanup_csv.sh < in

it produces the desired output

Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

I also tested it with more than two columns

Time,Channel A,Channel B
(s),(V),(mV)

0.00000000,0.58058560,12.34
0.00666667,0.58913630,3.1415
0.02000002,0.58058560,0.913

And that works as well

Time (s),Channel A (V),Channel B (mV)
0.00000000,0.58058560,12.34
0.00666667,0.58913630,3.1415
0.02000002,0.58058560,0.913

Edit:

I updated the reading and detection of the empty line because your input has Windows style line endings (CRLF).  You can see the carriage return using od -xc.  I went ahead and added tab characters to the set of characters to use as field separators (IFS), I then look to see if any non-whitespace characters are left after echo.

Here's the hex dump of the input I tested (with added space and tab in the 'empty' line):

$ od -xc in.csv
0000000    6954    656d    432c    6168    6e6e    6c65    4120    0a0d
          T   i   m   e   ,   C   h   a   n   n   e   l       A  \r  \n
0000020    7328    2c29    5628    0d29    200a    2009    0d20    300a
          (   s   )   ,   (   V   )  \r  \n      \t          \r  \n   0
0000040    302e    3030    3030    3030    2c30    2e30    3835    3530
          .   0   0   0   0   0   0   0   0   ,   0   .   5   8   0   5
0000060    3538    3036    0a0d    2e30    3030    3636    3636    3736
          8   5   6   0  \r  \n   0   .   0   0   6   6   6   6   6   7
0000100    302c    352e    3938    3331    3336    0d30    300a    302e
          ,   0   .   5   8   9   1   3   6   3   0  \r  \n   0   .   0
0000120    3331    3333    3333    2c34    2e30    3835    3530    3538
          1   3   3   3   3   3   4   ,   0   .   5   8   0   5   8   5
0000140    3036    0a0d    2e30    3230    3030    3030    3230    302c
          6   0  \r  \n   0   .   0   2   0   0   0   0   0   2   ,   0
0000160    352e    3038    3835    3635    0d30    300a    302e    3632
          .   5   8   0   5   8   5   6   0  \r  \n   0   .   0   2   6
0000200    3636    3636    2c39    2e30    3835    3139    3633    3033
          6   6   6   6   9   ,   0   .   5   8   9   1   3   6   3   0
0000220    0a0d    2e30    3330    3333    3333    3633    302c    352e
         \r  \n   0   .   0   3   3   3   3   3   3   6   ,   0   .   5
0000240    3938    3331    3336    0d30    300a    302e    3034    3030
          8   9   1   3   6   3   0  \r  \n   0   .   0   4   0   0   0
0000260    3030    2c33    2e30    3835    3139    3633    3033    0a0d
          0   0   3   ,   0   .   5   8   9   1   3   6   3   0  \r  \n
0000300


问:
Setting up recurrence relation
I am given this question:

Algorithm Mystery1(A[0...n-1])
//Input: An array A[0...n-1] of n real numbers
if (n = 1) return A[0]
else temp = Mystery1(A[0...n-2])
  if temp <= A[n - 1] return temp
  else return A[n - 1]
```

(a) What does this algorithm compute?

(b) Set up and solve a recurrence relation for the number of times the algorithm’s basic operation
is executed.

For part (a) I know that this algorithm computes the smallest element in an array. For part (b), I believe that the basic operation is a comparison, since it will be done the most amount of times, but i can't figure out how to set up the recurrence relation.

I understand how to solve a recurrence relation, i just need help setting up the problem.

答:
The recurrence expression should be:

```<code>T[n] = T[n-1] + O(1)
</code>```

Calculating the above expression the time complexity comes out to be O(n).

Title: Setting up recurrence relation

Body:
I am given this question:

Algorithm Mystery1(A[0...n-1])
//Input: An array A[0...n-1] of n real numbers
if (n = 1) return A[0]
else temp = Mystery1(A[0...n-2])
  if temp <= A[n - 1] return temp
  else return A[n - 1]

(a) What does this algorithm compute?

(b) Set up and solve a recurrence relation for the number of times the algorithm’s basic operation
is executed.

For part (a) I know that this algorithm computes the smallest element in an array. For part (b), I believe that the basic operation is a comparison, since it will be done the most amount of times, but i can't figure out how to set up the recurrence relation.

I understand how to solve a recurrence relation, i just need help setting up the problem.

Body:
The recurrence expression should be:

T[n] = T[n-1] + O(1)

Calculating the above expression the time complexity comes out to be O(n).


问:
virtualenv & subprocess: How to get the correct path to a script
When someone installs my Python package, they can use the command mycmd (it's a console script added to the python bin/ directory). In turn, mycmd launches several other Python console scripts using subprocess:

subprocess.Process('celery arg1 arg2')
subprocess.Process('huey arg1 arg2')
...

(celery and huey commands are installed through my package's pip dependencies.)

This generally works fine, except in the situation where someone invokes mycmd directly without activating its virtualenv. For example, I am trying to use mycmd inside the process control system "circusd". See here where the circus.ini file invokes venv/bin/chaussette directly, without actually activating the venv. If I do this, I get the message celery: No such file or directory, I presume because the virtualenv is not activated and therefore those commands are not found on the path.

How can I ensure that when someone runs mycmd, the correct celery gets run, even if the virtualenv was not activated? (And should also work if the person is not using virtualenv at all, and cross-platform, etc.)

By the way, I am not using subprocess.Process directly, but rather using Honcho, which provides a layer around it.

答: I solved this simply by adding my virtualenv bin path to the PATH used by circus.


问:
How can I use Pygame on atom editor?
I already installed the latest version of Python 3 and I installed Pygame using the terminal I also included import Pygame in my file however when I run the file it refuses to open and displays the error message "no module named pygame"
What's the problem?
What's the solution?

答:
Try  python3 first.py in your terminal.

Or in your file first.py add this line at the top:
(I used python3.x but you should add the correct version of your python 3)

```<code>#!/usr/local/bin/python3.x
</code>```

To see your version:

```<code>$ python3 -V
Python 3.5.2
</code>```

To see your python 3 path:

```<code> $ which python3
</code>```

Title: How can I use Pygame on atom editor?

Body:
Try  python3 first.py in your terminal.

Or in your file first.py add this line at the top:
(I used python3.x but you should add the correct version of your python 3)

#!/usr/local/bin/python3.x

To see your version:

$ python3 -V
Python 3.5.2

To see your python 3 path:

 $ which python3


问:
How To Add New fxml to Controller
I have 2 .fxml files (FXMLDocument.fxml/login.fxml) and one controller file (FXMLDocumentController). I want to remove FXMLDocument.fxml from the controller and add login.fxml to the contoller.

When I call the main method, I want get prompted with the login form instead of FXMLDocument.fxml.

Any idea what is happening?

PS: login.fxml is created using SceneBuilder.

答:
You don't have to use the default FXML file generated by your IDE. Here is a basic controller that will use login.fxml:

```<code>public class LoginController {

    public LoginController(){
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("login.fxml"));
            fxmlLoader.setController(this);
            fxmlLoader.load();
        } catch (IOException exception) {
            System.out.println("Error loading content.");
            System.exit(0);
        }
    }

}
</code>```

Note the line with FXMLLoader(getClass().getResource("login.fxml")). This is how you add an FXML file to a controller.

Title: How To Add New fxml to Controller

Body:
You don't have to use the default FXML file generated by your IDE. Here is a basic controller that will use login.fxml:

public class LoginController {

    public LoginController(){
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("login.fxml"));
            fxmlLoader.setController(this);
            fxmlLoader.load();
        } catch (IOException exception) {
            System.out.println("Error loading content.");
            System.exit(0);
        }
    }

}

Note the line with FXMLLoader(getClass().getResource("login.fxml")). This is how you add an FXML file to a controller.


问:
Parameter Paradox? (not sure how to word)
So I'm not sure how to word this so I'll just give an example here:

```<code>public class test {
    private Object1 o1;
    private Object2 o2;
    private Object3 o3;

    public test() {
        o1 = new Object1(o2, o3);
        o2 = new Object2(o1);
        o3 = new Object3(o1);
    }
}
</code>```

So my problem is that I need to give these 3 objects parameters these ways and I get problems because when I put o2 and o3 for o1, they are null. If I try to instantiate o2 and o3 above o1, o1 is null and problems occur again. Could someone help me find a solution to this. I would also like to keep these 3 objects separate (ie. not give o2 or o3 an o1 field).

答:
You are facing with circular dependency
that you need to avoid at all cost.

For your immediate need you can make constructor not to take depended objects, define set methods, create objects with empty constructor and then wire them together by passing objects to those set methods.

```<code>public class test {
        private Object1 o1;
        private Object2 o2;
        private Object3 o3;

        public test() {
            o1 = new Object1();
            o2 = new Object2();
            o3 = new Object3();

            o1.setO2(o2);
            o1.setO3(o3);

            o2.setO1(o1);
            o3.setO1(o1);

        }
    }
</code>```

Body:
So I'm not sure how to word this so I'll just give an example here:

public class test {
    private Object1 o1;
    private Object2 o2;
    private Object3 o3;

    public test() {
        o1 = new Object1(o2, o3);
        o2 = new Object2(o1);
        o3 = new Object3(o1);
    }
}

So my problem is that I need to give these 3 objects parameters these ways and I get problems because when I put o2 and o3 for o1, they are null. If I try to instantiate o2 and o3 above o1, o1 is null and problems occur again. Could someone help me find a solution to this. I would also like to keep these 3 objects separate (ie. not give o2 or o3 an o1 field).

Body:
You are facing with circular dependency
that you need to avoid at all cost.

For your immediate need you can make constructor not to take depended objects, define set methods, create objects with empty constructor and then wire them together by passing objects to those set methods.

public class test {
        private Object1 o1;
        private Object2 o2;
        private Object3 o3;

        public test() {
            o1 = new Object1();
            o2 = new Object2();
            o3 = new Object3();

            o1.setO2(o2);
            o1.setO3(o3);

            o2.setO1(o1);
            o3.setO1(o1);

        }
    }


问:
R ggplot ordering bars within groups
I'm attempting to format a grouped bar plot in R with ggplot such that bars are in decreasing order per group. This is my current plot:

based on this data frame:

```<code>> top_categories
                    Category Count Community
1         Singer-Songwriters   151         1
2          Adult Alternative   147         1
3                  Dance Pop    95         1
4                       Folk    89         1
5         Adult Contemporary    88         1
6                    Pop Rap   473         2
7         Gangsta & Hardcore   413         2
8                       Soul   175         2
9                 East Coast   170         2
10                West Coast   135         2
11 Album-Oriented Rock (AOR)   253         3
12        Singer-Songwriters   217         3
13                 Soft Rock   196         3
14                      Folk   145         3
15        Adult Contemporary   106         3
16                      Soul   278         4
17                     Blues   137         4
18                      Funk   119         4
19               Quiet Storm    76         4
20                 Dance Pop    74         4
21             Indie & Lo-Fi   235         5
22                Indie Rock   234         5
23         Adult Alternative   114         5
24          Alternative Rock    49         5
25        Singer-Songwriters    47         5
</code>```

created with this code:

```<code>ggplot(
  top_categories,
  aes(
    x=Community,
    y=Count,
    group=Category,
    label=Category
  )
) +
  geom_bar(
    stat="identity",
    color="black",
    fill="#9C27B0",
    position="dodge"
  ) +
  geom_text(
    angle=90,
    position=position_dodge(width=0.9),
    hjust=-0.05
  ) +
  ggtitle("Number of Products in each Category in Each Community") +
  guides(fill=FALSE)
</code>```

Based on suggestions from related posts, I've attempted to use the reorder function and turn the Count into a factor, both with results that seem to break the ordering of the bars vs. the text or rescale the plot in a nonsensical way such as this (with factors):

Any tips on how I might accomplish this in-group ordering? Thanks!

答:
When you group by Category, the bars are ordered according to the order of appearance of Categories in the dataframe. This works fine for Community 1 and 2 as your rows are already ordered by decreasing Count. But in Community 3, as Category "Singer-Songwriters" is the first occcurring Category in the dataframe, it is put first.

Grouping instead by an Id variable resolves the problem:

```<code>top_categories$Id=rep(c(1:5),5)

ggplot(
  top_categories,
  aes(
    x=Community,
    y=Count,
    group=Id,
    label=Category
  )
) +
  geom_bar(
    stat="identity",
    color="black",
    fill="#9C27B0",
    position="dodge"
  ) +
  geom_text(
    angle=90,
    position=position_dodge(width=0.9),
    hjust=-0.05
  ) +
  ggtitle("Number of Products in each Category in Each Community") +
  guides(fill=FALSE)
</code>```

Title: R ggplot ordering bars within groups

Body:
I'm attempting to format a grouped bar plot in R with ggplot such that bars are in decreasing order per group. This is my current plot:

based on this data frame:

> top_categories
                    Category Count Community
1         Singer-Songwriters   151         1
2          Adult Alternative   147         1
3                  Dance Pop    95         1
4                       Folk    89         1
5         Adult Contemporary    88         1
6                    Pop Rap   473         2
7         Gangsta & Hardcore   413         2
8                       Soul   175         2
9                 East Coast   170         2
10                West Coast   135         2
11 Album-Oriented Rock (AOR)   253         3
12        Singer-Songwriters   217         3
13                 Soft Rock   196         3
14                      Folk   145         3
15        Adult Contemporary   106         3
16                      Soul   278         4
17                     Blues   137         4
18                      Funk   119         4
19               Quiet Storm    76         4
20                 Dance Pop    74         4
21             Indie & Lo-Fi   235         5
22                Indie Rock   234         5
23         Adult Alternative   114         5
24          Alternative Rock    49         5
25        Singer-Songwriters    47         5

created with this code:

ggplot(
  top_categories,
  aes(
    x=Community,
    y=Count,
    group=Category,
    label=Category
  )
) +
  geom_bar(
    stat="identity",
    color="black",
    fill="#9C27B0",
    position="dodge"
  ) +
  geom_text(
    angle=90,
    position=position_dodge(width=0.9),
    hjust=-0.05
  ) +
  ggtitle("Number of Products in each Category in Each Community") +
  guides(fill=FALSE)

Based on suggestions from related posts, I've attempted to use the reorder function and turn the Count into a factor, both with results that seem to break the ordering of the bars vs. the text or rescale the plot in a nonsensical way such as this (with factors):

Any tips on how I might accomplish this in-group ordering? Thanks!

Body:
When you group by Category, the bars are ordered according to the order of appearance of Categories in the dataframe. This works fine for Community 1 and 2 as your rows are already ordered by decreasing Count. But in Community 3, as Category "Singer-Songwriters" is the first occcurring Category in the dataframe, it is put first.

Grouping instead by an Id variable resolves the problem:

top_categories$Id=rep(c(1:5),5)

ggplot(
  top_categories,
  aes(
    x=Community,
    y=Count,
    group=Id,
    label=Category
  )
) +
  geom_bar(
    stat="identity",
    color="black",
    fill="#9C27B0",
    position="dodge"
  ) +
  geom_text(
    angle=90,
    position=position_dodge(width=0.9),
    hjust=-0.05
  ) +
  ggtitle("Number of Products in each Category in Each Community") +
  guides(fill=FALSE)


问:
Dealing with HTTP content in HTTPS pages
We have a site which is accessed entirely over HTTPS, but sometimes display external content which is HTTP (images from RSS feeds, mainly).  The vast majority of our users are also stuck on IE6.

I would ideally like to do both of the following

Prevent the IE warning message about insecure content (so that I can show a less intrusive one, e.g. by replacing the images with a default icon as below)

Present something useful to users in place of the images that they can't otherwise see; if there was some JS I could run to figure out which images haven't been loaded and replace them with an image of ours instead that would be great.

I suspect that the first aim is simply not possible, but the second may be sufficient.

A worst case scenario is that I parse the RSS feeds when we import them, grab the images store them locally so that the users can access them that way, but it seems like a lot of pain for reasonably little gain.

答:
If you're looking for a quick solution to load images over HTTPS then the free reverse proxy service at https://images.weserv.nl/ may interest you. It was exactly what I was looking for.

If you're looking for a paid solution, I have previously used Cloudinary.com which also works well but is too expensive solely for this task, in my opinion.

ContentLicense: CC BY-SA 2.5


问:
Don't know how to spawn multiple enemies
My code should spawn multiple enemies that chase around my player. Instead, the enemy just stays in one place. This only happens when I try to input a value into the enemy-spawning function for the spawn coordinates. Heres the code:

```<code>class spawn(object):
def __init__(self,place1,place2):
    self.place1=place1
    self.place2=place2
def AIPrototype(self):#The important parts to this error star here
    global x,y,x1,y1
    pygame.draw.rect(screen,THECOLORS['blue'],(self.place1,self.place2,50,50))
    x1=self.place1
    y1=self.place2#end here
    if x1<x:
        xspeed1=1
        slopex1=x-x1
    if x1>x:
        xspeed1=-1
        slopex1=x1-x
    if y1<y:
        yspeed1=1
        slopey1=y-y1
    if y1>y:
        yspeed1=-1
        slopey1=y1-y
#
    hypo1=((slopex1**2)+(slopey1**2))**0.5
    speedmark1=hypo1/3
    speedy1=slopey1/speedmark1
    speedx1=slopex1/speedmark1
    movex1=speedx1
    movey1=speedy1
    if x1<=640 and x1>=0:
        if x1>x:
            x1+=xspeed1*movex1
            if x1<x:
                xspeed1=0
    if y1<=480 and x1>=0:
        if y1>y:
            y1+=yspeed1*movey1
            if y1<y:
                yspeed1=0
    if x1<=640 and x1>=0:
        if x1<x:
            x1+=xspeed1*movex1
            if x1>x:
                xspeed1=0
    if y1<=480 and x1>=0:
        if y1<y:
            y1+=yspeed1*movey1
            if y1>y:
                yspeed1=0
#
    if x1>640:
        x1=640
    if x1<0:
        x1=0
    if y1>480:
        y1=480
    if y1<0:
        y1=0
    self.place1=x1#start
    self.place2=y1#end
</code>```

That's the fucntion for spawning the enemies. The fucntion is called here:

```<code>clock = pygame.time.Clock()
keepGoing = True

try:
    while keepGoing:
        clock.tick(60)

        screen.fill(THECOLORS['red'])
        pygame.draw.rect(screen,THECOLORS['green'],(x,y,50,50))
        char()
        spawn1=spawn(200,200)#start
        spawn1.AIPrototype()#end
        pygame.display.flip()
</code>```

I don't know where my error in the coding is, so if someone could help me out, that would be great.

答:
Here's an example with vectors. To get the velocity of the enemies, I calculate the vector to the player, then normalize it and scale by 4 (the final speed).

```<code>vel = (player.center - self.pos).normalize() * 4
</code>```

Then you can just add the velocity to the pos and set the rect.center to the updated pos vector to move the object.

To spawn new enemies, first create a list that should hold the enemy instances and then just append new instances when an enemy spawns (press the f-key to spawn them). You can also use pygame sprites and sprite groups instead of the Enemy class and the list.

```<code>import sys
import pygame as pg

class Enemy:

    def __init__(self, pos, color):
        self.rect = pg.Rect(pos, (26, 45))
        self.color = color
        self.pos = pg.math.Vector2(pos)

    def update(self, player):
        vel = (player.center - self.pos).normalize() * 4
        self.pos += vel
        self.rect.center = self.pos

    def draw(self, screen):
        pg.draw.rect(screen, self.color, self.rect)

def main():
    screen = pg.display.set_mode((640, 480))
    bg_color = pg.Color('gray12')
    player_color = pg.Color('dodgerblue1')
    enemy_color = pg.Color('sienna1')
    clock = pg.time.Clock()
    player = pg.Rect((100, 300), (26, 50))
    enemy_list = [Enemy((100, 300), enemy_color)]

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    enemy_list.append(Enemy((400, 0), enemy_color))

        keys = pg.key.get_pressed()
        if keys[pg.K_a]:
            player.x -= 5
        elif keys[pg.K_d]:
            player.x += 5
        if keys[pg.K_w]:
            player.y -= 5
        elif keys[pg.K_s]:
            player.y += 5

        for enemy in enemy_list:
            enemy.update(player)

        screen.fill(bg_color)
        pg.draw.rect(screen, player_color, player)
        for enemy in enemy_list:
            enemy.draw(screen)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()
</code>```

Body:
My code should spawn multiple enemies that chase around my player. Instead, the enemy just stays in one place. This only happens when I try to input a value into the enemy-spawning function for the spawn coordinates. Heres the code:

class spawn(object):
def __init__(self,place1,place2):
    self.place1=place1
    self.place2=place2
def AIPrototype(self):#The important parts to this error star here
    global x,y,x1,y1
    pygame.draw.rect(screen,THECOLORS['blue'],(self.place1,self.place2,50,50))
    x1=self.place1
    y1=self.place2#end here
    if x1<x:
        xspeed1=1
        slopex1=x-x1
    if x1>x:
        xspeed1=-1
        slopex1=x1-x
    if y1<y:
        yspeed1=1
        slopey1=y-y1
    if y1>y:
        yspeed1=-1
        slopey1=y1-y
#
    hypo1=((slopex1**2)+(slopey1**2))**0.5
    speedmark1=hypo1/3
    speedy1=slopey1/speedmark1
    speedx1=slopex1/speedmark1
    movex1=speedx1
    movey1=speedy1
    if x1<=640 and x1>=0:
        if x1>x:
            x1+=xspeed1*movex1
            if x1<x:
                xspeed1=0
    if y1<=480 and x1>=0:
        if y1>y:
            y1+=yspeed1*movey1
            if y1<y:
                yspeed1=0
    if x1<=640 and x1>=0:
        if x1<x:
            x1+=xspeed1*movex1
            if x1>x:
                xspeed1=0
    if y1<=480 and x1>=0:
        if y1<y:
            y1+=yspeed1*movey1
            if y1>y:
                yspeed1=0
#
    if x1>640:
        x1=640
    if x1<0:
        x1=0
    if y1>480:
        y1=480
    if y1<0:
        y1=0
    self.place1=x1#start
    self.place2=y1#end

That's the fucntion for spawning the enemies. The fucntion is called here:

clock = pygame.time.Clock()
keepGoing = True

try:
    while keepGoing:
        clock.tick(60)

        screen.fill(THECOLORS['red'])
        pygame.draw.rect(screen,THECOLORS['green'],(x,y,50,50))
        char()
        spawn1=spawn(200,200)#start
        spawn1.AIPrototype()#end
        pygame.display.flip()

I don't know where my error in the coding is, so if someone could help me out, that would be great.

Body:
Here's an example with vectors. To get the velocity of the enemies, I calculate the vector to the player, then normalize it and scale by 4 (the final speed).

vel = (player.center - self.pos).normalize() * 4

Then you can just add the velocity to the pos and set the rect.center to the updated pos vector to move the object.

To spawn new enemies, first create a list that should hold the enemy instances and then just append new instances when an enemy spawns (press the f-key to spawn them). You can also use pygame sprites and sprite groups instead of the Enemy class and the list.

import sys
import pygame as pg

class Enemy:

    def __init__(self, pos, color):
        self.rect = pg.Rect(pos, (26, 45))
        self.color = color
        self.pos = pg.math.Vector2(pos)

    def update(self, player):
        vel = (player.center - self.pos).normalize() * 4
        self.pos += vel
        self.rect.center = self.pos

    def draw(self, screen):
        pg.draw.rect(screen, self.color, self.rect)

def main():
    screen = pg.display.set_mode((640, 480))
    bg_color = pg.Color('gray12')
    player_color = pg.Color('dodgerblue1')
    enemy_color = pg.Color('sienna1')
    clock = pg.time.Clock()
    player = pg.Rect((100, 300), (26, 50))
    enemy_list = [Enemy((100, 300), enemy_color)]

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    enemy_list.append(Enemy((400, 0), enemy_color))

        keys = pg.key.get_pressed()
        if keys[pg.K_a]:
            player.x -= 5
        elif keys[pg.K_d]:
            player.x += 5
        if keys[pg.K_w]:
            player.y -= 5
        elif keys[pg.K_s]:
            player.y += 5

        for enemy in enemy_list:
            enemy.update(player)

        screen.fill(bg_color)
        pg.draw.rect(screen, player_color, player)
        for enemy in enemy_list:
            enemy.draw(screen)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()


问:
How can I resolve "Your bundle only supports platforms ["x86-mingw32"] but your local platforms are ["ruby", "x86_64-linux"]"
I'm building a rails site on a Windows machine but when I check in my Gemfile.lock I get the following error on my Travis builds:

```<code>Your bundle only supports platforms ["x86-mingw32"] but your local platforms are ["ruby", "x86_64-linux"], and there's no compatible match between those two
</code>```

lists

Here is the full log: https://travis-ci.org/bikebike/BikeBike/builds/222395810#L654

I looked at my Gemfile.lock and it states:

```<code>PLATFORMS
  x86-mingw32
</code>```

Which appears to be part of the issue. I've tried putting any windows specific gems in a platforms block:

```<code>platforms 'mswin', 'mingw', 'mswin64', 'x64_mingw' do
  gem 'tzinfo-data'

  group :test do
    gem 'wdm', '>= 0.1.0'
    gem 'win32console', require: false
  end
end
</code>```

But the Gemfile.lock looks the same.

Here is my full Gemfile and Gemfile.lock.

I can temporarily get around the issue by removing the Gemfile.lock file from git but this is not best practice. Is there anyway that I can commit my Gemfile.lock file and continue to develop on my Windows machine?

答:
Run the following two commands on the command line:

```<code>bundle lock --add-platform ruby
bundle lock --add-platform x86_64-linux
</code>```

This will add the two platforms in Gemfile.lock

I had the same error when deploying to google cloud. But after running these two commands ruby and x86_64-linux were added and the issue was resolved.

Body:
I'm building a rails site on a Windows machine but when I check in my Gemfile.lock I get the following error on my Travis builds:

Your bundle only supports platforms ["x86-mingw32"] but your local platforms are ["ruby", "x86_64-linux"], and there's no compatible match between those two

lists

Here is the full log: https://travis-ci.org/bikebike/BikeBike/builds/222395810#L654

I looked at my Gemfile.lock and it states:

PLATFORMS
  x86-mingw32

Which appears to be part of the issue. I've tried putting any windows specific gems in a platforms block:

platforms 'mswin', 'mingw', 'mswin64', 'x64_mingw' do
  gem 'tzinfo-data'

  group :test do
    gem 'wdm', '>= 0.1.0'
    gem 'win32console', require: false
  end
end

But the Gemfile.lock looks the same.

Here is my full Gemfile and Gemfile.lock.

I can temporarily get around the issue by removing the Gemfile.lock file from git but this is not best practice. Is there anyway that I can commit my Gemfile.lock file and continue to develop on my Windows machine?

Body:
Run the following two commands on the command line:

bundle lock --add-platform ruby
bundle lock --add-platform x86_64-linux

This will add the two platforms in Gemfile.lock

I had the same error when deploying to google cloud. But after running these two commands ruby and x86_64-linux were added and the issue was resolved.


问:
SQL: count values in one table based on WHERE from other table
I am not sure, why this is not working.

I have two simple tables:

```<code>Orders
OrderTypeID EmployeeID   Completion_needed
10308       72             15%
10309       73             20%
10310       74             30%

Customers
Customer ID   OrderTypeID   OrderDate    Order_completed
    1          10308       2015-09-18          5%
    2          10309       2015-09-19          30%
    3          10310       2017-09-20          25%
    4          10308       2015-09-18          17%
    2          10308       2015-09-19          20%
    3          10309       2017-09-20          7%
</code>```

I want to calculate how many customers have non completed orders, where Order_completed in the Customers table is less than Completion_needed in the Orders table (please not that a customer can have more than one order type).

This is my query, but I get the wrong result:

```<code>SELECT COUNT(c.CustomerID) as count_employees
FROM Orders od
JOIN Customers c
ON od.OrderTypeID = c.OrderTypeID
WHERE od.Completion_needed > c.Order_completed
</code>```

I get 1; but I should get the count of 2.

答:
I don't see how you get "1" from your query.  I see it producing "3".  So, I think what you need is COUNT(DISTINCT):

```<code>  SELECT COUNT(DISTINCT c.CustomerId)
  FROM Orders od JOIN
       Customers c
       ON od.OrderTypeID = c.OrderTypeID
  WHERE c.Order_completed < od.Completion_needed;
</code>```

Body:
I am not sure, why this is not working.

I have two simple tables:

Orders
OrderTypeID EmployeeID   Completion_needed
10308       72             15%
10309       73             20%
10310       74             30%

Customers
Customer ID   OrderTypeID   OrderDate    Order_completed
    1          10308       2015-09-18          5%
    2          10309       2015-09-19          30%
    3          10310       2017-09-20          25%
    4          10308       2015-09-18          17%
    2          10308       2015-09-19          20%
    3          10309       2017-09-20          7%

I want to calculate how many customers have non completed orders, where Order_completed in the Customers table is less than Completion_needed in the Orders table (please not that a customer can have more than one order type).

This is my query, but I get the wrong result:

SELECT COUNT(c.CustomerID) as count_employees
FROM Orders od
JOIN Customers c
ON od.OrderTypeID = c.OrderTypeID
WHERE od.Completion_needed > c.Order_completed

I get 1; but I should get the count of 2.

Body:
I don't see how you get "1" from your query.  I see it producing "3".  So, I think what you need is COUNT(DISTINCT):

  SELECT COUNT(DISTINCT c.CustomerId)
  FROM Orders od JOIN
       Customers c
       ON od.OrderTypeID = c.OrderTypeID
  WHERE c.Order_completed < od.Completion_needed;


问:
Bootstrap tooltips in eex templates
I have a bootstrap tooltip. A test link works OK here:

```<code><a data-tooltip="I am tooltip text" data-placement="left">Clickame</a>
</code>```

I have an eex link:

```<code> <span><%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %></span>
</code>```

I tried to wrap anchor tags around the link:

```<code>    <a data-tooltip="edit" data-placement="left"><span><%= link "    ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %></span></a>
</code>```

... didn't work.

There are some ideas in this Ruby on Rails tooltip question:

Using Tooltips with link_to (Ruby on Rails 3.2.3)

rel: "data-tooltip" does not raise an error:

```<code><span><%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg", rel: "data-tooltip" %></span>
</code>```

but how do I add the data-placement="left" class?

Full tooltip here:

https://codepen.io/peiche/pen/JaftA

```<code>a[data-tooltip] {
  position: relative;
}

a[data-tooltip]::before,
a[data-tooltip]::after {
  position: absolute;
  display: none;
  opacity: 0.85;
}
</code>```

答:
You can generate the  with data-tooltip and data-placement attributes by passing the attribute and their values as a keyword list to Phoenix.HTML.Link.link/2:

```<code><%= link("Clickame", to: "/", "data-tooltip": "I am tooltip text", "data-placement": "left") %>
</code>```

This produces the following HTML, which should work with your tooltip:

```<code><a data-placement="left" data-tooltip="I am tooltip text" href="/">Clickame</a>
</code>```

Title: Bootstrap tooltips in eex templates

Body:
I have a bootstrap tooltip. A test link works OK here:

Clickame

I have an eex link:

 <%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %>

I tried to wrap anchor tags around the link:

    <%= link "    ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %>

... didn't work.

There are some ideas in this Ruby on Rails tooltip question:

Using Tooltips with link_to (Ruby on Rails 3.2.3)

rel: "data-tooltip" does not raise an error:

<%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg", rel: "data-tooltip" %>

but how do I add the data-placement="left" class?

Full tooltip here:

https://codepen.io/peiche/pen/JaftA

a[data-tooltip] {
  position: relative;
}

a[data-tooltip]::before,
a[data-tooltip]::after {
  position: absolute;
  display: none;
  opacity: 0.85;
}

Body:
You can generate the <a> with data-tooltip and data-placement attributes by passing the attribute and their values as a keyword list to Phoenix.HTML.Link.link/2:

<%= link("Clickame", to: "/", "data-tooltip": "I am tooltip text", "data-placement": "left") %>

This produces the following HTML, which should work with your tooltip:

<a data-placement="left" data-tooltip="I am tooltip text" href="/">Clickame</a>


问:
How to post string data to API
I wanted to post a string data to API, I try to send it to server by using the below code. I've check api there by using the postman, it did not pass in the string data into the server. I do not know what is the problem and need help on this. </p>

```<code>NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:reqURLStr]];
    [request setHTTPMethod:@"POST"];

**//Pass The String to server**
NSString *userUpdate =[NSString stringWithFormat:@"service_type=%@&ParcelSize=%@&ReceiverName=%@&MobileNumber=%@&Email=%@&DropOffHub=%@&PickupHub=%@" ,serviceType,pSize,rName,rMobile,rEmail,dropHubID,pickHubID];

NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data1];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[data makeRestAPICall:reqURLStr] forHTTPHeaderField:@"Authorization"];

NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);
if(resSrt)
{
    NSLog(@"got response");
}
else
{
    NSLog(@"fail to connect");
}
return resSrt;
</code>```

答:
Simple answer </p>

```<code>-(void)postJsonDataToServer{
NSDictionary *parameters = @{
                                 @"service_type": serviceType,
                                 @"ParcelSize": pSize,
                                 @"ReceiverName": rName,
                                 @"MobileNumber": rMobile,
                                 @"Email" : rEmail,
                                 @"DropOffHub" : dropHubID,
                                 @"PickupHub" : pickHubID
                                 };

    NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:/api/order/add"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
                                                             fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                                 if(data != nil)
                                                                 {
                                                                     NSError *parseError = nil;
                                                                     //If the response is in dictionary format
                                                                     NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                                                                     //OR
                                                                     //If the response is in array format
                                                                     NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                                                                     NSLog(@"The res is - %@",res);

                                                                 }
                                                                 else
                                                                     NSLog(@"Data returned the parameter is nil here");
                                                             }];
    [dataTask resume];

}
</code>```

Title: How to post string data to API

Body:
I wanted to post a string data to API, I try to send it to server by using the below code. I've check api there by using the postman, it did not pass in the string data into the server. I do not know what is the problem and need help on this.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:reqURLStr]];
    [request setHTTPMethod:@"POST"];

**//Pass The String to server**
NSString *userUpdate =[NSString stringWithFormat:@"service_type=%@&ParcelSize=%@&ReceiverName=%@&MobileNumber=%@&Email=%@&DropOffHub=%@&PickupHub=%@" ,serviceType,pSize,rName,rMobile,rEmail,dropHubID,pickHubID];

NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data1];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[data makeRestAPICall:reqURLStr] forHTTPHeaderField:@"Authorization"];

NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);
if(resSrt)
{
    NSLog(@"got response");
}
else
{
    NSLog(@"fail to connect");
}
return resSrt;

Body:
Simple answer

-(void)postJsonDataToServer{
NSDictionary *parameters = @{
                                 @"service_type": serviceType,
                                 @"ParcelSize": pSize,
                                 @"ReceiverName": rName,
                                 @"MobileNumber": rMobile,
                                 @"Email" : rEmail,
                                 @"DropOffHub" : dropHubID,
                                 @"PickupHub" : pickHubID
                                 };

    NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:/api/order/add"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
                                                             fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                                 if(data != nil)
                                                                 {
                                                                     NSError *parseError = nil;
                                                                     //If the response is in dictionary format
                                                                     NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                                                                     //OR
                                                                     //If the response is in array format
                                                                     NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                                                                     NSLog(@"The res is - %@",res);

                                                                 }
                                                                 else
                                                                     NSLog(@"Data returned the parameter is nil here");
                                                             }];
    [dataTask resume];

}


问:
Been advised to use same IV in AES implementation
We've had to extend our website to communicate user credentials to a suppliers website (in the query string) using AES with a 256-bit key, however they are using a static IV when decrypting the information.

I've advised that the IV should not be static and that it is not in our standards to do that, but if they change it their end we would incur the [big] costs so we have agreed to accept this as a security risk and use the same IV (much to my extreme frustration).

What I wanted to know is, how much of a security threat is this?  I need to be able to communicate this effectively to management so that they know exactly what they are agreeing to.

*UPDATE:*We are also using the same KEY throughout as well.

Thanks

答:
Using a static IV is always a bad idea. Using a static key is always a bad idea. I bet that your supplier had compiled the static key into their binaries.

Sadly, I've seen this before. Your supplier has a requirement that they implement encryption and they are attempting to implement the encryption in a manner that's as transparent as possible---or as "checkbox" as possible. That is, they aren't really using encryption to provide security, they are using it to satisfy a checkbox requirement.

My suggestion is that you see if the supplier would be willing to forsake this home-brewed encryption approach and instead run their system over SSL. Then you get the advantage of using a quality standard security protocol with known properties. It's clear from your question that neither your supplier nor you should be attempting to design a security protocol. You should, instead, use one that is free and available on every platform.


问:
WHERE != not working as intended in SQL
I am currently running this code:

```<code>select distinct day
from v_nem_rm16, dbp_holiday
where v_nem_rm16.day != dbp_holiday.holiday_date;
</code>```

Why am I still getting results where v_nem_rm16.day IS equal to dbp_holidays.holiday_day? I want to filter out any rows where the date in v_nem_rm16.day is equal to the dates in dbp_holidays.holiday_day.

答:
Why not just use not exists?

```<code>select r.day
from v_nem_rm16 r
where not exists (select 1
                  from dbp_holiday h
                  where r.day = h.holiday_date
                 );
</code>```

You can do what you want with a JOIN, specifically a LEFT JOIN:

```<code>select r.day
from v_nem_rm16 r left join
     dbp_holiday h
     on r.day = h.holiday_date
where h.holiday_date is null;
</code>```

This just emphasizes why you should never use commas in the from clause and always use explicit join syntax.

Title: WHERE != not working as intended in SQL

Body:
I am currently running this code:

select distinct day
from v_nem_rm16, dbp_holiday
where v_nem_rm16.day != dbp_holiday.holiday_date;

Why am I still getting results where v_nem_rm16.day IS equal to dbp_holidays.holiday_day? I want to filter out any rows where the date in v_nem_rm16.day is equal to the dates in dbp_holidays.holiday_day.

Body:
Why not just use not exists?

select r.day
from v_nem_rm16 r
where not exists (select 1
                  from dbp_holiday h
                  where r.day = h.holiday_date
                 );

You can do what you want with a JOIN, specifically a LEFT JOIN:

select r.day
from v_nem_rm16 r left join
     dbp_holiday h
     on r.day = h.holiday_date
where h.holiday_date is null;

This just emphasizes why you should never use commas in the from clause and always use explicit join syntax.


问:
What is the advantage of using bash -c over using a here string
Is there any real benefit to using bash -c 'some command' over using bash <<< 'some command'

They seem to achieve the same effect.

答:
bash -c '...' leaves you the option to provide stdin input to the command,

whereas bash <<<'...' precludes that option, because stdin is already being used to provide the script to execute.

Examples:

```<code># Executes the `ls` command then processes stdin input via `cat`
echo hi | bash -c 'ls -d /; cat -n'
/
     1  hi

# The here-string input takes precedence and pipeline input is ignored.
# The `ls` command executes as expected, but `cat` has nothing to read,
# since all stdin input (from the here-string) has already been consumed.
echo hi | bash <<<'ls -d /; cat -n'
/
</code>```

Body:
bash -c '...' leaves you the option to provide stdin input to the command,

whereas bash <<<'...' precludes that option, because stdin is already being used to provide the script to execute.

Examples:

# Executes the `ls` command then processes stdin input via `cat`
echo hi | bash -c 'ls -d /; cat -n'
/
     1  hi

# The here-string input takes precedence and pipeline input is ignored.
# The `ls` command executes as expected, but `cat` has nothing to read,
# since all stdin input (from the here-string) has already been consumed.
echo hi | bash <<<'ls -d /; cat -n'
/


问:
In Sequelize, How do you perform a where query on an association inside of an $or statement?
I have three models, User, Project and ProjectMember. Keeping things simple, the models have the following attributes:

```<code>User
    - id

Project
    - id
    - owner_id
    - is_published

ProjectMember
    - user_id
    - project_id
</code>```

Using sequelize.js, I want to find all projects where the project owner is a specific user, or where there is a project member for that project whose user is that user, or where the project is published. I imagine the raw SQL would look something like this:

SELECT p.*
FROM Project p
LEFT OUTER JOIN ProjectMember m
    ON p.id = m.project_id
WHERE m.user_id = 2
    OR p.owner_id = 2
    OR p.is_published = true;
```

<p>There are plenty of examples out there on how to perform a query on an association, but I can find none on how to do so conditionally. I have been able to query just the association using this code:</p>

<pre class="lang-js prettyprint-override"><code>projModel.findAll({
    where: { },
    include: [{
        model: memberModel,
        as: 'projectMembers',
        where: { 'user_id': 2 }
    }]
})
</code>```

How do I combine this where query in an $or to check the project's owner_id and is_published columns?

答:
It's frustrating, I worked for hours to try to solve this problem, and as soon as I ask here I found a way to do it. As it turns out, sequelize.js developers recently added the ability to use raw keys in your where query, making it (at long last) possible to query an association inside of the main where clause.

This is my solution:

projModel.findAll({
    where: {
        $or: {
            '$projectMembers.user_id$': 2,
            owner_id: 2,
            is_published: true
        }
    },
    include: [{
        model: memberModel,
        as: 'projectMembers'
    }]
})
```

Note: this solution breaks if you use 'limit' in the find options. As an alternative, you can fetch all results and then manually limit them afterwards.

Body:
I have three models, User, Project and ProjectMember. Keeping things simple, the models have the following attributes:

User
    - id

Project
    - id
    - owner_id
    - is_published

ProjectMember
    - user_id
    - project_id

Using sequelize.js, I want to find all projects where the project owner is a specific user, or where there is a project member for that project whose user is that user, or where the project is published. I imagine the raw SQL would look something like this:

SELECT p.*
FROM Project p
LEFT OUTER JOIN ProjectMember m
    ON p.id = m.project_id
WHERE m.user_id = 2
    OR p.owner_id = 2
    OR p.is_published = true;

There are plenty of examples out there on how to perform a query on an association, but I can find none on how to do so conditionally. I have been able to query just the association using this code:

projModel.findAll({
    where: { },
    include: [{
        model: memberModel,
        as: 'projectMembers',
        where: { 'user_id': 2 }
    }]
})

How do I combine this where query in an $or to check the project's owner_id and is_published columns?

Body:
It's frustrating, I worked for hours to try to solve this problem, and as soon as I ask here I found a way to do it. As it turns out, sequelize.js developers recently added the ability to use raw keys in your where query, making it (at long last) possible to query an association inside of the main where clause.

This is my solution:

projModel.findAll({
    where: {
        $or: {
            '$projectMembers.user_id$': 2,
            owner_id: 2,
            is_published: true
        }
    },
    include: [{
        model: memberModel,
        as: 'projectMembers'
    }]
})

Note: this solution breaks if you use 'limit' in the find options. As an alternative, you can fetch all results and then manually limit them afterwards.


问:
watching files for changes with perl (macos and linux)
I would like to watch a set of files for changes, and do so without a large CPU and battery penalty.  Ideally, my perl code would run on both macos and linux, but the former is more important.  I tried

I tried Mac::FSEvents, which works on macos and seems to do nicely for directories, but not for files as far as I can tell.

```<code>my $fs = Mac::FSEvents->new('try.txt');
my $fh= $fs->watch;

my $sel = IO::Select->new($fh);
while ( $sel->can_read ) {
  my @events = $fs->read_events;
  for my $event ( @events ) {
    printf "File %s changed\n", $event->path;
  }
}
</code>```

which simply does not respond; and the promisingly more OS agnostic

```<code>use File::Monitor;
my $monitor = File::Monitor->new();

my @files= qw(try.txt);

foreach (@files) { $monitor->watch($_); }
</code>```

which consumes 100% CPU.  the $monitor-watch() alone does not block.  I also tried

```<code>use File::Monitor;
my $monitor = File::Monitor->new();

$monitor->watch('try.txt', sub {
                  my ($name, $event, $change) = @_;
                  print "file has changed\n";
                });
</code>```

but this immediately returns.

I found another,

```<code>use File::ChangeNotify;

my $watcher =
  File::ChangeNotify->instantiate_watcher
  ( directories => [ './' ],
    filter      => qr/try\.txt/,
  );

# blocking
while ( my @events = $watcher->wait_for_events() ) {
  print "file has changed\n";
}
</code>```

but the CPU utilization is again high (70%).

Maybe these are all the wrong cpan modules, too.  could someone please give me advice on how I should do this?

regards,

/iaw

答:
Partial (macos-specific) example:

```<code>use IO::Select;
use Mac::FSEvents;
my $fs = Mac::FSEvents->new(
    path          => ['./try.txt', './try2.txt'],
    file_events   => 1,
    );

my $fh= $fs->watch;
my $sel = IO::Select->new($fh);
while ( $sel->can_read ) {
  my @events = $fs->read_events;
  for my $event ( @events ) {
    printf "File %s changed\n", $event->path;
  }
}
</code>```

(i.e., it needed the file_events flag.)

Body:
I would like to watch a set of files for changes, and do so without a large CPU and battery penalty.  Ideally, my perl code would run on both macos and linux, but the former is more important.  I tried

I tried Mac::FSEvents, which works on macos and seems to do nicely for directories, but not for files as far as I can tell.

my $fs = Mac::FSEvents->new('try.txt');
my $fh= $fs->watch;

my $sel = IO::Select->new($fh);
while ( $sel->can_read ) {
  my @events = $fs->read_events;
  for my $event ( @events ) {
    printf "File %s changed\n", $event->path;
  }
}

which simply does not respond; and the promisingly more OS agnostic

use File::Monitor;
my $monitor = File::Monitor->new();

my @files= qw(try.txt);

foreach (@files) { $monitor->watch($_); }

which consumes 100% CPU.  the $monitor-watch() alone does not block.  I also tried

use File::Monitor;
my $monitor = File::Monitor->new();

$monitor->watch('try.txt', sub {
                  my ($name, $event, $change) = @_;
                  print "file has changed\n";
                });

but this immediately returns.

I found another,

use File::ChangeNotify;

my $watcher =
  File::ChangeNotify->instantiate_watcher
  ( directories => [ './' ],
    filter      => qr/try\.txt/,
  );

# blocking
while ( my @events = $watcher->wait_for_events() ) {
  print "file has changed\n";
}

but the CPU utilization is again high (70%).

Maybe these are all the wrong cpan modules, too.  could someone please give me advice on how I should do this?

regards,

/iaw

Body:
Partial (macos-specific) example:

use IO::Select;
use Mac::FSEvents;
my $fs = Mac::FSEvents->new(
    path          => ['./try.txt', './try2.txt'],
    file_events   => 1,
    );

my $fh= $fs->watch;
my $sel = IO::Select->new($fh);
while ( $sel->can_read ) {
  my @events = $fs->read_events;
  for my $event ( @events ) {
    printf "File %s changed\n", $event->path;
  }
}

(i.e., it needed the file_events flag.)


问:
Overhang detection shader - how to return the coordinates of the vertices?
I'm trying to write a support generation app in browser using three.js, I have tried many approaches and all of them were slow, so now I decided to make the shader compute the overhang position and my program build supports to those points.

The overhang detection shader outputs:

Now the problem is I cannot figure out how to return those areas in red to the CPU /main JavaScript app to generate simple supports to those points,
I read somewhere here about a GPU CPU approach involving a FBO but can't understand this, is there any way to get the red areas coordinates back to CPU?

I could also calculate this in the vertex shader to update the position of non overhang vertices to be 0,0,0, but the problem is that the vertex position in three JavaScript doesn't update in that way, if there is some way to get updated vertex positions after vertex shader execution it could be a solution.

Maybe transform feedback? How can I use transform feedback from three.js?

答:
You can use other an FBO or transform feedback. With transform feedbackhe only problem is AFAICT  there is no way to discard vertices so like you mentioned the best you can do in that case is write some special value for non-overlapping vertices.

To use an FBO you make a floating point texture and check you can render to it. In WebGL1 that means enabling floating point textures, binding one to a framebuffer and calling checkFramebufferStatus. In WebGL 2 it means checking for and enabling EXT_color_buffer_float (and still calling checkFramebufferStatus)

You then make a buffer with just a count [0, 1, 2, 3, 4, 5, 6 etc.] use that to generate a gl_Position that will write to the next pixel in the FBO.

```<code>// WebGL2
varying uint count;
uniform uint2 resolutionOfFBO;

// compute output pixel
uint x = count % resolutinOfFBO.x;
uint y = count / resolutionOfFBO.x;

// set gl_Position so we'll write to that output pixel
gl_Position = vec4((vec2(x, y) + .5) / resolutionOfFBO, 0, 1);
</code>```

Pass the data you want to write in a varying and write that data in the fragment shader. Then render with POINTS.

You can then read the data back with gl.readPixels

Explaining transform feedback seems a little long for this question but here's a simple example: The input is [1, 2, 3] and the output is [2, 4, 6]

function main() {
  const gl = document.createElement("canvas").getContext("webgl2");

  const vs = `#version 300 es
    in float in_value;
    out float out_value;

    void main() {
       out_value = in_value * 2.;
    }
  `;
  const fs = `#version 300 es
    precision mediump float;
    layout (location = 0) out vec4 dummy;
    void main() {
      dummy = vec4(1);
    }
  `;
  const prog = createProgram(gl, [vs, fs], ["out_value"]);
  const inLoc = gl.getAttribLocation(prog, 'in_value');
  const outLoc = 0;

  const numVaryings = gl.getProgramParameter(prog, gl.TRANSFORM_FEEDBACK_VARYINGS);

  const srcBuffer1 = createBuffer(gl, new Float32Array([1, 2, 3]));
  const srcVAO1 = createVAO(gl, srcBuffer1, inLoc);

  const dstBuffer = createBuffer(gl, Float32Array.BYTES_PER_ELEMENT * 3);
  const srcVAO2 = createVAO(gl, dstBuffer, inLoc);

  const tf = gl.createTransformFeedback();
  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf);
  gl.useProgram(prog);
  gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, dstBuffer);
  // this binds the default (id = 0) TRANSFORM_FEEBACK buffer
  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
  // This line is onky because of a bug in Chrome
  gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);

  runFeedback(gl, prog, srcVAO1, tf);
  checkGLError(gl);

  const result = new Float32Array(3);
  gl.bindBuffer(gl.ARRAY_BUFFER, dstBuffer);
  gl.getBufferSubData(gl.ARRAY_BUFFER, 0, result);
  log(result);
}
main();

function runFeedback(gl, prog, srcVAO, tf, dstBufferInfo) {
  gl.enable(gl.RASTERIZER_DISCARD);

  gl.useProgram(prog);
  gl.bindVertexArray(srcVAO);

  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf);
  gl.beginTransformFeedback(gl.TRIANGLES);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
  gl.endTransformFeedback();

  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);

  gl.disable(gl.RASTERIZER_DISCARD);
}

function checkGLError(gl) {
  const err = gl.getError();
  if (err) {
    log("GL ERROR:", err);
  }
}

function createShader(gl, shaderSource, shaderType) {
  var shader = gl.createShader(shaderType);
  gl.shaderSource(shader, shaderSource);
  gl.compileShader(shader);
  var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  if (!compiled) {
    console.error(gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
    return null;
  }
  return shader;
}

function createProgram(gl, shaderSources, outputs) {
  const shaderTypes = [gl.VERTEX_SHADER, gl.FRAGMENT_SHADER];
  const program = gl.createProgram();
  shaderSources.forEach(function(shaderSrc, ndx) {
    gl.attachShader(program, createShader(gl, shaderSrc, shaderTypes[ndx]));
  });

  if (outputs) {
    gl.transformFeedbackVaryings(program, outputs, gl.SEPARATE_ATTRIBS);
  }
  gl.linkProgram(program);

  var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  if (!linked) {
    console.error(gl.getProgramInfoLog(program));
    gl.deleteProgram(program);
    return null;
  }
  return program;
}

function createBuffer(gl, dataOrSize) {
  const buf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.bufferData(gl.ARRAY_BUFFER, dataOrSize, gl.STATIC_DRAW);
  return buf;
}

function createVAO(gl, buf, inLoc) {
  const vao = gl.createVertexArray();
  gl.bindVertexArray(vao);
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.enableVertexAttribArray(inLoc);
  gl.vertexAttribPointer(inLoc, 1, gl.FLOAT, false, 0, 0);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);  // this is not needed
  gl.bindVertexArray(null);
  return vao;
}

function log(...args) {
  const elem = document.createElement("pre");
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}```
</div>
</div>
</p>

<p>The short explanation is with transform feedbacks your output varyings from your vertex shader are written to one or more buffers.</p>

<p>To do that you have to tell your shader program at link time what your outputs are with <code>gl.transformFeedbackVaryings</code>. </p>

<p>Then you create a transform feedback object. A transform feedback object is very similar to a vertex array object except it's for outputs instead of inputs. You specify the outputs by calling <code>gl.bindBufferBase</code> for each output just like you'd call <code>gl.vertexAttribPointer</code> for each input on vertex array object.</p>

<p>To actually generate the output you probably want to tell WebGL not to run the fragment shader</p>

```gl.enable(gl.RASTERIZER_DISCARD);
```

<p>Then you bind your transform feedback object, turn on transform feedback and draw</p>

```gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf);
gl.beginTransformFeedback(gl.TRIANGLES);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.endTransformFeedback();
```

<p>When you link the program you can choose separate or interleaved attribtes. With separate each attribute can go to a different buffer but there's a limit on how many attributes you can write (min is at least 4). With interleaved all outputs get written but they are interleaved. For example if you were writing both positions and normals then the output would be </p>

```position0, normal0, position1, normal1, position2, normal2
```

all to the same buffer.

Body:
You can use other an FBO or transform feedback. With transform feedbackhe only problem is AFAICT  there is no way to discard vertices so like you mentioned the best you can do in that case is write some special value for non-overlapping vertices.

To use an FBO you make a floating point texture and check you can render to it. In WebGL1 that means enabling floating point textures, binding one to a framebuffer and calling checkFramebufferStatus. In WebGL 2 it means checking for and enabling EXT_color_buffer_float (and still calling checkFramebufferStatus)

You then make a buffer with just a count [0, 1, 2, 3, 4, 5, 6 etc.] use that to generate a gl_Position that will write to the next pixel in the FBO.

// WebGL2
varying uint count;
uniform uint2 resolutionOfFBO;

// compute output pixel
uint x = count % resolutinOfFBO.x;
uint y = count / resolutionOfFBO.x;

// set gl_Position so we'll write to that output pixel
gl_Position = vec4((vec2(x, y) + .5) / resolutionOfFBO, 0, 1);

Pass the data you want to write in a varying and write that data in the fragment shader. Then render with POINTS.

You can then read the data back with gl.readPixels

Explaining transform feedback seems a little long for this question but here's a simple example: The input is [1, 2, 3] and the output is [2, 4, 6]

function main() {
  const gl = document.createElement("canvas").getContext("webgl2");

  const vs = `#version 300 es
    in float in_value;
    out float out_value;

    void main() {
       out_value = in_value * 2.;
    }
  `;
  const fs = `#version 300 es
    precision mediump float;
    layout (location = 0) out vec4 dummy;
    void main() {
      dummy = vec4(1);
    }
  `;
  const prog = createProgram(gl, [vs, fs], ["out_value"]);
  const inLoc = gl.getAttribLocation(prog, 'in_value');
  const outLoc = 0;

  const numVaryings = gl.getProgramParameter(prog, gl.TRANSFORM_FEEDBACK_VARYINGS);

  const srcBuffer1 = createBuffer(gl, new Float32Array([1, 2, 3]));
  const srcVAO1 = createVAO(gl, srcBuffer1, inLoc);

  const dstBuffer = createBuffer(gl, Float32Array.BYTES_PER_ELEMENT * 3);
  const srcVAO2 = createVAO(gl, dstBuffer, inLoc);

  const tf = gl.createTransformFeedback();
  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf);
  gl.useProgram(prog);
  gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, dstBuffer);
  // this binds the default (id = 0) TRANSFORM_FEEBACK buffer
  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
  // This line is onky because of a bug in Chrome
  gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);

  runFeedback(gl, prog, srcVAO1, tf);
  checkGLError(gl);

  const result = new Float32Array(3);
  gl.bindBuffer(gl.ARRAY_BUFFER, dstBuffer);
  gl.getBufferSubData(gl.ARRAY_BUFFER, 0, result);
  log(result);
}
main();

function runFeedback(gl, prog, srcVAO, tf, dstBufferInfo) {
  gl.enable(gl.RASTERIZER_DISCARD);

  gl.useProgram(prog);
  gl.bindVertexArray(srcVAO);

  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf);
  gl.beginTransformFeedback(gl.TRIANGLES);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
  gl.endTransformFeedback();

  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);

  gl.disable(gl.RASTERIZER_DISCARD);
}

function checkGLError(gl) {
  const err = gl.getError();
  if (err) {
    log("GL ERROR:", err);
  }
}

function createShader(gl, shaderSource, shaderType) {
  var shader = gl.createShader(shaderType);
  gl.shaderSource(shader, shaderSource);
  gl.compileShader(shader);
  var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  if (!compiled) {
    console.error(gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
    return null;
  }
  return shader;
}

function createProgram(gl, shaderSources, outputs) {
  const shaderTypes = [gl.VERTEX_SHADER, gl.FRAGMENT_SHADER];
  const program = gl.createProgram();
  shaderSources.forEach(function(shaderSrc, ndx) {
    gl.attachShader(program, createShader(gl, shaderSrc, shaderTypes[ndx]));
  });

  if (outputs) {
    gl.transformFeedbackVaryings(program, outputs, gl.SEPARATE_ATTRIBS);
  }
  gl.linkProgram(program);

  var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  if (!linked) {
    console.error(gl.getProgramInfoLog(program));
    gl.deleteProgram(program);
    return null;
  }
  return program;
}

function createBuffer(gl, dataOrSize) {
  const buf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.bufferData(gl.ARRAY_BUFFER, dataOrSize, gl.STATIC_DRAW);
  return buf;
}

function createVAO(gl, buf, inLoc) {
  const vao = gl.createVertexArray();
  gl.bindVertexArray(vao);
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.enableVertexAttribArray(inLoc);
  gl.vertexAttribPointer(inLoc, 1, gl.FLOAT, false, 0, 0);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);  // this is not needed
  gl.bindVertexArray(null);
  return vao;
}

function log(...args) {
  const elem = document.createElement("pre");
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}

The short explanation is with transform feedbacks your output varyings from your vertex shader are written to one or more buffers.

To do that you have to tell your shader program at link time what your outputs are with gl.transformFeedbackVaryings.

Then you create a transform feedback object. A transform feedback object is very similar to a vertex array object except it's for outputs instead of inputs. You specify the outputs by calling gl.bindBufferBase for each output just like you'd call gl.vertexAttribPointer for each input on vertex array object.

To actually generate the output you probably want to tell WebGL not to run the fragment shader

gl.enable(gl.RASTERIZER_DISCARD);

Then you bind your transform feedback object, turn on transform feedback and draw

gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf);
gl.beginTransformFeedback(gl.TRIANGLES);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.endTransformFeedback();

When you link the program you can choose separate or interleaved attribtes. With separate each attribute can go to a different buffer but there's a limit on how many attributes you can write (min is at least 4). With interleaved all outputs get written but they are interleaved. For example if you were writing both positions and normals then the output would be

position0, normal0, position1, normal1, position2, normal2

all to the same buffer.


问:
Networking; Router 10/100 to gigabit switch then PC.. Gigabit network xfer speeds?
This is just for a home setup, my router is a DSL box and I've not found a decent ADSL2+ modem that's also a gigabit +wifi router.. So this is my next-best idea..

DSL Router is 10/100 to a Gigabit switch.. The PCs are hooked up to the gigabit switch, along with a NAS- Will the PCs and NAS exchange data at gigabit speeds, being connected to the switch, or will the router's fast ethernet limit the switch's throughput?

The PCs in question all run Windows 10 and are modern machines equipped with gigabit NICs, so the only possible limiting factor would be the router behind the switch.

答:
Assuming all your internal nodes are gigabit your internal speeds will be as fast as the hardware will run if all connected to a gigabit switch. Your slowdown will be transfers through your DSL Router that said unless you have a really fast internet connection in excess of 70mps you will not be bottlenecked by the transfer rate for streaming or www browsing.
It’s a misconception that just because your connected with a gigabit NIC that you will be able to transfer at that speed. Most home systems will not get anywhere near that transfer speed. </p>


问:
ajax post data not working on shared hosting
I'm very confuse for this problem ajax post data, on localhost working but on shared hosting not working. This is my code

```<code><script type="text/javascript">
        $(document).ready(function(){
            $("#login").click(function(){
              alert('asdf');
                var page = "login";
                var username = $("#username").val().trim();
                var password = $("#password").val().trim();
                $.ajax({
                        url:'pages/content/input_query.php',
                        type:'post',
                        data:{page:page,username:username,password:password},
                        success:function(response){
                            var msg = "";
                            if(response ==1){
                                window.location = "index.php?pages=home";
                            }else{
                                $("#result").html(response);
                            }
                         }
                    });

            });

        });
</code>```

and my code html is

```<code> <form role="form" action="pages/content/input_query.php" method="post">
      <div class="form-group has-feedback">
        <input type="text" class="form-control" placeholder="username" id="username" />
        <span class="glyphicon glyphicon-user form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="password" class="form-control" placeholder="Password" id="password" />
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="row">
        <div class="col-xs-8">
          <div class="checkbox icheck">

          </div>
        </div><!-- /.col -->
        <div class="col-xs-4">
          <button type="button" class="btn btn-primary btn-block btn-flat" id="login">Sign In</button>
        </div><!-- /.col -->
      </div>
    </form>
</code>```

And I have add code alert('asdf') , but there are no alert message  every click the button. What is the problem. Please help me. Every answer I appricated

答:
Have you called jQuery on server?
Try calling from jQuery CDN.
Use this code:</p>

```<code><script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#login").click(function(){
          alert('asdf');
            var page = "login";
            var username = $("#username").val().trim();
            var password = $("#password").val().trim();
            $.ajax({
                    url:'pages/content/input_query.php',
                    type:'post',
                    data:{page:page,username:username,password:password},
                    success:function(response){
                        var msg = "";
                        if(response ==1){
                            window.location = "index.php?pages=home";
                        }else{
                            $("#result").html(response);
                        }
                     }
                });

        });

    });
    </script>
</code>```

Body:
Have you called jQuery on server?
Try calling from jQuery CDN.
Use this code:

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#login").click(function(){
          alert('asdf');
            var page = "login";
            var username = $("#username").val().trim();
            var password = $("#password").val().trim();
            $.ajax({
                    url:'pages/content/input_query.php',
                    type:'post',
                    data:{page:page,username:username,password:password},
                    success:function(response){
                        var msg = "";
                        if(response ==1){
                            window.location = "index.php?pages=home";
                        }else{
                            $("#result").html(response);
                        }
                     }
                });

        });

    });
    </script>