Title: How to plot a horizontal Stacked bar plot using Plotly-Python?

Body:
I'm trying to plot the below summary metric plot using plotly.

data

Model   F1_Score    Precision   Recall  Accuracy    ROC_AUC CV_Score
0   LogisticRegression  0.815068    0.777778    0.856115    0.739130    0.678058    0.752876
1   K-NearestNeighbors  0.828767    0.790850    0.870504    0.758454    0.699958    0.714476
2   SVM 0.852459    0.783133    0.935252    0.782609    0.702920    0.665067
3   GaussianProcess 0.825503    0.773585    0.884892    0.748792    0.677740    0.665067
4   MLP 0.774436    0.811024    0.741007    0.710145    0.694033    0.735327
5   DecisionTree    0.747170    0.785714    0.712230    0.676329    0.657586    0.692216
6   ExtraTrees  0.859060    0.805031    0.920863    0.797101    0.732490    0.792698
7   RandomForest    0.826667    0.770186    0.892086    0.748792    0.673984    0.778324
8   XGBoost 0.838488    0.802632    0.877698    0.772947    0.718261    0.764025
9   AdaBoostClassifier  0.800000    0.780822    0.820144    0.724638    0.674778    0.728927
10  GBClassifier    0.835017    0.784810    0.892086    0.763285    0.696043    0.754451
11  CatBoost    0.843854    0.783951    0.913669    0.772947    0.699482    0.768787
12  Stacking    0.833333    0.776398    0.899281    0.758454    0.684934    0.787949
13  Voting  0.836120    0.781250    0.899281    0.763285    0.692287    0.778337
14  Bagging 0.855263    0.787879    0.935252    0.787440    0.710273    0.792673

import plotly.graph_objects as go

mark_color = ['rgba(246, 78, 139, 0.6)', 'rgba(58, 71, 80, 0.6)', 'rgba(50, 171, 96, 0.6)', 'rgba(38, 24, 74, 0.6)', 'rgba(155, 83, 109, 0.6)', 'rgba(297, 55, 74, 0.6)']
line_color = ['rgba(246, 78, 139, 1.0)', 'rgba(58, 71, 80, 1.0)', 'rgba(50, 171, 96, 1.0)', 'rgba(38, 24, 74, 1.0)', 'rgba(155, 83, 109, 1.0)', 'rgba(297, 55, 74, 1.0)']

y_labels = ["F1_Score", "Precision", "Recall", "Accuracy", "ROC_AUC", "CV_Score"]

fig = go.Figure()

for i, j in enumerate(y_labels):
    fig.add_trace(go.Bar(
        y=y_labels,
        x=list(scores[j].values),
        name=j,
        orientation='h',
        marker=dict(
            color=mark_color[i]

        )
    ))

fig.update_layout(
    barmode='stack',
    title="Summary Metrics",
    xaxis_title="Metric Value",
    yaxis_title="Metric Name",
    legend_title="Model",

)

fig.show()

So far, I'm able to plot this

I'm unable to add Model Names to the plot. How add Model column as Legend and add all model values into the plot?

Body:
shape the data frame first df2 = df.set_index("Model").unstack().to_frame().reset_index()

then it's a simple case of using Plotly Express

import pandas as pd
import io
import plotly.express as px

df = pd.read_csv(
    io.StringIO(
        """Model   F1_Score    Precision   Recall  Accuracy    ROC_AUC CV_Score
0   LogisticRegression  0.815068    0.777778    0.856115    0.739130    0.678058    0.752876
1   K-NearestNeighbors  0.828767    0.790850    0.870504    0.758454    0.699958    0.714476
2   SVM 0.852459    0.783133    0.935252    0.782609    0.702920    0.665067
3   GaussianProcess 0.825503    0.773585    0.884892    0.748792    0.677740    0.665067
4   MLP 0.774436    0.811024    0.741007    0.710145    0.694033    0.735327
5   DecisionTree    0.747170    0.785714    0.712230    0.676329    0.657586    0.692216
6   ExtraTrees  0.859060    0.805031    0.920863    0.797101    0.732490    0.792698
7   RandomForest    0.826667    0.770186    0.892086    0.748792    0.673984    0.778324
8   XGBoost 0.838488    0.802632    0.877698    0.772947    0.718261    0.764025
9   AdaBoostClassifier  0.800000    0.780822    0.820144    0.724638    0.674778    0.728927
10  GBClassifier    0.835017    0.784810    0.892086    0.763285    0.696043    0.754451
11  CatBoost    0.843854    0.783951    0.913669    0.772947    0.699482    0.768787
12  Stacking    0.833333    0.776398    0.899281    0.758454    0.684934    0.787949
13  Voting  0.836120    0.781250    0.899281    0.763285    0.692287    0.778337
14  Bagging 0.855263    0.787879    0.935252    0.787440    0.710273    0.792673"""
    ),
    sep="\s+",
)

df2 = df.set_index("Model").unstack().to_frame().reset_index()

fig = px.bar(
    df2,
    y="level_0",
    x=0,
    color="Model",
    color_discrete_map={
        "LogisticRegression": "#2E91E5",
        "K-NearestNeighbors": "#E15F99",
        "SVM": "#1CA71C",
        "GaussianProcess": "#FB0D0D",
        "MLP": "#DA16FF",
        "DecisionTree": "#222A2A",
        "ExtraTrees": "#B68100",
        "RandomForest": "#750D86",
        "XGBoost": "#EB663B",
        "AdaBoostClassifier": "#511CFB",
        "GBClassifier": "#00A08B",
        "CatBoost": "#FB00D1",
        "Stacking": "#FC0080",
        "Voting": "#B2828D",
        "Bagging": "#6C7C32",
    },
)

fig.update_layout(
    title="Summary Metrics",
    xaxis_title="Metric Value",
    yaxis_title="Metric Name",
    legend_title="Model",
)


来源: stackexchange

问:
Installing GD extension in Docker
I'm new to Docker and I'm trying to install PHP GD extension.

This is my current Dockerfile:

```<code>FROM php:7.4-fpm-alpine

RUN docker-php-ext-install mysqli pdo pdo_mysql bcmath gd
</code>```

When running the docker via docker-compose build && docker-compose up -d I'm getting a lots of errors and in the end I get this message:

```<code>configure: error: Package requirements (zlib) were not met:

Package 'zlib', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables ZLIB_CFLAGS
and ZLIB_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
ERROR: Service 'php' failed to build: The command '/bin/sh -c docker-php-ext-install mysqli pdo pdo_mysql bcmath gd' returned a non-zero code: 1
</code>```

