问:
Interpreting CISC as RISC
I'm preparing for a test in computer science and there's this question that keeps coming up in previous tests that I can't find an answer to.

Consider the execution of the two instructions below on a typical RISC architecture with only one addressing mode (Reg + Offset).

```<code>804836e:    40            inc    %eax
804836f:    89 04 91      mov    %eax,(%ecx,%edx,4)
</code>```

Explain, justifying, how these 2 IA-32 instructions would be compiled for this architecture, using IA-32 sintaxe to show that code.

Comment on the size of this piece of code on the RISC architecture versus the IA-32.

The C function is :

```<code>voidpara_par (int a[], int n) {
    int i;
    for (i=0 ; i<n ; i++) {
        if (a[i] & 0x01) {
            a[i] += 1;
        }
    }
}
</code>```

Which receives an array of ints and increments the value of the odd ones.

For reference:

```<code>%eax -> int i
(%ecx,%edx,4) -> int, part of the array "a" saved to %ecx
</code>```

I know this question feels vague to say the least but that's my problem, I don't really know how to begin "translating" from one architecture to the other.

答:
The question just wants you to realize that the read-modify-write (RMW) instructions that exist in the x86 instruction set (a classically "CISC" ISA) would not be available on a RISC instruction set. Neither would the complex memory addressing that you find in x86 instructions.

Instead, a classic RISC ISA would provide only a "simplified" set of instructions, meaning that you'd have to decompose the x86 CISC-style instructions into a set of simpler instructions. In other words, you just break them up into their component bits.

Beyond showing you the classic contrast between CISC and RISC, the other reason why this is a somewhat interesting exercise is because it's the same thing that a modern x86 processor is doing internally. You see, even though you (the programmer) write this CISC-style code for x86, internally, the processor is actually more like a RISC system, so when it decodes the instruction, it decodes it into a series of µops that resemble what a programmer would write for a RISC system.

Let's study the instructions you were given:

```<code>804836e:    40            inc    %eax
804836f:    89 04 91      mov    %eax,(%ecx,%edx,4)
</code>```

The parameter (an int) was passed in the EAX register, so this just increments it by 1. Most likely, on a RISC system, there would not be specialized INC and DEC instructions like there are on x86. These were added to x86 to mirror the ++i and --i statements in languages like C, but notice that they are equivalent to an addition (or subtraction) of 1. So, on a RISC system, you would just write:

```<code>add  $1, %eax
</code>```

Then the MOV instruction. This one's a doozie. First, we need to figure out what it's actually doing. In this AT&T/GAS syntax, it's very difficult to see what is happening (in my opinion), so let's rewrite it into the more normal Intel/MASM syntax:

```<code>mov  DWORD PTR [ecx+edx*4], eax
</code>```

Now, it is clear that this scales (multiplies) the contents of the EDX register by 4, adds this to the contents of the ECX register, and then stores the contents of EAX at this address.

A classic RISC system would not support this complex memory addressing, so we need to break it down into simpler bits. That's not hard, though, now that we understand what the instruction is doing:

```<code>shl  edx, 2                  ; edx *= 4
add  edx, ecx                ; edx += ecx
mov  DWORD PTR [edx], eax    ; store EAX at address in EDX
</code>```

It's also worth noting that a classic RISC system wouldn't overload the MOV instruction like x86 does. Typically, RISC is a load-store architecture, which would break the x86's MOV instruction into three different things:

A register-to-register MOV instruction

A LOAD instruction to load from memory into a register

A STORE instruction to store from a register into memory

So if you were actually translating this to a RISC ISA, the code might look more like:

```<code>shl    edx, 2
add    edx, ecx
store  [edx], eax
</code>```

Not a big difference, but important to understand that on a normal RISC system, MOV wouldn't do all things like it does on x86.

Another minor thing, if you're the type that likes to nitpick. The complex memory addressing that we were originally using in the x86 MOV instruction doesn't actually modify the ECX or EDX registers, whereas our "translated" version clobbers the EDX register. If we wanted to be precise, we would need to:

```<code>mov    reg9, edx    ; a reg-reg move to a new temporary register
shl    reg9, 2
add    reg9, ecx
store  [reg9], eax
</code>```

where reg9 is a new temporary register. In modern implementations of x86, this would be a hidden, non-architectural register, which just means it's one that the processor's hardware has but is not exposed to the programmer as part of the instruction set. On most RISC systems, this wouldn't be necessary either, because their instructions accept three operands (operand 1, operand 2, and destination), so that the result can be placed in a different register without clobbering any of the operands. Thus, you'd have:

```<code>shl   reg9, edx, 2
add   reg9, reg9, ecx
store [reg9], eax
</code>```

So, putting it all together in AT&T syntax, the desired answer would be something like:

```<code>add    $1, %eax         # increment EAX by 1
mov    %edx, %reg9      # reg-reg move of EDX to a temp
shl    $2, %reg9        # scale by 4
add    %ecx, %reg9      # add offset in ECX
store  %eax, (%reg9)    # store EAX at this address
</code>```

Just for fun, let's take the C code that you were given and see how it would look when compiled for the two different types of architectures. Here is what GCC 4.8 generates when targeting x86 (a classic CISC architecture):

```<code>para_par(int*, int):
        mov     edx, DWORD PTR [esp+8]
        mov     eax, DWORD PTR [esp+4]
        test    edx, edx
        lea     ecx, [eax+edx*4]
        jle     .L1
.L5:
        mov     edx, DWORD PTR [eax]
        test    dl, 1
        je      .L3
        inc     edx
        mov     DWORD PTR [eax], edx
.L3:
        add     eax, 4
        cmp     eax, ecx
        jne     .L5
.L1:
        ret
</code>```

Now, rewriting this to RISC style (as your assignment calls for) would be pretty simple—there aren't that many "complex" instructions there, other than that LEA. I might do something like:

```<code>para_par(int*, int):
        load    ecx, DWORD PTR [esp+8]
        cmp     ecx, 0
        jle     .L1
        load    eax, DWORD PTR [esp+4]
        add     ecx, ecx
        add     ecx, ecx
        add     ecx, eax
.L5:
        load    edx, DWORD PTR [eax]
        test    dl, 1    ; a bit "complex" because it's an AND that doesn't modify, but
                         ; on RISC, we'd have the three-operand form of AND to avoid modifying
        je      .L3
        add     edx, 1
        store   DWORD PTR [eax], edx
.L3:
        add     eax, 4
        cmp     eax, ecx
        jne     .L5
.L1:
        ret
</code>```

Here's what GCC 4.8 generates if you compile for PowerPC (a classic RISC architecture):

```<code>add  $1, %eax
</code>```0

Of course, the mnemonics for PowerPC are all different from those for x86, which makes understanding it difficult if you've only ever studied x86. You can look up the mnemonics, but even without going through that much effort, you can still pick out a lot of what I've mentioned—the "simpler" instructions, the separate loads (lwzu) and stores (stw), and the three operands instead of two.

Curiously, both because of the code that was selected as the example and because of the magic of an optimizing compiler, there isn't that much difference between the x86 ("CISC") disassembly and the PowerPC ("RISC") disassembly.

Title: Interpreting CISC as RISC

Body:
I'm preparing for a test in computer science and there's this question that keeps coming up in previous tests that I can't find an answer to.

Consider the execution of the two instructions below on a typical RISC architecture with only one addressing mode (Reg + Offset).

804836e:    40            inc    %eax
804836f:    89 04 91      mov    %eax,(%ecx,%edx,4)

Explain, justifying, how these 2 IA-32 instructions would be compiled for this architecture, using IA-32 sintaxe to show that code.

Comment on the size of this piece of code on the RISC architecture versus the IA-32.

The C function is :

voidpara_par (int a[], int n) {
    int i;
    for (i=0 ; i<n ; i++) {
        if (a[i] & 0x01) {
            a[i] += 1;
        }
    }
}

Which receives an array of ints and increments the value of the odd ones.

For reference:

%eax -> int i
(%ecx,%edx,4) -> int, part of the array "a" saved to %ecx

I know this question feels vague to say the least but that's my problem, I don't really know how to begin "translating" from one architecture to the other.

Body:
The question just wants you to realize that the read-modify-write (RMW) instructions that exist in the x86 instruction set (a classically "CISC" ISA) would not be available on a RISC instruction set. Neither would the complex memory addressing that you find in x86 instructions.

Instead, a classic RISC ISA would provide only a "simplified" set of instructions, meaning that you'd have to decompose the x86 CISC-style instructions into a set of simpler instructions. In other words, you just break them up into their component bits.

Beyond showing you the classic contrast between CISC and RISC, the other reason why this is a somewhat interesting exercise is because it's the same thing that a modern x86 processor is doing internally. You see, even though you (the programmer) write this CISC-style code for x86, internally, the processor is actually more like a RISC system, so when it decodes the instruction, it decodes it into a series of µops that resemble what a programmer would write for a RISC system.

Let's study the instructions you were given:

804836e:    40            inc    %eax
804836f:    89 04 91      mov    %eax,(%ecx,%edx,4)

The parameter (an int) was passed in the EAX register, so this just increments it by 1. Most likely, on a RISC system, there would not be specialized INC and DEC instructions like there are on x86. These were added to x86 to mirror the ++i and --i statements in languages like C, but notice that they are equivalent to an addition (or subtraction) of 1. So, on a RISC system, you would just write:

add  $1, %eax

Then the MOV instruction. This one's a doozie. First, we need to figure out what it's actually doing. In this AT&T/GAS syntax, it's very difficult to see what is happening (in my opinion), so let's rewrite it into the more normal Intel/MASM syntax:

mov  DWORD PTR [ecx+edx*4], eax

Now, it is clear that this scales (multiplies) the contents of the EDX register by 4, adds this to the contents of the ECX register, and then stores the contents of EAX at this address.

A classic RISC system would not support this complex memory addressing, so we need to break it down into simpler bits. That's not hard, though, now that we understand what the instruction is doing:

