问:
x86 division exception-return address
When trying to write some routine in x86 assembly for a boot loader, I came across a bug where when a division error happened, the program would get stuck in an infinite loop. Through investigating, I found out that calling int 0 would go through the exception handler normally and then continue execution of the rest of the program. Writing my own exception handler for x86, the return address when a division error exception happened was the address of the instruction, meaning that it would just execute the division over and over looping forever. Is this normal behavior or a bug with Virtualbox/my cpu specifically?</p>
```<code>org 0x7c00      ;put all label addresses at offset 0x7c00

xor ax, ax      ;set up all segment registers
mov ds, ax
mov ax, 0x9000
mov ss, ax
mov sp, 0x1000
mov ax, 0xB800  ;video text memory starts at this address
mov es, ax

mov ah, 0x00
mov al, 0x02
int 0x10        ;go into 80x25 monochrome text

mov [0x0000], word DivideException
mov [0x0002], word 0x0000

xor di, di
xor bx, bx

;int 0   ;this and the divide CX below will cause a division error exception

mov ax, 0
mov cx, 0 ;when exception is handled it prints out
div cx    ;"a divide by zero error happened 0000:7C2D 0000:7C2F
          ;the first address is the division instruction and the second one is 2 bytes after
          ;when int 0 is uncommented out then it will have the two same addresses
jmp $

ToHex:
push bp
mov bp, sp
push bx

mov ax, word [bp+6]
mov bx, word [bp+4]
add bx, 3
mov cx, 16

.Loop:
xor dx, dx
div cx
add dx, 48
cmp dx, 58
jb .Skip
add dx, 7
.Skip:
mov byte [bx], dl
dec bx
cmp ax, 0
jne .Loop

.Ret:
pop bx
mov sp, bp
pop bp
ret

PrintStr:
push bp
mov bp, sp
push bx

mov bx, word [bp+6]
mov ah, byte [bx]
mov bx, word [bp+4]

.PrintLoop:
mov al, byte [bx]

mov word [es:di], ax
inc di
inc di
inc bx
cmp byte [bx], 0x00
jne .PrintLoop

pop bx
mov sp, bp
pop bp
ret

DivideException:
push bp
mov bp, sp
push bx

push word ColorAttributes1
push word String3
call PrintStr
add sp, 4

push word [bp+4]
push word String1
call ToHex
add sp, 4

push word [bp+2]
push word String2
call ToHex
add sp, 4

push word ColorAttributes1
push word String1
call PrintStr

push ds
mov ds, word [bp+4]
mov bx, word [bp+2]

cmp byte [ds:bx], 0xF7  ;checks if theres a 0xF7 byte at the return address
jne .DontAdd            ;for some reason the return address when calling int 0
add word [bp+2], 2      ;directly is the address after the instruction while
.DontAdd:               ;causing a divide error exception through divsion will
pop ds                  ;put the return address at the division leading to an
                        ;infinite loop
push word [bp+4]
push word String1
call ToHex
add sp, 4

push word [bp+2]
push word String2
call ToHex
add sp, 4

push word ColorAttributes1
push word String1
call PrintStr

add sp, 4

pop bx
mov sp, bp
pop bp
iret

String1: db "0000:";, 0x00
String2: db "0000 ", 0x00
String3: db "a divide by zero error happened ", 0x00
ColorAttributes1: db 0x0F ; first nibble is backround color
                         ;second nibble is foreground

times 2048-2- ($-$$) db 0  ;fills the rest with 0's until 510 bytes
dw 0xAA55               ;magic boot sector number
</code>```

答:
Original 8086/8088 does push the address of the following instruction for #DE exceptions.

But all other x86 CPUs push the start address of the faulting div/idiv instruction.  (At least starting from 386; but 286 is very likely the same as 386.)

That's normal for x86 in general: faulting instructions push the address of the instruction that faulted.  x86 machine code can't be reliably/unambiguously decoded backwards, so the design intent is that the exception handler can examine the situation and potentially repair it, and re-run the faulting instruction.

See Intel x86 - Interrupt Service Routine responsibility which breaks down the differences between Faults, Traps, and Aborts, and even specifically mentions the difference between int 0 and a faulting div.

That's useful for #PF page faults, although not as realistic for things like FP and integer arithmetic exceptions.  But if not repair, then at least report the actual instruction that faulted.  e.g. idiv dword [fs: rdi + 0xf1f7f1f7] would be ambiguous to disassemble backwards.  The f7 f1 bytes in the disp32 are the encoding for div  ecx.  You also wouldn't know if a jump had jumped straight to the idiv opcode after the FS prefix.  So it's definitely useful for debugging and possibly other purposes to have the actual address of the start of the faulting instruction, not its end.

