问:
hibernate secondary table for same entity relationship
I have a Profile class which holds user's information. One of the features of this application is to "follow" another profiles of your choice. I'm having trouble designing the DB and making the link happen, both writing the model code and the repository (is it just a matter of a save?).

My Profile class looks like this: (irrelevant fields to the question and getters/setters are omitted for the sake of simplicity)

```<code>import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.*;

@Entity
@Table(name = "USERS")
public class Profile implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 32)
    @Column(nullable = false)
    private String name;

    @Size(max = 16)
    @Column(unique=true, nullable = false)
    private String username;

    @Email
    @Column(unique=true)
    private String email;

    @ManyToOne
    @JoinColumn(name="profile_id")
    private Profile profile;

    @OneToMany(mappedBy = "profile")
    private List<Profile> friends = new ArrayList<>();

    public Profile() {
    }

    // other getters/setters

    public List<Profile> getFriends() {
        return friends;
    }

    public void setFriends(List<Profile> friends) {
        this.friends = friends;
    }

    public void addFriend(Profile friend) {
        this.friends.add(friend);
    }
}

</code>```

This creates a null field called profile_id in the users' table. I've done some research and it seems like creating another table using @SecondaryTable annotation may do the trick. The tutorials I've looked into did not solve my doubts. I'd like some light into the matter, and if possible avoid creating a different entity.

Ideally, I'd have a table with its own id, the owner's id (the person who is following) and the target's id (the person who is being followed).

Thanks in advance!

答:
What you need is a separate table to store this following relationship (many-to-many). The most simplest way is to use @ManyToMany :

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

        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name="following",
                joinColumns={@JoinColumn(name="user_id")},
                inverseJoinColumns={@JoinColumn(name="follower_id")})
        private Set<Profile> followers = new HashSet<Profile>();

        @ManyToMany(mappedBy = "followers", cascade = CascadeType.ALL)
        private Set<Profile> followBy = new HashSet<Profile>();
}
```

<p>It will be mapped to a relationship table called <code>following</code> which has the following schema : </p>

```---------------------------------
| column      | FK              |
=================================
| user_id     | FK to users.id  |
---------------------------------
| follower_id | FK to users.id  |
---------------------------------
```

So given an user A , the field followers is all users that A is following to. And the field followBy is all users the are following to A.

Also , note that the mappedBy setting .It means you have to use the field followers to maintain this following relationship but not the field followBy, which basically means that you have to insert /remove instances to the followers Set to change the following relationship for a given profile.

Also see this if you want the add additional columns to the relationship table (i.e. following table)

Body:
I have a Profile class which holds user's information. One of the features of this application is to "follow" another profiles of your choice. I'm having trouble designing the DB and making the link happen, both writing the model code and the repository (is it just a matter of a save?).

My Profile class looks like this: (irrelevant fields to the question and getters/setters are omitted for the sake of simplicity)

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.*;

@Entity
@Table(name = "USERS")
public class Profile implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 32)
    @Column(nullable = false)
    private String name;

    @Size(max = 16)
    @Column(unique=true, nullable = false)
    private String username;

    @Email
    @Column(unique=true)
    private String email;

    @ManyToOne
    @JoinColumn(name="profile_id")
    private Profile profile;

    @OneToMany(mappedBy = "profile")
    private List<Profile> friends = new ArrayList<>();

    public Profile() {
    }

    // other getters/setters

    public List<Profile> getFriends() {
        return friends;
    }

    public void setFriends(List<Profile> friends) {
        this.friends = friends;
    }

    public void addFriend(Profile friend) {
        this.friends.add(friend);
    }
}

This creates a null field called profile_id in the users' table. I've done some research and it seems like creating another table using @SecondaryTable annotation may do the trick. The tutorials I've looked into did not solve my doubts. I'd like some light into the matter, and if possible avoid creating a different entity.

Ideally, I'd have a table with its own id, the owner's id (the person who is following) and the target's id (the person who is being followed).

Thanks in advance!

Body:
What you need is a separate table to store this following relationship (many-to-many). The most simplest way is to use @ManyToMany :

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

        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name="following",
                joinColumns={@JoinColumn(name="user_id")},
                inverseJoinColumns={@JoinColumn(name="follower_id")})
        private Set<Profile> followers = new HashSet<Profile>();

        @ManyToMany(mappedBy = "followers", cascade = CascadeType.ALL)
        private Set<Profile> followBy = new HashSet<Profile>();
}

It will be mapped to a relationship table called following which has the following schema :

---------------------------------
| column      | FK              |
=================================
| user_id     | FK to users.id  |
---------------------------------
| follower_id | FK to users.id  |
---------------------------------

So given an user A , the field followers is all users that A is following to. And the field followBy is all users the are following to A.

Also , note that the mappedBy setting .It means you have to use the field followers to maintain this following relationship but not the field followBy, which basically means that you have to insert /remove instances to the followers Set to change the following relationship for a given profile.

Also see this if you want the add additional columns to the relationship table (i.e. following table)


来源: stackexchange

问:
detect memory before load kernel in bootloader
i try to detect memory with eax=0xe820 int 15h before load kernel in my bootloader.
So i have done some investigation and i have seen that the problem is the EDX registers .
I think that i have prepared DL and BX for loading kernel and then i have trashed them by calling do_e820 .

So there is my bootloader file (bootloader.asm) :

```<code>[bits 16]

global _start

number_sector db 0
_start:
    cli
    xor ax, ax
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, 0x8000      ; Stack pointer at SS:SP = 0x0000:0x8000
    mov [BOOT_DRIVE], dl; Boot drive passed to us by the BIOS
    mov dh, 17          ; Number of sectors (kernel.bin) to read from disk
                        ; 17*512 allows for a kernel.bin up to 8704 bytes
    mov bx, 0x9000      ; Load Kernel to ES:BX = 0x0000:0x9000

    call do_E820
    call load_kernel
    call enable_A20

;   call graphics_mode  ; Uncomment if you want to switch to graphics mode 0x13
    lgdt [gdtr]
    mov eax, cr0
    or al, 1
    mov cr0, eax
    jmp CODE_SEG:init_pm

graphics_mode:
    mov ax, 0013h
    int 10h
    ret

load_kernel:
                        ; load DH sectors to ES:BX from drive DL
    push dx             ; Store DX on stack so later we can recall
                        ; how many sectors were request to be read ,
                        ; even if it is altered in the meantime
    mov ah , 0x02       ; BIOS read sector function
    mov al , dh         ; Read DH sectors
    mov ch , 0x00       ; Select cylinder 0
    mov dh , 0x00       ; Select head 0
    mov cl , 0x02       ; Start reading from second sector ( i.e.
                        ; after the boot sector )
    int 0x13            ; BIOS interrupt
    jc disk_error       ; Jump if error ( i.e. carry flag set )
    pop dx              ; Restore DX from the stack
    cmp dh , al         ; if AL ( sectors read ) != DH ( sectors expected )
    jne disk_error      ; display error message
    ret
disk_error:
    mov bx , ERROR_MSG
    call print_string
    hlt

; prints a null - terminated string pointed to by EDX
print_string:
    pusha
    push es                   ;Save ES on stack and restore when we finish

    push VIDEO_MEMORY_SEG     ;Video mem segment 0xb800
    pop es
    xor di, di                ;Video mem offset (start at 0)
print_string_loop:
    mov al , [ bx ] ; Store the char at BX in AL
    mov ah , WHITE_ON_BLACK ; Store the attributes in AH
    cmp al , 0 ; if (al == 0) , at end of string , so
    je print_string_done ; jump to done
    mov word [es:di], ax ; Store char and attributes at current
        ; character cell.
    add bx , 1 ; Increment BX to the next char in string.
    add di , 2 ; Move to next character cell in vid mem.
    jmp print_string_loop ; loop around to print the next char.

print_string_done:
    pop es                    ;Restore ES that was saved on entry
    popa
    ret ; Return from the function

%include "BOOT/a20.inc"
%include "BOOT/gdt.inc"
%include "BOOT/detect_mem.inc"

[bits 32]
init_pm:
    mov ax, DATA_SEG
    mov ds, ax
    mov ss, ax
    mov es, ax
    mov fs, ax
    mov gs, ax

    mov ebp, 0x90000
    mov esp, ebp
    call 0x9000
    cli
loopend:                                ;Infinite loop when finished
    jmp loopend

[bits 16]
; Variables
ERROR            db "A20 Error!" , 0
ERROR_MSG        db "Error!" , 0
BOOT_DRIVE:      db 0

VIDEO_MEMORY_SEG equ 0xb800
WHITE_ON_BLACK   equ 0x0f

times 510-($-$$) db 0
db 0x55
db 0xAA
</code>```

and there is my function to detect memory (detect_mem.inc) :

```<code>entries equ 0
buffer equ 1

do_E820:
    pushf
    pusha
    mov edi , buffer ;destination buffer
    mov byte [edi+20] , 1  ;Force a vaalid ACPI

.begin:
    xor ebx , ebx
    mov edx , 0x534D4150
    mov eax , 0xE820
    mov ecx , 24
    int 0x15

    jc .failed
    mov edx ,  0x534D4150
    cmp eax,edx ;voir si eax est different de  0x534D4150
    jne .failed
    test ebx , ebx  ;EBX will be set to some non-zero value
    je .failed
    jmp .verify

.do_E820_loop:
    mov eax, 0xe820     ; eax, ecx get trashed on every int 0x15 call
    mov [es:di+20], dword 1 ; force a valid ACPI 3.X entry
    mov ecx, 24     ; ask for 24 bytes again
    int 0x15
    jc .e820_failed

.verify:
    jcxz .skip_entries  ;Length of "region" (if this value is 0, ignore the entry)
    cmp cl , 20
    jbe .extension
    cmp byte [es:di+20] , 0
    je .skip_entries

