问:
How to dynamicaly generate variable names depending on 3 predefined lists (f'{list1}_{list2}_{list3} ') in Python?
I read many questions/answers, but it does not really fit with what I'm looking for...

Here's the "story" : I'm anonymizing 1000 time series and now, I need to analyze how it looks like between real patient time series and the anonymized ones. I have the following parameters to test :

```<code>list_patient = ['pa', 'pr']   # pa = anonymized patients / pr = real patients
list_param = ['avg', 'std', 'med', 'max', 'min'] # Measures that I want to do
list_param_physio = ['FC', 'PAS', 'PAM', 'PAD'] # Physiological parameters such as cardiac frequency (FC)
</code>```

And I would definitely prefer to avoid this... : "3 lessons to make developers cry..." or how looks like a big part of my code without automation.

Just a taste of it :

```<code>avg_pa_fc, avg_pa_pas, avg_pa_pam, avg_pa_pad, std_pa_fc, std_pa_pas, std_pa_pam, std_pa_pad = ([] for i in range(8))
med_pa_fc, med_pa_pas, med_pa_pam, med_pa_pad = ([] for i in range(4))
min_pa_fc, min_pa_pas, min_pa_pam, min_pa_pad, max_pa_fc, max_pa_pas, max_pa_pam, max_pa_pad = ([] for i in range(8))
...
# Calculte means and stdev for each pa file, add it to a np.array and convert it to a pd.df
avg_pa_fc, std_pa_fc = pd.DataFrame(np.append(avg_pa_fc, (statistics.mean(pa_series_fc)))), pd.DataFrame(np.append(std_pa_fc, (statistics.stdev(pa_series_fc))))
avg_pa_pas, std_pa_pas = pd.DataFrame(np.append(avg_pa_pas, (statistics.mean(pa_series_pas)))), pd.DataFrame(np.append(std_pa_pas, (statistics.stdev(pa_series_pas))))
avg_pa_pam, std_pa_pam = pd.DataFrame(np.append(avg_pa_pam, (statistics.mean(pa_series_pam)))), pd.DataFrame(np.append(std_pa_pam, (statistics.stdev(pa_series_pam))))
avg_pa_pad, std_pa_pad = pd.DataFrame(np.append(avg_pa_pad, (statistics.mean(pa_series_pad)))), pd.DataFrame(np.append(std_pa_pad, (statistics.stdev(pa_series_pad))))

</code>```

So, I would like to create automatically some empty lists with this format : {list1}_{list2}_{list3} = [] (underscores are between lists as below)

I tried many things, such as :

```<code>list = []
for i in range(40):
    list.append(f'{list_param}_{list_patient}_{list_param_physio}')
    print(list)
# Output : ["['pa', 'pr']_['avg', 'std', 'med', 'max', 'min']_['FC', 'PAS', 'PAM', 'PAD']", "['pa', 'pr']_....

for param, patient, param_phy in enumerate(list_param, list_patient, list_param_physio):
    list.append(f'{param}_{patient}_{param_phy}')
    print(list)
# TypeError: enumerate() takes at most 2 arguments (3 given)

# For anonymized patients :
for param, param_phy in enumerate(list_param, list_param_physio):
    list.append((f'{param}_pa_{param_phy}').aslist())
    print(list)
# TypeError: 'list' object cannot be interpreted as an integer

</code>```

I also tried to use dictionaries, but with 3 parameters, it begins to be too tricky for me...

If you have any idea, that would be great !

答:
Since you seemed in interested in my idea of using a single map to store all of your patient combinations rather than trying to create a bunch of variable names, here's an example of how to do that.  This initially sets each key(variable) to an empty list, but you can set each one to whatever you want.

```<code>import itertools
from pprint import pprint

list_patient = ['pa', 'pr']   # pa = anonymized patients / pr = real patients
list_param = ['avg', 'std', 'med', 'max', 'min'] # Measures that I want to do
list_param_physio = ['FC', 'PAS', 'PAM', 'PAD'] # Physiological parameters such as cardiac frequency (FC)

patients = {}
for patient, param, param_physio in itertools.product(list_patient, list_param, list_param_physio):
    key = f"{patient}_{param}_{param_physio}"
    patients[key] = []
pprint(patients)
</code>```

Result:

```<code>{'pa_avg_FC': [],
 'pa_avg_PAD': [],
 'pa_avg_PAM': [],
 'pa_avg_PAS': [],
 'pa_max_FC': [],
 'pa_max_PAD': [],
 'pa_max_PAM': [],
 'pa_max_PAS': [],
 'pa_med_FC': [],
 'pa_med_PAD': [],
 'pa_med_PAM': [],
 'pa_med_PAS': [],
 'pa_min_FC': [],
 'pa_min_PAD': [],
 'pa_min_PAM': [],
 'pa_min_PAS': [],
 'pa_std_FC': [],
 'pa_std_PAD': [],
 'pa_std_PAM': [],
 'pa_std_PAS': [],
 'pr_avg_FC': [],
 'pr_avg_PAD': [],
 'pr_avg_PAM': [],
 'pr_avg_PAS': [],
 'pr_max_FC': [],
 'pr_max_PAD': [],
 'pr_max_PAM': [],
 'pr_max_PAS': [],
 'pr_med_FC': [],
 'pr_med_PAD': [],
 'pr_med_PAM': [],
 'pr_med_PAS': [],
 'pr_min_FC': [],
 'pr_min_PAD': [],
 'pr_min_PAM': [],
 'pr_min_PAS': [],
 'pr_std_FC': [],
 'pr_std_PAD': [],
 'pr_std_PAM': [],
 'pr_std_PAS': []}
</code>```

Rather that reduce your data down to a flat list with complex names, you're probably better off preserving the structure.  Here's an example of how to do that.  This creates a single structure where you can access each patient, then each set of physios for that patient, and then each of the stats (avg, std, etc.) for that patient:

```<code>patients = {}
for patient_name in list_patient:
    patient = {}
    for physio_name in list_param_physio:
        physio = {}
        for param in list_param:
            physio[param] = 0.0
        patient[physio_name] = physio
    patients[patient_name] = patient
pprint(patients)
</code>```

Result:

```<code>{'pa': {'FC': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAD': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAM': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAS': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0}},
 'pr': {'FC': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAD': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAM': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAS': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0}}}
</code>```

Here's a simple example of how to use this structure.  This shows you how to set and reference the 'avg' stat for the 'FC' physio for patient 'pr':

```<code>patients['pr']['FC']['avg'] = 1234.56
print(patients['pr']['FC']['avg'])
</code>```

Result:

```<code>1234.56
</code>```

If you want all the stats for the 'PAS' physio for the 'pa' patient, that's:

```<code>pprint(patients['pa']['PAS'])
</code>```

Result:

```<code>{'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0}
</code>```

This structure will be easy to iterate over to gather or compute values within it without any of your code having any idea how many items there are at each level.

Body:
I read many questions/answers, but it does not really fit with what I'm looking for...

Here's the "story" : I'm anonymizing 1000 time series and now, I need to analyze how it looks like between real patient time series and the anonymized ones. I have the following parameters to test :