int 0 (if allowed by the IDT if you're not in real mode) pushes the CS:[ER]IP of the following instruction, of course, since it's not something that could re-run without faulting after the situation is repaired.  int in general is intended to work kind of like call in terms of returning to the instruction after.

The 8086 behaviour appears to have been an intentional decision to simplify the hardware at the expense of worse behaviour.  It has no limit on max instruction length, and avoids remembering the start of an instruction at all, anywhere inside the CPU (Ken Shirriff quotes an Intel patent in an answer on Interrupts, Instruction Pointer, and Instruction Queue in 8086).

If cs rep movsb is interrupted by an external interrupt, the interrupt-return address is before the final prefix, not the actual instruction start.  (i.e. it would resume as rep movsb without the cs prefix, which is a disaster if you put the prefixes in that order.  This is the biggest "worse behaviour"; you can work around it by putting rep cs movsb inside a loop.)  Since 8086 doesn't have any kind of page-faults or configurable segment-limits, it can't take a synchronous exception during rep cs movsb or other rep-string instructions, only async external interrupts.

See Why do call and jump instruction use a displacement relative to the next instruction, not current? for more guesswork about 8086 design decisions.

Title: x86 division exception-return address

Body:
When trying to write some routine in x86 assembly for a boot loader, I came across a bug where when a division error happened, the program would get stuck in an infinite loop. Through investigating, I found out that calling int 0 would go through the exception handler normally and then continue execution of the rest of the program. Writing my own exception handler for x86, the return address when a division error exception happened was the address of the instruction, meaning that it would just execute the division over and over looping forever. Is this normal behavior or a bug with Virtualbox/my cpu specifically?

org 0x7c00      ;put all label addresses at offset 0x7c00

xor ax, ax      ;set up all segment registers
mov ds, ax
mov ax, 0x9000
mov ss, ax
mov sp, 0x1000
mov ax, 0xB800  ;video text memory starts at this address
mov es, ax

mov ah, 0x00
mov al, 0x02
int 0x10        ;go into 80x25 monochrome text

mov [0x0000], word DivideException
mov [0x0002], word 0x0000

xor di, di
xor bx, bx

;int 0   ;this and the divide CX below will cause a division error exception

mov ax, 0
mov cx, 0 ;when exception is handled it prints out
div cx    ;"a divide by zero error happened 0000:7C2D 0000:7C2F
          ;the first address is the division instruction and the second one is 2 bytes after
          ;when int 0 is uncommented out then it will have the two same addresses
jmp $

ToHex:
push bp
mov bp, sp
push bx

mov ax, word [bp+6]
mov bx, word [bp+4]
add bx, 3
mov cx, 16

.Loop:
xor dx, dx
div cx
add dx, 48
cmp dx, 58
jb .Skip
add dx, 7
.Skip:
mov byte [bx], dl
dec bx
cmp ax, 0
jne .Loop

.Ret:
pop bx
mov sp, bp
pop bp
ret

PrintStr:
push bp
mov bp, sp
push bx

mov bx, word [bp+6]
mov ah, byte [bx]
mov bx, word [bp+4]

.PrintLoop:
mov al, byte [bx]

mov word [es:di], ax
inc di
inc di
inc bx
cmp byte [bx], 0x00
jne .PrintLoop

pop bx
mov sp, bp
pop bp
ret

DivideException:
push bp
mov bp, sp
push bx

push word ColorAttributes1
push word String3
call PrintStr
add sp, 4

push word [bp+4]
push word String1
call ToHex
add sp, 4

push word [bp+2]
push word String2
call ToHex
add sp, 4

push word ColorAttributes1
push word String1
call PrintStr

push ds
mov ds, word [bp+4]
mov bx, word [bp+2]

cmp byte [ds:bx], 0xF7  ;checks if theres a 0xF7 byte at the return address
jne .DontAdd            ;for some reason the return address when calling int 0
add word [bp+2], 2      ;directly is the address after the instruction while
.DontAdd:               ;causing a divide error exception through divsion will
pop ds                  ;put the return address at the division leading to an
                        ;infinite loop
push word [bp+4]
push word String1
call ToHex
add sp, 4

push word [bp+2]
push word String2
call ToHex
add sp, 4

push word ColorAttributes1
push word String1
call PrintStr

add sp, 4

pop bx
mov sp, bp
pop bp
iret

String1: db "0000:";, 0x00
String2: db "0000 ", 0x00
String3: db "a divide by zero error happened ", 0x00
ColorAttributes1: db 0x0F ; first nibble is backround color
                         ;second nibble is foreground

times 2048-2- ($-$$) db 0  ;fills the rest with 0's until 510 bytes
dw 0xAA55               ;magic boot sector number


来源: stackexchange

问:
How can i use GNU Bash to find files of specific type without relaying on the file extension?
i have many pdf files without name extension dispersed in subdirectories. This prevents my bibliography software from organizing them. I want to identify these files, collect them on a new directory and, once there, add the missing .pdf extension.</p>

答:
as stated in comments - you could use core linux tools - find and file commands. Following oneliner should work:

```<code>find your_starting_path -print0 |xargs -0 file |grep 'PDF document' > potential_pdfs.txt
</code>```

Then you can verify your potential_pdfs.txt file, if all found files looks reasonable, and eventually clean up the file. Finally you may use this file as an input for cleanup script:

```<code>targetdirectory=some_path_for_pdfs
cat potential_pdfs.txt |awk -F: '{print $1}' | while read filename; do
 base=$(basename "$filename")
 cp -v "$filename" "$targetdirectory/$base.pdf"
done
</code>```

Eventually you may want to use mv to remove original files. Obiousely be careful with removing them. This script won't work for files containing : in names - for that you need to tweak it a bit.

ContentLicense: CC BY-SA 4.0

Body:
as stated in comments - you could use core linux tools - find and file commands. Following oneliner should work:

find your_starting_path -print0 |xargs -0 file |grep 'PDF document' > potential_pdfs.txt

Then you can verify your potential_pdfs.txt file, if all found files looks reasonable, and eventually clean up the file. Finally you may use this file as an input for cleanup script:

targetdirectory=some_path_for_pdfs
cat potential_pdfs.txt |awk -F: '{print $1}' | while read filename; do
 base=$(basename "$filename")
 cp -v "$filename" "$targetdirectory/$base.pdf"
done

Eventually you may want to use mv to remove original files. Obiousely be careful with removing them. This script won't work for files containing : in names - for that you need to tweak it a bit.


问:
Yarn reporting nodes are full even though they have free space
I have installed Hadoop and I'm trying to use it as a Pseudo-Distributed system in my own machine. I have also set up Yarn as the resource manager. However, when I try to run any job, I can see that it is stuck as Accepted. Checking the status of my only node tells me that it is Unhealthy with the following message:

1/1 local-dirs usable space is below configured utilization percentage/no more usable space [ /tmp/hadoop-usr/nm-local-dir : used space above threshold of 90.0% ] ; 1/1 log-dirs usable space is below configured utilization percentage/no more usable space [ /Users/usr/Documents/hadoop-3.3.1/logs/userlogs : used space above threshold of 90.0% ]

From what I understand, the issue is that the disk associated to the specific node is over 90% filled. However, when I check my log directory, I can see that it is empty so why would its usage be above the threshold? Also, I can see that nm-local-dir has 0B of usage. I would appreciate any help with this issue.

答:
I figured out my issue. All the responses that I found mentioned that the issue was that there was not enough space in the disk associated to the DataNode. In my case, my disk is the one on my Mac. Therefore, to verify if I didn't have any space, I checked on the Storage section in the About this Mac menu. According to this, I had plenty of space in my disk. However, when I went to check on Disk utilities, it turns out that most of this free space was purgeable. My guess is that HDFS does not see this purgeable space as free space and it reports it as being occupied. I ended up restarting my Mac and this freed up some of the purgeable space enough for HDFS to finally see enough free space to run my jobs.

While this fixed my issue, I am curious as to what other solutions could be. I know I can always increase the percentage disk utilization limit but I'm wondering if I can just create a new partition and associate it to my HDFS system? I would appreciate any guidance regarding this.


问:
How to remove all whitespace of a string in Dart?
Using trim() to eliminate white space in Dart and it doesn't work.
What am I doing wrong or is there an alternative?

```<code>       String product = "COCA COLA";

       print('Product id is: ${product.trim()}');
</code>```

Console prints: Product id is: COCA COLA

答: var s = "Coca Cola"; s.replaceAll(' ','');

Body:
Using trim() to eliminate white space in Dart and it doesn't work.
What am I doing wrong or is there an alternative?

       String product = "COCA COLA";

       print('Product id is: ${product.trim()}');

Console prints: Product id is: COCA COLA


问:
Vite.js (Vue): Unwanted Page Reload Happens Only On Samsung Internet
I have a weird problem with Vite.js and it only happens on Samsung Internet when I'm on development server...

Problem: page reloads automatically 3 seconds in a loop and I don't set nor write any intervals... the page reload happens at browser level.

These are unwanted reloads and I want to get rid of them.

Any Idea why it happens?

答:
It seems Samsung Internet browser disallows insecure websockets.

A workaround is to enable HTTPS in Vite with server.https, so that it creates a secure Websocket:

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  server: {
    https: true,
  }
})
```

Verified with Vite 2.7.13 and Samsung Internet 16.0.6.23

Body:
It seems Samsung Internet browser disallows insecure websockets.

A workaround is to enable HTTPS in Vite with server.https, so that it creates a secure Websocket:

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  server: {
    https: true,
  }
})

Verified with Vite 2.7.13 and Samsung Internet 16.0.6.23


问:
CodeMirror 6 React Wrapper?
I'm starting to use CodeMirror 6 (aka. next for the time being) in a React project.

In the past, I've used React CodeMirror 2 as a wrapper. Is there anything similar available for the upcoming version of CodeMirror?

答:
There are few links I know for using Codemirror 6 in react -

https://codesandbox.io/s/react-codemirror-next-yrtcf?file=/src/useCodeMirror.tsx

https://github.com/uiwjs/react-codemirror

https://discuss.codemirror.net/t/suggestions-for-using-with-react-workflow/2746

Also a quick and small example to get started -

```<code>const Editor = () => {
  const editorRef = useRef(null);

  useEffect(() => {
    const state = EditorState.create({
      doc: "",
      extensions: [
        basicSetup,
        EditorView.updateListener.of((v) => {
          if (v.docChanged) {
            handleChange(view); // custom function that will be triggered on every editor change.
          }
        }),
        javascript(), // or any other language you want to support
      ],
    });

    const view = new EditorView({
      state,
      parent: editorRef.current!,
    });

    return () => {
      view.destroy();
    };
  }, []);

  return (
    <div id="CMEditor">
      <div ref={editorRef} />
    </div>
  );
};
</code>```

Hope this helps.

Title: CodeMirror 6 React Wrapper?

Body:
There are few links I know for using Codemirror 6 in react -

https://codesandbox.io/s/react-codemirror-next-yrtcf?file=/src/useCodeMirror.tsx

https://github.com/uiwjs/react-codemirror

https://discuss.codemirror.net/t/suggestions-for-using-with-react-workflow/2746

Also a quick and small example to get started -

const Editor = () => {
  const editorRef = useRef(null);

  useEffect(() => {
    const state = EditorState.create({
      doc: "",
      extensions: [
        basicSetup,
        EditorView.updateListener.of((v) => {
          if (v.docChanged) {
            handleChange(view); // custom function that will be triggered on every editor change.
          }
        }),
        javascript(), // or any other language you want to support
      ],
    });

    const view = new EditorView({
      state,
      parent: editorRef.current!,
    });

    return () => {
      view.destroy();
    };
  }, []);

  return (
    <div id="CMEditor">
      <div ref={editorRef} />
    </div>
  );
};

Hope this helps.


问:
Filter logcat by selected application *and* add custom filter in Android Studio
I hate "your app is chatty" - messages, so i wrote a custom filter for them:

This works as expected, but i'd like to enhance it:

Currently, the filter shows logs of all of my appstarts.
I'd like it to only show logs of my current appstart (which is the same as the default filter "show only selected application" does)

I suspect this is possible by filtering the PID, but i don't know how.
(Android Studio hints, that there is code-completion enabled in the PID field)

答:
Locat entries that originate from an app without debug information, only have ? as package name. Since all system apps don't contain any debug information (AFAIK), messages from the system and most apps can be filtered by typing the following regex into the Package Name field:

```<code>^(?!(\?))
</code>```

This might not be perfect, since you might have other apps with debug information, which could still pollute your log, but for me it's enough.

Body:
Locat entries that originate from an app without debug information, only have ? as package name. Since all system apps don't contain any debug information (AFAIK), messages from the system and most apps can be filtered by typing the following regex into the Package Name field:

^(?!(\?))

This might not be perfect, since you might have other apps with debug information, which could still pollute your log, but for me it's enough.


问:
Remove multiple spaces and new lines inside of String
Suppose we have string like this:

```<code>Hello, my\n       name is Michael.
</code>```

How can I remove that new line and strip those spaces after that into one inside of string to get this?

```<code>Hello, my name is Michael.
</code>```

答:
To illustrate Rubys built in squeeze:

```<code>string.gsub("\n", ' ').squeeze(' ')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.

Body:
To illustrate Rubys built in squeeze:

string.gsub("\n", ' ').squeeze(' ')


问:
Django validate_unique error while updating from admin
I have created a validate_unique based on two fields (asset and portfolio), it works well when I try to create a new object that already exists, i get the correct message.

But i get the same error message if i try to update an existing object. Should i change something to make the update work?

```<code>class PortfolioAsset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    shares_amount = models.FloatField()
    share_average_price_brl = models.FloatField()
    total_cost_brl = models.FloatField(editable=False)
    total_today_brl = models.FloatField(editable=False)

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.filter(
                 portfolio=self.portfolio,
                 asset=self.asset
        ).exists():
            raise ValidationError(
                message='This asset already exists in this portfolio.',
                code='unique_together',
            )
    def save(self, *args, **kwargs):
        self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2)
        self.total_today_brl = round(self.shares_amount * self.asset.price, 2)
        super(PortfolioAsset, self).save(*args, **kwargs)
</code>```

答:
you could exclude the id of the current instance in the case of update:</p>
```<code> if self.__class__.objects.\
                filter(portfolio=self.portfolio, asset=self.asset).\
                exclude(id=self.id).\
                exists():
</code>```

Body:
I have created a validate_unique based on two fields (asset and portfolio), it works well when I try to create a new object that already exists, i get the correct message.

But i get the same error message if i try to update an existing object. Should i change something to make the update work?

class PortfolioAsset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    shares_amount = models.FloatField()
    share_average_price_brl = models.FloatField()
    total_cost_brl = models.FloatField(editable=False)
    total_today_brl = models.FloatField(editable=False)

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.filter(
                 portfolio=self.portfolio,
                 asset=self.asset
        ).exists():
            raise ValidationError(
                message='This asset already exists in this portfolio.',
                code='unique_together',
            )
    def save(self, *args, **kwargs):
        self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2)
        self.total_today_brl = round(self.shares_amount * self.asset.price, 2)
        super(PortfolioAsset, self).save(*args, **kwargs)

Body:
you could exclude the id of the current instance in the case of update:

 if self.__class__.objects.\
                filter(portfolio=self.portfolio, asset=self.asset).\
                exclude(id=self.id).\
                exists():


问:
NOT GROUP By issue
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

```<code>SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0
</code>```

答:
group by is required of any field named in either sum or having. In this case you have both, so you need something like this;

```<code>SELECT ROUND(SUM(FACT_WLT_AGENT.WLT_LHV_PO_FNGF + FACT_WLT_AGENT.WLT_LHV_PO_ENA + FACT_WLT_AGENT.WLT_LHV_PO_EEIND + FACT_WLT_AGENT.WLT_LHV_PO_PAQ)/ 3600 * 10 )

FROM FACT_WLT_AGENT, dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
AND is_last_master_reorg = 'Y'
group by FACT_WLT_AGENT.WLT_LHV_PO_FNGF, FACT_WLT_AGENT.WLT_LHV_PO_ENA, FACT_WLT_AGENT.WLT_LHV_PO_EEIND, FACT_WLT_AGENT.WLT_LHV_PO_PAQ
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF + FACT_WLT_AGENT.WLT_LHV_PO_ENA + FACT_WLT_AGENT.WLT_LHV_PO_EEIND + FACT_WLT_AGENT.WLT_LHV_PO_PAQ / 3600 > 0
</code>```

Title: NOT GROUP By issue

Body:
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0

Body:
group by is required of any field named in either sum or having. In this case you have both, so you need something like this;

SELECT ROUND(SUM(FACT_WLT_AGENT.WLT_LHV_PO_FNGF + FACT_WLT_AGENT.WLT_LHV_PO_ENA + FACT_WLT_AGENT.WLT_LHV_PO_EEIND + FACT_WLT_AGENT.WLT_LHV_PO_PAQ)/ 3600 * 10 )

FROM FACT_WLT_AGENT, dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
AND is_last_master_reorg = 'Y'
group by FACT_WLT_AGENT.WLT_LHV_PO_FNGF, FACT_WLT_AGENT.WLT_LHV_PO_ENA, FACT_WLT_AGENT.WLT_LHV_PO_EEIND, FACT_WLT_AGENT.WLT_LHV_PO_PAQ
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF + FACT_WLT_AGENT.WLT_LHV_PO_ENA + FACT_WLT_AGENT.WLT_LHV_PO_EEIND + FACT_WLT_AGENT.WLT_LHV_PO_PAQ / 3600 > 0