.extension:    ;go to the next buffer if cl equal 24
    push eax
        mov eax , dword [entries]
        inc eax
        mov dword [entries] , eax
    pop eax
    mov ecx , [es:di+8]
    jcxz .skip_entries
    add di ,24

.skip_entries:
    test ebx , ebx  ;if ebx resets to 0, list is complete
    jne .do_E820_loop

.e820_failed:
    clc
    popa
    popf
    ret

.failed:
    stc
    popa
    popf
    ret
</code>```

Please , can you advice me something , if i have done anothers mistakes , please advice me too.

答:
I think that i have prepared DL and BX for loading kernel and then i have trashed them by calling do_e820 .

No, you haven't - the pusha and popa in do_e820 will save and restore dx (which is dh and dl combined).

There are multiple other problems. For examples:

1) It doesn't make any sense to leave interrupts disabled/postponed (after the cli at the start); and not just because BIOS functions will just enable IRQs anyway (especially to handle disk, which may require an IRQ to indicate that a transfer completed).

2) The do_e820 code is using the carry flag to return success/failure; but it sets or clears the carry flag (clc or stc) and the pops the caller's flags from the stack (popf) which overwrites the "carry flag to return success/failure".

3) There's no "buffer full" guard on the do_e820 loop, so (at least in theory) if there's a very large number of entries in the memory map then di could wrap around and trash everything.

4) the jcxz .skip_entries (in do_e820) is wrong (it's only checking 32 bits of the entry's 64 bit "size" field, so if the BIOS wants to say there's a multiple of 4 GiB of usable RAM somewhere you'll incorrectly ignore that) and is misplaced (happens after you increment the number of entries, so you could increment the number of entries and then ignore/skip the entry, and end up with the wrong value in [entries]). Note that you could do inc dword [entries] to make it cleaner (no need to save/restore eax).

5) hlt only halts the CPU until an interrupt occurs. This includes "halt until non-masking interrupt/NMI occurs" where disabling/postponing IRQs (with cli, which is wrong/silly) will not prevent the NMI; allowing the CPU to continue executing code after the hlt. For this reason you should always use a loop (like ".die: hlt then jmp .die); but in that case you have no reason to disable IRQs. Note that (for real computers) being able to press "control+alt+delete" after a boot loader decided to halt forever is very convenient (but won't work when IRQs are disabled).

6) For floppy disks, you shouldn't give up after the first error (because floppies are relatively unreliable). Standard practice is to have at least 3 retries, and to reset the floppy between (some) retries.

Also note that with a little re-arrangement the code could be easier to read and less error prone. Specifically, you could call do_e820 first, then load parameters needed for call load_kernel after (e.g. mov dh, 17, mov bx, 0x9000). In this case you could also reload dl (with a mov dl,[BOOT_DRIVE]) and delete the pusha and popa (and pushf and popf) from do_e820.

ContentLicense: CC BY-SA 4.0

Body:
i try to detect memory with eax=0xe820 int 15h before load kernel in my bootloader.
So i have done some investigation and i have seen that the problem is the EDX registers .
I think that i have prepared DL and BX for loading kernel and then i have trashed them by calling do_e820 .

So there is my bootloader file (bootloader.asm) :

[bits 16]

global _start

number_sector db 0
_start:
    cli
    xor ax, ax
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, 0x8000      ; Stack pointer at SS:SP = 0x0000:0x8000
    mov [BOOT_DRIVE], dl; Boot drive passed to us by the BIOS
    mov dh, 17          ; Number of sectors (kernel.bin) to read from disk
                        ; 17*512 allows for a kernel.bin up to 8704 bytes
    mov bx, 0x9000      ; Load Kernel to ES:BX = 0x0000:0x9000

    call do_E820
    call load_kernel
    call enable_A20

;   call graphics_mode  ; Uncomment if you want to switch to graphics mode 0x13
    lgdt [gdtr]
    mov eax, cr0
    or al, 1
    mov cr0, eax
    jmp CODE_SEG:init_pm

graphics_mode:
    mov ax, 0013h
    int 10h
    ret

load_kernel:
                        ; load DH sectors to ES:BX from drive DL
    push dx             ; Store DX on stack so later we can recall
                        ; how many sectors were request to be read ,
                        ; even if it is altered in the meantime
    mov ah , 0x02       ; BIOS read sector function
    mov al , dh         ; Read DH sectors
    mov ch , 0x00       ; Select cylinder 0
    mov dh , 0x00       ; Select head 0
    mov cl , 0x02       ; Start reading from second sector ( i.e.
                        ; after the boot sector )
    int 0x13            ; BIOS interrupt
    jc disk_error       ; Jump if error ( i.e. carry flag set )
    pop dx              ; Restore DX from the stack
    cmp dh , al         ; if AL ( sectors read ) != DH ( sectors expected )
    jne disk_error      ; display error message
    ret
disk_error:
    mov bx , ERROR_MSG
    call print_string
    hlt

; prints a null - terminated string pointed to by EDX
print_string:
    pusha
    push es                   ;Save ES on stack and restore when we finish

    push VIDEO_MEMORY_SEG     ;Video mem segment 0xb800
    pop es
    xor di, di                ;Video mem offset (start at 0)
print_string_loop:
    mov al , [ bx ] ; Store the char at BX in AL
    mov ah , WHITE_ON_BLACK ; Store the attributes in AH
    cmp al , 0 ; if (al == 0) , at end of string , so
    je print_string_done ; jump to done
    mov word [es:di], ax ; Store char and attributes at current
        ; character cell.
    add bx , 1 ; Increment BX to the next char in string.
    add di , 2 ; Move to next character cell in vid mem.
    jmp print_string_loop ; loop around to print the next char.

print_string_done:
    pop es                    ;Restore ES that was saved on entry
    popa
    ret ; Return from the function

%include "BOOT/a20.inc"
%include "BOOT/gdt.inc"
%include "BOOT/detect_mem.inc"

[bits 32]
init_pm:
    mov ax, DATA_SEG
    mov ds, ax
    mov ss, ax
    mov es, ax
    mov fs, ax
    mov gs, ax

    mov ebp, 0x90000
    mov esp, ebp
    call 0x9000
    cli
loopend:                                ;Infinite loop when finished
    jmp loopend

[bits 16]
; Variables
ERROR            db "A20 Error!" , 0
ERROR_MSG        db "Error!" , 0
BOOT_DRIVE:      db 0

VIDEO_MEMORY_SEG equ 0xb800
WHITE_ON_BLACK   equ 0x0f

times 510-($-$$) db 0
db 0x55
db 0xAA

and there is my function to detect memory (detect_mem.inc) :

entries equ 0
buffer equ 1

do_E820:
    pushf
    pusha
    mov edi , buffer ;destination buffer
    mov byte [edi+20] , 1  ;Force a vaalid ACPI

.begin:
    xor ebx , ebx
    mov edx , 0x534D4150
    mov eax , 0xE820
    mov ecx , 24
    int 0x15

    jc .failed
    mov edx ,  0x534D4150
    cmp eax,edx ;voir si eax est different de  0x534D4150
    jne .failed
    test ebx , ebx  ;EBX will be set to some non-zero value
    je .failed
    jmp .verify

.do_E820_loop:
    mov eax, 0xe820     ; eax, ecx get trashed on every int 0x15 call
    mov [es:di+20], dword 1 ; force a valid ACPI 3.X entry
    mov ecx, 24     ; ask for 24 bytes again
    int 0x15
    jc .e820_failed

.verify:
    jcxz .skip_entries  ;Length of "region" (if this value is 0, ignore the entry)
    cmp cl , 20
    jbe .extension
    cmp byte [es:di+20] , 0
    je .skip_entries

.extension:    ;go to the next buffer if cl equal 24
    push eax
        mov eax , dword [entries]
        inc eax
        mov dword [entries] , eax
    pop eax
    mov ecx , [es:di+8]
    jcxz .skip_entries
    add di ,24

.skip_entries:
    test ebx , ebx  ;if ebx resets to 0, list is complete
    jne .do_E820_loop

.e820_failed:
    clc
    popa
    popf
    ret

.failed:
    stc
    popa
    popf
    ret

Please , can you advice me something , if i have done anothers mistakes , please advice me too.


问:
UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given
Getting error after installing dompdf

[2020-01-28 18:23:03] local.ERROR: UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given. in D:\xampp\htdocs\myproject\vendor\symfony\http-foundation\Response.php:399

答:
In my case,
I was trying to return a result object without even converting it into JSON format from the server-side. Use a loop to traverse through your result set and store it into an array then try using json_encode($your_data) function for returning to the client-side. I request you to share your code for a better understanding of your problem statement.


问:
Dotnet Core 3.1, EF1001: internal ef core api usage
Upgraded to Dotnet Core 3.1 from 2.2, EF core kept complaining EF1001: internal ef core api usage by putting an Exclamation Mark in my project.

But no error / warning shown during compilation. I do not know which line of code is causing the trouble.

May I know how can I find out which API / Method that I am not suppose to use?

答:
Are you using a database provider (i.e. packages for SQLServer, Postgres, etc)?

It sounds like you are saying there is some warning being given with your dependencies. I know Microsoft announced some breaking changes, mainly for database providers, with EF Core with the 3.0+ updates. Could be as simple as updating the other packages in your project.

Just guessing, I could very well be wrong.


问:
Site not valid - but it is
So, I'm building a website called "dagbok.nu", which is swedish for "diary now" :)

Anyway, when creating the Facebook application, it claims that the site URL is invalid as well as the app domain. For site url, I used "http://dagbok.nu" and for site domain, I used "dagbok.nu". Please don't reply (as I've seen others do on similar issues) that I should type the site url with the scheme and the domain without - that's exactly what I'm doing.

Right, so according to another question here, one could trouble shoot this functionality using FB's own URL scraper, so I did just that:

http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fdagbok.nu

And the reply: Error Parsing URL: Error parsing input URL, no data was scraped
Right, so now I can assume that the reason for it being considered invalid is because of FB not being able to scrape the URL. But why?

According to this question, one of the reasons seems to be that FB has deemed the URL insecure or "spammy". I've acquired this domain from a previous owner so this wasn't all that impossible. But when doing the same thing as Matthew in that post - i.e. trying to post in my timeline using the domain "http://dagbok.nu", I didn't get any information. The status box expanded as if to include a thumbnail and information about the link, but it only contained a "(No title)" text and nothing more.

So now I don't know what to do. I've tried to check the DIG and NS records from multiple servers around the web, and everyone seems to resolve it correctly, and I've had friends double check the URL from the states as well. I can't understand what's wrong and I have no idea how to ask someone at FB how to resolve this. Does anyone here have a good advice for this? Thanks in advance! :)

EDIT
When changing the domain to another domain that points to the exact same web server and document_root, it works! So this is definitely a problem with the domain "dagbok.nu" and not with the code on that page.

EDIT
When using the debug function above - I see no activity in the server log what so ever. Facebook doesn't even contact the server. When using the alternate url - the one from the last edit, it pops up in the logs as it should.

EDIT
I filed a bug report with Facebook, And their first response was that they were going to follow up. Now, a month later, I got an email that said "We are prioritizing bugs based on impact to the developer community. As this bug report has not received much attention from other developers, we are closing it so as to better focus on the top issues", and then they told me to go here to stackoverflow to try to solve my issue - but the issue is WITH THEM, and of course no one else have reported that my site doesn't work, it affects only me, and I haven't opened it yet due to this bug!

EDIT
I wanted to file a new bug report, but I can't even that now, since they are blocking bug reports with this URL as well!

I had to edit the URL - here is the new bug report

答:
This issue may also happen when Cloudflare is used. This is because Cloudflare protects the page from Facebook, which is then unable to collect the data, which in turn makes Facebook think the page is invalid.

My fix was:

Turn off Cloudflare for the page.

Scrape the page using Facebook's Dev Tools: https://developers.facebook.com/tools/debug/og/object

Click and let run the "Fetch new scrape information" button.

Re-enable cloudflare protection for the page.

You should then be able to continue to add the page where you needed.

ContentLicense: CC BY-SA 3.0

Title: Site not valid - but it is


问:
How to read cell values in a table using selenium webdriver
[Below is the html code. Actually I am unable to understand how to actually explain the condition the webtable has two table ids, tbl and tbr and the table has a total of 4 rows.The first column in under the table id=tbl and the remaining columns Rev and Qty and others under the table id=tbr.I am trying to check the col values exists or not considering each row for example col1 under table id=tbl is a Part Name and col2 and col3 under table id=tbr has Part Revision and Part Quantity. I want to check if the Part exists with the Revision and Quantity specified.Is my question clear now?</p>

```<code><form autocomplete="off" onsubmit="return false;" name="tvcTableForm">
    <input type="hidden" value="tvc-0000000000000002" name="object">
    <input type="hidden" value="35004.36845.30464.63080" name="parentOID">
    <div id="th">
    <div id="tb">
    <div id="tblc" style="top: 32px; height: 112px;">
    <table id="tbl" class="contentTable" cellspacing="0" cellpadding="0" style="border: 0px none; width: 199px; height: 144px; table-layout: fixed;">
    <tbody>
    </table>
    </div>
    <div id="tbrc" style="top: 32px; left: 199px; width: 1106px; height: 112px; overflow: auto;">
    <table id="tbr" class="contentTable" cellspacing="0" cellpadding="0" style="border: 0px none; width: 1089px; height: 144px; table-layout: fixed;">
    <tbody>
    <tr id="r573378134017" class="even" oncontextmenu="return ctxm(event)" style="height: 36px;">
