问:
I have a button in my react app that i only want it to be pressed once
I have implemented this onclick event in it and I want the functions inside the onclick event to run once</p>
```<code>    <button className='btn2' onClick={() => {

OpenForm();

      if (IsLoggedIn === true){
        Like();
    }else if(IsLoggedIn === false){
    return;
    }
      }}>
</code>```

答:
What you need to do is keep track of that using state, let's say a hasClicked, the default state will be false and you changed that in the onClick handler you have up there, an example code snippet would be like:

```<code>import { useState } from 'react'

const MyComponent = () => {
    const [hasClicked, setHasClicked] = useState(false)
    ...

    const btnClickHandler = () => {
        ...
        setHasClicked(true)
        ...
    }

    return (
        <button disabled={hasClicked} onClick={btnClickHandler}>Click<button/>
    )
}
</code>```

That way, the button will be disabled once the user clicks on it because disabled will now be pointing to a true hasClicked value.

Body:
I have implemented this onclick event in it and I want the functions inside the onclick event to run once

    <button className='btn2' onClick={() => {

OpenForm();

      if (IsLoggedIn === true){
        Like();
    }else if(IsLoggedIn === false){
    return;
    }
      }}>

Body:
What you need to do is keep track of that using state, let's say a hasClicked, the default state will be false and you changed that in the onClick handler you have up there, an example code snippet would be like:

import { useState } from 'react'

const MyComponent = () => {
    const [hasClicked, setHasClicked] = useState(false)
    ...

    const btnClickHandler = () => {
        ...
        setHasClicked(true)
        ...
    }

    return (
        <button disabled={hasClicked} onClick={btnClickHandler}>Click<button/>
    )
}

That way, the button will be disabled once the user clicks on it because disabled will now be pointing to a true hasClicked value.


来源: stackexchange

问:
Sound file to text file-speech recognition for ubuntu, specifically pocketsphinx usage
As made clear here: https://unix.stackexchange.com/questions/256138/is-there-any-decent-speech-recognition-software-for-linux

Finding speech recognition software that turns sound file into text is dificult to do on linux.

I trying to use pocketsphinx_continuous command. Pocket spinx is already installed.

There are several dict files, language model files and acoustic folders that I have downloaded. I tried running the command pocketsphinx_continuous.

The command I use is: sudo pocketsphinx_continuous -dict /home/barnabas/Desktop/dict/cmudict.dict -hmm /home/barnabas/Desktop/wsj_all_sc.cd_semi_5000/ -lm /home/barnabas/Desktop/en-70k-0.1.lm -infile untitled2.wav 2> pocketsphinx.log > myspeech.txt

Now.

Without fail all outputs have a padded index on the left without any pair output text.

000000000:

I want a short list of one dictionary file, language model file, acoustic file listed please, that are compatible with each other. Thank you.

答:
I want a short list of one dictionary file, language model file, acoustic file listed please, that are compatible with each other.

Install the pocketsphinx-en-us package from the universe/sound section.
(It's available in Ubuntu 18.04 Bionic Beaver and later.
Prior to that, I believe it was called pocketsphinx-hmm-en-hub4wsj.)
This will put the model in /usr/share/pocketsphinx/model/en-us/.