Without the "gd" at the end the Docker container runs normally.

What could be the problem and how could I fix it?

答:
In my docker using PHP8.0 I got GD working for jpg,png and webp by adding the following lines to my php.dockerfile:

```<code>FROM php:8.0-fpm-alpine

# Install dependencies for GD and install GD with support for jpeg, png webp and freetype
# Info about installing GD in PHP https://www.php.net/manual/en/image.installation.php
RUN apk add --no-cache \
        libjpeg-turbo-dev \
        libpng-dev \
        libwebp-dev \
        freetype-dev

# As of PHP 7.4 we don't need to add --with-png
RUN docker-php-ext-configure gd --with-jpeg --with-webp --with-freetype
RUN docker-php-ext-install gd
</code>```

ContentLicense: CC BY-SA 4.0

Title: Installing GD extension in Docker

Body:
I'm new to Docker and I'm trying to install PHP GD extension.

This is my current Dockerfile:

FROM php:7.4-fpm-alpine

RUN docker-php-ext-install mysqli pdo pdo_mysql bcmath gd

When running the docker via docker-compose build && docker-compose up -d I'm getting a lots of errors and in the end I get this message:

configure: error: Package requirements (zlib) were not met:

Package 'zlib', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables ZLIB_CFLAGS
and ZLIB_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
ERROR: Service 'php' failed to build: The command '/bin/sh -c docker-php-ext-install mysqli pdo pdo_mysql bcmath gd' returned a non-zero code: 1

Without the "gd" at the end the Docker container runs normally.

What could be the problem and how could I fix it?

Body:
In my docker using PHP8.0 I got GD working for jpg,png and webp by adding the following lines to my php.dockerfile:

FROM php:8.0-fpm-alpine

# Install dependencies for GD and install GD with support for jpeg, png webp and freetype
# Info about installing GD in PHP https://www.php.net/manual/en/image.installation.php
RUN apk add --no-cache \
        libjpeg-turbo-dev \
        libpng-dev \
        libwebp-dev \
        freetype-dev

# As of PHP 7.4 we don't need to add --with-png
RUN docker-php-ext-configure gd --with-jpeg --with-webp --with-freetype
RUN docker-php-ext-install gd


问:
Sql Server LOCK with CTE - Avoid duplicate processing
I have a table with thousands of transactions and multiple instances of a service, has to process the transactions one by one. To avoid, duplicate processing, i am using a column to block the transaction by service user. I have used TABLOCK and XLOCK on SELECT, but I am using CTE to block.

To me all looks good, but wanted expert's opinion to validate the same to avoid duplicate processing. Is there any possibility that two users might block same transaction in any given time  in my logic?

```<code>CREATE PROCEDURE [dbo].[GetMyTicket] (
    @username VARCHAR(20),
    @id INT OUTPUT)
AS
;WITH result AS (
     SELECT TOP 1 id, trx_user, trx_status
     FROM dbo.transaction_details t WITH(TABLOCK, XLOCK)
     WHERE t.trx_user IS NULL AND t.trx_status IS NULL
     ORDER BY t.id
)
UPDATE result
SET trx_user = @Username,
    trx_status = 'NEW',
    @id = id
GO
</code>```

答:
Is there any possibility that two users might block same transaction in any given time in my logic?

No.  Just make sure you understand that if you run GetMyTicket in a transaction, no other session can run GetMyTicket until you commit the transaction.

You can get additional concurrency with WITH (UPDLOCK, READPAST, ROWLOCK), see Using tables as queues, and you can serialize calls to that query with sp_getaplock/sp_releaseapplock and not hold an exclusive lock until the end of your transaction.

Body:
I have a table with thousands of transactions and multiple instances of a service, has to process the transactions one by one. To avoid, duplicate processing, i am using a column to block the transaction by service user. I have used TABLOCK and XLOCK on SELECT, but I am using CTE to block.

To me all looks good, but wanted expert's opinion to validate the same to avoid duplicate processing. Is there any possibility that two users might block same transaction in any given time  in my logic?

CREATE PROCEDURE [dbo].[GetMyTicket] (
    @username VARCHAR(20),
    @id INT OUTPUT)
AS
;WITH result AS (
     SELECT TOP 1 id, trx_user, trx_status
     FROM dbo.transaction_details t WITH(TABLOCK, XLOCK)
     WHERE t.trx_user IS NULL AND t.trx_status IS NULL
     ORDER BY t.id
)
UPDATE result
SET trx_user = @Username,
    trx_status = 'NEW',
    @id = id
GO


问:
How to wait for full page load using python beautifulsoup
I'm trying to scrape a site using Python with Beautifulsoup, but the site takes a long time to load and the scraping is fast and doesn't recover completely. I would like to know how to wait 5 seconds before retrieving the source code using Beautifulsoup.

I think a code is like this:

```<code>from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

url = 'https://www.edocente.com.br/pnld/2020/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}

req = Request(url, headers = headers)
response = urlopen(req)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
soup.findAll('a', class_="btn bold mt-4 px-5")
</code>```

I can't recovery a whole source code because site is slow to load and my tags aren´t recovered. How to wait to recover the whole source code from site?

I would like to get only the text of the href tags, as below:

```<code><a href="/pnld/2020/obra/companhia-das-ciencias-6-ano-saraiva" class="btn bold mt-4 px-5">Ver Obra </a>
<a href="/pnld/2020/obra/companhia-das-ciencias-7-ano-saraiva" class="btn bold mt-4 px-5">Ver Obra </a>
<a href="/pnld/2020/obra/companhia-das-ciencias-8-ano-saraiva" class="btn bold mt-4 px-5">Ver Obra </a>
</code>```

I'd like to recovery:

```<code>/pnld/2020/obra/companhia-das-ciencias-6-ano-saraiva
/pnld/2020/obra/companhia-das-ciencias-7-ano-saraiva
/pnld/2020/obra/companhia-das-ciencias-8-ano-saraiva
</code>```

How to do it?
Thanks

答:
You could try to get a page asynchronously using aiohttp and asyncio. For example let’s pass that url to query and headers as parameters to ClientSession instance, now we have a ClientResponse object called resp and you can get all the information you need from the response.

install modules by: pip install cchardet aiodns aiohttp aiotthp[speedups]

import aiohttp
import asyncio
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import ssl

#ssl._create_default_https_context = ssl._create_unverified_context
url = 'https://www.edocente.com.br/pnld/2020/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
html = ''

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers, verify_ssl=False) as response:
            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])
            html = await response.text()
            soup = BeautifulSoup(html, 'html.parser')
            print(soup.findAll('a', class_="btn bold mt-4 px-5"))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
