问:
Trinamic TMC2209 STM32 UART not reading from device
I've been struggling for ages, finally caved and asking for help now.
There are very little resources on STM32 for this driver that I have seen.

I can use the device with the STEP/DIR interface but I want to be able to do the more advanced things now with only the single UART line and not the STEP/DIR lines.

I am trying to control a TMC2209 in the most basic form to understand how it all works, without libraries and such.
I want to get basic controls working so I can understand it and build up my own code from there, right now the goal is to just talk to the thing and get it to spin.

I am using a STM32F103, I have setup the USART3 line (PC10) in signal wire half duplex mode and using the following code to try read from the CHOPCONF register.

```<code>       Sync = 0x05; // sync byte to start the Tx
       Address = 0x00; // MS1 and MS2 are pulled low so the device address is 0
       RegAddress = 0x6C; // Trying for a basic read from the CHOPCONF Reg
       motor_CRC = 0xCA;  // CRC that has been worked out

       HAL_UART_Transmit(&huart3,&Sync,sizeof(Sync),20);
       HAL_UART_Transmit(&huart3,&Address,sizeof(Address),20);
       HAL_UART_Transmit(&huart3,&RegAddress,sizeof(RegAddress),20);
       HAL_UART_Transmit(&huart3,&motor_CRC,sizeof(motor_CRC),20);

// Receive the data from the TMC2209

       HAL_UART_Receive(&huart3, &ReplySync, sizeof(ReplySync), 200);
       HAL_UART_Receive(&huart3, &ReplyMasterAddr, sizeof(ReplyMaster), 20);
       HAL_UART_Receive(&huart3, &ReplyAddr, sizeof(ReplyAddr), 20);
       HAL_UART_Receive(&huart3, &Reply1, sizeof(Reply1), 20);
       HAL_UART_Receive(&huart3, &Reply2, sizeof(Reply2), 20);
       HAL_UART_Receive(&huart3, &Reply3, sizeof(Reply3), 20);
       HAL_UART_Receive(&huart3, &Reply4, sizeof(Reply4), 20);
       HAL_UART_Receive(&huart3, &ReplyCRC, sizeof(ReplyCRC), 20);

       HAL_Delay(1000);
</code>```

I expect the following : ( according to the Datasheet that is,,, )

```<code>ReplySync      >>> 0x05
ReplyMasterAddr>>> 0xFF
ReplyAddr      >>> 0xCA
Reply1         >>> 0x53
Reply2         >>> 0x00
Reply3         >>> 0x00
Reply4         >>> 0x10
ReplyCRC       >>> I dont know this one yet,,,,
</code>```

But I am getting this :

```<code>ReplySync      >>> 0x05
ReplyMasterAddr>>> 0x00
ReplyAddr      >>> 0x5D
Reply1         >>> 0x09
Reply2         >>> 0x08
Reply3         >>> 0x00
Reply4         >>> 0x02
ReplyCRC       >>> 0x09
</code>```

I am not sure if I am transmitting these in the correct order or maybe the HAL function should not be used for this at all ?

Any help or pointers in the right direction would be greatly appreciated.

Body:
I've been struggling for ages, finally caved and asking for help now.
There are very little resources on STM32 for this driver that I have seen.

I can use the device with the STEP/DIR interface but I want to be able to do the more advanced things now with only the single UART line and not the STEP/DIR lines.

I am trying to control a TMC2209 in the most basic form to understand how it all works, without libraries and such.
I want to get basic controls working so I can understand it and build up my own code from there, right now the goal is to just talk to the thing and get it to spin.

I am using a STM32F103, I have setup the USART3 line (PC10) in signal wire half duplex mode and using the following code to try read from the CHOPCONF register.

       Sync = 0x05; // sync byte to start the Tx
       Address = 0x00; // MS1 and MS2 are pulled low so the device address is 0
       RegAddress = 0x6C; // Trying for a basic read from the CHOPCONF Reg
       motor_CRC = 0xCA;  // CRC that has been worked out

       HAL_UART_Transmit(&huart3,&Sync,sizeof(Sync),20);
       HAL_UART_Transmit(&huart3,&Address,sizeof(Address),20);
       HAL_UART_Transmit(&huart3,&RegAddress,sizeof(RegAddress),20);
       HAL_UART_Transmit(&huart3,&motor_CRC,sizeof(motor_CRC),20);

// Receive the data from the TMC2209

       HAL_UART_Receive(&huart3, &ReplySync, sizeof(ReplySync), 200);
       HAL_UART_Receive(&huart3, &ReplyMasterAddr, sizeof(ReplyMaster), 20);
       HAL_UART_Receive(&huart3, &ReplyAddr, sizeof(ReplyAddr), 20);
       HAL_UART_Receive(&huart3, &Reply1, sizeof(Reply1), 20);
       HAL_UART_Receive(&huart3, &Reply2, sizeof(Reply2), 20);
       HAL_UART_Receive(&huart3, &Reply3, sizeof(Reply3), 20);
       HAL_UART_Receive(&huart3, &Reply4, sizeof(Reply4), 20);
       HAL_UART_Receive(&huart3, &ReplyCRC, sizeof(ReplyCRC), 20);

       HAL_Delay(1000);

I expect the following : ( according to the Datasheet that is,,, )

ReplySync      >>> 0x05
ReplyMasterAddr>>> 0xFF
ReplyAddr      >>> 0xCA
Reply1         >>> 0x53
Reply2         >>> 0x00
Reply3         >>> 0x00
Reply4         >>> 0x10
ReplyCRC       >>> I dont know this one yet,,,,

But I am getting this :

ReplySync      >>> 0x05
ReplyMasterAddr>>> 0x00
ReplyAddr      >>> 0x5D
Reply1         >>> 0x09
Reply2         >>> 0x08
Reply3         >>> 0x00
Reply4         >>> 0x02
ReplyCRC       >>> 0x09

I am not sure if I am transmitting these in the correct order or maybe the HAL function should not be used for this at all ?

Any help or pointers in the right direction would be greatly appreciated.


来源: stackexchange

问:
How can I put same records under each other in same column
I have data set of companies,
Each row contain records for 1 company, but columns not contain same records as shown in the pic
I write python code but I couldn't complete it, so can you complete it or give me another solution?
Thanks in advance

I need to create columns to put the similar data in same column, and if the same company has for example 2 email, I need to create columns named email_1, email_2 when needed (for all categories too, even if the column will contain only 1 record)

```<code>import pandas as pd

# Read the csv file
df = pd.read_csv('data.csv')

# Create new columns
df['Telephone'] = ""
df['Mobile'] = ""
df['Email'] = ""
df['Web Site'] = ""
df['Facebook'] = ""
df['Messenger'] = ""
df['Skype'] = ""
df['Twitter'] = ""
df['WhatsApp'] = ""
df['Instagram'] = ""
df['Linkedin'] = ""

# List of the different contact types
contact_types = ['Telephone', 'Mobile', 'Email','Web Site', 'Facebook', 'Messenger', 'Skype', 'Twitter', 'WhatsApp', 'Instagram', 'Linkedin']

# Iterate through each row
for i in range(len(df)):
    c_1 = df.loc[i, 'c_1']
    c_2 = df.loc[i, 'c_2']
    c_3 = df.loc[i, 'c_3']
    c_4 = df.loc[i, 'c_4']
    c_5 = df.loc[i, 'c_5']
    c_6 = df.loc[i, 'c_6']
    c_7 = df.loc[i, 'c_7']
    c_8 = df.loc[i, 'c_8']
    c_9 = df.loc[i, 'c_9']
    c_10 = df.loc[i, 'c_10']
    c_11 = df.loc[i, 'c_11']
    c_12 = df.loc[i, 'c_12']
    c_13 = df.loc[i, 'c_13']
    c_14 = df.loc[i, 'c_14']
    c_15 = df.loc[i, 'c_15']
    c_16 = df.loc[i, 'c_16']
    c_17 = df.loc[i, 'c_17']
    c_18 = df.loc[i, 'c_18']
    c_19 = df.loc[i, 'c_19']
    c_20 = df.loc[i, 'c_20']
    c_21 = df.loc[i, 'c_21']
    c_22 = df.loc[i, 'c_22']
    c_23 = df.loc[i, 'c_23']
    c_24 = df.loc[i, 'c_24']
    c_25 = df.loc[i, 'c_25']
    c_26 = df.loc[i, 'c_26']
    c_27 = df.loc[i, 'c_27']
    c_28 = df.loc[i, 'c_28']
    c_29 = df.loc[i, 'c_29']
    c_30 = df.loc[i, 'c_30']
    c_31 = df.loc[i, 'c_31']
    c_32 = df.loc[i, 'c_32']
    c_33 = df.loc[i, 'c_33']
    c_34 = df.loc[i, 'c_34']
    c_35 = df.loc[i, 'c_35']
    c_36 = df.loc[i, 'c_36']
    c_37 = df.loc[i, 'c_37']
    c_38 = df.loc[i, 'c_38']
    c_39 = df.loc[i, 'c_39']

    contacts = [c_1 , c_2 , c_3 , c_4 , c_5 , c_6 , c_7 , c_8 , c_9 , c_10 , c_11 , c_12 , c_13 , c_14 , c_15 , c_16 , c_17 , c_18 , c_19 , c_20 , c_21 , c_22 , c_23 , c_24 , c_25 , c_26 , c_27 , c_28 , c_29 , c_30 , c_31 , c_32 , c_33 , c_34 , c_35 , c_36 , c_37 , c_38 , c_39]
    for contact in contacts:
        for contact_type in contact_types:
            if contact_type in contact:
                # Check if the column already has data
                if df.loc[i, contact_type] == "":
                    df.loc[i, contact_type] = contact
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have data set of companies,
Each row contain records for 1 company, but columns not contain same records as shown in the pic
I write python code but I couldn't complete it, so can you complete it or give me another solution?
Thanks in advance

I need to create columns to put the similar data in same column, and if the same company has for example 2 email, I need to create columns named email_1, email_2 when needed (for all categories too, even if the column will contain only 1 record)

import pandas as pd

# Read the csv file
df = pd.read_csv('data.csv')

# Create new columns
df['Telephone'] = ""
df['Mobile'] = ""
df['Email'] = ""
df['Web Site'] = ""
df['Facebook'] = ""
df['Messenger'] = ""
df['Skype'] = ""
df['Twitter'] = ""
df['WhatsApp'] = ""
df['Instagram'] = ""
df['Linkedin'] = ""

# List of the different contact types
contact_types = ['Telephone', 'Mobile', 'Email','Web Site', 'Facebook', 'Messenger', 'Skype', 'Twitter', 'WhatsApp', 'Instagram', 'Linkedin']

# Iterate through each row
for i in range(len(df)):
    c_1 = df.loc[i, 'c_1']
    c_2 = df.loc[i, 'c_2']
    c_3 = df.loc[i, 'c_3']
    c_4 = df.loc[i, 'c_4']
    c_5 = df.loc[i, 'c_5']
    c_6 = df.loc[i, 'c_6']
    c_7 = df.loc[i, 'c_7']
    c_8 = df.loc[i, 'c_8']
    c_9 = df.loc[i, 'c_9']
    c_10 = df.loc[i, 'c_10']
    c_11 = df.loc[i, 'c_11']
    c_12 = df.loc[i, 'c_12']
    c_13 = df.loc[i, 'c_13']
    c_14 = df.loc[i, 'c_14']
    c_15 = df.loc[i, 'c_15']
    c_16 = df.loc[i, 'c_16']
    c_17 = df.loc[i, 'c_17']
    c_18 = df.loc[i, 'c_18']
    c_19 = df.loc[i, 'c_19']
    c_20 = df.loc[i, 'c_20']
    c_21 = df.loc[i, 'c_21']
    c_22 = df.loc[i, 'c_22']
    c_23 = df.loc[i, 'c_23']
    c_24 = df.loc[i, 'c_24']
    c_25 = df.loc[i, 'c_25']
    c_26 = df.loc[i, 'c_26']
    c_27 = df.loc[i, 'c_27']
    c_28 = df.loc[i, 'c_28']
    c_29 = df.loc[i, 'c_29']
    c_30 = df.loc[i, 'c_30']
    c_31 = df.loc[i, 'c_31']
    c_32 = df.loc[i, 'c_32']
    c_33 = df.loc[i, 'c_33']
    c_34 = df.loc[i, 'c_34']
    c_35 = df.loc[i, 'c_35']
    c_36 = df.loc[i, 'c_36']
    c_37 = df.loc[i, 'c_37']
    c_38 = df.loc[i, 'c_38']
    c_39 = df.loc[i, 'c_39']

    contacts = [c_1 , c_2 , c_3 , c_4 , c_5 , c_6 , c_7 , c_8 , c_9 , c_10 , c_11 , c_12 , c_13 , c_14 , c_15 , c_16 , c_17 , c_18 , c_19 , c_20 , c_21 , c_22 , c_23 , c_24 , c_25 , c_26 , c_27 , c_28 , c_29 , c_30 , c_31 , c_32 , c_33 , c_34 , c_35 , c_36 , c_37 , c_38 , c_39]
    for contact in contacts:
        for contact_type in contact_types:
            if contact_type in contact:
                # Check if the column already has data
                if df.loc[i, contact_type] == "":
                    df.loc[i, contact_type] = contact


问:
Why do i get an error while performing variable assignment using list indexing?
I was studying this code:

```<code>"""Processes an encoded symbol together with its coefficients."""
def consume_packet(self, coefficients, packet):
    if not self.is_fully_decoded():
        # add new symbol to decoder matrix and packet vector
        self.coefficient_matrix[self.num_independent][0:self.num_symbols] = coefficients
        self.packet_vector[self.num_independent] = packet