问:
Not able to install the latest termcolor version
I am trying to install termcolor version 1.1.0, so that i can further install Tensorflow, as there's a dependency, but unable to install the latest termcolor.

```<code>ERROR: Could not find a version that satisfies the requirement termcolor==1.1.0
ERROR: No matching distribution found for termcolor==1.1.0
</code>```

Currently, my termcolor version is 0.2

I tried several ways like --upgrade, but no luck..

Please help.

答:
You can install termcolor using below code, it will install the latest version of termcolor which is 1.1.0.:

```<code>!pip install termcolor
</code>```

However, If you install TensorFlow using pip, it will automatically install some required package along with TensorFlow which also includes termcolor module.

```<code>!pip install tensorflow
</code>```

Body:
I am trying to install termcolor version 1.1.0, so that i can further install Tensorflow, as there's a dependency, but unable to install the latest termcolor.

ERROR: Could not find a version that satisfies the requirement termcolor==1.1.0
ERROR: No matching distribution found for termcolor==1.1.0

Currently, my termcolor version is 0.2

I tried several ways like --upgrade, but no luck..

Please help.

Body:
You can install termcolor using below code, it will install the latest version of termcolor which is 1.1.0.:

!pip install termcolor

However, If you install TensorFlow using pip, it will automatically install some required package along with TensorFlow which also includes termcolor module.

!pip install tensorflow


问:
Pandas Drop Rows when a String is Matched to a Longer String in a Column in an Exact Match
I'm trying to drop rows in a pandas DataFrame if a substring in a column exactly matches a string in a list. At the moment I can only get it working for partial matches.

```<code># list of strings to drop in an exact match
drop_list = ["sock", "shirt"]

# initialize data of lists.
data = {'keyword': ['adidas socks', 'adidas sock', 'adidas shoes', "sock"]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['keyword'].str.contains("|".join(drop_list))]
</code>```

Current Output:

```<code>        keyword
2  adidas shoes
</code>```

Desired Output:

```<code>        keyword
0  adidas socks
1  adidas shoes
</code>```

答:
Your code seems to be working.
The only thing I noticed is that the index is not "updated"

To achieve that we could reset the index:

```<code>df = df.reset_index(drop=True)
#or
df.reset_index(drop=True, inplace=True)
</code>```

I used the sample code you provided but my output looks different than yours but so does the input.

Honestly, I don't understand why that last empty string of data is not showing up on your output.

Input:

```<code>        keyword
0   adidas sock
1  adidas socks
2  adidas shoes
3          sock
4
</code>```

Output:

```<code>        keyword
0  adidas shoes
1
</code>```

Body:
I'm trying to drop rows in a pandas DataFrame if a substring in a column exactly matches a string in a list. At the moment I can only get it working for partial matches.

# list of strings to drop in an exact match
drop_list = ["sock", "shirt"]

# initialize data of lists.
data = {'keyword': ['adidas socks', 'adidas sock', 'adidas shoes', "sock"]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['keyword'].str.contains("|".join(drop_list))]

Current Output:

        keyword
2  adidas shoes

Desired Output:

        keyword
0  adidas socks
1  adidas shoes

Body:
Your code seems to be working.
The only thing I noticed is that the index is not "updated"

To achieve that we could reset the index:

df = df.reset_index(drop=True)
#or
df.reset_index(drop=True, inplace=True)

I used the sample code you provided but my output looks different than yours but so does the input.

Honestly, I don't understand why that last empty string of data is not showing up on your output.

Input:

        keyword
0   adidas sock
1  adidas socks
2  adidas shoes
3          sock
4

Output:

        keyword
0  adidas shoes
1


问:
Honeycomb activity spontaneously restarts itself
I've got a really odd problem which comes out when testing my app on the Honeycomb emulator. When the "tablet" is rotated to portrait, my main Activity seems to just get stuck, and restarts itself over and over again. The stack trace below seems to give no indication of what is going on, and I haven't been able to pinpoint the restart when debugging either. The same thing doesn't occur on a Gingerbread phone, which uses the same portrait layout.

I do not own a Honeycomb device (yet) so I cannot see whether this is a quirk of the emulator or not.

```<code>08-02 21:28:02.137: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:02.193: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21010
08-02 21:28:04.136: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:04.209: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21015
08-02 21:28:04.230: WARN/ActivityManager(81): Launch timeout has expired, giving up wake lock!
08-02 21:28:06.127: DEBUG/dalvikvm(419): GC_CONCURRENT freed 105K, 3% free 7353K/7559K, paused 13ms+161ms
08-02 21:28:06.178: WARN/ActivityManager(81): Activity idle timeout for ActivityRecord{40841ae0 com.espian.formulae.pro/.Host}
08-02 21:28:06.517: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:06.567: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21020
08-02 21:28:08.447: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
</code>```

Thanks in advance for your help

答:
Have you tried adding

```<code>android:configChanges="keyboardHidden|orientation"
</code>```

in manifest under the Actvity tag,  and overriding

```<code>@Override
        public void onConfigurationChanged(Configuration newConfig) {
            // TODO Auto-generated method stub
            super.onConfigurationChanged(newConfig);
        }
</code>```

the above method in the same Activity...

Body:
I've got a really odd problem which comes out when testing my app on the Honeycomb emulator. When the "tablet" is rotated to portrait, my main Activity seems to just get stuck, and restarts itself over and over again. The stack trace below seems to give no indication of what is going on, and I haven't been able to pinpoint the restart when debugging either. The same thing doesn't occur on a Gingerbread phone, which uses the same portrait layout.

I do not own a Honeycomb device (yet) so I cannot see whether this is a quirk of the emulator or not.

08-02 21:28:02.137: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:02.193: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21010
08-02 21:28:04.136: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:04.209: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21015
08-02 21:28:04.230: WARN/ActivityManager(81): Launch timeout has expired, giving up wake lock!
08-02 21:28:06.127: DEBUG/dalvikvm(419): GC_CONCURRENT freed 105K, 3% free 7353K/7559K, paused 13ms+161ms
08-02 21:28:06.178: WARN/ActivityManager(81): Activity idle timeout for ActivityRecord{40841ae0 com.espian.formulae.pro/.Host}
08-02 21:28:06.517: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:06.567: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21020
08-02 21:28:08.447: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419

Thanks in advance for your help

Body:
Have you tried adding

android:configChanges="keyboardHidden|orientation"

in manifest under the Actvity tag,  and overriding

@Override
        public void onConfigurationChanged(Configuration newConfig) {
            // TODO Auto-generated method stub
            super.onConfigurationChanged(newConfig);
        }

the above method in the same Activity...


问:
How to get old input array in blade laravel
I have some code like this

```<code><div class="form-group">
    <label for="tag">Tag</label><br>
    <input type="text" data-role="tagsinput"
           class="form-control form-control-lg @error('tag') is-invalid @enderror"
           id="tag" name="tag[]" value="{{old('tag')}}" placeholder="Enter tag">
    @error('tag') <div class="text-danger"> {{ $message }} </div> @enderror
</div>
</code>```

how to get old value array in laravel blade, in this case i want to get old value of tag?

答:
```<code><select name="groups[]" class="multi-default" id="groups" placeholder="Groups" multiple>
    <option value="" placeholder>Groups</option>
        @foreach ($groups as $group)
            <option value="{{ $group->id }}" title="{{ $group->id }}"
                {{is_array(old('groups',$groups??[]))&&in_array($group->id,old('groups',$group_data??[]))?'selected':null}}</option>
        @endforeach
</select>
</code>```

Body:
I have some code like this

    Tag

    <input type="text" data-role="tagsinput"
           class="form-control form-control-lg @error('tag') is-invalid @enderror"
           id="tag" name="tag[]" value="{{old('tag')}}" placeholder="Enter tag">
    @error('tag')
 {{ $message }}
 @enderror

how to get old value array in laravel blade, in this case i want to get old value of tag?


问:
I m not getting Dms console.log on discord.js npmjs plugin
The console.log() in the "messageCreate" event is not firing when sending a DM.

```<code>
const Client = new Discord.Client({
    intents: [
        "GUILDS",
        "GUILD_MESSAGES",
        "DIRECT_MESSAGES"
    ]
})

Client.on('messageCreate', (msg) => {
   msgArray = msg.content.toLowerCase().split(' ')

   if (msgArray[0] == "/botmsg"){
    Client.users.fetch(msgArray[1], false).then((user) => {
        user.send(msgArray[2]);
       });
   } else {
    console.log(msg.content);
   }
})

Client.login('token hidden')
</code>```

My goal is to log the message when a DM is received, how can I do this?

答:
With discord.js v13 you need to enable the partial CHANNEL, so your Client must be

const Client = new Discord.Client({
    intents: [
        "GUILDS",
        "GUILD_MESSAGES",
        "DIRECT_MESSAGES"
    ],
    partials: [
        "CHANNEL"
    ]
})
```

Body:
The console.log() in the "messageCreate" event is not firing when sending a DM.

const Client = new Discord.Client({
    intents: [
        "GUILDS",
        "GUILD_MESSAGES",
        "DIRECT_MESSAGES"
    ]
})

Client.on('messageCreate', (msg) => {
   msgArray = msg.content.toLowerCase().split(' ')

   if (msgArray[0] == "/botmsg"){
    Client.users.fetch(msgArray[1], false).then((user) => {
        user.send(msgArray[2]);
       });
   } else {
    console.log(msg.content);
   }
})

Client.login('token hidden')

My goal is to log the message when a DM is received, how can I do this?


问:
Get document data from Firebase Firestore in Node JS
after not finding anything online, I decided to write here. I need to get all the document in the /user/uid collection in Node JS. When I use the Firebase code it replies like this:

```<code>Promise {<pending>}
</code>```

Please help me!

PS: I don't want to use Firebase Admin SDK and await.

"Full" code

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

const { initializeApp } = require("firebase/app");
const { getDatabase, ref, get, child, set, onValue} = require("firebase/database");
const { getFirestore, collection, getDoc, doc} = require("firebase/firestore");

const firebaseApp = initializeApp(firebaseConfig);

// Get a reference to the database service

var app = express();

const PORT = process.env.PORT || 5050

app.get('/', (req, res) => {
    res.send('This is my demo project')
});

const db = getDatabase();
const firestore = getFirestore();

const document = getDoc(doc(collection(firestore, 'users'), "BW5kylV6rtZXtYibpKGc2m1asRm1"));

console.log(document);

//Response: "Promise {<pending>}""
</code>```

答:
Firebase method calls are asynchronous. So for both the Admin SDK or the JS SDK you have to deal with the asynchronicity, either by using then or by using async/await.

If you receive Promise {<pending>} it is because the asynchronous method getDoc returns a Promise and this promise is not fulfilled, but is still pending.

So you need to dive into the documentation on how to use Promises... or the async/await keywords.

In your case, the following will do the trick:

```<code>getDoc(doc(collection(firestore, 'users'), "BW5kylV6rtZXtYibpKGc2m1asRm1"))
.then(snap => {
   console.log(snap.data())
})
</code>```

However, if you write this code for running on a Node server you own, I would recommend to use the Admin SDK.