</code>```

答:
Here is another way: use javascript.

```<code>String cellValue = js.executeScript("return arguments[0].children[0].children[arguments[1]].children[arguments[2]].innerText", tableElement, rowIndex, columnIndex));
</code>```

This is based on the following javascript code where r = rowIndex and c = columnIndex

```<code>document.querySelector("#table").children[0].children[r].children[c].innerText
</code>```

Body:
[Below is the html code. Actually I am unable to understand how to actually explain the condition the webtable has two table ids, tbl and tbr and the table has a total of 4 rows.The first column in under the table id=tbl and the remaining columns Rev and Qty and others under the table id=tbr.I am trying to check the col values exists or not considering each row for example col1 under table id=tbl is a Part Name and col2 and col3 under table id=tbr has Part Revision and Part Quantity. I want to check if the Part exists with the Revision and Quantity specified.Is my question clear now?

<form autocomplete="off" onsubmit="return false;" name="tvcTableForm">
    <input type="hidden" value="tvc-0000000000000002" name="object">
    <input type="hidden" value="35004.36845.30464.63080" name="parentOID">

Body:
Here is another way: use javascript.

String cellValue = js.executeScript("return arguments[0].children[0].children[arguments[1]].children[arguments[2]].innerText", tableElement, rowIndex, columnIndex));

This is based on the following javascript code where r = rowIndex and c = columnIndex

document.querySelector("#table").children[0].children[r].children[c].innerText


问:
Keycloak logging to JSON format message field
I have been trying to set up keycloak logging to be scraped by fluentd to be used in elasticsearch. So far I have used the provided CLI string to use in my helm values script.

```<code>  cli:
    # Custom CLI script
    custom: |
      /subsystem=logging/json-formatter=json:add(exception-output-type=formatted, pretty-print=true, meta-data={label=value})
      /subsystem=logging/console-handler=CONSOLE:write-attribute(name=named-formatter, value=json)