<p>output:</p>
```Status: 200
Content-type: text/html; charset=UTF-8
[Ver {{ (current_edition=='2021-objeto-2') ? 'Coleção' : 'Obra' }} , AGUARDE, AGUARDE, AGUARDE]
```

Body:
I'm trying to scrape a site using Python with Beautifulsoup, but the site takes a long time to load and the scraping is fast and doesn't recover completely. I would like to know how to wait 5 seconds before retrieving the source code using Beautifulsoup.

I think a code is like this:

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

url = 'https://www.edocente.com.br/pnld/2020/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}

req = Request(url, headers = headers)
response = urlopen(req)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
soup.findAll('a', class_="btn bold mt-4 px-5")

I can't recovery a whole source code because site is slow to load and my tags aren´t recovered. How to wait to recover the whole source code from site?

I would like to get only the text of the href tags, as below:

Ver Obra
Ver Obra
Ver Obra

I'd like to recovery:

/pnld/2020/obra/companhia-das-ciencias-6-ano-saraiva
/pnld/2020/obra/companhia-das-ciencias-7-ano-saraiva
/pnld/2020/obra/companhia-das-ciencias-8-ano-saraiva

How to do it?
Thanks

Body:
You could try to get a page asynchronously using aiohttp and asyncio. For example let’s pass that url to query and headers as parameters to ClientSession instance, now we have a ClientResponse object called resp and you can get all the information you need from the response.

install modules by: pip install cchardet aiodns aiohttp aiotthp[speedups]

import aiohttp
import asyncio
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import ssl

#ssl._create_default_https_context = ssl._create_unverified_context
url = 'https://www.edocente.com.br/pnld/2020/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
html = ''

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers, verify_ssl=False) as response:
            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])
            html = await response.text()
            soup = BeautifulSoup(html, 'html.parser')
            print(soup.findAll('a', class_="btn bold mt-4 px-5"))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

output:

Status: 200
Content-type: text/html; charset=UTF-8
[<a :href="linkPrefixo + obra.tituloSeo" class="btn bold mt-4 px-5">Ver {{ (current_edition=='2021-objeto-2') ? 'Coleção' : 'Obra' }} </a>, <a class="btn bold mt-4 px-5">AGUARDE</a>, <a class="btn bold mt-4 px-5">AGUARDE</a>, <a class="btn bold mt-4 px-5">AGUARDE</a>]


问:
How to filter by date in Eloquent relationship
I've two tables first_levels and second_levels the first_levels have a relationship with themselves as parent and child and in the second table, I store the transactions.

my Model:

```<code>
    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')
            ->with(['children', 'transactions'])
            ->withsum('transactions', 'debit')
            ->withsum('transactions', 'credit');
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }

</code>```

my controller:

```<code>    function getGeneralLedger(Request $request)
    {
        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->where('company_id', $request->user()->company_id)
            ->get();
        return response()->json(['data' => $items]);
    }
</code>```

using this model and controller I can get all the data from the first and second tables but when I want to filter the second table based on the created_at column I'm unable to do it.

I tried this method but it didn't work.

```<code>    function getGeneralLedger(Request $request)
    {
        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->where('company_id', $request->user()->company_id)
            ->wherebetween('children.transactions.created_at', [$request->from, $request->to])
            ->get();
        return response()->json(['data' => $items]);
    }
</code>```

I get this error

```<code>Column not found: 1054 Unknown column 'children.transactions.created_at' in 'where clause' (SQL: select * from `first_levels` where `parent_id` = 0 and `company_id` = 1 and `children`.`transactions`.`created_at` between 2022-01-10 and 2022-02-09)",
</code>```

答:
try

```<code>function getGeneralLedger(Request $request)
{
    $items = first_level::with('children')
        ->where('parent_id', 0)
        ->where('company_id', $request->user()->company_id)
        ->whereHas('children.transactions', function ($q) use ($request) {
            $q->wherebetween('created_at', [$request->from, $request->to]);
        })
        ->get();
    return response()->json(['data' => $items]);
}
</code>```

Source: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

Body:
I've two tables first_levels and second_levels the first_levels have a relationship with themselves as parent and child and in the second table, I store the transactions.

my Model:

    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')
            ->with(['children', 'transactions'])
            ->withsum('transactions', 'debit')
            ->withsum('transactions', 'credit');
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }

my controller:

    function getGeneralLedger(Request $request)
    {
        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->where('company_id', $request->user()->company_id)
            ->get();
        return response()->json(['data' => $items]);
    }

using this model and controller I can get all the data from the first and second tables but when I want to filter the second table based on the created_at column I'm unable to do it.

I tried this method but it didn't work.

    function getGeneralLedger(Request $request)
    {
        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->where('company_id', $request->user()->company_id)
            ->wherebetween('children.transactions.created_at', [$request->from, $request->to])
            ->get();
        return response()->json(['data' => $items]);
    }

I get this error

Column not found: 1054 Unknown column 'children.transactions.created_at' in 'where clause' (SQL: select * from `first_levels` where `parent_id` = 0 and `company_id` = 1 and `children`.`transactions`.`created_at` between 2022-01-10 and 2022-02-09)",

Body:
try

function getGeneralLedger(Request $request)
{
    $items = first_level::with('children')
        ->where('parent_id', 0)
        ->where('company_id', $request->user()->company_id)
        ->whereHas('children.transactions', function ($q) use ($request) {
            $q->wherebetween('created_at', [$request->from, $request->to]);
        })
        ->get();
    return response()->json(['data' => $items]);
}

Source: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence


问:
Run three regression models based on a label
Im trying to run three different regressions based on the data i was provided with. The idea is to understand how sweetness is linked to bitterness, but that for the three different of ciders we have: {dry, semidry, sweet}.

What i had in mind was to first make a scatter plot with all the x values, regardless of the kind of cider we have, and then make three different regression models, based on three different 'sliced' panda df, x_dry, x_semidry and x_sweet.

I get an error line 20, saying that im essentially multiplying an int with a numpy array. So to start solving my problem, i tried to list(myarray). However the error persists. Can someone point me in the right direction here?

the error i get:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-138-fa4209c61f04> in <module>
     20     return slope*i + intercept
     21
---> 22 mymodeldry = list(map(myfunc, x_dry))
     23 mymodelsemidry = list(map(myfunc, x_semidry))
     24 mymodelsweet = list(map(myfunc, x_sweet))

<ipython-input-138-fa4209c61f04> in myfunc(i)
     18
     19 def myfunc(i):