</code>```

To help understand the two lines of code inside the if block, I tried this:

```<code>packet = [1, 2, 4]
num_symbols = 3
coefficient_matrix = [1, 2, 4, 5, 6, 7]
coefficient_matrix[0][0:num_symbols] = packet # I think this is supposed to extract the packet
print(coefficient_matrix[0])
print(coefficient_matrix[0][0:num_symbols])
</code>```

but I got an error that says int object does not support item assignment.

Why does this happen?

Body:
I was studying this code:

"""Processes an encoded symbol together with its coefficients."""
def consume_packet(self, coefficients, packet):
    if not self.is_fully_decoded():
        # add new symbol to decoder matrix and packet vector
        self.coefficient_matrix[self.num_independent][0:self.num_symbols] = coefficients
        self.packet_vector[self.num_independent] = packet

To help understand the two lines of code inside the if block, I tried this:

packet = [1, 2, 4]
num_symbols = 3
coefficient_matrix = [1, 2, 4, 5, 6, 7]
coefficient_matrix[0][0:num_symbols] = packet # I think this is supposed to extract the packet
print(coefficient_matrix[0])
print(coefficient_matrix[0][0:num_symbols])

but I got an error that says int object does not support item assignment.

Why does this happen?


问:
How to get the amount of RTV's currently bound?
How to get the exact amount of render targets currently bound to output-merger stage in DirectX11?
I'm using OMGetRenderTargets to retrieve the render targets and depth stencil view, and after my render step I want to set back the previous render targets with OMSetRenderTargets

But OMGetRenderTargets doesn't return the actual amount of RTV's currently bound and I haven't found any info about this in documentation.

It worked perfectly with exactly 1 render target, but if there's more and I don't know the exact amount it does not work at all.

Is this even possible?


问:
undetected_chromedriver can't use Remote browser
so I am currently using UC to bypass a bot protection on a website. For that, it works well but I recently used a new website that is called browserless.io . It is made to use selenium or other similarities, since this browserless.io is online browsers, I can't use UC since it doesn't include the function "Remote". I was wandering if someone had encountered the same problem and if someone had a solution. Thank you in advance.


问:
The api call works properly when run in node, but when adding it into Html it gives network errors
I am trying to learn how to use the api and trying to print the bitcoin value. When running in node the api call is working and giving the correct output, but in html when the pi is called it is giving network errors. I tried running it in different ide's and applied other things i found on google but had no luck.

Heres my current code,

```<code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Geo Guesser</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <h1 id="price"></h1>

  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
      <script>
      const apiKey = "key";
      const url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?                       symbol=BTC&CMC_PRO_API_KEY=${apiKey}`;

      window.onload = function() {
        axios.get(url)
        .then(response => {
          const bitcoinData = response.data.data.BTC;
          const price = bitcoinData.quote.USD.price;
          document.getElementById("price").innerHTML = `Bitcoin price: $${price}`;
        })
        .catch(error => console.log(error))
      }
    </script>

</body>

</html>
</code>```

Also, do u recomend using a different api?
Thank you in advacne

I tried different methods to calll the api, fetch, azios, etc.
Double checked the key and links and api documentation.
Made sure calls were being made by checking the console

Body:
I am trying to learn how to use the api and trying to print the bitcoin value. When running in node the api call is working and giving the correct output, but in html when the pi is called it is giving network errors. I tried running it in different ide's and applied other things i found on google but had no luck.

Heres my current code,

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Geo Guesser</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

Also, do u recomend using a different api?
Thank you in advacne

I tried different methods to calll the api, fetch, azios, etc.
Double checked the key and links and api documentation.
Made sure calls were being made by checking the console


问:
How to write DAX function to calculate database growth? DATESBETWEEN not gives the answer what I want
Database part

I have created a table:

Here is the postgresql query that I have use to create this table,

```<code>INSERT INTO growth_test.trax_qa_db_growth
SELECT
       now()::date as executed_date,
       schemaname as table_schema,
       relname as table_name,
       pg_size_pretty(pg_relation_size(relid)) as data_size,
       pg_relation_size(relid) as full_data_size
FROM pg_catalog.pg_statio_user_tables
WHERE schemaname='production'
order by pg_relation_size(relid) desc;
</code>```

Power BI part

I have to get the data in this table to powerbi. I want to visualize the size of db growth based on  "full_data_size" column based on specific two dates using sliser. How can I visualize dbgrowth based on specific takes?

I have tried the "DATESBETWEEN" but that not give the output that I want.

Start Date & End Date are the measures that I have create for the sliser,

DAX function

```<code>Data Size in the period =
VAR total =
    SUM ( trax_qa_db_growth[full_data_size] ) + 0
RETURN
IF (
        total < 1024,
       CALCULATE(FORMAT ( total, "#0.0# B" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
        IF (
            total < POWER ( 2, 20 ),
            CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
            IF (
                total < POWER ( 2, 30 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 20 ), "#0.0# MB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
                IF (
                total < POWER ( 2, 40 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 30 ), "#0.0# GB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
                CALCULATE(FORMAT ( total / POWER ( 2, 40 ), "#0.0# TB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date]))
        )
    )

   ))
</code>```

This DAX function didn't provide me the result the way I want. Instead it shows the size from full_db_size.
So, I have tried some different method.  I hope that will be the correct way.

New DAX function

```<code>Data Size in the period =
VAR total =
    SUM ( trax_qa_db_growth[full_data_size] ) + 0
RETURN
IF (
        total < 1024,
       CALCULATE(FORMAT ( total, "#0.0# B" )),
        IF (
            total < POWER ( 2, 20 ),
            CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date])),
            IF (
                total < POWER ( 2, 30 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 20 ), "#0.0# MB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date])),
                IF (
                total < POWER ( 2, 40 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 30 ), "#0.0# GB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date])),
                CALCULATE(FORMAT ( total / POWER ( 2, 40 ), "#0.0# TB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date]))
        )
    )

   ))
</code>```

What is the issue with the "New DAX function"? How to calculate the DB growth?

Is there any way to calculate db growth in postgresql? (In the oracle DB has that type of options)

Body:
Database part

I have created a table:

Here is the postgresql query that I have use to create this table,

INSERT INTO growth_test.trax_qa_db_growth
SELECT
       now()::date as executed_date,
       schemaname as table_schema,
       relname as table_name,
       pg_size_pretty(pg_relation_size(relid)) as data_size,
       pg_relation_size(relid) as full_data_size
FROM pg_catalog.pg_statio_user_tables
WHERE schemaname='production'
order by pg_relation_size(relid) desc;

Power BI part

I have to get the data in this table to powerbi. I want to visualize the size of db growth based on  "full_data_size" column based on specific two dates using sliser. How can I visualize dbgrowth based on specific takes?

I have tried the "DATESBETWEEN" but that not give the output that I want.

Start Date & End Date are the measures that I have create for the sliser,

DAX function

Data Size in the period =
VAR total =
    SUM ( trax_qa_db_growth[full_data_size] ) + 0