</code>```

However, as you can see in the picture provided, the logs that are generated seem to be completely json apart from the core of the log, the message field. Currently the message field is provided as comma separated key-value pairs. Is there any way to tell keycloak, jboss or wildfly that it needs to provide the message in JSON too? This allows me to efficiently search through the data in elastic.

答:
Check this project on GitHub: keycloak_jsonlog_eventlistener: Outputs Keycloak events as JSON into the server log.

Keycloak JSON Log Eventlistener

Primarily written for the Jboss Keycloak docker image, it will output Keycloak events as JSON into the keycloak server log.

The idea is to parse logs once they get to logstash via journalbeat.

Tested with Keycloak version 8.0.1

Body:
I have been trying to set up keycloak logging to be scraped by fluentd to be used in elasticsearch. So far I have used the provided CLI string to use in my helm values script.

  cli:
    # Custom CLI script
    custom: |
      /subsystem=logging/json-formatter=json:add(exception-output-type=formatted, pretty-print=true, meta-data={label=value})
      /subsystem=logging/console-handler=CONSOLE:write-attribute(name=named-formatter, value=json)

However, as you can see in the picture provided, the logs that are generated seem to be completely json apart from the core of the log, the message field. Currently the message field is provided as comma separated key-value pairs. Is there any way to tell keycloak, jboss or wildfly that it needs to provide the message in JSON too? This allows me to efficiently search through the data in elastic.


问:
Ranking newer items fairly?
Using StackOverflow itself as an example, if you had any such system where entries were voted and viewed in order of rank based on this, how do you compensate to sort newer entries fairly? That is, if ten bad answers are given and upvoted, how do you make sure people see the new entry that might be better, but hasn't had time to gather votes or even been seen all the way at the bottom?</p>

答:
Or an "Unanswered" section - using StackOverflow as an example.

As your "bad" answers have been upvoted and so, by the rules of your site, should appear higher when ordered by rank.

OwnerDisplayName: ironfroggy

ContentLicense: CC BY-SA 2.5

Title: Ranking newer items fairly?

LastEditorDisplayName: Pete Kirkham

OwnerDisplayName: ChrisF


问:
Navigate after login (Angular)
After I login I need to redirect based on another request. For example:

I click login button

It calls login method in auth service

Here I need to get '/self' to get information which page should user be on

Navigate there

The main problem is when I get response it's async, so I can't redirect.

答:
```<code>constructor(
    protected httpClient: HttpClient,
    protected router: Router
}

    login() {
    this.httpClient.post(yourUrl).subscribe(
          (data) => {
              const path: string=this.getPage(data);
              this.router.navigate([path])
           }
     }
</code>```

In this way you synchronize the redirect to the login response.

Title: Navigate after login (Angular)

Body:
constructor(
    protected httpClient: HttpClient,
    protected router: Router
}

    login() {
    this.httpClient.post(yourUrl).subscribe(
          (data) => {
              const path: string=this.getPage(data);
              this.router.navigate([path])
           }
     }

In this way you synchronize the redirect to the login response.


问:
How to split start time and end time from different days into a daily table?
I am struggling with a table that show me a start time and an end time of a machine status, and I would like to sum the hours but only considering day by day.

As an example:

```<code>ID STATUS    START_TIME          END_TIME
01 OPERATIVE 12/01/2020 08:00:00 14/01/2020 08:00:00
02 OPERATIVE 11/01/2020 05:00:00 13/01/2020 02:00:00
</code>```

My expected result would give me a table showing that in 11/01/2020, the machine number 2 worked from 05:00:00 to 23:59:59, so it would be 19h. Machine number two did not work at all.

In 12/01/2020, machine number one worked from 08:00:00 til 23:59:59 - 16h and machine number two worked the whole day: 24h, so it would give me 24h + 16h in this day = 40h.

And so it goes, giving me as part of the final table:

```<code>DAY        WORKING_HOURS
11/01/2020 19H
12/01/2020 40H
</code>```

So, what would you guys recommend me to do? How can I solve it?

Thanks in advance,

答:
```<code>;WITH calcs AS (
    -- 24 hours in seconds, minus 1 second for 23:59:59
    SELECT CAST(24 * 60 * 60 - 1 AS INT) AS [t_const_1]
    ,   CAST(2 * 24 * 60 * 60 - 1 AS INT) AS [t_const_2]
)
,   timeCTE AS (
    SELECT T.ID
    ,   T.START_TIME AS [start_dt]
        -- Find the "start" of the day (00:00:00) and add our constant
    ,   DATEADD(SECOND, calcs.[t_const_1], CAST(CAST(T.START_TIME AS DATE) AS DATETIME)) AS [end_dt_1]
    ,   T.END_TIME AS [end_dt]
    FROM #_tmp AS T, calcs
    UNION ALL
    SELECT T1.ID
    ,   DATEADD(HOUR, 24, CAST(CAST(T1.[end_dt_1] AS DATE) AS DATETIME)) AS [start_dt]

    -- Find the "start" of the day (00:00:00) and add our constant times 2
    ,   DATEADD(SECOND, calcs.[t_const_2], CAST(CAST(T1.[end_dt_1] AS DATE) AS DATETIME)) AS [end_dt_1]
    ,   T1.[end_dt]
    FROM timeCTE AS T1, calcs
    WHERE CAST(T1.[end_dt_1] AS DATE) < CAST(T1.[end_dt] AS DATE)
)
,   finalCTE AS (
    SELECT T2.ID
    ,   CONVERT(DATETIME, T2.[start_dt]) AS [start_dt]
    ,   CASE
            WHEN T2.[end_dt_1] > T2.[end_dt] THEN T2.[end_dt]
            ELSE T2.[end_dt_1]
        END AS [end_date]
    FROM timeCTE AS T2
)
SELECT fin.[ID]
,   CONVERT(DATETIME, fin.start_dt) AS [start_date]
,   CONVERT(DATETIME, fin.end_date) AS [end_date]
,   DATEPART(HOUR, fin.end_date) - DATEPART(HOUR, fin.[start_dt]) AS [net_daily_hours]
FROM finalCTE AS fin
</code>```

Output:

```<code>ID  start_dt                end_date                net_hours
01  2020-01-12 08:00:00.000 2020-01-12 23:59:59.000 15
02  2020-01-11 05:00:00.000 2020-01-11 23:59:59.000 18
02  2020-01-12 00:00:00.000 2020-01-12 23:59:59.000 23
02  2020-01-13 00:00:00.000 2020-01-13 02:00:00.000 2
01  2020-01-13 00:00:00.000 2020-01-13 23:59:59.000 23
01  2020-01-14 00:00:00.000 2020-01-14 08:00:00.000 8
</code>```

Mostly drawn from this post.

Body:
I am struggling with a table that show me a start time and an end time of a machine status, and I would like to sum the hours but only considering day by day.

As an example:

ID STATUS    START_TIME          END_TIME
01 OPERATIVE 12/01/2020 08:00:00 14/01/2020 08:00:00
02 OPERATIVE 11/01/2020 05:00:00 13/01/2020 02:00:00

My expected result would give me a table showing that in 11/01/2020, the machine number 2 worked from 05:00:00 to 23:59:59, so it would be 19h. Machine number two did not work at all.

In 12/01/2020, machine number one worked from 08:00:00 til 23:59:59 - 16h and machine number two worked the whole day: 24h, so it would give me 24h + 16h in this day = 40h.

And so it goes, giving me as part of the final table:

DAY        WORKING_HOURS
11/01/2020 19H
12/01/2020 40H

So, what would you guys recommend me to do? How can I solve it?

Thanks in advance,

Body:
;WITH calcs AS (
    -- 24 hours in seconds, minus 1 second for 23:59:59
    SELECT CAST(24 * 60 * 60 - 1 AS INT) AS [t_const_1]
    ,   CAST(2 * 24 * 60 * 60 - 1 AS INT) AS [t_const_2]
)
,   timeCTE AS (
    SELECT T.ID
    ,   T.START_TIME AS [start_dt]
        -- Find the "start" of the day (00:00:00) and add our constant
    ,   DATEADD(SECOND, calcs.[t_const_1], CAST(CAST(T.START_TIME AS DATE) AS DATETIME)) AS [end_dt_1]
    ,   T.END_TIME AS [end_dt]
    FROM #_tmp AS T, calcs
    UNION ALL
    SELECT T1.ID
    ,   DATEADD(HOUR, 24, CAST(CAST(T1.[end_dt_1] AS DATE) AS DATETIME)) AS [start_dt]

    -- Find the "start" of the day (00:00:00) and add our constant times 2
    ,   DATEADD(SECOND, calcs.[t_const_2], CAST(CAST(T1.[end_dt_1] AS DATE) AS DATETIME)) AS [end_dt_1]
    ,   T1.[end_dt]
    FROM timeCTE AS T1, calcs
    WHERE CAST(T1.[end_dt_1] AS DATE) < CAST(T1.[end_dt] AS DATE)
)
,   finalCTE AS (
    SELECT T2.ID
    ,   CONVERT(DATETIME, T2.[start_dt]) AS [start_dt]
    ,   CASE
            WHEN T2.[end_dt_1] > T2.[end_dt] THEN T2.[end_dt]
            ELSE T2.[end_dt_1]
        END AS [end_date]
    FROM timeCTE AS T2
)
SELECT fin.[ID]
,   CONVERT(DATETIME, fin.start_dt) AS [start_date]
,   CONVERT(DATETIME, fin.end_date) AS [end_date]
,   DATEPART(HOUR, fin.end_date) - DATEPART(HOUR, fin.[start_dt]) AS [net_daily_hours]
FROM finalCTE AS fin

Output:

ID  start_dt                end_date                net_hours
01  2020-01-12 08:00:00.000 2020-01-12 23:59:59.000 15
02  2020-01-11 05:00:00.000 2020-01-11 23:59:59.000 18
02  2020-01-12 00:00:00.000 2020-01-12 23:59:59.000 23
02  2020-01-13 00:00:00.000 2020-01-13 02:00:00.000 2
01  2020-01-13 00:00:00.000 2020-01-13 23:59:59.000 23
01  2020-01-14 00:00:00.000 2020-01-14 08:00:00.000 8

Mostly drawn from this post.


问:
How do you call postMessage() from a vue service worker
We have a vue firebase service worker that needs to call back to the main vue app. According to my research you can do this with the postMessage() function like so:

// firebase-messaging-sw.js

addEventListener('fetch', event => {
  event.waitUntil(
    (async function() {
      // Exit early if we don't have access to the client.
      // Eg, if it's cross-origin.
      if (!event.clientId) return

      // Get the client.
      const client = await clients.get(event.clientId)
      // Exit early if we don't get the client.
      // Eg, if it closed.
      if (!client) return

      // Send a message to the client.
      client.postMessage({
        msg: 'Hey I just got a fetch from you!',
        url: event.request.url
      })
    })()
  )
})

```

<p>You handle the message in the main app so:</p>

<pre class="lang-js prettyprint-override"><code>// main.js

navigator.serviceWorker.addEventListener('message', event => {
  console.log('Url', event.data.url)
  console.log('msg', event.data.msg)
})
</code>```

The problem is that postMessage() needs to be called on a client object and you get the client object on the fetch event, but vue does not seem to fetch anything as it is a single page application.
So how can I get the client?
and how do I message the main app?

答:
The client does not need to make a fetch request in order to allow the Service Worker to communicate with it. You can use the Clients API inside the Service Worker. You can also initiate a completely separate postMessage message from the client in the beginning after the app has started.

Clients API: https://developer.mozilla.org/en-US/docs/Web/API/Clients

I also suggest you check out this example: https://serviceworke.rs/message-relay.html

Body:
We have a vue firebase service worker that needs to call back to the main vue app. According to my research you can do this with the postMessage() function like so:

// firebase-messaging-sw.js

addEventListener('fetch', event => {
  event.waitUntil(
    (async function() {
      // Exit early if we don't have access to the client.
      // Eg, if it's cross-origin.
      if (!event.clientId) return

      // Get the client.
      const client = await clients.get(event.clientId)
      // Exit early if we don't get the client.
      // Eg, if it closed.
      if (!client) return

      // Send a message to the client.
      client.postMessage({
        msg: 'Hey I just got a fetch from you!',
        url: event.request.url
      })
    })()
  )
})

You handle the message in the main app so:

// main.js

navigator.serviceWorker.addEventListener('message', event => {
  console.log('Url', event.data.url)
  console.log('msg', event.data.msg)
})

The problem is that postMessage() needs to be called on a client object and you get the client object on the fetch event, but vue does not seem to fetch anything as it is a single page application.
So how can I get the client?
and how do I message the main app?


问:
command not found: django-admin when using django-admin startproject prj in mac
I'm trying to start a new project using django usign the command

```<code>django-admin startproject prj1
</code>```

in Mac, but it shows command not found:django-admin.

答:
First Activate the virtual environment ..type in

```<code>......source your_env/bin/activate
</code>```

Then immediatly run the create project command.Note now you will be in the venv created above your_env...

```<code>......django-admin startproject prji
</code>```

Body:
I'm trying to start a new project using django usign the command

django-admin startproject prj1

in Mac, but it shows command not found:django-admin.

Body:
First Activate the virtual environment ..type in

......source your_env/bin/activate

Then immediatly run the create project command.Note now you will be in the venv created above your_env...

......django-admin startproject prji


问:
Finding device IP J2ME
I am trying to connect 2 devices together using a datagram connection but so far it only works over localhost so I need to find the IP of the device to open the connection but I don't know how to do this. Can anyone help me?</p>

Title: Finding device IP J2ME


问:
HttpClient not returning data
I have the following scenario:

api.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const baseUrl: string = 'https://example.com/api/v1';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  getSingleUser(mail: string) {
    console.log('Getting info from:');
    var url: string = baseUrl + '/users/' + mail;
    console.log(url);
    return this.http.get(url);
  }
}
</code>```

login.component.ts

```<code>import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { ApiService } from 'app/api.service';

@Component({
  selector: "login-cmp",
  moduleId: module.id,
  templateUrl: "login.component.html"
})
export class LoginComponent implements OnInit {
  private userProfile: any = [];
  private email: string = 'mail@example.com';

  constructor(private router: Router,
              private apiService: ApiService) {}

  ngOnInit() { }

  signIn(provider: String): void {
        console.log('Starting http for ' + this.email);

        this.apiService.getSingleUser(this.email)
          .subscribe(data => {
            console.log('entered subscribe');
            console.log(data);
          });
        console.log('Finished getting data.');
      }
    });
  }
}
</code>```

And this is the output on my console:

```<code>Starting http for mail@example.com
Getting info from:
https://example.com/api/v1/users/mail@example.com
Finished getting data.
</code>```

What I can see in the log is that the method getSingleUser is being called (messages 2 and 3 are generated by the method), but the commands inside the subscribe block are not being executed and I do not understand why.

答:
this is not the best practice but the logic is correct.
first thing you want to check is if you are returning any data back from the backend. if not, you should try to return a json response which your subscribe function is expecting.
secondly you will need to check your network response to know the exact details of that get request.
also you can use postman for request testing to trigger that url.
in your postman, past this on the url with a get request
https://example.com/api/v1/users/mail@example.com
and see th exact response you are geetting for the request. but note. you need to return something from the backend for that request, else nothing will be displayed

Title: HttpClient not returning data

Body:
I have the following scenario:

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const baseUrl: string = 'https://example.com/api/v1';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  getSingleUser(mail: string) {
    console.log('Getting info from:');
    var url: string = baseUrl + '/users/' + mail;
    console.log(url);
    return this.http.get(url);
  }
}