---> 20     return slope*i + intercept
     21
     22 mymodeldry = list(map(myfunc, x_dry))

TypeError: can't multiply sequence by non-int of type 'numpy.float64'
</code>```

My code

```<code># d) Represent the sweet flavor according to the bitter flavor and add the regression line, for each type of cider.
x = list(ciderdf["Sweetness"])

x_dry = ciderdf[ciderdf["Type"]=="Dry"]
x_dry = list(x_dry[["Sweetness"]])

x_semidry = ciderdf[ciderdf["Type"]=="Semi-dry"]
x_semidry = list(x_semidry[["Sweetness"]])

x_sweet = ciderdf[ciderdf["Type"]=="Sweet"]
x_sweet = list(x_sweet[["Sweetness"]])

y = list(ciderdf["Bitterness"])

slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(i):
    return slope*i + intercept

mymodeldry = list(map(myfunc, x_dry))
mymodelsemidry = list(map(myfunc, x_semidry))
mymodelsweet = list(map(myfunc, x_sweet))

plt.scatter(x,y)
plt.plot(x, mymodeldry, mymodelsemidry, mymodelsweet)
plt.show()
</code>```

答:
You're actually multiplying a list by a float, which is not possible.
That is in fact possible only with int since multiplying a list by a number n repeats the list n times.

I think you wanted to multiply each element of the list by a float value, which you can achieve by transforming the list x_dry = list(x_dry[["Sweetness"]]) in a numpy array x_dry = np.array(list(x_dry[["Sweetness"]]))

Body:
Im trying to run three different regressions based on the data i was provided with. The idea is to understand how sweetness is linked to bitterness, but that for the three different of ciders we have: {dry, semidry, sweet}.

What i had in mind was to first make a scatter plot with all the x values, regardless of the kind of cider we have, and then make three different regression models, based on three different 'sliced' panda df, x_dry, x_semidry and x_sweet.

I get an error line 20, saying that im essentially multiplying an int with a numpy array. So to start solving my problem, i tried to list(myarray). However the error persists. Can someone point me in the right direction here?

the error i get:

TypeError                                 Traceback (most recent call last)
<ipython-input-138-fa4209c61f04> in <module>
     20     return slope*i + intercept
     21
---> 22 mymodeldry = list(map(myfunc, x_dry))
     23 mymodelsemidry = list(map(myfunc, x_semidry))
     24 mymodelsweet = list(map(myfunc, x_sweet))

<ipython-input-138-fa4209c61f04> in myfunc(i)
     18
     19 def myfunc(i):
---> 20     return slope*i + intercept
     21
     22 mymodeldry = list(map(myfunc, x_dry))

TypeError: can't multiply sequence by non-int of type 'numpy.float64'

My code

# d) Represent the sweet flavor according to the bitter flavor and add the regression line, for each type of cider.
x = list(ciderdf["Sweetness"])

x_dry = ciderdf[ciderdf["Type"]=="Dry"]
x_dry = list(x_dry[["Sweetness"]])

x_semidry = ciderdf[ciderdf["Type"]=="Semi-dry"]
x_semidry = list(x_semidry[["Sweetness"]])

x_sweet = ciderdf[ciderdf["Type"]=="Sweet"]
x_sweet = list(x_sweet[["Sweetness"]])

y = list(ciderdf["Bitterness"])

slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(i):
    return slope*i + intercept

mymodeldry = list(map(myfunc, x_dry))
mymodelsemidry = list(map(myfunc, x_semidry))
mymodelsweet = list(map(myfunc, x_sweet))

plt.scatter(x,y)
plt.plot(x, mymodeldry, mymodelsemidry, mymodelsweet)
plt.show()


问:
How to enable basic authentication in Atlantis?
I'm trying to enable basic auth for atlantis I have followed the official docs here however it seems the below settings are not honored by atlantis

```<code>docker run runatlantis/atlantis:v0.18.1 server --gitlab-user=username --gitlab-token=token --web-basic-auth=true --web-username=admin --web-password=password --repo-allowlist="gitlab.com/group/*"
</code>```

When the server is running I can login without username/password

答:
According to https://github.com/runatlantis/atlantis/releases/tag/v0.18.2 version v0.18.2 has fixed issue with basic auth

fix: add back basic auth support by @Aayyush in #2008

```<code>docker run runatlantis/atlantis:v0.18.2 server --gitlab-user=username --gitlab-token=token --web-basic-auth=true --web-username=admin --web-password=password --repo-allowlist="gitlab.com/group/*"
</code>```

Body:
I'm trying to enable basic auth for atlantis I have followed the official docs here however it seems the below settings are not honored by atlantis

docker run runatlantis/atlantis:v0.18.1 server --gitlab-user=username --gitlab-token=token --web-basic-auth=true --web-username=admin --web-password=password --repo-allowlist="gitlab.com/group/*"

When the server is running I can login without username/password

Body:
According to https://github.com/runatlantis/atlantis/releases/tag/v0.18.2 version v0.18.2 has fixed issue with basic auth

fix: add back basic auth support by @Aayyush in #2008

docker run runatlantis/atlantis:v0.18.2 server --gitlab-user=username --gitlab-token=token --web-basic-auth=true --web-username=admin --web-password=password --repo-allowlist="gitlab.com/group/*"


问:
C++ Initializer lists
I have to fill a std::vector with elements of type struct MHD_OptionItem.
This struct have this implementation:

```<code>struct MHD_OptionItem
{
    enum MHD_OPTION option;
    intptr_t value;
    void *ptr_value;
 };
</code>```

I have tried this way:

```<code> vector<struct MHD_OptionItem> iov;
 if(...)
     iov.push_back({ MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL });
 if(...)
     iov.push_back({ MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout });
 [....]