shl  edx, 2                  ; edx *= 4
add  edx, ecx                ; edx += ecx
mov  DWORD PTR [edx], eax    ; store EAX at address in EDX

It's also worth noting that a classic RISC system wouldn't overload the MOV instruction like x86 does. Typically, RISC is a load-store architecture, which would break the x86's MOV instruction into three different things:

A register-to-register MOV instruction

A LOAD instruction to load from memory into a register

A STORE instruction to store from a register into memory

So if you were actually translating this to a RISC ISA, the code might look more like:

shl    edx, 2
add    edx, ecx
store  [edx], eax

Not a big difference, but important to understand that on a normal RISC system, MOV wouldn't do all things like it does on x86.

Another minor thing, if you're the type that likes to nitpick. The complex memory addressing that we were originally using in the x86 MOV instruction doesn't actually modify the ECX or EDX registers, whereas our "translated" version clobbers the EDX register. If we wanted to be precise, we would need to:

mov    reg9, edx    ; a reg-reg move to a new temporary register
shl    reg9, 2
add    reg9, ecx
store  [reg9], eax

where reg9 is a new temporary register. In modern implementations of x86, this would be a hidden, non-architectural register, which just means it's one that the processor's hardware has but is not exposed to the programmer as part of the instruction set. On most RISC systems, this wouldn't be necessary either, because their instructions accept three operands (operand 1, operand 2, and destination), so that the result can be placed in a different register without clobbering any of the operands. Thus, you'd have:

shl   reg9, edx, 2
add   reg9, reg9, ecx
store [reg9], eax

So, putting it all together in AT&T syntax, the desired answer would be something like:

add    $1, %eax         # increment EAX by 1
mov    %edx, %reg9      # reg-reg move of EDX to a temp
shl    $2, %reg9        # scale by 4
add    %ecx, %reg9      # add offset in ECX
store  %eax, (%reg9)    # store EAX at this address

Just for fun, let's take the C code that you were given and see how it would look when compiled for the two different types of architectures. Here is what GCC 4.8 generates when targeting x86 (a classic CISC architecture):

para_par(int*, int):
        mov     edx, DWORD PTR [esp+8]
        mov     eax, DWORD PTR [esp+4]
        test    edx, edx
        lea     ecx, [eax+edx*4]
        jle     .L1
.L5:
        mov     edx, DWORD PTR [eax]
        test    dl, 1
        je      .L3
        inc     edx
        mov     DWORD PTR [eax], edx
.L3:
        add     eax, 4
        cmp     eax, ecx
        jne     .L5
.L1:
        ret

Now, rewriting this to RISC style (as your assignment calls for) would be pretty simple—there aren't that many "complex" instructions there, other than that LEA. I might do something like:

para_par(int*, int):
        load    ecx, DWORD PTR [esp+8]
        cmp     ecx, 0
        jle     .L1
        load    eax, DWORD PTR [esp+4]
        add     ecx, ecx
        add     ecx, ecx
        add     ecx, eax
.L5:
        load    edx, DWORD PTR [eax]
        test    dl, 1    ; a bit "complex" because it's an AND that doesn't modify, but
                         ; on RISC, we'd have the three-operand form of AND to avoid modifying
        je      .L3
        add     edx, 1
        store   DWORD PTR [eax], edx
.L3:
        add     eax, 4
        cmp     eax, ecx
        jne     .L5
.L1:
        ret

Here's what GCC 4.8 generates if you compile for PowerPC (a classic RISC architecture):

para_par(int*, int):
        cmpwi 7,4,0       # compare to 0
        addi 3,3,-4       # add
        slwi 4,4,2        # left-shift by 2
        add 4,3,4         # add
        blelr- 7          # branch if less-than-or-equal
        subf 4,3,4        # subtract
        addi 4,4,-4       # add
        srwi 4,4,2        # right-shift by 2
        addi 4,4,1        # add
        mtctr 4           # move to count register (a special register)
.L9:
        lwzu 9,4(3)       # load from memory
        andi. 10,9,1      # bitwise AND
        addi 9,9,1        # add
        beq- 0,.L3        # branch if equal-to
        stw 9,0(3)        # store to memory
.L3:
        bdnz .L9          # decrement and branch if not-zero
        blr               # unconditional branch (JMP)

Of course, the mnemonics for PowerPC are all different from those for x86, which makes understanding it difficult if you've only ever studied x86. You can look up the mnemonics, but even without going through that much effort, you can still pick out a lot of what I've mentioned—the "simpler" instructions, the separate loads (lwzu) and stores (stw), and the three operands instead of two.

Curiously, both because of the code that was selected as the example and because of the magic of an optimizing compiler, there isn't that much difference between the x86 ("CISC") disassembly and the PowerPC ("RISC") disassembly.


来源: stackexchange

问:
Python redirect to URL not working
I know there are other posts on this, but I've tried everything I can think of and still can't get a simple redirect working as a CGI script on a Linux server. I've tried 3 different methods and none of them works. I know some people will suggest removing the first two print statements after the import, but that gives me 500 Server error. All I'm trying to do is have the browser redirect to another URL when this python CGI script is called. </p>

```<code>#!/usr/bin/env python
import cgi, cgitb
print "Content-Type: text/html"
print

def go_to_url(url):
    print "HTTP/1.1 302 Found"
    print "Location: ",url,"\r\n"
    print "Connection: close \r\n"
    print " "

def go_to_url2(url):
    print ('<script type="text/javascript">window.location = ' + url + ';</script>')

def go_to_url3(url):
    print '<html><head><script type="text/javascript">'
    print '<!-- function jump(){window.location = "' + url + '" } //-->'
    print '</script></head><body onLoad="jump()"></body></html>'

url = 'http://www.yahoo.com'
# go_to_url(url)
# go_to_url2(url)
go_to_url3(url)
</code>```

答:
First, it's important to keep in mind that the HTTP version should be dynamic by the client's browser, you shouldn't force it.

Javascript solution for HTTP redirect creates more overhead in performance.

Because 1st request is for an HTML page with the JS redirect code, then a 2nd request is for the redirect itself ( two requests in total vs one )

I believe you can't redirect after you've printed print "Content-Type: text/html".

Your script should look something like this:

```<code>#!/usr/bin/env python
import cgi

def print_http_header():
    print "Content-type: text/html; charset=UTF-8"
    print

def go_to_url(url):
    # HTTP version ( 1.0 / 1.1 / 2.0 ) should be determine by browser
    print "Status: 302 Moved"
    print "Location: %s" % url
    print

def go_to_url2(url):
    print_http_header()
    print ('<script type="text/javascript">window.location = ' + url + ';</script>')

def go_to_url3(url):
    print_http_header()
    print '<html><head><script type="text/javascript">'
    print '<!-- function jump(){window.location = "' + url + '" } //-->'
    print '</script></head><body onLoad="jump()"></body></html>'

url = 'http://www.yahoo.com'
# go_to_url(url)
# go_to_url2(url)
go_to_url3(url)
</code>```

Hope that helps....

ContentLicense: CC BY-SA 3.0

Title: Python redirect to URL not working

Body:
I know there are other posts on this, but I've tried everything I can think of and still can't get a simple redirect working as a CGI script on a Linux server. I've tried 3 different methods and none of them works. I know some people will suggest removing the first two print statements after the import, but that gives me 500 Server error. All I'm trying to do is have the browser redirect to another URL when this python CGI script is called.

#!/usr/bin/env python
import cgi, cgitb
print "Content-Type: text/html"
print

def go_to_url(url):
    print "HTTP/1.1 302 Found"
    print "Location: ",url,"\r\n"
    print "Connection: close \r\n"
    print " "

def go_to_url2(url):
    print ('')

def go_to_url3(url):
    print ''

url = 'http://www.yahoo.com'
# go_to_url(url)
# go_to_url2(url)
go_to_url3(url)

Body:
First, it's important to keep in mind that the HTTP version should be dynamic by the client's browser, you shouldn't force it.

Javascript solution for HTTP redirect creates more overhead in performance.

Because 1st request is for an HTML page with the JS redirect code, then a 2nd request is for the redirect itself ( two requests in total vs one )

I believe you can't redirect after you've printed print "Content-Type: text/html".

Your script should look something like this:

#!/usr/bin/env python
import cgi

def print_http_header():
    print "Content-type: text/html; charset=UTF-8"
    print

def go_to_url(url):
    # HTTP version ( 1.0 / 1.1 / 2.0 ) should be determine by browser
    print "Status: 302 Moved"
    print "Location: %s" % url
    print

def go_to_url2(url):
    print_http_header()
    print ('<script type="text/javascript">window.location = ' + url + ';</script>')

def go_to_url3(url):
    print_http_header()
    print '<html><head><script type="text/javascript">'
    print '<!-- function jump(){window.location = "' + url + '" } //-->'
    print '</script></head><body onLoad="jump()"></body></html>'

url = 'http://www.yahoo.com'
# go_to_url(url)
# go_to_url2(url)
go_to_url3(url)

Hope that helps....


问:
mongoose where on array of data nested
my collection is like this:

```<code>{
"_id" : ObjectId("590886af47627f86e5857141"),
"code" : "MY",
"pre_title" : "republic of",
"name" : "Malaysia",
"topics" : [
    {
        "name" : "overview",
        "body" : "ergergerg123234",
        "type" : "info",
        "_id" : ObjectId("5931243d26fca3496dbffe92"),
        "facts" : [
            {
                "key" : "capital",
                "value" : "Kuala Lumpur",
                "_id" : ObjectId("5931243d26fca3496dbffe96")
            },
            {
                "key" : "population",
                "value" : "232424234",
                "_id" : ObjectId("5931243d26fca3496dbffe95")
            },
            {
                "key" : "reliogion",
                "value" : "Islam",
                "_id" : ObjectId("5931243d26fca3496dbffe94")
            },
            {
                "key" : "government_form",
                "value" : "Federal constitutional monarchy",
                "_id" : ObjectId("5931243d26fca3496dbffe93")
            }
        ]
    },
    {
        "name" : "Good to know",
        "body" : "here in good to know",
        "type" : "info",
        "_id" : ObjectId("5931243d26fca3496dbffe90"),
        "facts" : [
            {
                "key" : "key1",
                "value" : "value1",
                "_id" : ObjectId("5931243d26fca3496dbffe91")
            }
        ]
    }
]
}
</code>```