login.component.ts

import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { ApiService } from 'app/api.service';

@Component({
  selector: "login-cmp",
  moduleId: module.id,
  templateUrl: "login.component.html"
})
export class LoginComponent implements OnInit {
  private userProfile: any = [];
  private email: string = 'mail@example.com';

  constructor(private router: Router,
              private apiService: ApiService) {}

  ngOnInit() { }

  signIn(provider: String): void {
        console.log('Starting http for ' + this.email);

        this.apiService.getSingleUser(this.email)
          .subscribe(data => {
            console.log('entered subscribe');
            console.log(data);
          });
        console.log('Finished getting data.');
      }
    });
  }
}

And this is the output on my console:

Starting http for mail@example.com
Getting info from:
https://example.com/api/v1/users/mail@example.com
Finished getting data.

What I can see in the log is that the method getSingleUser is being called (messages 2 and 3 are generated by the method), but the commands inside the subscribe block are not being executed and I do not understand why.


问:
How to resolve error 500 on Azure web app?
What I have:

VS2015U2

ASP.NET 5 MVC 6 website

Deployed to Azure Web App

The site works locally

When I deploy to Azure I get internal server error (500)

I'm unable to Attach a debugger since they messed up something with the latest versions (tried manually too https://azure.microsoft.com/en-us/blog/introduction-to-remote-debugging-on-azure-web-sites/)

I have app.UseDeveloperExceptionPage(); but I guess the site is failing during configuration so it doesn't display any other information.

So how to resolve this? I need to see the .net exception but I have no idea how to do that.

答: I solved this problem like show below.HTTP 500 error interested about that is not allowed to access the server.Go to azure portal address and choose your database.Press"Set server firewall " and Allow Azure services and resources to access this server choose "Yes" save that page and  refresh your service.Than you can see your data</p>


问:
Multiple Categorical Variables in a Column & The Prep
I have a survey data, with text answers, categorical variables, and numeric.

Converted into a dataframe in pandas, but the problem is multiple-choice columns, sometimes have more than 1 categorical variables, because the survey was designed as "choose all applies".

For example:

```<code>ID  Category    Num1 Num2 Num3
1   A, B, C     1    1    1
2   B, C, D     1    0    1
3   A, C        1    1    1
4   A           0    1    1
5   A, C, D     0    1    1
</code>```

I am trying to correlate these categories to the numerical variables.

Let's say the presence of A to value of Num1.

But when I use the dataframe, as it is, Python (and R) considers, for example [A, B, C] as another category, recognizes the whole cell as the category.

I think I need a method of parsing (exploding?) the value (in a hidden way), before feeding into a statistical analysis command.

How can I solve this problem?

答:
If your dataframe is called df, then you can test for the presence of "A" in Category like this:

```<code>grepl("A", as.character(df$Category))
#> [1]  TRUE FALSE  TRUE  TRUE  TRUE
</code>```

If you want TRUE and FALSE as 1 and 0 you just do:

```<code>grepl("A", as.character(df$Category)) * 1
#> [1] 1 0 1 1 1
</code>```

If you want them all at once, do:

```<code>sapply(c("A", "B", "C", "D"), function(x) grepl(x, as.character(df$Category)) * 1)
#>      A B C D
#> [1,] 1 1 1 0
#> [2,] 0 1 1 1
#> [3,] 1 0 1 0
#> [4,] 1 0 0 0
#> [5,] 1 0 1 1
</code>```

Or if you want them as columns in your original data frame, do:

```<code>cbind(df, sapply(c("A", "B", "C", "D"), function(x) grepl(x, as.character(df$Category)) * 1))
#>   ID Category Num1 Num2 Num3 A B C D
#> 1  1  A, B, C    1    1    1 1 1 1 0
#> 2  2  B, C, D    1    0    1 0 1 1 1
#> 3  3     A, C    1    1    1 1 0 1 0
#> 4  4        A    0    1    1 1 0 0 0
#> 5  5  A, C, D    0    1    1 1 0 1 1

</code>```

Body:
I have a survey data, with text answers, categorical variables, and numeric.

Converted into a dataframe in pandas, but the problem is multiple-choice columns, sometimes have more than 1 categorical variables, because the survey was designed as "choose all applies".

For example:

ID  Category    Num1 Num2 Num3
1   A, B, C     1    1    1
2   B, C, D     1    0    1
3   A, C        1    1    1
4   A           0    1    1
5   A, C, D     0    1    1

I am trying to correlate these categories to the numerical variables.

Let's say the presence of A to value of Num1.

But when I use the dataframe, as it is, Python (and R) considers, for example [A, B, C] as another category, recognizes the whole cell as the category.

I think I need a method of parsing (exploding?) the value (in a hidden way), before feeding into a statistical analysis command.

How can I solve this problem?

Body:
If your dataframe is called df, then you can test for the presence of "A" in Category like this:

grepl("A", as.character(df$Category))
#> [1]  TRUE FALSE  TRUE  TRUE  TRUE

If you want TRUE and FALSE as 1 and 0 you just do:

grepl("A", as.character(df$Category)) * 1
#> [1] 1 0 1 1 1

If you want them all at once, do:

sapply(c("A", "B", "C", "D"), function(x) grepl(x, as.character(df$Category)) * 1)
#>      A B C D
#> [1,] 1 1 1 0
#> [2,] 0 1 1 1
#> [3,] 1 0 1 0
#> [4,] 1 0 0 0
#> [5,] 1 0 1 1

Or if you want them as columns in your original data frame, do:

cbind(df, sapply(c("A", "B", "C", "D"), function(x) grepl(x, as.character(df$Category)) * 1))
#>   ID Category Num1 Num2 Num3 A B C D
#> 1  1  A, B, C    1    1    1 1 1 1 0
#> 2  2  B, C, D    1    0    1 0 1 1 1
#> 3  3     A, C    1    1    1 1 0 1 0
#> 4  4        A    0    1    1 1 0 0 0
#> 5  5  A, C, D    0    1    1 1 0 1 1


问:
How does CV_OCL_RUN macro work in goodFeaturesToTrack implementation from OpenCV (version 3.4.5)?
I was taking a look at goodFeaturesToTrack implementation from OpenCV (version 3.4.5, file modules/imgproc/src/featureselect.cpp) and found the CV_OCL_RUN macro inside of it. I don't know anything about OpencCL but I understand the preprocessor mechanisms typically used in C. I don't understand how this is supposed to work:

```<code>void cv::goodFeaturesToTrack( InputArray _image, OutputArray _corners,
                              int maxCorners, double qualityLevel, double minDistance,
                              InputArray _mask, int blockSize, int gradientSize,
                              bool useHarrisDetector, double harrisK )
{
    CV_INSTRUMENT_REGION();

    CV_Assert( qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0 );
    CV_Assert( _mask.empty() || (_mask.type() == CV_8UC1 && _mask.sameSize(_image)) );

    CV_OCL_RUN(_image.dims() <= 2 && _image.isUMat(),
               ocl_goodFeaturesToTrack(_image, _corners, maxCorners, qualityLevel, minDistance,
                                    _mask, blockSize, gradientSize, useHarrisDetector, harrisK))

    Mat image = _image.getMat(), eig, tmp;
    if (image.empty())
    {
        _corners.release();
        return;
    }
    .
    .
    .
</code>```

Let's suppose this is compiled with OpenCL support so where the macro CV_OCL_RUN is, the function ocl_goodFeaturesToTrack is effectively called. After that, would not the execution continue to the lines of code intended for versions without OpenCL? I can think of other macros defined at a higher level that could make that if you have OpenCL support then the function I am looking at would not be called but I did not find any other part where it is defined.

答:
If I'm not misunderstanding the situation, the function would not continue executing - the macro contains a return statement.

Have a look at the possible options of what CV_OCL_RUN can expand to:
https://github.com/opencv/opencv/blob/master/modules/core/include/opencv2/core/opencl/ocl_defs.hpp

All three variants of CV_OCL_RUN_ return if the OpenCL route is taken: lines 36, 57 and 67.

Body:
I was taking a look at goodFeaturesToTrack implementation from OpenCV (version 3.4.5, file modules/imgproc/src/featureselect.cpp) and found the CV_OCL_RUN macro inside of it. I don't know anything about OpencCL but I understand the preprocessor mechanisms typically used in C. I don't understand how this is supposed to work:

void cv::goodFeaturesToTrack( InputArray _image, OutputArray _corners,
                              int maxCorners, double qualityLevel, double minDistance,
                              InputArray _mask, int blockSize, int gradientSize,
                              bool useHarrisDetector, double harrisK )
{
    CV_INSTRUMENT_REGION();

    CV_Assert( qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0 );
    CV_Assert( _mask.empty() || (_mask.type() == CV_8UC1 && _mask.sameSize(_image)) );

    CV_OCL_RUN(_image.dims() <= 2 && _image.isUMat(),
               ocl_goodFeaturesToTrack(_image, _corners, maxCorners, qualityLevel, minDistance,
                                    _mask, blockSize, gradientSize, useHarrisDetector, harrisK))

    Mat image = _image.getMat(), eig, tmp;
    if (image.empty())
    {
        _corners.release();
        return;
    }
    .
    .
    .

Let's suppose this is compiled with OpenCL support so where the macro CV_OCL_RUN is, the function ocl_goodFeaturesToTrack is effectively called. After that, would not the execution continue to the lines of code intended for versions without OpenCL? I can think of other macros defined at a higher level that could make that if you have OpenCL support then the function I am looking at would not be called but I did not find any other part where it is defined.


问:
Binary Tree Python - AttributeError: 'NoneType' object has no attribute 'left'
I'm trying to add elements to a binary tree and print them in pre-order.

The elements that are added to the binary tree are of type node.

I'm getting an error while adding an element:
AttributeError: 'NoneType' object has no attribute 'left'

Please let me know where I have to make a change
Below is the code:

```<code>class Node(object):

    def __init__(self, item, left=None, right=None):
        self.item = item
        self.left = None
        self.right = None

    def __repr__(self):
        return '{}'.format(self.item)

class BinaryTree(object):

    def __init__(self, root=None):
        self.root = root

    def add(self, value):

        val = self.root
        if not val:
            val = value
        elif not val.left:
            val = value
        elif not val.right:
            val = value
        else:
            self.left = val.left.add(value)
        return val

    def preorder(self):
        val = self.root
        print(val)
        if val.left:
            val.left.preorder()
        if val.right:
            val.right.preorder()

def main():

    binary_tree = BinaryTree()

    print("Adding nodes in tree")
    for i in range(1, 11):
        node = Node(i)
        binary_tree.add(node)

    print("Printing preorder...")
    binary_tree.preorder()

if __name__ == '__main__':
    main()

</code>```

Error:

```<code>Adding nodes in tree
Printing preorder...
None
Traceback (most recent call last):
  File ".\binary_tree_test5.py", line 52, in <module>
    main()
  File ".\binary_tree_test5.py", line 49, in main
    binary_tree.preorder()
  File ".\binary_tree_test5.py", line 33, in preorder
    if val.left:
AttributeError: 'NoneType' object has no attribute 'left'
</code>```

答:
in your code its the case when your root node is null.

you can prevent this by checking root values.

def preorder(self):
    val = self.root
    if not val: # this will handle the case when root node is None.
        return
    print(val)
    if val.left:
        val.left.preorder()
    if val.right:
        val.right.preorder()
```

PS: I think your add method is wrong. You can debug that part for any other issues.

Body:
I'm trying to add elements to a binary tree and print them in pre-order.

The elements that are added to the binary tree are of type node.

I'm getting an error while adding an element:
AttributeError: 'NoneType' object has no attribute 'left'

Please let me know where I have to make a change
Below is the code:

class Node(object):

    def __init__(self, item, left=None, right=None):
        self.item = item
        self.left = None
        self.right = None

    def __repr__(self):
        return '{}'.format(self.item)

class BinaryTree(object):

    def __init__(self, root=None):
        self.root = root

    def add(self, value):

        val = self.root
        if not val:
            val = value
        elif not val.left:
            val = value
        elif not val.right:
            val = value
        else:
            self.left = val.left.add(value)
        return val

    def preorder(self):
        val = self.root
        print(val)
        if val.left:
            val.left.preorder()
        if val.right:
            val.right.preorder()

def main():

    binary_tree = BinaryTree()

    print("Adding nodes in tree")
    for i in range(1, 11):
        node = Node(i)
        binary_tree.add(node)

    print("Printing preorder...")
    binary_tree.preorder()

if __name__ == '__main__':
    main()

Error:

Adding nodes in tree
Printing preorder...
None
Traceback (most recent call last):
  File ".\binary_tree_test5.py", line 52, in <module>
    main()
  File ".\binary_tree_test5.py", line 49, in main
    binary_tree.preorder()
  File ".\binary_tree_test5.py", line 33, in preorder
    if val.left:
AttributeError: 'NoneType' object has no attribute 'left'

Body:
in your code its the case when your root node is null.

you can prevent this by checking root values.

def preorder(self):
    val = self.root
    if not val: # this will handle the case when root node is None.
        return
    print(val)
    if val.left:
        val.left.preorder()
    if val.right:
        val.right.preorder()

PS: I think your add method is wrong. You can debug that part for any other issues.


问:
extend button android, xml layout
I have the following class (included into another class)

```<code>class RecordButton extends Button {
    boolean mStartRecording = true;

    OnClickListener clicker = new OnClickListener() {
        public void onClick(View v) {
            onRecord(mStartRecording);
            if (mStartRecording) {
                setText("Stop recording");
            } else {
                setText("Start recording");
            }
            mStartRecording = !mStartRecording;
        }
    };

    public RecordButton(Context ctx) {
        super(ctx);
        setText("Start recording");
        setOnClickListener(clicker);
    }
}
</code>```

The display of the button is made using the following code:

```<code>public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    LinearLayout ll = new LinearLayout(this);
    mRecordButton = new RecordButton(this);
    ll.addView(mRecordButton,
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            0));
    setContentView(ll);
}
</code>```

How can I define the Button layout into the .xml file instead of doing it in the java code?

I have tried that:

```<code><AudioRecordTest.test.RecordButton
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Button"
    android:id="@+id/record" />
</code>```

But it is not working...

Many thanks,

Joachim

答:
I understand "(included into another class)" as you have an inner class RecordButton.

Assuming your package is AudioRecordTest.test (which would be a very bad name choice) and your RecordButton class is an inner class of AudioRecord.class, you need to use:

```<code> <view class="AudioRecordTest.test.AudioRecord$RecordButton"
</code>```

Use the $ sign to separate inner classes. You need to write the qualified name inside quotes. Also, make sure you create your class public static, or it won't be visible.

BTW: any particular reason you create it as an inner class instead of having it separate?

Title: extend button android, xml layout

Body:
I have the following class (included into another class)

class RecordButton extends Button {
    boolean mStartRecording = true;

    OnClickListener clicker = new OnClickListener() {
        public void onClick(View v) {
            onRecord(mStartRecording);
            if (mStartRecording) {
                setText("Stop recording");
            } else {
                setText("Start recording");
            }
            mStartRecording = !mStartRecording;
        }
    };

    public RecordButton(Context ctx) {
        super(ctx);
        setText("Start recording");
        setOnClickListener(clicker);
    }
}

The display of the button is made using the following code:

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    LinearLayout ll = new LinearLayout(this);
    mRecordButton = new RecordButton(this);
    ll.addView(mRecordButton,
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            0));
    setContentView(ll);
}

How can I define the Button layout into the .xml file instead of doing it in the java code?

I have tried that:

<AudioRecordTest.test.RecordButton
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Button"
    android:id="@+id/record" />

But it is not working...

Many thanks,

Joachim

Body:
I understand "(included into another class)" as you have an inner class RecordButton.

Assuming your package is AudioRecordTest.test (which would be a very bad name choice) and your RecordButton class is an inner class of AudioRecord.class, you need to use:

 <view class="AudioRecordTest.test.AudioRecord$RecordButton"

Use the $ sign to separate inner classes. You need to write the qualified name inside quotes. Also, make sure you create your class public static, or it won't be visible.

BTW: any particular reason you create it as an inner class instead of having it separate?


问:
For Each Loop with ArrayList
In the below code, how is it that in the inner For Each loop, we can create a variable of type int from the variable we created in the outer For Each loop that is of type List? Yet if we try to create this variable of primitive type int, there is an error. Can't work out how we can create a For Each variable of type int from userAge, but not from userAges.</p>

```<code>   List <List<Integer>> userAges = new ArrayList<List<Integer>>();

    userAges.add(Arrays.asList(51, 48, 21));
    userAges.add(Arrays.asList(33, 51, 19));
    userAges.add(Arrays.asList(39, 47, 58));

    for (List<Integer> userAge : userAges)
    {
        for (int age : userAge)
        {
            System.out.print(age + " ");
        }
        System.out.println();
    }
</code>```

答:
Java will auto-unbox the primitive wrapper classes to their primitive equivalent, so given

```<code>List<Integer> userAge; // what the outer loop provides to the inner loop
</code>```

We can write either:

```<code>for (Integer age : userAge)
</code>```

or:

```<code>for (int age : userAge)
</code>```

More generally, given:

```<code>Integer integer;
</code>```

We can write:

```<code>int i = integer;
</code>```

Read the full specification here.

Title: For Each Loop with ArrayList

Body:
In the below code, how is it that in the inner For Each loop, we can create a variable of type int from the variable we created in the outer For Each loop that is of type List? Yet if we try to create this variable of primitive type int, there is an error. Can't work out how we can create a For Each variable of type int from userAge, but not from userAges.

   List <List<Integer>> userAges = new ArrayList<List<Integer>>();

    userAges.add(Arrays.asList(51, 48, 21));
    userAges.add(Arrays.asList(33, 51, 19));
    userAges.add(Arrays.asList(39, 47, 58));

    for (List<Integer> userAge : userAges)
    {
        for (int age : userAge)
        {
            System.out.print(age + " ");
        }
        System.out.println();
    }

Body:
Java will auto-unbox the primitive wrapper classes to their primitive equivalent, so given

List<Integer> userAge; // what the outer loop provides to the inner loop

We can write either:

for (Integer age : userAge)

or:

for (int age : userAge)

More generally, given:

Integer integer;

We can write:

int i = integer;

Read the full specification here.


问:
Enter a valid date/time in Django Forms
Anytime I try to input datetime into my form, it always says Enter a valid date/time
I tried different datetime formats; the one i speified and the default ones, they all did not work.
I have tried different solutions on Stack Overflow, but they all do not seem to work.
The field I have this issue with is due_date

NOTE: I didn't show any imports

Also, i need recommendations for nice datetime pickers. All the ones I tried didn't work for some reason or the other.

views.py:

```<code>@login_required
def task_create(request):
    data = dict()