</code>```

but the g++ compiler, as expected, says to me:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

I know that I can initialize a temporary struct and then pass it to the vector, but this method seems to me to be inefficient and not so elegant.

I can't change the struct inserting a constructor because this is not my code but a library included.

There is an elegant way to do this without using c++0x syntax?

答:
You have to create a constructor for your struct.

```<code>struct MHD_OptionItem
{
    MHD_OptionItem(enum MHD_OPTION _option, intptr_t _value, void *_ptr_value)
    : option(_option), value(_value), ptr_value(_ptr_value) {}
    enum MHD_OPTION option;
    intptr_t value;
    void *ptr_value;
};
</code>```

Then you can initialize this way:

```<code>ov.push_back(MHD_OptionItem(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++ Initializer lists

Body:
I have to fill a std::vector with elements of type struct MHD_OptionItem.
This struct have this implementation:

struct MHD_OptionItem
{
    enum MHD_OPTION option;
    intptr_t value;
    void *ptr_value;
 };

I have tried this way:

 vector<struct MHD_OptionItem> iov;
 if(...)
     iov.push_back({ MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL });
 if(...)
     iov.push_back({ MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout });
 [....]

but the g++ compiler, as expected, says to me:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

I know that I can initialize a temporary struct and then pass it to the vector, but this method seems to me to be inefficient and not so elegant.

I can't change the struct inserting a constructor because this is not my code but a library included.

There is an elegant way to do this without using c++0x syntax?

Body:
You have to create a constructor for your struct.

struct MHD_OptionItem
{
    MHD_OptionItem(enum MHD_OPTION _option, intptr_t _value, void *_ptr_value)
    : option(_option), value(_value), ptr_value(_ptr_value) {}
    enum MHD_OPTION option;
    intptr_t value;
    void *ptr_value;
};

Then you can initialize this way:

ov.push_back(MHD_OptionItem(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));


问:
Redshift generate rows as many as value in another column
df

```<code>customer_code contract_code    product  num_products
    C0134        AB01245        toy_1        4
    B8328        EF28421        doll_4       2
</code>```

I would like to transform this table based on the integer value in column num_products and generate a unique id for each row:

Expected_df

```<code>unique_id  customer_code contract_code     product      num_products
      A1           C0134        AB01245        toy_1        1
      A2           C0134        AB01245        toy_1        1
      A3           C0134        AB01245        toy_1        1
      A4           C0134        AB01245        toy_1        1
      A5           B8328        EF28421        doll_4       1
      A6           B8328        EF28421        doll_4       1
</code>```

unique_id can be any random characters as long as I can use a count(distinct) on it later on.
I read that generate_series(1,10000) i is available in later versions of Postgres but not in Redshift

答:
You need to use a recursive CTE to generate the series of number.  Then join this with you data to produce the extra rows.  I used row_number() to get the unique_id in the example below.

This should meet you needs or at least give you a start:

```<code>create table df (customer_code varchar(16),
                 contract_code varchar(16),
                 product varchar(16),
                 num_products int);

insert into df values
('C0134', 'AB01245', 'toy_1', 4),
('B8328', 'EF28421', 'doll_4', 2);

with recursive nums (n) as
( select 1 as n
  union all
  select n+1 as n
  from nums
  where n < (select max(num_products) from df) )
select row_number() over() as unique_id, customer_code, contract_code, product, num_products
from df d
left join nums n
on d.num_products >= n.n;
</code>```

SQLfiddle at http://sqlfiddle.com/#!15/d829b/12

Body:
df

customer_code contract_code    product  num_products
    C0134        AB01245        toy_1        4
    B8328        EF28421        doll_4       2

I would like to transform this table based on the integer value in column num_products and generate a unique id for each row:

Expected_df

unique_id  customer_code contract_code     product      num_products
      A1           C0134        AB01245        toy_1        1
      A2           C0134        AB01245        toy_1        1
      A3           C0134        AB01245        toy_1        1
      A4           C0134        AB01245        toy_1        1
      A5           B8328        EF28421        doll_4       1
      A6           B8328        EF28421        doll_4       1

unique_id can be any random characters as long as I can use a count(distinct) on it later on.
I read that generate_series(1,10000) i is available in later versions of Postgres but not in Redshift

Body:
You need to use a recursive CTE to generate the series of number.  Then join this with you data to produce the extra rows.  I used row_number() to get the unique_id in the example below.

This should meet you needs or at least give you a start:

create table df (customer_code varchar(16),
                 contract_code varchar(16),
                 product varchar(16),
                 num_products int);

insert into df values
('C0134', 'AB01245', 'toy_1', 4),
('B8328', 'EF28421', 'doll_4', 2);

with recursive nums (n) as
( select 1 as n
  union all
  select n+1 as n
  from nums
  where n < (select max(num_products) from df) )
select row_number() over() as unique_id, customer_code, contract_code, product, num_products
from df d
left join nums n
on d.num_products >= n.n;

SQLfiddle at http://sqlfiddle.com/#!15/d829b/12


问:
Incompatible types: 'string' and 'Boolean'
I have to check for a sound card, so I don't need quality but only one answer yes or no. I used this code:

```<code>function IsSoundCardInstalled: Boolean;
Begin
   Result := waveOutGetNumDevs > 0;
End;

procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
  myStringList: TStringList;
begin
  ids := TidIpWatch.Create;
  Speed := GetCPUSpeed;
  ids.Free;

  myStringList:=TStringList.Create;
  myStringList.Add('IP:' + (ids.LocalIP));
  myStringList.Add('CPU: ' + (Tipo_cpu) + ' ' + Format('%f', [Speed]));
  myStringList.Add((IsSoundCardInstalled));
  myStringList.Add('etc.');

  Memo1.Lines.Assign(myStringList);

  myStringList.Free;
end;
</code>```

But the error returns to me:

[DCC Error] Unit1.pas(138): E2010 Incompatible types: 'string' and 'Boolean'

On the line:

```<code>myStringList.Add((IsSoundCardInstalled));
</code>```

答:
IsSoundCardInstalled() returns a Boolean, but myStringList.Add() expects a string instead. You can't assign a Boolean as-is to a string, you need to use a conversion function (just like in your previous question), such as SysUtils.BoolToStr():

```<code>uses
  ..., SysUtils;

myStringList.Add(BoolToStr(IsSoundCardInstalled));
</code>```

Or SysUtils.TBooleanHelper.ToString() in XE4+:

```<code>uses
  ..., SysUtils;

myStringList.Add(IsSoundCardInstalled.ToString);
</code>```

On a side note: you are freeing the TIdIPWatch component before reading its LocalIP property, which is undefined behavior.

For that matter, you should not be using TIdIPWatch in this manner at all.  It is meant for notifying you when the local IP changes, and for maintaining a history of local IP changes over time, but that is not how you have been using it lately. The TIdIPWatch.LocalIP property simply reads the global GStack.LocalAddress property, that is what you should be using instead:

```<code>uses
  ..., IdStack;

TIdStack.IncUsage;
try
  myStringList.Add('IP:' + GStack.LocalAddress);
finally
  TIdStack.DecUsage;
end;
</code>```

However, a machine can have multiple local IPs, so you really should use GStack.GetLocalAddressList() instead:

```<code>uses
  ..., IdStack;

var
  myLocalIPList: TIdStackLocalAddressList;
  i: Integer;
begin
  ...
  TIdStack.IncUsage;
  try
    myLocalIPList := TIdStackLocalAddressList.Create;
    try
      GStack.GetLocalAddressList(myLocalIPList);
      for I := 0 to myLocalIPList.Count-1 do
        myStringList.Add('IP:' + myLocalIPList[I].IPAddress);
    finally
      list.Free;
    end;
  finally
    TIdStack.DecUsage;
  end;
  ...
end;
</code>```

Body:
I have to check for a sound card, so I don't need quality but only one answer yes or no. I used this code:

function IsSoundCardInstalled: Boolean;
Begin
   Result := waveOutGetNumDevs > 0;
End;

procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
  myStringList: TStringList;
begin
  ids := TidIpWatch.Create;
  Speed := GetCPUSpeed;
  ids.Free;

  myStringList:=TStringList.Create;
  myStringList.Add('IP:' + (ids.LocalIP));
  myStringList.Add('CPU: ' + (Tipo_cpu) + ' ' + Format('%f', [Speed]));
  myStringList.Add((IsSoundCardInstalled));
  myStringList.Add('etc.');

  Memo1.Lines.Assign(myStringList);

  myStringList.Free;
end;

But the error returns to me:

[DCC Error] Unit1.pas(138): E2010 Incompatible types: 'string' and 'Boolean'

On the line:

myStringList.Add((IsSoundCardInstalled));

Body:
IsSoundCardInstalled() returns a Boolean, but myStringList.Add() expects a string instead. You can't assign a Boolean as-is to a string, you need to use a conversion function (just like in your previous question), such as SysUtils.BoolToStr():

uses
  ..., SysUtils;

myStringList.Add(BoolToStr(IsSoundCardInstalled));

Or SysUtils.TBooleanHelper.ToString() in XE4+:

uses
  ..., SysUtils;

myStringList.Add(IsSoundCardInstalled.ToString);

On a side note: you are freeing the TIdIPWatch component before reading its LocalIP property, which is undefined behavior.

For that matter, you should not be using TIdIPWatch in this manner at all.  It is meant for notifying you when the local IP changes, and for maintaining a history of local IP changes over time, but that is not how you have been using it lately. The TIdIPWatch.LocalIP property simply reads the global GStack.LocalAddress property, that is what you should be using instead:

uses
  ..., IdStack;

TIdStack.IncUsage;
try
  myStringList.Add('IP:' + GStack.LocalAddress);
finally
  TIdStack.DecUsage;
end;

However, a machine can have multiple local IPs, so you really should use GStack.GetLocalAddressList() instead:

uses
  ..., IdStack;

var
  myLocalIPList: TIdStackLocalAddressList;
  i: Integer;
begin
  ...
  TIdStack.IncUsage;
  try
    myLocalIPList := TIdStackLocalAddressList.Create;
    try
      GStack.GetLocalAddressList(myLocalIPList);
      for I := 0 to myLocalIPList.Count-1 do
        myStringList.Add('IP:' + myLocalIPList[I].IPAddress);
    finally
      list.Free;
    end;
  finally
    TIdStack.DecUsage;
  end;
  ...
end;


问:
excel VBA for without next(login system)
Hi I was just curious as to why this error occurs when attempting to run the code. The following code is meant to be a login system. The error that occurs is for without next and I have tried multiple times to refactor the code and it still isn't working. I don't have much experience in VBA so any help would be appreciated thanks.</p>
```<code>Sub CommandButton1_Click()
Dim Username As String
Username = Range("D6").Value
UsernameLength = Len(Username)
MsgBox (UsernameLength)

Dim PasswordLength As String
Password = Range("D10").Value
PasswordLength = Len(Password)
MsgBox ("Password length is:" + PasswordLength)

If PasswordLength = 0 And UsernameLength = 0 Then
  MsgBox ("Please enter login details or create an account")
Else
Set rng = Range("A1:A1000")
For Each row In rng.Rows
For Each cell In row.Cells
            Username_Lines = Username_Lines + 1
            Password_Lines = Password_Lines + 1
            If cell = Username Then
                Correct_Username = True
                a = Username_Lines
                Lines = a - b
                MsgBox ("True")
                Stop
            Else
               Correct_Password = False
               Correct_Username = False
               MsgBox ("False")
               End If
               Next
If Lines = 0 Then
    Correct_Password = True
    Correct_Username = True
Else:
    Correct_Password = False
    Correct_Username = False
    End If

If Correct_Password And Correct_Username = True Then
        Worksheets("MainSystem").Visible = xlSheetVisible
        Worksheets("LoginSystem").Visible = Not xlSheetVisible

ElseIf Correct_Password = Sql Or Correct_Username = Sql Then
        MsgBox ("Login Failed")

ElseIf Correct_Password And Correct_Username = False Then
        MsgBox ("Login Failed")

Else:
    MsgBox ("Login Failed")

End If
End Sub
</code>```

答:
Consider an alternative to the For Each loops by using Match.

Option Explicit

Private Sub CommandButton1_Click()
    Dim username As String, password As String
    Dim ws As Worksheet, lastrow As Long, rng As Range, r

    Set ws = ActiveSheet '  better as Sheets("Sheetname")
    With ws
        username = .Range("D6").Value
        password = .Range("D10").Value
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Set rng = .Range("A1:A" & lastrow)
    End With

    If Len(username) = 0 Or Len(password) = 0 Then
        MsgBox "Please enter login details or create an account", vbCritical
        Exit Sub
    End If

    ' find username
    r = Application.Match(username, rng, 0)
    If IsError(r) Then
         MsgBox ("Login Failed")
    Else
        If ws.Cells(r, "B") = password Then
            MsgBox ("Login OK")
            Sheets("MainSystem").Visible = xlSheetVisible
            Sheets("LoginSystem").Visible = xlSheetHidden
        Else
            MsgBox ("Login Failed")
        End If
    End If
End Sub
```

Body:
Hi I was just curious as to why this error occurs when attempting to run the code. The following code is meant to be a login system. The error that occurs is for without next and I have tried multiple times to refactor the code and it still isn't working. I don't have much experience in VBA so any help would be appreciated thanks.

Sub CommandButton1_Click()
Dim Username As String
Username = Range("D6").Value
UsernameLength = Len(Username)
MsgBox (UsernameLength)

Dim PasswordLength As String
Password = Range("D10").Value
PasswordLength = Len(Password)
MsgBox ("Password length is:" + PasswordLength)

If PasswordLength = 0 And UsernameLength = 0 Then
  MsgBox ("Please enter login details or create an account")
Else
Set rng = Range("A1:A1000")
For Each row In rng.Rows
For Each cell In row.Cells
            Username_Lines = Username_Lines + 1
            Password_Lines = Password_Lines + 1
            If cell = Username Then
                Correct_Username = True
                a = Username_Lines
                Lines = a - b
                MsgBox ("True")
                Stop
            Else
               Correct_Password = False
               Correct_Username = False
               MsgBox ("False")
               End If
               Next
If Lines = 0 Then
    Correct_Password = True
    Correct_Username = True
Else:
    Correct_Password = False
    Correct_Username = False
    End If

If Correct_Password And Correct_Username = True Then
        Worksheets("MainSystem").Visible = xlSheetVisible
        Worksheets("LoginSystem").Visible = Not xlSheetVisible

ElseIf Correct_Password = Sql Or Correct_Username = Sql Then
        MsgBox ("Login Failed")

ElseIf Correct_Password And Correct_Username = False Then
        MsgBox ("Login Failed")

Else:
    MsgBox ("Login Failed")

End If
End Sub


问:
Interrupt optim and retrieve the last set of parameters tested
I want to use optim to minimize a function but it takes quite long to converge. Thus, I want to interrupt optim when I see the parameters it plugs in are stuck around some numbers. I wonder if I can keep track of both the function value and the parameters along the way. I can only see the function values when I set control(list(trace=TRUE)).

Please see a replicable example (much simpler than what I have to work on) as below:

g <- function(x){x[1]^2+x[2]^2}

optim(par=c(1,1), g, control = list(trace=TRUE))

Thank you!

Body:
Add an on.exit which saves the information.  Before running optim set .optim to NULL to ensure that we are not looking at an .optim from a prior run.

g <- function(x) {
  on.exit(.optim <<- list(x = x, obj = print(returnValue())))
  x[1]^2+x[2]^2
}

.optim <- NULL
optim(par = c(1, 1), g, control = list(trace = TRUE))

giving:

  Nelder-Mead direct search function minimizer
[1] 2
function value for initial parameters = 2.000000
  Scaled convergence tolerance is 2.98023e-08
Stepsize computed as 0.100000
[1] 2.21
[1] 2.21
BUILD              3 2.210000 2.000000
[1] 2.02
[1] 2.058125
LO-REDUCTION       5 2.210000 2.000000
[1] 1.81
[1] 1.625
EXTENSION          7 2.020000 1.625000
[1] 1.625
[1] 1.711562
LO-REDUCTION       9 2.000000 1.625000
[1] 1.28
[1] 0.98
EXTENSION         11 1.625000 0.980000
[1] 1
[1] 1.132812
LO-REDUCTION      13 1.625000 0.980000
[1] 0.505
[1] 0.185
EXTENSION         15 1.000000 0.185000
[1] 0.185
[1] 0.3203125
LO-REDUCTION      17 0.980000 0.185000
[1] 0.02
[1] 0.5
REFLECTION        19 0.185000 0.020000
[1] 0.04
[1] 0.0078125
LO-REDUCTION      21 0.185000 0.007813
[1] 0.3203125
[1] 0.03455078
HI-REDUCTION      23 0.034551 0.007813
[1] 0.102207
[1] 0.005395508
HI-REDUCTION      25 0.020000 0.005396
[1] 0.05719238
[1] 0.004512024
HI-REDUCTION      27 0.007813 0.004512
[1] 2.716064e-05
[1] 0.002380447
REFLECTION        29 0.005396 0.000027
[1] 0.01355591
[1] 0.00123909
HI-REDUCTION      31 0.004512 0.000027
[1] 0.004123611
[1] 0.001166844
LO-REDUCTION      33 0.001239 0.000027
[1] 0.001268125
[1] 0.0004683784
HI-REDUCTION      35 0.001167 0.000027
[1] 0.0007208946
[1] 0.0001780652
LO-REDUCTION      37 0.000468 0.000027
[1] 0.0009161481
[1] 0.0001085663
HI-REDUCTION      39 0.000178 0.000027
[1] 7.815627e-05
[1] 1.762216e-05
LO-REDUCTION      41 0.000109 0.000018
[1] 0.0001409279
[1] 2.349272e-05
HI-REDUCTION      43 0.000027 0.000018
[1] 0.0001703958
[1] 8.496039e-07
HI-REDUCTION      45 0.000023 0.000001
[1] 1.338207e-05
[1] 4.260709e-06
LO-REDUCTION      47 0.000018 0.000001
[1] 1.625014e-05
[1] 4.21486e-06
LO-REDUCTION      49 0.000004 0.000001
[1] 1.599159e-05
[1] 9.538017e-07
HI-REDUCTION      51 0.000004 0.000001
[1] 1.042423e-06
[1] 6.601059e-08
LO-REDUCTION      53 0.000001 0.000000
[1] 2.402063e-06
[1] 1.632133e-07
HI-REDUCTION      55 0.000001 0.000000
[1] 1.322682e-06
[1] 1.711765e-07
HI-REDUCTION      57 0.000000 0.000000
[1] 4.077154e-07
[1] 3.113701e-08
HI-REDUCTION      59 0.000000 0.000000
[1] 2.398648e-07
[1] 3.284831e-08
HI-REDUCTION      61 0.000000 0.000000
[1] 3.007464e-07
[1] 4.091568e-09
Exiting from Nelder Mead minimizer
    63 function evaluations used
$par
[1] 3.754010e-05 5.179101e-05

$value
[1] 4.091568e-09

$counts
function gradient
      63       NA

$convergence
[1] 0

$message
NULL

and we can look at the last value of .optim which in this case is the return value from optim but might not be if it were stopped early.

> .optim
$x
[1] 3.754010e-05 5.179101e-05

$obj
[1] 4.091568e-09


问:
best way to join query fields, union all/union
I have 4 fields
cnpj 1
cnpj 2
cnpj 3
cnpj 4
all with the same typing, these fields go through an IN filter, for that I use UNION ALL in all 4 fields, is there a way to do this without union all ? or is it really the best way?</p>
```<code> select id
 from ( select id from db_armazenamento..arquivo_conhecimento
 WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
and cpf_cnpj_emitente COLLATE database_default in (SELECT cnpj from
  db_armazenamento..INTEGRA_ORCL_CTE)
    union all
select id from db_armazenamento..arquivo_conhecimento
WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
and cpf_cnpj_destinatario COLLATE database_default in (SELECT cnpj from
db_armazenamento..INTEGRA_ORCL_CTE)
    union all
select id from db_armazenamento..arquivo_conhecimento
WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
and cpf_cnpj_remetente COLLATE database_default in (SELECT cnpj from
db_armazenamento..INTEGRA_ORCL_CTE)
   union all
select id from db_armazenamento..arquivo_conhecimento
WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
  and cpf_cnpj_recebedor COLLATE database_default in (SELECT cnpj from
  db_armazenamento..INTEGRA_ORCL_CTE)
) as c
</code>```

答:
To be honest I don't know why you keep selecting the rows over and over and over from the same table and then compare them to different columns be equal in another table. Pretty sure you could simplify the whole thing into something like this.</p>
```<code>SELECT ac.id
    FROM db_armazenamento.dbo.arquivo_conhecimento ac --you really should be explicit with the schema instead of relying on the default
    join db_armazenamento.dbo.INTEGRA_ORCL_CTE ioc on ioc.cnpj in
                                                            (
                                                                ac.cpf_cnpj_emitente
                                                                , ac.cpf_cnpj_destinatario
                                                                , ac.cpf_cnpj_remetente
                                                                , ac.cpf_cnpj_recebedor
                                                            )
where ac.dta_inclusao >= dateadd(day, -20, getdate()
    and ac.dta_inclusao <= getdate()
</code>```

Body:
I have 4 fields
cnpj 1
cnpj 2
cnpj 3
cnpj 4
all with the same typing, these fields go through an IN filter, for that I use UNION ALL in all 4 fields, is there a way to do this without union all ? or is it really the best way?

 select id
 from ( select id from db_armazenamento..arquivo_conhecimento
 WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
and cpf_cnpj_emitente COLLATE database_default in (SELECT cnpj from
  db_armazenamento..INTEGRA_ORCL_CTE)
    union all
select id from db_armazenamento..arquivo_conhecimento
WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
and cpf_cnpj_destinatario COLLATE database_default in (SELECT cnpj from
db_armazenamento..INTEGRA_ORCL_CTE)
    union all
select id from db_armazenamento..arquivo_conhecimento
WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
and cpf_cnpj_remetente COLLATE database_default in (SELECT cnpj from
db_armazenamento..INTEGRA_ORCL_CTE)
   union all
select id from db_armazenamento..arquivo_conhecimento
WITH(INDEX(IX_arquivo_conhecimento_6),nolock)
        where dta_inclusao between getdate () -20 and getdate ()
  and cpf_cnpj_recebedor COLLATE database_default in (SELECT cnpj from
  db_armazenamento..INTEGRA_ORCL_CTE)
) as c

Body:
To be honest I don't know why you keep selecting the rows over and over and over from the same table and then compare them to different columns be equal in another table. Pretty sure you could simplify the whole thing into something like this.

SELECT ac.id
    FROM db_armazenamento.dbo.arquivo_conhecimento ac --you really should be explicit with the schema instead of relying on the default
    join db_armazenamento.dbo.INTEGRA_ORCL_CTE ioc on ioc.cnpj in
                                                            (
                                                                ac.cpf_cnpj_emitente
                                                                , ac.cpf_cnpj_destinatario
                                                                , ac.cpf_cnpj_remetente
                                                                , ac.cpf_cnpj_recebedor
                                                            )
where ac.dta_inclusao >= dateadd(day, -20, getdate()
    and ac.dta_inclusao <= getdate()


问:
How to run lambda function passed to a mockked method?
I wonder whather it's possible to run a lambda function passed as a parameter to a mocked function. And run it whenever the mocked method is called.

I am using Mockk and I imagine the code to be something like this:

```<code>class DataManager {
   fun submit(lambda: (Int) => Unit) { ... }
}

...

val mock = mockk<DataManager>()

every { mock.submit(lambda = any()) }.run { lambda(5) }
</code>```

In my real implementation the datamanager calls a server and runs the lambda as a callback when it recieves a successful response. The lambda happens to be a private method of the class under test.

答:
Can be solve in the following ways.

with args from answer:

```<code>every { dataManager.submit(any()) } answers {
      firstArg<(Int) -> Unit>().invoke(5)
}
</code>```

or with captureLambda

```<code>every { dataManager.submit(captureLambda()) } answers {
      lambda<(Int) -> Unit>().captured.invoke(5)
}
</code>```

Body:
I wonder whather it's possible to run a lambda function passed as a parameter to a mocked function. And run it whenever the mocked method is called.

I am using Mockk and I imagine the code to be something like this:

class DataManager {
   fun submit(lambda: (Int) => Unit) { ... }
}

...

val mock = mockk<DataManager>()

every { mock.submit(lambda = any()) }.run { lambda(5) }

In my real implementation the datamanager calls a server and runs the lambda as a callback when it recieves a successful response. The lambda happens to be a private method of the class under test.

Body:
Can be solve in the following ways.

with args from answer:

every { dataManager.submit(any()) } answers {
      firstArg<(Int) -> Unit>().invoke(5)
}

or with captureLambda

every { dataManager.submit(captureLambda()) } answers {
      lambda<(Int) -> Unit>().captured.invoke(5)
}


问:
Django DetailView don't show data in template
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

Here the code:

models.py:

```<code>class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name
</code>```

urls.py:

```<code>  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]
</code>```

views.py:

```<code>class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'
</code>```

detail.html:

```<code>{% block content %}
    <h1>Site showing School Detail</h1>
    <div class="container">
        <div class="p-5 text-white bg-dark rounded-3 container">
            <p>Name: {{schooldetail.name}}</p>
            <p>Principal: {{schooldetail.principal}}</p>
            <p>Location: {{schooldetail.location}}</p>
            <h2>Student: </h2>
            {% for student in schooldetail.students.all %}
                <p>{{student.name}} who is {{student.age}} years old</p>
            {% endfor %}
        </div>
    </div>
{% endblock %}
</code>```

Thank you

答:
In School_Detail you use Student as Model instead of School Model.

Change your Model from Student to School as

```<code>class School_Detail(DetailView):
    context_object_name = 'schooldetail'
    model = School                       #<---- change model name here
    template_name = 'basicapp/School_detail.html'
</code>```

Body:
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

Here the code:

models.py:

class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

urls.py:

  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]

views.py:

class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'

detail.html:

{% block content %}

Site showing School Detail

Name: {{schooldetail.name}}

Principal: {{schooldetail.principal}}

Location: {{schooldetail.location}}

Student:

            {% for student in schooldetail.students.all %}

{{student.name}} who is {{student.age}} years old

            {% endfor %}

{% endblock %}

Thank you

Body:
In School_Detail you use Student as Model instead of School Model.

Change your Model from Student to School as

class School_Detail(DetailView):
    context_object_name = 'schooldetail'
    model = School                       #<---- change model name here
    template_name = 'basicapp/School_detail.html'