I need to get access in topic where topicId ="X" and countryId =_id .I write this lines but result is wrong: so it have two condition. first countryId should match then TopicId

```<code>  var query = {"_id":_id,"topics.$._id": topicId }
   Country.findOne(query ,function (err, topic) {

    console.log('topic',topic);
})
</code>```

UPDATE:

it is working like this but also I need to go inside facts where key={XX}

```<code>Country.findById(query).select({ topics: { $elemMatch: { _id: topicId }
} }).
  .then((topic,err) => {
</code>```

答:
```<code>var query = {"_id":_id,"topics._id": topicId }
 Country.findOne(query,{topics.$:1} ,function (err, topic) {

   console.log('topic',topic);
})
</code>```

remove $ from query use topics._id instead topics.$._id

Title: mongoose where on array of data nested

Body:
my collection is like this:

{
"_id" : ObjectId("590886af47627f86e5857141"),
"code" : "MY",
"pre_title" : "republic of",
"name" : "Malaysia",
"topics" : [
    {
        "name" : "overview",
        "body" : "ergergerg123234",
        "type" : "info",
        "_id" : ObjectId("5931243d26fca3496dbffe92"),
        "facts" : [
            {
                "key" : "capital",
                "value" : "Kuala Lumpur",
                "_id" : ObjectId("5931243d26fca3496dbffe96")
            },
            {
                "key" : "population",
                "value" : "232424234",
                "_id" : ObjectId("5931243d26fca3496dbffe95")
            },
            {
                "key" : "reliogion",
                "value" : "Islam",
                "_id" : ObjectId("5931243d26fca3496dbffe94")
            },
            {
                "key" : "government_form",
                "value" : "Federal constitutional monarchy",
                "_id" : ObjectId("5931243d26fca3496dbffe93")
            }
        ]
    },
    {
        "name" : "Good to know",
        "body" : "here in good to know",
        "type" : "info",
        "_id" : ObjectId("5931243d26fca3496dbffe90"),
        "facts" : [
            {
                "key" : "key1",
                "value" : "value1",
                "_id" : ObjectId("5931243d26fca3496dbffe91")
            }
        ]
    }
]
}

I need to get access in topic where topicId ="X" and countryId =_id .I write this lines but result is wrong: so it have two condition. first countryId should match then TopicId

  var query = {"_id":_id,"topics.$._id": topicId }
   Country.findOne(query ,function (err, topic) {

    console.log('topic',topic);
})

UPDATE:

it is working like this but also I need to go inside facts where key={XX}