#, data=request.POST
    if request.method == 'POST':
        form = TaskForm(request.user, data=request.POST)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
    else:
        form = TaskForm(request.user)

    context = {'form': form}
    data['html_form'] = render_to_string('partial_task_create.html',
        context,
        request=request
    )
    return JsonResponse(data)
</code>```

forms.py:

```<code>class TaskForm(ModelForm):

    due_date = forms.DateTimeField(input_formats=['%I:%M %p %d-%b-%Y'])
    parent = forms.ModelChoiceField(queryset=Task.objects.all(), empty_label="---None---", required=False)
    #widget=DateTimePickerInput(format='%I:%M %p %d-%m-%Y')

    class Meta:
        model = Task
        fields = ['task_title', 'task_description', 'due_date', 'is_completed', 'categories', 'parent']
        widgets = {
             #'due_date': DateTimeInput()
        }

    def __init__(self, user, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['categories'].queryset = Categories.objects.filter(Q(user_id__isnull=True) | Q(user_id=user.id))
</code>```

答:
You will need to set the widget attribute on the due_date form field to match the input formats.
Something like:

```<code>due_date = forms.DateTimeField(input_formats=['%I:%M %p %d-%b-%Y'],
             widget = forms.DateTimeInput(
                 attrs={'type': 'datetime-local'},
                 format='%I:%M %p %d-%b-%Y'))
</code>```

For datetime pickers, take a look at https://github.com/xdan/datetimepicker

Title: Enter a valid date/time in Django Forms

Body:
Anytime I try to input datetime into my form, it always says Enter a valid date/time
I tried different datetime formats; the one i speified and the default ones, they all did not work.
I have tried different solutions on Stack Overflow, but they all do not seem to work.
The field I have this issue with is due_date

NOTE: I didn't show any imports

Also, i need recommendations for nice datetime pickers. All the ones I tried didn't work for some reason or the other.

views.py:

@login_required
def task_create(request):
    data = dict()
#, data=request.POST
    if request.method == 'POST':
        form = TaskForm(request.user, data=request.POST)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
    else:
        form = TaskForm(request.user)

    context = {'form': form}
    data['html_form'] = render_to_string('partial_task_create.html',
        context,
        request=request
    )
    return JsonResponse(data)

forms.py:

class TaskForm(ModelForm):

    due_date = forms.DateTimeField(input_formats=['%I:%M %p %d-%b-%Y'])
    parent = forms.ModelChoiceField(queryset=Task.objects.all(), empty_label="---None---", required=False)
    #widget=DateTimePickerInput(format='%I:%M %p %d-%m-%Y')

    class Meta:
        model = Task
        fields = ['task_title', 'task_description', 'due_date', 'is_completed', 'categories', 'parent']
        widgets = {
             #'due_date': DateTimeInput()
        }

    def __init__(self, user, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['categories'].queryset = Categories.objects.filter(Q(user_id__isnull=True) | Q(user_id=user.id))

Body:
You will need to set the widget attribute on the due_date form field to match the input formats.
Something like:

due_date = forms.DateTimeField(input_formats=['%I:%M %p %d-%b-%Y'],
             widget = forms.DateTimeInput(
                 attrs={'type': 'datetime-local'},
                 format='%I:%M %p %d-%b-%Y'))

For datetime pickers, take a look at https://github.com/xdan/datetimepicker


问:
Is there a way to install Valgrind on Catalina?
Is there a way to install Valgrind on Catalina and have it run properly? If so, I would very much appreciate a step-by-step process.

I tried installing Valgrind with https://github.com/sowson/valgrind
but when I tested out helloWorld.cpp on the terminal, the console returned errors I should not have gotten.

I'm not sure if I committed an error on my part in the installation process of this version of Valgrind or if Valgrind itself is simply incompatible with Catalina OS.

I have also tried installing Valgrind via Homebrew, but I've had issues with that as well (github.com/Homebrew/homebrew-core/issues/36683).

答: Ok. I've found a way to use Valgrind on Catalina. Here's a link to my guide for how https://github.com/john-yohan-park/Valgrind_Catalina</p>


问:
Add an image dynamically to this beautiful frame
Here is a beautifully animated border in pure CSS.

What if we want this animated borders as a frame and add an image as the content inside it.

When I add the image it just overlays the frame, But I want to put the image inside the frame, not over it.

I have tried my best but I can't find a solution without a hand.

Here is what I've tried (I need to add the image dynamically using javascript):

//addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

let image = document.createElement('img');
image.setAttribute("id", "shot");
var node = document.getElementsByClassName('content');
node[0].appendChild(image);
image.src = `${pictureSource}`;
let shot = document.getElementById("shot");

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box .content {
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}</code>```

```

答:
Another option: set .content to overflow: hidden

And to help preserve the illusion that the frame is on top of the image, and an :after pseudo element to .box with an inset shadow.

addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

let image = document.createElement('img');
image.setAttribute("id", "shot");
var node = document.getElementsByClassName('content');
node[0].appendChild(image);
image.src = `${pictureSource}`;
let shot = document.getElementById("shot");

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box:after {
  content: '';
  position: absolute;
  z-index: 3;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
 border-radius: 10px;
 box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
}

.box .content {
  overflow: hidden;
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}</code>```

```

Body:
Here is a beautifully animated border in pure CSS.

What if we want this animated borders as a frame and add an image as the content inside it.

When I add the image it just overlays the frame, But I want to put the image inside the frame, not over it.

I have tried my best but I can't find a solution without a hand.

Here is what I've tried (I need to add the image dynamically using javascript):

//addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

let image = document.createElement('img');
image.setAttribute("id", "shot");
var node = document.getElementsByClassName('content');
node[0].appendChild(image);
image.src = `${pictureSource}`;
let shot = document.getElementById("shot");

}

html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box .content {
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}

Body:
Another option: set .content to overflow: hidden

And to help preserve the illusion that the frame is on top of the image, and an :after pseudo element to .box with an inset shadow.

addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

let image = document.createElement('img');
image.setAttribute("id", "shot");
var node = document.getElementsByClassName('content');
node[0].appendChild(image);
image.src = `${pictureSource}`;
let shot = document.getElementById("shot");

}

html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box:after {
  content: '';
  position: absolute;
  z-index: 3;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
 border-radius: 10px;
 box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
}

.box .content {
  overflow: hidden;
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}

<div class="box">
  <div class="content">

  </div>
</div>


问:
Algorithm to rotate an array in linear time
How to rotate an integer array by i times using swap function only in linear time.

答:
```<code>void rotate(int array [], int n, int k)
{
    int temp1,temp2;     //two variable to hold values
    int visited,count,index;   //'visited' to check if cycle
                               // collides with index
                               //'count' to check number of loops
    visited = n-1;
    temp1 = array[n-1];
    index = n-1;
    count = 0;

    while(count<n)
    {
        temp2 = temp1;
        temp1 = array[(n+index-k)%n];
        array[(n+index-k)%n] = temp2;
        index = (n+index-k)%n;
        if (index == visited)
        {
            cout<<"\nindex == visited at index = "<<index;
            getch();
            index--;
            visited=index;
            temp1=array[index];
        }
        count++;
        cout<<"\ncount is : "<<count;
        cout<<"\narray is : ";
        p_all_arr(array,0,n); //display arr
        getch();
    }

}
</code>```


问:
Why am I getting a double free or corruption error with realloc()?
I've tried to write a string replace function in C, which works on a char *, which has been allocated using malloc().  It's a little different in that it will find and replace strings, rather than characters in the starting string.

It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated.  If I try to use realloc(), I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using realloc().

Perhaps a little code will help:

```<code>void strrep(char *input, char *search, char *replace) {
    int searchLen = strlen(search);
    int replaceLen = strlen(replace);
    int delta = replaceLen - searchLen;
    char *find = input;

    while (find = strstr(find, search)) {

        if (delta > 0) {
            realloc(input, strlen(input) + delta);
            find = strstr(input, search);
        }

        memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input));
        memmove(find, replace, replaceLen);
    }
}
</code>```

The program works, until I try to realloc() in an instance where the replaced string will be longer than the initial string.  (It still kind of works, it just spits out errors as well as the result).

If it helps, the calling code looks like:

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

void strrep(char *input, char *search, char *replace);

int main(void) {
    char *input = malloc(81);

    while ((fgets(input, 81, stdin)) != NULL) {
        strrep(input, "Noel", "Christmas");
    }
}
</code>```

答:
realloc is strange, complicated and should only be used when dealing with lots of memory lots of times per second. i.e. - where it actually makes your code faster.

I have seen code where

```<code>realloc(bytes, smallerSize);
</code>```

was used and worked to resize the buffer, making it smaller. Worked about a million times, then for some reason realloc decided that even if you were shortening the buffer, it would give you a nice new copy. So you crash in a random place 1/2 a second after the bad stuff happened.

Always use the return value of realloc.