After that, you can run commands like this (there's no need to use sudo):

```<code>pocketsphinx_continuous -infile myfile.wav 2>&1 > myspeech.txt | tee out.log | less
</code>```

Or if you want to specify the folders manually:

```<code>pocketsphinx_continuous \
    -hmm /usr/share/pocketsphinx/model/en-us/en-us \
    -dict /usr/share/pocketsphinx/model/en-us/cmudict-en-us.dict \
    -lm /usr/share/pocketsphinx/model/en-us/en-us.lm.bin \
    -infile myfile.wav > myspeech.txt
</code>```

Make sure you have a 16-bit, 16 kHz mono wav file, or convert if necessary:

```<code>ffmpeg -i myfile.mp3 -ar 16000 -ac 1 -sample_fmt s16 myfile.wav
</code>```

You might not have the best accuracy from the generic model.
Here's set #1 of the Harvard Sentences:

```<code>One: The birch canoe slid on the smooth planks.
Two: Glue the sheet to the dark blue background.
Three: It's easy to tell the depth of a well.
Four: These days a chicken leg is a rare dish.
Five: Rice is often served in round bowls.
Six: The juice of lemons makes fine punch.
Seven: The box was thrown beside the parked truck.
Eight: The hogs were fed chopped corn and garbage.
Nine: Four hours of steady work faced us.
Ten: Large size in stockings is hard to sell.
</code>```

and here's the output I got from my recording:

```<code>if one half the brcko nude lid on this good length
to conclude ishii to the dark blue background
three it's easy to tell the devil wow
for these days eat chicken leg is a rare dish
five race is often served in round polls
six the juice of the lemons makes flying conch
seven the box was thrown beside the parked truck
eight the hogs griffin chopped coroner and garbage
not in four hours of steady work the stocks
ten large son is in stockings his heart is the good
</code>```

Related:

How to give an input wav file to pocket sphinx

Error when running pocketsphinx_continuous: Acoustic model definition is not specified

How can we convert .wav file to text by using pocketsphinx?

https://askubuntu.com/questions/837408/convert-speech-mp3-audio-files-to-text

https://askubuntu.com/questions/161515/speech-recognition-app-to-convert-mp3-to-text

https://old.reddit.com/r/linuxquestions/comments/bj54y0/speech_to_text_program/em6b7j9/

https://unicom.crosenthal.com/blog/entry/686

ContentLicense: CC BY-SA 4.0

Body:
I want a short list of one dictionary file, language model file, acoustic file listed please, that are compatible with each other.

Install the pocketsphinx-en-us package from the universe/sound section.
(It's available in Ubuntu 18.04 Bionic Beaver and later.
Prior to that, I believe it was called pocketsphinx-hmm-en-hub4wsj.)
This will put the model in /usr/share/pocketsphinx/model/en-us/.

After that, you can run commands like this (there's no need to use sudo):

pocketsphinx_continuous -infile myfile.wav 2>&1 > myspeech.txt | tee out.log | less

Or if you want to specify the folders manually:

pocketsphinx_continuous \
    -hmm /usr/share/pocketsphinx/model/en-us/en-us \
    -dict /usr/share/pocketsphinx/model/en-us/cmudict-en-us.dict \
    -lm /usr/share/pocketsphinx/model/en-us/en-us.lm.bin \
    -infile myfile.wav > myspeech.txt

Make sure you have a 16-bit, 16 kHz mono wav file, or convert if necessary:

ffmpeg -i myfile.mp3 -ar 16000 -ac 1 -sample_fmt s16 myfile.wav

You might not have the best accuracy from the generic model.
Here's set #1 of the Harvard Sentences:

One: The birch canoe slid on the smooth planks.
Two: Glue the sheet to the dark blue background.
Three: It's easy to tell the depth of a well.
Four: These days a chicken leg is a rare dish.
Five: Rice is often served in round bowls.
Six: The juice of lemons makes fine punch.
Seven: The box was thrown beside the parked truck.
Eight: The hogs were fed chopped corn and garbage.
Nine: Four hours of steady work faced us.
Ten: Large size in stockings is hard to sell.

and here's the output I got from my recording:

if one half the brcko nude lid on this good length
to conclude ishii to the dark blue background
three it's easy to tell the devil wow
for these days eat chicken leg is a rare dish
five race is often served in round polls
six the juice of the lemons makes flying conch
seven the box was thrown beside the parked truck
eight the hogs griffin chopped coroner and garbage
not in four hours of steady work the stocks
ten large son is in stockings his heart is the good

Related:

How to give an input wav file to pocket sphinx

Error when running pocketsphinx_continuous: Acoustic model definition is not specified

How can we convert .wav file to text by using pocketsphinx?

https://askubuntu.com/questions/837408/convert-speech-mp3-audio-files-to-text

https://askubuntu.com/questions/161515/speech-recognition-app-to-convert-mp3-to-text

https://old.reddit.com/r/linuxquestions/comments/bj54y0/speech_to_text_program/em6b7j9/

https://unicom.crosenthal.com/blog/entry/686


问:
How to call and pass array of string and find the length of that array inside the function
I am writing a program to check if a string is inside an array of strings.
I predefined an array of words before the main method

```<code>const char *items[] = {"a","b","c","d"};
</code>```

then I have a function like

```<code>bool isInside(const char *array[], char *s1){
 //which will try to compare all strings from the input array with s1
  int len = sizeof(array)/sizeof(array[0]);
  for (int i =0; i< len ; i++){
   //do string comparasion}
}
</code>```

It worked before but not sure where I messed up the code now I got two errors and the function is only able to check the first string of the array with s1.

I found out the problem is that now len = 1 always.

one of the errors is

```<code>`warning: ‘sizeof’ on array function parameter ‘array’ will return size of ‘const char **’ [-Wsizeof-array-argument]` and the other one is

isInside(items, words[i]))
      |                               ^~~~~~~~~
      |                               |
      |                               const char **
code.c:63:21: note: expected ‘char *’ but argument is of type ‘const char **’
</code>```

How can I fix this or call this function so the length is correct and no type warning?

Thanks a lot.

答:
Arrays in C will degrade to pointers when passed as arguments to functions. When they become pointers, their length cannot be retrieved by sizeof.

You should pass the length of arrays as an additional argument to the function.

Maybe your function can be modified as:

```<code>bool isInside(const char **array, int arrayLength, char *s1){
  for (int i =0; i< arrayLength; i++){
     const char* str = array[i];
     if(strcmp(str, s1) == 0){
        return 1;
     }
  }
  return 0;
}
</code>```

Body:
I am writing a program to check if a string is inside an array of strings.
I predefined an array of words before the main method

const char *items[] = {"a","b","c","d"};

then I have a function like

bool isInside(const char *array[], char *s1){
 //which will try to compare all strings from the input array with s1
  int len = sizeof(array)/sizeof(array[0]);
  for (int i =0; i< len ; i++){
   //do string comparasion}
}

It worked before but not sure where I messed up the code now I got two errors and the function is only able to check the first string of the array with s1.

I found out the problem is that now len = 1 always.

one of the errors is

`warning: ‘sizeof’ on array function parameter ‘array’ will return size of ‘const char **’ [-Wsizeof-array-argument]` and the other one is

isInside(items, words[i]))
      |                               ^~~~~~~~~
      |                               |
      |                               const char **
code.c:63:21: note: expected ‘char *’ but argument is of type ‘const char **’

How can I fix this or call this function so the length is correct and no type warning?

Thanks a lot.

Body:
Arrays in C will degrade to pointers when passed as arguments to functions. When they become pointers, their length cannot be retrieved by sizeof.

You should pass the length of arrays as an additional argument to the function.

Maybe your function can be modified as:

bool isInside(const char **array, int arrayLength, char *s1){
  for (int i =0; i< arrayLength; i++){
     const char* str = array[i];
     if(strcmp(str, s1) == 0){
        return 1;
     }
  }
  return 0;
}


问:
How to find a missing row between two similar 2d numpy arrays
Say I have two 2d arrays:

```<code>aa = np.array([[1,2],[3,4],[9,10],[48,59]])
bb = np.array([[1,2],[9,10]])
</code>```

array aa is my ideal array and bb is what I have recorded. I want to find out what rows bb is missing compared to aa. I can do this by looping through the rows but as my dataset is approximately 5Gb I want to know if there is a pythonic way of doing this to minimize run time. It would be preferable to carry out this operation as a numpy array but it doesn't HAVE to be that way if there is a better option.

Any help is appreciated. Thanks

答:
The main step is to find boolean indices of aa that tells if items in aa are present in bb. For example, if:

```<code>aa = np.array([[1,2],[3,4],[9,10],[48,59]])
bb = np.array([[1,2],[9,10]])
</code>```

then we should get:

```<code>idx
>>> array([ True, False,  True, False])
</code>```

And we could use later:

```<code>aa[~idx]
>>>
array([[ 3,  4],
       [48, 59]])
</code>```

Since aa[~idx] is relatively fast, I'll try to review all the ways to find idx. They divide between two groups: the way of searching the data (np.isin, np.searchsort, etc.) and the way that data could be made 1-dimensional.

The way of reduction

Way 1. Make arrays aa and bb contiguous then call np.isin on their views:

```<code>def _view1D(a, b): # a, b are arrays
    a = np.ascontiguousarray(a, dtype=np.uint32)
    b = np.ascontiguousarray(b, dtype=np.uint32)
    uint32_dt = np.dtype([('', np.uint32)]*2)
    return a.view(uint32_dt).ravel(),  b.view(uint32_dt).ravel()

A, B = _view1D(aa, bb)
idx = np.isin(A, B)
</code>```

Way 2.
Reduce dimensionality of aa and bb then call np.isin on resulting arrays:

```<code>def numpy_dimreduce(arr, M):
    return np.ravel_multi_index(arr.T, M, order='F')

M = aa.max(axis=0)+1
idx = np.isin(numpy_dimreduce(aa, M), numpy_dimreduce(bb, M))
</code>```

Way 3. Improve performance of dimensionality reduction significantly using numba:

```<code>@njit(parallel=True)
def _numba_dot(arr, dimshape, len_arr, len_dimshape, su):
    for i in prange(len_arr):
        for j in range(len_dimshape):
            su[i] = su[i] + arr[i][j] * dimshape[j]

def numba_dimreduce(arr, M, dtype=np.int64):
    '''not safe if allocation is exceeded'''
    dimshape = np.cumprod(np.insert(M[:-1], 0, 1))
    su = np.zeros(len(arr), dtype=dtype)
    _numba_dot(arr, dimshape, len(arr), len(dimshape), su)
    return su

M = aa.max(axis=0)+1
idx = np.isin(numba_dimreduce(aa, M), numba_dimreduce(bb, M))
</code>```

The way of searching

Way 1.
Use np.isinlike in previous solutions

Way 2.
Use np.in1D instead of np.isin.

Way 3.
Use argsort + np.searchsorted:

```<code>def searchsort(A, B):
    sidx = A.argsort()
    out = np.zeros(len(A), dtype=bool)
    s = np.searchsorted(A, B, sorter=sidx)
    out[sidx[s]] = True
    return out
</code>```

Way 4 Use masking:

```<code>def masking(A, B):
    mask = np.empty(shape=np.prod(M), dtype=bool)
    mask[A] = 0
    mask[B] = 1
    return mask[A]
</code>```

It could be applied in case np.prod(M) is small only. Therefore I put it into category of alternative solutions.

Conclusion

In conclusion, the general pattern of finding idx looks like this:

```<code>def isin2D(a, b, view=_view1D, search=np.isin):
    # choose your optional view and search
    A, B = view(a), view(b)
    idx = search(A, B)
    return idx
</code>```

Actually, neither ndarray.views nor np.searchsorted helps to save time. The best option is to combine dimensionality reduction with np.isin. In OP's case, it could be applied like so:

```<code>def isin2D(a, b):
    M = a.max(axis=0) + 1
    A = np.ravel_multi_index(a.T, M, order='C')
    B = np.ravel_multi_index(b.T, M, order='C')
    idx = np.isin(A, B)
    return idx

idx = isin2D(aa, bb)
aa[~idx]
>>>
array([[ 3,  4],
       [48, 59]])
</code>```

Performance

Now let's time it using benchit package to illustrate what's winning

```<code>idx
>>> array([ True, False,  True, False])
</code>```0

Alternative solutions

In case product of M = aa.max(axis=0) + 1 is not too large you could allocate M items for masking. Make sure you won't blow up your RAM. A couple more ways:

```<code>idx
>>> array([ True, False,  True, False])
</code>```1

Runtime in case np.max(aa, axis=0) + 1 = (1000, 1000):

Body:
Say I have two 2d arrays:

aa = np.array([[1,2],[3,4],[9,10],[48,59]])
bb = np.array([[1,2],[9,10]])

array aa is my ideal array and bb is what I have recorded. I want to find out what rows bb is missing compared to aa. I can do this by looping through the rows but as my dataset is approximately 5Gb I want to know if there is a pythonic way of doing this to minimize run time. It would be preferable to carry out this operation as a numpy array but it doesn't HAVE to be that way if there is a better option.

Any help is appreciated. Thanks

Body:
The main step is to find boolean indices of aa that tells if items in aa are present in bb. For example, if:

aa = np.array([[1,2],[3,4],[9,10],[48,59]])
bb = np.array([[1,2],[9,10]])

then we should get:

idx
>>> array([ True, False,  True, False])

And we could use later:

aa[~idx]
>>>
array([[ 3,  4],
       [48, 59]])

Since aa[~idx] is relatively fast, I'll try to review all the ways to find idx. They divide between two groups: the way of searching the data (np.isin, np.searchsort, etc.) and the way that data could be made 1-dimensional.

The way of reduction

Way 1. Make arrays aa and bb contiguous then call np.isin on their views:

def _view1D(a, b): # a, b are arrays
    a = np.ascontiguousarray(a, dtype=np.uint32)
    b = np.ascontiguousarray(b, dtype=np.uint32)
    uint32_dt = np.dtype([('', np.uint32)]*2)
    return a.view(uint32_dt).ravel(),  b.view(uint32_dt).ravel()

A, B = _view1D(aa, bb)
idx = np.isin(A, B)

Way 2.
Reduce dimensionality of aa and bb then call np.isin on resulting arrays:

def numpy_dimreduce(arr, M):
    return np.ravel_multi_index(arr.T, M, order='F')

M = aa.max(axis=0)+1
idx = np.isin(numpy_dimreduce(aa, M), numpy_dimreduce(bb, M))

Way 3. Improve performance of dimensionality reduction significantly using numba:

@njit(parallel=True)
def _numba_dot(arr, dimshape, len_arr, len_dimshape, su):
    for i in prange(len_arr):
        for j in range(len_dimshape):
            su[i] = su[i] + arr[i][j] * dimshape[j]

def numba_dimreduce(arr, M, dtype=np.int64):
    '''not safe if allocation is exceeded'''
    dimshape = np.cumprod(np.insert(M[:-1], 0, 1))
    su = np.zeros(len(arr), dtype=dtype)
    _numba_dot(arr, dimshape, len(arr), len(dimshape), su)
    return su

M = aa.max(axis=0)+1
idx = np.isin(numba_dimreduce(aa, M), numba_dimreduce(bb, M))

The way of searching

Way 1.
Use np.isinlike in previous solutions

Way 2.
Use np.in1D instead of np.isin.

Way 3.
Use argsort + np.searchsorted:

def searchsort(A, B):
    sidx = A.argsort()
    out = np.zeros(len(A), dtype=bool)
    s = np.searchsorted(A, B, sorter=sidx)
    out[sidx[s]] = True
    return out

Way 4 Use masking:

def masking(A, B):
    mask = np.empty(shape=np.prod(M), dtype=bool)
    mask[A] = 0
    mask[B] = 1
    return mask[A]

It could be applied in case np.prod(M) is small only. Therefore I put it into category of alternative solutions.

Conclusion

In conclusion, the general pattern of finding idx looks like this:

def isin2D(a, b, view=_view1D, search=np.isin):
    # choose your optional view and search
    A, B = view(a), view(b)
    idx = search(A, B)
    return idx

Actually, neither ndarray.views nor np.searchsorted helps to save time. The best option is to combine dimensionality reduction with np.isin. In OP's case, it could be applied like so:

def isin2D(a, b):
    M = a.max(axis=0) + 1
    A = np.ravel_multi_index(a.T, M, order='C')
    B = np.ravel_multi_index(b.T, M, order='C')
    idx = np.isin(A, B)
    return idx

idx = isin2D(aa, bb)
aa[~idx]
>>>
array([[ 3,  4],
       [48, 59]])

Performance

Now let's time it using benchit package to illustrate what's winning

import numpy as np
from numba import njit, prange
import benchit
%matplotlib inline
benchit.setparams(rep=3)

sizes = [100000, 300000, 500000, 1000000, 1700000, 3000000, 5000000]#, 10000000, 30000000]
N = sizes[-1]
aa = np.random.randint(0, 1000000, size=(N, 2))
r = np.random.randint(0, 2, size=N).astype(bool)
M = aa.max(axis=0) + 1

def _view1D(arr, dtype=np.uint32):
    a = np.ascontiguousarray(arr, dtype=dtype)
    dt = np.dtype([('', dtype)]*2)
    return a.view(dt).ravel()

def _numpy_dimreduce(arr, M):
    return np.ravel_multi_index(arr.T, M, order='C')

@njit(parallel=True)
def _numba_dot(arr, dimshape, len_arr, len_dimshape, su):
    for i in prange(len_arr):
        for j in range(len_dimshape):
            su[i] = su[i] + arr[i][j] * dimshape[j]

def _numba_dimreduce(arr, M, dtype=np.int64):
    '''not safe if allocation is exceeded'''
    dimshape = np.cumprod(np.insert(M[:-1], 0, 1))
    su = np.zeros(len(arr), dtype=dtype)
    _numba_dot(arr, dimshape, len(arr), len(dimshape), su)
    return su

def isin2D(a, b, view=_view1D, search=np.isin):
    A, B = view(a), view(b)
    idx = search(A, B)
    return idx

def searchsort(A, B):
    sidx = A.argsort()
    out = np.zeros(len(A), dtype=bool)
    s = np.searchsorted(A, B, sorter=sidx)
    out[sidx[s]] = True
    return out

def isin2D_numpy_view(a, b): return isin2D(a, b, view=_view1D, search=np.isin)

def isin2D_numpy_dimr_isin(a, b, M=M): return isin2D(a, b, view=lambda arr, M=M: _numpy_dimreduce(arr, M), search=np.isin)
def isin2D_numba_dimr_isin(a, b, M=M): return isin2D(a, b, view=lambda arr, M=M: _numba_dimreduce(arr, M), search=np.isin)

def isin2D_numpy_dimr_searchsort(a, b, M=M): return isin2D(a, b, view=lambda arr, M=M: _numpy_dimreduce(arr, M), search=searchsort)
def isin2D_numba_dimr_searchsort(a, b, M=M): return isin2D(a, b, view=lambda arr, M=M: _numba_dimreduce(arr[:, ::-1], M[::-1]), search=searchsort)

def isin2D_numpy_dimr_in1D(a, b, M=M): return isin2D(a, b, view=lambda arr, M=M: _numpy_dimreduce(arr, M), search=np.in1d)
def isin2D_numba_dimr_in1D(a, b, M=M): return isin2D(a, b, view=lambda arr, M=M: _numba_dimreduce(arr[:, ::-1], M[::-1]), search=np.in1d)

fns = [isin2D_numpy_dimr, isin2D_numba_dimr, isin2D_numpy_view, isin2D_numpy_dimr_searchsort, isin2D_numba_dimr_searchsort, isin2D_numpy_dimr_in1D, isin2D_numba_dimr_in1D]

in_ = {s/1000000: (aa[:s], aa[:s][r[:s]]) for s in sizes}
t = benchit.timings(fns, in_, multivar=True, input_name='Millions of events')
t.plot(logx=True, figsize=(12, 6), fontsize=14)

Alternative solutions

In case product of M = aa.max(axis=0) + 1 is not too large you could allocate M items for masking. Make sure you won't blow up your RAM. A couple more ways:

def masking1D(a, b):
    M = aa.max(axis=0) + 1
    A = np.ravel_multi_index(a.T, M, order='C')
    B = np.ravel_multi_index(b.T, M, order='C')
    mask = np.empty(shape=np.prod(M), dtype=bool)
    mask[A] = 1
    mask[B] = 0
    return mask[A]

def masking2D(a, b):
    M = a.max(axis=0) + 1
    mask = np.empty(shape=M, dtype=bool)
    mask[tuple(a.T)] = 1
    mask[tuple(b.T)] = 0
    return mask[tuple(a.T)]

aa = np.array([[988, 986], [299, 327], [756, 30], [327, 189], [988, 294], [64, 232], [11, 46], [38, 223], [933, 770], [141, 141]])
bb = aa[[1, 2, 3, 6, 7, 4]]
masking1D(aa, bb)
>>> array([ True, False, False, False, False,  True, False, False,  True, True])
masking2D(aa, bb)
>>> array([ True, False, False, False, False,  True, False, False,  True, True])

Runtime in case np.max(aa, axis=0) + 1 = (1000, 1000):


问:
Threshold based on sample size in each dataset in R
I want to create in R a threshold that is based on the sample size and will differ in each dataset. Let's say I have the following two datasets:

```<code>data<-matrix( rnorm(200*10,mean=0,sd=1), 200, 10)
colnames(data) <- c("X1", "X2", "X3", "X4", "X5", "X6","X7","X8","X9","X10")

data<-matrix( rnorm(100*10,mean=0,sd=1), 100, 10)
colnames(data) <- c("X1", "X2", "X3", "X4", "X5", "X6","X7","X8","X9","X10")
</code>```

and I want to create a threshold that each time will differ and will be calculated based on the sample size. I want to code the following picture as a threshold, where on the left there are the threshold values, and on the right the sample size of each column(=n) . How can I achieve that?

答:
As I understand it, you want to take the number of rows your matrix and then choose a threshold.

One approach is to create a table with the sample sizes and thresholds. Then, given a sample size, filter the table so that the last row is the threshold and pull out that value.

```<code># create table of thresholds
thresholds <- data.frame(n = c(50, 60, 70, 85), # etc
                         threshold = c(.75, .7, .65, .6) )

sample_size <- nrow(data)

tail(thresholds[thresholds$n <= sample_size, "threshold"], 1)
</code>```
```<code># Or if you're more comfortable with dplyr / tidyverse
thresholds <- tibble(n = c(50, 60, 70, 85), # etc
                         threshold = c(.75, .7, .65, .6) )
thresholds %>%
   filter(n <= nrow(data)) %>%
   pull(threshold) %>%
   last()

</code>```

If you plan on doing this with several data sets you can create a function:

```<code>get_threshold <- function(data, .thresholds = thresholds) {
   .thresholds %>%
      filter(n <= nrow(data)) %>%
      pull(threshold) %>%
      last()
}
</code>```

Body:
I want to create in R a threshold that is based on the sample size and will differ in each dataset. Let's say I have the following two datasets:

data<-matrix( rnorm(200*10,mean=0,sd=1), 200, 10)
colnames(data) <- c("X1", "X2", "X3", "X4", "X5", "X6","X7","X8","X9","X10")

data<-matrix( rnorm(100*10,mean=0,sd=1), 100, 10)
colnames(data) <- c("X1", "X2", "X3", "X4", "X5", "X6","X7","X8","X9","X10")

and I want to create a threshold that each time will differ and will be calculated based on the sample size. I want to code the following picture as a threshold, where on the left there are the threshold values, and on the right the sample size of each column(=n) . How can I achieve that?

Body:
As I understand it, you want to take the number of rows your matrix and then choose a threshold.

One approach is to create a table with the sample sizes and thresholds. Then, given a sample size, filter the table so that the last row is the threshold and pull out that value.

# create table of thresholds
thresholds <- data.frame(n = c(50, 60, 70, 85), # etc
                         threshold = c(.75, .7, .65, .6) )

sample_size <- nrow(data)

tail(thresholds[thresholds$n <= sample_size, "threshold"], 1)

# Or if you're more comfortable with dplyr / tidyverse
thresholds <- tibble(n = c(50, 60, 70, 85), # etc
                         threshold = c(.75, .7, .65, .6) )
thresholds %>%
   filter(n <= nrow(data)) %>%
   pull(threshold) %>%
   last()

If you plan on doing this with several data sets you can create a function:

get_threshold <- function(data, .thresholds = thresholds) {
   .thresholds %>%
      filter(n <= nrow(data)) %>%
      pull(threshold) %>%
      last()
}


问:
Replacing characters with other characters in C files
I am attempting to write a program that takes in two files (or if not provided either file, uses stdin/stdout to replace a specified character array with another character array.

For example: if passed "--ax -+td" then my program will replace every instance of 'a' with 't' and every 'x' with 'd'.

Here is what I am trying:

char *takeOut = "ax";
char *putIn = "td";

FILE *in = freopen(src, "r", stdin);
FILE *out = freopen(dest, "w", stdout);
int ch;

   for (int i=0; i<strlen(putIn); i++) {

      while ((ch = getc(in)) != EOF) {
           if (ch == '\n') { // for stdout displaying without "%"
              putc('\n', out);
              break;
           } else if (ch != takeOut[i]) {
              putc(ch, out);
           } else {
              putc((putIn[i]), out);
           }
       }
    }
```

The program ensures that the putIn and takeOut are of the same size, by the way.

The result is that only the first letter specified is replaced in every instance (in this case all "a's" are replaced with "t's". But no "x's" are replaced with "d's".

What am I doing wrong?

答:
well you set i to 0 and read the whole input. This looks for 'a'. All fine, then you hit EOF.

then you loop back and set i = 1 to look for 'x', BUT the files are still at EOF. you need to rewind the files. Or close and reopen

Much better tho is to invert the loops

```<code>   while ((ch = getc(in)) != EOF) {
         for(int i = 0; i< strlen(takeout); i++{
            if(ch == takeout(i)......
         }
   }
</code>```

this is much more efficient as it only reads the file once

Body:
I am attempting to write a program that takes in two files (or if not provided either file, uses stdin/stdout to replace a specified character array with another character array.

For example: if passed "--ax -+td" then my program will replace every instance of 'a' with 't' and every 'x' with 'd'.

Here is what I am trying:

char *takeOut = "ax";
char *putIn = "td";

FILE *in = freopen(src, "r", stdin);
FILE *out = freopen(dest, "w", stdout);
int ch;

   for (int i=0; i<strlen(putIn); i++) {

      while ((ch = getc(in)) != EOF) {
           if (ch == '\n') { // for stdout displaying without "%"
              putc('\n', out);
              break;
           } else if (ch != takeOut[i]) {
              putc(ch, out);
           } else {
              putc((putIn[i]), out);
           }
       }
    }

The program ensures that the putIn and takeOut are of the same size, by the way.

The result is that only the first letter specified is replaced in every instance (in this case all "a's" are replaced with "t's". But no "x's" are replaced with "d's".

What am I doing wrong?

Body:
well you set i to 0 and read the whole input. This looks for 'a'. All fine, then you hit EOF.

then you loop back and set i = 1 to look for 'x', BUT the files are still at EOF. you need to rewind the files. Or close and reopen

Much better tho is to invert the loops

   while ((ch = getc(in)) != EOF) {
         for(int i = 0; i< strlen(takeout); i++{
            if(ch == takeout(i)......
         }
   }

this is much more efficient as it only reads the file once


问:
Discord.JS v13 set nickname to bot Missing Permissions
I'm trying to change bot's username with  await client.guilds.cache.get(msg.guild.id).me.setNickname("something"), but it returns Missing Permissions error. The bot has even administrator permissions in the server and I can't figure out what's the problem. Is it Intents error or idk?

```<code>DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/tom/Documents/Phyc/Phyc/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/home/tom/Documents/Phyc/Phyc/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
    at async GuildMemberManager.edit (/home/tom/Documents/Phyc/Phyc/node_modules/discord.js/src/managers/GuildMemberManager.js:277:15)
    at async Client.<anonymous> (/home/tom/Documents/Phyc/Phyc/bot.js:1678:9) {
  method: 'patch',
  path: '/guilds/919217411268411392/members/872813046236606505',
  code: 50013,
  httpStatus: 403,
  requestData: {
    json: { nick: 'something', communication_disabled_until: undefined },
    files: []
  }
}
</code>```

答:
DiscordAPIError: Missing Permissions

at some point. This error can be caused by one of the following reasons:

• Your bot is missing the needed permission to execute this action in it’s calculated base or final permissions (requirement changes based on the type of action you are trying to execute).

• You provided an invalid permission number while trying to create overwrites. (The calculator on the apps page returns decimal values while the developer documentation lists the flags in hex. Make sure you are not mixing the two and don’t use the hex prefix 0x where not applicable)

• It is trying to execute an action on a guild member with a role higher than or equal to your bots highest role.

• It is trying to modify or assign a role that is higher than or equal to its highest role.

• It is trying to execute a forbidden action on the server owner.

• It is trying to execute an action based on another unfulfilled factor (for example reserved for partnered guilds).

• It is trying to execute an action on a voice channel without the VIEW_CHANNEL permission.

Good Luck

Body:
I'm trying to change bot's username with  await client.guilds.cache.get(msg.guild.id).me.setNickname("something"), but it returns Missing Permissions error. The bot has even administrator permissions in the server and I can't figure out what's the problem. Is it Intents error or idk?

DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/tom/Documents/Phyc/Phyc/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/home/tom/Documents/Phyc/Phyc/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
    at async GuildMemberManager.edit (/home/tom/Documents/Phyc/Phyc/node_modules/discord.js/src/managers/GuildMemberManager.js:277:15)
    at async Client.<anonymous> (/home/tom/Documents/Phyc/Phyc/bot.js:1678:9) {
  method: 'patch',
  path: '/guilds/919217411268411392/members/872813046236606505',
  code: 50013,
  httpStatus: 403,
  requestData: {
    json: { nick: 'something', communication_disabled_until: undefined },
    files: []
  }
}


问:
HTTParty post method doesn't return status code when adding follow_redirects = false along with other headers and cookies?
The HTTParty methods are like   HTTParty.XXX(urlGoesHere, and Args Here)

I'm doing the following:

```<code>params = {:UserName => "uname", :Password => "pwd"}

cookie_hash = HTTParty::CookieHash.new
cookie_hash.add_cookies("key1=val1")
cookie_hash.add_cookies("key2=val2")

options = {
   :body=>params,
   :headers => { 'Cookie' => cookie_hash.to_cookie_string,
                 'Accept' => something },
   :follow_redirects => false
}

URLUserNamePwd = HTTParty.post(myURL, options) # Is this the right way to do?
</code>```

When I check the http status code, body I get nothing. When I check in the browser development console, I see 302 redirect, and in response headers I see lot of header pairs returned.

答: What is the URL you're attempting to hit? 302 Found will be paired with a  Location header containing the URL where the resource can be found.

Body:
The HTTParty methods are like   HTTParty.XXX(urlGoesHere, and Args Here)

I'm doing the following:

params = {:UserName => "uname", :Password => "pwd"}

cookie_hash = HTTParty::CookieHash.new
cookie_hash.add_cookies("key1=val1")
cookie_hash.add_cookies("key2=val2")

options = {
   :body=>params,
   :headers => { 'Cookie' => cookie_hash.to_cookie_string,
                 'Accept' => something },
   :follow_redirects => false
}

URLUserNamePwd = HTTParty.post(myURL, options) # Is this the right way to do?

When I check the http status code, body I get nothing. When I check in the browser development console, I see 302 redirect, and in response headers I see lot of header pairs returned.


问:
Programmatically animate a blender model — where to start?
I have to create a simplistic 3D demo.

Having a model in Blender, I will write a python program that will:

build a scene, set camera, draw an infinite plane, fill it with texture

load a model (exported from Blender) and position the object

handle key presses to produce the object moves

I need a link to descriptive tutorial(s) covering these 3 points:

creating a 3d scene from Python program

loading model from the file (of course I'm fine with any format, just letting you know that the source is created in Blender)

catching key presses

No need in help on physics, or designing, only the principal programmatic part.

Thanks!

答:
Not much to say: OpenGL / Glut

Also, take a look at the OpenGL red book. You can read it online.
 Samples are written in C, but can be easily ported to python, since function calls are the same.

As for loading the blender model, take a look at this:
Loading wavefront obj files with python

In a nutshell look for:

Push/Pop matrix

glTranslate / glRotate / glScale

gluLookAt

define a function that and pass it to glutKeyboardFunc

ContentLicense: CC BY-SA 3.0


问:
How to access method of an object in the object?
I am trying to condense my code, so I want to create object instead of having to create labels each time I need one.

However, I can't figure out how to be able to change attributes of the object-labels using .config. I've tried using objectvariable.config(...), but that doesn't work. Neither does using a method like in the following:

```<code>class title_label():
    def __init__(self):
        self = tkinter.Label(root)
        self.pack(side='left')

    def update(self, text):
        self.config(text=text)
</code>```

Error-message is: objectvariable object has no attribute config.

How can I use .config on an object containing a label?

答:
If you made your class a subclass of tkinter.Label then it would have inherited a config() method from it.

Here's an example of how that might be done:

```<code>import tkinter as tk

class TitleLabel(tk.Label):
    def update(self, text):
        self.config(text=text)

if __name__ == '__main__':
    root = tk.Tk()

    title_lbl = TitleLabel(root, text='Initial Text')
    title_lbl.pack(side='left')

    root.after(1000, lambda: title_lbl.update('CHANGED!'))  # Update after 1 sec.
    root.mainloop()
</code>```

But as you can see, there wouldn't really be much point of doing so, since the only thing update() does is forward to call on the base class.

Body:
I am trying to condense my code, so I want to create object instead of having to create labels each time I need one.

However, I can't figure out how to be able to change attributes of the object-labels using .config. I've tried using objectvariable.config(...), but that doesn't work. Neither does using a method like in the following:

class title_label():
    def __init__(self):
        self = tkinter.Label(root)
        self.pack(side='left')

    def update(self, text):
        self.config(text=text)

Error-message is: objectvariable object has no attribute config.

How can I use .config on an object containing a label?

Body:
If you made your class a subclass of tkinter.Label then it would have inherited a config() method from it.

Here's an example of how that might be done:

import tkinter as tk

class TitleLabel(tk.Label):
    def update(self, text):
        self.config(text=text)

if __name__ == '__main__':
    root = tk.Tk()

    title_lbl = TitleLabel(root, text='Initial Text')
    title_lbl.pack(side='left')

    root.after(1000, lambda: title_lbl.update('CHANGED!'))  # Update after 1 sec.
    root.mainloop()

But as you can see, there wouldn't really be much point of doing so, since the only thing update() does is forward to call on the base class.


问:
Update panel Avoid page reload when Radio button is checked not working
I am trying to use 2 Radio buttons and swap the view according to the radio button selected, but it's not working, the page does not reload and nothing happens.
can someone tell me where is the problem?</p>
```<code>        <%@ Page Title="" Language="C#" MasterPageFile="~/Admin Part/Admin.Master" AutoEventWireup="true" CodeBehind="DataEntry.aspx.cs" Inherits="_4Kids.Admin_Part.DataEntry" EnableEventValidation="false" %>

        <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="ajaxToolkit" %>
        <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>           <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
                                <asp:UpdatePanel ID="upd" runat="server" UpdateMode="Conditional">
                                    <ContentTemplate>
<table>
<tr>
                                        <td style="height: 21px;">

                                            <asp:RadioButton ID="rdb_Preterm" runat="server" Text="Preterm" AutoPostBack="true" OnCheckedChanged="rdb_Preterm_CheckedChanged" />
                                            <asp:RadioButton ID="rdb_Fulterm" runat="server" Text="Full term" AutoPostBack="true" OnCheckedChanged="rdb_Fulterm_CheckedChanged" />

                                        </td>
                                        <td style="height: 21px;">
                                            <asp:MultiView ID="Mul" runat="server">
                                                <asp:View ID="view_null" runat="server"></asp:View>
                                                <asp:View ID="view_weeks" runat="server">
                                                    <table>
                                                        <tr>
                                                            <td>
                                                                <asp:Label ID="Label14" runat="server" Text="Weeks:"></asp:Label>
                                                            </td>
                                                            <td>
                                                                <asp:TextBox ID="txt_pretermWeeks" runat="server"></asp:TextBox>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </asp:View>
                                            </asp:MultiView>
                                        </td>
</tr>
</table>
                                    </ContentTemplate>
                                    <Triggers>
                                        <asp:AsyncPostBackTrigger ControlID="rdb_Preterm" EventName="CheckedChanged" />
                                        <asp:AsyncPostBackTrigger ControlID="rdb_Fulterm" EventName="CheckedChanged"/>
                                    </Triggers>
                                </asp:UpdatePanel>

    </asp:Content>
</code>```

答:
A few things:
In your posted markup, I don't seen anything related to the ajaxtoolkit.

So, remove that stuff. Also, remove the post back triggers. They are really for causing OTHER update panels to trigger - and you don't have multiple panels, so dump that stuff.

You do however need the script manager due to use of the update panel.

So, we now have this:

```<code>    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="upd" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table>
            <tr>
            <td style="height: 21px;">
                <asp:RadioButton ID="rdb_Preterm" runat="server"
                    Text="Preterm" AutoPostBack="true" OnCheckedChanged="rdb_Preterm_CheckedChanged" />
                <asp:RadioButton ID="rdb_Fulterm" runat="server"
                    Text="Full term" AutoPostBack="true" OnCheckedChanged="rdb_Fulterm_CheckedChanged" />
            </td>
            <td style="height: 21px;">
                <asp:MultiView ID="Mul" runat="server">
                    <asp:View ID="view_null" runat="server"></asp:View>
                    <asp:View ID="view_weeks" runat="server">
                        <table>
                            <tr>
                                <td>
                                    <asp:Label ID="Label14" runat="server" Text="Weeks:"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txt_pretermWeeks" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                        </table>
                    </asp:View>
                </asp:MultiView>
            </td>
            </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</code>```

And you code behind can be this:

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void rdb_Preterm_CheckedChanged(object sender, EventArgs e)
    {
        if (rdb_Preterm.Checked)
        {
            rdb_Fulterm.Checked = false;
            Mul.SetActiveView(view_null);
        }
    }

    protected void rdb_Fulterm_CheckedChanged(object sender, EventArgs e)
    {
        if (rdb_Fulterm.Checked)
        {
            rdb_Preterm.Checked = false;
            Mul.SetActiveView(view_weeks);
        }
    }
</code>```

That's all you really should need here. As noted, no need for the triggers, you ALREADY have postback=true for the radio buttons.

Body:
I am trying to use 2 Radio buttons and swap the view according to the radio button selected, but it's not working, the page does not reload and nothing happens.
can someone tell me where is the problem?

        <%@ Page Title="" Language="C#" MasterPageFile="~/Admin Part/Admin.Master" AutoEventWireup="true" CodeBehind="DataEntry.aspx.cs" Inherits="_4Kids.Admin_Part.DataEntry" EnableEventValidation="false" %>

        <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="ajaxToolkit" %>
        <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>           <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
                                <asp:UpdatePanel ID="upd" runat="server" UpdateMode="Conditional">
                                    <ContentTemplate>

                                            <asp:RadioButton ID="rdb_Preterm" runat="server" Text="Preterm" AutoPostBack="true" OnCheckedChanged="rdb_Preterm_CheckedChanged" />
                                            <asp:RadioButton ID="rdb_Fulterm" runat="server" Text="Full term" AutoPostBack="true" OnCheckedChanged="rdb_Fulterm_CheckedChanged" />

                                            <asp:MultiView ID="Mul" runat="server">
                                                <asp:View ID="view_null" runat="server"></asp:View>
                                                <asp:View ID="view_weeks" runat="server">

                                                                <asp:Label ID="Label14" runat="server" Text="Weeks:"></asp:Label>

                                                                <asp:TextBox ID="txt_pretermWeeks" runat="server"></asp:TextBox>

                                                </asp:View>
                                            </asp:MultiView>

                                    </ContentTemplate>
                                    <Triggers>
                                        <asp:AsyncPostBackTrigger ControlID="rdb_Preterm" EventName="CheckedChanged" />
                                        <asp:AsyncPostBackTrigger ControlID="rdb_Fulterm" EventName="CheckedChanged"/>
                                    </Triggers>
                                </asp:UpdatePanel>

    </asp:Content>

Body:
A few things:
In your posted markup, I don't seen anything related to the ajaxtoolkit.

So, remove that stuff. Also, remove the post back triggers. They are really for causing OTHER update panels to trigger - and you don't have multiple panels, so dump that stuff.

You do however need the script manager due to use of the update panel.

So, we now have this:

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="upd" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table>
            <tr>
            <td style="height: 21px;">
                <asp:RadioButton ID="rdb_Preterm" runat="server"
                    Text="Preterm" AutoPostBack="true" OnCheckedChanged="rdb_Preterm_CheckedChanged" />
                <asp:RadioButton ID="rdb_Fulterm" runat="server"
                    Text="Full term" AutoPostBack="true" OnCheckedChanged="rdb_Fulterm_CheckedChanged" />
            </td>
            <td style="height: 21px;">
                <asp:MultiView ID="Mul" runat="server">
                    <asp:View ID="view_null" runat="server"></asp:View>
                    <asp:View ID="view_weeks" runat="server">
                        <table>
                            <tr>
                                <td>
                                    <asp:Label ID="Label14" runat="server" Text="Weeks:"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txt_pretermWeeks" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                        </table>
                    </asp:View>
                </asp:MultiView>
            </td>
            </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>

And you code behind can be this:

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void rdb_Preterm_CheckedChanged(object sender, EventArgs e)
    {
        if (rdb_Preterm.Checked)
        {
            rdb_Fulterm.Checked = false;
            Mul.SetActiveView(view_null);
        }
    }

    protected void rdb_Fulterm_CheckedChanged(object sender, EventArgs e)
    {
        if (rdb_Fulterm.Checked)
        {
            rdb_Preterm.Checked = false;
            Mul.SetActiveView(view_weeks);
        }
    }

That's all you really should need here. As noted, no need for the triggers, you ALREADY have postback=true for the radio buttons.


问:
Spring Security custom form login not working with custom loginProcessingUrl, returns 404
My project is using Spring Boot 1.5.6, the goal is to have two separate login forms, one for standard users and one for admins.

My problem is that Spring ignores the config paramter for loginProcessingUrl, for the admin as well as for the user area.
It looks like there's never a handler registered for the POST request?

The config below is an adapted version from this tutorial:
http://www.baeldung.com/spring-security-two-login-pages

WebSecurityConfig

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Configuration
    @Order(1)
    public static class AdminSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        DaoAuthenticationProvider daoAuthenticationProvider;

        public AdminSecurityConfigurationAdapter() {
            super();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(daoAuthenticationProvider);
        }

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                .antMatcher("/admin/*")
                  .authorizeRequests()
                  .anyRequest()
                  .hasRole("ADMIN")

                  .and()
                  .formLogin()
                  .loginPage("/loginAdmin")
                  .loginProcessingUrl("/doAdminLogin")
                  .failureUrl("/loginAdmin?error=loginError")
                  .defaultSuccessUrl("/admin/dashboard")

                   //TODO implement logout pages
                  .and()
                  .logout()
                  .logoutUrl("/admin_logout")
                  .logoutSuccessUrl("/protectedLinks")
                  .deleteCookies("JSESSIONID")

                  .and()
                  .exceptionHandling()
                  .accessDeniedPage("/403")

                  .and()
                  .csrf().disable();
            }
    }

    @Configuration
    @Order(2)
    public static class UserSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

            @Autowired
            DaoAuthenticationProvider daoAuthenticationProvider;

        public UserSecurityConfigurationAdapter() {
            super();
        }

            @Override
            protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.authenticationProvider(daoAuthenticationProvider);
            }

        protected void configure(HttpSecurity http) throws Exception {
            http
            .antMatcher("/user/*")
              .authorizeRequests()
              .anyRequest()
              .hasRole("USER")

              .and()
              .formLogin()
              .loginPage("/loginUser")
              .loginProcessingUrl("/doUserLogin")
              .failureUrl("/loginUser?error=loginError")
              .defaultSuccessUrl("/user/start")

              //TODO configure logout
              .and()
              .logout()
              .logoutUrl("/user_logout")
              .logoutSuccessUrl("/protectedLinks")
              .deleteCookies("JSESSIONID")

              .and()
              .exceptionHandling()
              .accessDeniedPage("/403")

              .and()
              .csrf().disable();
        }
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(encoder());
        return authProvider;
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(11);
    }
</code>```

Here's the relevant part of loginAdmin.html:

```<code><form name="f" action="doAdminLogin" method="POST">
  <input type="text" name="username" placeholder="Username" required="">
  <input type="password" name="password" placeholder="Passwort" required="">
  <button class="btn1">Submit</button>
</form>
</code>```

(The version for loginUser.html is basically the same, so I'll omit it here.)

After clicking the Submit button, Spring returns just returns a 404 message. Here's the debug log for the POST request:

Reqest Log

```<code>o.s.b.w.f.OrderedRequestContextFilter    : Bound request context to thread: org.apache.catalina.connector.RequestFacade@3da35d95
o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/doAdminLogin'; against '/admin/*'
o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/doAdminLogin'; against '/user/*'
o.s.security.web.FilterChainProxy        : /doAdminLogin has no matching filters
o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/doAdminLogin]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /doAdminLogin
s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/doAdminLogin]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/doAdminLogin] are [/**]
o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/doAdminLogin] are {}
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/doAdminLogin] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@1bdb3e41]]] and 1 interceptor
o.s.web.cors.DefaultCorsProcessor        : Skip CORS processing: request is from same origin
o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
o.s.web.servlet.DispatcherServlet        : Successfully completed request
</code>```

Below is the part of the startup log regarding the RequestMappingHandlers:

Startup Log

```<code>s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/admin || /admin/dashboard]}" onto public java.lang.String org.app.controller.web.DashboardController.dashboard(java.lang.String,org.springframework.ui.Model)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/loginUser]}" onto public java.lang.String org.app.controller.web.LoginController.loginUser()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/loginAdmin]}" onto public java.lang.String org.app.controller.web.LoginController.loginAdmin()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/rsvp]}" onto public java.lang.String org.app.controller.web.RsvpController.dashboard(java.lang.String,org.springframework.ui.Model)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

It looks to me like the loginProcessingUrl config parameters just gets lost?

Any help would be greatly appreciated!

答:
I've reproduced similar issue using configuration in format:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .antMatchers("/templates/**").permitAll()
            .antMatchers("/login").permitAll()
            .and().formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/login").defaultSuccessUrl("/products/")
            .permitAll().and()
            .logout()
            .logoutSuccessUrl("/login")
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .and()
            .authorizeRequests()
            .anyRequest()
            .authenticated();

}
</code>```

when parameter loginProcessingUrl in combination with defaultSuccessUrl was ignored by Spring and I had 404 after login.

In my specific use case I've fixed it using another form of defaultSuccessUrl for loginProcessingUrl:

```<code>.loginProcessingUrl("/login").defaultSuccessUrl("/products/", true)
</code>```

instead of:

```<code>.loginProcessingUrl("/login").defaultSuccessUrl("/products/")
</code>```

as stated in examples here and here.

And there is what documentation says about the difference between the usage of these two forms of defaultSuccessUrl:

public final T defaultSuccessUrl(String defaultSuccessUrl)

Specifies where users will go after authenticating successfully if they have not visited a secured page prior to authenticating. This is
a shortcut for calling defaultSuccessUrl(String).

and:

public final T defaultSuccessUrl(String defaultSuccessUrl,
boolean alwaysUse)

Specifies where users will go after authenticating successfully if they have not
visited a secured page prior to authenticating or alwaysUse is true.
This is a shortcut for calling
successHandler(AuthenticationSuccessHandler).

Body:
My project is using Spring Boot 1.5.6, the goal is to have two separate login forms, one for standard users and one for admins.

My problem is that Spring ignores the config paramter for loginProcessingUrl, for the admin as well as for the user area.
It looks like there's never a handler registered for the POST request?

The config below is an adapted version from this tutorial:
http://www.baeldung.com/spring-security-two-login-pages

WebSecurityConfig

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Configuration
    @Order(1)
    public static class AdminSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        DaoAuthenticationProvider daoAuthenticationProvider;

        public AdminSecurityConfigurationAdapter() {
            super();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(daoAuthenticationProvider);
        }

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                .antMatcher("/admin/*")
                  .authorizeRequests()
                  .anyRequest()
                  .hasRole("ADMIN")

                  .and()
                  .formLogin()
                  .loginPage("/loginAdmin")
                  .loginProcessingUrl("/doAdminLogin")
                  .failureUrl("/loginAdmin?error=loginError")
                  .defaultSuccessUrl("/admin/dashboard")

                   //TODO implement logout pages
                  .and()
                  .logout()
                  .logoutUrl("/admin_logout")
                  .logoutSuccessUrl("/protectedLinks")
                  .deleteCookies("JSESSIONID")

                  .and()
                  .exceptionHandling()
                  .accessDeniedPage("/403")

                  .and()
                  .csrf().disable();
            }
    }

    @Configuration
    @Order(2)
    public static class UserSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

            @Autowired
            DaoAuthenticationProvider daoAuthenticationProvider;

        public UserSecurityConfigurationAdapter() {
            super();
        }

            @Override
            protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.authenticationProvider(daoAuthenticationProvider);
            }

        protected void configure(HttpSecurity http) throws Exception {
            http
            .antMatcher("/user/*")
              .authorizeRequests()
              .anyRequest()
              .hasRole("USER")

              .and()
              .formLogin()
              .loginPage("/loginUser")
              .loginProcessingUrl("/doUserLogin")
              .failureUrl("/loginUser?error=loginError")
              .defaultSuccessUrl("/user/start")

              //TODO configure logout
              .and()
              .logout()
              .logoutUrl("/user_logout")
              .logoutSuccessUrl("/protectedLinks")
              .deleteCookies("JSESSIONID")

              .and()
              .exceptionHandling()
              .accessDeniedPage("/403")

              .and()
              .csrf().disable();
        }
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(encoder());
        return authProvider;
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(11);
    }

Here's the relevant part of loginAdmin.html:

<form name="f" action="doAdminLogin" method="POST">
  <input type="text" name="username" placeholder="Username" required="">
  <input type="password" name="password" placeholder="Passwort" required="">
  <button class="btn1">Submit</button>
</form>

(The version for loginUser.html is basically the same, so I'll omit it here.)

After clicking the Submit button, Spring returns just returns a 404 message. Here's the debug log for the POST request:

Reqest Log

o.s.b.w.f.OrderedRequestContextFilter    : Bound request context to thread: org.apache.catalina.connector.RequestFacade@3da35d95
o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/doAdminLogin'; against '/admin/*'
o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/doAdminLogin'; against '/user/*'
o.s.security.web.FilterChainProxy        : /doAdminLogin has no matching filters
o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/doAdminLogin]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /doAdminLogin
s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/doAdminLogin]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/doAdminLogin] are [/**]
o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/doAdminLogin] are {}
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/doAdminLogin] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@1bdb3e41]]] and 1 interceptor
o.s.web.cors.DefaultCorsProcessor        : Skip CORS processing: request is from same origin
o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
o.s.web.servlet.DispatcherServlet        : Successfully completed request

Below is the part of the startup log regarding the RequestMappingHandlers:

Startup Log

s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/admin || /admin/dashboard]}" onto public java.lang.String org.app.controller.web.DashboardController.dashboard(java.lang.String,org.springframework.ui.Model)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/loginUser]}" onto public java.lang.String org.app.controller.web.LoginController.loginUser()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/loginAdmin]}" onto public java.lang.String org.app.controller.web.LoginController.loginAdmin()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/rsvp]}" onto public java.lang.String org.app.controller.web.RsvpController.dashboard(java.lang.String,org.springframework.ui.Model)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

It looks to me like the loginProcessingUrl config parameters just gets lost?

Any help would be greatly appreciated!

Body:
I've reproduced similar issue using configuration in format:

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .antMatchers("/templates/**").permitAll()
            .antMatchers("/login").permitAll()
            .and().formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/login").defaultSuccessUrl("/products/")
            .permitAll().and()
            .logout()
            .logoutSuccessUrl("/login")
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .and()
            .authorizeRequests()
            .anyRequest()
            .authenticated();

}

when parameter loginProcessingUrl in combination with defaultSuccessUrl was ignored by Spring and I had 404 after login.

In my specific use case I've fixed it using another form of defaultSuccessUrl for loginProcessingUrl:

.loginProcessingUrl("/login").defaultSuccessUrl("/products/", true)

instead of:

.loginProcessingUrl("/login").defaultSuccessUrl("/products/")

as stated in examples here and here.

And there is what documentation says about the difference between the usage of these two forms of defaultSuccessUrl:

public final T defaultSuccessUrl(String defaultSuccessUrl)

Specifies where users will go after authenticating successfully if they have not visited a secured page prior to authenticating. This is
a shortcut for calling defaultSuccessUrl(String).

and:

public final T defaultSuccessUrl(String defaultSuccessUrl,
boolean alwaysUse)

Specifies where users will go after authenticating successfully if they have not
visited a secured page prior to authenticating or alwaysUse is true.
This is a shortcut for calling
successHandler(AuthenticationSuccessHandler).


问:
Sum two columns to a third one of DataGridView. How?
How can I sum the values of two dataGridView columns and store the result in a third column for each row ? </p>

答:
Where do you get the data for the Grid? from a datatable? If yes, you can add another column to the datatable and set the "Expression" property of the newly created datatablecolumn to the sum of other two columns that you already have. You might want to do the following:</p>

```<code><yourDataTable>.Columns.Add("yourNewSumColumnName");
<yourDataTable.Columns["yourSumColumnName"].Expression = "<yourExistingCol1> +  <yourExistingCol2>"
</code>```

Body:
Where do you get the data for the Grid? from a datatable? If yes, you can add another column to the datatable and set the "Expression" property of the newly created datatablecolumn to the sum of other two columns that you already have. You might want to do the following:

<yourDataTable>.Columns.Add("yourNewSumColumnName");
<yourDataTable.Columns["yourSumColumnName"].Expression = "<yourExistingCol1> +  <yourExistingCol2>"


问:
Joining a calendar table on date to a table of items returns all NULLS (adding missing dates to table by a group)
I am trying to join a table of dates to an existing table of items.  I want to add the missing dates for each item see items table:

original dataset

```<code>date    item    price
1/1/2018    toys    22.82
1/3/2018    toys    28.99
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/4/2018    shoes   62.74
1/10/2018   shoes   35.16
</code>```

I need to fill in missing dates for each item with a NULL price so then I can estimate it
so I want this result:
result wanted

```<code>date    item    price
1/1/2018    toys    22.82
1/2/2018    toys    NULL
1/3/2018    toys    28.99
1/4/2018    toys    NULL
1/5/2018    toys    NULL
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/3/2018    shoes   NULL
1/4/2018    shoes   62.74
1/5/2018    shoes   NULL
1/6/2018    shoes   NULL
1/7/2018    shoes   NULL
1/8/2018    shoes   NULL
1/9/2018    shoes   NULL
1/10/2018   shoes   35.16
</code>```

I have tried the following:

```<code>    select c.day, e.item, e.price
from db.days c cross join
     (select distinct item from db.items e)
     left join
     db.items e
     on c.day = e.date_added;
</code>```

It gives me the following:
result

```<code>date    item    price
1/1/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/7/2018    NULL    NULL
1/8/2018    NULL    NULL
1/9/2018    NULL    NULL
1/10/2018   NULL    NULL
</code>```

How can I get rid of the NULLs and get my desired result above? I am using SQLite Studio

答:
Try this, I think it will work =)

```<code>   select c.day, e.item,
   (select price
    from items i
    where i.date_added = c.day and i.item = e.item) price
   from days c left join (select distinct item, min(date_added) min_date, max(date_added) max_date from items group by item) e
   where (c.day BETWEEN  min_date and max_date)
   order by item, day
</code>```

Scripts:

```<code>create table days (day date);

INSERT INTO days ("day") VALUES ('2022-01-06');
INSERT INTO days ("day") VALUES ('2022-02-06');
INSERT INTO days ("day") VALUES ('2022-03-06');
INSERT INTO days ("day") VALUES ('2022-04-06');
INSERT INTO days ("day") VALUES ('2022-05-06');
INSERT INTO days ("day") VALUES ('2022-06-06');
INSERT INTO days ("day") VALUES ('2022-07-06');
INSERT INTO days ("day") VALUES ('2022-08-06');
INSERT INTO days ("day") VALUES ('2022-09-06');
INSERT INTO days ("day") VALUES ('2022-10-06');
INSERT INTO days ("day") VALUES ('2022-11-06');
INSERT INTO days ("day") VALUES ('2022-12-06');

create table items (item varchar(20), price numeric(12,6), date_added date);

INSERT INTO items (item,price,date_added) VALUES ('toys',22.82,'2022-01-06');
INSERT INTO items (item,price,date_added) VALUES ('toys',28.99,'2022-03-06');
INSERT INTO items (item,price,date_added) VALUES ('shoes',32.56,'2022-06-06');
INSERT INTO items (item,price,date_added) VALUES ('shoes',62.74,'2022-04-06');
INSERT INTO items (item,price,date_added) VALUES ('shoes',35.16,'2022-10-06');
INSERT INTO items (item,price,date_added) VALUES ('toys',28.99,'2022-06-06');
</code>```

Body:
I am trying to join a table of dates to an existing table of items.  I want to add the missing dates for each item see items table:

original dataset

date    item    price
1/1/2018    toys    22.82
1/3/2018    toys    28.99
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/4/2018    shoes   62.74
1/10/2018   shoes   35.16

I need to fill in missing dates for each item with a NULL price so then I can estimate it
so I want this result:
result wanted

date    item    price
1/1/2018    toys    22.82
1/2/2018    toys    NULL
1/3/2018    toys    28.99
1/4/2018    toys    NULL
1/5/2018    toys    NULL
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/3/2018    shoes   NULL
1/4/2018    shoes   62.74
1/5/2018    shoes   NULL
1/6/2018    shoes   NULL
1/7/2018    shoes   NULL
1/8/2018    shoes   NULL
1/9/2018    shoes   NULL
1/10/2018   shoes   35.16

I have tried the following:

    select c.day, e.item, e.price
from db.days c cross join
     (select distinct item from db.items e)
     left join
     db.items e
     on c.day = e.date_added;

It gives me the following:
result

date    item    price
1/1/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/7/2018    NULL    NULL
1/8/2018    NULL    NULL
1/9/2018    NULL    NULL
1/10/2018   NULL    NULL

How can I get rid of the NULLs and get my desired result above? I am using SQLite Studio

Body:
Try this, I think it will work =)

   select c.day, e.item,
   (select price
    from items i
    where i.date_added = c.day and i.item = e.item) price
   from days c left join (select distinct item, min(date_added) min_date, max(date_added) max_date from items group by item) e
   where (c.day BETWEEN  min_date and max_date)
   order by item, day

Scripts:

create table days (day date);

INSERT INTO days ("day") VALUES ('2022-01-06');
INSERT INTO days ("day") VALUES ('2022-02-06');
INSERT INTO days ("day") VALUES ('2022-03-06');
INSERT INTO days ("day") VALUES ('2022-04-06');
INSERT INTO days ("day") VALUES ('2022-05-06');
INSERT INTO days ("day") VALUES ('2022-06-06');
INSERT INTO days ("day") VALUES ('2022-07-06');
INSERT INTO days ("day") VALUES ('2022-08-06');
INSERT INTO days ("day") VALUES ('2022-09-06');
INSERT INTO days ("day") VALUES ('2022-10-06');
INSERT INTO days ("day") VALUES ('2022-11-06');
INSERT INTO days ("day") VALUES ('2022-12-06');

create table items (item varchar(20), price numeric(12,6), date_added date);

INSERT INTO items (item,price,date_added) VALUES ('toys',22.82,'2022-01-06');
INSERT INTO items (item,price,date_added) VALUES ('toys',28.99,'2022-03-06');
INSERT INTO items (item,price,date_added) VALUES ('shoes',32.56,'2022-06-06');
INSERT INTO items (item,price,date_added) VALUES ('shoes',62.74,'2022-04-06');
INSERT INTO items (item,price,date_added) VALUES ('shoes',35.16,'2022-10-06');
INSERT INTO items (item,price,date_added) VALUES ('toys',28.99,'2022-06-06');


问:
How to validate AWS Cognito JWT in .NET Core Web API using .AddJwtBearer()
I was having some trouble figuring out how to go about validating a JWT given to the client by AWS Cognito inside my .NET Core Web API.

Not only could I not figure out what the variables for Microsoft.IdentityModel.Tokens.TokenValidationParameters were supposed to be, but once I finally did, I didn't know how to retrieve the JWT key set from https://cognito-idp.{region}.amazonaws.com/{pool ID}/.well-known/jwks.json

Finally, though a lot of random Googling and trial and error, I found a (seemingly-not-very-efficient solution) solution. However, I spent way too much time doing it. Citing that, plus the fact that AWS documentation on the subject is severely lacking, I decided to post this Q&A to help others find this solution more easily in the future.

If there's a better way to do this, somebody please tell me because I have yet to find a way to do this besides my answer listed below.

答:
This has been easily the most difficult bit of code I've had to work with in the last year. "Authenticating JWT tokens from AWS Cognito in a .NET Web API app". AWS documentation still leaves much to be desired.

Here's what I used for a new .NET 6 Web API solution (so Startup.cs is now contained within Program.cs. Adjust to fit your version of .NET if needed. Main difference vs .NET 5 and earlier is the Services object is accessed via a variable called builder, so anytime you see code like services.SomeMethod..., you can likely replace it with builder.Services.SomeMethod... to make it .NET 6-compatible):

```<code>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = "https://cognito-idp.{aws region here}.amazonaws.com/{Cognito UserPoolId here}",
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateLifetime = true,
            ValidAudience = "{Cognito AppClientId here}",
            ValidateAudience = false
        };

        options.MetadataAddress = "https://cognito-idp.{aws region here}.amazonaws.com/{Cognito UserPoolId here}/.well-known/openid-configuration";
    });
</code>```

Note that I have ValidateAudience set to false. I was getting 401 Unauthorized responses from the .NET app otherwise. Someone else on SO has said they had to do this to get OAuth's Authentication/Authentication Code grant type to work. Evidently ValidateAudience = true will work just fine for implicit grant, however implicit grant is regarded as deprecated by most and you should try to avoid it if possible.

Also note that I am setting options.MetadataAddress. Per another SO user, this apparently allows for behind the scenes caching of the signing keys from AWS that they rotate from time to time.

I was led astray by some official AWS documentation (boo) that had me using builder.Services.AddCognitoIdentity(); (services.AddCognitoIdentity(); for .NET 5 and earlier). Apparently this is for "ASP.NET" apps where the backend serves up the frontend (e.g. Razor/Blazor). Or maybe it's deprecated, who knows. It is on AWS's website so it could very well be deprecated...

As for the Controllers, a simple [Authorize] attribute at the class level sufficed. No need to specify "Bearer" as the AuthenticationScheme in the [Authorize] attribute, or create middleware.

If you want to skip having to add another using to every controller as well as the [Authorize] attribute, and you want every endpoint in every controller to require a JWT, you can put this in Startup/Program.cs:

```<code>builder.Services.AddControllers(opt =>
{
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    opt.Filters.Add(new AuthorizeFilter(policy));
});
</code>```

Make sure that in Program.cs (Startup.cs for .NET 5 and earlier) app.UseAuthentication comes before app.UseAuthorization().

Here are the usings in Program.cs/Startup.cs:

```<code>using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.IdentityModel.Tokens;
</code>```

Body:
This has been easily the most difficult bit of code I've had to work with in the last year. "Authenticating JWT tokens from AWS Cognito in a .NET Web API app". AWS documentation still leaves much to be desired.

Here's what I used for a new .NET 6 Web API solution (so Startup.cs is now contained within Program.cs. Adjust to fit your version of .NET if needed. Main difference vs .NET 5 and earlier is the Services object is accessed via a variable called builder, so anytime you see code like services.SomeMethod..., you can likely replace it with builder.Services.SomeMethod... to make it .NET 6-compatible):

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = "https://cognito-idp.{aws region here}.amazonaws.com/{Cognito UserPoolId here}",
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateLifetime = true,
            ValidAudience = "{Cognito AppClientId here}",
            ValidateAudience = false
        };

        options.MetadataAddress = "https://cognito-idp.{aws region here}.amazonaws.com/{Cognito UserPoolId here}/.well-known/openid-configuration";
    });

Note that I have ValidateAudience set to false. I was getting 401 Unauthorized responses from the .NET app otherwise. Someone else on SO has said they had to do this to get OAuth's Authentication/Authentication Code grant type to work. Evidently ValidateAudience = true will work just fine for implicit grant, however implicit grant is regarded as deprecated by most and you should try to avoid it if possible.

Also note that I am setting options.MetadataAddress. Per another SO user, this apparently allows for behind the scenes caching of the signing keys from AWS that they rotate from time to time.

I was led astray by some official AWS documentation (boo) that had me using builder.Services.AddCognitoIdentity(); (services.AddCognitoIdentity(); for .NET 5 and earlier). Apparently this is for "ASP.NET" apps where the backend serves up the frontend (e.g. Razor/Blazor). Or maybe it's deprecated, who knows. It is on AWS's website so it could very well be deprecated...

As for the Controllers, a simple [Authorize] attribute at the class level sufficed. No need to specify "Bearer" as the AuthenticationScheme in the [Authorize] attribute, or create middleware.

If you want to skip having to add another using to every controller as well as the [Authorize] attribute, and you want every endpoint in every controller to require a JWT, you can put this in Startup/Program.cs:

builder.Services.AddControllers(opt =>
{
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    opt.Filters.Add(new AuthorizeFilter(policy));
});

Make sure that in Program.cs (Startup.cs for .NET 5 and earlier) app.UseAuthentication comes before app.UseAuthorization().

Here are the usings in Program.cs/Startup.cs:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.IdentityModel.Tokens;


问:
Why is '.vue' loader not found by Vite when using Vue 3 migration build?
I'm attempting to upgrade a Vue 2 project to Vue 3 using the migration build and vite (https://v3-migration.vuejs.org/breaking-changes/migration-build.html#overview)

I've done steps 1-4 (though skipped 4, since not using typescript).  At this point, I get the following error:

```<code>src/main.js:3:16: error: No loader is configured for ".vue" files: src/App.vue
</code>```

Despite the message, the issue appears to be with the @ alias, because if I change import App from '@/App.vue'; to import App from './App.vue'; in main.js it works fine.  Any ideas?  I have tried changing the alias to /src/ as well.

On the one hand, that seems like an easy fix, but on the other there are a bunch of other imports throughout the project that would have to be rewritten.

main.js:

```<code>import Vue from 'vue';
import App from '@/App.vue';

Vue.config.productionTip = false;

let app = new Vue({
  render: h => h(App)
}).$mount('#app');
</code>```

vite.config.js

```<code>import { defineConfig } from 'vite';
import createVuePlugin from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
  plugins: [
      createVuePlugin({
        template: {
          compilerOptions: {
            compatConfig: {
              MODE: 2
            }
          }
        }
      }),
    ],
  resolve: {
    alias: {
      '@/': path.resolve(__dirname, './src/'),
      'vue': '@vue/compat',
    },
  },
});
</code>```

package.json

```<code>{
  "name": "xxx",
  "version": "0.1.0",
  "dependencies": {
    "@vue/compat": "^3.1.0",
    "vue": "^3.1.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.2.2",
    "@vue/compiler-sfc": "^3.1.0",
    "vite": "^2.4.1"
  }
}
</code>```

I was unable to get a reproduction running in codesandbox (it doesn't appear to like the alias statements in vite.config.js at all).  But this repo shows the behavior: https://github.com/dovrosenberg/vite-vue-alias-issue

The error changes sometimes (for no reason apparent to me) when using this repo to:
Internal server error: Failed to resolve import "@/App.vue" from "src/main.js". Does the file exist?'

答:
The resolve.alias key for @ must not include the slash:

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  ⋮
  resolve: {
    alias: {
      // '@/': path.resolve(__dirname, './src/'), ❌
      '@': path.resolve(__dirname, './src/'), ✅
      ⋮
    },
  },
});
```

demo

Body:
I'm attempting to upgrade a Vue 2 project to Vue 3 using the migration build and vite (https://v3-migration.vuejs.org/breaking-changes/migration-build.html#overview)

I've done steps 1-4 (though skipped 4, since not using typescript).  At this point, I get the following error:

src/main.js:3:16: error: No loader is configured for ".vue" files: src/App.vue

Despite the message, the issue appears to be with the @ alias, because if I change import App from '@/App.vue'; to import App from './App.vue'; in main.js it works fine.  Any ideas?  I have tried changing the alias to /src/ as well.

On the one hand, that seems like an easy fix, but on the other there are a bunch of other imports throughout the project that would have to be rewritten.

main.js:

import Vue from 'vue';
import App from '@/App.vue';

Vue.config.productionTip = false;

let app = new Vue({
  render: h => h(App)
}).$mount('#app');

vite.config.js

import { defineConfig } from 'vite';
import createVuePlugin from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
  plugins: [
      createVuePlugin({
        template: {
          compilerOptions: {
            compatConfig: {
              MODE: 2
            }
          }
        }
      }),
    ],
  resolve: {
    alias: {
      '@/': path.resolve(__dirname, './src/'),
      'vue': '@vue/compat',
    },
  },
});

package.json

{
  "name": "xxx",
  "version": "0.1.0",
  "dependencies": {
    "@vue/compat": "^3.1.0",
    "vue": "^3.1.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.2.2",
    "@vue/compiler-sfc": "^3.1.0",
    "vite": "^2.4.1"
  }
}

I was unable to get a reproduction running in codesandbox (it doesn't appear to like the alias statements in vite.config.js at all).  But this repo shows the behavior: https://github.com/dovrosenberg/vite-vue-alias-issue

The error changes sometimes (for no reason apparent to me) when using this repo to:
Internal server error: Failed to resolve import "@/App.vue" from "src/main.js". Does the file exist?'

Body:
The resolve.alias key for @ must not include the slash:

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  ⋮
  resolve: {
    alias: {
      // '@/': path.resolve(__dirname, './src/'), ❌
      '@': path.resolve(__dirname, './src/'), ✅
      ⋮
    },
  },
});

demo


问:
Importing multiple objects with ObjectInputStream
After implementing the suggestions I was given on my last post, I now have a working piece of code without any error messages, but my code will still only print the first object from my file. I would be grateful for any suggestions.

```<code>import java.io.*;
import java.util.*;

public class Mainclass {
    public static void main(String[] args) {

        InputStream is;
        try {
            is = new FileInputStream("or.rtf");

            ObjectInputStream ois;
            try {

                int l = 1;
                ois = new ObjectInputStream(is);

                while (l > 0) {

                    try {

                        Stone p = (Stone) ois.readObject();
                        System.out.println(p);

                    }   catch(Exception e) {
                            if(e instanceof EOFException) {
                                l--;
                                System.err.println();
                            } else if(e instanceof FileNotFoundException) {
                                l--;
                                System.err.println(e);
                            } else {
                                System.err.println(e);
                            }
                    }
                }
                ois.close();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
</code>```

Code to save objects to a file:

```<code>import java.io.*;
import java.util.*;

public class Saver {
    public static void main(String[] args) {

        ArrayList<Stone> objects = new ArrayList<Stone>();
        objects.add(new Stone("Max",50,90));
        objects.add(new Stone("Fiona",30,60));
        objects.add(new Stone("Sam",20,30));

        for (int i = 0; i < objects.size(); i++ ) {

            try {
            OutputStream os = new FileOutputStream("qt.rtf");
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(objects.get(i));
            System.out.println(i);
            oos.close();
        }   catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}
</code>```

I implemented the println(i) to check whether the code was even executed in a loop.

答:
Change the scope of ObjectOutputStream and FileOutputStream.

```<code>    public static void main(String[] args) {
        ArrayList<Stone> objects = new ArrayList<Stone>();
        objects.add(new Stone("Max",50,90));
        objects.add(new Stone("Fiona",30,60));
        objects.add(new Stone("Sam",20,30));

        try {
            OutputStream os = new FileOutputStream("qt.rtf");
            ObjectOutputStream oos = new ObjectOutputStream(os);

            for (int i = 0; i < objects.size(); i++ ) {
                oos.writeObject(objects.get(i));
                System.out.println(i);
            }
            oos.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}
</code>```

You are also not reading from the same file you created or.rtf and qr.rtf.

Body:
After implementing the suggestions I was given on my last post, I now have a working piece of code without any error messages, but my code will still only print the first object from my file. I would be grateful for any suggestions.

import java.io.*;
import java.util.*;

public class Mainclass {
    public static void main(String[] args) {

        InputStream is;
        try {
            is = new FileInputStream("or.rtf");

            ObjectInputStream ois;
            try {

                int l = 1;
                ois = new ObjectInputStream(is);

                while (l > 0) {

                    try {

                        Stone p = (Stone) ois.readObject();
                        System.out.println(p);

                    }   catch(Exception e) {
                            if(e instanceof EOFException) {
                                l--;
                                System.err.println();
                            } else if(e instanceof FileNotFoundException) {
                                l--;
                                System.err.println(e);
                            } else {
                                System.err.println(e);
                            }
                    }
                }
                ois.close();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

Code to save objects to a file:

import java.io.*;
import java.util.*;

public class Saver {
    public static void main(String[] args) {

        ArrayList<Stone> objects = new ArrayList<Stone>();
        objects.add(new Stone("Max",50,90));
        objects.add(new Stone("Fiona",30,60));
        objects.add(new Stone("Sam",20,30));

        for (int i = 0; i < objects.size(); i++ ) {

            try {
            OutputStream os = new FileOutputStream("qt.rtf");
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(objects.get(i));
            System.out.println(i);
            oos.close();
        }   catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}

I implemented the println(i) to check whether the code was even executed in a loop.

Body:
Change the scope of ObjectOutputStream and FileOutputStream.

    public static void main(String[] args) {
        ArrayList<Stone> objects = new ArrayList<Stone>();
        objects.add(new Stone("Max",50,90));
        objects.add(new Stone("Fiona",30,60));
        objects.add(new Stone("Sam",20,30));

        try {
            OutputStream os = new FileOutputStream("qt.rtf");
            ObjectOutputStream oos = new ObjectOutputStream(os);

            for (int i = 0; i < objects.size(); i++ ) {
                oos.writeObject(objects.get(i));
                System.out.println(i);
            }
            oos.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

You are also not reading from the same file you created or.rtf and qr.rtf.


问:
Intervention/image plugin does not work on Docker Laravel image
I combined Laravel, Nginx, and MySQL in one docker image. Everything is fine except images are not showing when I deploy docker image.

When I have several tests on my local PC with Laravel source, the intervention images are successfully shown.

On the docker image, the intervention images are like this on inspect dialog.

```<code><img class="lazy" src="/img/placeholder.png" data-src="/assets/logos/c200x90/hallon.png" width="100" height="45" alt="Hallon">
</code>```

And on my local PC, the intervention image looks like this on inspect dialog

```<code><img class="lazy" src="/assets/logos/c200x90/hallon.png" width="100" height="45" alt="Hallon" style="">
</code>```

Even though Laravel sources are the same, I don't know why this happened?

答:
I think that is the php setting problem.

Try to add the following config cmd to php.ini.

extension=gd

Let me know if it works or not.

Body:
I combined Laravel, Nginx, and MySQL in one docker image. Everything is fine except images are not showing when I deploy docker image.

When I have several tests on my local PC with Laravel source, the intervention images are successfully shown.

On the docker image, the intervention images are like this on inspect dialog.

And on my local PC, the intervention image looks like this on inspect dialog

Even though Laravel sources are the same, I don't know why this happened?