问:
Need help installing openpyxl - Solved
I keep getting this error:

```<code>**WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)'))': /simple/openpyxl/**
**Could not fetch URL https://pypi.org/simple/openpyxl/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/openpyxl/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer **
certificate (_ssl.c:992)'))) - skipping
**ERROR: Could not find a version that satisfies the requirement openpyxl (from versions: none)
ERROR: No matching distribution found for openpyxl**
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the
ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)'))) - skipping
**WARNING: There was an error checking the latest version of pip.**
</code>```

I'm using Visual Studios and want to use python to automated excel but can get past this first step XD

I've tried installing/updating pip and uninstalling/reinstalling python 3.11.1 but don't know what else to try

Title: Need help installing openpyxl - Solved

Body:
I keep getting this error:

**WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)'))': /simple/openpyxl/**
**Could not fetch URL https://pypi.org/simple/openpyxl/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/openpyxl/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer **
certificate (_ssl.c:992)'))) - skipping
**ERROR: Could not find a version that satisfies the requirement openpyxl (from versions: none)
ERROR: No matching distribution found for openpyxl**
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the
ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)'))) - skipping
**WARNING: There was an error checking the latest version of pip.**

I'm using Visual Studios and want to use python to automated excel but can get past this first step XD

I've tried installing/updating pip and uninstalling/reinstalling python 3.11.1 but don't know what else to try


来源: stackexchange

问:
There a way to schedule a script to automatically unzip a .zip file which overwrites all existing files?
I'm a bit of a newbie, but is there a way to schedule a script to automatically unzip a .zip file which overwrites all existing files?I've been reading and some people suggesting writing a .php script then having Cron to schedule it.If anyone can help me to figure out what do to, that will be much appreciated.
actually in my domain directory i create a zip like {mydomain.com/index.zip}
i am try to run this code but no result
/usr/local/bin/unzip /home/myhostname/mydomain.com/index.zip schedule:run >> /dev/null 2>&1
please give me a solution about it how i unzip it by cronjob

please give me a solution about it how i unzip it by cronjob

ContentLicense: CC BY-SA 4.0


问:
role is coming Undefine
```<code>exports.authorizeRoles = (...Roles)=>{

  return (req,res,next)=>{
    if(!Roles.includes(req.user.role)){
        next(new ErrorHander(`Role ${req.user.role} is not allowed to accsess this resource`,403))
    }
    next();
  }
}
</code>```

the above is my code for getting the role and authorize them to do some specific operation
but i am getting this type of error in my postman at the time of API testing

```<code>{
    "success": false,
    "message": "Cannot read properties of null (reading 'role')"
}
</code>```

Title: role is coming Undefine

Body:
exports.authorizeRoles = (...Roles)=>{

  return (req,res,next)=>{
    if(!Roles.includes(req.user.role)){
        next(new ErrorHander(`Role ${req.user.role} is not allowed to accsess this resource`,403))
    }
    next();
  }
}

the above is my code for getting the role and authorize them to do some specific operation
but i am getting this type of error in my postman at the time of API testing

{
    "success": false,
    "message": "Cannot read properties of null (reading 'role')"
}


问:
How to put quotes around all fields without specifying for the each individual field?
I wanted to export the data from the views to the CSV using the BCP Command, with each field of data in double quotes as text qualifiers,

For that, I have specified that in the XML format as below:

```<code><?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" LENGTH="9"  xsi:type="CharFixed" />
<FIELD ID="2" LENGTH="3"  xsi:type="CharFixed" />
</RECORD>
  <ROW>
    <COLUMN SOURCE="1" NAME="Id_ein_empr" xsi:type="SQLNVARCHAR" LENGTH="9" />
    <COLUMN SOURCE="2" NAME="Emp_Loc_nbr" xsi:type="SQLNVARCHAR" LENGTH="3" />
   </ROW>
</BCPFORMAT>
</code>```

And I am using this XML format in BCP query as:

For that, I have written the following query.

```<code>DECLARE
@DATACmd VARCHAR(500),
@FileLocation varchar(255),
@FileName varchar(255),
@StateCode varchar(2),
@v_Out_file_path varchar(255),
@v_Data_path varchar(255),
@header_format_path varchar(255),
@v_Header_path varchar(255),
@HeaderFileName varchar(255);

SET @FileLocation ='c:\csv\output'
SET @FileName = 'Araddis_'+FORMAT(Getdate(), 'MMddyyyy') + '.txt'
SET @v_Out_file_path = 'c:\csv\' + @StateCode + '\output\' + 'Output_' + @FileName
SET @v_Data_path = @FileLocation + '\' + @FileName

SELECT  @DATACmd = 'bcp '
                        + '"select * from Db_1.dbo.[Forms]"'
                        + ' queryout ' + @FileLocation
                        + '\' + @FileName
                        + ' -f "C:\csv\Format_FL.xml" -T -S' + @@servername;
SELECT  @DATACmd AS 'Command to execute';
EXECUTE master..xp_cmdshell @DATACmd;
</code>```

If there were just three columns on the records I would have done like
SELECT id, age, QUOTENAME(name,'"') FROM DBName..vieter as mentioned: in the answer of this question.

But I can't select the field one by one because it will have at least 50-60 fields in the export, without specifying the individual column?
Is there any way to add the quotes in the value, but ignore the null one?

Body:
I wanted to export the data from the views to the CSV using the BCP Command, with each field of data in double quotes as text qualifiers,

For that, I have specified that in the XML format as below:

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" LENGTH="9"  xsi:type="CharFixed" />
<FIELD ID="2" LENGTH="3"  xsi:type="CharFixed" />
</RECORD>
  <ROW>
    <COLUMN SOURCE="1" NAME="Id_ein_empr" xsi:type="SQLNVARCHAR" LENGTH="9" />
    <COLUMN SOURCE="2" NAME="Emp_Loc_nbr" xsi:type="SQLNVARCHAR" LENGTH="3" />
   </ROW>
</BCPFORMAT>

And I am using this XML format in BCP query as:

For that, I have written the following query.

DECLARE
@DATACmd VARCHAR(500),
@FileLocation varchar(255),
@FileName varchar(255),
@StateCode varchar(2),
@v_Out_file_path varchar(255),
@v_Data_path varchar(255),
@header_format_path varchar(255),
@v_Header_path varchar(255),
@HeaderFileName varchar(255);

SET @FileLocation ='c:\csv\output'
SET @FileName = 'Araddis_'+FORMAT(Getdate(), 'MMddyyyy') + '.txt'
SET @v_Out_file_path = 'c:\csv\' + @StateCode + '\output\' + 'Output_' + @FileName
SET @v_Data_path = @FileLocation + '\' + @FileName

SELECT  @DATACmd = 'bcp '
                        + '"select * from Db_1.dbo.[Forms]"'
                        + ' queryout ' + @FileLocation
                        + '\' + @FileName
                        + ' -f "C:\csv\Format_FL.xml" -T -S' + @@servername;
SELECT  @DATACmd AS 'Command to execute';
EXECUTE master..xp_cmdshell @DATACmd;

If there were just three columns on the records I would have done like
SELECT id, age, QUOTENAME(name,'"') FROM DBName..vieter as mentioned: in the answer of this question.

But I can't select the field one by one because it will have at least 50-60 fields in the export, without specifying the individual column?
Is there any way to add the quotes in the value, but ignore the null one?


问:
Creating function groups
I have recently decided to build an event library for the Arduino/ESP microcontrollers, the idea is simple - if an action happens, it invokes a function. In the code it requires holding a vector of function pointers in each Event object. Since the microcontrollers are limited in RAM, especially Arduino, I thought about ways of memory management and one of the ideas that I think maybe useful is to create function groups - objects that will wrap an array of function pointers (also they will be immutable) and will have an execute method that will run over each function and call it with the parameters needed.

My first attempt looked like this:

```<code>template<typename... Args>
class StaticFunctionGroup {
private:
    using function = action<Args...>; // action is a pointer for a function that returns 'void'
public:
    template<uint8_t Size>
    constexpr StaticFunctionGroup(function(functions)[Size])
        : m_functions(functions), m_size(Size)
    {
    }

    void operator () (Args... args) {
        for (uint8_t i = 0; i < m_size; i++)
            m_functions[i](args...);
    }

private:
    uint8_t m_size;
    function* m_functions;
};
</code>```

In main() function it could be used as following:

```<code>int main()
{
    StaticFunctionGroup<> group({
        f1, f2,f3, f4 // f1-f4 are void functions without parameters
    });
    group();
}
</code>```

The problem is that there is essentially a memory waste as I see it, because first I use a pointer to an array and I am not storing it in the object, and secondly I have to save the size of the array (for simplicity I used one byte sized number). So on the Arduino board this result in 3 bytes wasted for each such group (1 byte - size, 2 bytes the pointer).

Another change that I thought might be helpful was written like this:

```<code>template<uint8_t Size, typename... Args>
class StaticFunctionGroup {
private:
    using function = action<Args...>;
public:
    StaticFunctionGroup(function(&& functions)[Size])
    {
        for (uint8_t i = 0; i < Size; i++)
            m_functions[i] = functions[i];
    }

    void operator () (Args... args) {
        for (uint8_t i = 0; i < Size; i++)
            m_functions[i](args...);
    }

private:

    function m_functions[Size];
};
</code>```

This variation eliminates the 3 wasted bytes but turns as a problem itself since in the main() function there are two issues with this object:

```<code>int main()
{
    StaticFunctionGroup<4, > group({
        f1, f2,f3, f4
    });
    group();
}
</code>```

First, I have to specify the size of the function group each time, so if I remove or add some functions from the initializer braces, I will have to keep in mind the count of the functions and rewrite them every time. The second problem is that the code above simply doesn't work; It works if I add types in the template<> list so StaticFunctionGroup<4, int, int> would be valid, but it doesn't seem to work for functions with no parameters.

So thought this code journey I have combined all my questions:

Which version seems to be better, or none of them is good and there is another better version.

What is the solution for functions without parameters in version 2 and is there a rework for it to count the items itself without the need of specifying their amount every time?

General question - is moving the function pointers a good idea? What may be the difference between just creating new ones or moving them?

Title: Creating function groups

Body:
I have recently decided to build an event library for the Arduino/ESP microcontrollers, the idea is simple - if an action happens, it invokes a function. In the code it requires holding a vector of function pointers in each Event object. Since the microcontrollers are limited in RAM, especially Arduino, I thought about ways of memory management and one of the ideas that I think maybe useful is to create function groups - objects that will wrap an array of function pointers (also they will be immutable) and will have an execute method that will run over each function and call it with the parameters needed.

My first attempt looked like this:

template<typename... Args>
class StaticFunctionGroup {
private:
    using function = action<Args...>; // action is a pointer for a function that returns 'void'
public:
    template<uint8_t Size>
    constexpr StaticFunctionGroup(function(functions)[Size])
        : m_functions(functions), m_size(Size)
    {
    }

    void operator () (Args... args) {
        for (uint8_t i = 0; i < m_size; i++)
            m_functions[i](args...);
    }

private:
    uint8_t m_size;
    function* m_functions;
};

In main() function it could be used as following:

int main()
{
    StaticFunctionGroup<> group({
        f1, f2,f3, f4 // f1-f4 are void functions without parameters
    });
    group();
}

The problem is that there is essentially a memory waste as I see it, because first I use a pointer to an array and I am not storing it in the object, and secondly I have to save the size of the array (for simplicity I used one byte sized number). So on the Arduino board this result in 3 bytes wasted for each such group (1 byte - size, 2 bytes the pointer).

Another change that I thought might be helpful was written like this:

template<uint8_t Size, typename... Args>
class StaticFunctionGroup {
private:
    using function = action<Args...>;
public:
    StaticFunctionGroup(function(&& functions)[Size])
    {
        for (uint8_t i = 0; i < Size; i++)
            m_functions[i] = functions[i];
    }

    void operator () (Args... args) {
        for (uint8_t i = 0; i < Size; i++)
            m_functions[i](args...);
    }

private:

    function m_functions[Size];
};

This variation eliminates the 3 wasted bytes but turns as a problem itself since in the main() function there are two issues with this object:

int main()
{
    StaticFunctionGroup<4, > group({
        f1, f2,f3, f4
    });
    group();
}

First, I have to specify the size of the function group each time, so if I remove or add some functions from the initializer braces, I will have to keep in mind the count of the functions and rewrite them every time. The second problem is that the code above simply doesn't work; It works if I add types in the template<> list so StaticFunctionGroup<4, int, int> would be valid, but it doesn't seem to work for functions with no parameters.

So thought this code journey I have combined all my questions:

Which version seems to be better, or none of them is good and there is another better version.

What is the solution for functions without parameters in version 2 and is there a rework for it to count the items itself without the need of specifying their amount every time?

General question - is moving the function pointers a good idea? What may be the difference between just creating new ones or moving them?


问:
Ephemeral port limit on a Login Server that must support many concurrent connections
I am building a server cluster. One server will be the login server and there will be multiple "worker servers". So all users will point to the login server first and it will assign a working server to each user. The workload on this server will be minimal so that it can easily support hundreds of thousands (or even millions) of login requests per minute.

The connection uses TCP. Thus each new connection opens an ephemeral port for the duration of the connection/response (which is quite fast).

I started doing load tests and soon encountered ephemeral exhaustion. I've loaded a thousand or so users at a time and it takes seconds or less to run out of ports and the whole system becomes sluggish.

I increased the port range from 5000 to 65000.
I reduced the time_wait to 30 sec

But even then, that essentially means no more than 60,000 users can log in every 30 seconds (2000 per seconds). This is a too low number.

I know servers can support a much bigger load. But I can't find a good answer on how to overcome this limitation.

What would be the best approach to support hundreds of thousands of connections per minute?

I saw a suggestion to use multiple IPs and have a load balancer to send traffic to different IPs. But it seemed a lot more work.


Title: How to group by every n minutes and also avoid leakage in pandas?

Body:
I have got the dataset as below:

ID   Min_date                   Max_date                   time_diff_in_sec Name
1    2023-01-01 12:00:00.000    2023-01-01 12:00:01.000    1                A
2    2023-01-01 12:00:00.000    2023-01-01 12:00:10.000    10               A
3    2023-01-01 12:00:00.000    2023-01-01 12:10:00.000    600              A
4    2023-01-01 12:00:00.000    2023-01-01 12:15:00.000    900              A
5    2023-01-01 12:00:00.000    2023-01-01 12:15:01.000    901              A
6    2023-01-01 12:15:00.000    2023-01-01 12:16:00.000    60               A
7    2023-01-01 12:15:00.000    2023-01-01 12:17:01.000    121              A
8    2023-01-01 12:15:00.000    2023-01-01 12:15:02.000    2                A

I wanted to groupby every 10 mins for each Name and also take care of the residual time that has happened post 15 mins. The data after processing should look like:

Min_date                   Max_date                   time_diff_in_sec(sum)    Name   Count
2023-01-01 12:00:00.000    2023-01-01 12:09:59.999    1808(1+2+599+599+599)    A      5 (ID->1,2,3,4,5)
2023-01-01 12:10:00.000    2023-01-01 12:19:59.999    787(1+301+302+60+121+2)  A      6 (ID->3,4,5,6,7,8)


Title: Writing a conditional for printElements function that has 100+ Values

Body:
I am making a currencey exchange application by making an API call to currencey exchange website. I want the option for the user to select any desired currencey from around the world. With a succsesful API call, a JSON is returned

   {
    "result": "success",
    "documentation": "https://www.exchangerate-api.com/docs",
    "terms_of_use": "https://www.exchangerate-api.com/terms",
    "time_last_update_unix": 1673481602,
    "time_last_update_utc": "Thu, 12 Jan 2023 00:00:02 +0000",
    "time_next_update_unix": 1673568002,
    "time_next_update_utc": "Fri, 13 Jan 2023 00:00:02 +0000",
    "base_code": "USD",
    "conversion_rates": {
        "USD": 1,
        "AED": 3.6725,
        "AFN": 89.8016,
        "ALL": 109.0819,
        "AMD": 395.8582,
        "ANG": 1.7900,
        "AOA": 511.1933,
        "ARS": 180.3325,
        "AUD": 1.4481,
        "AWG": 1.7900,
        "AZN": 1.6989,
        "BAM": 1.8196,
        "BBD": 2.0000,
        "BDT": 103.8073,
        "BGN": 1.8196,
        "BHD": 0.3760,
        "BIF": 2067.3074,
        "BMD": 1.0000,
        "BND": 1.3312,
        "BOB": 6.9149,
        "BRL": 5.1987,
        "BSD": 1.0000,
        "BTN": 81.6573,
        "BWP": 12.7633,
        "BYN": 2.5109,
        "BZD": 2.0000,
        "CAD": 1.3418,
        "CDF": 2055.9987,
        "CHF": 0.9300,
        "CLP": 826.7277,
        "CNY": 6.7674,
        "COP": 4779.3841,
        "CRC": 585.8749,
        "CUP": 24.0000,
        "CVE": 102.5848,
        "CZK": 22.3444,
        "DJF": 177.7210,
        "DKK": 6.9408,
        "DOP": 56.5585,
        "DZD": 136.5304,
        "EGP": 28.4516,
        "ERN": 15.0000,
        "ETB": 53.5835,
        "EUR": 0.9304,
        "FJD": 2.1839,
        "FKP": 0.8235,
        "FOK": 6.9408,
        "GBP": 0.8235,
        "GEL": 2.6734,
        "GGP": 0.8235,
        "GHS": 10.4821,
        "GIP": 0.8235,
        "GMD": 63.0672,
        "GNF": 8653.3405,
        "GTQ": 7.8366,
        "GYD": 209.0327,
        "HKD": 7.8128,
        "HNL": 24.6584,
        "HRK": 7.0097,
        "HTG": 148.0084,
        "HUF": 370.9793,
        "IDR": 15436.3431,
        "ILS": 3.4421,
        "IMP": 0.8235,
        "INR": 81.6574,
        "IQD": 1459.6724,
        "IRR": 41971.2662,
        "ISK": 143.9749,
        "JEP": 0.8235,
        "JMD": 152.8483,
        "JOD": 0.7090,
        "JPY": 132.2611,
        "KES": 123.6722,
        "KGS": 85.4781,
        "KHR": 4119.4417,
        "KID": 1.4479,
        "KMF": 457.7013,
        "KRW": 1245.8448,
        "KWD": 0.3059,
        "KYD": 0.8333,
        "KZT": 461.9412,
        "LAK": 17033.9499,
        "LBP": 1507.5000,
        "LKR": 364.2070,
        "LRD": 154.3269,
        "LSL": 16.9409,
        "LYD": 4.7881,
        "MAD": 10.2148,
        "MDL": 19.1559,
        "MGA": 4543.5399,
        "MKD": 57.4550,
        "MMK": 2096.9659,
        "MNT": 3440.6855,
        "MOP": 8.0470,
        "MRU": 36.3695,
        "MUR": 43.9635,
        "MVR": 15.4304,
        "MWK": 1028.1896,
        "MXN": 18.9919,
        "MYR": 4.3712,
        "MZN": 64.0975,
        "NAD": 16.9409,
        "NGN": 449.9128,
        "NIO": 36.4912,
        "NOK": 9.9897,
        "NPR": 130.6517,
        "NZD": 1.5721,
        "OMR": 0.3845,
        "PAB": 1.0000,
        "PEN": 3.7946,
        "PGK": 3.5199,
        "PHP": 54.9816,
        "PKR": 228.4668,
        "PLN": 4.3584,
        "PYG": 7384.4414,
        "QAR": 3.6400,
        "RON": 4.5908,
        "RSD": 109.2836,
        "RUB": 69.1497,
        "RWF": 1085.6315,
        "SAR": 3.7500,
        "SBD": 8.3868,
        "SCR": 13.2984,
        "SDG": 538.0288,
        "SEK": 10.4712,
        "SGD": 1.3317,
        "SHP": 0.8235,
        "SLE": 19.5029,
        "SLL": 19502.8928,
        "SOS": 568.0050,
        "SRD": 32.0441,
        "SSP": 679.5885,
        "STN": 22.7935,
        "SYP": 2536.3858,
        "SZL": 16.9409,
        "THB": 33.4146,
        "TJS": 10.2240,
        "TMT": 3.4958,
        "TND": 3.0930,
        "TOP": 2.3699,
        "TRY": 18.7763,
        "TTD": 6.7711,
        "TVD": 1.4479,
        "TWD": 30.3627,
        "TZS": 2335.6703,
        "UAH": 36.7444,
        "UGX": 3687.5599,
        "UYU": 39.8317,
        "UZS": 11294.5364,
        "VES": 19.0531,
        "VND": 23436.0815,
        "VUV": 120.6118,
        "WST": 2.6811,
        "XAF": 610.2684,
        "XCD": 2.7000,
        "XDR": 0.7443,
        "XOF": 610.2684,
        "XPF": 111.0203,
        "YER": 250.0901,
        "ZAR": 16.9536,
        "ZMW": 18.3080,
        "ZWL": 704.5695
    }
}

I have a select input form on my HTML

<form id="form">
      US Dollars
      <input id="usdInput" type="number" name="usdInput">
      <select id="selectCurrencey">
        <option value="USD"></option>
        <option value="AED"></option>
        <option value="AFN"></option>
        <option value="ALL"></option>
        <option value="AMD"></option>
        <option value="ANG"></option>
        <option value="AOA"></option>
        <option value="ARS"></option>
        <option value="AUD"></option>
        <option value="AWG"></option>
        <option value="AZN"></option>
        <option value="BAM"></option>
        <option value="BBD"></option>
        <option value="BDT"></option>
        <option value="BGN"></option>
        <option value="BHD"></option>
        <option value="BIF"></option>
        <option value="BMD"></option>
        <option value="BND"></option>
        <option value="BOB"></option>
        <option value="BRL"></option>
        <option value="BSD"></option>
        <option value="BTN"></option>
        <option value="BWP"></option>
        <option value="BYN"></option>
        <option value="BZD"></option>
        <option value="CAD"></option>
        <option value="CDF"></option>
        <option value="CHF"></option>
        <option value="CLP"></option>
        <option value="CNY"></option>
        <option value="COP"></option>
        <option value="CRC"></option>
        <option value="CUP"></option>
        <option value="CVE"></option>
        <option value="CZK"></option>
        <option value="DJF"></option>
        <option value="DKK"></option>
        <option value="DOP"></option>
        <option value="DZD"></option>
        <option value="EGP"></option>
        <option value="ERN"></option>
        <option value="ETB"></option>
        <option value="EUR"></option>
        <option value="FJD"></option>
        <option value="FKP"></option>
        <option value="FOK"></option>
        <option value="GBP"></option>
        <option value="GEL"></option>
        <option value="GGP"></option>
        <option value="GHS"></option>
        <option value="GIP"></option>
        <option value="GMD"></option>
        <option value="GNF"></option>
        <option value="GTQ"></option>
        <option value="GYD"></option>
        <option value="HKD"></option>
        <option value="HNL"></option>
        <option value="HRK"></option>
        <option value="HTG"></option>
        <option value="HUF"></option>
        <option value="IDR"></option>
        <option value="ILS"></option>
        <option value="IMP"></option>
        <option value="INR"></option>
        <option value="IQD"></option>
        <option value="IRR"></option>
        <option value="ISK"></option>
        <option value="JEP"></option>
        <option value="JMD"></option>
        <option value="JOD"></option>
        <option value="JPY"></option>
        <option value="KES"></option>
        <option value="KGS"></option>
        <option value="KHR"></option>
        <option value="KID"></option>
        <option value="KMF"></option>
        <option value="KRW"></option>
        <option value="KWD"></option>
        <option value="KYD"></option>
        <option value="KZT"></option>
        <option value="LAK"></option>
        <option value="LBP"></option>
        <option value="LKR"></option>
        <option value="LRD"></option>
        <option value="LSL"></option>
        <option value="LYD"></option>
        <option value="MAD"></option>
        <option value="MDL"></option>
        <option value="MGA"></option>
        <option value="MKD"></option>
        <option value="MMK"></option>
        <option value="MNT"></option>
        <option value="MOP"></option>
        <option value="MRU"></option>
        <option value="MUR"></option>
        <option value="MVR"></option>
        <option value="MWK"></option>
        <option value="MXN"></option>
        <option value="MYR"></option>
        <option value="MZN"></option>
        <option value="NAD"></option>
        <option value="NGN"></option>
        <option value="NIO"></option>
        <option value="NOK"></option>
        <option value="NPR"></option>
        <option value="NZD"></option>
        <option value="OMR"></option>
        <option value="PAB"></option>
        <option value="PEN"></option>
        <option value="PGK"></option>
        <option value="PHP"></option>
        <option value="PKR"></option>
        <option value="PLN"></option>
        <option value="PYG"></option>
        <option value="QAR"></option>
        <option value="RON"></option>
        <option value="RSD"></option>
        <option value="RUB"></option>
        <option value="RWF"></option>
        <option value="SAR"></option>
        <option value="SBD"></option>
        <option value="SCR"></option>
        <option value="SDG"></option>
        <option value="SEK"></option>
        <option value="SGD"></option>
        <option value="SHP"></option>
        <option value="SLE"></option>
        <option value="SLL"></option>
        <option value="SOS"></option>
        <option value="SRD"></option>
        <option value="SSP"></option>
        <option value="STN"></option>
        <option value="SYP"></option>
        <option value="SZL"></option>
        <option value="THB"></option>
        <option value="TJS"></option>
        <option value="TMT"></option>
        <option value="TND"></option>
        <option value="TOP"></option>
        <option value="TRY"></option>
        <option value="TTD"></option>
        <option value="TVD"></option>
        <option value="TWD"></option>
        <option value="TZS"></option>
        <option value="UAH"></option>
        <option value="UGX"></option>
        <option value="UYU"></option>
        <option value="UZS"></option>
        <option value="VES"></option>
        <option value="VND"></option>
        <option value="VUV"></option>
        <option value="WST"></option>
        <option value="XAF"></option>
        <option value="XCD"></option>
        <option value="XDR"></option>
        <option value="XOF"></option>
        <option value="XPF"></option>
        <option value="YER"></option>
        <option value="ZAR"></option>
        <option value="ZMW"></option>
        <option value="ZWL"></option>

      </select>

Then the printElements when API call is 200

 function printElements(response, usd) {
  let currencySelect = document.getElementById('SELECTED OPTION').value
  document.getElementById('showExchange').innerText = `${usd} to ${response["conversion_rates"].'SELECTED OPTION'}`
}

Instead of writing 100+ if statements...
is there a way to select the input of which currencey is selected and check to see if that value is equal to currencey key in the JSON in order to print it to the DOM?

I have not tried writing the 100+ if statements, wondering if anyone else knew?


问:
why my lintr doesn’t work on viscose remote
I’m already installed R extension in vscode but it’s shown

```<code>Failed to run diagnostics: unused argument (text = content)
</code>```

Meanwhile I’m created .lintr file on the root path.
I also run it on terminal,it’s works.

int(“./xx/li.R”)

It’s works on my local environment but when I remote it’s doesn’t work,which is really confusing me.

my R code as follow:

```<code>num1 <- 2
num2 <- 3
print(num1+num2)
</code>```

Body:
I’m already installed R extension in vscode but it’s shown

Failed to run diagnostics: unused argument (text = content)

Meanwhile I’m created .lintr file on the root path.
I also run it on terminal,it’s works.

int(“./xx/li.R”)

It’s works on my local environment but when I remote it’s doesn’t work,which is really confusing me.

my R code as follow:

num1 <- 2
num2 <- 3
print(num1+num2)


问:
Vite gives invalid js syntax error to file that has array of paths and elements
I have migrated my react app to Vite. Initially I had error Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.

I changed file extensions to .jsx from .js. There is one file routes.js that contains an array of object with properties path and element, element is the page that will be used in react-router when looped over the array.

When I change the  extension to .jsx the application stops loading, and when I make it .js the vite gives extension error.

Array of pages and paths looks like this:

```<code>const Routes = [
  {
    path: "/",
    element: <DashBoard />,
  }
]
</code>```

I tried changing the extension to .jsx but then the application stops loading/routing and when change it back to only .js vite has error.

Body:
I have migrated my react app to Vite. Initially I had error Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.

I changed file extensions to .jsx from .js. There is one file routes.js that contains an array of object with properties path and element, element is the page that will be used in react-router when looped over the array.

When I change the  extension to .jsx the application stops loading, and when I make it .js the vite gives extension error.

Array of pages and paths looks like this:

const Routes = [
  {
    path: "/",
    element: <DashBoard />,
  }
]

I tried changing the extension to .jsx but then the application stops loading/routing and when change it back to only .js vite has error.


问:
react-native-youtube-iframe (framework) is authorized for youtube?
Is it safe to use it at my job in company? My boss said that his friend took block on all videos on the site because he was using unauthorized resources to play them and took a huge damage...

I have been searching a long time for this question and I have nothing


问:
How to stop Retrofit from caching old parameter values?
On some APIs on the app I'm working on, the user location is sent as one of the parameters, so their locations can be monitored via web dashboard, like this:

```<code>@FormUrlEncoded
@POST("v1/visit")
Call<StartVisitResponse> startVisit(
    @Header("Authorization") String token,
    @Header("latitude") String latiude,
    @Header("longitude") String longitude,
    @Field("outlet_id") int outlet_id,
    @Field("date") String String visit_date
);
</code>```

And this is an activity that illustrates the main problem:

```<code>class StartVisitActivity implements AppCompactActivity {

    ActivityStartVisitBinding uiBinding;
    InstantLocate theInstantLocate; // from https://github.com/mukul56/InstantLocate

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        uiBinding.btnGetLocation( v -> {
            initLocation();
        });

        uiBinding.btnStartVisit( v -> {

            ApiClient.getClient().create(ApiInterface.class).startVisit(
                                           Helper.getAuthToken(),
                                           ""+theInstantLocate.getlatitude(),
                                           ""+theInstantLocate.getlongitude(),
                                           outletId,
                                           date).enqueue(new Callback<StartVisitResponse>() {

                                       @Override
                                       public void onResponse(Call<StartVisitResponse> call, Response<StartVisitResponse> response) {
                                           if (response.isSuccessful()) {

                                           } else {

                                           }
                                       }

                                       @Override
                                       public void onFailure(Call<StartVisitResponse> call, Throwable t) {

                                       }
                                   });

        })

    }

    private void initLocation(){
        theInstantLocate = new InstantLocate(this);
        theInstantLocate.instantLocation();

        Toast.makeText(getApplicationContext, "Hi you are going to visit outlet ("+theInstantLocate.getlatitude()+","+theInstantLocate.getlongitude()+").", Toast.LENGTH_SHOW).show();
    }

}
</code>```

First press the "Get Location" button to get our current location, then the "Start Visit" button. While inspecting the web dashboard, we found some users visiting different outlets started at the same position (which actually didn't). Weird.

After about 15 minutes of changing FakeGPS location and calling initLocation() (without quitting the app) repeatedly, both locations are always match. The issue is on startVisit(). For example I changed locations a few time: Tokyo -> Bangkok -> Jakarta. When inspecting the startVisit log, my detection location was still in Tokyo. Seems like Retrofit cached my old position parameters. How to clear those, so the latest values are always used?

For more information, this is my ApiClient class:

```<code>public class ApiClient {

    public static final String BASE_URL = ".........";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Interceptor httpClient = chain -> {
            Request original = chain.request();
            String method = original.method();
            HttpUrl.Builder httpBuilder = original.url().newBuilder();
            String token = Prefs.getString("TOKEN", null);

            Request.Builder requestBuilder;
            if (token != null){
                requestBuilder = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .method(method, original.body())
                        .header("Authorization", Helper.getToken())
                        .header("latitude", Helper.getLatitude())
                        .header("longitude", Helper.getLongitude());
            }else {
                requestBuilder = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .method(method, original.body());
            }

            Request request = requestBuilder.url(httpBuilder.build()).build();
            return chain.proceed(request);
        };
        OkHttpClient client = null;
            client = new OkHttpClient.Builder().connectTimeout(100, TimeUnit.SECONDS)
                    .readTimeout(100, TimeUnit.SECONDS).addInterceptor(interceptor)
                    .addInterceptor(new ChuckerInterceptor(BaseApp.getAppContext()))
                    .addInterceptor(httpClient).build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
</code>```

Body:
On some APIs on the app I'm working on, the user location is sent as one of the parameters, so their locations can be monitored via web dashboard, like this:

@FormUrlEncoded
@POST("v1/visit")
Call<StartVisitResponse> startVisit(
    @Header("Authorization") String token,
    @Header("latitude") String latiude,
    @Header("longitude") String longitude,
    @Field("outlet_id") int outlet_id,
    @Field("date") String String visit_date
);

And this is an activity that illustrates the main problem:

class StartVisitActivity implements AppCompactActivity {

    ActivityStartVisitBinding uiBinding;
    InstantLocate theInstantLocate; // from https://github.com/mukul56/InstantLocate

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        uiBinding.btnGetLocation( v -> {
            initLocation();
        });

        uiBinding.btnStartVisit( v -> {

            ApiClient.getClient().create(ApiInterface.class).startVisit(
                                           Helper.getAuthToken(),
                                           ""+theInstantLocate.getlatitude(),
                                           ""+theInstantLocate.getlongitude(),
                                           outletId,
                                           date).enqueue(new Callback<StartVisitResponse>() {

                                       @Override
                                       public void onResponse(Call<StartVisitResponse> call, Response<StartVisitResponse> response) {
                                           if (response.isSuccessful()) {

                                           } else {

                                           }
                                       }

                                       @Override
                                       public void onFailure(Call<StartVisitResponse> call, Throwable t) {

                                       }
                                   });

        })

    }

    private void initLocation(){
        theInstantLocate = new InstantLocate(this);
        theInstantLocate.instantLocation();

        Toast.makeText(getApplicationContext, "Hi you are going to visit outlet ("+theInstantLocate.getlatitude()+","+theInstantLocate.getlongitude()+").", Toast.LENGTH_SHOW).show();
    }

}

First press the "Get Location" button to get our current location, then the "Start Visit" button. While inspecting the web dashboard, we found some users visiting different outlets started at the same position (which actually didn't). Weird.

After about 15 minutes of changing FakeGPS location and calling initLocation() (without quitting the app) repeatedly, both locations are always match. The issue is on startVisit(). For example I changed locations a few time: Tokyo -> Bangkok -> Jakarta. When inspecting the startVisit log, my detection location was still in Tokyo. Seems like Retrofit cached my old position parameters. How to clear those, so the latest values are always used?

For more information, this is my ApiClient class:

public class ApiClient {

    public static final String BASE_URL = ".........";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Interceptor httpClient = chain -> {
            Request original = chain.request();
            String method = original.method();
            HttpUrl.Builder httpBuilder = original.url().newBuilder();
            String token = Prefs.getString("TOKEN", null);

            Request.Builder requestBuilder;
            if (token != null){
                requestBuilder = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .method(method, original.body())
                        .header("Authorization", Helper.getToken())
                        .header("latitude", Helper.getLatitude())
                        .header("longitude", Helper.getLongitude());
            }else {
                requestBuilder = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .method(method, original.body());
            }

            Request request = requestBuilder.url(httpBuilder.build()).build();
            return chain.proceed(request);
        };
        OkHttpClient client = null;
            client = new OkHttpClient.Builder().connectTimeout(100, TimeUnit.SECONDS)
                    .readTimeout(100, TimeUnit.SECONDS).addInterceptor(interceptor)
                    .addInterceptor(new ChuckerInterceptor(BaseApp.getAppContext()))
                    .addInterceptor(httpClient).build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}


问:
html2canvas text alignment is off
I'm using html2canvas to allow users to download a div element to their local files as an image.
What they are saving is an image with dynamic text on top of it that changes based on their user input (this whole div becomes one image).

The saving part works, and users can save the div as an image to their local files. However, the dynamic text moves downward and the image looks off because of it.

I tried to make changes to html2canvas code based on someone's solution on github, but it didn't work and I reset this code to the original.

Is this a common problem that others have faced? How do I solve this problem without hard-coding the solution (moving the dynamic text up on the web application so when it moves downward when saving, it looks how it's supposed to look)?

Thanks!

Title: html2canvas text alignment is off


问:
rticles::arxiv_article template seems confused by \newpage
I'm modifying the bookdown arXiv template by gradually adding chunks (containing knitr::include_graphics() images) and hoped to generate a new page prior to the "tables" section.

Problem: "table 1" is presented out of order in the output and the \newpage prior to "3.2 Tables" is not recognized.

Question: Does this template support \newpage per https://bookdown.org/yihui/rmarkdown-cookbook/pagebreaks.html ?

my output:

template and output are on https://github.com/cordphelps/arXiv-preprint-ampelos


问:
getting req.params is showing undefined
I need product id that's _id from my mongo document but when I consoled req.params.id it is showing undefined to my /shop page and I'm following mvc format</p>
```<code>// get request://
router.get("/shop/:id",userController.shopPage)

//route://

 getProductPage: (req, res) => {
    try{
      let proId = req.params.id;
      console.log(proId)
      productHelpers
    .getProduct(proId)
    .then((products) => {

      res.render("user/view-product",{products}); })}
      catch(error){

      }

//get Product//

  getProduct: (proId) => {
    console.log(proId)
    return new Promise((resolve, reject) => {
      try {
        db.products.find({_id:proId}).then((products) => {
          resolve(products);
        });
      } catch (error) {
        console.log(error);
      }
    });
  },
</code>```

Title: getting req.params is showing undefined

Body:
I need product id that's _id from my mongo document but when I consoled req.params.id it is showing undefined to my /shop page and I'm following mvc format

// get request://
router.get("/shop/:id",userController.shopPage)

//route://

 getProductPage: (req, res) => {
    try{
      let proId = req.params.id;
      console.log(proId)
      productHelpers
    .getProduct(proId)
    .then((products) => {

      res.render("user/view-product",{products}); })}
      catch(error){

      }

//get Product//

  getProduct: (proId) => {
    console.log(proId)
    return new Promise((resolve, reject) => {
      try {
        db.products.find({_id:proId}).then((products) => {
          resolve(products);
        });
      } catch (error) {
        console.log(error);
      }
    });
  },


问:
Unity Horizontal Input is Always -1
Whenever I'm making a game (3D or 2D) and I use Input.GetAxis("Horizontal"); Without pressing any buttons, my input is always -1. This problem only shows up with Unity.

Inputs for Unity

To test, I played other video games (some made with Unity & some not made with Unity) and they work fine. Only one or two games made with Unity kept thinking I'm holding down either the left arrow key or the "A" key.

While in play mode, if I press the "D" key, I'll move to the right and when I take my finger off the key, it moves back to the left as if I'm pressing the "A" key.

Somethings when I enter play mode, the Vertical Input will also receive inputs that are not given.
Note: This happens at the very start (when I click the play button).
Console & Game (no inputs by me)

Same Input in a UI Scene

My Code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    private Rigidbody2D rb;
    private Vector2 moveDirection;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        ProcessInputs();
    }

    private void FixedUpdate()
    {
        Move();
    }

    void ProcessInputs()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveY = Input.GetAxis("Vertical");

        print("X: " + moveX + " | Y: " + moveY);

        moveDirection = new Vector2(moveX, moveY).normalized;
    }

    void Move()
    {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }
}
</code>```

Title: Unity Horizontal Input is Always -1

Body:
Whenever I'm making a game (3D or 2D) and I use Input.GetAxis("Horizontal"); Without pressing any buttons, my input is always -1. This problem only shows up with Unity.

Inputs for Unity

To test, I played other video games (some made with Unity & some not made with Unity) and they work fine. Only one or two games made with Unity kept thinking I'm holding down either the left arrow key or the "A" key.

While in play mode, if I press the "D" key, I'll move to the right and when I take my finger off the key, it moves back to the left as if I'm pressing the "A" key.

Somethings when I enter play mode, the Vertical Input will also receive inputs that are not given.
Note: This happens at the very start (when I click the play button).
Console & Game (no inputs by me)

Same Input in a UI Scene

My Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    private Rigidbody2D rb;
    private Vector2 moveDirection;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        ProcessInputs();
    }

    private void FixedUpdate()
    {
        Move();
    }

    void ProcessInputs()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveY = Input.GetAxis("Vertical");

        print("X: " + moveX + " | Y: " + moveY);

        moveDirection = new Vector2(moveX, moveY).normalized;
    }

    void Move()
    {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }
}


问:
What causes a type error when subscribing to list?
I have the following code im running in CoLab with Python Version 3.8 (not 3.9):

```<code>from typing import List, Dict

def get_embedding(text: str, model: str=EMBEDDING_MODEL) -> list[float]:
    result = openai.Embedding.create(
      model=model,
      input=text
    )
    return result["data"][0]["embedding"]

def compute_doc_embeddings(df: pd.DataFrame) -> dict[tuple[str, str], list[float]]:
    """
    Create an embedding for each row in the dataframe using the OpenAI Embeddings API.

    Return a dictionary that maps between each embedding vector and the index of the row that it corresponds to.
    """
    return {
        idx: get_embedding(r.content) for idx, r in df.iterrows()
    }
</code>```

Which results in this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-bd6d3a14202c> in <module>
      1 from typing import List, Dict
      2
----> 3 def get_embedding(text: str, model: str=EMBEDDING_MODEL) -> list[float]:
      4     result = openai.Embedding.create(
      5       model=model,

TypeError: 'type' object is not subscriptable
```

Is there a workaround to fixing the declaration besides upgrading to 3.9?

Body:
I have the following code im running in CoLab with Python Version 3.8 (not 3.9):

from typing import List, Dict

def get_embedding(text: str, model: str=EMBEDDING_MODEL) -> list[float]:
    result = openai.Embedding.create(
      model=model,
      input=text
    )
    return result["data"][0]["embedding"]

def compute_doc_embeddings(df: pd.DataFrame) -> dict[tuple[str, str], list[float]]:
    """
    Create an embedding for each row in the dataframe using the OpenAI Embeddings API.

    Return a dictionary that maps between each embedding vector and the index of the row that it corresponds to.
    """
    return {
        idx: get_embedding(r.content) for idx, r in df.iterrows()
    }

Which results in this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-bd6d3a14202c> in <module>
      1 from typing import List, Dict
      2
----> 3 def get_embedding(text: str, model: str=EMBEDDING_MODEL) -> list[float]:
      4     result = openai.Embedding.create(
      5       model=model,

TypeError: 'type' object is not subscriptable

Is there a workaround to fixing the declaration besides upgrading to 3.9?


问:
Deploy application on aws and make other user pay the bill
I am noob on AWS, I need to deploy an app there but I don't want to pay for it, instead the person who asked me to do the the app must be the payer, How can I do this? I saw that I can create IAM users but I don't see any documentation to delegate the payment to one IAM user and I am scared of being charged for something that I am not benefiting, I am missunderstanding the concept of IAM users? where can I find docs for achieve this purpose?</p>


问:
How can I get all my values from a Promise and for each loop to not just log to the console but to store in an array to use in react
Right now I am getting a list of 10 url's from a promise from firebase and I then logging them to the console. What I would like to do is store the list in an object but I don't know how to return it from the promise to use elsewhere in my code.

I tried array.push as well as return obj but that doesn't seem to work well.

```<code>const multipleurls = await Promise.all([urlRef.getDownloadURL()])
  .then((data) => data.forEach(function (obj){
    console.log(obj) // this is logging all the values so i know the promise fine.
  }))
</code>```

UPDATE::  I took away the object multiple urls and left it as a function and then i returned obj and it worked.

Body:
Right now I am getting a list of 10 url's from a promise from firebase and I then logging them to the console. What I would like to do is store the list in an object but I don't know how to return it from the promise to use elsewhere in my code.

I tried array.push as well as return obj but that doesn't seem to work well.

const multipleurls = await Promise.all([urlRef.getDownloadURL()])
  .then((data) => data.forEach(function (obj){
    console.log(obj) // this is logging all the values so i know the promise fine.
  }))

UPDATE::  I took away the object multiple urls and left it as a function and then i returned obj and it worked.


问:
How laravel cache works?
how does the cache in laravel work?
I use the function Cache::remember to save for 5 seconds the response to the request, and when the time expires it will be updated again, but this does not happen for some reason

cache driver - redis

without caching the function gives fresh results, but with caching - the old results

code example

```<code>public function last_win()
{
    return Cache::remember("last-wins", config("cache-config.cache_time.last-wins"), function () {
        return GameBet::with("getGame")
            ->where('created_at', '<=', Carbon::now())
            ->where("win", ">", 0)
            ->orderBy("created_at", "desc")
            ->orderBy("id", "desc")
            ->simplePaginate(25)
            ->toArray();
    });
}
</code>```

in config:

```<code>"cache_time" => [
    "last-wins" => env("CACHE_TIME_LAST_WINS", 5), // 5 sec
],
</code>```

please tell me what i'm doing wrong:)

Title: How laravel cache works?

Body:
how does the cache in laravel work?
I use the function Cache::remember to save for 5 seconds the response to the request, and when the time expires it will be updated again, but this does not happen for some reason

cache driver - redis

without caching the function gives fresh results, but with caching - the old results

code example

public function last_win()
{
    return Cache::remember("last-wins", config("cache-config.cache_time.last-wins"), function () {
        return GameBet::with("getGame")
            ->where('created_at', '<=', Carbon::now())
            ->where("win", ">", 0)
            ->orderBy("created_at", "desc")
            ->orderBy("id", "desc")
            ->simplePaginate(25)
            ->toArray();
    });
}

in config:

"cache_time" => [
    "last-wins" => env("CACHE_TIME_LAST_WINS", 5), // 5 sec
],

please tell me what i'm doing wrong:)


问:
Python merging npz files , array with dtype S3
I have two npz file, downloaded from Biobank :

The first file is chr6_24000001_27000001.gz and the second is chr6_25000001_28000001.gz.

Based on previous suggestion here   and here , I reazlied that my files containng five arrays and tried to concotenate them.

But for the third array which it name is 'format', I got error message :

Traceback (most recent call last):
File "", line 1, in
File "<array_function internals>", line 180, in concatenate
ValueError: zero-dimensional arrays cannot be concatenated

By runnung this code :
data2['format'] the answer is array(b'coo', dtype='|S3')

I`m not very familiar with Python but after a lot of searching, the only place that I found S3 type was here.

I used this code to combine two npz files:

data1 = np.load('chr6_24000001_27000001.npz' , allow_pickle=True)
data2 = np.load('chr6_25000001_28000001.npz', allow_pickle=True)

for k in data1.files :
...     print(k)
...
row
col
format
shape
data

row = np.concatenate([data1['row'], data2['row']])
col = np.concatenate([data1['col'], data2['col']])

data2['format']
array(b'coo', dtype='|S3')
data1['format']
array(b'coo', dtype='|S3')

print(data1['format'])
b'coo'
print(data2['format'])
b'coo'

format = data1['format']

Because two content where the same and I don`t know what was inside them!

shape = np.concatenate([data1['shape'], data2['shape']])
data = np.concatenate([data1['data'], data2['data']])

np.savez_compressed('chr6_24000001_28000001.npz', row=row, col=col, format=format, shape=shape, data=data )
loaded = np.load('chr6_24000001_28000001.npz')
print(np.array_equal(format , loaded['format']))
True

When I used this npz file, I got error :

ValueError: too many values to unpack (expected 2)

I`m so grteful if someone help me to combine these two files, correctly.


问:
How to call plenty of hierarchical RESTful APIs simultaneously and efficiently in Java
Suppose I've got a RESTful API /getDivision/dID=?, the ? need to be replaced with the actual division ID.

Assuming the dID=1, it return a JSON like below:

```<code>{
    "division": 1
    "subdivisions": "2,3,4,5",
    "status": true
}
</code>```

The return JSON contains the subdivision IDs of the dID=1 split by commas.

Note that a subdivision also has its own subdivisions and the top division id is 1. So it is a hierarchical API calling.

Now, in Java, I want to collect all the division IDs in a thread-safe collection. How can I run the routine concurrently and efficiently?

I've tried multithreading, but I think it's high performance overhead. Can I do something akin to non-blocking I/O?

Body:
Suppose I've got a RESTful API /getDivision/dID=?, the ? need to be replaced with the actual division ID.

Assuming the dID=1, it return a JSON like below:

{
    "division": 1
    "subdivisions": "2,3,4,5",
    "status": true
}

The return JSON contains the subdivision IDs of the dID=1 split by commas.

Note that a subdivision also has its own subdivisions and the top division id is 1. So it is a hierarchical API calling.

Now, in Java, I want to collect all the division IDs in a thread-safe collection. How can I run the routine concurrently and efficiently?

I've tried multithreading, but I think it's high performance overhead. Can I do something akin to non-blocking I/O?


问:
Show multiple files from console log in html paragraph tag
```<code>app.post("/upload",upload.single('myfile'), function(req,res){
  fs.readdir(directoryPath, function (err, files) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {

      //
        console.log(file);
    });
});
  res.redirect("/");

})
</code>```
```<code>          <form enctype="multipart/form-data" action="/upload" method="post">
           <input type="file" name="myfile" /><br/><br/>
           <input type="submit" value="Upload File" name="submit"><br/><br/>
          </form>
</code>```

I'm trying to show the multiple files that I have uploaded but i'm not sure how to take it from the console.log(file) to print in my index.ejs

i tried watching a couple of videos both of which left them in the console log and didn't transfer to show the saved files on the website portion.

Body:
app.post("/upload",upload.single('myfile'), function(req,res){
  fs.readdir(directoryPath, function (err, files) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {

      //
        console.log(file);
    });
});
  res.redirect("/");

})

          <form enctype="multipart/form-data" action="/upload" method="post">
           <input type="file" name="myfile" />

           <input type="submit" value="Upload File" name="submit">

          </form>

I'm trying to show the multiple files that I have uploaded but i'm not sure how to take it from the console.log(file) to print in my index.ejs

i tried watching a couple of videos both of which left them in the console log and didn't transfer to show the saved files on the website portion.


问:
react native ios crash on launch UIKitCore
we're getting a small number but regular crashes on launch in a production app.
We have Crashlytics and Sentry but i cant see any references to the react code.

Here is a couple of stacktraces

```<code>Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x2d318 __abort_with_payload + 8
1  libsystem_kernel.dylib         0x2fc24 abort_with_payload_wrapper_internal + 104
2  libsystem_kernel.dylib         0x2fbbc abort_with_payload_wrapper_internal + 30
3  libobjc.A.dylib                0x2d0b4 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 116
4  libobjc.A.dylib                0x2d040 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30
5  libobjc.A.dylib                0x5acc weak_register_no_lock + 392
6  libobjc.A.dylib                0xa924 objc_storeWeak + 448
7  UIKitCore                      0x2a2ee0 -[_UIBoundingPath initWithCoordinateSpace:] + 96
8  UIKitCore                      0x613fc4 -[_UIComplexBoundingPath initWithCoordinateSpace:orientation:scale:boundingPathBitmap:] + 112
9  UIKitCore                      0x3f11d0 -[_UIScreenComplexBoundingPathUtilities boundingPathForWindow:] + 2836
10 UIKitCore                      0x675ddc -[UIWindow _boundingPath] + 204
11 UIKitCore                      0x1b1650 -[UIView(UIViewBoundingPathSupportInternal) _effectiveBoundingPathAndBoundingPathView:] + 244
12 UIKitCore                      0x4bab4c -[UIView(UIViewBoundingPathSupport) _rectTuckedAgainstBoundingPathEdge:withSize:cornerRadii:minimumPadding:] + 260
13 UIKitCore                      0x6b74f8 -[_UISheetLayoutInfo _unsafeInsets] + 160
14 UIKitCore                      0x71f18 -[_UISheetLayoutInfo _marginsWhenFloating] + 184
15 UIKitCore                      0x3aca4c -[_UISheetLayoutInfo _isEdgeAttached] + 52
16 UIKitCore                      0x467ffc -[_UISheetLayoutInfo _reversedIndexOfLastUndimmedDetent] + 84
17 UIKitCore                      0x2d713c -[_UISheetLayoutInfo _activeDetentValues] + 348
18 UIKitCore                      0x24b990 -[_UISheetLayoutInfo _offsetForCurrentActiveDetent] + 48
19 UIKitCore                      0x583b5c -[_UISheetLayoutInfo _frameOfPresentedViewInContainerView] + 100
20 UIKitCore                      0x3cad98 -[UISheetPresentationController _containerViewLayoutSubviews] + 652
21 UIKitCore                      0x2231dc -[UITransitionView layoutSubviews] + 92
22 UIKitCore                      0x18c17c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2592
23 QuartzCore                     0x407fc CA::Layer::layout_if_needed(CA::Transaction*) + 532
24 QuartzCore                     0x32c60 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 136
25 QuartzCore                     0x475b4 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 452
26 QuartzCore                     0x504a8 CA::Transaction::commit() + 704
27 QuartzCore                     0x323a0 CA::Transaction::flush_as_runloop_observer(bool) + 88
28 UIKitCore                      0x53e6e0 _UIApplicationFlushCATransaction + 72
29 UIKitCore                      0x7d8d5c _UIUpdateSequenceRun + 84
30 UIKitCore                      0xe5fedc schedulerStepScheduledMainSection + 144
31 UIKitCore                      0xe5f6a4 runloopSourceCallback + 92
32 CoreFoundation                 0xbb414 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
33 CoreFoundation                 0xcc1a0 __CFRunLoopDoSource0 + 208
34 CoreFoundation                 0x5694 __CFRunLoopDoSources0 + 268
35 CoreFoundation                 0xb05c __CFRunLoopRun + 828
36 CoreFoundation                 0x1ebc8 CFRunLoopRunSpecific + 600
37 GraphicsServices               0x1374 GSEventRunModal + 164
38 UIKitCore                      0x514b58 -[UIApplication _run] + 1100
39 UIKitCore                      0x296090 UIApplicationMain + 364
40 App.                           0x72a4 main + 8 (main.m:8)
</code>```
```<code>Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x2d318 __abort_with_payload + 8
1  libsystem_kernel.dylib         0x2fc24 abort_with_payload_wrapper_internal + 104
2  libsystem_kernel.dylib         0x2fbbc abort_with_payload_wrapper_internal + 30
3  libobjc.A.dylib                0x2d0b4 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 116
4  libobjc.A.dylib                0x2d040 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30
5  libobjc.A.dylib                0x5acc weak_register_no_lock + 392
6  libobjc.A.dylib                0xa924 objc_storeWeak + 448
7  UIKitCore                      0x2a2ee0 -[_UIBoundingPath initWithCoordinateSpace:] + 96
8  UIKitCore                      0x613fc4 -[_UIComplexBoundingPath initWithCoordinateSpace:orientation:scale:boundingPathBitmap:] + 112
9  UIKitCore                      0x3f11d0 -[_UIScreenComplexBoundingPathUtilities boundingPathForWindow:] + 2836
10 UIKitCore                      0x675ddc -[UIWindow _boundingPath] + 204
11 UIKitCore                      0x1b1650 -[UIView(UIViewBoundingPathSupportInternal) _effectiveBoundingPathAndBoundingPathView:] + 244
12 UIKitCore                      0x4bab4c -[UIView(UIViewBoundingPathSupport) _rectTuckedAgainstBoundingPathEdge:withSize:cornerRadii:minimumPadding:] + 260
13 UIKitCore                      0x6b74f8 -[_UISheetLayoutInfo _unsafeInsets] + 160
14 UIKitCore                      0x71f18 -[_UISheetLayoutInfo _marginsWhenFloating] + 184
15 UIKitCore                      0x3aca4c -[_UISheetLayoutInfo _isEdgeAttached] + 52
16 UIKitCore                      0x467ffc -[_UISheetLayoutInfo _reversedIndexOfLastUndimmedDetent] + 84
17 UIKitCore                      0x2d713c -[_UISheetLayoutInfo _activeDetentValues] + 348
18 UIKitCore                      0x24b990 -[_UISheetLayoutInfo _offsetForCurrentActiveDetent] + 48
19 UIKitCore                      0x583b5c -[_UISheetLayoutInfo _frameOfPresentedViewInContainerView] + 100
20 UIKitCore                      0x3cad98 -[UISheetPresentationController _containerViewLayoutSubviews] + 652
21 UIKitCore                      0x2231dc -[UITransitionView layoutSubviews] + 92
22 UIKitCore                      0x18c17c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2592
23 QuartzCore                     0x407fc CA::Layer::layout_if_needed(CA::Transaction*) + 532
24 QuartzCore                     0x32c60 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 136
25 QuartzCore                     0x475b4 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 452
26 QuartzCore                     0x504a8 CA::Transaction::commit() + 704
27 QuartzCore                     0x323a0 CA::Transaction::flush_as_runloop_observer(bool) + 88
28 UIKitCore                      0x53e6e0 _UIApplicationFlushCATransaction + 72
29 UIKitCore                      0x7d8d5c _UIUpdateSequenceRun + 84
30 UIKitCore                      0xe5fedc schedulerStepScheduledMainSection + 144
31 UIKitCore                      0xe5f6a4 runloopSourceCallback + 92
32 CoreFoundation                 0xbb414 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
33 CoreFoundation                 0xcc1a0 __CFRunLoopDoSource0 + 208
34 CoreFoundation                 0x5694 __CFRunLoopDoSources0 + 268
35 CoreFoundation                 0xb05c __CFRunLoopRun + 828
36 CoreFoundation                 0x1ebc8 CFRunLoopRunSpecific + 600
37 GraphicsServices               0x1374 GSEventRunModal + 164
38 UIKitCore                      0x514b58 -[UIApplication _run] + 1100
39 UIKitCore                      0x296090 UIApplicationMain + 364
40 App.                           0x77f8 main + 8 (main.m:8)
41 ???                            0x105a99da4 (Missing)
</code>```

my only clue is from "initWithCoordinateSpace:orientation:scale:boundingPathBitmap" If there was a corrupt http image reference could this be causing a crash somewhere?

We are also using Firebase in-app-messaging. Could this be crashing the app on startup?

Body:
we're getting a small number but regular crashes on launch in a production app.
We have Crashlytics and Sentry but i cant see any references to the react code.

Here is a couple of stacktraces

Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x2d318 __abort_with_payload + 8
1  libsystem_kernel.dylib         0x2fc24 abort_with_payload_wrapper_internal + 104
2  libsystem_kernel.dylib         0x2fbbc abort_with_payload_wrapper_internal + 30
3  libobjc.A.dylib                0x2d0b4 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 116
4  libobjc.A.dylib                0x2d040 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30
5  libobjc.A.dylib                0x5acc weak_register_no_lock + 392
6  libobjc.A.dylib                0xa924 objc_storeWeak + 448
7  UIKitCore                      0x2a2ee0 -[_UIBoundingPath initWithCoordinateSpace:] + 96
8  UIKitCore                      0x613fc4 -[_UIComplexBoundingPath initWithCoordinateSpace:orientation:scale:boundingPathBitmap:] + 112
9  UIKitCore                      0x3f11d0 -[_UIScreenComplexBoundingPathUtilities boundingPathForWindow:] + 2836
10 UIKitCore                      0x675ddc -[UIWindow _boundingPath] + 204
11 UIKitCore                      0x1b1650 -[UIView(UIViewBoundingPathSupportInternal) _effectiveBoundingPathAndBoundingPathView:] + 244
12 UIKitCore                      0x4bab4c -[UIView(UIViewBoundingPathSupport) _rectTuckedAgainstBoundingPathEdge:withSize:cornerRadii:minimumPadding:] + 260
13 UIKitCore                      0x6b74f8 -[_UISheetLayoutInfo _unsafeInsets] + 160
14 UIKitCore                      0x71f18 -[_UISheetLayoutInfo _marginsWhenFloating] + 184
15 UIKitCore                      0x3aca4c -[_UISheetLayoutInfo _isEdgeAttached] + 52
16 UIKitCore                      0x467ffc -[_UISheetLayoutInfo _reversedIndexOfLastUndimmedDetent] + 84
17 UIKitCore                      0x2d713c -[_UISheetLayoutInfo _activeDetentValues] + 348
18 UIKitCore                      0x24b990 -[_UISheetLayoutInfo _offsetForCurrentActiveDetent] + 48
19 UIKitCore                      0x583b5c -[_UISheetLayoutInfo _frameOfPresentedViewInContainerView] + 100
20 UIKitCore                      0x3cad98 -[UISheetPresentationController _containerViewLayoutSubviews] + 652
21 UIKitCore                      0x2231dc -[UITransitionView layoutSubviews] + 92
22 UIKitCore                      0x18c17c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2592
23 QuartzCore                     0x407fc CA::Layer::layout_if_needed(CA::Transaction*) + 532
24 QuartzCore                     0x32c60 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 136
25 QuartzCore                     0x475b4 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 452
26 QuartzCore                     0x504a8 CA::Transaction::commit() + 704
27 QuartzCore                     0x323a0 CA::Transaction::flush_as_runloop_observer(bool) + 88
28 UIKitCore                      0x53e6e0 _UIApplicationFlushCATransaction + 72
29 UIKitCore                      0x7d8d5c _UIUpdateSequenceRun + 84
30 UIKitCore                      0xe5fedc schedulerStepScheduledMainSection + 144
31 UIKitCore                      0xe5f6a4 runloopSourceCallback + 92
32 CoreFoundation                 0xbb414 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
33 CoreFoundation                 0xcc1a0 __CFRunLoopDoSource0 + 208
34 CoreFoundation                 0x5694 __CFRunLoopDoSources0 + 268
35 CoreFoundation                 0xb05c __CFRunLoopRun + 828
36 CoreFoundation                 0x1ebc8 CFRunLoopRunSpecific + 600
37 GraphicsServices               0x1374 GSEventRunModal + 164
38 UIKitCore                      0x514b58 -[UIApplication _run] + 1100
39 UIKitCore                      0x296090 UIApplicationMain + 364
40 App.                           0x72a4 main + 8 (main.m:8)

Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x2d318 __abort_with_payload + 8
1  libsystem_kernel.dylib         0x2fc24 abort_with_payload_wrapper_internal + 104
2  libsystem_kernel.dylib         0x2fbbc abort_with_payload_wrapper_internal + 30
3  libobjc.A.dylib                0x2d0b4 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 116
4  libobjc.A.dylib                0x2d040 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30
5  libobjc.A.dylib                0x5acc weak_register_no_lock + 392
6  libobjc.A.dylib                0xa924 objc_storeWeak + 448
7  UIKitCore                      0x2a2ee0 -[_UIBoundingPath initWithCoordinateSpace:] + 96
8  UIKitCore                      0x613fc4 -[_UIComplexBoundingPath initWithCoordinateSpace:orientation:scale:boundingPathBitmap:] + 112
9  UIKitCore                      0x3f11d0 -[_UIScreenComplexBoundingPathUtilities boundingPathForWindow:] + 2836
10 UIKitCore                      0x675ddc -[UIWindow _boundingPath] + 204
11 UIKitCore                      0x1b1650 -[UIView(UIViewBoundingPathSupportInternal) _effectiveBoundingPathAndBoundingPathView:] + 244
12 UIKitCore                      0x4bab4c -[UIView(UIViewBoundingPathSupport) _rectTuckedAgainstBoundingPathEdge:withSize:cornerRadii:minimumPadding:] + 260
13 UIKitCore                      0x6b74f8 -[_UISheetLayoutInfo _unsafeInsets] + 160
14 UIKitCore                      0x71f18 -[_UISheetLayoutInfo _marginsWhenFloating] + 184
15 UIKitCore                      0x3aca4c -[_UISheetLayoutInfo _isEdgeAttached] + 52
16 UIKitCore                      0x467ffc -[_UISheetLayoutInfo _reversedIndexOfLastUndimmedDetent] + 84
17 UIKitCore                      0x2d713c -[_UISheetLayoutInfo _activeDetentValues] + 348
18 UIKitCore                      0x24b990 -[_UISheetLayoutInfo _offsetForCurrentActiveDetent] + 48
19 UIKitCore                      0x583b5c -[_UISheetLayoutInfo _frameOfPresentedViewInContainerView] + 100
20 UIKitCore                      0x3cad98 -[UISheetPresentationController _containerViewLayoutSubviews] + 652
21 UIKitCore                      0x2231dc -[UITransitionView layoutSubviews] + 92
22 UIKitCore                      0x18c17c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2592
23 QuartzCore                     0x407fc CA::Layer::layout_if_needed(CA::Transaction*) + 532
24 QuartzCore                     0x32c60 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 136
25 QuartzCore                     0x475b4 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 452
26 QuartzCore                     0x504a8 CA::Transaction::commit() + 704
27 QuartzCore                     0x323a0 CA::Transaction::flush_as_runloop_observer(bool) + 88
28 UIKitCore                      0x53e6e0 _UIApplicationFlushCATransaction + 72
29 UIKitCore                      0x7d8d5c _UIUpdateSequenceRun + 84
30 UIKitCore                      0xe5fedc schedulerStepScheduledMainSection + 144
31 UIKitCore                      0xe5f6a4 runloopSourceCallback + 92
32 CoreFoundation                 0xbb414 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
33 CoreFoundation                 0xcc1a0 __CFRunLoopDoSource0 + 208
34 CoreFoundation                 0x5694 __CFRunLoopDoSources0 + 268
35 CoreFoundation                 0xb05c __CFRunLoopRun + 828
36 CoreFoundation                 0x1ebc8 CFRunLoopRunSpecific + 600
37 GraphicsServices               0x1374 GSEventRunModal + 164
38 UIKitCore                      0x514b58 -[UIApplication _run] + 1100
39 UIKitCore                      0x296090 UIApplicationMain + 364
40 App.                           0x77f8 main + 8 (main.m:8)
41 ???                            0x105a99da4 (Missing)

my only clue is from "initWithCoordinateSpace:orientation:scale:boundingPathBitmap" If there was a corrupt http image reference could this be causing a crash somewhere?

We are also using Firebase in-app-messaging. Could this be crashing the app on startup?


问:
How to use CATIA CatScript macro to capture a specific view of a part?
I am tasked to find a way to help our design team to screen capture a specific position of a part. However, I don't know how to customize my own position.

I tried looking at some codes on the internet and I found this:

```<code>Sub CATMain()

Dim productDocument1 As Document
Set productDocument1 = CATIA.ActiveDocument
Dim cameras1 As Cameras
Set cameras1 = productDocument1.Cameras
Dim camera3D1 As Camera
Set camera3D1 = cameras1.Item(1)
Dim viewpoint3D1 As Viewpoint3D
Set viewpoint3D1 = camera3D1.Viewpoint3D
Dim specsAndGeomWindow1 As Window
Set specsAndGeomWindow1 = CATIA.ActiveWindow
Dim viewer3D1 As Viewer
Set viewer3D1 = specsAndGeomWindow1.ActiveViewer
viewer3D1.Viewpoint3D = viewpoint3D1
Set viewpoint3D1 = camera3D1.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D1

Dim filelocation As String
filelocation = "c:\Temporary\"
Dim extension As String
extension = ".jpg"
Dim Name as string
Name= filelocation & "right" & extension
viewer3D1.Viewpoint3D =camera3D1.Viewpoint3D
CATIA.ActiveDocument.Selection.Clear()
viewer3D1.Capturetofile 5,Name

Dim camera3D2 As Camera
Set camera3D2 = cameras1.Item(2)
Dim viewpoint3D2 As Viewpoint3D
Set viewpoint3D2 = camera3D2.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D2
Set viewpoint3D2 = camera3D2.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D2

Name = filelocation & "left" & extension
viewer3D1.Viewpoint3D =camera3D2.Viewpoint3D
CATIA.ActiveDocument.Selection.Clear()
viewer3D1.Capturetofile 5,Name
End Sub
</code>```

Is there a way to tweak this code in terms of my own position that I want?

Thank you!

Body:
I am tasked to find a way to help our design team to screen capture a specific position of a part. However, I don't know how to customize my own position.

I tried looking at some codes on the internet and I found this:

Sub CATMain()

Dim productDocument1 As Document
Set productDocument1 = CATIA.ActiveDocument
Dim cameras1 As Cameras
Set cameras1 = productDocument1.Cameras
Dim camera3D1 As Camera
Set camera3D1 = cameras1.Item(1)
Dim viewpoint3D1 As Viewpoint3D
Set viewpoint3D1 = camera3D1.Viewpoint3D
Dim specsAndGeomWindow1 As Window
Set specsAndGeomWindow1 = CATIA.ActiveWindow
Dim viewer3D1 As Viewer
Set viewer3D1 = specsAndGeomWindow1.ActiveViewer
viewer3D1.Viewpoint3D = viewpoint3D1
Set viewpoint3D1 = camera3D1.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D1

Dim filelocation As String
filelocation = "c:\Temporary\"
Dim extension As String
extension = ".jpg"
Dim Name as string
Name= filelocation & "right" & extension
viewer3D1.Viewpoint3D =camera3D1.Viewpoint3D
CATIA.ActiveDocument.Selection.Clear()
viewer3D1.Capturetofile 5,Name

Dim camera3D2 As Camera
Set camera3D2 = cameras1.Item(2)
Dim viewpoint3D2 As Viewpoint3D
Set viewpoint3D2 = camera3D2.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D2
Set viewpoint3D2 = camera3D2.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D2

Name = filelocation & "left" & extension
viewer3D1.Viewpoint3D =camera3D2.Viewpoint3D
CATIA.ActiveDocument.Selection.Clear()
viewer3D1.Capturetofile 5,Name
End Sub

Is there a way to tweak this code in terms of my own position that I want?

Thank you!


问:
Type 'undefined' is not assignable to type 'WritableDraft<T> | null'
I'm getting the error: Type 'undefined' is not assignable to type 'WritableDraft<LoginError> | null'. in my extraReducer as follows:

```<code>export const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
        .addCase(login.fulfilled, (state, action) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = true;
        })
        .addCase(login.rejected, (state, action) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = false;
            state.auth.error = action.payload; //this is throwing the error
        })
    }
});

</code>```

I'm not sure if this is caused by the typings in my thunk but here is my code for it:

```<code>export const login = createAsyncThunk<
    LoginResponse,
    LoginData,
    {
        rejectValue: LoginError
    }>(
    "auth/login",
    async (loginData: LoginData, thunkAPI: any) => {
        try {
            const { email, password } = loginData;
            const { data: resData } = await serveraxios.post<LoginResponse>(
                "/login",
                {
                    email: email,
                    password: password,
                },
                {
                    withCredentials: true
                }
            );
            return resData;
        }
        catch (error: any) {
            return thunkAPI.rejectWithValue({
                status: error.response.data.status,
                message: error.response.data.message,
            });
        }
    }
)
</code>```
```<code>export interface LoginData {
    email: string;
    password: string;
}

type LoginResponse = {
    data: UserLogin
}

interface UserLogin {
    messsage: string;
    user: UserInterface;
}

type LoginError = {
    status: number;
    message: string;
}
</code>```

How can I go about resolving the error?

Body:
I'm getting the error: Type 'undefined' is not assignable to type 'WritableDraft<LoginError> | null'. in my extraReducer as follows:

export const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
        .addCase(login.fulfilled, (state, action) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = true;
        })
        .addCase(login.rejected, (state, action) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = false;
            state.auth.error = action.payload; //this is throwing the error
        })
    }
});

I'm not sure if this is caused by the typings in my thunk but here is my code for it:

export const login = createAsyncThunk<
    LoginResponse,
    LoginData,
    {
        rejectValue: LoginError
    }>(
    "auth/login",
    async (loginData: LoginData, thunkAPI: any) => {
        try {
            const { email, password } = loginData;
            const { data: resData } = await serveraxios.post<LoginResponse>(
                "/login",
                {
                    email: email,
                    password: password,
                },
                {
                    withCredentials: true
                }
            );
            return resData;
        }
        catch (error: any) {
            return thunkAPI.rejectWithValue({
                status: error.response.data.status,
                message: error.response.data.message,
            });
        }
    }
)

export interface LoginData {
    email: string;
    password: string;
}

type LoginResponse = {
    data: UserLogin
}

interface UserLogin {
    messsage: string;
    user: UserInterface;
}

type LoginError = {
    status: number;
    message: string;
}

How can I go about resolving the error?


问:
What are the performance implications of casting between simple structs with the same memory?
I implemented From Point3 for Vertex a simple struct with one field called position that is [f32; 3]. Point3 is marked as #[repr(C)] which I think means that the 3 f32 will be right next to each other in memory, with no padding for alignment. I also think that [f32, 3] will also have no padding for alignment. Is this true? If it is true, does that mean there is a way to "reinterpret" the memory of Point3 as Vertex? If it is not true, what is are the performance implications? I'm sorry if this is not clear, I am asking this question to understand a bit more about the low level parts of Rust.

```<code>impl From<cgmath::Point3<f32>> for Vertex {
    fn from(vertex: cgmath::Point3<f32>) -> Self {
        Vertex {
            position: [vertex.x, vertex.y, vertex.z],
        }
    }
}
</code>```

Body:
I implemented From Point3 for Vertex a simple struct with one field called position that is [f32; 3]. Point3 is marked as #[repr(C)] which I think means that the 3 f32 will be right next to each other in memory, with no padding for alignment. I also think that [f32, 3] will also have no padding for alignment. Is this true? If it is true, does that mean there is a way to "reinterpret" the memory of Point3 as Vertex? If it is not true, what is are the performance implications? I'm sorry if this is not clear, I am asking this question to understand a bit more about the low level parts of Rust.

impl From<cgmath::Point3<f32>> for Vertex {
    fn from(vertex: cgmath::Point3<f32>) -> Self {
        Vertex {
            position: [vertex.x, vertex.y, vertex.z],
        }
    }
}


问:
error: Result from function call is not a proper array of floats. While using scipy.optimize.curve_fit
I am trying to fit a function

```<code>def fun(x,a,b):
    return np.array((nsum(lambda i: (2*i-len(x)-1)*(1-(a*x+b))*x,
                         [0, len(x)]))/(nsum(lambda i: (1-(a*x+b))*x,[0, len(x)])*len(x)))
</code>```

And this is the code for the fit

```<code>n=len(sim["avg"])
y= np.array([0.33]*n, dtype=float).reshape(n,)
x=np.array(sim["avg"], dtype=float).reshape(n,)
a,b =curve_fit(fun,x, y, method='trf')
</code>```

n is the length of the data whil sim["avg"] is our x.
y in my case is constant, equals 0.33

This is the imports:

```<code>import pandas as pd
import numpy as np
from sympy import *
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from mpmath import nsum, exp, inf
</code>```

This is sample data:

```<code>0        1250.0
1        1250.0
2        1250.0
3        1250.0
4        1250.0
         ...
976    150000.0
977    150000.0
978    150000.0
979    150000.0
980    150000.0
</code>```

This is the error message

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-92-c1d0f29febb8> in <module>
      3 y= np.array([0.33]*n, dtype=float).reshape(n,)
      4 x=np.array(sim["avg"], dtype=float).reshape(n,)
----> 5 a,b =curve_fit(fun,x, y)

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    782         # Remove full_output from kwargs, otherwise we're passing it in twice.
    783         return_full = kwargs.pop('full_output', False)
--> 784         res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
    785         popt, pcov, infodict, errmsg, ier = res
    786         ysize = len(infodict['fvec'])

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    420         if maxfev == 0:
    421             maxfev = 200*(n + 1)
--> 422         retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
    423                                  gtol, maxfev, epsfcn, factor, diag)
    424     else:

error: Result from function call is not a proper array of floats.
</code>```

I was hoping that someone could either solve this error or could help with fitting this function which involves two summation (not sure if will work with Scipy).

Body:
I am trying to fit a function

def fun(x,a,b):
    return np.array((nsum(lambda i: (2*i-len(x)-1)*(1-(a*x+b))*x,
                         [0, len(x)]))/(nsum(lambda i: (1-(a*x+b))*x,[0, len(x)])*len(x)))

And this is the code for the fit

n=len(sim["avg"])
y= np.array([0.33]*n, dtype=float).reshape(n,)
x=np.array(sim["avg"], dtype=float).reshape(n,)
a,b =curve_fit(fun,x, y, method='trf')

n is the length of the data whil sim["avg"] is our x.
y in my case is constant, equals 0.33

This is the imports:

import pandas as pd
import numpy as np
from sympy import *
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from mpmath import nsum, exp, inf

This is sample data:

0        1250.0
1        1250.0
2        1250.0
3        1250.0
4        1250.0
         ...
976    150000.0
977    150000.0
978    150000.0
979    150000.0
980    150000.0

This is the error message

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-92-c1d0f29febb8> in <module>
      3 y= np.array([0.33]*n, dtype=float).reshape(n,)
      4 x=np.array(sim["avg"], dtype=float).reshape(n,)
----> 5 a,b =curve_fit(fun,x, y)

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    782         # Remove full_output from kwargs, otherwise we're passing it in twice.
    783         return_full = kwargs.pop('full_output', False)
--> 784         res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
    785         popt, pcov, infodict, errmsg, ier = res
    786         ysize = len(infodict['fvec'])

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    420         if maxfev == 0:
    421             maxfev = 200*(n + 1)
--> 422         retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
    423                                  gtol, maxfev, epsfcn, factor, diag)
    424     else:

error: Result from function call is not a proper array of floats.

I was hoping that someone could either solve this error or could help with fitting this function which involves two summation (not sure if will work with Scipy).


问:
Spring https redirect solution wants to exclude redirecting only certain URLs

public class SSLConfig {

    @Value("${server.port.http}")
    private int httpPort;

    @Value("${server.port}")
    private int httpsPort;

    @Bean
    public ServletWebServerFactory serverFactory(){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };

        tomcat.addAdditionalTomcatConnectors(createSslConnector());
        return tomcat;
    }

    private Connector createSslConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        return connector;
    }

}
```
<p>The http to https redirect solution you are currently using. I'd like to exclude certain url, for example, /member/* patterns that go in this way. Is there a way?</p>
<p>A new context was added to exclude the URL, but it worked locally and did not work on the server.
The server will continue to be redirected to https.</p>
<pre class="lang-java prettyprint-override"><code>    SecurityConstraint ignoreConstraint = new SecurityConstraint();
    SecurityCollection ignoreCollection = new SecurityCollection();
    ignoreCollection.addPattern("/admin/*");
    ignoreConstraint.addCollection(ignoreCollection);
    context.addConstraint(ignoreConstraint);
</code>```

Body:
public class SSLConfig {

    @Value("${server.port.http}")
    private int httpPort;

    @Value("${server.port}")
    private int httpsPort;

    @Bean
    public ServletWebServerFactory serverFactory(){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };

        tomcat.addAdditionalTomcatConnectors(createSslConnector());
        return tomcat;
    }

    private Connector createSslConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        return connector;
    }

}

The http to https redirect solution you are currently using. I'd like to exclude certain url, for example, /member/* patterns that go in this way. Is there a way?

A new context was added to exclude the URL, but it worked locally and did not work on the server.
The server will continue to be redirected to https.

    SecurityConstraint ignoreConstraint = new SecurityConstraint();
    SecurityCollection ignoreCollection = new SecurityCollection();
    ignoreCollection.addPattern("/admin/*");
    ignoreConstraint.addCollection(ignoreCollection);
    context.addConstraint(ignoreConstraint);


问:
Load Balancing and TCP Connections
Apologies if this is a very naive question, but in the case of a TCP connection from a client to a backend server that is behind a load balancer, how does the load balancer know which server to serve the data to after the initial connection?

Thanks

Title: Load Balancing and TCP Connections


问:
ActiveRecord::StatementInvalid in Summaries#index
PG::UndefinedColumn: ERROR:  column summaries.user does not exist
LINE 1: SELECT "summaries".* FROM "summaries" WHERE "summaries"."use...

I'm trying to make a view restriction, where only the admin can see all the records in an app


问:
Excel Target Entire Row using Text Content found in Cell
is there a way to target and show an entire row using text content found in a cell?

the screenshot below shows a sample questionnaire that users will have to answer, a ticked checkbox means 'yes' and a non-ticked checkbox means 'no'.

after answering, a requirement spreadsheet will generate the requirements needed by hiding "not needed requirements". below is a screenshot of the generated requirements spreadsheet.

below is a screenshot of the requirement matrix.

since the requirements in the requirement matrix can be altered (add/remove requirements, which will affect the row number.) the change in row number will affect the requirements being shown, the generated requirements spreadsheet is "hard-coded", meaning, my macros logic is "if question 1 checkbox is ticked, show row 2", so on and so forth.

hence, i am thinking of whether if it is possible to reference an entire row using text content found in a cell in the row itself. i apologise if i am unclear here, i will try to explain again if it is confusing. TIA

Edit: Markdown Tables generator, for example, i have the following table with the following response. question 1 is connected to requirement 1, question 2 is connected to requirement 2, question 3 is connected to requirement 3.

Question Number
Response (Yes/No)

Question 1
Yes

Question 2
No

Question 3
Yes

this is yield me the following table due to the above response.

Requirement Number
Description

General Requirement
Section Header

Requirement 1
A

Security Requirement
Section Header

Requirement 3
C

as you can see, requirement 2 is hidden as the response for question 2 is 'No'. now, the requirement spreadsheet is constantly being updated, meaning, the row number of the requirement can be changed. for example, currently 'Requirement 3' is row number 7 (keep in mind that the Section Header and Requirement 2 is hidden), however, if a new update comes and a new row is being inserted into 'General Requirement', the row number for 'Requirement 3' will be changed, therefore hiding and unhiding a wrong row.

p.s. i am currently using row number to reference the entire row, hence, i am trying to figure out a way to reference an entire row using the description instead, since each description is unique.


问:
Does npm i for Bootstrap install for all of my git branches?
I'm upgrading to Bootstrap 5 from 4, but I wanted to test it out first on a separate local branch before I do that. If I run the command "npm i bootstrap@5.3.0-alpha1", will that install it on all of my branches, or just the branch that I'm checking out?

I know that I can also just copy over the min.css and min.js, but I'm checking to see if I can just run that command instead.

Is there is a better way to test out Bootstrap 5?