Country.findById(query).select({ topics: { $elemMatch: { _id: topicId }
} }).
  .then((topic,err) => {

Body:
var query = {"_id":_id,"topics._id": topicId }
 Country.findOne(query,{topics.$:1} ,function (err, topic) {

   console.log('topic',topic);
})

remove $ from query use topics._id instead topics.$._id


问:
Removing similar rows using GROUP BY / DISTINCT
I currently have a table of document paths next to an ID and other metadata, however the same file path is referenced multiple times with different IDs.

An example data set:

```<code>ID           FullPath
1            \\some\file\path.txt
2            \\some\file\path.txt
3            \\some\file\path.txt
4            \\another\file\path.txt
5            \\another\file\path.txt
</code>```

I want to return a distinct set of paths and do not need the other IDs. It is probably quite a simple GROUP BY aggregate function but I can't figure it out. Please help!

I think I want something along these lines, but to be selecting the ID from the subquery instead of the path as the path causes it to return all rows. But I cant do that and GROUP BY the FullPath!

```<code>select *
from Documents
where FullPath in (
    select min(FullPath)
    from Documents
    group by FullPath
)
</code>```

Results I am after:

```<code>ID           FullPath
1            \\some\file\path.txt
4            \\another\file\path.txt
</code>```

答:
If I understand your question, there are multiple ways to do what you want.  But using the structure that you have chosen, the subquery should be returning id rather than the file path:

```<code>select d.*
from Documents d
where d.FullPath in (select min(d2.id)
                     from Documents d2
                     group by d2.FullPath
                    );
</code>```

I more natural way to get just the two columns is:

```<code>select fullpath, min(id)
from Documents
group by fullpath;
</code>```

Or, if you want other columns, use row_number() or rank().

Body:
I currently have a table of document paths next to an ID and other metadata, however the same file path is referenced multiple times with different IDs.

An example data set:

ID           FullPath
1            \\some\file\path.txt
2            \\some\file\path.txt
3            \\some\file\path.txt
4            \\another\file\path.txt
5            \\another\file\path.txt

I want to return a distinct set of paths and do not need the other IDs. It is probably quite a simple GROUP BY aggregate function but I can't figure it out. Please help!

I think I want something along these lines, but to be selecting the ID from the subquery instead of the path as the path causes it to return all rows. But I cant do that and GROUP BY the FullPath!

select *
from Documents
where FullPath in (
    select min(FullPath)
    from Documents
    group by FullPath
)

Results I am after:

ID           FullPath
1            \\some\file\path.txt
4            \\another\file\path.txt

Body:
If I understand your question, there are multiple ways to do what you want.  But using the structure that you have chosen, the subquery should be returning id rather than the file path:

select d.*
from Documents d
where d.FullPath in (select min(d2.id)
                     from Documents d2
                     group by d2.FullPath
                    );

I more natural way to get just the two columns is:

select fullpath, min(id)
from Documents
group by fullpath;

Or, if you want other columns, use row_number() or rank().


答:
You should use min(id)</p>

```<code>  select *
  from Documents
  where id  in (
      select min(id)
      from Documents
      group by FullPath
  )
</code>```

Title: Removing similar rows using GROUP BY / DISTINCT

Body:
You should use min(id)

  select *
  from Documents
  where id  in (
      select min(id)
      from Documents
      group by FullPath
  )


问:
Mysql join tables with or without a condition
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

```<code>Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;
</code>```

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

答:
The Process MySQL processing the query is that it first Do From clause that is your left join and then where clause on the column you specify and than the it generate the result set based on the column selected in select clause </p>

<p>(asked)At the moment if I put the in('') it wouldn't show anything.
Reason it would look for the column you specify in where clause and find if it contain '' if yes that result would be displayed if not Zero row</p>

Body:
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

Body:
The Process MySQL processing the query is that it first Do From clause that is your left join and then where clause on the column you specify and than the it generate the result set based on the column selected in select clause

(asked)At the moment if I put the in('') it wouldn't show anything.
Reason it would look for the column you specify in where clause and find if it contain '' if yes that result would be displayed if not Zero row


问:
How to access a child's child of a parent Node
I have a challenge accessing a child's child of a parentNode. Below is the xml i am working with:

```<code>String response = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<closure>
    <amount>1055296.0000</amount>
    <currency>USD</currency>
    <unit>2</unit>
    <year>2012</year>
    <taxes>
        <tax>
            <descript>FEE LEVY</descript>
            <taxAmt>
                <amt>30304.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>SUR</taxCode>
        </tax>
        <tax>
            <descript>MED LEVY</descript>
            <taxAmt>
                <amt>25125.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>CIS</taxCode>
        </tax>
    </taxes>
</closure>";
</code>```

Below is the code i have tried:

```<code>     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource src = new InputSource();`
     src.setCharacterStream(new StringReader(response));
     Document doc = builder.parse(src);
     String amount =doc.getElementsByTagName("amount").item(0).getTextContent();
     NodeList nodeList = doc.getElementsByTagName("tax");
     for (int i = 0; i < nodeList.getLength(); i++)
     {
     Node childNode = nodeList.item(i);
     }
</code>```

Please how do i get descript, taxAmt and taxCode inside the element tax?

Body:
I have a challenge accessing a child's child of a parentNode. Below is the xml i am working with:

String response = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<closure>
    <amount>1055296.0000</amount>
    <currency>USD</currency>
    <unit>2</unit>
    <year>2012</year>
    <taxes>
        <tax>
            <descript>FEE LEVY</descript>
            <taxAmt>
                <amt>30304.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>SUR</taxCode>
        </tax>
        <tax>
            <descript>MED LEVY</descript>
            <taxAmt>
                <amt>25125.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>CIS</taxCode>
        </tax>
    </taxes>
</closure>";

Below is the code i have tried:

     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource src = new InputSource();`
     src.setCharacterStream(new StringReader(response));
     Document doc = builder.parse(src);
     String amount =doc.getElementsByTagName("amount").item(0).getTextContent();
     NodeList nodeList = doc.getElementsByTagName("tax");
     for (int i = 0; i < nodeList.getLength(); i++)
     {
     Node childNode = nodeList.item(i);
     }

Please how do i get descript, taxAmt and taxCode inside the element tax?

Body: doc.getElementsByTagName("amount").item(0).getFirstChild().getNodeValue()


问:
How does V8 inline caching work with delete and computed property access?
As exampled in https://github.com/v8/v8/wiki/Design%20Elements#fast-property-access, I (attempt to) understand that properties of an object are stored based in a hidden class, call it "C[N]", of its constructor. I may not have understood it correctly... For example:

```<code>// Let's suppose Object has these hidden classes already

/* Object[[HiddenClasses]] > C0, C1, C2
 *
 * C0 - for "x", goto C1
 * C1 - "x"; for "y", goto C2
 * C2 - "x", "y";
 */

var obj = {
    x: 0
};
// Currently based in C1 to get/put properties

obj.y = 0;
// Now based in C2
</code>```

1. What happens if this new object adds a new property?

```<code>obj.z = 0
</code>```

Will it still behave like the first instance of Object?

2. What happens if an object of the same constructor adds properties in opposite order of the hidden classes?

```<code>({ y: 5; }); // Will this be based in C2?
</code>```

3. What happens if a property is deleted? Is its value only changed in memory for representing deleted?

4. Are lookups done inside hidden classes when the compiler can't see an object or name of its computed property access? I.e.:

```<code>({ [Math.random()]: 0 }),
randomlyReceivedObject.property;
</code>```

答:
After obj.z = 0, C2 gets a new transition for "z", goto C3, and a new hidden class C3 - "x", "y", "z" is created for the object.

That object will have a new hidden class C4 - "y". And C0 gets a new transition: for "y", goto C4. If that object later gets an "x" property, a new hidden class C5 - "y", "x" will be created, and a transition in C4: for "x", goto C5. C5 and C2 will forever remain distinct. This is actually mandated by the JavaScript spec, because e.g. a for..in loop Object.getOwnPropertyKeys must iterate properties in creation order, and V8 keeps track of property creation order via hidden classes.
Since having more hidden classes naturally has a speed and memory cost, it is generally recommended to always create properties in the same order (e.g. by using a constructor function).

When a property is deleted, the object is put into dictionary mode, and hidden classes are no longer used to keep track of its properties. Internally this is implemented via a special hidden class: C6 - all properties are in the properties dictionary. Every subsequent property access will then require a dictionary lookup. If you want to avoid this, you can manually overwrite properties instead of deleting them: obj.x = null or similar. (Fine print: as of very recent V8 versions, there is an exception to this, where if the last property is deleted, then the last hidden class transition is rolled back. This implementation detail may or may not stick around in the future, so don't rely on it.)

Hidden classes are always used for lookups. Inline caches simply cache the results of these lookups; this always happens at execution time, not at compilation time. "The compiler" generally can't "see" objects, because at compilation time there are no objects yet.

Body:
As exampled in https://github.com/v8/v8/wiki/Design%20Elements#fast-property-access, I (attempt to) understand that properties of an object are stored based in a hidden class, call it "C[N]", of its constructor. I may not have understood it correctly... For example:

// Let's suppose Object has these hidden classes already

/* Object[[HiddenClasses]] > C0, C1, C2
 *
 * C0 - for "x", goto C1
 * C1 - "x"; for "y", goto C2
 * C2 - "x", "y";
 */

var obj = {
    x: 0
};
// Currently based in C1 to get/put properties

obj.y = 0;
// Now based in C2

1. What happens if this new object adds a new property?

obj.z = 0

Will it still behave like the first instance of Object?

2. What happens if an object of the same constructor adds properties in opposite order of the hidden classes?

({ y: 5; }); // Will this be based in C2?

3. What happens if a property is deleted? Is its value only changed in memory for representing deleted?

4. Are lookups done inside hidden classes when the compiler can't see an object or name of its computed property access? I.e.:

({ [Math.random()]: 0 }),
randomlyReceivedObject.property;


问:
Hibernate not deleting rows
I am currently developing a Java EE application using hibernate as ORM.
I am using the DAO design pattern. I want to delete a row from the contact table but I don't know why it is not working. When I delete société it works.

I have a relation between société and contact. When a contact has idSociéte=null it is deleted, but if it exist it will not delete it. When I did delete in phpmysadmin it works even if idSociété not null.

```<code>@Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
    @PersistenceContext
    private EntityManager em;

    protected Class<T> daoType;

    public GenericDaoImp() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        daoType = (Class) pt.getActualTypeArguments()[0];
    }

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public Class<T> getDaoType() {
        return daoType;
    }

    public void setDaoType(Class<T> daoType) {
        this.daoType = daoType;
    }

    public void insert(T t) {
        // TODO Auto-generated method stub
        em.persist(t);

    }

    public void update(T t) {
        // TODO Auto-generated method stub
        em.merge(t);
    }

    public void delete(T t) {
        // TODO Auto-generated method stub
        Object managed = em.merge(t);
        em.remove(managed);

    }

    public T findById(Class<T> t, int id) {
        // TODO Auto-generated method stub
        return em.find(daoType, id);
    }

    public List<T> findAll() {
        // TODO Auto-generated method stub
        Query query = em.createQuery("SELECT e FROM " + daoType.getName() + " e");
        return (List<T>) query.getResultList();
    }

}

   package biz.picosoft.entity;

    @Entity
    @Table(name = "Contacte")
    public class Contacte implements Serializable {

        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "idContact")
        int idContact;
        @Column(name = "nom")
        String nom;
        @Column(name = "mail")
        String mail;
        @Column(name = "téléphone")
        String téléphone;
        @Column(name = "adresse")
        String adresse;
        @ManyToOne
        @JoinColumn(name = "société_id")
        private Société société;

        public Contacte() {
            super();
        }

        public long getIdContact() {
            return idContact;
        }

        public Contacte(String nom, String mail, String téléphone, String adresse, Société société) {
            super();
            this.nom = nom;
            this.mail = mail;
            this.téléphone = téléphone;
            this.adresse = adresse;
            this.société = société;
        }

        public Contacte(int idContact, String nom, String mail, String téléphone, String adresse, Société société) {
            super();
            this.idContact = idContact;
            this.nom = nom;
            this.mail = mail;
            this.téléphone = téléphone;
            this.adresse = adresse;
            this.société = société;
        }

        public void setIdContact(int idContact) {
            this.idContact = idContact;
        }

        public String getNom() {
            return nom;
        }

        public void setNom(String nom) {
            this.nom = nom;
        }

        public String getMail() {
            return mail;
        }

        public void setMail(String mail) {
            this.mail = mail;
        }

        public String getTéléphone() {
            return téléphone;
        }

        public void setTéléphone(String téléphone) {
            this.téléphone = téléphone;
        }

        public String getAdresse() {
            return adresse;
        }

        public void setAdresse(String adresse) {
            this.adresse = adresse;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (int) (idContact ^ (idContact >>> 32));
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Contacte other = (Contacte) obj;
            if (idContact != other.idContact)
                return false;
            return true;
        }

        public Société getSociété() {
            return société;
        }

        public void setSociété(Société société) {
            this.société = société;
        }

    }

    package biz.picosoft.daoImpl;

    @Component
    public class ContacteDaoImpl extends GenericDaoImp<Contacte> implements ContacteDao {

    }

package biz.picosoft.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity(name = "société")
@Table(name="société")
public class Société implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idSociété")
    int idSociété;
    @Column(name =  "nom")
    String nom;
    @Column(name = "email")
    String email;
    @Column(name = "télèphone")
    String télèphone;
    @Column(name = "adress")
    String adress;
    @OneToMany (fetch = FetchType.EAGER,mappedBy = "société", cascade = CascadeType.ALL)
    private List<Contacte> contacts;

     public Société(String nom, String email, String télèphone, String adress) {
        super();
        this.nom = nom;
        this.email = email;
        this.télèphone = télèphone;
        this.adress = adress;
    }

    public Société(int idSociété, String nom, String email, String télèphone, String adress) {
        super();
        this.idSociété = idSociété;
        this.nom = nom;
        this.email = email;
        this.télèphone = télèphone;
        this.adress = adress;
        this.contacts = contacts;
    }

    public Société() {
        super();
    }

    public int getIdSociété() {
        return idSociété;
    }

    public void setIdSociété(int idSociété) {
        this.idSociété = idSociété;
    }
    @Column(name =  "nom")
    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTélèphone() {
        return télèphone;
    }

    public void setTélèphone(String télèphone) {
        this.télèphone = télèphone;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public List<Contacte> getContacts() {
        return contacts;
    }

    public void setContacts(List<Contacte> contacts) {
        this.contacts = contacts;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + idSociété;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Société other = (Société) obj;
        if (idSociété != other.idSociété)
            return false;
        return true;
    }

}
</code>```

答:
when a contact has idSociéte=null it is deleted but if it exist it
  will not delete it.

It means if the idSociete is not null and have some value for eg. 123. You need to check if any of the contact have the same idSociete. if it's present with any other contact then your contact will not be deleted as Many contacts can be associated with same société. Try with single contact and a single société associated with it.

Title: Hibernate not deleting rows

Body:
I am currently developing a Java EE application using hibernate as ORM.
I am using the DAO design pattern. I want to delete a row from the contact table but I don't know why it is not working. When I delete société it works.

I have a relation between société and contact. When a contact has idSociéte=null it is deleted, but if it exist it will not delete it. When I did delete in phpmysadmin it works even if idSociété not null.

@Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
    @PersistenceContext
    private EntityManager em;

    protected Class<T> daoType;

    public GenericDaoImp() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        daoType = (Class) pt.getActualTypeArguments()[0];
    }

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public Class<T> getDaoType() {
        return daoType;
    }

    public void setDaoType(Class<T> daoType) {
        this.daoType = daoType;
    }

    public void insert(T t) {
        // TODO Auto-generated method stub
        em.persist(t);

    }

    public void update(T t) {
        // TODO Auto-generated method stub
        em.merge(t);
    }

    public void delete(T t) {
        // TODO Auto-generated method stub
        Object managed = em.merge(t);
        em.remove(managed);

    }

    public T findById(Class<T> t, int id) {
        // TODO Auto-generated method stub
        return em.find(daoType, id);
    }

    public List<T> findAll() {
        // TODO Auto-generated method stub
        Query query = em.createQuery("SELECT e FROM " + daoType.getName() + " e");
        return (List<T>) query.getResultList();
    }

}

   package biz.picosoft.entity;

    @Entity
    @Table(name = "Contacte")
    public class Contacte implements Serializable {

        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "idContact")
        int idContact;
        @Column(name = "nom")
        String nom;
        @Column(name = "mail")
        String mail;
        @Column(name = "téléphone")
        String téléphone;
        @Column(name = "adresse")
        String adresse;
        @ManyToOne
        @JoinColumn(name = "société_id")
        private Société société;

        public Contacte() {
            super();
        }

        public long getIdContact() {
            return idContact;
        }

        public Contacte(String nom, String mail, String téléphone, String adresse, Société société) {
            super();
            this.nom = nom;
            this.mail = mail;
            this.téléphone = téléphone;
            this.adresse = adresse;
            this.société = société;
        }

        public Contacte(int idContact, String nom, String mail, String téléphone, String adresse, Société société) {
            super();
            this.idContact = idContact;
            this.nom = nom;
            this.mail = mail;
            this.téléphone = téléphone;
            this.adresse = adresse;
            this.société = société;
        }

        public void setIdContact(int idContact) {
            this.idContact = idContact;
        }

        public String getNom() {
            return nom;
        }

        public void setNom(String nom) {
            this.nom = nom;
        }

        public String getMail() {
            return mail;
        }

        public void setMail(String mail) {
            this.mail = mail;
        }

        public String getTéléphone() {
            return téléphone;
        }

        public void setTéléphone(String téléphone) {
            this.téléphone = téléphone;
        }

        public String getAdresse() {
            return adresse;
        }

        public void setAdresse(String adresse) {
            this.adresse = adresse;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (int) (idContact ^ (idContact >>> 32));
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Contacte other = (Contacte) obj;
            if (idContact != other.idContact)
                return false;
            return true;
        }

        public Société getSociété() {
            return société;
        }

        public void setSociété(Société société) {
            this.société = société;
        }

    }

    package biz.picosoft.daoImpl;

    @Component
    public class ContacteDaoImpl extends GenericDaoImp<Contacte> implements ContacteDao {

    }