Body:
after not finding anything online, I decided to write here. I need to get all the document in the /user/uid collection in Node JS. When I use the Firebase code it replies like this:

Promise {<pending>}

Please help me!

PS: I don't want to use Firebase Admin SDK and await.

"Full" code

var express = require('express');

const { initializeApp } = require("firebase/app");
const { getDatabase, ref, get, child, set, onValue} = require("firebase/database");
const { getFirestore, collection, getDoc, doc} = require("firebase/firestore");

const firebaseApp = initializeApp(firebaseConfig);

// Get a reference to the database service

var app = express();

const PORT = process.env.PORT || 5050

app.get('/', (req, res) => {
    res.send('This is my demo project')
});

const db = getDatabase();
const firestore = getFirestore();

const document = getDoc(doc(collection(firestore, 'users'), "BW5kylV6rtZXtYibpKGc2m1asRm1"));

console.log(document);

//Response: "Promise {<pending>}""

Body:
Firebase method calls are asynchronous. So for both the Admin SDK or the JS SDK you have to deal with the asynchronicity, either by using then or by using async/await.

If you receive Promise {<pending>} it is because the asynchronous method getDoc returns a Promise and this promise is not fulfilled, but is still pending.

So you need to dive into the documentation on how to use Promises... or the async/await keywords.

In your case, the following will do the trick:

getDoc(doc(collection(firestore, 'users'), "BW5kylV6rtZXtYibpKGc2m1asRm1"))
.then(snap => {
   console.log(snap.data())
})

However, if you write this code for running on a Node server you own, I would recommend to use the Admin SDK.