RETURN
IF (
        total < 1024,
       CALCULATE(FORMAT ( total, "#0.0# B" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
        IF (
            total < POWER ( 2, 20 ),
            CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
            IF (
                total < POWER ( 2, 30 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 20 ), "#0.0# MB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
                IF (
                total < POWER ( 2, 40 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 30 ), "#0.0# GB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date])),
                CALCULATE(FORMAT ( total / POWER ( 2, 40 ), "#0.0# TB" ),DATESBETWEEN('trax_qa_db_growth'[executed_date],[Start Date],[End Date]))
        )
    )

   ))

This DAX function didn't provide me the result the way I want. Instead it shows the size from full_db_size.
So, I have tried some different method.  I hope that will be the correct way.

New DAX function

Data Size in the period =
VAR total =
    SUM ( trax_qa_db_growth[full_data_size] ) + 0
RETURN
IF (
        total < 1024,
       CALCULATE(FORMAT ( total, "#0.0# B" )),
        IF (
            total < POWER ( 2, 20 ),
            CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date])),
            IF (
                total < POWER ( 2, 30 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 20 ), "#0.0# MB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date])),
                IF (
                total < POWER ( 2, 40 ),
                CALCULATE(FORMAT ( total / POWER ( 2, 30 ), "#0.0# GB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date])),
                CALCULATE(FORMAT ( total / POWER ( 2, 40 ), "#0.0# TB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [End Date]))-CALCULATE(FORMAT ( total / POWER ( 2, 10 ), "#0.0# KB" ),FILTER(trax_qa_db_growth, trax_qa_db_growth[executed_date] = [Start Date]))
        )
    )

   ))

What is the issue with the "New DAX function"? How to calculate the DB growth?

Is there any way to calculate db growth in postgresql? (In the oracle DB has that type of options)


问:
Execution order of onSubscribe(), map() and flatMap()
In a simple demo program I compared the output of Mono.just().map().subscribe() and Mono.just().flatMap().subscribe(), to my surprise map() is executed after onSubscribe() but flatMap() is before.

The program:

    public static void main(@Nonnull String[] args) {
        // 1. Case with map()
        Mono.just(1).map(number -> {
            System.out.printf("[%s] mapping:%d%n", threadName(), number);
            return number * 10;

        }).subscribe(buildSubscriber());

        // 2. Case with flatMap()
        System.out.println();
        Mono.just(1).flatMap(number -> {
            System.out.printf("[%s] flat-mapping:%d%n", threadName(), number);
            return Mono.just(number * 10);

        }).subscribe(buildSubscriber());
    }

    @SuppressWarnings("ReactiveStreamsSubscriberImplementation")
    @Nonnull
    private static Subscriber<Integer> buildSubscriber() {
        return new Subscriber<>() {
            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription subscription) {
                System.out.printf("[%s] onSubscribe%n", threadName());
                this.subscription = subscription;
                subscription.request(1);
            }

            @Override
            public void onNext(Integer item) {
                System.out.printf("[%s] onNext:%s%n", threadName(), item);
                subscription.request(1);
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.printf("[%s] onError:%s%n", threadName(), throwable);
            }

            @Override
            public void onComplete() {
                System.out.printf("[%s] onComplete%n", threadName());
            }
        };
    }

    @Nonnull
    private static String threadName() {
        return Thread.currentThread().getName();
    }
```
<p>The output:</p>
```[main] onSubscribe
[main] mapping:1
[main] onNext:10
[main] onComplete

[main] flat-mapping:1
[main] onSubscribe
[main] onNext:10
[main] onComplete
```

In the output of the first case onSubscribe is before mapping:1. It's conceivable that the subscriber made a request for one event and then the publisher produced one, and then this very event went through the transformation and other operations if any.

In the output of the second case flat-mapping:1 comes first, which means onSubscribe() is not yet called but the event is emitted already. The documentation says that map() is implemented by applying a synchronous function, and flatMap() transforms asynchronously. What we witness here is that everything happens in the main  thread.

Things seem in contradiction, neither flatMap() is performed asynchronously, nor the publisher emits on subscriber's demand, so what's going on under the hood in reactor？

Body:
In a simple demo program I compared the output of Mono.just().map().subscribe() and Mono.just().flatMap().subscribe(), to my surprise map() is executed after onSubscribe() but flatMap() is before.

The program:

    public static void main(@Nonnull String[] args) {
        // 1. Case with map()
        Mono.just(1).map(number -> {
            System.out.printf("[%s] mapping:%d%n", threadName(), number);
            return number * 10;

        }).subscribe(buildSubscriber());

        // 2. Case with flatMap()
        System.out.println();
        Mono.just(1).flatMap(number -> {
            System.out.printf("[%s] flat-mapping:%d%n", threadName(), number);
            return Mono.just(number * 10);

        }).subscribe(buildSubscriber());
    }

    @SuppressWarnings("ReactiveStreamsSubscriberImplementation")
    @Nonnull
    private static Subscriber<Integer> buildSubscriber() {
        return new Subscriber<>() {
            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription subscription) {
                System.out.printf("[%s] onSubscribe%n", threadName());
                this.subscription = subscription;
                subscription.request(1);
            }

            @Override
            public void onNext(Integer item) {
                System.out.printf("[%s] onNext:%s%n", threadName(), item);
                subscription.request(1);
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.printf("[%s] onError:%s%n", threadName(), throwable);
            }

            @Override
            public void onComplete() {
                System.out.printf("[%s] onComplete%n", threadName());
            }
        };
    }

    @Nonnull
    private static String threadName() {
        return Thread.currentThread().getName();
    }

The output:

[main] onSubscribe
[main] mapping:1
[main] onNext:10
[main] onComplete

[main] flat-mapping:1
[main] onSubscribe
[main] onNext:10
[main] onComplete

In the output of the first case onSubscribe is before mapping:1. It's conceivable that the subscriber made a request for one event and then the publisher produced one, and then this very event went through the transformation and other operations if any.

In the output of the second case flat-mapping:1 comes first, which means onSubscribe() is not yet called but the event is emitted already. The documentation says that map() is implemented by applying a synchronous function, and flatMap() transforms asynchronously. What we witness here is that everything happens in the main  thread.

Things seem in contradiction, neither flatMap() is performed asynchronously, nor the publisher emits on subscriber's demand, so what's going on under the hood in reactor？


问:
getUserMedia to get video stream, galaxy S20 screen's aspect ratio broken
problem screen shot!
normal screen shot

Specific device(Galaxy S20 with chrome browser), shows the video stream like the image above.

Almost all of devices are fine, but some devices have the problems like this.

How can I approach the problem?

How can I solve it?

my code for getting the Stream data,

```<code>
useEffect(() => {
    const getStreamData = async () => {
      if (videoRef.current) {
        try {
          const stream = await navigator.mediaDevices.getUserMedia({
            video: {
              aspectRatio: 3 / 4,
              facingMode: 'environment',
            },
          });
          window.stream = stream;
          videoRef.current.srcObject = stream;
        } catch (error) {
          console.error('Error getStreamData', error);
        }
      }
    };
    getStreamData();

    return () => {
      cameraOff();
    };
  }, []);
</code>```

my code for styled component

```<code><RootContainer>
  <Dummy />
  <ScanContainer>
    <StyledVideo playsInline autoPlay controls ref={videoRef}>
      VideoStream Not Available.
    </StyledVideo>
    <StyledCanvas width={1280} height={720} ref={canvasRef} />
  </ScanContainer>
</RootContainer>
</code>```
```<code>const RootContainer = styled.div`
  display: flex;
  flex-direction: column;
  flex: 1;
  position: relative;
  width: 100%;
  overflow: hidden;
  color: #363636;
  z-index: 3;
  margin-top: 60px;
  background-color: #001b45 !important;
`;

const ScanContainer = styled.div`
  height: 100%;
`;

const StyledVideo = styled.video`
  width: 70%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  left: 50%;
`;

const StyledCanvas = styled.canvas`
  width: 70%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  left: 50%;
  border: 3px solid silver;
`;

const Dummy = styled.div`
  display: block;
  height: 500px;
  width: 90%;
`;

</code>```

thank you for your help

I tried changing aspect ratio to 9:16,
using width/height instead of aspectRatio in getUserMedia constraint.

crop also have some problem with latest chrome.
cuz it can not get the offset value.

Body:
problem screen shot!
normal screen shot

Specific device(Galaxy S20 with chrome browser), shows the video stream like the image above.

Almost all of devices are fine, but some devices have the problems like this.

How can I approach the problem?

How can I solve it?

my code for getting the Stream data,

useEffect(() => {
    const getStreamData = async () => {
      if (videoRef.current) {
        try {
          const stream = await navigator.mediaDevices.getUserMedia({
            video: {
              aspectRatio: 3 / 4,
              facingMode: 'environment',
            },
          });
          window.stream = stream;
          videoRef.current.srcObject = stream;
        } catch (error) {
          console.error('Error getStreamData', error);
        }
      }
    };
    getStreamData();

    return () => {
      cameraOff();
    };
  }, []);

my code for styled component

<RootContainer>
  <Dummy />
  <ScanContainer>


问:
Any reason to wrap transaction or include locking hint for single operation stored procedure?
SQL Server 2022

For a stored procedure that contains only a single DML operation (insert, update, delete) :

Is there ever any reason to wrap the operation in a transaction?

Is there ever any reason to include a locking hint (ROWLOCK, UPDLOCK, etc.)

Here's an (artificial ) example :

```<code>USE [CarShop]
GO

DROP PROCEDURE [dbo].[InsertAutoForCustomer]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertAutoForCustomer]
    @autoMake nvarchar(50),
    @autoModel nvarchar(50),
    @autoYear int,
    @customerNameFirst nvarchar(50),
    @customerNameLast nvarchar(50),
    @autoId bigint output
AS
BEGIN

DECLARE @customerId bigint

SELECT @customerId = c.[Id]
FROM [dbo].[Customer] c
WHERE c.[NameFirst] = @customerNameFirst
AND c.[NameLast] = @customerNameLast

INSERT INTO [dbo].[Auto]
           ([CustomerId]
            [Make]
           ,[Model]
           ,[Year])
     VALUES
           (@customerId
           ,@autoMake
           ,@autoModel
           ,@autoYear)

SELECT @id = SCOPE_IDENTITY()

END
GO
</code>```

Does SQL Server automatically (1) force atomicity across all SQL statements in the procedure, and (2) lock both [Customer] and [Auto] ( at relevant level row/page/table ) for duration of execution of all statements ?

Or is it necessary to wrap the procedure ( all three statements : SELECT , UPDATE , SELECT ) in a transaction to ensure that customer is row still present at time of insert auto, and auto is still present at time of set output to SCOPE_IDENTITY() ?

EDIT : Ok as pointed out in comments the correct way to do this is condense to single line of SQL that is executed atomically by SQL Server Engine :

```<code>INSERT INTO [dbo].[Auto]
           ([CustomerId]
            [Make]
           ,[Model]
           ,[Year])
SELECT [Id] AS [CustomerId]
      ,@autoMake AS [Make]
      ,@autoModel AS [Model]
      ,@autoYear AS [Year]
FROM [dbo].[Customer]
WHERE [NameFirst] = @customerNameFirst
AND [NameLast] = @customerNameLast
</code>```

Body:
SQL Server 2022

For a stored procedure that contains only a single DML operation (insert, update, delete) :

Is there ever any reason to wrap the operation in a transaction?

Is there ever any reason to include a locking hint (ROWLOCK, UPDLOCK, etc.)

Here's an (artificial ) example :

USE [CarShop]
GO

DROP PROCEDURE [dbo].[InsertAutoForCustomer]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertAutoForCustomer]
    @autoMake nvarchar(50),
    @autoModel nvarchar(50),
    @autoYear int,
    @customerNameFirst nvarchar(50),
    @customerNameLast nvarchar(50),
    @autoId bigint output
AS
BEGIN

DECLARE @customerId bigint

SELECT @customerId = c.[Id]
FROM [dbo].[Customer] c
WHERE c.[NameFirst] = @customerNameFirst
AND c.[NameLast] = @customerNameLast

INSERT INTO [dbo].[Auto]
           ([CustomerId]
            [Make]
           ,[Model]
           ,[Year])
     VALUES
           (@customerId
           ,@autoMake
           ,@autoModel
           ,@autoYear)

SELECT @id = SCOPE_IDENTITY()

END
GO

Does SQL Server automatically (1) force atomicity across all SQL statements in the procedure, and (2) lock both [Customer] and [Auto] ( at relevant level row/page/table ) for duration of execution of all statements ?

Or is it necessary to wrap the procedure ( all three statements : SELECT , UPDATE , SELECT ) in a transaction to ensure that customer is row still present at time of insert auto, and auto is still present at time of set output to SCOPE_IDENTITY() ?

EDIT : Ok as pointed out in comments the correct way to do this is condense to single line of SQL that is executed atomically by SQL Server Engine :

INSERT INTO [dbo].[Auto]
           ([CustomerId]
            [Make]
           ,[Model]
           ,[Year])
SELECT [Id] AS [CustomerId]
      ,@autoMake AS [Make]
      ,@autoModel AS [Model]
      ,@autoYear AS [Year]
FROM [dbo].[Customer]
WHERE [NameFirst] = @customerNameFirst
AND [NameLast] = @customerNameLast


问:
Column CHDRNUM or expression in SELECT list not valid. How I fixed?
```<code>SELECT
    a.CHDRNUM, a.COWNNUM
    CASE
        WHEN COUNT(H.ENTITYCODE) > 0
            THEN 'Y'
            ELSE 'N'
    END AS B
FROM
    (SELECT CHDRNUM,COWNNUM
     FROM CHDRPF)  AS a
INNER JOIN
    (SELECT ENTITYCODE, ENTITYTYPE, ISTATUS
     FROM ZBLSPF
     WHERE ENTITYTYPE = 'CN'
       AND ISTATUS IN ('RED', 'RED 1', 'RED 2', 'RED 3', 'RED 4', 'RED 5')) AS H ON H.ENTITYCODE = A.COWNNUM
WHERE
    a.CHDRNUM = '123';
</code>```

Why are those 2 columns not included in the select list, but when I delete 2 columns (CHDRNUM, COWNNUM) it runs.

The error I get is

Column CHDRNUM or expression in SELECT list not valid

Body:
SELECT
    a.CHDRNUM, a.COWNNUM
    CASE
        WHEN COUNT(H.ENTITYCODE) > 0
            THEN 'Y'
            ELSE 'N'
    END AS B
FROM
    (SELECT CHDRNUM,COWNNUM
     FROM CHDRPF)  AS a
INNER JOIN
    (SELECT ENTITYCODE, ENTITYTYPE, ISTATUS
     FROM ZBLSPF
     WHERE ENTITYTYPE = 'CN'
       AND ISTATUS IN ('RED', 'RED 1', 'RED 2', 'RED 3', 'RED 4', 'RED 5')) AS H ON H.ENTITYCODE = A.COWNNUM
WHERE
    a.CHDRNUM = '123';

Why are those 2 columns not included in the select list, but when I delete 2 columns (CHDRNUM, COWNNUM) it runs.

The error I get is

Column CHDRNUM or expression in SELECT list not valid


问:
How to create DAO database access object in nodejs mongodb project?
I want to create Database layer and I am confused how to create / start with it.

The database layer mainly contains this three files for instance

The database model layer where user's model resides

The BaseModel/layer where all the instances (insert, update, delete) etc resides

The database access layer.

I am confused in how to create that 3rd point .
(I am following the class based architecture)

If any one have solution/tutorial/documentation please share .

Thank you


问:
Typorm migration needs permission to all tables in database
I have a nestjs app and migrations configured to run automatically on startup. Recently, a new table was added to the database for aws dms. This table should not be included in migrations or accessed by the app in any way but needs to be in the same database for dms purposes. We did not give the user used by the app permissions to this new table and the migrations failed to run with the following error:

Migration "migrations1673309585875" failed, error: permission denied for table awsdms_ddl_audit

in the nestjs logs

```<code>ERROR [TypeOrmModule] Unable to connect to the database. Message: permission denied for sequence awsdms_ddl_audit_c_key_seq. Retrying (9)...
QueryFailedError: permission denied for sequence awsdms_ddl_audit_c_key_seq
at PostgresQueryRunner.query (/app/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:211:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Migration "migrations1673309585875" failed, error: permission denied for sequence awsdms_ddl_audit_c_key_seq
</code>```

I want to reiterate that this migration does not include any changes to that table. It includes very minor changes to another table with no relation to the aws dms table.

The only thing I was able to find on this was this GitHub issue where someone had exactly the same problem and their solution was to grant permissions for the table and a sequence to that user. You can find that here.

This solution worked for me but I would prefer to not have the permissions granted if I can avoid it. Is there a way to specify a table to be excluded in typeorm migration? There isn't anything in the migration related to that table and there never should be. I don't know what typeorm is doing to need permissions on this table.

Here's what I did to 'fix' the issue:

GRANT ALL
ON awsdms_ddl_audit
TO user_role;

GRANT USAGE, SELECT ON SEQUENCE awsdms_ddl_audit_c_key_seq TO user_role;
```
<p>Here's an example of our typeorm configuration</p>
<pre class="lang-js prettyprint-override"><code>// typeorm/config.ts
export const databaseConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host,
  port,
  username,
  password,
  database,
  entities,
  synchronize: false,
  migrations: ['dist/migrations/**/*.js'],
  migrationsRun: true,
  logging: true,
};
</code>```

// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { databaseConfig } from './typeorm/config';

@Module({
  imports: [TypeOrmModule.forRoot(databaseConfig)],
  controllers: [controllers],
  providers: [providers],
})
export class AppModule {}
```

Body:
I have a nestjs app and migrations configured to run automatically on startup. Recently, a new table was added to the database for aws dms. This table should not be included in migrations or accessed by the app in any way but needs to be in the same database for dms purposes. We did not give the user used by the app permissions to this new table and the migrations failed to run with the following error:

Migration "migrations1673309585875" failed, error: permission denied for table awsdms_ddl_audit

in the nestjs logs

ERROR [TypeOrmModule] Unable to connect to the database. Message: permission denied for sequence awsdms_ddl_audit_c_key_seq. Retrying (9)...
QueryFailedError: permission denied for sequence awsdms_ddl_audit_c_key_seq
at PostgresQueryRunner.query (/app/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:211:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Migration "migrations1673309585875" failed, error: permission denied for sequence awsdms_ddl_audit_c_key_seq

I want to reiterate that this migration does not include any changes to that table. It includes very minor changes to another table with no relation to the aws dms table.

The only thing I was able to find on this was this GitHub issue where someone had exactly the same problem and their solution was to grant permissions for the table and a sequence to that user. You can find that here.

This solution worked for me but I would prefer to not have the permissions granted if I can avoid it. Is there a way to specify a table to be excluded in typeorm migration? There isn't anything in the migration related to that table and there never should be. I don't know what typeorm is doing to need permissions on this table.

Here's what I did to 'fix' the issue:

GRANT ALL
ON awsdms_ddl_audit
TO user_role;

GRANT USAGE, SELECT ON SEQUENCE awsdms_ddl_audit_c_key_seq TO user_role;

Here's an example of our typeorm configuration

// typeorm/config.ts
export const databaseConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host,
  port,
  username,
  password,
  database,
  entities,
  synchronize: false,
  migrations: ['dist/migrations/**/*.js'],
  migrationsRun: true,
  logging: true,
};

// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { databaseConfig } from './typeorm/config';

@Module({
  imports: [TypeOrmModule.forRoot(databaseConfig)],
  controllers: [controllers],
  providers: [providers],
})
export class AppModule {}


问:
How to add schema code in a personalized HTML Joomla 3.9 Module
I've added successfully some schema code in my personalized HTML Joomla module before, it was when i needed to add separated "course" data, I created it and then added it to the module with a plug in called "sourcerer" that adds the tags "source" at the beginning and "/source" at the end. This allows the schema code to be read by google rich results while not visible to the eye on the page.

My problem is now I wanted to add a feature of schema code called "Carousel", which essentially groups all "courses" in the website to post them as schema in just one page. But for some reason Goggle rich results don´t read the Rich "Carousel" schema, though it works fine when tested as a code snippet in the testing tool. Weird.

I just need to insert this carousel schema code in my personalized HTML Joomla module, so it shows in just one page and not to be forced to add it in the Head for the whole website...

I've tried editing the carousel schema snippet but there's no point I guess, since the google testing tool says it´s correct.

I wonder if Joomla has another way to achieve this (insert schema code in personalized HTML module), I have not been able to find a solution...


问:
Cross referencing a file for users and checking another file for their pending tasks
I am on the last step of my project and have come to a little hurdle. I would like to write a program that holds tickets for a ticketing system. What that means is that one file holds usernames and the other file has tasks in them.

If a user is called admin, I would like the program to pull out the admin tasks. The program I have so far is this. The menu system asks for vm to be entered as 'View my tasks'.

I tried to call to a username input. 'y = username input' then stated if username input == y[0] (Which references my file on index position 0) then it should pass and print just the admin tasks.

```<code>    elif menu == 'vm':
        file = open("tasks.txt")
        with open("tasks.txt", "r") as f:
            y = username_input
            if username_input == y[0]: #this needs fixed!!!
                for line in f:
                    line = line.rstrip("\n")
                    y = line.split(", ")
                    print("Task: \t\t\t", y[1])
                    print("Assigned to: \t\t", y[0])
                    print("Date assigned: \t\t", y[4])
                    print("Due date: \t\t", y[3])
                    print("Task Complete? \t\t", y[5])
                    print("Task description: \t", y[2])
                    print("\n")
            else:
                print("You have no pending tasks. ")

Output Example:

Task:                    Assign initial tasks
Assigned to:             admin
Date assigned:           25 Oct 2019
Due date:                10 Oct 2019
Task Complete?           No
Task description:        Use taskManager.py to assign each team member with appropriate tasks
</code>```

Body:
I am on the last step of my project and have come to a little hurdle. I would like to write a program that holds tickets for a ticketing system. What that means is that one file holds usernames and the other file has tasks in them.

If a user is called admin, I would like the program to pull out the admin tasks. The program I have so far is this. The menu system asks for vm to be entered as 'View my tasks'.

I tried to call to a username input. 'y = username input' then stated if username input == y[0] (Which references my file on index position 0) then it should pass and print just the admin tasks.

    elif menu == 'vm':
        file = open("tasks.txt")
        with open("tasks.txt", "r") as f:
            y = username_input
            if username_input == y[0]: #this needs fixed!!!
                for line in f:
                    line = line.rstrip("\n")
                    y = line.split(", ")
                    print("Task: \t\t\t", y[1])
                    print("Assigned to: \t\t", y[0])
                    print("Date assigned: \t\t", y[4])
                    print("Due date: \t\t", y[3])
                    print("Task Complete? \t\t", y[5])
                    print("Task description: \t", y[2])
                    print("\n")
            else:
                print("You have no pending tasks. ")

Output Example:

Task:                    Assign initial tasks
Assigned to:             admin
Date assigned:           25 Oct 2019
Due date:                10 Oct 2019
Task Complete?           No
Task description:        Use taskManager.py to assign each team member with appropriate tasks


问:
Using a non-primeface icon to a p-fileUpload button?
I have been trying to replace the icon of the upload button (which is a p-fileupload element) with an icon from FontAwesome (like fas fa-file-import) but it keeps showing a blank space instead of the wanted icon.

Here's is the code I have written:

```<code><p-fileUpload
  mode="basic"
  [maxFileSize]="10000000"
  chooseLabel="{{ 'ImportBtn' | localize }}"
  class="p-mr-2 p-d-inline-block mr-2"
  chooseIcon="fas fa-file-import"
  accept=".xlsx,.xls"
  customUpload="true"
  [auto]="true"
  (uploadHandler)="uploadBillExcels($event)"
  draggable="true">
</p-fileUpload>
</code>```


问:
Issue with FireBase auth Imports on react project "(name of auth related function) was not found in 'firebase/auth' (module has no exports)"
I'm brand new to Stack Overflow, react, and firebase simultaneously so please bear with me

These are the exact errors I'm getting:
Errors in react app instance
The errors started when I imported useAuthState and seems to work when I don't have it in there, but it's functionality would be super helpful for my project. I've imported firebase so I don't think that's the issue however there are a few "high severity vulnerabilities" when I tried to reinstall it so I'm not sure:
npm install veunerabilities
some other stuff I think may be useful:
Versions of all the libraries

My Code

```<code>import React, { useRef, useState, Component } from "react";
import logo from "./logo.svg";
import "./App.css";
// Import the functions you need from the SDKs you need
// import firebase from "firebase/compat/app";
import { initializeApp } from "firebase/app";
import { getAuth, signInWithEmailAndPassword, signOut } from "firebase/auth";
import { useAuthState } from "react-firebase-hooks/auth";
// import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Material UI imports
import { TextField } from "@mui/material";
import { Button } from "@mui/material";

const firebaseConfig = {
  apiKey: "AIzaSyAkW85ebxOCgKz5d9wGc75UlRZjdMp7EUw",
  authDomain: "employee-management-ec260.firebaseapp.com",
  projectId: "employee-management-ec260",
  storageBucket: "employee-management-ec260.appspot.com",
  messagingSenderId: "143304785244",
  appId: "1:143304785244:web:fa850ea1891c95dc029599",
  measurementId: "G-JE5TL17G3G",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// const analytics = firebase.analytics();
const auth = getAuth(app);
const db = getFirestore(app);

function App() {
  const [user, loading, error] = useAuthState(auth);
  return (
    <div className="App">
      <h1>Log In</h1>
      {user ? <UserAccess /> : <SignIn />}
    </div>
  );
}

function SignIn() {
  const [passText] = "";
  const signIn = (email, password) => {
    console.log(` The email is ${email} and password is ${password}`);
    signInWithEmailAndPassword(auth, email, password)
      .then((userCrential) => {
        const user = userCrential.user;
        passText = "Logged In";
      })
      .catch((error) => {
        passText = "INVALID PASSWORD";
      });
  };
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  return (
    <div>
      <h3>E-Mail</h3>
      <TextField
        label="E-Mail"
        variant="outlined"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <br />
      <h3>Password</h3>
      <TextField
        label="Password"
        variant="outlined"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <br />
      <br />
      <Button variant="contained" onClick={() => signIn(email, password)}>
        Sign In
      </Button>
      <br />
      <br />
      <br />
      <h3>{passText}</h3>
    </div>
  );
}
function SignOut() {
  return <Button onClick={auth.signOut}>Sign Out</Button>;
}
function UserAccess() {
  return (
    <div>
      <h1>{user.email} has been logged out</h1>
    </div>
  );
}
export default App;
</code>```

I've tried changing the libraries from "firebase/app" -> "firebase/compat/app" which didn't seem to do anything at all, I've tried restarting my computer, I've tried taking a break and nothing seems to be working

Body:
I'm brand new to Stack Overflow, react, and firebase simultaneously so please bear with me

These are the exact errors I'm getting:
Errors in react app instance
The errors started when I imported useAuthState and seems to work when I don't have it in there, but it's functionality would be super helpful for my project. I've imported firebase so I don't think that's the issue however there are a few "high severity vulnerabilities" when I tried to reinstall it so I'm not sure:
npm install veunerabilities
some other stuff I think may be useful:
Versions of all the libraries

My Code

import React, { useRef, useState, Component } from "react";
import logo from "./logo.svg";
import "./App.css";
// Import the functions you need from the SDKs you need
// import firebase from "firebase/compat/app";
import { initializeApp } from "firebase/app";
import { getAuth, signInWithEmailAndPassword, signOut } from "firebase/auth";
import { useAuthState } from "react-firebase-hooks/auth";
// import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Material UI imports
import { TextField } from "@mui/material";
import { Button } from "@mui/material";

const firebaseConfig = {
  apiKey: "AIzaSyAkW85ebxOCgKz5d9wGc75UlRZjdMp7EUw",
  authDomain: "employee-management-ec260.firebaseapp.com",
  projectId: "employee-management-ec260",
  storageBucket: "employee-management-ec260.appspot.com",
  messagingSenderId: "143304785244",
  appId: "1:143304785244:web:fa850ea1891c95dc029599",
  measurementId: "G-JE5TL17G3G",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// const analytics = firebase.analytics();
const auth = getAuth(app);
const db = getFirestore(app);

function App() {
  const [user, loading, error] = useAuthState(auth);
  return (

Log In

      {user ? <UserAccess /> : <SignIn />}

  );
}

function SignIn() {
  const [passText] = "";
  const signIn = (email, password) => {
    console.log(` The email is ${email} and password is ${password}`);
    signInWithEmailAndPassword(auth, email, password)
      .then((userCrential) => {
        const user = userCrential.user;
        passText = "Logged In";
      })
      .catch((error) => {
        passText = "INVALID PASSWORD";
      });
  };
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  return (

E-Mail

      <TextField
        label="E-Mail"
        variant="outlined"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />

Password

      <TextField
        label="Password"
        variant="outlined"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />

      <Button variant="contained" onClick={() => signIn(email, password)}>
        Sign In
      </Button>

{passText}

  );
}
function SignOut() {
  return <Button onClick={auth.signOut}>Sign Out</Button>;
}
function UserAccess() {
  return (

{user.email} has been logged out

  );
}
export default App;

I've tried changing the libraries from "firebase/app" -> "firebase/compat/app" which didn't seem to do anything at all, I've tried restarting my computer, I've tried taking a break and nothing seems to be working


问:
react-native-gifted-chat Can't show keyboard when have other text input in same screen
If I have another text input on the same screen with react-native-gifted-chat component, the keyboard won't work correctly. It will appear in a sec then be dismissed immediately. Happens on both Android and IOS, physical devices and emulator.

I handled keyboard by myself, inside a KeyboardAvoidingView

Demo:

Here my code

```<code><View style={styles.container}>
  <View style={styles.container}>
    {renderVideo()}
    <KeyboardAvoidingView
      behavior={Platform.OS === "ios" ? "padding" : undefined}
      style={{ flex: 1, justifyContent: "flex-end" }}
    >
      <View style={{ height: 350 }}>
        <GiftedChat
          textInputProps={{ onFocus: onFocusHandler, onBlur: onBlurHandler }} //
          isKeyboardInternallyHandled={false}
          wrapInSafeArea={false}
          keyboardShouldPersistTaps="handled"
          onSend={onSendMessage}
          alwaysShowSend
          messages={messages}
          infiniteScroll
          scrollToBottom={false}
          inverted
        />
      </View>
    </KeyboardAvoidingView>
  </View>
  <AlertModal ref={alertRef} /> // This modal contain another input
</View>
</code>```

Need some help making Keyboard for second text input works fine

Body:
If I have another text input on the same screen with react-native-gifted-chat component, the keyboard won't work correctly. It will appear in a sec then be dismissed immediately. Happens on both Android and IOS, physical devices and emulator.

I handled keyboard by myself, inside a KeyboardAvoidingView

Demo:

Here my code

<View style={styles.container}>
  <View style={styles.container}>
    {renderVideo()}
    <KeyboardAvoidingView
      behavior={Platform.OS === "ios" ? "padding" : undefined}
      style={{ flex: 1, justifyContent: "flex-end" }}
    >
      <View style={{ height: 350 }}>
        <GiftedChat
          textInputProps={{ onFocus: onFocusHandler, onBlur: onBlurHandler }} //
          isKeyboardInternallyHandled={false}
          wrapInSafeArea={false}
          keyboardShouldPersistTaps="handled"
          onSend={onSendMessage}
          alwaysShowSend
          messages={messages}
          infiniteScroll
          scrollToBottom={false}
          inverted
        />
      </View>
    </KeyboardAvoidingView>
  </View>
  <AlertModal ref={alertRef} /> // This modal contain another input
</View>

Need some help making Keyboard for second text input works fine


问:
whatsapp web loading issue for QWebEngineView under pyside6
So i have ask this question a few days ago the issue is that i have changed the user agent for the browser and it works as it can load whatsapp,but the issue came back whenever i refresh or logout from whatsapp web.i have a video(link) and code with some explaination clipped with this question to make things more clear as per request from D.L.
**Statement:sorry but i don't think i can shorten the code as the whole code is needed to show how it works

video link here

Code:

```<code>import sys
from PySide6.QtCore import QUrl
from PySide6.QtWidgets import *
from PySide6.QtWebEngineWidgets import QWebEngineView

class Widgets(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Simple Web Browser")
        self.widget = QWidget(self)

        self.webview = QWebEngineView()
        #change the user agent
        self.webview.page().profile().setHttpUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.75 Safari/537.36")
        #the link to whatsapp web
        self.webview.load(QUrl("https://web.whatsapp.com/"))

        self.check_button = QPushButton("Refesh")
        self.check_button.clicked.connect(self.button_clicked)

        self.toplayout = QHBoxLayout()
        self.toplayout.addWidget(self.check_button)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.toplayout)
        self.layout.addWidget(self.webview)

        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)

    def button_clicked(self):
        #reload the webpage
        self.webview.reload()
        #print out the  user agent
        print(self.webview.page().profile().httpUserAgent()+"\n")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Widgets()
    window.show()
    sys.exit(app.exec())
</code>```

i can't seem to find any current available solution,so i ask here hoping someone that can solve this issue,what i request is that the whatsapp page can be loaded even after refresh and logout.

Body:
So i have ask this question a few days ago the issue is that i have changed the user agent for the browser and it works as it can load whatsapp,but the issue came back whenever i refresh or logout from whatsapp web.i have a video(link) and code with some explaination clipped with this question to make things more clear as per request from D.L.
**Statement:sorry but i don't think i can shorten the code as the whole code is needed to show how it works

video link here

Code:

import sys
from PySide6.QtCore import QUrl
from PySide6.QtWidgets import *
from PySide6.QtWebEngineWidgets import QWebEngineView

class Widgets(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Simple Web Browser")
        self.widget = QWidget(self)

        self.webview = QWebEngineView()
        #change the user agent
        self.webview.page().profile().setHttpUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.75 Safari/537.36")
        #the link to whatsapp web
        self.webview.load(QUrl("https://web.whatsapp.com/"))

        self.check_button = QPushButton("Refesh")
        self.check_button.clicked.connect(self.button_clicked)

        self.toplayout = QHBoxLayout()
        self.toplayout.addWidget(self.check_button)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.toplayout)
        self.layout.addWidget(self.webview)

        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)

    def button_clicked(self):
        #reload the webpage
        self.webview.reload()
        #print out the  user agent
        print(self.webview.page().profile().httpUserAgent()+"\n")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Widgets()
    window.show()
    sys.exit(app.exec())

i can't seem to find any current available solution,so i ask here hoping someone that can solve this issue,what i request is that the whatsapp page can be loaded even after refresh and logout.


问:
.db file from Heroku app does not sync with github repository
I have this app on Heroku that deploys code from a GitHub repository. In this GitHub repository, there is this database file "something.db", which has all the necessary fields but empty of any records. When I build the app on Heroku and deploy it, it pulls the code from the GitHub repository, including the "something.db" database file. When people access the website, when they register a user account for example, the app inserts a new record to the database "something.db". However, I have some a concern about this:

How would I be able to sync this "something.db" database file from the Heroku app back to the GitHub repository? I.e. How can the GitHub repository be able to see the data changes in the "something.db" database file once I create a new user on the website.

I am asking this question in the context that every time I need to push code onto that GitHub repository, I would need to redeploy the app from heroku, which will then also deploy the empty "something.db" database file, which I do not want, since I want to retain the data that was previously added while the website was live.

I know this method of storing data in a .db file is not professional, but I would like to keep things as simple as possible since this website is small scale and does not hold that much data.

The app that I am using is a python Flask app, and the database is using flask alchemy (sqlite).

I tried looking online for some answers on how to push the changes from Heroku back to the GitHub pipeline but could not find anything about it. All I saw was how to deploy an app FROM GitHub to Heroku, but not push code FROM Heroku back to the GitHub repository.


问:
Can I use free Visual Studio Community to develop commercial application?
I am looking to build serverless application with .Net Core. Visual Studio will be a good choice.

Could the Community be used to develop commercial application? (not individual developers)


问:
Boost files not being found by cmake
OS: Windows
Requirement: to build https://github.com/jgaa/restc-cpp using cmake.
The above project needs openssl, zlib and boost.
All good with finding the first 2 but can't find boost libraries.

Have used

```<code>file (GLOB_RECURSE boostDirs LIST_DIRECTORIES true C:/path/to/boost/libs/*.lib)
</code>```

to find all possible directories where the lib files may live.

```<code>INCLUDE_DIRECTORIES(${boostDirs})
</code>```

doesn't help as

```<code>set(Boost_DEBUG 1)
</code>```

reveals that
_boost_LIBRARY_SEARCH_DIRS_RELEASE = has a mind of its own and doesn't use the included directories.

Have looked high (google) and low (the docs), to no avail.
Anybody have the solution to my problem?

All suggestions/workarounds welcome.  And thanks in advance!

Title: Boost files not being found by cmake

Body:
OS: Windows
Requirement: to build https://github.com/jgaa/restc-cpp using cmake.
The above project needs openssl, zlib and boost.
All good with finding the first 2 but can't find boost libraries.

Have used

file (GLOB_RECURSE boostDirs LIST_DIRECTORIES true C:/path/to/boost/libs/*.lib)

to find all possible directories where the lib files may live.

INCLUDE_DIRECTORIES(${boostDirs})

doesn't help as

set(Boost_DEBUG 1)

reveals that
_boost_LIBRARY_SEARCH_DIRS_RELEASE = has a mind of its own and doesn't use the included directories.

Have looked high (google) and low (the docs), to no avail.
Anybody have the solution to my problem?

All suggestions/workarounds welcome.  And thanks in advance!


问:
Vue2 binding inside style tag isn't properly parsing
I have been looking for ways to use variables within the style tag of a Vue file and have come across this solution. I have attempted to use it as can be seen in the code sample below

```<code>...
</template>
<script>
export default {
  data() {
    return {
      url: "test",
    };
  },
};
</script>

<style>
.backIm:before {
  ...
  background: v-bind(url);
  ...
}
</style>
</code>```

However, despite seeming set up the exact same way as was done in the documentation, the v-bind(url) isn't interpreted when testing, as can be seen within the developer tools

I've searched but not found anyone with this exact issue. If anyone could explain why this is incorrect, and provide a solution, I'd be grateful.

Body:
I have been looking for ways to use variables within the style tag of a Vue file and have come across this solution. I have attempted to use it as can be seen in the code sample below

...
</template>

However, despite seeming set up the exact same way as was done in the documentation, the v-bind(url) isn't interpreted when testing, as can be seen within the developer tools

I've searched but not found anyone with this exact issue. If anyone could explain why this is incorrect, and provide a solution, I'd be grateful.


问:
OpenAPI spec generated from FastAPI not showing missing values allowed as dict values
Take this simple service:

```<code># main.py

import typing as t

from pydantic.types import StrictStr

from fastapi import FastAPI
from pydantic import BaseModel, StrictBool, StrictInt, StrictStr

Value = t.Optional[StrictBool] | t.Optional[StrictInt]

class Example(BaseModel):
    x: dict[StrictStr, Value]

app = FastAPI()

@app.get("/read", response_model=Example)
def read():
    return Example(x={"value": None})
</code>```

the actual service works as intended:

```<code>$ curl localhost:8000/read | jq
{
  "x": {
    "value": null
  }
}
</code>```

The issue is with the openapi.json and how it's translating the Example class -- it doesn't seem to allow null values:

```<code>$ curl localhost:8000/openapi.json | jq '.components'
{
  "schemas": {
    "Example": {
      "title": "Example",
      "required": [
        "x"
      ],
      "type": "object",
      "properties": {
        "x": {
          "title": "X",
          "type": "object",
          "additionalProperties": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "integer"
              }
            ]
          }
        }
      }
    }
  }
}
</code>```

This is a problem because when I use it to generate client libraries, they fail on validating the output with something like

```<code>ApiValueError: Invalid inputs given to generate an instance of <class>. None of the anyOf schemas matched the input data.
</code>```

Any solutions here?

Body:
Take this simple service:

# main.py

import typing as t

from pydantic.types import StrictStr

from fastapi import FastAPI
from pydantic import BaseModel, StrictBool, StrictInt, StrictStr

Value = t.Optional[StrictBool] | t.Optional[StrictInt]

class Example(BaseModel):
    x: dict[StrictStr, Value]

app = FastAPI()

@app.get("/read", response_model=Example)
def read():
    return Example(x={"value": None})

the actual service works as intended:

$ curl localhost:8000/read | jq
{
  "x": {
    "value": null
  }
}

The issue is with the openapi.json and how it's translating the Example class -- it doesn't seem to allow null values:

$ curl localhost:8000/openapi.json | jq '.components'
{
  "schemas": {
    "Example": {
      "title": "Example",
      "required": [
        "x"
      ],
      "type": "object",
      "properties": {
        "x": {
          "title": "X",
          "type": "object",
          "additionalProperties": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "integer"
              }
            ]
          }
        }
      }
    }
  }
}

This is a problem because when I use it to generate client libraries, they fail on validating the output with something like

ApiValueError: Invalid inputs given to generate an instance of <class>. None of the anyOf schemas matched the input data.

Any solutions here?


问:
GetItems() filtering Archived items
Finding my around Xero API. Using the Xero .NetStandard library and getting a little stuck with what I thought would be quite a simple thing so pretty sure I'm missing something.

Trying to get a list of Items from a particular tenant using the follow code.

```<code>string whereFilter = "IsSold==True";
var xeroApi = new Xero.NetStandard.OAuth2.Api.AccountingApi();
var response = await xeroApi.GetItemsAsync(<AccessToken>, <TenantId>, null, whereFilter);
</code>```

Where I'm getting stuck is I can't for the life of me figure out how to filter out items that have been marked as Archived.  What am I missing?

Title: GetItems() filtering Archived items

Body:
Finding my around Xero API. Using the Xero .NetStandard library and getting a little stuck with what I thought would be quite a simple thing so pretty sure I'm missing something.

Trying to get a list of Items from a particular tenant using the follow code.

string whereFilter = "IsSold==True";
var xeroApi = new Xero.NetStandard.OAuth2.Api.AccountingApi();
var response = await xeroApi.GetItemsAsync(<AccessToken>, <TenantId>, null, whereFilter);

Where I'm getting stuck is I can't for the life of me figure out how to filter out items that have been marked as Archived.  What am I missing?


问:
DOMException: The operation is insecure when caching on Firefox
I'm facing the problem of insecure when using caching on Firefox
It's normal when tracking protection is turned off
But we can't ask users to turn it off every time they go to our website
 const newCache = await caches.open('new-cache');
I can't open cache by this method
tracking protection turn on
error happen

Access to cache by caches.open() method
No insecure error


问:
Getting message "Compression negotiation not requested by client" in db connection logs
I am trying to use network compression feature of mongoDb using golang,
I am trying to use Zstd compression, and I am using the following method at the time of db connection,

```<code>opts := options.Client().ApplyURI("mongodb://" + ipPort).SetConnectTimeout(5 * time.Second).SetCompressors([]string{"zstd"})

</code>```

While checking the db logs, I found an message with the db connection logs,

Compression negotiation not requested by client

Can you please help me, why this message is shown?
Is there any problem with the db connection?
Will it make any impact on MongoDb queries?

Body:
I am trying to use network compression feature of mongoDb using golang,
I am trying to use Zstd compression, and I am using the following method at the time of db connection,

opts := options.Client().ApplyURI("mongodb://" + ipPort).SetConnectTimeout(5 * time.Second).SetCompressors([]string{"zstd"})

While checking the db logs, I found an message with the db connection logs,

Compression negotiation not requested by client

Can you please help me, why this message is shown?
Is there any problem with the db connection?
Will it make any impact on MongoDb queries?


问:
Extract above the fold CSS and put it as inline style in HTML using html-critical-webpack-plugin
Platform:

Gatsby v2.28.0

html-critical-webpack-plugin

Webpack v4 pre-configured with Gatsby

Our requirement is to extract the CSS which is required above the fold in mobile and desktop. Then the plugin would programmatically insert the extracted CSS into the final built HTML file as an inline style in the head thereby reducing the initial network load and the CSS-rendering blocking files would be reduced, increasing the performance scores.

Since webpack is pre-configured in Gatsby, we use the above plugin in conjunction with Gatsby's onPostBuild function so that after the HTML file has been built and sent out to the public folder, we need to do the extraction of CSS and push it in the HTML file.

Tried:

```<code>exports.onPostBuild = ({ reporter, basePath, pathPrefix }) => {
  const path1 = path.join(__dirname, '../', 'web', 'public', 'index.html');
  reporter.info(
    `Site was built with basePath: ${basePath} & pathPrefix: ${pathPrefix} and index.html ${path1} PATH.`
  );

new HtmlCriticalWebpackPlugin({
    base: path.join(__dirname, 'web', 'public'),
    src: 'index.html',
    dest: 'index.html',
    inline: true,
    minify: true,
    extract: true,
    width: 375,
    height: 565,
    penthouse: {
      blockJSRequests: false,
    },
  });

  const logStream = fs.createWriteStream(path1, { flags: 'a' });
  // use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
  logStream.write('Initial line...');
  logStream.end('this is the end line');
};
</code>```

The path is correctly pointing to the HTML file in the public directory which is available after the production build completes and the onPostBuild function runs at the very end of the build process.

I have tried to log some dummy data to the HTML file at that works fine.
We do not have any permission issues for write.

Expected:

Above the fold CSS should be programmatically extracted from the styles.hash.css file and inline in HTML.

Body:
Platform:

Gatsby v2.28.0

html-critical-webpack-plugin

Webpack v4 pre-configured with Gatsby

Our requirement is to extract the CSS which is required above the fold in mobile and desktop. Then the plugin would programmatically insert the extracted CSS into the final built HTML file as an inline style in the head thereby reducing the initial network load and the CSS-rendering blocking files would be reduced, increasing the performance scores.

Since webpack is pre-configured in Gatsby, we use the above plugin in conjunction with Gatsby's onPostBuild function so that after the HTML file has been built and sent out to the public folder, we need to do the extraction of CSS and push it in the HTML file.

Tried:

exports.onPostBuild = ({ reporter, basePath, pathPrefix }) => {
  const path1 = path.join(__dirname, '../', 'web', 'public', 'index.html');
  reporter.info(
    `Site was built with basePath: ${basePath} & pathPrefix: ${pathPrefix} and index.html ${path1} PATH.`
  );

new HtmlCriticalWebpackPlugin({
    base: path.join(__dirname, 'web', 'public'),
    src: 'index.html',
    dest: 'index.html',
    inline: true,
    minify: true,
    extract: true,
    width: 375,
    height: 565,
    penthouse: {
      blockJSRequests: false,
    },
  });

  const logStream = fs.createWriteStream(path1, { flags: 'a' });
  // use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
  logStream.write('Initial line...');
  logStream.end('this is the end line');
};

The path is correctly pointing to the HTML file in the public directory which is available after the production build completes and the onPostBuild function runs at the very end of the build process.

I have tried to log some dummy data to the HTML file at that works fine.
We do not have any permission issues for write.

Expected:

Above the fold CSS should be programmatically extracted from the styles.hash.css file and inline in HTML.


问:
CSS Scroll Snap - Children with Transform on Hover Causes Janky Effect in Chromium Browsers
When scrolling through content in a scroll container with the scroll-snap-align property applied to the children, I was able to create this jarring/janky effect with children elements that have a transform property applied on hover.

Running example code here!

HTML

Card Container:

card 1

card 2

card 3

card 4

card 5

card 6

card 7

card 8

card 9

card 10

```
<p><strong>CSS</strong></p>
<pre class="lang-css prettyprint-override"><code>.card {
  border-radius: 12px;
  background-color: lightgrey;
  height: 150px;
  width: 250px;
  border: black solid 3px;
  display: grid;
  place-content: center;
  flex-grow: 0;
  flex-shrink: 0;
  transition: 0.3s;
  user-select: none;
  scroll-snap-align: center;
  cursor: pointer;
}

.card:hover {
  transform: scale(1.05);
}

.scroll-container {
  width: 350px;
  height: 275px;
  border: black solid 5px;
  display: flex;
  align-items: center;
  flex-direction: column;
  padding: 30px;
  overflow-x: hidden;
  overflow-y: scroll;
  gap: 20px;
  scroll-snap-type: y mandatory;
}

.app-container {
  display: grid;
  place-content: center;
  height: 100vh;
  width: 100vw;
}
</code>```

This seems to happen in Chromium browsers (tested in Chrome, Brave, and Edge), and appears to work completely fine in Firefox. I have not tested Safari.

Wondering if this is a known quirk/bug with scroll containers in Chromium browsers or if there exists some sort of solution for this problem.

Body:
When scrolling through content in a scroll container with the scroll-snap-align property applied to the children, I was able to create this jarring/janky effect with children elements that have a transform property applied on hover.

Running example code here!

HTML

Card Container:

card 1

card 2

card 3

card 4

card 5

card 6

card 7

card 8

card 9

card 10

CSS

.card {
  border-radius: 12px;
  background-color: lightgrey;
  height: 150px;
  width: 250px;
  border: black solid 3px;
  display: grid;
  place-content: center;
  flex-grow: 0;
  flex-shrink: 0;
  transition: 0.3s;
  user-select: none;
  scroll-snap-align: center;
  cursor: pointer;
}

.card:hover {
  transform: scale(1.05);
}

.scroll-container {
  width: 350px;
  height: 275px;
  border: black solid 5px;
  display: flex;
  align-items: center;
  flex-direction: column;
  padding: 30px;
  overflow-x: hidden;
  overflow-y: scroll;
  gap: 20px;
  scroll-snap-type: y mandatory;
}

.app-container {
  display: grid;
  place-content: center;
  height: 100vh;
  width: 100vw;
}

This seems to happen in Chromium browsers (tested in Chrome, Brave, and Edge), and appears to work completely fine in Firefox. I have not tested Safari.

Wondering if this is a known quirk/bug with scroll containers in Chromium browsers or if there exists some sort of solution for this problem.


问:
Connecting Android Studio to Internet using Tor
I have Tor Connected to the Internet and I want to use it for connecting Android Studio:

And I have changed proxy settings in Android Studio:

But Android Studio always asks me for Proxy Authentication, and I couldn't connect Android Studio to the Internet:


问:
<ast.Constant object at 0x000001E6188A7BE0>" } SQLAlchemy
Error

`While doing login operation using swagger UI, This error show: <ast.Constant object at 0x000001E6188A7BE0>" }

In post request: 400 Bad Request

curl -X POST "http://127.0.0.1:8000/login" -H "accept: application/json" -H "Content-Type: application/json" -d "{ "password": "123", "username": "sagu"}"
`

**Login Api Code:
**

```<code>class LoginAPI(MethodResource, Resource):
    @doc(description='Log In API', tags=['LogIn Api'])
    @use_kwargs(LoginRequest, location = ('json'))
    @marshal_with(APIResponse)
    def post(self,**kwargs):
        try:
            is_logged_in, session_id = login_user(**kwargs)
            if is_logged_in:
                return APIResponse().dump(dict(message=f'User is sucessfully logged in')), 200
            else:
                return APIResponse().dump(dict(message=f'user not found')), 404
        except Exception as e:
            print(Str(e))
            return APIResponse().dump(dict(message=f'Not able to login user:{Str(e)}')), 400

api.add_resource(LoginAPI, '/login')
docs.register(LoginAPI)

</code>```

**ORM code:
**

```<code>def check_user_session_is_active(user_id):
    try:
        user_session = UserSession.query.filter_by(user_id = user_id, is_active = 1).first()
        if user_session:
            return True, user_session.session_id
        else:
            return False, None
    except Exception as e:
        raise e

def login_user(**kwargs):
    try:
        user = UserMaster.query.filter_by(username=kwargs['username'], password = kwargs['password'])
        if user:
            print("Logged In")

            is_active, session_id = check_user_session_is_active(user.id)

            if not is_active:
                session_id =uuid.uuid4()
                user_session = UserSession(uuid.uuid4(), user.id, session_id)
                db.session.add(user_session)
                db.session.commit()

            else:
                session['session_id'] = session_id

            session['session_id'] = session_id
            return True, session_id
        else:
            return False, None
    except Exception as e:
        raise e

</code>```

LoginRequest code

```<code>class LoginRequest(Schema):
    username = fields.Str(default='username')
    password = fields.Str(default='password')

</code>```

Expecting login success in swagger UI

Body:
Error

`While doing login operation using swagger UI, This error show: <ast.Constant object at 0x000001E6188A7BE0>" }

In post request: 400 Bad Request

curl -X POST "http://127.0.0.1:8000/login" -H "accept: application/json" -H "Content-Type: application/json" -d "{ "password": "123", "username": "sagu"}"
`

**Login Api Code:
**

class LoginAPI(MethodResource, Resource):
    @doc(description='Log In API', tags=['LogIn Api'])
    @use_kwargs(LoginRequest, location = ('json'))
    @marshal_with(APIResponse)
    def post(self,**kwargs):
        try:
            is_logged_in, session_id = login_user(**kwargs)
            if is_logged_in:
                return APIResponse().dump(dict(message=f'User is sucessfully logged in')), 200
            else:
                return APIResponse().dump(dict(message=f'user not found')), 404
        except Exception as e:
            print(Str(e))
            return APIResponse().dump(dict(message=f'Not able to login user:{Str(e)}')), 400

api.add_resource(LoginAPI, '/login')
docs.register(LoginAPI)

**ORM code:
**

def check_user_session_is_active(user_id):
    try:
        user_session = UserSession.query.filter_by(user_id = user_id, is_active = 1).first()
        if user_session:
            return True, user_session.session_id
        else:
            return False, None
    except Exception as e:
        raise e

def login_user(**kwargs):
    try:
        user = UserMaster.query.filter_by(username=kwargs['username'], password = kwargs['password'])
        if user:
            print("Logged In")

            is_active, session_id = check_user_session_is_active(user.id)

            if not is_active:
                session_id =uuid.uuid4()
                user_session = UserSession(uuid.uuid4(), user.id, session_id)
                db.session.add(user_session)
                db.session.commit()

            else:
                session['session_id'] = session_id

            session['session_id'] = session_id
            return True, session_id
        else:
            return False, None
    except Exception as e:
        raise e

LoginRequest code

class LoginRequest(Schema):
    username = fields.Str(default='username')
    password = fields.Str(default='password')

Expecting login success in swagger UI


问:
Updating RStudio in Linux (Google Chromebook)
I am trying to update RStudio on my Google Chromebook (running on Linux) and it is not working. Does anyone have some code I could use in the Linux terminal to update my RStudio?
Thanks in advance!</p>


问:
Text-overflow: ellipsis and overflow: scroll clip overflown text when scrolling
I've encountered a strange issue with scroll and text-overflow behaviour in div. Obviously, the content after the ellipsis should become visible when there is extra space. But that doesn't happen.

CSS:

```<code>overflow: scroll;
white-space: nowrap;
text-overflow: ellipsis;
</code>```

Picture

Any ideas on how to fix this?

Body:
I've encountered a strange issue with scroll and text-overflow behaviour in div. Obviously, the content after the ellipsis should become visible when there is extra space. But that doesn't happen.

CSS:

overflow: scroll;
white-space: nowrap;
text-overflow: ellipsis;

Picture

Any ideas on how to fix this?


Title: How to click on map and open page of state?

Body:
I have a map like this.

map

I want to open the province page when a user clicks on the province.

blade.php

<path onclick="parent.location.assign('http://localhost:8000/tourism/newyork')" class="NewYork" d=" M 322.03 227.95 C 319.84 226.68 321.35 222.19 323.96 223.37 C 330.39 224.41 336.80 225.64 343.16 227.04 C 348.44 228.07 352.49 231.90 357.48 233.68 C 359.80 234.56 362.17 235.33 364.52 236.14 C 364.83 237.64 365.15 239.15 365.47 240.67 C 360.74 242.31 355.77 243.14 351.10 244.90 C 346.81 246.02 347.83 251.28 346.16 254.43 C 343.86 256.42 340.68 257.36 338.89 259.94 C 337.06 262.50 335.71 265.36 334.23 268.13 C 334.13 265.83 334.02 263.53 333.92 261.24 C 332.28 261.00 330.64 260.76 329.01 260.53 C 328.87 263.09 328.72 265.66 328.57 268.23 C 327.94 266.28 327.30 264.32 326.70 262.37 C 321.87 262.27 317.03 262.45 312.20 262.11 C 312.10 259.41 311.57 256.67 312.03 253.98 C 314.93 250.92 319.36 250.12 322.83 247.88 C 327.95 244.74 330.84 238.90 331.54 233.06 C 328.32 231.46 324.89 230.16 322.03 227.95 Z" />

web.php

Route::get('/tourism/{tourismSlug}', [App\Http\Controllers\TourismController::class, 'single']);

TourismController.php

public function single(Tourism $tourism)
{
    $state = Tourism::query()->whereHas('state')->get();
    return $state   ;
}

Tourism.php

use HasFactory, Sluggable;

protected $guarded = [];

public function sluggable(): array
{
    return [
        'slug' => [
            'source' => 'city.name'
        ],
    ];
}

public function state()
{
    return $this->belongsTo(State::class);
}

public function city()
{
    return $this->belongsTo(City::class);
}

public function path()
{
    $locale = app()->getLocale();
    return "/$locale/tourism/$this->slug";
}

When I click on any province: I see this message.

404 Not Found


问:
How to setup imgproxy and frontend application for production
I am building an application that has a frontend (nuxt3) and a backend(nodejs/adonisjs). So far they both work in perfect harmony.

Now, the frontend applications needs to display and resize images of the products, so I've setup a new service, the imgproxy docker image. Everything worked perfect until I've added a key and a salt to verify the urls signature.

I don't understand how I should setup my applications so I can use the imgproxy image.

I generate the signature from the frontend application? - I tried that, it's not easy to do that and as per my readings it's not really recommended.

I generate the signature from the backend application? - I tried that, I can generate the signature from the backend, but the problem is, in the backend I don't know the sizes asked by the frontend. Do I make a standard list of image sizes that I need and for each I generate a signature?

My question is, what it's a recommended way of setting up the imgproxy to be used securely. It's not clear to me how to build the infrastructure so that the frontend can talk to the imgproxy and ask for different sizes images and in the same time the urls to be signed so that the imgproxy won't be abused.

How the infrastructure for this looks like? What are the implementations I need to do? What other software I need to use, how to use them?
It's really unclear for me this part.

Can someone give me some practical advises on how to setup the frontend, backend and imgproxy to work together?


问:
Which alternatives does Motif 2.3.8 has for virtual desktop?
I have read that MWM had WSM in the past, and that is included in the demos/programs folder in the source code for 2.3.8.

However, there is a note stating that the functionality to support was removed in 2.1.

As Motif is quite a legacy toolkit now the information available on this is obviously limited, I am wondering if somebody would still now (or remember from past days) which are the options to implement that kind of functionality in Motif.

I know such functionality is included in CDE which is now open sourced, but I do not like CDE.


问:
can't set Pixmap or Background by url of photo
i'm trying to setPixmap or Background by image url cause i'm using Pafy Module and it gives a link of YouTube video thumb so i hope if there a solution

i tried to setPixmap and Background both didn't work


问:
SQL Server (Linked Server)
My database is from a linked server and I have a problem with my connection string in ASP.NET (web.config) it says that :
Database schema could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online. Cannot open database "AA" requested by the login. The login failed. Login failed for user 'sa' at DataObjectSupport(423,6)

I try to use this connection string.

```<code><connectionStrings>
<add name="localconnection" connectionString="Data Source=SERVERNAME;Persist Security Info=True;Initial Catalog=database; uid=sa; Password=password; " providerName="System.Data.SqlClient"/>
</connectionStrings>
</code>```

Title: SQL Server (Linked Server)

Body:
My database is from a linked server and I have a problem with my connection string in ASP.NET (web.config) it says that :
Database schema could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online. Cannot open database "AA" requested by the login. The login failed. Login failed for user 'sa' at DataObjectSupport(423,6)

I try to use this connection string.

<connectionStrings>
<add name="localconnection" connectionString="Data Source=SERVERNAME;Persist Security Info=True;Initial Catalog=database; uid=sa; Password=password; " providerName="System.Data.SqlClient"/>
</connectionStrings>


问:
In my code is correct but after the run time error occurred in at Mozilla Firefox does not open
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line
How to resolve this issue


问:
TS Understanding Type Inference Between Defining a Type Alias For A Function And With Defining Its Type At Function Declaration
In the following functions, only the one using a defined type alias (myFunc) correctly narrows down the type of the arg within the IF...ELSE statement and I really don't know why this is the case:

interface Person {
  name: string
}

type MyFunc<T = Person | null> = (arg: T) => void;

const myFunc: MyFunc = arg => {
  if (arg === null) {
    const d = arg; // null
  } else {
    const d = arg; // Person
  }
};

const myFunc2: <T extends Person | null>(arg: T) => void = arg => {
  if (arg === null) {
    const d = arg; // T extends Person | null
  } else {
    const d = arg; // T & {}
  }
};
```
<p>What's the reason for these two to work so differently?</p>
<p>EDITED<br />
After reading @jcalz comment, I realized I need to be more specific with what I'm asking for the sake of avoiding confusion; basically, initially I was expecting <code>myFunc2</code> to work in the following way (again, thanks @jcalz for this code):</p>
<pre class="lang-js prettyprint-override"><code>const myFunc: (arg: Person | null) => void = arg => {
    if (arg === null) {
        const d = arg; // null
    } else {
        const d = arg; // Person
    }
};
</code>```

So my question is, why in myFunc2, inside branch arg === null, the type of arg is still considering Person as part of it; I'm not sure whether the reason for this is that one uses extends and the other simply defines its type, (meaning that one is generic and the other not), and if that's the case, I still not sure why the type isn't narrowed down as to remove Person from it.

I also don't know why the type of the falsy(?) branch does not include either of those types (null and Person).

Body:
In the following functions, only the one using a defined type alias (myFunc) correctly narrows down the type of the arg within the IF...ELSE statement and I really don't know why this is the case:

interface Person {
  name: string
}

type MyFunc<T = Person | null> = (arg: T) => void;

const myFunc: MyFunc = arg => {
  if (arg === null) {
    const d = arg; // null
  } else {
    const d = arg; // Person
  }
};

const myFunc2: <T extends Person | null>(arg: T) => void = arg => {
  if (arg === null) {
    const d = arg; // T extends Person | null
  } else {
    const d = arg; // T & {}
  }
};

What's the reason for these two to work so differently?

EDITED

After reading @jcalz comment, I realized I need to be more specific with what I'm asking for the sake of avoiding confusion; basically, initially I was expecting myFunc2 to work in the following way (again, thanks @jcalz for this code):

const myFunc: (arg: Person | null) => void = arg => {
    if (arg === null) {
        const d = arg; // null
    } else {
        const d = arg; // Person
    }
};

So my question is, why in myFunc2, inside branch arg === null, the type of arg is still considering Person as part of it; I'm not sure whether the reason for this is that one uses extends and the other simply defines its type, (meaning that one is generic and the other not), and if that's the case, I still not sure why the type isn't narrowed down as to remove Person from it.

I also don't know why the type of the falsy(?) branch does not include either of those types (null and Person).


问:
How to compute summation over distinct indices fast in R?
I want to compute

```<code>Tn<-sum((X[k]-X[l]) *(X[s]-X[t])) *(Y[k]-Y[l]) *(Y[s]-Y[t])
</code>```

with k, l, s, t distinct.

I tried this way:

```<code>Tn1<-sum((X[k]-X[l]) *(X[s]-X[t])) *(Y[k]-Y[l]) *(Y[s]-Y[t])
Tn2<-sum((X[k]-X[s]) *(X[l]-X[t])) *(Y[k]-Y[s]) *(Y[l]-Y[t])
Tn3<-sum((X[k]-X[t]) *(X[s]-X[l])) *(Y[k]-Y[t]) *(Y[s]-Y[l])
Tn<-(Tn1+Tn2+Tn3) / 3
</code>```

where the summations are over all indices with no restriction (by some computation, this is equal to the original one), but it is very slow. Is there any way to compute summation over distinct indices fast in R?

Body:
I want to compute

Tn<-sum((X[k]-X[l]) *(X[s]-X[t])) *(Y[k]-Y[l]) *(Y[s]-Y[t])

with k, l, s, t distinct.

I tried this way:

Tn1<-sum((X[k]-X[l]) *(X[s]-X[t])) *(Y[k]-Y[l]) *(Y[s]-Y[t])
Tn2<-sum((X[k]-X[s]) *(X[l]-X[t])) *(Y[k]-Y[s]) *(Y[l]-Y[t])
Tn3<-sum((X[k]-X[t]) *(X[s]-X[l])) *(Y[k]-Y[t]) *(Y[s]-Y[l])
Tn<-(Tn1+Tn2+Tn3) / 3

where the summations are over all indices with no restriction (by some computation, this is equal to the original one), but it is very slow. Is there any way to compute summation over distinct indices fast in R?