package biz.picosoft.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity(name = "société")
@Table(name="société")
public class Société implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idSociété")
    int idSociété;
    @Column(name =  "nom")
    String nom;
    @Column(name = "email")
    String email;
    @Column(name = "télèphone")
    String télèphone;
    @Column(name = "adress")
    String adress;
    @OneToMany (fetch = FetchType.EAGER,mappedBy = "société", cascade = CascadeType.ALL)
    private List<Contacte> contacts;

     public Société(String nom, String email, String télèphone, String adress) {
        super();
        this.nom = nom;
        this.email = email;
        this.télèphone = télèphone;
        this.adress = adress;
    }

    public Société(int idSociété, String nom, String email, String télèphone, String adress) {
        super();
        this.idSociété = idSociété;
        this.nom = nom;
        this.email = email;
        this.télèphone = télèphone;
        this.adress = adress;
        this.contacts = contacts;
    }

    public Société() {
        super();
    }

    public int getIdSociété() {
        return idSociété;
    }

    public void setIdSociété(int idSociété) {
        this.idSociété = idSociété;
    }
    @Column(name =  "nom")
    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTélèphone() {
        return télèphone;
    }

    public void setTélèphone(String télèphone) {
        this.télèphone = télèphone;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public List<Contacte> getContacts() {
        return contacts;
    }

    public void setContacts(List<Contacte> contacts) {
        this.contacts = contacts;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + idSociété;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Société other = (Société) obj;
        if (idSociété != other.idSociété)
            return false;
        return true;
    }

}


问:
Reanaming xcode project having older test file
I have a old project EmojiMaker and now i have renamed the project as Emoji Maker Pro.The display name, bundle id and other files have been renamed.There is a test folder with same old name,i have also renamed to new one ,but the .m file still has old filename.Will it create any issue while the project to app store?</p>

答:
no no any issue create for that but you verify

click on project then show in right side identify and type in select proper location of your project.. so no issue generate.


问:
pull property object as parent object
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

```<code>let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]
</code>```

How can I group school first? I need the format to be like this

```<code>[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]
</code>```

答:
Use reduce and simply push a new object into your resulting array if id not exist, else just update the data array in the found object</p>

```<code>const myArray = x.reduce((res, data) => {
  const found = res.find(o => o.id === data.school.id);

  if (!found) {
    res.push({
        id: data.school.id,
        name: data.school.name,
        data: [data]
    });
  } else {
    found.data.push(data);
  }
  return res;
}, []);

console.log(myArray)
</code>```

Title: pull property object as parent object

Body:
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]

How can I group school first? I need the format to be like this

[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]

Body:
Use reduce and simply push a new object into your resulting array if id not exist, else just update the data array in the found object

const myArray = x.reduce((res, data) => {
  const found = res.find(o => o.id === data.school.id);

  if (!found) {
    res.push({
        id: data.school.id,
        name: data.school.name,
        data: [data]
    });
  } else {
    found.data.push(data);
  }
  return res;
}, []);

console.log(myArray)


问:
Why it seems to cost more for a big string to get length? What's the complexity string.length?
According to time complexity or hidden cost of <Array Name>.length in java , it's a O(1) operating for an array to get length in java. As String is an array of char, I think it is the same.

But when I do a simple test:

```<code>public static void main(String args[]) {
    String a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    for (int i = 0; i < 23; i++){
        long start = System.nanoTime();
        int l = a.length();
        long end = System.nanoTime();
        System.out.println("length: " + l + " cost: " + String.valueOf(end - start));
        a = a + a;
    }
}
</code>```

And get

```<code>length: 100 cost: 395
length: 200 cost: 395
length: 400 cost: 395
length: 800 cost: 394
length: 1600 cost: 395
length: 3200 cost: 394
length: 6400 cost: 395
length: 12800 cost: 394
length: 25600 cost: 394
length: 51200 cost: 395
length: 102400 cost: 789
length: 204800 cost: 789
length: 409600 cost: 1974
length: 819200 cost: 790
length: 1638400 cost: 3158
length: 3276800 cost: 3553
length: 6553600 cost: 4342
length: 13107200 cost: 3552
length: 26214400 cost: 2368
length: 52428800 cost: 6711
length: 104857600 cost: 3158
length: 209715200 cost: 1974
</code>```

It seems the length operating cost much more when there are more than 400000 characters.

Did I miss or misunderstand something?

答:
String.length() is indeed O(1). If you look in the class (available since Java 1.6) it returns a field.

```<code>public int length() {
    return value.length;
}
</code>```

So I would say your benchmark technique must be introducing error.

Body:
According to time complexity or hidden cost of <Array Name>.length in java , it's a O(1) operating for an array to get length in java. As String is an array of char, I think it is the same.

But when I do a simple test:

public static void main(String args[]) {
    String a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    for (int i = 0; i < 23; i++){
        long start = System.nanoTime();
        int l = a.length();
        long end = System.nanoTime();
        System.out.println("length: " + l + " cost: " + String.valueOf(end - start));
        a = a + a;
    }
}

And get

length: 100 cost: 395
length: 200 cost: 395
length: 400 cost: 395
length: 800 cost: 394
length: 1600 cost: 395
length: 3200 cost: 394
length: 6400 cost: 395
length: 12800 cost: 394
length: 25600 cost: 394
length: 51200 cost: 395
length: 102400 cost: 789
length: 204800 cost: 789
length: 409600 cost: 1974
length: 819200 cost: 790
length: 1638400 cost: 3158
length: 3276800 cost: 3553
length: 6553600 cost: 4342
length: 13107200 cost: 3552
length: 26214400 cost: 2368
length: 52428800 cost: 6711
length: 104857600 cost: 3158
length: 209715200 cost: 1974

It seems the length operating cost much more when there are more than 400000 characters.

Did I miss or misunderstand something?

Body:
String.length() is indeed O(1). If you look in the class (available since Java 1.6) it returns a field.

public int length() {
    return value.length;
}

So I would say your benchmark technique must be introducing error.


问:
how to unit test a delete method using JustMock lite
I am just getting started with unit testing and now stuck writing a test method for delete. I am using JustMock. Below I have mentioned my controller action method and test method but the test method is not working. The return value of the method is not retaining it's always returning false. Please guide me on what I'm doing wrong here.

This is the test method.

```<code>   [TestMethod]
    public void Delete_User()
    {
        Mapper.CreateMap<UserViewModel,User>();

        IStaticMembershipService membershipRepository = Mock.Create<IStaticMembershipService>();

        var mockUserViewModel = new UserViewModel { Id = 1};

        var mockUser = Mapper.Map<UserViewModel, User>(mockUserViewModel);
        var UserRepository = Mock.Create<IUserRepository>();

        Mock.Arrange(() => UserRepository.DeleteUser(mockUser)).Returns(new OperationStatus { Status = true }).MustBeCalled();

        UserController controller = new UserController(UserRepository, membershipRepository);
        ActionResult result = controller.Delete(mockUserViewModel);

        Mock.Assert(() => UserRepository.DeleteUser(mockUser), Occurs.AtLeastOnce());
    }
</code>```

Any relevant controller info.

```<code>    private IUserRepository _UserRepository;
    private IStaticMembershipService _membershipService;

    public UserController(IUserRepository UserRepo, IStaticMembershipService membershipService)
    {
        _UserRepository = UserRepo;
        _membershipService = membershipService;
    }
</code>```

The repository is mocked correctly but the "opStatus" property getting returned is always false not the value I have specified to be the result in testmethod.

```<code>    public ActionResult Delete(UserViewModel usr)
    {
        var selectedUser = Mapper.Map<UserViewModel, User>(usr);

        var opStatus = _UserRepository.DeleteUser(selectedUser);
        if (!opStatus.Status)
            throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

        return RedirectToAction("Index");
    }
</code>```

I hope i have provided enough information. Any help much appreciated.

答:
Change:

Mock.Arrange(() => UserRepository.DeleteUser(mockUser)).Returns(new OperationStatus { Status = true }).MustBeCalled();

to:

Mock.Arrange(() => UserRepository.DeleteUser(mockUser)).IgnoreArguments().Returns(new OperationStatus { Status = true }).MustBeCalled();