list_patient = ['pa', 'pr']   # pa = anonymized patients / pr = real patients
list_param = ['avg', 'std', 'med', 'max', 'min'] # Measures that I want to do
list_param_physio = ['FC', 'PAS', 'PAM', 'PAD'] # Physiological parameters such as cardiac frequency (FC)

And I would definitely prefer to avoid this... : "3 lessons to make developers cry..." or how looks like a big part of my code without automation.

Just a taste of it :

avg_pa_fc, avg_pa_pas, avg_pa_pam, avg_pa_pad, std_pa_fc, std_pa_pas, std_pa_pam, std_pa_pad = ([] for i in range(8))
med_pa_fc, med_pa_pas, med_pa_pam, med_pa_pad = ([] for i in range(4))
min_pa_fc, min_pa_pas, min_pa_pam, min_pa_pad, max_pa_fc, max_pa_pas, max_pa_pam, max_pa_pad = ([] for i in range(8))
...
# Calculte means and stdev for each pa file, add it to a np.array and convert it to a pd.df
avg_pa_fc, std_pa_fc = pd.DataFrame(np.append(avg_pa_fc, (statistics.mean(pa_series_fc)))), pd.DataFrame(np.append(std_pa_fc, (statistics.stdev(pa_series_fc))))
avg_pa_pas, std_pa_pas = pd.DataFrame(np.append(avg_pa_pas, (statistics.mean(pa_series_pas)))), pd.DataFrame(np.append(std_pa_pas, (statistics.stdev(pa_series_pas))))
avg_pa_pam, std_pa_pam = pd.DataFrame(np.append(avg_pa_pam, (statistics.mean(pa_series_pam)))), pd.DataFrame(np.append(std_pa_pam, (statistics.stdev(pa_series_pam))))
avg_pa_pad, std_pa_pad = pd.DataFrame(np.append(avg_pa_pad, (statistics.mean(pa_series_pad)))), pd.DataFrame(np.append(std_pa_pad, (statistics.stdev(pa_series_pad))))

So, I would like to create automatically some empty lists with this format : {list1}_{list2}_{list3} = [] (underscores are between lists as below)

I tried many things, such as :

list = []
for i in range(40):
    list.append(f'{list_param}_{list_patient}_{list_param_physio}')
    print(list)
# Output : ["['pa', 'pr']_['avg', 'std', 'med', 'max', 'min']_['FC', 'PAS', 'PAM', 'PAD']", "['pa', 'pr']_....

for param, patient, param_phy in enumerate(list_param, list_patient, list_param_physio):
    list.append(f'{param}_{patient}_{param_phy}')
    print(list)
# TypeError: enumerate() takes at most 2 arguments (3 given)

# For anonymized patients :
for param, param_phy in enumerate(list_param, list_param_physio):
    list.append((f'{param}_pa_{param_phy}').aslist())
    print(list)
# TypeError: 'list' object cannot be interpreted as an integer

I also tried to use dictionaries, but with 3 parameters, it begins to be too tricky for me...

If you have any idea, that would be great !

Body:
Since you seemed in interested in my idea of using a single map to store all of your patient combinations rather than trying to create a bunch of variable names, here's an example of how to do that.  This initially sets each key(variable) to an empty list, but you can set each one to whatever you want.

import itertools
from pprint import pprint

list_patient = ['pa', 'pr']   # pa = anonymized patients / pr = real patients
list_param = ['avg', 'std', 'med', 'max', 'min'] # Measures that I want to do
list_param_physio = ['FC', 'PAS', 'PAM', 'PAD'] # Physiological parameters such as cardiac frequency (FC)

patients = {}
for patient, param, param_physio in itertools.product(list_patient, list_param, list_param_physio):
    key = f"{patient}_{param}_{param_physio}"
    patients[key] = []
pprint(patients)

Result:

{'pa_avg_FC': [],
 'pa_avg_PAD': [],
 'pa_avg_PAM': [],
 'pa_avg_PAS': [],
 'pa_max_FC': [],
 'pa_max_PAD': [],
 'pa_max_PAM': [],
 'pa_max_PAS': [],
 'pa_med_FC': [],
 'pa_med_PAD': [],
 'pa_med_PAM': [],
 'pa_med_PAS': [],
 'pa_min_FC': [],
 'pa_min_PAD': [],
 'pa_min_PAM': [],
 'pa_min_PAS': [],
 'pa_std_FC': [],
 'pa_std_PAD': [],
 'pa_std_PAM': [],
 'pa_std_PAS': [],
 'pr_avg_FC': [],
 'pr_avg_PAD': [],
 'pr_avg_PAM': [],
 'pr_avg_PAS': [],
 'pr_max_FC': [],
 'pr_max_PAD': [],
 'pr_max_PAM': [],
 'pr_max_PAS': [],
 'pr_med_FC': [],
 'pr_med_PAD': [],
 'pr_med_PAM': [],
 'pr_med_PAS': [],
 'pr_min_FC': [],
 'pr_min_PAD': [],
 'pr_min_PAM': [],
 'pr_min_PAS': [],
 'pr_std_FC': [],
 'pr_std_PAD': [],
 'pr_std_PAM': [],
 'pr_std_PAS': []}

Rather that reduce your data down to a flat list with complex names, you're probably better off preserving the structure.  Here's an example of how to do that.  This creates a single structure where you can access each patient, then each set of physios for that patient, and then each of the stats (avg, std, etc.) for that patient:

patients = {}
for patient_name in list_patient:
    patient = {}
    for physio_name in list_param_physio:
        physio = {}
        for param in list_param:
            physio[param] = 0.0
        patient[physio_name] = physio
    patients[patient_name] = patient
pprint(patients)

Result:

{'pa': {'FC': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAD': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAM': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAS': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0}},
 'pr': {'FC': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAD': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAM': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0},
        'PAS': {'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0}}}

Here's a simple example of how to use this structure.  This shows you how to set and reference the 'avg' stat for the 'FC' physio for patient 'pr':

patients['pr']['FC']['avg'] = 1234.56
print(patients['pr']['FC']['avg'])

Result:

1234.56

If you want all the stats for the 'PAS' physio for the 'pa' patient, that's:

pprint(patients['pa']['PAS'])

Result:

{'avg': 0.0, 'max': 0.0, 'med': 0.0, 'min': 0.0, 'std': 0.0}

This structure will be easy to iterate over to gather or compute values within it without any of your code having any idea how many items there are at each level.


来源: stackexchange

问:
How to optmize integrals in numba?
I am trying to implement the Galerkin discontinous method in Python to solve Partial Differential Equations. This method involves solving a large number of systems of ordinary differential equations with the form

where the matrix $M^i$ is definied by the $L^2$ product, i.e. each entry of the matrix is an integral of the product of two functions $N_k$, and $N_l$, that is

where $I_i=[-1,1]$.

To do these integrals, I have defined the function DotProduct(G, H) as follows

```<code>from scipy.integrate import quad

def DotProduct(G, H):
    F = lambda x:G(x)*H(x)
    w = quad(F, -1.0, 1.0)[0]
return w
</code>```

The use of this function is as follows

```<code>f01 = lambda x: 0.5*(1-x)
f11 = lambda x: 0.5*(1+x)
Integral = DotProduct(f01, f11)
print(Integral)
</code>```

My problem is that 90% of the execution time of the code is dedicated to calculating these integrals.

I've read about speeding up the computation time for integrals using numba, but have had no success implementing it in the function DotProduct(G, H).

Does anyone have any advice?

答:
Almost all SciPy function are not yet supported by Numba. This includes quad. That being said, the function called by quad could be accelerated by Numba. The point is you cannot use lambda functions the way you do too because it is also not supported by Numba. You need to move f01 and f11 in the jitted function.

import numba as nb
from scipy.integrate import quad

@nb.njit
def F(x):
    G = lambda x: 0.5*(1-x)
    H = lambda x: 0.5*(1+x)
    return G(x) * H(x)

def DotProduct():
    w = quad(F, -1.0, 1.0)[0]
    return w

Integral = DotProduct()
print(Integral)
```

This is 36% faster on my machine but this is not a case where Numba is really useful... Numba can be faster at least if the F function is expensive. The initial code takes less than 6 us to complete. This is far too small.

ContentLicense: CC BY-SA 4.0

Title: How to optmize integrals in numba?

Body:
I am trying to implement the Galerkin discontinous method in Python to solve Partial Differential Equations. This method involves solving a large number of systems of ordinary differential equations with the form

where the matrix $M^i$ is definied by the $L^2$ product, i.e. each entry of the matrix is an integral of the product of two functions $N_k$, and $N_l$, that is

where $I_i=[-1,1]$.

To do these integrals, I have defined the function DotProduct(G, H) as follows

from scipy.integrate import quad

def DotProduct(G, H):
    F = lambda x:G(x)*H(x)
    w = quad(F, -1.0, 1.0)[0]
return w

The use of this function is as follows

f01 = lambda x: 0.5*(1-x)
f11 = lambda x: 0.5*(1+x)
Integral = DotProduct(f01, f11)
print(Integral)

My problem is that 90% of the execution time of the code is dedicated to calculating these integrals.

I've read about speeding up the computation time for integrals using numba, but have had no success implementing it in the function DotProduct(G, H).

Does anyone have any advice?

Body:
Almost all SciPy function are not yet supported by Numba. This includes quad. That being said, the function called by quad could be accelerated by Numba. The point is you cannot use lambda functions the way you do too because it is also not supported by Numba. You need to move f01 and f11 in the jitted function.

import numba as nb
from scipy.integrate import quad

@nb.njit
def F(x):
    G = lambda x: 0.5*(1-x)
    H = lambda x: 0.5*(1+x)
    return G(x) * H(x)

def DotProduct():
    w = quad(F, -1.0, 1.0)[0]
    return w

Integral = DotProduct()
print(Integral)

This is 36% faster on my machine but this is not a case where Numba is really useful... Numba can be faster at least if the F function is expensive. The initial code takes less than 6 us to complete. This is far too small.


问:
How do I make my NW.js application *start* in fullscreen?
I know how to enter fullscreen once it's already loaded in a window. This causes an ugly effect where, when I click its icon, briefly flashes a windowed window which immediately goes fullscreen. I hate that effect.

How do I make it actually start, right away, in fullscreen, without ever being in windowed mode even for a split second?

答: You just need to put fullscreen: true in your manifest:  https://docs.nwjs.io/en/latest/References/Manifest%20Format/#fullscreen.


问:
Hello how can I implement the following code so that it will not make a broken image?
My client won an award. To display it on a website, they sent the following html:

```

This is consistently coming back a broken image. Unsure of how to fix, other images on site work fine

答:
This worked for me:
(note: I put the <div tag on the outside)

<!doctype html>

  <meta charset="utf-8">
  <title>Test</title>

Some other text

```

Body:
My client won an award. To display it on a website, they sent the following html:

This is consistently coming back a broken image. Unsure of how to fix, other images on site work fine

Body:
This worked for me:
(note: I put the <div tag on the outside)

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body class="mat-typography">
 <div style="font-size: 10px; text-align: center; width:200px; margin:0 auto">
 <a target="_blank" href="https://www.theknot.com/marketplace/redirect-2046979" style="margin: 0 auto;">
    <img src="https://s3.amazonaws.com/tkpro-assets/bow_2022/section_4_3.png"
         width="70" height="70"
         alt="The Knot Best of Weddings - 2022 Pick"
         border="0"
         style="margin:0 auto;" >
</a>
<br>
<br>
Some other text
  </div>

</body>
</html>


问:
It's possible to use an array of property on "item-text" in Vuetify?
```<code> <v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-text="name" <!-- use here Array ['name', 'id', 'value'] -->
   item-value="name"
  >
</code>```

It's possible to use an array of property on "text-item" in Vuetify?

答:
use slots like this:</p>
```<code><v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-value="name"
  >
 <template v-slot:item="{ item }">
   {{item.name}}-{{item.id}}-{{item.value}}
 </template>
</v-autocomplete>
</code>```

Body:
 <v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-text="name"
   item-value="name"
  >

It's possible to use an array of property on "text-item" in Vuetify?

Body:
use slots like this:

<v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-value="name"
  >
 <template v-slot:item="{ item }">
   {{item.name}}-{{item.id}}-{{item.value}}
 </template>
</v-autocomplete>


问:
How to fix the error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>')
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};
```
<p>The error is happening at <code>const res = await fetch("/api/sendChoice" ,{</code></p>
<p>In terminal server the error</p>
<blockquote>
<p>error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'</p>
</blockquote>
<p>In the inspect element the error is as<br />
<img src="https://i.stack.imgur.com/15p7J.png" alt="this" /></p>
<p>I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.</p>
<p>Some other related code from my project:</p>
<p>api/sendChoice</p>
<pre class="lang-js prettyprint-override"><code>import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}
</code>```

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);
```

答:
This issue occured recently and apparently its happening with latest version of node.

issue link

So you can change the version of node to older version and it will be fixed. I am using node version v14.19.0

Body:
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};

The error is happening at const res = await fetch("/api/sendChoice" ,{

In terminal server the error

error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'

In the inspect element the error is as

I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.

Some other related code from my project:

api/sendChoice

import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);


问:
How to make image banner and two div cards responsive for every sreensize
I have an image banner with some text and buttons on top of it and two widgets right next to it in a flex (watch image for reference). I want them to be responsive when the screen changes sizes.

```<code><div className="tabs">
          <div className="tabs-container">
            <img src={MainBG} alt="background" className="banner-img" />
            <div className="top-text">
              <div>
                <h1>
                  Track Crypto Activity <br /> For Smarter Trading
                </h1>
                <button className="join-button"> Join Now</button>
                <button className="academy-button"> Crypto Academy</button>
              </div>
            </div>
          </div>
          <div className="widgets">
            <TechnicalAnalysis
              colorTheme="dark"
              width="280"
              height="305"
              symbol="BITSTAMP:BTCUSD"
            />
            <TechnicalAnalysis
              colorTheme="dark"
              width="280"
              height="305"
              symbol="BINANCE:ETHUSDT"
            />
          </div>

</code>```

How the Ui is on one screen size

Here is the current CSS:

```<code>.tabs {
  display: flex;
  overflow: scroll;
  width: 100%;
}
.banner-img {
  width: 95%;
}
.tabs-container {
  position: relative;
  margin-top: 20px;
  margin-left: 10px;
}

.top-text {
  position: absolute;
  margin-left: 30px;
  display: flex;
  justify-content: space-around;
  color: white;
  top: 50px;
}

.join-button {
  background-color: #bb46e2;
  cursor: pointer;
  color: white;
  padding: 10px;
  width: 90px;
  border-radius: 10px;
  border: none;
}

.academy-button {
  background-color: transparent;
  cursor: pointer;
  padding: 10px;
  border: 1px solid white;
  color: white;
  border-radius: 10px;
  margin-left: 15px;
}

.academy-button:hover {
  background-color: white;
  color: #bb46e2;
}

.widgets {
  display: flex;
  flex-direction: row;
  width: 50%;
  justify-content: space-between;
  margin-top: 20px;
  margin-right: 30px;
}
</code>```

How do I make these responsive for all screen sizes?

答: You can use media queries. You can use those it change the styling of elements depending on the screen size. Read the documentation here.</p>

Body:
I have an image banner with some text and buttons on top of it and two widgets right next to it in a flex (watch image for reference). I want them to be responsive when the screen changes sizes.

                  Track Crypto Activity
 For Smarter Trading

                <button className="join-button"> Join Now</button>
                <button className="academy-button"> Crypto Academy</button>

            <TechnicalAnalysis
              colorTheme="dark"
              width="280"
              height="305"
              symbol="BITSTAMP:BTCUSD"
            />
            <TechnicalAnalysis
              colorTheme="dark"
              width="280"
              height="305"
              symbol="BINANCE:ETHUSDT"
            />

How the Ui is on one screen size

Here is the current CSS:

.tabs {
  display: flex;
  overflow: scroll;
  width: 100%;
}
.banner-img {
  width: 95%;
}
.tabs-container {
  position: relative;
  margin-top: 20px;
  margin-left: 10px;
}

.top-text {
  position: absolute;
  margin-left: 30px;
  display: flex;
  justify-content: space-around;
  color: white;
  top: 50px;
}

.join-button {
  background-color: #bb46e2;
  cursor: pointer;
  color: white;
  padding: 10px;
  width: 90px;
  border-radius: 10px;
  border: none;
}

.academy-button {
  background-color: transparent;
  cursor: pointer;
  padding: 10px;
  border: 1px solid white;
  color: white;
  border-radius: 10px;
  margin-left: 15px;
}

.academy-button:hover {
  background-color: white;
  color: #bb46e2;
}

.widgets {
  display: flex;
  flex-direction: row;
  width: 50%;
  justify-content: space-between;
  margin-top: 20px;
  margin-right: 30px;
}

How do I make these responsive for all screen sizes?


问:
An Authentication object was not found in the SecurityContext - Spring 3.2.2
I'm trying to invoke a protected method from a class that implements the ApplicationListener<AuthenticationSuccessEvent> interface on successful login (Spring 3.2.2 and Spring Security 3.2.0 M1). This is my previous question.

The application runs under the following environment.

Spring 3.2.2

Spring Security 3.2.0

JPA 2.0

JSF 2.1.9

MySQL 5.6.11

JDK-7u11

NetBeans 7.2.1

I have added the following libraries related to Spring security to the classpath.

spring-security-core-3.2.0.M1.jar

spring-security-config-3.2.0.M1.jar

spring-security-web-3.2.0.M1.jar

The class that implements ApplicationListener<AuthenticationSuccessEvent> is as follows.

```<code>package loginsuccesshandler;

import admin.dao.service.StateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Service;

@Service
public final class AuthSuccessHandler implements ApplicationListener<AuthenticationSuccessEvent>
{
    @Autowired
    private StateService stateService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event)
    {
        System.out.println(event.getAuthentication());
        System.out.println("rowCount = "+stateService.rowCount());
    }
}
</code>```

This prevents a user from being logged in even with correct credentials with the following message (it is just an example. Counting the number of states upon successful authentication is not required at all).

An Authentication object was not found in the SecurityContext

The event is raised. The first statement inside the onApplicationEvent() method displays the following.

```<code>org.springframework.security.authentication.UsernamePasswordAuthenticationToken@45264a59: Principal: org.springframework.security.core.userdetails.User@586034f:Username: admin;
Password: [PROTECTED];
Enabled: true;
AccountNonExpired: true;
credentialsNonExpired: true;
AccountNonLocked: true;
Granted Authorities: ROLE_ADMIN;
Credentials: [PROTECTED];
Authenticated: true;
Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 127.0.0.1;
SessionId: 88777A678DC5BB0272F84CA4BC61FAF2;
Granted Authorities: ROLE_ADMIN
</code>```

So it appears that the user is authenticated and the authentication object is available.

My springSecurity.xml file simply looks like the following.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http pattern="/utility/Login.jsf*" security="none"/>
    <debug/>
    <http auto-config='true' use-expressions="true" disable-url-rewriting="true">
        <session-management session-fixation-protection="newSession">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>

        <intercept-url pattern="/admin_side/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/>
        <intercept-url pattern="/utility/Login.jsf" access="permitAll" requires-channel="any"/>
        <http-basic />
        <anonymous />

        <form-login login-processing-url="/j_spring_security_check" login-page="/utility/Login.jsf" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="authenticationFailureHandler"/>
        <logout logout-success-url="/utility/Login.jsf" invalidate-session="true" delete-cookies="JSESSIONID"/>
    </http>

    <authentication-manager>
       <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select email_id, password, enabled from user_table where lower(email_id)=lower(?)"
               authorities-by-username-query="select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)"/>
       </authentication-provider>
    </authentication-manager>

    <beans:bean id="loginSuccessHandler" class="loginsuccesshandler.LoginSuccessHandler"/>
    <beans:bean id="authenticationFailureHandler" class="loginsuccesshandler.AuthenticationFailureHandler" />

    <global-method-security secured-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="false">
        <protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
    </global-method-security>
</beans:beans>
</code>```

The Spring security works fine, when the following lines of XML is omitted from the spring-security.xml file.

```<code><global-method-security secured-annotations="enabled" proxy-target-class="false">
     <protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
</global-method-security>
</code>```

Can a protected method (with method security applied) be invoked from a class implementing the ApplicationListener<AuthenticationSuccessEvent> interface? If yes, then what is missing in my case? I have clicked thousands of links so far but couldn't find a single clue.

The application-context.xml file.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:component-scan base-package="admin.mangedbean loginsuccesshandler" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
        <context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/>
    </context:component-scan>

    <mvc:annotation-driven/>
    <context:annotation-config/>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
            </props>
        </property>

        <property name="jpaPropertyMap">
            <map>
              <entry key="eclipselink.weaving" value="false"/>
            </map>
        </property>

        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/jdbc/social_networking"/>
    </bean>

    <!--The bean shown in the beginning is configured here-->
    <bean id="authSuccessHandler" class="loginsuccesshandler.AuthSuccessHandler"/>

    <bean id="testService" class="admin.dao.TestDAO"/>
    <bean id="stateService" class="admin.dao.StateDAO"/>
    <bean id="sharableService" class="admin.dao.SharableDAO"/>
</beans>
</code>```

The web.xml file.

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <!--<param-value>Development</param-value>-->
        <param-value>Production</param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <security-constraint>
        <display-name>Restrict direct access to XHTML files</display-name>
        <web-resource-collection>
            <web-resource-name>XHTML files</web-resource-name>
            <url-pattern>*.xhtml</url-pattern>
        </web-resource-collection>
        <auth-constraint />
    </security-constraint>

    <session-config>
        <session-timeout>
            120
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>/utility/Login.jsf</welcome-file>
    </welcome-file-list>

    <resource-ref>
        <res-ref-name>jdbc/social_networking</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>
</code>```

The debug information can be seen below, when an attempt is made to login which ultimately fails.

```<code>DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 1 of 13 in additional filter chain; firing Filter: 'ChannelProcessingFilter'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/admin_side/**'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1103da5. A new one will be created.
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 3 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 4 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:189) - Request is to process authentication
DEBUG [http-apr-8080-exec-55] (ProviderManager.java:152) - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select email_id, password, enabled from user_table where lower(email_id)=lower(?)]
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)]
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
DEBUG [http-apr-8080-exec-55] (AbstractFallbackTransactionAttributeSource.java:106) - Adding transactional method 'rowCount' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
DEBUG [http-apr-8080-exec-55] (DelegatingMethodSecurityMetadataSource.java:65) - Caching method [CacheKey[admin.dao.StateDAO; public abstract java.lang.Long admin.dao.service.StateService.rowCount()]] with attributes [ROLE_ADMIN]
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'transactionManager'
DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:366) - Creating new transaction with name [admin.dao.StateDAO.rowCount]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:369) - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11] for JPA transaction
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:408) - Not exposing JPA transaction [org.hibernate.ejb.EntityManagerImpl@84ff11] as JDBC transaction because JpaDialect [org.springframework.orm.jpa.DefaultJpaDialect@d9dbb8] does not support JDBC Connection retrieval
DEBUG [http-apr-8080-exec-55] (AbstractSecurityInterceptor.java:194) - Secure object: ReflectiveMethodInvocation: public abstract java.lang.Long admin.dao.service.StateService.rowCount(); target is of class [admin.dao.StateDAO]; Attributes: [ROLE_ADMIN]
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:844) - Initiating transaction rollback
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:534) - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11]
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:594) - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11] after transaction
DEBUG [http-apr-8080-exec-55] (EntityManagerFactoryUtils.java:338) - Closing JPA EntityManager
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:346) - Authentication request failed: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:347) - Updated SecurityContextHolder to contain null Authentication
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:348) - Delegating to authentication failure handler loginsuccesshandler.AuthenticationFailureHandler@14883a3
DEBUG [http-apr-8080-exec-55] (DefaultRedirectStrategy.java:36) - Redirecting to '/SocialNetworking/utility/Login.jsf'
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:269) - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG [http-apr-8080-exec-55] (SecurityContextPersistenceFilter.java:97) - SecurityContextHolder now cleared, as request processing completed
DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-49] (FilterChainProxy.java:180) - /utility/Login.jsf has an empty filter list
</code>```

The last thing:

When I give up this bean and unregister from the application-context.xml file, the login is made successfully but the following information can be seen on the server console.

```<code>DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@b910c1. A new one will be created.
</code>```

答:
My issue was that I needed to properly disable security and implement my own preAuthorization. Unlike the OP, I was trying to disable authentication altogether and implement my own solution.</p>
```<code>@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests().antMatchers("/**").permitAll();
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to invoke a protected method from a class that implements the ApplicationListener<AuthenticationSuccessEvent> interface on successful login (Spring 3.2.2 and Spring Security 3.2.0 M1). This is my previous question.

The application runs under the following environment.

Spring 3.2.2

Spring Security 3.2.0

JPA 2.0

JSF 2.1.9

MySQL 5.6.11

JDK-7u11

NetBeans 7.2.1

I have added the following libraries related to Spring security to the classpath.

spring-security-core-3.2.0.M1.jar

spring-security-config-3.2.0.M1.jar

spring-security-web-3.2.0.M1.jar

The class that implements ApplicationListener<AuthenticationSuccessEvent> is as follows.

package loginsuccesshandler;

import admin.dao.service.StateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Service;

@Service
public final class AuthSuccessHandler implements ApplicationListener<AuthenticationSuccessEvent>
{
    @Autowired
    private StateService stateService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event)
    {
        System.out.println(event.getAuthentication());
        System.out.println("rowCount = "+stateService.rowCount());
    }
}

This prevents a user from being logged in even with correct credentials with the following message (it is just an example. Counting the number of states upon successful authentication is not required at all).

An Authentication object was not found in the SecurityContext

The event is raised. The first statement inside the onApplicationEvent() method displays the following.

org.springframework.security.authentication.UsernamePasswordAuthenticationToken@45264a59: Principal: org.springframework.security.core.userdetails.User@586034f:Username: admin;
Password: [PROTECTED];
Enabled: true;
AccountNonExpired: true;
credentialsNonExpired: true;
AccountNonLocked: true;
Granted Authorities: ROLE_ADMIN;
Credentials: [PROTECTED];
Authenticated: true;
Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 127.0.0.1;
SessionId: 88777A678DC5BB0272F84CA4BC61FAF2;
Granted Authorities: ROLE_ADMIN

So it appears that the user is authenticated and the authentication object is available.

My springSecurity.xml file simply looks like the following.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http pattern="/utility/Login.jsf*" security="none"/>
    <debug/>
    <http auto-config='true' use-expressions="true" disable-url-rewriting="true">
        <session-management session-fixation-protection="newSession">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>

        <intercept-url pattern="/admin_side/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/>
        <intercept-url pattern="/utility/Login.jsf" access="permitAll" requires-channel="any"/>
        <http-basic />
        <anonymous />

        <form-login login-processing-url="/j_spring_security_check" login-page="/utility/Login.jsf" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="authenticationFailureHandler"/>
        <logout logout-success-url="/utility/Login.jsf" invalidate-session="true" delete-cookies="JSESSIONID"/>
    </http>

    <authentication-manager>
       <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select email_id, password, enabled from user_table where lower(email_id)=lower(?)"
               authorities-by-username-query="select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)"/>
       </authentication-provider>
    </authentication-manager>

    <beans:bean id="loginSuccessHandler" class="loginsuccesshandler.LoginSuccessHandler"/>
    <beans:bean id="authenticationFailureHandler" class="loginsuccesshandler.AuthenticationFailureHandler" />

    <global-method-security secured-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="false">
        <protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
    </global-method-security>
</beans:beans>

The Spring security works fine, when the following lines of XML is omitted from the spring-security.xml file.

<global-method-security secured-annotations="enabled" proxy-target-class="false">
     <protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
</global-method-security>

Can a protected method (with method security applied) be invoked from a class implementing the ApplicationListener<AuthenticationSuccessEvent> interface? If yes, then what is missing in my case? I have clicked thousands of links so far but couldn't find a single clue.

The application-context.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:component-scan base-package="admin.mangedbean loginsuccesshandler" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
        <context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/>
    </context:component-scan>

    <mvc:annotation-driven/>
    <context:annotation-config/>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
            </props>
        </property>

        <property name="jpaPropertyMap">
            <map>
              <entry key="eclipselink.weaving" value="false"/>
            </map>
        </property>

        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/jdbc/social_networking"/>
    </bean>

    <bean id="authSuccessHandler" class="loginsuccesshandler.AuthSuccessHandler"/>

    <bean id="testService" class="admin.dao.TestDAO"/>
    <bean id="stateService" class="admin.dao.StateDAO"/>
    <bean id="sharableService" class="admin.dao.SharableDAO"/>
</beans>

The web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>

        <param-value>Production</param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <security-constraint>
        <display-name>Restrict direct access to XHTML files</display-name>
        <web-resource-collection>
            <web-resource-name>XHTML files</web-resource-name>
            <url-pattern>*.xhtml</url-pattern>
        </web-resource-collection>
        <auth-constraint />
    </security-constraint>

    <session-config>
        <session-timeout>
            120
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>/utility/Login.jsf</welcome-file>
    </welcome-file-list>

    <resource-ref>
        <res-ref-name>jdbc/social_networking</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

The debug information can be seen below, when an attempt is made to login which ultimately fails.

DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 1 of 13 in additional filter chain; firing Filter: 'ChannelProcessingFilter'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/admin_side/**'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1103da5. A new one will be created.
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 3 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 4 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:189) - Request is to process authentication
DEBUG [http-apr-8080-exec-55] (ProviderManager.java:152) - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select email_id, password, enabled from user_table where lower(email_id)=lower(?)]
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)]
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
DEBUG [http-apr-8080-exec-55] (AbstractFallbackTransactionAttributeSource.java:106) - Adding transactional method 'rowCount' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
DEBUG [http-apr-8080-exec-55] (DelegatingMethodSecurityMetadataSource.java:65) - Caching method [CacheKey[admin.dao.StateDAO; public abstract java.lang.Long admin.dao.service.StateService.rowCount()]] with attributes [ROLE_ADMIN]
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'transactionManager'
DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:366) - Creating new transaction with name [admin.dao.StateDAO.rowCount]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:369) - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11] for JPA transaction
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:408) - Not exposing JPA transaction [org.hibernate.ejb.EntityManagerImpl@84ff11] as JDBC transaction because JpaDialect [org.springframework.orm.jpa.DefaultJpaDialect@d9dbb8] does not support JDBC Connection retrieval
DEBUG [http-apr-8080-exec-55] (AbstractSecurityInterceptor.java:194) - Secure object: ReflectiveMethodInvocation: public abstract java.lang.Long admin.dao.service.StateService.rowCount(); target is of class [admin.dao.StateDAO]; Attributes: [ROLE_ADMIN]
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:844) - Initiating transaction rollback
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:534) - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11]
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:594) - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11] after transaction
DEBUG [http-apr-8080-exec-55] (EntityManagerFactoryUtils.java:338) - Closing JPA EntityManager
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:346) - Authentication request failed: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:347) - Updated SecurityContextHolder to contain null Authentication
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:348) - Delegating to authentication failure handler loginsuccesshandler.AuthenticationFailureHandler@14883a3
DEBUG [http-apr-8080-exec-55] (DefaultRedirectStrategy.java:36) - Redirecting to '/SocialNetworking/utility/Login.jsf'
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:269) - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG [http-apr-8080-exec-55] (SecurityContextPersistenceFilter.java:97) - SecurityContextHolder now cleared, as request processing completed
DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-49] (FilterChainProxy.java:180) - /utility/Login.jsf has an empty filter list

The last thing:

When I give up this bean and unregister from the application-context.xml file, the login is made successfully but the following information can be seen on the server console.

DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@b910c1. A new one will be created.

Body:
My issue was that I needed to properly disable security and implement my own preAuthorization. Unlike the OP, I was trying to disable authentication altogether and implement my own solution.

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests().antMatchers("/**").permitAll();
    }

}


问:
How to make this T-SQL query run faster (using Group by & Case)?
I have bottom SQL view on the bottom, and I would like to get some feedback how I should make this perform better.

I believe it runs slow due to Group by and Case.

Is there anything/anywhere I could make the query perform better?

```<code>select FacilityID,
   TransactionDate,
   sum(Amount) as Amount,
   AccountNumber as RevenueTypeID,
   (case when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '201' then 'Medicare Part A'
         when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '202' then 'Medicare Part B'
         when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '211' then 'Medicare HMO'
         else 'Other'
   end) as RevenueTypeDesc,
   (LastName + ', ' + FirstName) as FullName,
   Payer,
   EffectiveDate,
   (case when EffectiveDate >= DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1) then 'Current Period' else 'Past Period' end) as CategoryDesc
from [dbo].[view_ods_revenue_journal]
where TransactionDate <= EOMONTH(getdate())
group by FacilityID,
     TransactionDate,
     AccountNumber,
     (case when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '201' then 'Medicare Part A'
           when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '202' then 'Medicare Part B'
           when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '211' then 'Medicare HMO'
           else 'Other'
     end),
     (LastName + ', ' + FirstName),
     Payer,
     EffectiveDate,
     (case when EffectiveDate >= DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1) then 'Current Period' else 'Past Period' end)
</code>```

答:
Try this:</p>
```<code>WITH    RevenueType AS
        (
            SELECT  Code    =   '201', Description  =   'Medicare Part A' UNION
            SELECT  Code    =   '202', Description  =   'Medicare Part B' UNION
            SELECT  Code    =   '211', Description  =   'Medicare HMO'
        )
,       RevenueJournal AS
        (
            SELECT
                    FacilityID
                ,   TransactionDate
                ,   Amount
                ,   RevenueTypeID   =   AccountNumber
                ,   RevenueTypeCode =   CASE WHEN   AccountNumber LIKE  '%z%'
                                             THEN   SUBSTRING(AccountNumber, 8, 3)
                                             ELSE   SUBSTRING(AccountNumber, 6, 3)
                                        END
                ,   FullName        =   LastName + ', ' + FirstName
                ,   Payer
                ,   EffectiveDate
                ,   CategoryDesc    =   CASE WHEN   EffectiveDate >= DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1)
                                             THEN   'Current Period'
                                             ELSE   'Past Period'
                                        END
            FROM    dbo.view_ods_revenue_journal

            WHERE   TransactionDate <=  EOMONTH(GETDATE())
        )
,       RevenueJournalFinal AS
        (
            SELECT
                    FacilityID
                ,   TransactionDate
                ,   Amount
                ,   RevenueTypeID
                ,   RevenueTypeDesc = ISNULL(T.Description, 'Other')
                ,   FullName
                ,   Payer
                ,   EffectiveDate
                ,   CategoryDesc
            FROM        RevenueJournal  J
            LEFT JOIN   RevenueType     T   ON T.Code = J.Code
        )

SELECT
        FacilityID
    ,   TransactionDate
    ,   Amount          =   SUM(Amount)
    ,   RevenueTypeID
    ,   RevenueTypeDesc
    ,   FullName
    ,   Payer
    ,   EffectiveDate
    ,   CategoryDesc
FROM    RevenueJournalFinal

GROUP BY
        FacilityID
    ,   TransactionDate
    ,   RevenueTypeID
    ,   RevenueTypeDesc
    ,   FullName
    ,   Payer
    ,   EffectiveDate
    ,   CategoryDesc
</code>```

Body:
I have bottom SQL view on the bottom, and I would like to get some feedback how I should make this perform better.

I believe it runs slow due to Group by and Case.

Is there anything/anywhere I could make the query perform better?

select FacilityID,
   TransactionDate,
   sum(Amount) as Amount,
   AccountNumber as RevenueTypeID,
   (case when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '201' then 'Medicare Part A'
         when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '202' then 'Medicare Part B'
         when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '211' then 'Medicare HMO'
         else 'Other'
   end) as RevenueTypeDesc,
   (LastName + ', ' + FirstName) as FullName,
   Payer,
   EffectiveDate,
   (case when EffectiveDate >= DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1) then 'Current Period' else 'Past Period' end) as CategoryDesc
from [dbo].[view_ods_revenue_journal]
where TransactionDate <= EOMONTH(getdate())
group by FacilityID,
     TransactionDate,
     AccountNumber,
     (case when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '201' then 'Medicare Part A'
           when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '202' then 'Medicare Part B'
           when (case when AccountNumber like '%z%' then SUBSTRING(AccountNumber, 8, 3) else SUBSTRING(AccountNumber, 6, 3) end) = '211' then 'Medicare HMO'
           else 'Other'
     end),
     (LastName + ', ' + FirstName),
     Payer,
     EffectiveDate,
     (case when EffectiveDate >= DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1) then 'Current Period' else 'Past Period' end)

Body:
Try this:

WITH    RevenueType AS
        (
            SELECT  Code    =   '201', Description  =   'Medicare Part A' UNION
            SELECT  Code    =   '202', Description  =   'Medicare Part B' UNION
            SELECT  Code    =   '211', Description  =   'Medicare HMO'
        )
,       RevenueJournal AS
        (
            SELECT
                    FacilityID
                ,   TransactionDate
                ,   Amount
                ,   RevenueTypeID   =   AccountNumber
                ,   RevenueTypeCode =   CASE WHEN   AccountNumber LIKE  '%z%'
                                             THEN   SUBSTRING(AccountNumber, 8, 3)
                                             ELSE   SUBSTRING(AccountNumber, 6, 3)
                                        END
                ,   FullName        =   LastName + ', ' + FirstName
                ,   Payer
                ,   EffectiveDate
                ,   CategoryDesc    =   CASE WHEN   EffectiveDate >= DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1)
                                             THEN   'Current Period'
                                             ELSE   'Past Period'
                                        END
            FROM    dbo.view_ods_revenue_journal

            WHERE   TransactionDate <=  EOMONTH(GETDATE())
        )
,       RevenueJournalFinal AS
        (
            SELECT
                    FacilityID
                ,   TransactionDate
                ,   Amount
                ,   RevenueTypeID
                ,   RevenueTypeDesc = ISNULL(T.Description, 'Other')
                ,   FullName
                ,   Payer
                ,   EffectiveDate
                ,   CategoryDesc
            FROM        RevenueJournal  J
            LEFT JOIN   RevenueType     T   ON T.Code = J.Code
        )

SELECT
        FacilityID
    ,   TransactionDate
    ,   Amount          =   SUM(Amount)
    ,   RevenueTypeID
    ,   RevenueTypeDesc
    ,   FullName
    ,   Payer
    ,   EffectiveDate
    ,   CategoryDesc
FROM    RevenueJournalFinal

GROUP BY
        FacilityID
    ,   TransactionDate
    ,   RevenueTypeID
    ,   RevenueTypeDesc
    ,   FullName
    ,   Payer
    ,   EffectiveDate
    ,   CategoryDesc


问:
OpenXML escaping illegal characters
I am doing some string replacement within a Word Docx file using OpenXML Power Tools and it is working as expected. However things break when I have invalid characters in the substitution such as ampersand, so for instance "Harry & Sally" will break and produce an invalid document. According to this post illegal characters need to be converted to xHHHH.

I am having trouble finding the contents to the OOXML clause mentioned in the post and hence escaping characters appropriately.

I am hoping someone either has some code or insights into exactly what characters need to be escaped. I was also hopeful OpenXML Power Tools could do this for me in some way, but I cannot seem to find anything in there either.

答:
I created an extension method with help from Michael Edenfield's answer. Pretty self explanatory... just make sure you replace the ampersands first! Otherwise you will end up replacing your other escaped symbols by mistake.

```<code>public static string EscapeXmlCharacters(this string input)
{
    switch (input)
    {
        case null: return null;
        case "": return "";
        default:
        {
            input = input.Replace("&", "&")
                .Replace("'", "'")
                .Replace("\"", """)
                .Replace(">", ">")
                .Replace("<", "<");

            return input;
        }
    }
}
</code>```

.NET Fiddle: https://dotnetfiddle.net/PCqffy

Title: OpenXML escaping illegal characters

Body:
I created an extension method with help from Michael Edenfield's answer. Pretty self explanatory... just make sure you replace the ampersands first! Otherwise you will end up replacing your other escaped symbols by mistake.

public static string EscapeXmlCharacters(this string input)
{
    switch (input)
    {
        case null: return null;
        case "": return "";
        default:
        {
            input = input.Replace("&", "&amp;")
                .Replace("'", "&apos;")
                .Replace("\"", "&quot;")
                .Replace(">", "&gt;")
                .Replace("<", "&lt;");

            return input;
        }
    }
}

.NET Fiddle: https://dotnetfiddle.net/PCqffy


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
It may help to read the pointer declaration backwards:

```<code>const Dict *dict
</code>```

means

'dict' is a pointer to a Dict that is constant.

You can move the address it's pointing to, but the struct it is pointing to is treated as constant.

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

Body:
It may help to read the pointer declaration backwards:

const Dict *dict

means

'dict' is a pointer to a Dict that is constant.

You can move the address it's pointing to, but the struct it is pointing to is treated as constant.

OwnerDisplayName: veefu


问:
Rails 3 routing: add action to all resources in namespace
I'm designing my admin panel for a cms and I want to have for example Downloads, Images and Articles. Each of these elements can be categorized, so I have an action "categories" on each controller(Downloads, Images and Articles).

In my routes file I have the following:

```<code> namespace :admin do
     resources :downloads
     resources :images
     resources :articles
 end
</code>```

My problem is that the above code only creates routes for index, show, edit, update and destroy. Is there a method of adding the categories action to all resources once, without declaring it 3 times?

答:
```<code>namespace :admin do
  [:downloads, :images, :articles].each do |resource|
    resources resource do
      get :categories, :on => :collection
    end
  end
end
</code>```

Body:
I'm designing my admin panel for a cms and I want to have for example Downloads, Images and Articles. Each of these elements can be categorized, so I have an action "categories" on each controller(Downloads, Images and Articles).

In my routes file I have the following:

 namespace :admin do
     resources :downloads
     resources :images
     resources :articles
 end

My problem is that the above code only creates routes for index, show, edit, update and destroy. Is there a method of adding the categories action to all resources once, without declaring it 3 times?


问:
regex replace last occurance of number in between 2 chars javascript
I am trying to replace the last number of each match in between parenthesis.

so if I had cos(3 * 3)

before this regex

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)
```

would turn cos(3 * 3) into cos(3deg * 3deg)

I need only the last number to be changed to deg

So if  I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

What regular expression magic could I use to do this.

答:
The insertion position for deg is just a place between two defined Assertions.

(?<=\([^()]*\d)(?=[^()\d]*\))

https://regex101.com/r/sjw3CX/1

```<code> (?<= \( [^()]* \d )           # Lookbehind open parenth up to last number
 (?= [^()\d]* \) )             # Lookahead no digits and must have a closing parenth
</code>```

var input = " cos(3 * 3) + cos(3 * 2)"

var output = input.replace(/(?<=\([^()]*\d)(?=[^()\d]*\))/g,'deg')

console.log(output)```

Body:
I am trying to replace the last number of each match in between parenthesis.

so if I had cos(3 * 3)

before this regex

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)

would turn cos(3 * 3) into cos(3deg * 3deg)

I need only the last number to be changed to deg

So if  I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

What regular expression magic could I use to do this.

Body:
The insertion position for deg is just a place between two defined Assertions.

(?<=\([^()]*\d)(?=[^()\d]*\))

https://regex101.com/r/sjw3CX/1

 (?<= \( [^()]* \d )           # Lookbehind open parenth up to last number
 (?= [^()\d]* \) )             # Lookahead no digits and must have a closing parenth

var input = " cos(3 * 3) + cos(3 * 2)"

var output = input.replace(/(?<=\([^()]*\d)(?=[^()\d]*\))/g,'deg')

console.log(output)


问:
Finding a public facing IP address in Python?
How can I find the public facing IP for my net work in Python?</p>

答:
You can also use DNS which in some cases may be more reliable than http methods:

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

# pip install --user dnspython

import dns.resolver

resolver1_opendns_ip = False
resolver = dns.resolver.Resolver()
opendns_result = resolver.resolve("resolver1.opendns.com", "A")
for record in opendns_result:
    resolver1_opendns_ip = record.to_text()

if resolver1_opendns_ip:
    resolver.nameservers = [resolver1_opendns_ip]
    myip_result = resolver.resolve("myip.opendns.com", "A")
    for record in myip_result:
        print(f"Your external ip is {record.to_text()}")
</code>```

This is the python equivalent of dig +short -4 myip.opendns.com @resolver1.opendns.com

OwnerDisplayName: Unkwntech

LastEditorDisplayName: Bobby Jack

Body:
You can also use DNS which in some cases may be more reliable than http methods:

#!/usr/bin/env python3

# pip install --user dnspython

import dns.resolver

resolver1_opendns_ip = False
resolver = dns.resolver.Resolver()
opendns_result = resolver.resolve("resolver1.opendns.com", "A")
for record in opendns_result:
    resolver1_opendns_ip = record.to_text()

if resolver1_opendns_ip:
    resolver.nameservers = [resolver1_opendns_ip]
    myip_result = resolver.resolve("myip.opendns.com", "A")
    for record in myip_result:
        print(f"Your external ip is {record.to_text()}")

This is the python equivalent of dig +short -4 myip.opendns.com @resolver1.opendns.com


问:
ElasticSearch/OpenSearch historical histogram
I'm using ElasticSearch (OpenSearch) to store multiple objects in an index. Each object has a unique ID, creation date and an "amount" field that stores integer value. This "amount" value changes periodically, so I'm updating objects in-place using the IDs to match the existing objects.

What I want is to display a histogram of total amount across all objects over time. The problem is that I need to preserve historical data somehow in order for it to be displayed on the graph.

What are my option to implement this? Is there an automatic way to aggregate and preserve these totals? Or should I do this manually from my application? E.g. send these totals instead of individual objects?

The data structure:

[
  { id: '{uuidv4}', amount: 100 },
  { id: '{uuidv4}', amount: 25 },
  { id: '{uuidv4}', amount: 150 },
  { id: '{uuidv4}', amount: 0 },
  ...
]
```

答:
(from an Elasticsearch point of view) you would normally store each each change as an individual record, rather than updating the existing one. that way you get the history and can do your aggs, and still show the latest values

just treat it as any other time based data, logs, click streams, transaction. etc


问:
Check if a flag is set on an enum field in Azure Cognitive Search using OData Query Syntax
I have to find a way to query (am using Azure search) whether or not a field has a set of flags set without using bitwise and. The reason for the limitation is that Azure Cognitive Search uses OData for querying, which does not support any bitwise operations.

Say we have an enum like so:

```<code>public enum PreferredColors
{
     red = 1,
     blue = 2,
     green = 4,
     yellow = 8
}
</code>```

Now say I have a user who prefers yellow, blue, and red. I'm want to check for users that prefer yellow and red. Normally you would do that like so:

```<code>PreferredColors preference = PreferredColors.red | PreferredColors.yellow
bool res = (preference & user.ColorPreferences) == preference
</code>```

Where res is the result we're looking for. This check has to be part of the query (for paging reasons). Is there any other way I can perform this check that avoids using bitwise &?

答:
Azure Cognitive Search doesn't support OData enums, so you'll have to model this scenario with a different data type than Edm.Int32. Depending on how you want to model things in your application, you could use either Collection(Edm.Int32) or maybe Collection(Edm.String). Let's use a string collection for these examples just for the sake of clarity.

Another thing you can't do in Azure Cognitive Search is compare one field of an index to another field, so I'm going to assume that the desired color preferences are known to the application code and can be injected into the query string that you're going to send to Azure Cognitive Search. The scenario is that for any given document in the search index, you want to check whether all of the preferred colors given to the application are present in the colors for that document.

Here's how you would express this query using a string collection field if the color preferences to search for are 'red' and 'green':

```<code>$filter=preferences/any(p: p eq 'red') and preferences/any(p: p eq 'green')
</code>```

If you have a document where the preferences field contains ["green", "yellow", "red"] for example, then the above query will match.

Body:
I have to find a way to query (am using Azure search) whether or not a field has a set of flags set without using bitwise and. The reason for the limitation is that Azure Cognitive Search uses OData for querying, which does not support any bitwise operations.

Say we have an enum like so:

public enum PreferredColors
{
     red = 1,
     blue = 2,
     green = 4,
     yellow = 8
}

Now say I have a user who prefers yellow, blue, and red. I'm want to check for users that prefer yellow and red. Normally you would do that like so:

PreferredColors preference = PreferredColors.red | PreferredColors.yellow
bool res = (preference & user.ColorPreferences) == preference

Where res is the result we're looking for. This check has to be part of the query (for paging reasons). Is there any other way I can perform this check that avoids using bitwise &?

Body:
Azure Cognitive Search doesn't support OData enums, so you'll have to model this scenario with a different data type than Edm.Int32. Depending on how you want to model things in your application, you could use either Collection(Edm.Int32) or maybe Collection(Edm.String). Let's use a string collection for these examples just for the sake of clarity.

Another thing you can't do in Azure Cognitive Search is compare one field of an index to another field, so I'm going to assume that the desired color preferences are known to the application code and can be injected into the query string that you're going to send to Azure Cognitive Search. The scenario is that for any given document in the search index, you want to check whether all of the preferred colors given to the application are present in the colors for that document.

Here's how you would express this query using a string collection field if the color preferences to search for are 'red' and 'green':

$filter=preferences/any(p: p eq 'red') and preferences/any(p: p eq 'green')

If you have a document where the preferences field contains ["green", "yellow", "red"] for example, then the above query will match.