问:
Brownie compile ValueError: Invalid NPM block with OpenZeppelin
*****top lines of my .sol file
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract ParcelAsset is ERC721 {

******command line VScode
brownie compile contracts\ParcelAsset.sol

I get this error.
ValueError: Invalid NPM block in '>=0.6.0 <0.8.0 import "@openzeppelin/contracts/token/ERC721/ERC721.sol"': 'import'

*********** snippet of my brownie-config.yaml
dependencies:

smartcontractkit/chainlink-brownie-contracts@1.1.1

OpenZeppelin/openzeppelin-contracts@3.4.0
compiler:
solc:
remappings:

'@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'

'@openzeppelin=OpenZeppelin/openzeppelin-contracts@3.4.0'

I have tried
npm install @openzeppelin/contracts
and upadating solidity to 0.8.0

Anyone known what I am doing wrong?

答:
I solved it by doing: npm install @chainlink/contracts --save

and in the yaml file doing:

I personally didn't bother importing openzeppelin because all safemath functionalities (if that is what you are importing) are already implemented into solidity 0.8.0, so if you're using solidity 0.8.0, the safemath library is obsolete


问:
Should I dispose a Mutex?
I'm working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex.

Now I'm wondering whether it's ok to just call WaitOne() and ReleaseMutex() in a try-finally block or should I also dispose the Mutex (e.g. in a using block). If so I guess I should always catch the AbandonedMutexException on the WaitOne() method or am I wrong here?

答:
You need to dispose the resources which are used by the waithandle.

From the documentation:

Releases all resources used by the current instance of the WaitHandle
  class. (Inherited from WaitHandle.)

The waithandle uses unmanaged resources which should be disposed at the end of use.

MSDN Documentation Mutex

Title: Should I dispose a Mutex?


问:
executing file_server giving error after install, when deno is already installed and executes without any error
I installed deno and have been practicing successfully while going through the manual.

But as soon as I did the steps as outlined in the examples of File Server, after I have installed and executed ...

$ file_server .
~/.deno/bin/file_server: 3: exec: deno: not found
```
<p>I have <code>file_server</code> in the bin of <code>deno</code>...</p>
<pre class="lang-sh prettyprint-override"><code>$ ls -al ~/.deno/bin/
total 86668
drwxr-xr-x 2 ***** *****     4096 Feb 10 23:53 .
drwxr-xr-x 3 ***** *****     4096 Feb  9 15:34 ..
-rwxr-xr-x 1 ***** ***** 88735456 Feb  4 05:48 deno
-rwxr-xr-x 1 ***** *****      134 Feb 10 23:53 file_server
</code>```

My .bashrc has...

export DENO_INSTALL="~/.deno"
export PATH="$DENO_INSTALL/bin:$PATH"
. "$HOME/.cargo/env"

```
<p><code>deno</code> executes fine...</p>
```$ deno
Deno 1.18.2
exit using ctrl+d or close()
> 1+ 2
3
>
```
<p><code>file_server</code> content...</p>
```#!/bin/sh
# generated by deno install
exec deno run --allow-read --allow-net 'https://deno.land/std@0.125.0/http/file_server.ts' "$@"
```
<p><code>uname -a</code>...</p>
```$ uname -a
Linux ranjan-t410 4.19.0-17-amd64 #1 SMP Debian 4.19.194-3 (2021-07-18) x86_64 GNU/Linux
```
<p>Results of <code>which</code> command...</p>
<pre class="lang-sh prettyprint-override"><code>:~$ which deno
:~$ which file_server
:~$
</code>```

deno version...

$ deno --version
deno 1.18.2 (release, x86_64-unknown-linux-gnu)
v8 9.8.177.6
typescript 4.5.2
```

All other examples I have been able to deno run until this one.

What is it that I haven't done properly, or have I missed anything?

Few Observations on my computer

which command return(s) empty for both deno and file_server

$ ls -al /usr/bin/sh

lrwxrwxrwx 1 root root 4 Sep 16  2020 /usr/bin/sh -> dash

If I change the shebang in file_server file from #!/bin/sh to #!/bin/bash, then it works...

答:
Without having more information, I think problem is that the sh in your $PATH points to dash, rather than bash, so your ~/.bashrc isn't being sourced by dash. If you source your ~/.bashrc in ~/.profile (or just modify the environment variables there directly), I think it should work as expected.

Ref: What is the dash equivalent for .bashrc?

Body:
I installed deno and have been practicing successfully while going through the manual.

But as soon as I did the steps as outlined in the examples of File Server, after I have installed and executed ...

$ file_server .
~/.deno/bin/file_server: 3: exec: deno: not found

I have file_server in the bin of deno...

$ ls -al ~/.deno/bin/
total 86668
drwxr-xr-x 2 ***** *****     4096 Feb 10 23:53 .
drwxr-xr-x 3 ***** *****     4096 Feb  9 15:34 ..
-rwxr-xr-x 1 ***** ***** 88735456 Feb  4 05:48 deno
-rwxr-xr-x 1 ***** *****      134 Feb 10 23:53 file_server

My .bashrc has...

export DENO_INSTALL="~/.deno"
export PATH="$DENO_INSTALL/bin:$PATH"
. "$HOME/.cargo/env"

deno executes fine...

$ deno
Deno 1.18.2
exit using ctrl+d or close()
> 1+ 2
3
>

file_server content...

#!/bin/sh
# generated by deno install
exec deno run --allow-read --allow-net 'https://deno.land/std@0.125.0/http/file_server.ts' "$@"

uname -a...

$ uname -a
Linux ranjan-t410 4.19.0-17-amd64 #1 SMP Debian 4.19.194-3 (2021-07-18) x86_64 GNU/Linux

Results of which command...

:~$ which deno
:~$ which file_server
:~$

deno version...

$ deno --version
deno 1.18.2 (release, x86_64-unknown-linux-gnu)
v8 9.8.177.6
typescript 4.5.2

All other examples I have been able to deno run until this one.

What is it that I haven't done properly, or have I missed anything?

Few Observations on my computer

which command return(s) empty for both deno and file_server

$ ls -al /usr/bin/sh

lrwxrwxrwx 1 root root 4 Sep 16  2020 /usr/bin/sh -> dash

If I change the shebang in file_server file from #!/bin/sh to #!/bin/bash, then it works...


问:
"No numeric types to aggregate" while using Pandas expanding()
In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby.

Example dataset:

```<code>tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']})

print(tmp)

col1    col2
a       red
b       red
b       green
c       green
d       red
d       blue
</code>```

This works:

```<code>tmp.groupby('col1').agg(lambda x: ','.join(x))
</code>```

And this works:

```<code>tmp.groupby('col1').expanding().agg('count')
</code>```

But this returns an error:

```<code>tmp.groupby('col1').expanding().agg(lambda x: ','.join(x))
</code>```

DataError: No numeric types to aggregate

There is no conceptual reason this shouldn't work, and there are several references online to people using custom functions within an ExpandingGroupby.

There is obviously no reason that this should need to be a numeric, especially given that the count works with the non-numeric column.  What is happening here?  If this can't be done natively for whatever reason, how can I do it manually?

答:
You can use accumulate from itertools module:

```<code>from itertools import accumulate

concat = lambda *args: ','.join(args)
expand = lambda x: list(accumulate(x, func=concat))

df['col3'] = df.groupby('col1')['col2'].transform(expand)
print(df)

# Output
  col1   col2       col3
0    a    red        red
1    b    red        red
2    b  green  red,green
3    c  green      green
4    d    red        red
5    d   blue   red,blue
</code>```

Update

One line version:

```<code>df['col3'] = df.groupby('col1')['col2'].transform(lambda x: list(accumulate(x, func=lambda *args: ','.join(args))))
</code>```

Body:
In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby.

Example dataset:

tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']})

print(tmp)

col1    col2
a       red
b       red
b       green
c       green
d       red
d       blue

This works:

tmp.groupby('col1').agg(lambda x: ','.join(x))

And this works:

tmp.groupby('col1').expanding().agg('count')

But this returns an error:

tmp.groupby('col1').expanding().agg(lambda x: ','.join(x))

DataError: No numeric types to aggregate

There is no conceptual reason this shouldn't work, and there are several references online to people using custom functions within an ExpandingGroupby.

There is obviously no reason that this should need to be a numeric, especially given that the count works with the non-numeric column.  What is happening here?  If this can't be done natively for whatever reason, how can I do it manually?

Body:
You can use accumulate from itertools module:

from itertools import accumulate

concat = lambda *args: ','.join(args)
expand = lambda x: list(accumulate(x, func=concat))

df['col3'] = df.groupby('col1')['col2'].transform(expand)
print(df)

# Output
  col1   col2       col3
0    a    red        red
1    b    red        red
2    b  green  red,green
3    c  green      green
4    d    red        red
5    d   blue   red,blue

Update

One line version:

df['col3'] = df.groupby('col1')['col2'].transform(lambda x: list(accumulate(x, func=lambda *args: ','.join(args))))


问:
Android Studio/Emulator on macOS with ARM CPU M1
I started Android Studio 4.1 in macOS Big Sure 11.0.1 with new ARM cpu M1

After installing Rosetta: Yes, it builds !

But the Emulator has problems, it shows me CPU does not support VT-x

Even ARM images have this issue

I used the most recent, a very old api25 (Google has to do here something) but it's increadible slow

How to make the Emulator work and fast ?

答:
For me none of the solutions worked.
Tried Arctic fox, bumblebee and etc.
The only thing that worked was the Dolphin canary version.
As you install this version, it gives you a default emulator but it's also possible to create a new one without any issue.
Of course, there could be issues (because its canary ver.) but I'm happy that I can run something at this point.</p>


问:
Java Math issue incorrect output
(51^43)Mod77 in scientific calculator gives 2 as the output however,

(int)(Math.pow(51,43)%(double)77) gives 12 which should be 2 instead.

Can you please help ?

答:
```<code>    final BigInteger base = BigInteger.valueOf(51);
    final BigInteger exponent = BigInteger.valueOf(43);
    final BigInteger modulus = BigInteger.valueOf(77);
    System.out.println(base.modPow(exponent, modulus));
</code>```

prints 2.

Title: Java Math issue incorrect output

Body:
    final BigInteger base = BigInteger.valueOf(51);
    final BigInteger exponent = BigInteger.valueOf(43);
    final BigInteger modulus = BigInteger.valueOf(77);
    System.out.println(base.modPow(exponent, modulus));

prints 2.


问:
Split data frame string column into multiple columns (comma separated characters)
I am trying to split a column of comma separated characters into several columns (as many as different characters overall).
I read similar questions such as this:

Split data frame string column into multiple columns

But the solutions were based on a small number of possible characters, so that the new columns could be named in advanced before the columns was split.

This is my example:

```<code>subject <- c(1,2,3)
 letters <- c("a, b, f, g", "b, g, m, l", "g, m, z")

df1 <- data.frame(subject, letters)

df1

 subject    letters
1       1 a, b, f, g
2       2 b, g, m, l
3       3    g, m, z
</code>```

The desired result would be:

```<code>  subject a b f g m z
1       1 1 1 1 1 0 0
2       2 0 1 0 1 1 0
3       3 0 0 0 1 1 1
</code>```

Thanks in advance for any help.

答:
A base R approach that grepls the unique list of letters against each row of trimws and strsplited letters. Has the advantage of being able to easily interact with each step manually in case any adjustment needs to be done, e.g. order changes or leaving out letters etc.

```<code>list_letter <- sapply(strsplit(df1$letters, ","), trimws)
letter <- unique(unlist(list_letter))
letter
[1] "a" "b" "f" "g" "m" "l" "z"

data.frame( subject=df1$subject,
            sapply(letter, function(x) sapply(list_letter, function(y)
              any(grepl(x, y))))*1 )
  subject a b f g m l z
1       1 1 1 1 1 0 0 0
2       2 0 1 0 1 1 1 0
3       3 0 0 0 1 1 0 1
</code>```

Body:
I am trying to split a column of comma separated characters into several columns (as many as different characters overall).
I read similar questions such as this:

Split data frame string column into multiple columns

But the solutions were based on a small number of possible characters, so that the new columns could be named in advanced before the columns was split.

This is my example:

subject <- c(1,2,3)
 letters <- c("a, b, f, g", "b, g, m, l", "g, m, z")

df1 <- data.frame(subject, letters)

df1

 subject    letters
1       1 a, b, f, g
2       2 b, g, m, l
3       3    g, m, z

The desired result would be:

  subject a b f g m z
1       1 1 1 1 1 0 0
2       2 0 1 0 1 1 0
3       3 0 0 0 1 1 1

Thanks in advance for any help.

Body:
A base R approach that grepls the unique list of letters against each row of trimws and strsplited letters. Has the advantage of being able to easily interact with each step manually in case any adjustment needs to be done, e.g. order changes or leaving out letters etc.

list_letter <- sapply(strsplit(df1$letters, ","), trimws)
letter <- unique(unlist(list_letter))
letter
[1] "a" "b" "f" "g" "m" "l" "z"

data.frame( subject=df1$subject,
            sapply(letter, function(x) sapply(list_letter, function(y)
              any(grepl(x, y))))*1 )
  subject a b f g m l z
1       1 1 1 1 1 0 0 0
2       2 0 1 0 1 1 1 0
3       3 0 0 0 1 1 0 1


问:
Make manual servervalidation and color textfield if failed
I am trying to change the color of a textfield to red if a serverside validation fails.

If result is True or False nothing happens

JQuery

```<code>        $('.datein').change(function () {
        //send servervalidering ajax
        var data = { dateOut: $('#resource_dateout').val(), dateHourOut: $('#resource_hourout').val(), dateMinuteOut: $('#resource_minuteout').val(),
            dateIn: $('#resource_datein').val(), dateHourIn: $('#resource_hourin').val(), dateMinuteIn: $('#resource_minutein').val()
        };
        $.post("Resource/isDateValid", data, ajaxsuccess);
    });

function ajaxsuccess(result) {
    if ($('.datein').hasClass('.resourceerror')) {
        if (result == "True") {
            $('.datein').removeClass('.resourceerror');
        }
    }
    else if (result == "False") {
        $('.datein').addClass('.resourceerror');
    }
}
</code>```

Html

```<code>                <span class="editor-field">
                    @Html.TextBoxFor(m => m.DateIn.Date, new { @Id = "resource_datein", @class = "datepicker datein", maxlength = "10" })
                    @Html.TextBoxFor(m => m.DateIn.Hour, new { @Id = "resource_hourin", @class = "datein", maxlength = "2" })
                    :
                    @Html.TextBoxFor(m => m.DateIn.Minute, new { @Id = "resource_minutein", @class = "datein", maxlength = "2" })
                </span>
                <span>
                    @Html.ValidationMessageFor(m => m.DateIn.Date)
                    @Html.ValidationMessageFor(m => m.DateIn.Hour)
                    @Html.ValidationMessageFor(m => m.DateIn.Minute)
                </span>
</code>```

Is there a way I can just toggle a validation instead? My code dont work, I am 100% sure the Ajax call either returns "True" or "False"

Edit: When accessing the css classes I wrote hasClass('.classname') instead of hasClass('classname')

答: When accessing the css classes I wrote hasClass('.classname') instead of hasClass('classname')</p>

Body:
I am trying to change the color of a textfield to red if a serverside validation fails.

If result is True or False nothing happens

JQuery

        $('.datein').change(function () {
        //send servervalidering ajax
        var data = { dateOut: $('#resource_dateout').val(), dateHourOut: $('#resource_hourout').val(), dateMinuteOut: $('#resource_minuteout').val(),
            dateIn: $('#resource_datein').val(), dateHourIn: $('#resource_hourin').val(), dateMinuteIn: $('#resource_minutein').val()
        };
        $.post("Resource/isDateValid", data, ajaxsuccess);
    });

function ajaxsuccess(result) {
    if ($('.datein').hasClass('.resourceerror')) {
        if (result == "True") {
            $('.datein').removeClass('.resourceerror');
        }
    }
    else if (result == "False") {
        $('.datein').addClass('.resourceerror');
    }
}

Html

                    @Html.TextBoxFor(m => m.DateIn.Date, new { @Id = "resource_datein", @class = "datepicker datein", maxlength = "10" })
                    @Html.TextBoxFor(m => m.DateIn.Hour, new { @Id = "resource_hourin", @class = "datein", maxlength = "2" })
                    :
                    @Html.TextBoxFor(m => m.DateIn.Minute, new { @Id = "resource_minutein", @class = "datein", maxlength = "2" })

                    @Html.ValidationMessageFor(m => m.DateIn.Date)
                    @Html.ValidationMessageFor(m => m.DateIn.Hour)
                    @Html.ValidationMessageFor(m => m.DateIn.Minute)

Is there a way I can just toggle a validation instead? My code dont work, I am 100% sure the Ajax call either returns "True" or "False"

Edit: When accessing the css classes I wrote hasClass('.classname') instead of hasClass('classname')


问:
Looking to assign subgroup values to of a group to a common value in R
I have a series of phone numbers that have individual names associated with them.  The phone numbers are not necessarily unique, and sometimes the name associated with them is missing. I would like to fill in the names with the following rules:

If a grouped phone number has blank entries and only a single name available, I would like to replace the blank names with the one available.

If the grouped number has entries with multiple non-blank names, then I cannot determine who belongs to that phone number and so I make no changes.

Here is the original table:

```<code>library("dplyr")
phone = c("1234","1234","1234","4567","4567","4567","4567","4567");phone
sgroup = c("","Jones","","Smith","","Smith","Williams","Jones");sgroup

DATA = data.frame(phone,sgroup);DATA
</code>```

And here is how I want it to look:

```<code>phone1 = c("1234","1234","1234","4567","4567","4567","4567","4567");phone1
sgroup1 = c("Jones","Jones","Jones","Smith","","Smith","Williams","Jones");sgroup1

DATA1 = data.frame(phone1,sgroup1)
</code>```

Note the "1234" since it originally had only 'Jones" and Blanks(NAs) assigned, so I assigned all records in that group to 'Jones. The second number (4567) had multiple names assigned, so I was unable to determine a common name so no assignment was made.

I can determine which phones have blank or non-blank name assignments, but I have been unable to determine how to assign them back to the blank records in that group.

```<code>Countdf1 <- DATA %>% count(phone,sgroup)
</code>```

答:
The original data.table solution (see the bottom of the post for a more performant implementation):

```<code>library(data.table)

dt <- data.table(phone = c("1234","1234","1234","4567","4567","4567","4567","4567"),
                 sgroup = c("","Jones","","Smith","","Smith","Williams","Jones"))
dt[, ngrp := .(.(unique(sgroup[sgroup != ""]))), by = "phone"][lengths(ngrp) == 1, sgroup := unlist(ngrp)][, 1:2]
#>    phone   sgroup
#> 1:  1234    Jones
#> 2:  1234    Jones
#> 3:  1234    Jones
#> 4:  4567    Smith
#> 5:  4567
#> 6:  4567    Smith
#> 7:  4567 Williams
#> 8:  4567    Jones
</code>```

This works by adding a helper column ngrp. For each unique phone value, it creates a list containing a vector of unique sgroup values. (.( is data.table shorthand for list). That list gets stored in ngrp.

```<code>dt[, ngrp := .(.(unique(sgroup[sgroup != ""]))), by = "phone"]; dt
#>    phone   sgroup                 ngrp
#> 1:  1234                         Jones
#> 2:  1234    Jones                Jones
#> 3:  1234                         Jones
#> 4:  4567    Smith Smith,Williams,Jones
#> 5:  4567          Smith,Williams,Jones
#> 6:  4567    Smith Smith,Williams,Jones
#> 7:  4567 Williams Smith,Williams,Jones
#> 8:  4567    Jones Smith,Williams,Jones
</code>```

For the subset of dt where the length of the vector in ngrp is 1, set sgroup to the corresponding value stored in ngrp (use unlist to avoid the warning message about list to character type conversion).

```<code>dt[lengths(ngrp) == 1, sgroup := unlist(ngrp)]; dt
#>    phone   sgroup                 ngrp
#> 1:  1234    Jones                Jones
#> 2:  1234    Jones                Jones
#> 3:  1234    Jones                Jones
#> 4:  4567    Smith Smith,Williams,Jones
#> 5:  4567          Smith,Williams,Jones
#> 6:  4567    Smith Smith,Williams,Jones
#> 7:  4567 Williams Smith,Williams,Jones
#> 8:  4567    Jones Smith,Williams,Jones
</code>```

Subset on the first two columns.

```<code>dt[, 1:2]
#>    phone   sgroup
#> 1:  1234    Jones
#> 2:  1234    Jones
#> 3:  1234    Jones
#> 4:  4567    Smith
#> 5:  4567
#> 6:  4567    Smith
#> 7:  4567 Williams
#> 8:  4567    Jones
</code>```

Alternatively, drop the helper column.

```<code>dt[, ngrp := NULL]; dt
#>    phone   sgroup
#> 1:  1234    Jones
#> 2:  1234    Jones
#> 3:  1234    Jones
#> 4:  4567    Smith
#> 5:  4567
#> 6:  4567    Smith
#> 7:  4567 Williams
#> 8:  4567    Jones
</code>```

A faster solution would be to do the clean-up in a function that can be called by phone group. This runs about twice as fast by avoiding the helper column.

```<code>fCleanGroup <- function(x) {
  xu <- unique(x[nchar(x) != 0L])
  if (length(xu) == 1L) xu else x
}

dt[, sgroup := fCleanGroup(sgroup), by = "phone"]

microbenchmark::microbenchmark(fun = copy(dt)[, sgroup := fCleanGroup(sgroup), by = "phone"],
                               lst = copy(dt)[, ngrp := .(.(unique(sgroup[sgroup != ""]))), by = "phone"][lengths(ngrp) == 1, sgroup := unlist(ngrp)][, 1:2],
                               copy(dt))
#> Unit: microseconds
#>      expr    min      lq     mean  median      uq    max neval
#>       fun  485.8  595.75  653.372  616.05  680.00 1164.2   100
#>       lst 1058.4 1256.75 1383.188 1302.90 1425.35 3685.1   100
#>  copy(dt)   11.9   21.10   27.425   27.65   31.00   62.6   100
</code>```

Body:
I have a series of phone numbers that have individual names associated with them.  The phone numbers are not necessarily unique, and sometimes the name associated with them is missing. I would like to fill in the names with the following rules:

If a grouped phone number has blank entries and only a single name available, I would like to replace the blank names with the one available.

If the grouped number has entries with multiple non-blank names, then I cannot determine who belongs to that phone number and so I make no changes.

Here is the original table:

library("dplyr")
phone = c("1234","1234","1234","4567","4567","4567","4567","4567");phone
sgroup = c("","Jones","","Smith","","Smith","Williams","Jones");sgroup

DATA = data.frame(phone,sgroup);DATA

And here is how I want it to look:

phone1 = c("1234","1234","1234","4567","4567","4567","4567","4567");phone1
sgroup1 = c("Jones","Jones","Jones","Smith","","Smith","Williams","Jones");sgroup1

DATA1 = data.frame(phone1,sgroup1)

Note the "1234" since it originally had only 'Jones" and Blanks(NAs) assigned, so I assigned all records in that group to 'Jones. The second number (4567) had multiple names assigned, so I was unable to determine a common name so no assignment was made.

I can determine which phones have blank or non-blank name assignments, but I have been unable to determine how to assign them back to the blank records in that group.

Countdf1 <- DATA %>% count(phone,sgroup)

Body:
The original data.table solution (see the bottom of the post for a more performant implementation):

library(data.table)

dt <- data.table(phone = c("1234","1234","1234","4567","4567","4567","4567","4567"),
                 sgroup = c("","Jones","","Smith","","Smith","Williams","Jones"))
dt[, ngrp := .(.(unique(sgroup[sgroup != ""]))), by = "phone"][lengths(ngrp) == 1, sgroup := unlist(ngrp)][, 1:2]
#>    phone   sgroup
#> 1:  1234    Jones
#> 2:  1234    Jones
#> 3:  1234    Jones
#> 4:  4567    Smith
#> 5:  4567
#> 6:  4567    Smith
#> 7:  4567 Williams
#> 8:  4567    Jones

This works by adding a helper column ngrp. For each unique phone value, it creates a list containing a vector of unique sgroup values. (.( is data.table shorthand for list). That list gets stored in ngrp.

dt[, ngrp := .(.(unique(sgroup[sgroup != ""]))), by = "phone"]; dt
#>    phone   sgroup                 ngrp
#> 1:  1234                         Jones
#> 2:  1234    Jones                Jones
#> 3:  1234                         Jones
#> 4:  4567    Smith Smith,Williams,Jones
#> 5:  4567          Smith,Williams,Jones
#> 6:  4567    Smith Smith,Williams,Jones
#> 7:  4567 Williams Smith,Williams,Jones
#> 8:  4567    Jones Smith,Williams,Jones

For the subset of dt where the length of the vector in ngrp is 1, set sgroup to the corresponding value stored in ngrp (use unlist to avoid the warning message about list to character type conversion).

dt[lengths(ngrp) == 1, sgroup := unlist(ngrp)]; dt
#>    phone   sgroup                 ngrp
#> 1:  1234    Jones                Jones
#> 2:  1234    Jones                Jones
#> 3:  1234    Jones                Jones
#> 4:  4567    Smith Smith,Williams,Jones
#> 5:  4567          Smith,Williams,Jones
#> 6:  4567    Smith Smith,Williams,Jones
#> 7:  4567 Williams Smith,Williams,Jones
#> 8:  4567    Jones Smith,Williams,Jones

Subset on the first two columns.

dt[, 1:2]
#>    phone   sgroup
#> 1:  1234    Jones
#> 2:  1234    Jones
#> 3:  1234    Jones
#> 4:  4567    Smith
#> 5:  4567
#> 6:  4567    Smith
#> 7:  4567 Williams
#> 8:  4567    Jones

Alternatively, drop the helper column.

dt[, ngrp := NULL]; dt
#>    phone   sgroup
#> 1:  1234    Jones
#> 2:  1234    Jones
#> 3:  1234    Jones
#> 4:  4567    Smith
#> 5:  4567
#> 6:  4567    Smith
#> 7:  4567 Williams
#> 8:  4567    Jones

A faster solution would be to do the clean-up in a function that can be called by phone group. This runs about twice as fast by avoiding the helper column.

fCleanGroup <- function(x) {
  xu <- unique(x[nchar(x) != 0L])
  if (length(xu) == 1L) xu else x
}

dt[, sgroup := fCleanGroup(sgroup), by = "phone"]

microbenchmark::microbenchmark(fun = copy(dt)[, sgroup := fCleanGroup(sgroup), by = "phone"],
                               lst = copy(dt)[, ngrp := .(.(unique(sgroup[sgroup != ""]))), by = "phone"][lengths(ngrp) == 1, sgroup := unlist(ngrp)][, 1:2],
                               copy(dt))
#> Unit: microseconds
#>      expr    min      lq     mean  median      uq    max neval
#>       fun  485.8  595.75  653.372  616.05  680.00 1164.2   100
#>       lst 1058.4 1256.75 1383.188 1302.90 1425.35 3685.1   100
#>  copy(dt)   11.9   21.10   27.425   27.65   31.00   62.6   100


问:
VS Code: Generate boilerplate code when creating a new component
I am wondering if there is a way to configure VS Code to generate Typescript/ React boilerplate code when creating a new component.
For example when I create a new component named myComponent.tsx I would like the file to be pre-filled with

```<code>import * as React from "react";

export interface props {}

export const MyComponent: React.FC<props> = (): JSX.Element => (
  <div>
    {"MyComponent"}
  </div>
);

</code>```

I found this extension but the generated boilerplate doesn't match what I want.

Thanks!

答:
The easiest way would be to create a custom snippet:

Press F1

Preferences: Configure User Snippets

typescriptreact.json

```<code>{
  "boilerplate": {
    "prefix": "boilerplate",
    "body": [
      "import * as React from \"react\";",
      "",
      "export interface props {}",
      "",
      "export const $TM_FILENAME_BASE: React.FC<props> = (): JSX.Element => (",
      "\t<div>",
      "\t\t{\"$TM_FILENAME_BASE\"}",
      "\t</div>",
      ");"
    ]
  }
}
</code>```

Then, in a .tsx file, typing boilerplate would suggest the code above which would write exactly the code you want.

Body:
I am wondering if there is a way to configure VS Code to generate Typescript/ React boilerplate code when creating a new component.
For example when I create a new component named myComponent.tsx I would like the file to be pre-filled with

import * as React from "react";

export interface props {}

export const MyComponent: React.FC<props> = (): JSX.Element => (

    {"MyComponent"}

);

I found this extension but the generated boilerplate doesn't match what I want.

Thanks!

Body:
The easiest way would be to create a custom snippet:

Press F1

Preferences: Configure User Snippets

typescriptreact.json

{
  "boilerplate": {
    "prefix": "boilerplate",
    "body": [
      "import * as React from \"react\";",
      "",
      "export interface props {}",
      "",
      "export const $TM_FILENAME_BASE: React.FC<props> = (): JSX.Element => (",
      "\t<div>",
      "\t\t{\"$TM_FILENAME_BASE\"}",
      "\t</div>",
      ");"
    ]
  }
}

Then, in a .tsx file, typing boilerplate would suggest the code above which would write exactly the code you want.


答:
Another tidyverse possibility:

```<code>library(tidyverse)

df1 %>%
  separate_rows(letters) %>%
  mutate(value = 1) %>%
  pivot_wider(names_from = letters, values_fill = 0)

  subject     a     b     f     g     m     l     z
    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1       1     1     1     1     1     0     0     0
2       2     0     1     0     1     1     1     0
3       3     0     0     0     1     1     0     1
</code>```

Title: Split data frame string column into multiple columns (comma separated characters)

Body:
Another tidyverse possibility:

library(tidyverse)

df1 %>%
  separate_rows(letters) %>%
  mutate(value = 1) %>%
  pivot_wider(names_from = letters, values_fill = 0)

  subject     a     b     f     g     m     l     z
    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1       1     1     1     1     1     0     0     0
2       2     0     1     0     1     1     1     0
3       3     0     0     0     1     1     0     1


问:
Blazor .Net 6.0 Hot Reload
I have an asp.net hosted blazor wasm app that I just upgraded from 5.0 to 6.0.  When trying hot reload either from VS 2022 or from dotnet watch run I get the following error in the browser console:

aspnetcore-browser-refresh.js:138

```<code>   Error: System.NullReferenceException: Object reference not set to an instance of an object.
</code>```

at Microsoft.AspNetCore.Components.WebAssembly.HotReload.WebAssemblyHotReload.ApplyHotReloadDelta(String moduleIdString, Byte[] metadataDelta, Byte[] ilDeta)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
--- End of stack trace from previous location ---
at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.InvokeSynchronously(JSRuntime jsRuntime, DotNetInvocationInfo& callInfo, IDotNetObjectReference objectReference, String argsJson)
at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.Invoke(JSRuntime jsRuntime, DotNetInvocationInfo& invocationInfo, String argsJson)
at Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime.InvokeDotNet(String assemblyName, String methodIdentifier, String dotNetObjectId, String argsJson)
at Object._convert_exception_for_method_call (https://localhost:44362/_framework/dotnet.6.0.0.qme34vl4fz.js:1:178709)
at Object._handle_exception_for_call (https://localhost:44362/_framework/dotnet.6.0.0.qme34vl4fz.js:1:180678)
at managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_InvokeDotNet (https://mono-wasm.invalid/managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_InvokeDotNet:20:21)
at Object.invokeDotNetFromJS (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:42078)
at g (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:1618)
at Object.e.invokeMethod (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:2665)
at Object.St.Te._internal.applyHotReload (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:56100)
at https://localhost:44362/_framework/aspnetcore-browser-refresh.js:136:33
at Array.forEach ()
at applyBlazorDeltas (https://localhost:44362/_framework/aspnetcore-browser-refresh.js:134:12)

答:
Check inside your *.csproj project file to see if there is any configuration related to the target platform. If so, delete it and try again. For example:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <Prefer32Bit>true</Prefer32Bit>
    <Optimize>True</Optimize>
</PropertyGroup>
```

Title: Blazor .Net 6.0 Hot Reload

Body:
I have an asp.net hosted blazor wasm app that I just upgraded from 5.0 to 6.0.  When trying hot reload either from VS 2022 or from dotnet watch run I get the following error in the browser console:

aspnetcore-browser-refresh.js:138

   Error: System.NullReferenceException: Object reference not set to an instance of an object.

at Microsoft.AspNetCore.Components.WebAssembly.HotReload.WebAssemblyHotReload.ApplyHotReloadDelta(String moduleIdString, Byte[] metadataDelta, Byte[] ilDeta)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
--- End of stack trace from previous location ---
at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.InvokeSynchronously(JSRuntime jsRuntime, DotNetInvocationInfo& callInfo, IDotNetObjectReference objectReference, String argsJson)
at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.Invoke(JSRuntime jsRuntime, DotNetInvocationInfo& invocationInfo, String argsJson)
at Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime.InvokeDotNet(String assemblyName, String methodIdentifier, String dotNetObjectId, String argsJson)
at Object._convert_exception_for_method_call (https://localhost:44362/_framework/dotnet.6.0.0.qme34vl4fz.js:1:178709)
at Object._handle_exception_for_call (https://localhost:44362/_framework/dotnet.6.0.0.qme34vl4fz.js:1:180678)
at managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_InvokeDotNet (https://mono-wasm.invalid/managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_InvokeDotNet:20:21)
at Object.invokeDotNetFromJS (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:42078)
at g (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:1618)
at Object.e.invokeMethod (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:2665)
at Object.St.Te._internal.applyHotReload (https://localhost:44362/_framework/blazor.webassembly.js?version=32330328618b4ff08635274a6f31248c:1:56100)
at https://localhost:44362/_framework/aspnetcore-browser-refresh.js:136:33
at Array.forEach ()
at applyBlazorDeltas (https://localhost:44362/_framework/aspnetcore-browser-refresh.js:134:12)


问:
Problem with simple jQuery Tabs
I have a very simple jquery tabs functions that looks like this :

```<code>$(document).ready(function() {

    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });

});
</code>```

and the HTML for it is :

```<code><div class="container">
  <ul class="tabs">
    <li><a href="#tab1">Tab 1</a></li>
    <li><a href="#tab2">Tab 2</a></li>
  </ul>
  <div class="tab_container">
    <div id="tab1" class="tab_content">
      <h2>Content</h2>
    </div>
    <div id="tab2" class="tab_content">
      <h2>Content</h2>
    </div>
    <div id="tab3" class="tab_content">
      <h2>Content</h2>
    </div>
    <div id="tab4" class="tab_content">
      <h2>Content</h2>
    </div>
  </div>
</div>
</code>```

What im trying to do here is add another tab navigation, so bacically repat the ul tag with content in it but different class so I can have something like this :

```<code><ul class="tabs">
        <li><a href="#tab1">Tab 1</a></li>
        <li><a href="#tab2">Tab 2</a></li>
</ul>
<ul class="markers">
        <li><a href="#tab1">Tab 1</a></li>
        <li><a href="#tab2">Tab 2</a></li>
</ul>
</code>```

..and whenever I click on any of the list it will affect
 in other  group.

Any help much appreciaated.

Thank you for your help in advance.

Dom

答:
try to put a class for  tag a grab that tag using the class identifier
as

```<code>var activeTab = $(this).find("a.classname").attr("href");
</code>```

it will only affect the tags whose class is matched with the one you specified

Title: Problem with simple jQuery Tabs

Body:
I have a very simple jquery tabs functions that looks like this :

$(document).ready(function() {

    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });

});

and the HTML for it is :

Tab 1

Tab 2

Content

Content

Content

Content

What im trying to do here is add another tab navigation, so bacically repat the ul tag with content in it but different class so I can have something like this :

Tab 1

Tab 2

Tab 1

Tab 2

..and whenever I click on any of the list it will affect
 in other  group.

Any help much appreciaated.

Thank you for your help in advance.

Dom

Body:
try to put a class for <a> tag a grab that tag using the class identifier
as

var activeTab = $(this).find("a.classname").attr("href");

it will only affect the tags whose class is matched with the one you specified


问:
Java code for verification of FusionAuth HS256 signed id token
How to verify HS256 ID Token using FusionAuth java Client libraries ?

Description: I have created an app in FusionAuth that has a Client ID and Client Secret generated, I have not touched any other section/tab like JWT etc, default JWT signing algo is OIDC standard HMAC SHA256.

I tried using following code approach to validate the token based on public key, but its not working for HS256 signed token, I searched over internet and found public key is not applicable for HS256

Could you please provide me a Java code to verify HS256 signed token using FusionAuth Java client libraries (https://github.com/FusionAuth/fusionauth-jwt).
Please also let me know that do I need any additional configuration on FusionAuth Admin Console.

Code which I tried: It's giving blank public keys.

```<code>List<JSONWebKey> keys = JSONWebKeySetHelper.retrieveKeysFromJWKS("http://localhost:9011/.well-known/jwks.json");

Map<String, Verifier> publicKeyVerifiers = new HashMap<String, Verifier>();

JWT jwtDecoded = JWT.getDecoder().decode(idToken, publicKeyVerifiers);
</code>```

答:
Tokens received by apps should usually be signed with an asymmetric key. You can then verify the digital signature of the token with its signing public key, which is provided via the JWKS endpoint. The most mainstream algorithm for tokens is RS256. Perhaps you need to reconfigure as suggested here?. I think your code will then work also.

HS256 is a symmetric algorithm, which feels wrong, since clients would only be able to verify JWTs if they had the full signing key. This enables a malicious client to mint their own tokens, whereas only the Authorization Server should be able to do that. For this reason, if JWTs are ever signed with symmetric keys, the JWKS endpoint will not provide the token signing keys.

Meant to say Curity have a good related doc:

JWT Best Practices

Body:
How to verify HS256 ID Token using FusionAuth java Client libraries ?

Description: I have created an app in FusionAuth that has a Client ID and Client Secret generated, I have not touched any other section/tab like JWT etc, default JWT signing algo is OIDC standard HMAC SHA256.

I tried using following code approach to validate the token based on public key, but its not working for HS256 signed token, I searched over internet and found public key is not applicable for HS256

Could you please provide me a Java code to verify HS256 signed token using FusionAuth Java client libraries (https://github.com/FusionAuth/fusionauth-jwt).
Please also let me know that do I need any additional configuration on FusionAuth Admin Console.

Code which I tried: It's giving blank public keys.

List<JSONWebKey> keys = JSONWebKeySetHelper.retrieveKeysFromJWKS("http://localhost:9011/.well-known/jwks.json");

Map<String, Verifier> publicKeyVerifiers = new HashMap<String, Verifier>();

JWT jwtDecoded = JWT.getDecoder().decode(idToken, publicKeyVerifiers);


问:
How can I instruct R to left justify the text in a character column when displaying a data.table?
How can I instruct R to left justify the text in a character column when displaying a data.table?

For example, how might I instruct R to left justify column "text" in the following output so that it matches the desired output?

library(data.table)
(data1 <- data.table(text = c("AAAAAA", "B", "C"), number = c(1, 2, 3)))
#>      text number
#> 1: AAAAAA      1
#> 2:      B      2
#> 3:      C      3
```
<p><sup>Created on 2022-02-10 by the reprex package (v2.0.1)</sup></p>
<p>Desired output:</p>
<pre class="lang-r prettyprint-override"><code>#>    text   number
#> 1: AAAAAA      1
#> 2: B           2
#> 3: C           3
</code>```

答:
You could pass justify = "left" argument to print.data.table:

```<code>print(data1,justify="left")
     text number
   <char>  <num>
1: AAAAAA      1
2: B           2
3: C           3
</code>```

Body:
How can I instruct R to left justify the text in a character column when displaying a data.table?

For example, how might I instruct R to left justify column "text" in the following output so that it matches the desired output?

library(data.table)
(data1 <- data.table(text = c("AAAAAA", "B", "C"), number = c(1, 2, 3)))
#>      text number
#> 1: AAAAAA      1
#> 2:      B      2
#> 3:      C      3

Created on 2022-02-10 by the reprex package (v2.0.1)

Desired output:

#>    text   number
#> 1: AAAAAA      1
#> 2: B           2
#> 3: C           3

Body:
You could pass justify = "left" argument to print.data.table:

print(data1,justify="left")
     text number
   <char>  <num>
1: AAAAAA      1
2: B           2
3: C           3


问:
HAXM installed successfully, but not recognized by Android Studio 2.1
Intel HAXM installs successfully (according to the log) both through Android Studio and directly from Intel's executable. However, Android Studio 2.1 says "HAXM is not installed" and prompts me to install it in an endless cycle (Not installed, install? Installed successfully. Not installed, install?).

Note: it worked fine in the previous version of Android Studio. Since upon upgrading it didn't recognize HAXM, I tried uninstalling Android Studio and reinstalling 2.1, but it still is not recognizing the HAXM installation.

How can I get Android Studio to understand that Intel HAXM is installed?

This is on Windows 10.

答:
I solved it by:
1- going to my android sdk.
2- open 'extras' file then 'intel then 'Hardware_Accelerated_Execution_Manager'.
3- Finally 'haxm-7.6.5-setup' to setup manually.
this should work will with you as happened with me.</p>


问:
Powershell - capture all non-blank lines between key words
I have a script that was put together with the community help and it works great.  I'm trying to alter it to work for my new requirements.
I have data (See below) that needs to be captured from 10K+ files.
Inside each file could be multiple iterations of the data I need to capture.  The script I'm using captured only the file name and not the data I need.  Can someone see where I'm off (Code wise) and offer another option.

Here is my Raw Data.  There could be four or five places in a text member with this data and I need to capture it all.
The words in Bold (Select and From) are the words I'm keying on.  I need to capture those lines as well as all the lines between them.

```<code>    SELECT   FIL_ID_NUM,                                             00481002
             LAU_CRE_DTS,                                            00482002
             LAU_CD,                                                 00483002
             LAU_EFF_DT,                                             00484002
             LAU_EFF_TIM,                                            00485002
             LAU_EXP_DT,                                             00486002
             LAU_EXP_TIM,                                            00487002
             LAU_SERV_REAS1_CD,                                      00488002
             LAU_SERV_REAS2_CD,                                      00489002
             LAU_SERV_REAS3_CD,                                      00489102
             LAU_CARE_IND,                                           00489202
             SEG_UPDT_LOCK_NUM,                                      00489302
             LAU_AGRMT_PER_NAM,                                      00489402
             LAU_AGRMT_DSGT_NAM,                                     00489502
             LAU_AGRMT_DIR_TXT,                                      00489602
             LAU_TERMS_TXT                                           00489702
                                                                     00520002
        FROM TLEGAL
</code>```

Here is my script....

```<code># create a List object to collect the 'flowerbox' strings in
$Flowerbox = [System.Collections.Generic.List[string]]::new()
$treat = $false

# get a list of the .pl1m files and loop through. Collect all output in variable $result
$CBLFileList = Get-ChildItem -Path 'C:\src' -Filter '*.pl1m' -File -Recurse
$result = foreach ($CBLFile in $CBLFileList) {
    Write-Host "Processing ... $($CBLFile.Name)" -ForegroundColor Green

    $Flowerbox.Clear()  # empty the list for the next run
    $treat = $false
    switch -Regex -File $CBLFile.FullName {
        'SELECT' {
        Write-Host "Found Select" -ForegroundColor DarkYellow
            # start collecting lines from here
            $treat = $true
        }
        'FROM ' {
        Write-Host "Found From" -ForegroundColor DarkRed
           if ($treat) {

            # stop colecting Flowerbox lines and output what we already have
            # output an object with the two properties you need
            [PsCustomObject]@{
                Program     = $CBLFile.Name  # or $CBLFile.FullName
                Description = $Flowerbox -join [environment]::NewLine
            }
            }
            $Flowerbox.Clear()  # empty the list for the next run
            $treat = $false
        }
        default {
                # Add captures data here
                if ($treat -and ($_ -match '/[^\s\\]/')) {
                $Flowerbox.Add($Matches[1])
            }
        }
    }
}

# now you have everything in an array of PSObjects so you can save that as Csv
$result | Export-Csv -Path 'C:\src\SQL_Desc.csv' -UseCulture -NoTypeInformation
</code>```

答:
Your script needs only a few tweaks:

Add the full line, reflected in $_, to your $Flowerbox list

Also do so in the 'SELECT' and 'FROM ' branches.

```<code># ...
$Flowerbox.Clear()  # empty the list for the next run
$treat = $false
switch -Regex -CaseSensitive -File $CBLFile.FullName {
  '^\s*SELECT\s' {
    Write-Host "Found Select" -ForegroundColor DarkYellow
    # start collecting lines from here
    $treat = $true
    $Flowerbox.Add($_) # Add this line to the list.
    continue # So that the FROM branch needn't also be checked.
  }
  '^\s*FROM\s' {
    Write-Host "Found From" -ForegroundColor DarkRed
    if ($treat) {
      $Flowerbox.Add($_)  # Add this line to the list.
      # stop collecting Flowerbox lines and output what we already have
      # output an object with the two properties you need
      [PsCustomObject]@{
        Program     = $CBLFile.Name  # or $CBLFile.FullName
        Description = $Flowerbox -join [environment]::NewLine
      }
      $Flowerbox.Clear()  # empty the list for the next run
      $treat = $false
    }
  }
  default {
    # When inside a block of interest, add all non-blank lines.
    if ($treat -and $_ -match '\S') {
      $Flowerbox.Add($_)  # Add this line to the list.
    }
  }
}
# ...
</code>```

Note that, in the interest of minimizing the risk of false positives:

-CaseSensitive was added to the switch statement for case-sensitive matching.

The regexes were made more robust to prevent accidental substring matching and to tolerate whitespace variations (spaces vs. tabs).

Also, to exclude blank (empty and all-whitespace) lines, condition -match '\S' was added to the default branch.

Body:
I have a script that was put together with the community help and it works great.  I'm trying to alter it to work for my new requirements.
I have data (See below) that needs to be captured from 10K+ files.
Inside each file could be multiple iterations of the data I need to capture.  The script I'm using captured only the file name and not the data I need.  Can someone see where I'm off (Code wise) and offer another option.

Here is my Raw Data.  There could be four or five places in a text member with this data and I need to capture it all.
The words in Bold (Select and From) are the words I'm keying on.  I need to capture those lines as well as all the lines between them.

    SELECT   FIL_ID_NUM,                                             00481002
             LAU_CRE_DTS,                                            00482002
             LAU_CD,                                                 00483002
             LAU_EFF_DT,                                             00484002
             LAU_EFF_TIM,                                            00485002
             LAU_EXP_DT,                                             00486002
             LAU_EXP_TIM,                                            00487002
             LAU_SERV_REAS1_CD,                                      00488002
             LAU_SERV_REAS2_CD,                                      00489002
             LAU_SERV_REAS3_CD,                                      00489102
             LAU_CARE_IND,                                           00489202
             SEG_UPDT_LOCK_NUM,                                      00489302
             LAU_AGRMT_PER_NAM,                                      00489402
             LAU_AGRMT_DSGT_NAM,                                     00489502
             LAU_AGRMT_DIR_TXT,                                      00489602
             LAU_TERMS_TXT                                           00489702
                                                                     00520002
        FROM TLEGAL

Here is my script....

# create a List object to collect the 'flowerbox' strings in
$Flowerbox = [System.Collections.Generic.List[string]]::new()
$treat = $false

# get a list of the .pl1m files and loop through. Collect all output in variable $result
$CBLFileList = Get-ChildItem -Path 'C:\src' -Filter '*.pl1m' -File -Recurse
$result = foreach ($CBLFile in $CBLFileList) {
    Write-Host "Processing ... $($CBLFile.Name)" -ForegroundColor Green

    $Flowerbox.Clear()  # empty the list for the next run
    $treat = $false
    switch -Regex -File $CBLFile.FullName {
        'SELECT' {
        Write-Host "Found Select" -ForegroundColor DarkYellow
            # start collecting lines from here
            $treat = $true
        }
        'FROM ' {
        Write-Host "Found From" -ForegroundColor DarkRed
           if ($treat) {

            # stop colecting Flowerbox lines and output what we already have
            # output an object with the two properties you need
            [PsCustomObject]@{
                Program     = $CBLFile.Name  # or $CBLFile.FullName
                Description = $Flowerbox -join [environment]::NewLine
            }
            }
            $Flowerbox.Clear()  # empty the list for the next run
            $treat = $false
        }
        default {
                # Add captures data here
                if ($treat -and ($_ -match '/[^\s\\]/')) {
                $Flowerbox.Add($Matches[1])
            }
        }
    }
}

# now you have everything in an array of PSObjects so you can save that as Csv
$result | Export-Csv -Path 'C:\src\SQL_Desc.csv' -UseCulture -NoTypeInformation

Body:
Your script needs only a few tweaks:

Add the full line, reflected in $_, to your $Flowerbox list

Also do so in the 'SELECT' and 'FROM ' branches.

# ...
$Flowerbox.Clear()  # empty the list for the next run
$treat = $false
switch -Regex -CaseSensitive -File $CBLFile.FullName {
  '^\s*SELECT\s' {
    Write-Host "Found Select" -ForegroundColor DarkYellow
    # start collecting lines from here
    $treat = $true
    $Flowerbox.Add($_) # Add this line to the list.
    continue # So that the FROM branch needn't also be checked.
  }
  '^\s*FROM\s' {
    Write-Host "Found From" -ForegroundColor DarkRed
    if ($treat) {
      $Flowerbox.Add($_)  # Add this line to the list.
      # stop collecting Flowerbox lines and output what we already have
      # output an object with the two properties you need
      [PsCustomObject]@{
        Program     = $CBLFile.Name  # or $CBLFile.FullName
        Description = $Flowerbox -join [environment]::NewLine
      }
      $Flowerbox.Clear()  # empty the list for the next run
      $treat = $false
    }
  }
  default {
    # When inside a block of interest, add all non-blank lines.
    if ($treat -and $_ -match '\S') {
      $Flowerbox.Add($_)  # Add this line to the list.
    }
  }
}
# ...

Note that, in the interest of minimizing the risk of false positives:

-CaseSensitive was added to the switch statement for case-sensitive matching.

The regexes were made more robust to prevent accidental substring matching and to tolerate whitespace variations (spaces vs. tabs).

Also, to exclude blank (empty and all-whitespace) lines, condition -match '\S' was added to the default branch.


问:
Cell referencing using just numbers
I have a formula:

```<code>=LET(Data,'Sheet1'!G9:Y19, .....)
</code>```

I really would like to reference Y19 using numbers, kind of like

```<code>=LET(Data,'Sheet1'!G9:Column(25)19, .....)
</code>```

if that makes sense. Since this cell reference changes and needs to be dynamic. How can I achieve this? Could I just remake a formula in VBA that does this? If so, how?

Title: Cell referencing using just numbers

Body:
I have a formula:

=LET(Data,'Sheet1'!G9:Y19, .....)

I really would like to reference Y19 using numbers, kind of like

=LET(Data,'Sheet1'!G9:Column(25)19, .....)

if that makes sense. Since this cell reference changes and needs to be dynamic. How can I achieve this? Could I just remake a formula in VBA that does this? If so, how?

Body:
Use INDEX:

=LET(Data,'Sheet1'!G9:INDEX(Sheet1!1:1048576,19,25)...


问:
Rendering elements in a V-For loop based on specific IDX
I have a component, in which I only ever want to render the first element in the Array. However the length is 1, which is resulting in two renders.

```<code><template>
  <div>
    <DataSolutions
      v-for="(rs, idx) in Solutions"
    >
    </DataSolutions>
 </div>
</template>
</code>```

How does one specify the index to only render a single time? Keeping in mind that Solutions is an Array of objects.

答:
I'm not sure if I understood your question.

If you only want to show one element there why do you have a v-for?
You use v-for only if you want to show more than one element based on an array of strings/objects etc.

In any case, you can have a computed property and either filter out the objects you don't want to render

For example if you have an array called solution):

```<code>data() {
  return {
    solutions: [
      { id: '0001' },
      { id: '0002' },
      { id: '0003' },
    ]
  }
}
</code>```

Then you can pick the item you want to render using computed:

```<code>computed: {
  solution() {
    return this.solutions[0]
  }
}
</code>```

By doing the above, you don't need a v-for.

If you have more than one item to show then you can use again computed and filter out the items you don't want to render.

Body:
I have a component, in which I only ever want to render the first element in the Array. However the length is 1, which is resulting in two renders.

<template>

    <DataSolutions
      v-for="(rs, idx) in Solutions"
    >
    </DataSolutions>

</template>

How does one specify the index to only render a single time? Keeping in mind that Solutions is an Array of objects.

Body:
I'm not sure if I understood your question.

If you only want to show one element there why do you have a v-for?
You use v-for only if you want to show more than one element based on an array of strings/objects etc.

In any case, you can have a computed property and either filter out the objects you don't want to render

For example if you have an array called solution):

data() {
  return {
    solutions: [
      { id: '0001' },
      { id: '0002' },
      { id: '0003' },
    ]
  }
}

Then you can pick the item you want to render using computed:

computed: {
  solution() {
    return this.solutions[0]
  }
}

By doing the above, you don't need a v-for.

If you have more than one item to show then you can use again computed and filter out the items you don't want to render.