Alternatively, add equality operators to User so that it realises that mockUser  and selectedUser are the 'same'. Or use lambdas for argument matching (see http://www.telerik.com/blogs/handling-arguments-in-justmock-arrangements).

Body:
I am just getting started with unit testing and now stuck writing a test method for delete. I am using JustMock. Below I have mentioned my controller action method and test method but the test method is not working. The return value of the method is not retaining it's always returning false. Please guide me on what I'm doing wrong here.

This is the test method.

   [TestMethod]
    public void Delete_User()
    {
        Mapper.CreateMap<UserViewModel,User>();

        IStaticMembershipService membershipRepository = Mock.Create<IStaticMembershipService>();

        var mockUserViewModel = new UserViewModel { Id = 1};

        var mockUser = Mapper.Map<UserViewModel, User>(mockUserViewModel);
        var UserRepository = Mock.Create<IUserRepository>();

        Mock.Arrange(() => UserRepository.DeleteUser(mockUser)).Returns(new OperationStatus { Status = true }).MustBeCalled();

        UserController controller = new UserController(UserRepository, membershipRepository);
        ActionResult result = controller.Delete(mockUserViewModel);

        Mock.Assert(() => UserRepository.DeleteUser(mockUser), Occurs.AtLeastOnce());
    }

Any relevant controller info.

    private IUserRepository _UserRepository;
    private IStaticMembershipService _membershipService;

    public UserController(IUserRepository UserRepo, IStaticMembershipService membershipService)
    {
        _UserRepository = UserRepo;
        _membershipService = membershipService;
    }

The repository is mocked correctly but the "opStatus" property getting returned is always false not the value I have specified to be the result in testmethod.

    public ActionResult Delete(UserViewModel usr)
    {
        var selectedUser = Mapper.Map<UserViewModel, User>(usr);

        var opStatus = _UserRepository.DeleteUser(selectedUser);
        if (!opStatus.Status)
            throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

        return RedirectToAction("Index");
    }

I hope i have provided enough information. Any help much appreciated.


问:
Error 3706 Visual FoxPro OLE DB Provider and Excel
I made an application that uses VBA in order to read Excel 2013 sheets, and save data in Visual FoxPro tables. This app runs very fine in my computer, but when I run on another computer, issues this error: “Run time error 3706 Provider cannot be found, it may not be properly installed.” I installed, uninstalled, and back to install OLE DB Provider (Microsoft OLE DB Provider for Visual FoxPro, that comes with VFP SP2)  and VFP runtime files (VFP 9 SP2), but error is issued again. Why does it happen? How can I solve that?

Both computers uses Microsoft Windows 7 Professional SP1 64 bits and Microsoft Office 2013 Professional 32 Bits.

Thanks in advance for your help.

答:
Instead of using VBA and VFPOLEDB, simply use VFP and Microsoft.ACE.Oledb driver to read excel tables. You can check:

importing exporting excel files sample


问:
Android: Edittext that only allows a digit from 1-9
I am looking for a way so that users can only input a number between 1-9 with edittext. No exception should be displayed. It should not be possible to type in more than one digit. </p>

答:
1. Use attribute android:inputType="number" to take input only number 0-9

2. Use attribute android:digits="123456789" to take only 1-9

3. Use attribute android:maxLength="1" to allow user to input only a  single digit.

Try this:

```<code><EditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:digits="123456789"
    android:maxLength="1"/>
</code>```

Body:
1. Use attribute android:inputType="number" to take input only number 0-9

2. Use attribute android:digits="123456789" to take only 1-9

3. Use attribute android:maxLength="1" to allow user to input only a  single digit.

Try this:

<EditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:digits="123456789"
    android:maxLength="1"/>


问:
Reading a string, char[] until end of line C
I need to read a file name, but I want my code working for names contains space.
How to read until end of line from keyboard?

My code:

```<code>#define szoveghosz 256
//....
char bemenet[szoveghosz];
fgets (bemenet,sizeof(bemenet),stdin);
</code>```

答:
Read carefully the documentation of fgets(3) (which might be locally available on your Linux computer with man fgets)

fgets() reads in at most one less than size characters from stream
         and stores them into the buffer pointed to by s.  Reading stops after
         an EOF or a newline.  If a newline is read, it is stored into the
         buffer.  A terminating null byte ('\0') is stored after the last
         character in the buffer.

As documented, fgets will (when possible) keep the newline character. You probably want to remove it. So I recommend coding instead

```<code> memset (bemenet, 0, sizeof(bemenet)); // clear the buffer
 if (fgets(bemenet, sizeof(bemenet), stdin)) {
    char *eol = strchr(bemenet, '\n');
    if (eol)
       *eol = '\0';
    /// do appropriate things on bemenet
 }
</code>```

See also strchr(3) & memset(3)

But as I commented, on Linux and POSIX systems, getline(3) is preferable (because it is allocating dynamically an arbitrarily long line). See this.

Notice that (in principle) a filename could contain a newline (but in most cases, you can forget that possibility). See also glob(3) & wordexp(3) and glob(7) and path_resolution(7).

Body:
I need to read a file name, but I want my code working for names contains space.
How to read until end of line from keyboard?

My code:

#define szoveghosz 256
//....
char bemenet[szoveghosz];
fgets (bemenet,sizeof(bemenet),stdin);

Body:
Read carefully the documentation of fgets(3) (which might be locally available on your Linux computer with man fgets)

fgets() reads in at most one less than size characters from stream
         and stores them into the buffer pointed to by s.  Reading stops after
         an EOF or a newline.  If a newline is read, it is stored into the
         buffer.  A terminating null byte ('\0') is stored after the last
         character in the buffer.

As documented, fgets will (when possible) keep the newline character. You probably want to remove it. So I recommend coding instead

 memset (bemenet, 0, sizeof(bemenet)); // clear the buffer
 if (fgets(bemenet, sizeof(bemenet), stdin)) {
    char *eol = strchr(bemenet, '\n');
    if (eol)
       *eol = '\0';
    /// do appropriate things on bemenet
 }

See also strchr(3) & memset(3)

But as I commented, on Linux and POSIX systems, getline(3) is preferable (because it is allocating dynamically an arbitrarily long line). See this.

Notice that (in principle) a filename could contain a newline (but in most cases, you can forget that possibility). See also glob(3) & wordexp(3) and glob(7) and path_resolution(7).


问:
Optimize MySQL Query ti may it faster
I am fairly new to MySQL and would like to ask how can you fine tune this query or rewrite it in a better way.

```<code> SELECT *
 FROM emp
 WHERE birth_date BETWEEN '1999-05-01'
 AND '1999-05-31'
 OR last_name in ('Bart', 'Martha', 'Lisa');
</code>```

Your assistance is greatly appreciated. Can you also explain why you did it so I would know

Thanks.

答:
I think this question SQL Performance UNION vs OR  is what you are looking for
the first answer explains the difference between OR and UNION and in your case this might be the best optimization. </p>

Title: Optimize MySQL Query ti may it faster

Body:
I am fairly new to MySQL and would like to ask how can you fine tune this query or rewrite it in a better way.

 SELECT *
 FROM emp
 WHERE birth_date BETWEEN '1999-05-01'
 AND '1999-05-31'
 OR last_name in ('Bart', 'Martha', 'Lisa');

Your assistance is greatly appreciated. Can you also explain why you did it so I would know

Thanks.


问:
Group following rows using only one flag
I have a table with a Flag column which can be true/false.
I would like to group rows and calculate average of column Val as shown in the picture below:

Source table and Desired results

Body:
You can do this with a derived table and windowed functions:

declare @t table(ID int,Val decimal(10,2),Flag bit);
insert into @t values (515,5.4,0),(516,1,1),(517,0,0),(518,0,0),(519,3,0),(520,7,0),(521,8,0),(522,2,0),(523,5,0),(524,3,1),(525,1,0),(526,2,0),(527,3,0),(528,2,0),(529,8,0),(530,9,0),(531,0,0),(532,4,1),(533,0,0),(534,2,0),(535,1,0),(536,0,0),(537,0,1),(538,1,0);

with c as
(
    select ID
            ,Val
            ,Flag
            ,sum(cast(Flag as int)) over (order by ID) as rn
    from @t
)
select cast(min(ID) as nvarchar(10)) + ' to ' + cast(max(ID) as nvarchar(10)) as IDRange
    ,avg(Val) as AverageVal
from c
group by rn
order by rn;

Output:

+------------+------------+
|  IDRange   | AverageVal |
+------------+------------+
| 515 to 515 |        5.4 |
| 516 to 523 |       3.25 |
| 524 to 531 |        3.5 |
| 532 to 536 |        1.4 |
| 537 to 538 |        0.5 |
+------------+------------+

Update for 2008 R2 version

This utilises recursion to get your running grouping so can probably be improved upon, but will get you the results you want:

declare @t table(ID int,Val decimal(10,2),Flag bit);
insert into @t values (515,5.4,0),(516,1,1),(517,0,0),(518,0,0),(519,3,0),(520,7,0),(521,8,0),(522,2,0),(523,5,0),(524,3,1),(525,1,0),(526,2,0),(527,3,0),(528,2,0),(529,8,0),(530,9,0),(531,0,0),(532,4,1),(533,0,0),(534,2,0),(535,1,0),(536,0,0),(537,0,1),(538,1,0);

with t as
(
    select ID
            ,Val
            ,Flag
            ,row_number() over (order by ID) as rn
    from @t
),c as
(
    select ID
            ,Val
            ,Flag
            ,rn
            ,0 as g
    from t
    where rn = 1

    union all

    select t.ID
            ,t.Val
            ,t.Flag
            ,t.rn
            ,c.g + cast(t.Flag as int) as g
    from t
        join c
            on t.rn = c.rn+1
)
select cast(min(ID) as nvarchar(10)) + ' to ' + cast(max(ID) as nvarchar(10)) as IDRange
    ,avg(Val) as AverageVal
from c
group by g
order by g;


问:
How to add tabs to TabLayout in layout XML file in Android?
I have been studying Android for two weeks. Now I am developing my first Android project.

In my project I need to work with Tabs together with action bar. I know that is very common in Android. For action bar I am using toolbar with v7. I seriously know about action bar. But I have an issue with tab layout. The problem is I want to add tabs to tab layout in layout XML file.

For example:

```<code><TabLayout>
//tab buttton goes here
 <TabButton1></TabButton1>
 <TabButton1></TabButton1>
 .
 .
<TabLayout>
</code>```

I search so many tutorials about tablayout. But all tutorials define tabs for tab layout programmatically. How can I define tabs for tab layout in XML and define event for them programmatically by findViewById? I don't want to use button view instead of tabs.

答:
This should be what you want:</p>

```<code><android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            android:background="?attr/colorPrimary"
            app:tabMode="fixed">

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Popular" />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Most Rated" />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Favorites" />
        </android.support.design.widget.TabLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been studying Android for two weeks. Now I am developing my first Android project.

In my project I need to work with Tabs together with action bar. I know that is very common in Android. For action bar I am using toolbar with v7. I seriously know about action bar. But I have an issue with tab layout. The problem is I want to add tabs to tab layout in layout XML file.

For example:

<TabLayout>
//tab buttton goes here
 <TabButton1></TabButton1>
 <TabButton1></TabButton1>
 .
 .
<TabLayout>

I search so many tutorials about tablayout. But all tutorials define tabs for tab layout programmatically. How can I define tabs for tab layout in XML and define event for them programmatically by findViewById? I don't want to use button view instead of tabs.

Body:
This should be what you want:

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            android:background="?attr/colorPrimary"
            app:tabMode="fixed">

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Popular" />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Most Rated" />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Favorites" />
        </android.support.design.widget.TabLayout>


问:
How persist with Hibernate
I have a class named "Token Requestor" and "Certificates". Each Token Requestor have many Certificates and Certificates have only one Token Requestor.

TokenRequestor.java

```<code>@Entity
@Table(name = "TOKEN_REQUESTOR")
public class TokenRequestor implements Serializable {

    @Id
    @SequenceGenerator(name = "TOKEN_REQUESTOR_ID_GENERATOR", sequenceName = "TOKEN_REQUESTOR_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "TOKEN_REQUESTOR_ID_GENERATOR")
    @Column(name = "TOKEN_REQUESTOR_ID")
    private Long id;
    @OneToMany(mappedBy = "tokenRequestorId")
    private List<Certificate> certificates;
</code>```

Certificate.java

```<code>@Entity
@Table(name = "CERTIFICATES")
public class Certificate {

    @Id
    @SequenceGenerator(name = "CERTIFICATES_ID_GENERATOR", sequenceName = "SQ_CERTIFICATES_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "CERTIFICATES_ID_GENERATOR")
    @Column(name = "CERTIFICATES_ID")
    private Long id;
    @ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @JoinColumn(name = "TOKEN_REQUESTOR_ID")
    private TokenRequestor tokenRequestorId;    //Foreign key*/
</code>```

When I insert a Token Requestor, they certificate must be create. They are created but with TOKEN_REQUESTOR_ID null in Certificate table. Why this happens?

POST Token Requestor

```<code>{
    "domain": "GTW",
    ...,
    "certificates": [
    {
      "usage": "ENC",
      "alias": "encryption_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "DEC",
      "alias": "decryption_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "SSL",
      "alias": "communication_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "CA",
      "alias": "TSP ROOT CA",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    }
  ]
}
</code>```

答:
your problem is that you define the relationship to be bidirectional, which basically means each side of the relation should have reference to the other side.

lets say we have TokenRequestor  object , this object has two Certificates, this would be enough only if the relation is unidirectional ( which you can turn your relation to to solve this issue btw), for a bidirectional relation you need to haveeach one of the Certificate holding a reference to their TokenReguestor.

Title: How persist with Hibernate

Body:
I have a class named "Token Requestor" and "Certificates". Each Token Requestor have many Certificates and Certificates have only one Token Requestor.

TokenRequestor.java

@Entity
@Table(name = "TOKEN_REQUESTOR")
public class TokenRequestor implements Serializable {

    @Id
    @SequenceGenerator(name = "TOKEN_REQUESTOR_ID_GENERATOR", sequenceName = "TOKEN_REQUESTOR_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "TOKEN_REQUESTOR_ID_GENERATOR")
    @Column(name = "TOKEN_REQUESTOR_ID")
    private Long id;
    @OneToMany(mappedBy = "tokenRequestorId")
    private List<Certificate> certificates;

Certificate.java

@Entity
@Table(name = "CERTIFICATES")
public class Certificate {

    @Id
    @SequenceGenerator(name = "CERTIFICATES_ID_GENERATOR", sequenceName = "SQ_CERTIFICATES_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "CERTIFICATES_ID_GENERATOR")
    @Column(name = "CERTIFICATES_ID")
    private Long id;
    @ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @JoinColumn(name = "TOKEN_REQUESTOR_ID")
    private TokenRequestor tokenRequestorId;    //Foreign key*/

When I insert a Token Requestor, they certificate must be create. They are created but with TOKEN_REQUESTOR_ID null in Certificate table. Why this happens?

POST Token Requestor

{
    "domain": "GTW",
    ...,
    "certificates": [
    {
      "usage": "ENC",
      "alias": "encryption_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "DEC",
      "alias": "decryption_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "SSL",
      "alias": "communication_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "CA",
      "alias": "TSP ROOT CA",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    }
  ]
}


问:
Laravel export is not working on server, But working fine on localhost
following is the code which I used for export functionality

```<code>public function export(){
        $users = DB::table('users')->where('user_type','Farmer')->orWhere('user_type','Dealer')->select('id','name','middlename','surname','mobile','state','district','taluka','user_type')->get()->map(function ($item, $key){
            return (array) $item;
        })
        ->all();

        $usersArray = [];
        foreach ($users as $user) {
             $usersArray[] =$user;
        }

        Excel::create('users',function($excel)use($usersArray) {
            $excel->setTitle('users');
            $excel->setCreator('Laravel');
            $excel->setDescription('users file');
            $excel->sheet('sheet1',function($sheet)use($usersArray) {
            $sheet->fromArray($usersArray,null,'A1',true,true);
            });

        })->download('xlsx');
    }
</code>```

This code is working fine on localhost,no issue at localhost, But on server it is showing error that "This site can't be reached", I am unable to figure it out that what is the issue on server.
I even try some other solutions on stackoverflow but unable to work.

答: PHPExcel ZipArchive not found after lot of trouble finally this solution is worked for me. I just append PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP); this line before $zipClass = PHPExcel_Settings::getZipClass(); In File PHPExcel/Reader/Excel2007.php, and Now my export function is running on server too.</p>

Body:
following is the code which I used for export functionality

public function export(){
        $users = DB::table('users')->where('user_type','Farmer')->orWhere('user_type','Dealer')->select('id','name','middlename','surname','mobile','state','district','taluka','user_type')->get()->map(function ($item, $key){
            return (array) $item;
        })
        ->all();

        $usersArray = [];
        foreach ($users as $user) {
             $usersArray[] =$user;
        }

        Excel::create('users',function($excel)use($usersArray) {
            $excel->setTitle('users');
            $excel->setCreator('Laravel');
            $excel->setDescription('users file');
            $excel->sheet('sheet1',function($sheet)use($usersArray) {
            $sheet->fromArray($usersArray,null,'A1',true,true);
            });

        })->download('xlsx');
    }

This code is working fine on localhost,no issue at localhost, But on server it is showing error that "This site can't be reached", I am unable to figure it out that what is the issue on server.
I even try some other solutions on stackoverflow but unable to work.


问:
Kubernetes livenessProbe http result?
We have an HTTP livenessProbe setup which returns a 500 if service is unhealthy, and prints out what the problem is.

Is there any way to view the output that was returned by livenessProbe?

I could log it in the application, but maybe it's possible to view from Kubernetes?

Currently, the only thing that I see doing pod describe:

```<code>Killing container with id docker://12568746c312e6646fd6ecdb2123db448be0bc6808629b1a63ced8b7298be444:pod "test-3893895584-7f4cr_test(524091bd-49d8-11e7-bd00-42010a840224)" container "test" is unhealthy, it will be killed and re-created.
</code>```

Running on GKE

答:
Unfortunately, there does not seem to be a way to access the HTTP response body of a failed HTTP probe.

To confirm this suspicion, let's have a look at the HTTP Prober's source code, which is run within the Kubelet daemon:

```<code>func DoHTTPProbe(url *url.URL, headers http.Header, client HTTPGetInterface) (probe.Result, string, error) {
    // ...
    body := string(b)
    if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusBadRequest {
        glog.V(4).Infof("Probe succeeded for %s, Response: %v", url.String(), *res)
        return probe.Success, body, nil
    }
    glog.V(4).Infof("Probe failed for %s with request headers %v, response body: %v", url.String(), headers, body)
    return probe.Failure, fmt.Sprintf("HTTP probe failed with statuscode: %d", res.StatusCode), nil
}
</code>```

As you can see, the Kubelet daemon will log the HTTP response body of a failed probe in its own log, but even then only if verbosity was set to 4 or higher. Beyond logging the response in its own log, it is not passed back from the DoHTTPProbe method and will not be processed any further by the Kubelet.

As already noted by yourself, I'd think your safest bet would be to log the data you need from within your application itself.

Title: Kubernetes livenessProbe http result?

Body:
We have an HTTP livenessProbe setup which returns a 500 if service is unhealthy, and prints out what the problem is.

Is there any way to view the output that was returned by livenessProbe?

I could log it in the application, but maybe it's possible to view from Kubernetes?

Currently, the only thing that I see doing pod describe:

Killing container with id docker://12568746c312e6646fd6ecdb2123db448be0bc6808629b1a63ced8b7298be444:pod "test-3893895584-7f4cr_test(524091bd-49d8-11e7-bd00-42010a840224)" container "test" is unhealthy, it will be killed and re-created.

Running on GKE

Body:
Unfortunately, there does not seem to be a way to access the HTTP response body of a failed HTTP probe.

To confirm this suspicion, let's have a look at the HTTP Prober's source code, which is run within the Kubelet daemon:

func DoHTTPProbe(url *url.URL, headers http.Header, client HTTPGetInterface) (probe.Result, string, error) {
    // ...
    body := string(b)
    if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusBadRequest {
        glog.V(4).Infof("Probe succeeded for %s, Response: %v", url.String(), *res)
        return probe.Success, body, nil
    }
    glog.V(4).Infof("Probe failed for %s with request headers %v, response body: %v", url.String(), headers, body)
    return probe.Failure, fmt.Sprintf("HTTP probe failed with statuscode: %d", res.StatusCode), nil
}

As you can see, the Kubelet daemon will log the HTTP response body of a failed probe in its own log, but even then only if verbosity was set to 4 or higher. Beyond logging the response in its own log, it is not passed back from the DoHTTPProbe method and will not be processed any further by the Kubelet.

As already noted by yourself, I'd think your safest bet would be to log the data you need from within your application itself.


问:
Wordpress column header full image
I want to achieve this with a column in Wordpress;

example

A column with a Image header and some text beneath. It will function as a content box.

It is something easy i know, but i cant figure it out right now = (

Help me out please

答:
You mean something like this?

.box {
  max-width: 200px;
  width: 100%;
  border-radius: 10px;
  border: 1px black solid;
  padding: 10px 5px;
}

.box img {
  width: 100%;
}

.box .body {
  margin-top: 5px;
  border-top: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <img src="" alt="img" />
  <div class="body">
    <h2>Header</h2>
    <p>Body</p>
    <button>A button</button>
  </div>
</div></code>```

Title: Wordpress column header full image

Body:
You mean something like this?

.box {
  max-width: 200px;
  width: 100%;
  border-radius: 10px;
  border: 1px black solid;
  padding: 10px 5px;
}

.box img {
  width: 100%;
}

.box .body {
  margin-top: 5px;
  border-top: 1px solid black;
}

<div class="box">
  <img src="" alt="img" />
  <div class="body">
    <h2>Header</h2>
    <p>Body</p>
    <button>A button</button>
  </div>
</div>


问:
Too Many Weights in Multinomial logistic regression and the code is running for hours
I have a DF(train_market) having 8523 rows and 12 Columns as shown

And I'm Doing multinomial logistic regression model to get the ITem_Outlet_Sales on the test_data.
but the code to run the model is running from hours together

```<code> model <- nnet(Item_Outlet_Sales~.,train_market,family="multinomial",size = 5574900,softmax=TRUE)
</code>```

I tried others two shown below but still its running for hours, what changes should i do to get it done

```<code> model <- multinom(Item_Outlet_Sales~.,train_market,family="multinomial")
 model <- nnet(Item_Outlet_Sales~.,train_market,family="multinomial",size = 5574900,softmax=TRUE)
</code>```

And i got the error for the 2nd Code as

```<code>Error in nnet.default(X, Y, w, mask = mask, size = 0, skip = TRUE, softmax = TRUE,  :
 too many (5574828) weights
</code>```

so kept size =5574900 in 3rd and tried,Which dint help.

答:
There is the argument MaxNWts in the nnet package in general for controlling the maximum number of weights. Hence, setting MaxNWts to a sufficiently large integer (for example, MaxNWts =10000000) should do the job:

```<code>model <- nnet(Item_Outlet_Sales~.,train_market,family="multinomial",size = 5574900,softmax=TRUE,MaxNWts =10000000)
</code>```

Body:
I have a DF(train_market) having 8523 rows and 12 Columns as shown

And I'm Doing multinomial logistic regression model to get the ITem_Outlet_Sales on the test_data.
but the code to run the model is running from hours together

 model <- nnet(Item_Outlet_Sales~.,train_market,family="multinomial",size = 5574900,softmax=TRUE)

I tried others two shown below but still its running for hours, what changes should i do to get it done

 model <- multinom(Item_Outlet_Sales~.,train_market,family="multinomial")
 model <- nnet(Item_Outlet_Sales~.,train_market,family="multinomial",size = 5574900,softmax=TRUE)

And i got the error for the 2nd Code as

Error in nnet.default(X, Y, w, mask = mask, size = 0, skip = TRUE, softmax = TRUE,  :
 too many (5574828) weights

so kept size =5574900 in 3rd and tried,Which dint help.

Body:
There is the argument MaxNWts in the nnet package in general for controlling the maximum number of weights. Hence, setting MaxNWts to a sufficiently large integer (for example, MaxNWts =10000000) should do the job:

model <- nnet(Item_Outlet_Sales~.,train_market,family="multinomial",size = 5574900,softmax=TRUE,MaxNWts =10000000)


问:
Proper way to do polling in swift?
I have lot of experience with other programming languages, but not so much in swift 3. I want to do polling loop. This is what i have written:

```<code>DispatchQueue.global(qos: .userInitiated).async {
            [unowned self] in
            while self.isRunning {
                WebService.getPeople(completion: nil)
                sleep(100)
            }
        }
</code>```

This works fine for me, every 100 seconds, i do polling, and then make this thread sleep. What I am wondering, is this correct way to do this in swift 3?

答:
You have 2 options:

Use NSTimer

Use a DispatchSourceTimer

Using NSTimer is pretty easy, but it needs an active run loop, so if you need to poll on a background thread things could be a little bit tricky, because you will need to create a thread and keep alive a run loop on it (probably the timer itself will keep the run loop alive).

DispatchSourceTimer on the other hand works using queues. You can easily create a dispatch source timer from one of the system provided queues or create one.

```<code>    var timer: DispatchSourceTimer?
    let queue = DispatchQueue.global(qos: .background)
    guard let timer = DispatchSource.makeTimerSource(queue: queue) else { return }
    timer.scheduleRepeating(deadline: .now(), interval: .seconds(100), leeway: .seconds(1))
    timer.setEventHandler(handler: {
        // Your code
    })
    timer.resume()
</code>```

The leeway arguments is the amount of time that the system can defer the timer.

Title: Proper way to do polling in swift?

Body:
I have lot of experience with other programming languages, but not so much in swift 3. I want to do polling loop. This is what i have written:

DispatchQueue.global(qos: .userInitiated).async {
            [unowned self] in
            while self.isRunning {
                WebService.getPeople(completion: nil)
                sleep(100)
            }
        }

This works fine for me, every 100 seconds, i do polling, and then make this thread sleep. What I am wondering, is this correct way to do this in swift 3?

Body:
You have 2 options:

Use NSTimer

Use a DispatchSourceTimer

Using NSTimer is pretty easy, but it needs an active run loop, so if you need to poll on a background thread things could be a little bit tricky, because you will need to create a thread and keep alive a run loop on it (probably the timer itself will keep the run loop alive).

DispatchSourceTimer on the other hand works using queues. You can easily create a dispatch source timer from one of the system provided queues or create one.

    var timer: DispatchSourceTimer?
    let queue = DispatchQueue.global(qos: .background)
    guard let timer = DispatchSource.makeTimerSource(queue: queue) else { return }
    timer.scheduleRepeating(deadline: .now(), interval: .seconds(100), leeway: .seconds(1))
    timer.setEventHandler(handler: {
        // Your code
    })
    timer.resume()

The leeway arguments is the amount of time that the system can defer the timer.


问:
Handle multiple csv import request parallel and efficiently
I will have to import data in CSV from database, there can be over 100k records to import. Cron will be based on each user reoccurence time like after 2,3,4 hours and it will pick data from database and import in CSV and send to customer. At one time, I could have multiple requests to import data in csv and send to customer.

As parallel processing directly is not allowed in PHP so I searched some method that I can use like

Multi curl request

Gearman

pcntl

Threading

But I am not getting which method would be efficient and easy to implement? I am trying to make logic so that all users get their CSVs on time.

答:
If you can configure your php interpreter instance, good idea is use that library thread.

Multi curl request seems to be lowest option.

Pcntl also requires configure php interpreter instance.


问:
In Cakephp numeric model name convention
i have att_2010_masters table.

and Att2010Master model.

but it is not working.

Is naming convention of model is ok ?

and

what can i do to take numeric value in my table name ?

答:
I think it would be better if you named the model normally, without the numbers and just use the $useTable property in the model.</p>

```<code>var $useTable = 'att_2010_masters'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think it would be better if you named the model normally, without the numbers and just use the $useTable property in the model.

var $useTable = 'att_2010_masters'


问:
Value format in Php Remove caracteres
I have this value :

"24,7 km"

i would like to remove "Km" and get only 24,7 as a float number ! someone know how i could do this ? thanks a lot in advance

here my code actualy :

```<code>Route::get('/test', function () {

    $origin = '155 avenue franklin roosevelt 11000 Carcassonne';

    $destination = '36 avenue André Chenier 11300 Limoux';

    $response = \GoogleMaps::load('directions')
        ->setParam([
            'origin'          => $origin,
            'destination'     => $destination,
            'mode' => 'driving' ,
            'language' => 'fr',

        ])->get();

   $parsed_json = (json_decode($response));

   $distance = $parsed_json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'text'};

   dd($distance);
</code>```

UPDATE WORKING :

```<code>  $parsed_json = (json_decode($response));

        $distance = $parsed_json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'text'};

        $a = $distance;
        $b = str_replace(" km",'',$a);
        $c = str_replace(",",'.',$b);

        dd($c);
</code>```

Title: Value format in Php Remove caracteres

Body:
I have this value :

"24,7 km"

i would like to remove "Km" and get only 24,7 as a float number ! someone know how i could do this ? thanks a lot in advance

here my code actualy :

Route::get('/test', function () {

    $origin = '155 avenue franklin roosevelt 11000 Carcassonne';

    $destination = '36 avenue André Chenier 11300 Limoux';

    $response = \GoogleMaps::load('directions')
        ->setParam([
            'origin'          => $origin,
            'destination'     => $destination,
            'mode' => 'driving' ,
            'language' => 'fr',

        ])->get();

   $parsed_json = (json_decode($response));

   $distance = $parsed_json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'text'};

   dd($distance);

UPDATE WORKING :

  $parsed_json = (json_decode($response));

        $distance = $parsed_json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'text'};

        $a = $distance;
        $b = str_replace(" km",'',$a);
        $c = str_replace(",",'.',$b);

        dd($c);

Body:
$a = "24,7 km";
$b = str_replace(" km",'',$a);
$c = str_replace(",",'.',$b);