Body:
I've tried to write a string replace function in C, which works on a char *, which has been allocated using malloc().  It's a little different in that it will find and replace strings, rather than characters in the starting string.

It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated.  If I try to use realloc(), I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using realloc().

Perhaps a little code will help:

void strrep(char *input, char *search, char *replace) {
    int searchLen = strlen(search);
    int replaceLen = strlen(replace);
    int delta = replaceLen - searchLen;
    char *find = input;

    while (find = strstr(find, search)) {

        if (delta > 0) {
            realloc(input, strlen(input) + delta);
            find = strstr(input, search);
        }

        memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input));
        memmove(find, replace, replaceLen);
    }
}

The program works, until I try to realloc() in an instance where the replaced string will be longer than the initial string.  (It still kind of works, it just spits out errors as well as the result).

If it helps, the calling code looks like:

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

void strrep(char *input, char *search, char *replace);

int main(void) {
    char *input = malloc(81);

    while ((fgets(input, 81, stdin)) != NULL) {
        strrep(input, "Noel", "Christmas");
    }
}

Body:
realloc is strange, complicated and should only be used when dealing with lots of memory lots of times per second. i.e. - where it actually makes your code faster.

I have seen code where

realloc(bytes, smallerSize);

was used and worked to resize the buffer, making it smaller. Worked about a million times, then for some reason realloc decided that even if you were shortening the buffer, it would give you a nice new copy. So you crash in a random place 1/2 a second after the bad stuff happened.

Always use the return value of realloc.


问:
how to check function is called or not in react js?
I am trying to test my service which have one function saveWithoutSubmit

```<code>export const saveWithoutSubmit = async (
  values,
  orderId,
  taskId,
  fseMsisdn,
  updateTaskListAfterFilter
) => {
  var obj = {
    remarks: values.remarks,
    requestedBy: localStorage.getItem("msisdn")
  };
  try {
    const response = await sendPostRequest(`${API_TASK_URL}closeSr`, {
      ...obj,
      saveWithoutSubmit: true
    });

    if (response && response.data && response.data.status.code !== "200") {
      error(response.data.result.message);
    } else {
      console.log(response);
      success(response.data.status.message);
      updateTaskListAfterFilter();
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
      error(e.response.data.status.message);
    }
  }
};
</code>```

I want to check success or error method is called or not ? or updateTaskListAfterFilter is called or not?

I tried like this

https://codesandbox.io/s/ecstatic-currying-5q1b8

```<code>describe("remark service test", () => {
  const fakeAxios = {
    get: jest.fn(() => Promise.resolve({ data: { greeting: "hello there" } }))
  };
  it("save without sumit", () => {
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();
  });
});
</code>```

can you please suggest how i will test async methods or post request (using mook data)??

so that my test cases will be passed.
I want to check if I got success from promise my success method will be called else error

any update ?..!!

update

https://codesandbox.io/s/ecstatic-currying-5q1b8

```<code>it("save without sumit", async () => {
    const sendPostRequest = jest.fn(() =>
      Promise.resolve({ data: { greeting: "hello there" } })
    );
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();
  });

it("save without sumit", async () => {
    const sendPostRequest = jest.fn(() =>
      Promise.resolve({ data: { greeting: "hello there" } })
    );

    const mockUpdateTaskListAfterFilter = jest.fn();
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();

    await wait(() => {
      expect(mockUpdateTaskListAfterFilter).toBeCalled();
    });
  });
</code>```

答:
You should change it("save without sumit", () => { to it("save without sumit", async () => {.

Then you usually use jest.fn() to create a mock function that you will give to another function or component.

Finally, await the mock function to be called:

```<code>await wait(() => {
  expect(mockUpdateTaskListAfterFilter).toBeCalled();
});
</code>```

Alternatively, you can await some other event that you know will occur before your mock is called, like some other mock getting called or something appearing on the page, and then check that your mock was called.

Body:
I am trying to test my service which have one function saveWithoutSubmit

export const saveWithoutSubmit = async (
  values,
  orderId,
  taskId,
  fseMsisdn,
  updateTaskListAfterFilter
) => {
  var obj = {
    remarks: values.remarks,
    requestedBy: localStorage.getItem("msisdn")
  };
  try {
    const response = await sendPostRequest(`${API_TASK_URL}closeSr`, {
      ...obj,
      saveWithoutSubmit: true
    });

    if (response && response.data && response.data.status.code !== "200") {
      error(response.data.result.message);
    } else {
      console.log(response);
      success(response.data.status.message);
      updateTaskListAfterFilter();
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
      error(e.response.data.status.message);
    }
  }
};

I want to check success or error method is called or not ? or updateTaskListAfterFilter is called or not?

I tried like this

https://codesandbox.io/s/ecstatic-currying-5q1b8

describe("remark service test", () => {
  const fakeAxios = {
    get: jest.fn(() => Promise.resolve({ data: { greeting: "hello there" } }))
  };
  it("save without sumit", () => {
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();
  });
});

can you please suggest how i will test async methods or post request (using mook data)??

so that my test cases will be passed.
I want to check if I got success from promise my success method will be called else error

any update ?..!!

update

https://codesandbox.io/s/ecstatic-currying-5q1b8

it("save without sumit", async () => {
    const sendPostRequest = jest.fn(() =>
      Promise.resolve({ data: { greeting: "hello there" } })
    );
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();
  });

it("save without sumit", async () => {
    const sendPostRequest = jest.fn(() =>
      Promise.resolve({ data: { greeting: "hello there" } })
    );

    const mockUpdateTaskListAfterFilter = jest.fn();
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();

    await wait(() => {
      expect(mockUpdateTaskListAfterFilter).toBeCalled();
    });
  });

Body:
You should change it("save without sumit", () => { to it("save without sumit", async () => {.

Then you usually use jest.fn() to create a mock function that you will give to another function or component.

Finally, await the mock function to be called:

await wait(() => {
  expect(mockUpdateTaskListAfterFilter).toBeCalled();
});

Alternatively, you can await some other event that you know will occur before your mock is called, like some other mock getting called or something appearing on the page, and then check that your mock was called.


问:
Python Loop for temperature
I am learning python for the first time and my assignment required me to:

Write a loop to print all elements in hourly_temperature. Separate
elements with a -> surrounded by spaces. Sample output for the given
program:

```<code>90 -> 92 -> 94 -> 95
</code>```

Note: 95 is followed by a space, then a newline.

After playing I had difficulty and found the coded answer as:

```<code>hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list
temps = []

if Htemp >= 0:
    for i in hourly_temperature: #question on i and appends i
        temps.append(i)
        temps.append('->')
        Htemp -= 1
        continue
temps.pop()
for s in temps:    #question here
    print(s,'', end='')
    continue
print('')
</code>```

My question is regarding the for loops that I have notated with the #question.

I am wondering what the purpose is for the i and s to make the code work.

答:
I am sure many people here will give you 'Pythonic' one-liners that will output what you need.  But I think you're at the stage where you need to learn how to code logically, rather than how to be Pythonic.

The example you give is messy and not elegant in any language.

Here is how I would code your assignment, using simple logic suitable for a beginner.  Hopefully this will be more helpful than a short one-liner.

```<code>hourly_temperature = [90, 92, 94, 95]

# Start with an empty string
s = ""

# Step through each temperature in the list
for t in hourly_temperature:

    # If the string contains a number, then we need to add ->
    # before the next number.
    if s != "":
        s += "-> "

    # Add the temperature and a space
    s += str(t) + " "

# Print the string we have just built
print(s)
</code>```

Another common way to achieve the result is to not worry about checking whether "-> " needs to be prefixed during the loop.  Instead, always prefix "-> " and remove the erroneous one at the end.  This is slightly more efficient for large loops.

```<code>hourly_temperature = [90, 92, 94, 95]

s = ""
for t in hourly_temperature:
    s += " -> " + str(t)

# At this stage, s contains " -> 90 -> 92 -> 94 -> 95" so we need to remove the first ->
# We do this by keeping everything from character 4 onwards
print(s[4:])
</code>```

Title: Python Loop for temperature

Body:
I am learning python for the first time and my assignment required me to:

Write a loop to print all elements in hourly_temperature. Separate
elements with a -> surrounded by spaces. Sample output for the given
program:

90 -> 92 -> 94 -> 95

Note: 95 is followed by a space, then a newline.

After playing I had difficulty and found the coded answer as:

hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list
temps = []

if Htemp >= 0:
    for i in hourly_temperature: #question on i and appends i
        temps.append(i)
        temps.append('->')
        Htemp -= 1
        continue
temps.pop()
for s in temps:    #question here
    print(s,'', end='')
    continue
print('')

My question is regarding the for loops that I have notated with the #question.

I am wondering what the purpose is for the i and s to make the code work.

Body:
I am sure many people here will give you 'Pythonic' one-liners that will output what you need.  But I think you're at the stage where you need to learn how to code logically, rather than how to be Pythonic.

The example you give is messy and not elegant in any language.

Here is how I would code your assignment, using simple logic suitable for a beginner.  Hopefully this will be more helpful than a short one-liner.

hourly_temperature = [90, 92, 94, 95]

# Start with an empty string
s = ""

# Step through each temperature in the list
for t in hourly_temperature:

    # If the string contains a number, then we need to add ->
    # before the next number.
    if s != "":
        s += "-> "

    # Add the temperature and a space
    s += str(t) + " "

# Print the string we have just built
print(s)

Another common way to achieve the result is to not worry about checking whether "-> " needs to be prefixed during the loop.  Instead, always prefix "-> " and remove the erroneous one at the end.  This is slightly more efficient for large loops.

hourly_temperature = [90, 92, 94, 95]

s = ""
for t in hourly_temperature:
    s += " -> " + str(t)

# At this stage, s contains " -> 90 -> 92 -> 94 -> 95" so we need to remove the first ->
# We do this by keeping everything from character 4 onwards
print(s[4:])