问:
RSI Crossover Back-Testing Issue
As I was running my RSI crossover back-testing script on Jupyter, I encountered an unexpected error message. Upon closer examination, I discovered that the issue stemmed from a KeyError with the "rsi21" column. This came as a surprise to me, as I had previously defined the "rsi21" column in my code and it had been functioning without issue up until this point. I have tried to troubleshoot the problem by carefully reviewing my code for any typos or syntax errors, but to no avail. It is frustrating to encounter this issue and I am eager to find a solution. Can anyone provide any insight or assistance in resolving this KeyError with the "rsi21" column?

```<code>KeyError                                  Traceback (most recent call last)
File ~\.julia\conda\3\lib\site-packages\pandas\core\indexes\base.py:3803, in Index.get_loc(self, key, method, tolerance)
   3802 try:
-> 3803     return self._engine.get_loc(casted_key)
   3804 except KeyError as err:

File ~\.julia\conda\3\lib\site-packages\pandas\_libs\index.pyx:138, in pandas._libs.index.IndexEngine.get_loc()

File ~\.julia\conda\3\lib\site-packages\pandas\_libs\index.pyx:165, in pandas._libs.index.IndexEngine.get_loc()

File pandas\_libs\hashtable_class_helper.pxi:5745, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas\_libs\hashtable_class_helper.pxi:5753, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'rsi21'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In [31], line 28
     26 df_temp = df_5min[df_5min.index.date == index.date()]
     27 # if the RSI21 is above the RSI55 and RSI100 and the RSI is above 30 in the 5 minute interval data, place a buy order
---> 28 if (row['rsi21'] > row['rsi55']) and (row['rsi21'] > row['rsi100']) and (df_temp['rsi21'].values[-1] > 30):
     29     # place buy order
     30     num_trades += 1
     31     # calculate profit/loss based on the current price and the buy price

File ~\.julia\conda\3\lib\site-packages\pandas\core\frame.py:3805, in DataFrame.__getitem__(self, key)
   3803 if self.columns.nlevels > 1:
   3804     return self._getitem_multilevel(key)
-> 3805 indexer = self.columns.get_loc(key)
   3806 if is_integer(indexer):
   3807     indexer = [indexer]

File ~\.julia\conda\3\lib\site-packages\pandas\core\indexes\base.py:3805, in Index.get_loc(self, key, method, tolerance)
   3803     return self._engine.get_loc(casted_key)
   3804 except KeyError as err:
-> 3805     raise KeyError(key) from err
   3806 except TypeError:
   3807     # If we have a listlike key, _check_indexing_error will raise
   3808     #  InvalidIndexError. Otherwise we fall through and re-raise
   3809     #  the TypeError.
   3810     self._check_indexing_error(key)

KeyError: 'rsi21'
</code>```

In an effort to resolve the KeyError with the "rsi21" column, I tried several different approaches. First, I checked my code for any typos or syntax errors that could be causing the issue. I also tried re-running the script to see if the error was a temporary glitch. However, neither of these approaches yielded any results. I was expecting the script to run smoothly and for the "rsi21" column to be recognized without issue. However, instead, I received the KeyError message and the script halted. This discrepancy between my expectations and the actual result has been frustrating and I am seeking a solution to resolve the issue.

```<code>import yfinance as yf

start_date = "2020-01-01"
end_date = "2022-12-31"

stock = yf.Ticker("SPY")
df = stock.history(start=start_date, end=end_date)

def moving_average(df, window):
    return df['Close'].rolling(window=window).mean()
df_5min = stock.history(interval='5m')

def rsi(df, window):
    # create a new column for the difference between the current and previous close
    df['diff'] = df['Close'].diff()
    # create new columns for the gain and loss
    df['gain'] = df['diff'].apply(lambda x: x if x > 0 else 0)
    df['loss'] = df['diff'].apply(lambda x: abs(x) if x < 0 else 0)
    # calculate the average gain and loss over the specified window
    avg_gain = df['gain'].rolling(window=window).mean()
    avg_loss = df['loss'].rolling(window=window).mean()
    # calculate the relative strength
    df['rs'] = avg_gain / avg_loss
    # return the relative strength index
    return 100 - (100 / (1 + df['rs']))

df['rsi21'] = rsi(df, 21)
df['rsi55'] = rsi(df, 55)
df['rsi100'] = rsi(df, 100)

num_trades = 0
total_profit = 0

for index, row in df.iterrows():
    # get the 5-minute interval data for the current date
    df_temp = df_5min[df_5min.index.date == index.date()]
    # if the RSI21 is above the RSI55 and RSI100 and the RSI is above 30 in the 5 minute interval data, place a buy order
    if (row['rsi21'] > row['rsi55']) and (row['rsi21'] > row['rsi100']) and (df_temp['rsi21'].values[-1] > 30):
        # place buy order
        num_trades += 1
        # calculate profit/loss based on the current price and the buy price
        profit = row['Close'] - df_temp['Open'].values[-1]
        total_profit += profit
    # if the RSI21 is below the RSI55 and RSI100 and the RSI is below 70 in the 5 minute interval data, place a sell order
    elif (row['rsi21'] < row['rsi55']) and (row['rsi21'] < row['rsi100']) and (df_temp['rsi21'].values[-1] < 70):
        # place sell order
        num_trades += 1
        # calculate profit/loss based on the current price and the sell price
        profit = df_temp['Open'].values[-1] - row['Close']
        total_profit += profit

#print the total number of trades and total profit/loss
print("Total number of trades:", num_trades)
print("Total profit/loss:", total_profit)
</code>```

Title: RSI Crossover Back-Testing Issue

Body:
As I was running my RSI crossover back-testing script on Jupyter, I encountered an unexpected error message. Upon closer examination, I discovered that the issue stemmed from a KeyError with the "rsi21" column. This came as a surprise to me, as I had previously defined the "rsi21" column in my code and it had been functioning without issue up until this point. I have tried to troubleshoot the problem by carefully reviewing my code for any typos or syntax errors, but to no avail. It is frustrating to encounter this issue and I am eager to find a solution. Can anyone provide any insight or assistance in resolving this KeyError with the "rsi21" column?

KeyError                                  Traceback (most recent call last)
File ~\.julia\conda\3\lib\site-packages\pandas\core\indexes\base.py:3803, in Index.get_loc(self, key, method, tolerance)
   3802 try:
-> 3803     return self._engine.get_loc(casted_key)
   3804 except KeyError as err:

File ~\.julia\conda\3\lib\site-packages\pandas\_libs\index.pyx:138, in pandas._libs.index.IndexEngine.get_loc()

File ~\.julia\conda\3\lib\site-packages\pandas\_libs\index.pyx:165, in pandas._libs.index.IndexEngine.get_loc()

File pandas\_libs\hashtable_class_helper.pxi:5745, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas\_libs\hashtable_class_helper.pxi:5753, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'rsi21'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In [31], line 28
     26 df_temp = df_5min[df_5min.index.date == index.date()]
     27 # if the RSI21 is above the RSI55 and RSI100 and the RSI is above 30 in the 5 minute interval data, place a buy order
---> 28 if (row['rsi21'] > row['rsi55']) and (row['rsi21'] > row['rsi100']) and (df_temp['rsi21'].values[-1] > 30):
     29     # place buy order
     30     num_trades += 1
     31     # calculate profit/loss based on the current price and the buy price

File ~\.julia\conda\3\lib\site-packages\pandas\core\frame.py:3805, in DataFrame.__getitem__(self, key)
   3803 if self.columns.nlevels > 1:
   3804     return self._getitem_multilevel(key)
-> 3805 indexer = self.columns.get_loc(key)
   3806 if is_integer(indexer):
   3807     indexer = [indexer]

File ~\.julia\conda\3\lib\site-packages\pandas\core\indexes\base.py:3805, in Index.get_loc(self, key, method, tolerance)
   3803     return self._engine.get_loc(casted_key)
   3804 except KeyError as err:
-> 3805     raise KeyError(key) from err
   3806 except TypeError:
   3807     # If we have a listlike key, _check_indexing_error will raise
   3808     #  InvalidIndexError. Otherwise we fall through and re-raise
   3809     #  the TypeError.
   3810     self._check_indexing_error(key)

KeyError: 'rsi21'

In an effort to resolve the KeyError with the "rsi21" column, I tried several different approaches. First, I checked my code for any typos or syntax errors that could be causing the issue. I also tried re-running the script to see if the error was a temporary glitch. However, neither of these approaches yielded any results. I was expecting the script to run smoothly and for the "rsi21" column to be recognized without issue. However, instead, I received the KeyError message and the script halted. This discrepancy between my expectations and the actual result has been frustrating and I am seeking a solution to resolve the issue.

import yfinance as yf

start_date = "2020-01-01"
end_date = "2022-12-31"

stock = yf.Ticker("SPY")
df = stock.history(start=start_date, end=end_date)

def moving_average(df, window):
    return df['Close'].rolling(window=window).mean()
df_5min = stock.history(interval='5m')

def rsi(df, window):
    # create a new column for the difference between the current and previous close
    df['diff'] = df['Close'].diff()
    # create new columns for the gain and loss
    df['gain'] = df['diff'].apply(lambda x: x if x > 0 else 0)
    df['loss'] = df['diff'].apply(lambda x: abs(x) if x < 0 else 0)
    # calculate the average gain and loss over the specified window
    avg_gain = df['gain'].rolling(window=window).mean()
    avg_loss = df['loss'].rolling(window=window).mean()
    # calculate the relative strength
    df['rs'] = avg_gain / avg_loss
    # return the relative strength index
    return 100 - (100 / (1 + df['rs']))

df['rsi21'] = rsi(df, 21)
df['rsi55'] = rsi(df, 55)
df['rsi100'] = rsi(df, 100)

num_trades = 0
total_profit = 0

for index, row in df.iterrows():
    # get the 5-minute interval data for the current date
    df_temp = df_5min[df_5min.index.date == index.date()]
    # if the RSI21 is above the RSI55 and RSI100 and the RSI is above 30 in the 5 minute interval data, place a buy order
    if (row['rsi21'] > row['rsi55']) and (row['rsi21'] > row['rsi100']) and (df_temp['rsi21'].values[-1] > 30):
        # place buy order
        num_trades += 1
        # calculate profit/loss based on the current price and the buy price
        profit = row['Close'] - df_temp['Open'].values[-1]
        total_profit += profit
    # if the RSI21 is below the RSI55 and RSI100 and the RSI is below 70 in the 5 minute interval data, place a sell order
    elif (row['rsi21'] < row['rsi55']) and (row['rsi21'] < row['rsi100']) and (df_temp['rsi21'].values[-1] < 70):
        # place sell order
        num_trades += 1
        # calculate profit/loss based on the current price and the sell price
        profit = df_temp['Open'].values[-1] - row['Close']
        total_profit += profit

#print the total number of trades and total profit/loss
print("Total number of trades:", num_trades)
print("Total profit/loss:", total_profit)


来源: stackexchange

问:
Getting net/http: request canceled while waiting for connection error when deploying a model trained with Azure Auto ML via Azure Studio
I am training a simple text classification model in Azure Auto ML. Got a decent model and now trying to deploy it. Deployment goes ok initially and I get:

Provisioning state: Succeeded

But then after a while, Provisioning state is returning an error: and no traffic as allocated to the model.
ResourceNotReady: User container has crashed or terminated: Liveness probe failed: HTTP probe failed with statuscode: 502.

When I logs at deployment logs, I see following on top of bunch successful env creation logs:

```<code>Container events:
Kind: Pod, Name: LivenessProbeFailed, Type: Warning, Time: 2023-01-03T13:22:14.905684Z, Message: Liveness probe failed: HTTP probe failed with statuscode: 502
Kind: Pod, Name: Killing, Type: Normal, Time: 2023-01-03T13:22:14.912478Z, Message: Stopping container inference-server
Kind: Pod, Name: ReadinessProbeFailed, Type: Warning, Time: 2023-01-03T13:22:18.653423Z, Message: Readiness probe failed: Get http://10.66.0.2:5001/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
</code>```

Looks to me like contained was deployed but is not reachable?

I tried various combinations of models and virtual machines, but it ends up in this error every time.

ContentLicense: CC BY-SA 4.0

Body:
I am training a simple text classification model in Azure Auto ML. Got a decent model and now trying to deploy it. Deployment goes ok initially and I get:

Provisioning state: Succeeded

But then after a while, Provisioning state is returning an error: and no traffic as allocated to the model.
ResourceNotReady: User container has crashed or terminated: Liveness probe failed: HTTP probe failed with statuscode: 502.

When I logs at deployment logs, I see following on top of bunch successful env creation logs:

Container events:
Kind: Pod, Name: LivenessProbeFailed, Type: Warning, Time: 2023-01-03T13:22:14.905684Z, Message: Liveness probe failed: HTTP probe failed with statuscode: 502
Kind: Pod, Name: Killing, Type: Normal, Time: 2023-01-03T13:22:14.912478Z, Message: Stopping container inference-server
Kind: Pod, Name: ReadinessProbeFailed, Type: Warning, Time: 2023-01-03T13:22:18.653423Z, Message: Readiness probe failed: Get http://10.66.0.2:5001/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

Looks to me like contained was deployed but is not reachable?

I tried various combinations of models and virtual machines, but it ends up in this error every time.


问:
TestNG Parallel Tests always omits 1 test for each method provided by DataProviderClass
My TestClass:

```<code>@Test(dataProvider = "data-provider", dataProviderClass = DataProviderClass.class)
public void testHappyCase(String a, String b, String c, String d, String e) {
TEST CODE HERE
}
</code>```

My DataProviderClass:

```<code>@DataProvider(name = "data-provider", parallel = true)
public static Object[][] dataProviderMethod(final Method m) {
    switch (m.getName()) {
        case "testHappyCase":
            return new Object[][] {
                    {"12345678", "000047", "33", "150", "27.50"},
                    {"12345678", "000047", "33", "500", "33.75"}};
            }
            return null;
       }
</code>```

My TestNG.xml File:

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestSuite" verbose="2" thread-count="10" data-provider-thread-count="20">
    <parameter name="domain" value="test"/>
    <parameter name="region" value="us-east-1"/>
    <parameter name="endpoint" value="https://localhost:8443"/>
    <test name="SomeTest" annotations="JDK" parallel="methods" verbose="2" preserve-order="true">
        <packages>
            <package name="com.service.*"/>
        </packages>
    </test>
</suite>

</code>```

When I run this test, it shows only 1 test being run (picks one of the two from DataProviderClass at random). Why is this happening?

I have attempted to modify the testNG.xml file along with adding multiple fields to the test method and class with no resolution. When I increase the number of tests to 10, only 9 out of 10 tests run. I am very confused and need help! Thank you!

Body:
My TestClass:

@Test(dataProvider = "data-provider", dataProviderClass = DataProviderClass.class)
public void testHappyCase(String a, String b, String c, String d, String e) {
TEST CODE HERE
}

My DataProviderClass:

@DataProvider(name = "data-provider", parallel = true)
public static Object[][] dataProviderMethod(final Method m) {
    switch (m.getName()) {
        case "testHappyCase":
            return new Object[][] {
                    {"12345678", "000047", "33", "150", "27.50"},
                    {"12345678", "000047", "33", "500", "33.75"}};
            }
            return null;
       }

My TestNG.xml File:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestSuite" verbose="2" thread-count="10" data-provider-thread-count="20">
    <parameter name="domain" value="test"/>
    <parameter name="region" value="us-east-1"/>
    <parameter name="endpoint" value="https://localhost:8443"/>
    <test name="SomeTest" annotations="JDK" parallel="methods" verbose="2" preserve-order="true">
        <packages>
            <package name="com.service.*"/>
        </packages>
    </test>
</suite>

When I run this test, it shows only 1 test being run (picks one of the two from DataProviderClass at random). Why is this happening?

I have attempted to modify the testNG.xml file along with adding multiple fields to the test method and class with no resolution. When I increase the number of tests to 10, only 9 out of 10 tests run. I am very confused and need help! Thank you!


问:
Connection to localhost proxy breaking
We are encountering errors when trying to use a web application, iframe, and proxy port in colab in Chrome.

First, we pick an unused port, then set up a server on that port.
Then, we create an iframe that connects to this proxy url:
server_url = eval_js(f"google.colab.kernel.proxyPort({port})")

The iframe itself is loading, but we see tons of network errors and the server is not properly connecting in colab. Many of the errors we see are grouped like this, with a 500 and 401, and don’t think we should be seeing this. It appears that there is a service worker intercepting our fetch call (a grpc-web+protobuf call), and when it encounters the 401 error from the server-side proxy, it translates it into a 500 that our application code sees. Are there any other details that we should know about in regards to the proxy/service worker that seems to be intercepting the calls?

Attached it a screenshot of Chrome's dev tools, showing the 500 and 401 calls. As you can see, a service worker handles the initial request, and appends a ?authuser=0 to the request before it goes to the server-side proxy.

The 500 response is empty, and the 401 response is below:

```<code><html lang=en>
 <meta charset=utf-8>
 <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
 <title>Error 401 (Unauthorized)!!1</title>
 <style>
  *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/logos/errorpage/error_logo-150x54.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/logos/errorpage/error_logo-150x54-2x.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/logos/errorpage/error_logo-150x54-2x.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/logos/errorpage/error_logo-150x54-2x.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
 </style>
 <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
 <p><b>401.</b> <ins>That's an error.</ins>
 <p> <ins>That's all we know.</ins>
It looks like the first unary grpc-web call will go through, but subsequent calls will fail - in our use case, the next call is server-streaming, but later unary calls also fail, so it doesn't seem to be specific to expecting h2 server-streaming responses.
</code>```

Colab link:
https://colab.research.google.com/drive/1FGDlUi3Ibtffb9hoYCp27WCe7JLpQRl7?usp=sharing

We're confident that our server isn't sending the 401 reply (as it would use a grpc-status instead), and as far as we can tell, it doesn't even get the request, much less have the opportunity to respond.

We would expect to be able to connect to the server and continue communication.

Title: Connection to localhost proxy breaking

Body:
We are encountering errors when trying to use a web application, iframe, and proxy port in colab in Chrome.

First, we pick an unused port, then set up a server on that port.
Then, we create an iframe that connects to this proxy url:
server_url = eval_js(f"google.colab.kernel.proxyPort({port})")

The iframe itself is loading, but we see tons of network errors and the server is not properly connecting in colab. Many of the errors we see are grouped like this, with a 500 and 401, and don’t think we should be seeing this. It appears that there is a service worker intercepting our fetch call (a grpc-web+protobuf call), and when it encounters the 401 error from the server-side proxy, it translates it into a 500 that our application code sees. Are there any other details that we should know about in regards to the proxy/service worker that seems to be intercepting the calls?

Attached it a screenshot of Chrome's dev tools, showing the 500 and 401 calls. As you can see, a service worker handles the initial request, and appends a ?authuser=0 to the request before it goes to the server-side proxy.

The 500 response is empty, and the 401 response is below:

 <meta charset=utf-8>
 <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
 <title>Error 401 (Unauthorized)!!1</title>

401. That's an error.

 That's all we know.
It looks like the first unary grpc-web call will go through, but subsequent calls will fail - in our use case, the next call is server-streaming, but later unary calls also fail, so it doesn't seem to be specific to expecting h2 server-streaming responses.

Colab link:
https://colab.research.google.com/drive/1FGDlUi3Ibtffb9hoYCp27WCe7JLpQRl7?usp=sharing

We're confident that our server isn't sending the 401 reply (as it would use a grpc-status instead), and as far as we can tell, it doesn't even get the request, much less have the opportunity to respond.

We would expect to be able to connect to the server and continue communication.


问:
What is the purpose of closing a database connection
I was just doing a lesson in CodeCademy under the 'Intermediate PHP' course for the lesson called 'Connecting to the Database'. In the last step, the task is to terminate the database connection. I might be asking this question a little too early on, but since I'm new to this, what is the purpose of terminating a database connection?


问:
How to save empty string as "" and None as nothing (not even quotes) in csv using Python
I am trying to select specific columns from a MySQL table into csv. This table has integers, varchar, NULL and empty strings. I want to differentiate between NULL and empty strings in specific way.

I am using mysql.connector module which gives me list of tuples as result of SQL. A sample row converted into tuple is:

DB Row: '786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, 2022-18-05 00:00:00, NULL, NULL

Tuple: '786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None

Now I want to write this entire list of tuples to a csv file and ensure that empty string is written in csv as "" and None is written in csv as nothing, not even quotes.

So the result I want is:

786a1f32e9e4|ABC|Abcdefgh|ABC2Y1Z|1.2.3-4-x202203100026-ABC2Y1Z-envr|ABC|""|active|1|0|2022-05-18 00:00:00||

OR

"786a1f32e9e4"|"ABC"|"Abcdefgh"|"ABC2Y1Z"|"1.2.3-4-x202203100026-ABC2Y1Z-envr"|"ABC"|""|"active"|"1"|"0"|"2022-05-18 00:00:00"||

I tried using csv:

```<code>import csv
import datetime

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]

with open('so_ex_1.csv', 'w') as f:
    write = csv.writer(f)
    write.writerows(myresult)
</code>```

pandas:

```<code>import pandas as pd
import datetime

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]

df = pd.DataFrame(myresult)
df.to_csv('so_ex_2.csv')
</code>```

numpy:

```<code>import numpy as np
import datetime

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]

np.savetxt('so_ex_3.csv', myresult, delimiter = "|", fmt = '% s')
</code>```

But can't find right parameters to set so I get the desired result.
Closest I could get was using pandas and csv modules with code:

```<code>import pandas as pd
import datetime
import csv

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]
df = pd.DataFrame(myresult)
df.to_csv(r'so_ex_4.csv', index=False, sep='|', quoting=csv.QUOTE_ALL, na_rep='None') # Option 5
</code>```

But even here I am unable to find a value that I can give to na_rep option so it doesn't print anything for None. So I end up getting following in csv:

"786a1f32e9e4"|"ABC"|"Abcdefgh"|"ABC2Y1Z"|"1.2.3-4-x202203100026-ABC2Y1Z-envr"|"ABC"|""|"active"|"1"|"0"|"2022-05-18"|"None"|"None"

Is there any way to get result in format I want using Python without having to do row level operations? The reason I want to avoid using row level operations is that sql can pull large amount of data so row level operations can be time consuming.

Body:
I am trying to select specific columns from a MySQL table into csv. This table has integers, varchar, NULL and empty strings. I want to differentiate between NULL and empty strings in specific way.

I am using mysql.connector module which gives me list of tuples as result of SQL. A sample row converted into tuple is:

DB Row: '786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, 2022-18-05 00:00:00, NULL, NULL

Tuple: '786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None

Now I want to write this entire list of tuples to a csv file and ensure that empty string is written in csv as "" and None is written in csv as nothing, not even quotes.

So the result I want is:

786a1f32e9e4|ABC|Abcdefgh|ABC2Y1Z|1.2.3-4-x202203100026-ABC2Y1Z-envr|ABC|""|active|1|0|2022-05-18 00:00:00||

OR

"786a1f32e9e4"|"ABC"|"Abcdefgh"|"ABC2Y1Z"|"1.2.3-4-x202203100026-ABC2Y1Z-envr"|"ABC"|""|"active"|"1"|"0"|"2022-05-18 00:00:00"||

I tried using csv:

import csv
import datetime

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]

with open('so_ex_1.csv', 'w') as f:
    write = csv.writer(f)
    write.writerows(myresult)

pandas:

import pandas as pd
import datetime

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]

df = pd.DataFrame(myresult)
df.to_csv('so_ex_2.csv')

numpy:

import numpy as np
import datetime

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]

np.savetxt('so_ex_3.csv', myresult, delimiter = "|", fmt = '% s')

But can't find right parameters to set so I get the desired result.
Closest I could get was using pandas and csv modules with code:

import pandas as pd
import datetime
import csv

myresult = [('786a1f32e9e4', 'ABC', 'Abcdefgh', 'ABC2Y1Z', '1.2.3-4-x202203100026-ABC2Y1Z-envr', 'ABC', '', 'active', 1, 0, datetime.datetime(2022, 5, 18, 0, 0), None, None)]
df = pd.DataFrame(myresult)
df.to_csv(r'so_ex_4.csv', index=False, sep='|', quoting=csv.QUOTE_ALL, na_rep='None') # Option 5

But even here I am unable to find a value that I can give to na_rep option so it doesn't print anything for None. So I end up getting following in csv:

"786a1f32e9e4"|"ABC"|"Abcdefgh"|"ABC2Y1Z"|"1.2.3-4-x202203100026-ABC2Y1Z-envr"|"ABC"|""|"active"|"1"|"0"|"2022-05-18"|"None"|"None"

Is there any way to get result in format I want using Python without having to do row level operations? The reason I want to avoid using row level operations is that sql can pull large amount of data so row level operations can be time consuming.


问:
How to develop a class module for a keyboard shortcut
I have a custom button on a ribbon, and I want to create a keyboard shortcut using a class module. I have managed to start it, but I am not able to take the next step, which would be to perform the action. I give you the code:

`

```<code>Option Compare Database
Option Explicit

Private WithEvents Form As Access.Form
Private mPresionarTecla As Boolean

Public Property Get PresionarTecla() As Boolean
    PresionarTecla = mPresionarTecla
End Property

Public Property Let PresionarTecla(ByVal vNewValue As Boolean)
    mPresionarTecla = vNewValue
End Property

Public Sub InitalizeAutokeys(FName As Form)
    Set Form = FName

    mPresionarTecla = True
    If mPresionarTecla = True Then
        FName.OnKeyDown = "[Event Procedure]"
    End If
End Sub

Private Sub frmCustomForm_KeyDown(KeyCode As Integer, Shift As Integer)
    If mPresionarTecla = True Then
        rbPegarSinFormato (Screen.ActiveControl)
    End If
End Sub
</code>```

`

I want to create a keyboard shortcut to execute a button on a ribbon. The ribbon button is a procedure created by me, which applies only to formatted text fields, to paste without formatting.

So that you understand me, in the toolbar you have a button, which can be executed by means of the combination of letters control + v. I want to achieve something similar.

Now if I do this through a macro, it's very limited because I can only do a few things, and with VBA I can do a lot more. That is, if I want to add conditions or, most importantly, execute a procedure, not a function, a macro is not worth it. Also, I can select which fields I want to apply it to, that is, since the function I'm using is to copy without formatting, it doesn't make sense for numeric fields to be applied

Body:
I have a custom button on a ribbon, and I want to create a keyboard shortcut using a class module. I have managed to start it, but I am not able to take the next step, which would be to perform the action. I give you the code:

`

Option Compare Database
Option Explicit

Private WithEvents Form As Access.Form
Private mPresionarTecla As Boolean

Public Property Get PresionarTecla() As Boolean
    PresionarTecla = mPresionarTecla
End Property

Public Property Let PresionarTecla(ByVal vNewValue As Boolean)
    mPresionarTecla = vNewValue
End Property

Public Sub InitalizeAutokeys(FName As Form)
    Set Form = FName

    mPresionarTecla = True
    If mPresionarTecla = True Then
        FName.OnKeyDown = "[Event Procedure]"
    End If
End Sub

Private Sub frmCustomForm_KeyDown(KeyCode As Integer, Shift As Integer)
    If mPresionarTecla = True Then
        rbPegarSinFormato (Screen.ActiveControl)
    End If
End Sub

`

I want to create a keyboard shortcut to execute a button on a ribbon. The ribbon button is a procedure created by me, which applies only to formatted text fields, to paste without formatting.

So that you understand me, in the toolbar you have a button, which can be executed by means of the combination of letters control + v. I want to achieve something similar.

Now if I do this through a macro, it's very limited because I can only do a few things, and with VBA I can do a lot more. That is, if I want to add conditions or, most importantly, execute a procedure, not a function, a macro is not worth it. Also, I can select which fields I want to apply it to, that is, since the function I'm using is to copy without formatting, it doesn't make sense for numeric fields to be applied


问:
Session not destroyed in php after closing browser?
I am new to web develepment and I am trying to create a simple login page.
For backend I use php.
For the login I use sessions.
My problem is that sessions are not destroyed when I close the browser.
I read that sessions are destroyed automatically when closing a browser, but that is not happening in my project.

I have read many articles, I tried with

```<code>session_set_cookie_params(0);
session_start();
</code>```

but this is not helping me at all, basically it does nothing.
I also read that there is a default timeout for sessions that lasts about 20 minutes and then session is closed, but it has been more than 6 hours and yet the session is not destroyed.

Sorry, if my question is stupid.
Thank you in advance! Any help or comment would be appreciated!

PS. I use Chrome browser

Body:
I am new to web develepment and I am trying to create a simple login page.
For backend I use php.
For the login I use sessions.
My problem is that sessions are not destroyed when I close the browser.
I read that sessions are destroyed automatically when closing a browser, but that is not happening in my project.

I have read many articles, I tried with

session_set_cookie_params(0);
session_start();

but this is not helping me at all, basically it does nothing.
I also read that there is a default timeout for sessions that lasts about 20 minutes and then session is closed, but it has been more than 6 hours and yet the session is not destroyed.

Sorry, if my question is stupid.
Thank you in advance! Any help or comment would be appreciated!

PS. I use Chrome browser


问:
Data Flow Diagram with Flylines information
I have data in the below format:

Input Data

And I need to generate the Data flow Diagram which will look like this:
Data flow visualization

If possible I would like to make the thickness of arrows based on the count which will determine visually the most important connectivities.

Is there any better way to do this?

Thanks in advance!

I tried plotting this in Excel/visio, but the results werent satisfactory.


问:
Debugging an environment issue for large package with tidyverse and dplyr
I'm trying to run a complex (and confidential) package that I use for work. I've run the package many times in the past, but am not able to run it now (in the interim, I likely updated R Studio and/or my installed packages). My coworkers are able run the package on their machines while using previous versions of the packages.

Tidyverse is a required package for the package that I am trying to use and is attached when I run the custom package (that was developed by a contractor for my company long before I joined who has since left). I'm able to match/load previous versions of the all tidyverse packages except for dplyr. I'm using 1.0.10 and my coworkers are using 1.0.8, but I get a tidyverse error message that it is no longer supporting versions of dplyr before 1.0.10.

Any thoughts on how I might go about debugging? I know that it's difficult without example code, but unfortunately I am not able to create a synthetic version and share.

I've tried debugging if it's a masking issue by using the conflicted package (i.e. conflict_prefer("mutate", "dplyr") and incorporating syntax (i.e. dplyr::mutate) throughout the function/script that is getting the error.

The error that I'm getting is:

Error in mutate():

! Problem while computing *calculatedfield*= pmap(...). Caused by
error in gather(): ! Can't subset columns that don't exist. x
Columns 2020, 2021, 2022, 2023, 2024, etc. don't exist.
(These columns are present when running the script line by line and
unnesting the tibble)


问:
Why is blazor.server.js blocking my other js files?
I have Blazor Server Web App Project that contains this default javascript link:

```<code><script src="_framework/blazor.server.js"></script>
</code>```

When I remove the link, my other js files load correctly, but if I add it back then they do not load. It does not matter if I add blazor.server.js before or after my js links.

HOW TO RECREATE MY SCENARIO:

Create default Blazor Server Web App

Add a new demo.js file to wwwroot and enter this js code:

$(document).ready(function () {

    $("#clickme").on("click", function () {
        alert("Handler for the 'Click Me' button is called.");
    });
});
```

Add demo.js to _Host.cshtml like this:

Create a button in /Index or /Counter and add: id="clickme"

Make sure that  is present in _Host.cshtml

Buid and Run.

Result 01:

The Blazor Server Web App will run but when you click the button, js code is not called.

Now, remove , build and run.

Result 02:

The Blazor Server Web App will run and when you click the button, js code is called correctly.

I want to include  and other js files and make them work.

What could be the problem?

I am using:

Visual Studio IDE 2022

Blazor Server Web App

.NET 7

Body:
I have Blazor Server Web App Project that contains this default javascript link:

When I remove the link, my other js files load correctly, but if I add it back then they do not load. It does not matter if I add blazor.server.js before or after my js links.

HOW TO RECREATE MY SCENARIO:

Create default Blazor Server Web App

Add a new demo.js file to wwwroot and enter this js code:

$(document).ready(function () {

    $("#clickme").on("click", function () {
        alert("Handler for the 'Click Me' button is called.");
    });
});

Add demo.js to _Host.cshtml like this:

Create a button in /Index or /Counter and add: id="clickme"

Make sure that  is present in _Host.cshtml

Buid and Run.

Result 01:

The Blazor Server Web App will run but when you click the button, js code is not called.

Now, remove , build and run.

Result 02:

The Blazor Server Web App will run and when you click the button, js code is called correctly.

I want to include  and other js files and make them work.

What could be the problem?

I am using:

Visual Studio IDE 2022

Blazor Server Web App

.NET 7


问:
Does @babel/traverse support remark-parse AST output?
I was wondering if there are any good traverser's like @babel/traverse that supports remark-parse AST output


问:
what happens next after you create a dev AAD tenant needed for Testing
I have created my dev ADD tenant, what are the next moves or things i need to configure to ensure the dev tenant mimics the prod tenant?

How do i manage users that are tied to my prod tenant to get them to my dev AAD tenant? is it a good idea to get same users from prod to dev or just ensure Dev has test users that i can use to create resources?

Has anyone work on something similar?


问:
Dynamically override content-type response header in AWS CloudFront
I'm using AWS S3 and CloudFront to distribute content.

My files stored in S3 have binary/octet-stream type but in fact they can be images or documents.
When generating S3 URLs, I can override the response content type with a parameter like this: https://my-bucket.s3.eu-central-1.amazonaws.com/foo/bar?[...]&response-content-type=image/jpeg

Is there a way to do it with CloudFront (with the same S3 bucket as origin)?

I tried adding the same parameter -- it's ignored.
I can create a response headers policy and add a custom header overriding origin, but as far as I can see, it'll be the same for all files whereas I need to control it with a request parameter.


问:
How to send a chatlog of all written chats to a newly joined client using socket programming in Python?
I have written a simple server and client py using UDP. The base is working, however I want that every time a user (client) joins, he would receive a chatlog of everything that has been said.

This is my code until now:

Server:

```<code>import socket
import threading
import queue
import pickle

messages = queue.Queue()
clients = []

# AF_INET used for IPv4
# SOCK_DGRAM used for UDP protocol

ip = "localhost"
port = 5555
chatlog=[]
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# binding IP and port

UDPServerSocket.bind((ip, port))

def receive():
    while True:
        try:
            message, addr = UDPServerSocket.recvfrom(1024)
            messages.put((message, addr))
            chatlog.append((message,addr))
        except:
            pass

def broadcast():
    while True:
        while not messages.empty():
            message, addr = messages.get()
            print(message.decode())
            if addr not in clients:
                clients.append(addr)
            for client in clients:
                try:
                    if message.decode().startswith("SIGNUP_TAG:"):
                        name = message.decode()[message.decode().index(":") + 1:]
                        UDPServerSocket.sendto(f"{name} joined!".encode(), client)
                        if len(chatlog)>0:
                            sending= pickle.dumps(chatlog)
                            UDPServerSocket.sendto(sending, client)
                        else:
                            pass
                    else:
                        UDPServerSocket.sendto(message, client)
                except:
                    clients.remove(client)

t1 = threading.Thread(target=receive)
t2 = threading.Thread(target=broadcast)

t1.start()
t2.start()

</code>```

And the client

```<code>import socket
import threading
import random

client= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.bind(("localhost", random.randint(7000, 8000))) # random port for every client

name =  "Henk" #test name

def receive():
    while True:
        try:
            message, _ = client.recvfrom(1024)
            print(message.decode())
        except:
            pass

t= threading.Thread(target= receive)
t.start()

#this gives the server the name of the people who have entered the server
client.sendto(f"SIGNUP_TAG: {name}".encode(), ("localhost", 5555))

while True:
    message= input("")
    if message=="!q":
        exit()
    else:
        client.sendto(f'[{name}]: {message}'.encode(), ("localhost",5555))

</code>```

So I am actually a bit stuck on how I will approach this. Shall create a text file where every time that a message is written it gets written on the file as well? Or shall I create some kind of string list/database where every message is stored :/

Body:
I have written a simple server and client py using UDP. The base is working, however I want that every time a user (client) joins, he would receive a chatlog of everything that has been said.

This is my code until now:

Server:

import socket
import threading
import queue
import pickle

messages = queue.Queue()
clients = []

# AF_INET used for IPv4
# SOCK_DGRAM used for UDP protocol

ip = "localhost"
port = 5555
chatlog=[]
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# binding IP and port

UDPServerSocket.bind((ip, port))

def receive():
    while True:
        try:
            message, addr = UDPServerSocket.recvfrom(1024)
            messages.put((message, addr))
            chatlog.append((message,addr))
        except:
            pass

def broadcast():
    while True:
        while not messages.empty():
            message, addr = messages.get()
            print(message.decode())
            if addr not in clients:
                clients.append(addr)
            for client in clients:
                try:
                    if message.decode().startswith("SIGNUP_TAG:"):
                        name = message.decode()[message.decode().index(":") + 1:]
                        UDPServerSocket.sendto(f"{name} joined!".encode(), client)
                        if len(chatlog)>0:
                            sending= pickle.dumps(chatlog)
                            UDPServerSocket.sendto(sending, client)
                        else:
                            pass
                    else:
                        UDPServerSocket.sendto(message, client)
                except:
                    clients.remove(client)

t1 = threading.Thread(target=receive)
t2 = threading.Thread(target=broadcast)

t1.start()
t2.start()

And the client

import socket
import threading
import random

client= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.bind(("localhost", random.randint(7000, 8000))) # random port for every client

name =  "Henk" #test name

def receive():
    while True:
        try:
            message, _ = client.recvfrom(1024)
            print(message.decode())
        except:
            pass

t= threading.Thread(target= receive)
t.start()

#this gives the server the name of the people who have entered the server
client.sendto(f"SIGNUP_TAG: {name}".encode(), ("localhost", 5555))

while True:
    message= input("")
    if message=="!q":
        exit()
    else:
        client.sendto(f'[{name}]: {message}'.encode(), ("localhost",5555))

So I am actually a bit stuck on how I will approach this. Shall create a text file where every time that a message is written it gets written on the file as well? Or shall I create some kind of string list/database where every message is stored :/


问:
props value reset to 0 and NaN in reactjs component
So I am trying to make a simple Typing App in reactjs, But I am facing an issue while passing values of Accuracy and WPM to another Component ResultsPage.js. The values are correct in App.js and are passed correctly to ResultsPage.js too(by seeing console.log) but then resets to 0.
Here is my return code block of App.js

```<code> return (
    <div>
      <h1>Type the paragraph:</h1>
      <h2>{currentParagraph}</h2>
      <textarea
        ref={inputRef}
        value={typedText}
        onChange={handleChange}
        disabled={!isPlaying}
        rows={6}
        style={{ width: "100%" }}
      />
      {showResults ? (
        <ResultsPage
          accuracy={accuracy}
          wpm={wpm}
          onTryAgain={() => setShowResults(false)}
        />
      ) : (
        <div>
          {isPlaying ? (
            <div>
              Time remaining: {timeRemaining}
              <br />
              Accuracy: {accuracy.toFixed(2)}%<p>WPM: {wpm.toFixed(0)}</p>
            </div>
          ) : (
            <div>
              <label htmlFor="timer-length">Timer length:</label>
              <input
                id="timer-length"
                type="number"
                value={timerLength}
                onChange={(event) => setTimerLength(Number(event.target.value))}
              />
              <button onClick={handleStartClick}>Start</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
</code>```

This is where Im calculating WPM and Accuracy

```<code>useEffect(() => {
    // Calculate the accuracy as the number of correctly typed words divided by the total number of words
    const currentWords = currentParagraph.split(" ");
    const totalWords = currentWords.length;
    const typedWords = typedText.split(" ");
    const correctWords = typedWords.reduce((total, word, index) => {
      if (word === currentWords[index]) {
        return total + 1;
      }
      return total;
    }, 0);
    setAccuracy((correctWords / typedWords.length) * 100);
    // console.log("acc" + accuracy);
    // Calculate the WPM as the number of correctly typed words divided by the time elapsed, multiplied by 60 seconds
    const elapsedTime = timerLength - timeRemaining;
    let totalChars = 0;
    typedWords.forEach((word, index) => {
      if (word === currentWords[index]) {
        totalChars += word.length + 1; // +1 to count the space
      }
    });
    setWpm((totalChars / 5 / elapsedTime) * 60);
    //console.log("wpm" + wpm);
  }, [currentParagraph, typedText, timerLength, timeRemaining]);
</code>```

This is ResultsPage.js

```<code>function ResultsPage(props) {
  // Set default values for accuracy and wpm
  const { accuracy = 0, wpm = 0, onTryAgain } = props;

   console.log("," + accuracy + "," + wpm);
  return (
    <div>
      <p>Your accuracy was {accuracy}%</p>
      <p>Your WPM was {wpm}</p>
      <button onClick={onTryAgain}>Try Again</button>
    </div>
  );
}

export default ResultsPage;
</code>```

This is the output:

This is after the timer runs out and ResultsPage component is called:

Body:
So I am trying to make a simple Typing App in reactjs, But I am facing an issue while passing values of Accuracy and WPM to another Component ResultsPage.js. The values are correct in App.js and are passed correctly to ResultsPage.js too(by seeing console.log) but then resets to 0.
Here is my return code block of App.js

 return (

Type the paragraph:

{currentParagraph}

      <textarea
        ref={inputRef}
        value={typedText}
        onChange={handleChange}
        disabled={!isPlaying}
        rows={6}
        style={{ width: "100%" }}
      />
      {showResults ? (
        <ResultsPage
          accuracy={accuracy}
          wpm={wpm}
          onTryAgain={() => setShowResults(false)}
        />
      ) : (

          {isPlaying ? (

              Time remaining: {timeRemaining}

              Accuracy: {accuracy.toFixed(2)}%
WPM: {wpm.toFixed(0)}

          ) : (

              Timer length:
              <input
                id="timer-length"
                type="number"
                value={timerLength}
                onChange={(event) => setTimerLength(Number(event.target.value))}
              />
              <button onClick={handleStartClick}>Start</button>

          )}

      )}

  );

This is where Im calculating WPM and Accuracy

useEffect(() => {
    // Calculate the accuracy as the number of correctly typed words divided by the total number of words
    const currentWords = currentParagraph.split(" ");
    const totalWords = currentWords.length;
    const typedWords = typedText.split(" ");
    const correctWords = typedWords.reduce((total, word, index) => {
      if (word === currentWords[index]) {
        return total + 1;
      }
      return total;
    }, 0);
    setAccuracy((correctWords / typedWords.length) * 100);
    // console.log("acc" + accuracy);
    // Calculate the WPM as the number of correctly typed words divided by the time elapsed, multiplied by 60 seconds
    const elapsedTime = timerLength - timeRemaining;
    let totalChars = 0;
    typedWords.forEach((word, index) => {
      if (word === currentWords[index]) {
        totalChars += word.length + 1; // +1 to count the space
      }
    });
    setWpm((totalChars / 5 / elapsedTime) * 60);
    //console.log("wpm" + wpm);
  }, [currentParagraph, typedText, timerLength, timeRemaining]);

This is ResultsPage.js

function ResultsPage(props) {
  // Set default values for accuracy and wpm
  const { accuracy = 0, wpm = 0, onTryAgain } = props;

   console.log("," + accuracy + "," + wpm);
  return (

Your accuracy was {accuracy}%

Your WPM was {wpm}

      <button onClick={onTryAgain}>Try Again</button>

  );
}

export default ResultsPage;

This is the output:

This is after the timer runs out and ResultsPage component is called:


问:
Localstack: Lambda not executing with below error (Linux)
Using localstack latest version (v1.3.2.dev), getting below error.
lambdas were working in my previous version.

This is error message that's getting recorded with localstack/localstack-pro:latest
when lambda is being invoked.

Getting ipv4 address for container sre-localstackBaseline in network
SAE-default-network. 2023-01-03 20:51:17 2023-01-03T20:51:17.031  INFO
--- [uncthread542] l.u.container_networking   : Determined main container target IP: 172.23.0.5 2023-01-03 20:51:17
2023-01-03T20:51:17.031  INFO --- [uncthread542]
l.s.a.lambda_executors     : Running lambda:
arn:aws:lambda:eu-west-1:000000000000:function:InitiationService
2023-01-03 20:51:17 2023-01-03T20:51:17.031 DEBUG --- [uncthread542]
l.s.a.lambda_launcher      : Executing docker separate execution hook
for function arn:aws:lambda:eu-west-1:000000000000:function:aaaService
2023-01-03 20:51:17 2023-01-03T20:51:17.130 DEBUG --- [uncthread542]
l.u.c.container_client     : Getting the entrypoint for image:
localstack/lambda:dotnet6

2023-01-03 18:51:18 2023-01-03T18:51:18.525  INFO --- [uncthread494]
localstack.utils.threads   : Thread run method <function
LambdaExecutor.execute..do_execute at 0x7fc525d61ea0>(None)
failed: Mount to /var/lib/localstack needs to be a bind mount for
mounting to work Traceback (most recent call last):

2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/utils/threads.py", line 58, in run
2023-01-03 18:51:18     result = self.func(self.params, **kwargs)
2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 484, in do_execute 2023-01-03 18:51:18     return
_run(func_arn=func_arn) 2023-01-03 18:51:18   File "/opt/code/localstack/localstack/utils/cloudwatch/cloudwatch_util.py",
line 183, in wrapped 2023-01-03 18:51:18     raise e 2023-01-03
18:51:18   File
"/opt/code/localstack/localstack/utils/cloudwatch/cloudwatch_util.py",
line 179, in wrapped 2023-01-03 18:51:18     result = func(*args,
**kwargs) 2023-01-03 18:51:18   File "/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 471, in _run 2023-01-03 18:51:18     raise e 2023-01-03 18:51:18
File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 467, in _run 2023-01-03 18:51:18     result =
self._execute(lambda_function, inv_context) 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 790, in _execute 2023-01-03 18:51:18     result =
self.run_lambda_executor(lambda_function=lambda_function,
inv_context=inv_context) 2023-01-03 18:51:18   File
"/opt/code/localstack/.venv/lib/python3.10/site-packages/localstack_ext/services/awslambda/lambda_extended.py.enc",
line 347, in run_lambda_executor 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 667, in run_lambda_executor 2023-01-03 18:51:18     result,
log_output = self.execute_in_container( 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 1268, in execute_in_container 2023-01-03 18:51:18

on_docker_separate_execution.run(lambda_function, container_config)
2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/runtime/hooks.py", line 63, in
run_in_order 2023-01-03 18:51:18     fn_plugin(*args, **kwargs)
2023-01-03 18:51:18   File
"/opt/code/localstack/.venv/lib/python3.10/site-packages/plugin/core.py",
line 183, in call 2023-01-03 18:51:18     return self.fn(*args,
**kwargs) 2023-01-03 18:51:18   File "/opt/code/localstack/.venv/lib/python3.10/site-packages/localstack_ext/services/awslambda/lambda_launcher.py.enc",
line 66, in docker_separate_lambda_execution 2023-01-03 18:51:18

File
"/opt/code/localstack/.venv/lib/python3.10/site-packages/localstack_ext/services/awslambda/lambda_launcher.py.enc",
line 56, in modify_docker_lambda_execution 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/utils/docker_utils.py", line 114, in
get_host_path_for_path_in_docker 2023-01-03 18:51:18     raise
ValueError( 2023-01-03 18:51:18 ValueError: Mount to
/var/lib/localstack needs to be a bind mount for mounting to work
2023-01-03 18:51:18 2023-01-03 18:51:18 2023-01-03T18:51:18.525 DEBUG
--- [uncthread494] localstack.utils.threads   : FINISHED: <Future at 0x7fc525dbc0a0 state=finished raised ValueError>

Any suggestion will be apprecicated.

below is docker file for reference:

version: "3.8"

```<code>services:
  localstack:
    env_file:
        - developer.env
    container_name: "sre-localstackBaseline"
    image: localstack/localstack-pro
    platform: linux
    privileged: true
    ##network_mode: bridge
    ports:
      - "127.0.0.1:53:53"                # only required for Pro (DNS)
      - "127.0.0.1:53:53/udp"            # only required for Pro (DNS)
      - "127.0.0.1:443:443"              # only required for Pro (LocalStack HTTPS Edge Proxy)
      - "127.0.0.1:4510-4559:4510-4559"  # external service port range
      - "127.0.0.1:4566:4566"            # LocalStack Edge Proxy
    environment:
      - REQUIRE_PRO=0
      - LOCALSTACK_API_KEY=1212121212
      - USE_SINGLE_REGION=1
      - EDGE_PORT=4566
      - PORT_WEB_UI=8081
      - START_WEB=1
      - DEBUG=1
      - SERVICES=serverless,s3,sqs,ec2,apigateway,dynamodb,lambda,iam,ssm,cloudformation,sts,kinesis,events
      - DEFAULT-REGION=eu-west-1
      - TMPDIR=/tmp
      - DATA_DIR=/tmp/localstack/data
      - LAMBDA_EXECUTOR=docker
      - LAMBDA_REMOVE_CONTAINERS=1
      - LAMBDA_XRAY_INIT=1
      - LAMBDA_REMOTE_DOCKER=true
      - LAMBDA_DOCKER_NETWORK=SAE-default-network
      - HOST_TMP_FOLDER=${TMPDIR:-/tmp/}localstack
      - DOCKER_HOST=unix:///var/run/docker.sock
      - LOCALSTACK_DOCKER_NAME= enterprise
      - DEFAULT_REGION=eu-west-1
      - HOSTNAME_EXTERNAL=sre-localstackBaseline #same as container_name
      - LOCALSTACK_HOSTNAME=sre-localstackBaseline #same as container_name
    volumes:
      - ./init/scripts:/docker-entrypoint-initaws.d
      - ./init/cloudFormation:/tmp/localstack/data/cloudFormation
      - "localstackDataVolume:/tmp/localstack" #use a volume not a path
      - "/var/run/docker.sock:/var/run/docker.sock"
    networks:
    - SAE-default-network
volumes:
    localstackDataVolume: #declare the volume for the compose file
      external: true

networks:
    SAE-default-network:
        external: false
        driver: bridge
        name: SAE-default-network
</code>```

Many Thanks

Body:
Using localstack latest version (v1.3.2.dev), getting below error.
lambdas were working in my previous version.

This is error message that's getting recorded with localstack/localstack-pro:latest
when lambda is being invoked.

Getting ipv4 address for container sre-localstackBaseline in network
SAE-default-network. 2023-01-03 20:51:17 2023-01-03T20:51:17.031  INFO
--- [uncthread542] l.u.container_networking   : Determined main container target IP: 172.23.0.5 2023-01-03 20:51:17
2023-01-03T20:51:17.031  INFO --- [uncthread542]
l.s.a.lambda_executors     : Running lambda:
arn:aws:lambda:eu-west-1:000000000000:function:InitiationService
2023-01-03 20:51:17 2023-01-03T20:51:17.031 DEBUG --- [uncthread542]
l.s.a.lambda_launcher      : Executing docker separate execution hook
for function arn:aws:lambda:eu-west-1:000000000000:function:aaaService
2023-01-03 20:51:17 2023-01-03T20:51:17.130 DEBUG --- [uncthread542]
l.u.c.container_client     : Getting the entrypoint for image:
localstack/lambda:dotnet6

2023-01-03 18:51:18 2023-01-03T18:51:18.525  INFO --- [uncthread494]
localstack.utils.threads   : Thread run method <function
LambdaExecutor.execute..do_execute at 0x7fc525d61ea0>(None)
failed: Mount to /var/lib/localstack needs to be a bind mount for
mounting to work Traceback (most recent call last):

2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/utils/threads.py", line 58, in run
2023-01-03 18:51:18     result = self.func(self.params, **kwargs)
2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 484, in do_execute 2023-01-03 18:51:18     return
_run(func_arn=func_arn) 2023-01-03 18:51:18   File "/opt/code/localstack/localstack/utils/cloudwatch/cloudwatch_util.py",
line 183, in wrapped 2023-01-03 18:51:18     raise e 2023-01-03
18:51:18   File
"/opt/code/localstack/localstack/utils/cloudwatch/cloudwatch_util.py",
line 179, in wrapped 2023-01-03 18:51:18     result = func(*args,
**kwargs) 2023-01-03 18:51:18   File "/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 471, in _run 2023-01-03 18:51:18     raise e 2023-01-03 18:51:18
File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 467, in _run 2023-01-03 18:51:18     result =
self._execute(lambda_function, inv_context) 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 790, in _execute 2023-01-03 18:51:18     result =
self.run_lambda_executor(lambda_function=lambda_function,
inv_context=inv_context) 2023-01-03 18:51:18   File
"/opt/code/localstack/.venv/lib/python3.10/site-packages/localstack_ext/services/awslambda/lambda_extended.py.enc",
line 347, in run_lambda_executor 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 667, in run_lambda_executor 2023-01-03 18:51:18     result,
log_output = self.execute_in_container( 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/services/awslambda/lambda_executors.py",
line 1268, in execute_in_container 2023-01-03 18:51:18

on_docker_separate_execution.run(lambda_function, container_config)
2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/runtime/hooks.py", line 63, in
run_in_order 2023-01-03 18:51:18     fn_plugin(*args, **kwargs)
2023-01-03 18:51:18   File
"/opt/code/localstack/.venv/lib/python3.10/site-packages/plugin/core.py",
line 183, in call 2023-01-03 18:51:18     return self.fn(*args,
**kwargs) 2023-01-03 18:51:18   File "/opt/code/localstack/.venv/lib/python3.10/site-packages/localstack_ext/services/awslambda/lambda_launcher.py.enc",
line 66, in docker_separate_lambda_execution 2023-01-03 18:51:18

File
"/opt/code/localstack/.venv/lib/python3.10/site-packages/localstack_ext/services/awslambda/lambda_launcher.py.enc",
line 56, in modify_docker_lambda_execution 2023-01-03 18:51:18   File
"/opt/code/localstack/localstack/utils/docker_utils.py", line 114, in
get_host_path_for_path_in_docker 2023-01-03 18:51:18     raise
ValueError( 2023-01-03 18:51:18 ValueError: Mount to
/var/lib/localstack needs to be a bind mount for mounting to work
2023-01-03 18:51:18 2023-01-03 18:51:18 2023-01-03T18:51:18.525 DEBUG
--- [uncthread494] localstack.utils.threads   : FINISHED: <Future at 0x7fc525dbc0a0 state=finished raised ValueError>

Any suggestion will be apprecicated.

below is docker file for reference:

version: "3.8"

services:
  localstack:
    env_file:
        - developer.env
    container_name: "sre-localstackBaseline"
    image: localstack/localstack-pro
    platform: linux
    privileged: true
    ##network_mode: bridge
    ports:
      - "127.0.0.1:53:53"                # only required for Pro (DNS)
      - "127.0.0.1:53:53/udp"            # only required for Pro (DNS)
      - "127.0.0.1:443:443"              # only required for Pro (LocalStack HTTPS Edge Proxy)
      - "127.0.0.1:4510-4559:4510-4559"  # external service port range
      - "127.0.0.1:4566:4566"            # LocalStack Edge Proxy
    environment:
      - REQUIRE_PRO=0
      - LOCALSTACK_API_KEY=1212121212
      - USE_SINGLE_REGION=1
      - EDGE_PORT=4566
      - PORT_WEB_UI=8081
      - START_WEB=1
      - DEBUG=1
      - SERVICES=serverless,s3,sqs,ec2,apigateway,dynamodb,lambda,iam,ssm,cloudformation,sts,kinesis,events
      - DEFAULT-REGION=eu-west-1
      - TMPDIR=/tmp
      - DATA_DIR=/tmp/localstack/data
      - LAMBDA_EXECUTOR=docker
      - LAMBDA_REMOVE_CONTAINERS=1
      - LAMBDA_XRAY_INIT=1
      - LAMBDA_REMOTE_DOCKER=true
      - LAMBDA_DOCKER_NETWORK=SAE-default-network
      - HOST_TMP_FOLDER=${TMPDIR:-/tmp/}localstack
      - DOCKER_HOST=unix:///var/run/docker.sock
      - LOCALSTACK_DOCKER_NAME= enterprise
      - DEFAULT_REGION=eu-west-1
      - HOSTNAME_EXTERNAL=sre-localstackBaseline #same as container_name
      - LOCALSTACK_HOSTNAME=sre-localstackBaseline #same as container_name
    volumes:
      - ./init/scripts:/docker-entrypoint-initaws.d
      - ./init/cloudFormation:/tmp/localstack/data/cloudFormation
      - "localstackDataVolume:/tmp/localstack" #use a volume not a path
      - "/var/run/docker.sock:/var/run/docker.sock"
    networks:
    - SAE-default-network
volumes:
    localstackDataVolume: #declare the volume for the compose file
      external: true

networks:
    SAE-default-network:
        external: false
        driver: bridge
        name: SAE-default-network

Many Thanks


问:
Output mixed Hebrew & English to Excel starting on left, uniformly
I have a list of object Strings with some Hebrew and English mixed.  The Sentence always starts with Hebrew.  My GOAL output is:

```<code>אדר: Mon, 40 minutes and 11 חלקים after 12:00 PM
ניסן: Wed, 24 minutes and 12 חלקים after 1:00 AM
אייר: Thu, 8 minutes and 13 חלקים after 2:00 PM
סיון: שבת, 52 minutes and 14 חלקים after 2:00 AM
</code>```

Current output:

I've tried interject the left to right bytes such as "\u202E" + "שבת" + "\u202D" but I can't find a combination of code that makes this uniformly work.

At a minimum if I print the cell starting with an English character it starts in the right place, but the Hebrew after the colon starts the same issue:

Here is some Sample Java code to generate the above

```<code>import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.junit.Test;

import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class TestHebrew {

    int rowNumber = 1;
    XSSFSheet sheet;
    XSSFRow row;

    @Test
    public void TestHebrewEnglishInterlace() throws IOException {
        List<MyObject> objects = new ArrayList<>();
        objects.add(new MyObject("אדר", "Mon, 40 minutes and 11 חלקים after 12:00 PM"));
        objects.add(new MyObject("ניסן", "Wed, 24 minutes and 12 חלקים after 1:00 AM"));
        objects.add(new MyObject("אייר", "Thu, 8 minutes and 13 חלקים after 2:00 PM"));
        objects.add(new MyObject("סיון", "Sat, 52 minutes and 14 חלקים after 2:00 AM"));

        objects.get(3).description = objects.get(3).description.replace("Sat", "שבת");

        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            sheet = workbook.createSheet("TestSheet");
            row = sheet.createRow(rowNumber);

            XSSFCellStyle style = workbook.createCellStyle();
            style.setWrapText(true);
            style.setAlignment(HorizontalAlignment.LEFT);
            for (MyObject o : objects) {
                addCellAndNextRow(style, o.month + ":" + "" + o.description);
            }

            addCellAndNextRow(style, "");
            addCellAndNextRow(style, "Same values but appending English first");
            addCellAndNextRow(style, "");

            for (MyObject o : objects) {
                addCellAndNextRow(style, "a " + o.month + ": " + "" + o.description);
            }

            IntStream.range(0, 1).forEach(i -> sheet.autoSizeColumn(i));

            try (FileOutputStream out = new FileOutputStream(FileSystemView.getFileSystemView().getHomeDirectory().toPath().resolve("output.xlsx").toFile())) {
                workbook.write(out);
            }
            Desktop.getDesktop().open(FileSystemView.getFileSystemView().getHomeDirectory().toPath().resolve("output.xlsx").toFile());

        }
    }

    private void addCellAndNextRow(XSSFCellStyle style, String value) {
        XSSFCell cell = row.createCell(0);
        cell.setCellStyle(style);
        cell.setCellValue(value);
        row = sheet.createRow(++rowNumber);
    }

    static class MyObject {
        String month;
        String description;

        public MyObject(String month, String description) {
            this.month = month;
            this.description = description;
        }
    }
}

</code>```

Body:
I have a list of object Strings with some Hebrew and English mixed.  The Sentence always starts with Hebrew.  My GOAL output is:

אדר: Mon, 40 minutes and 11 חלקים after 12:00 PM
ניסן: Wed, 24 minutes and 12 חלקים after 1:00 AM
אייר: Thu, 8 minutes and 13 חלקים after 2:00 PM
סיון: שבת, 52 minutes and 14 חלקים after 2:00 AM

Current output:

I've tried interject the left to right bytes such as "\u202E" + "שבת" + "\u202D" but I can't find a combination of code that makes this uniformly work.

At a minimum if I print the cell starting with an English character it starts in the right place, but the Hebrew after the colon starts the same issue:

Here is some Sample Java code to generate the above

import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.junit.Test;

import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class TestHebrew {

    int rowNumber = 1;
    XSSFSheet sheet;
    XSSFRow row;

    @Test
    public void TestHebrewEnglishInterlace() throws IOException {
        List<MyObject> objects = new ArrayList<>();
        objects.add(new MyObject("אדר", "Mon, 40 minutes and 11 חלקים after 12:00 PM"));
        objects.add(new MyObject("ניסן", "Wed, 24 minutes and 12 חלקים after 1:00 AM"));
        objects.add(new MyObject("אייר", "Thu, 8 minutes and 13 חלקים after 2:00 PM"));
        objects.add(new MyObject("סיון", "Sat, 52 minutes and 14 חלקים after 2:00 AM"));

        objects.get(3).description = objects.get(3).description.replace("Sat", "שבת");

        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            sheet = workbook.createSheet("TestSheet");
            row = sheet.createRow(rowNumber);

            XSSFCellStyle style = workbook.createCellStyle();
            style.setWrapText(true);
            style.setAlignment(HorizontalAlignment.LEFT);
            for (MyObject o : objects) {
                addCellAndNextRow(style, o.month + ":" + "" + o.description);
            }

            addCellAndNextRow(style, "");
            addCellAndNextRow(style, "Same values but appending English first");
            addCellAndNextRow(style, "");

            for (MyObject o : objects) {
                addCellAndNextRow(style, "a " + o.month + ": " + "" + o.description);
            }

            IntStream.range(0, 1).forEach(i -> sheet.autoSizeColumn(i));

            try (FileOutputStream out = new FileOutputStream(FileSystemView.getFileSystemView().getHomeDirectory().toPath().resolve("output.xlsx").toFile())) {
                workbook.write(out);
            }
            Desktop.getDesktop().open(FileSystemView.getFileSystemView().getHomeDirectory().toPath().resolve("output.xlsx").toFile());

        }
    }

    private void addCellAndNextRow(XSSFCellStyle style, String value) {
        XSSFCell cell = row.createCell(0);
        cell.setCellStyle(style);
        cell.setCellValue(value);
        row = sheet.createRow(++rowNumber);
    }

    static class MyObject {
        String month;
        String description;

        public MyObject(String month, String description) {
            this.month = month;
            this.description = description;
        }
    }
}


问:
Naming conventions to be used when creating APIs in django to be consumed in javascript
I am creating a REST API in Django to be used in JavaScript. In python, the fields are all named using snake_case, but in JavaScript it is recommended to use camelCase for variable names.
How do I resolve this difference without having to rename them when I use them in JS, or do I just stick to one convention on both front and back end?</p>


问:
Gulp Error ...calculateStatsPerFile(messages) ^^^ SyntaxError: Unexpected token
```<code> ...calculateStatsPerFile(messages)
        ^^^
SyntaxError: Unexpected token ...
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
</code>```

I get this error when i run gulp.

i have had this issue before but i deleted my node_modules folder and ran npm install again and it fixed it, but i restarted my computer and it came back ive tried removing the node_modules folder again but it still wont work.

npm -v : 3.10.8
node -v : v6.9.0
gulp -v : CLI version: 2.3.0
Local version: 4.0.2

Body:
 ...calculateStatsPerFile(messages)
        ^^^
SyntaxError: Unexpected token ...
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

I get this error when i run gulp.

i have had this issue before but i deleted my node_modules folder and ran npm install again and it fixed it, but i restarted my computer and it came back ive tried removing the node_modules folder again but it still wont work.

npm -v : 3.10.8
node -v : v6.9.0
gulp -v : CLI version: 2.3.0
Local version: 4.0.2


问:
How Do I Add Multiple Testing Stages For AWS Amplify to Achieve Automated Full-Stack CI/CD Deployment?
Current Deployment:

Development Environment - I have an amplify hosting setup where I build my current code. This could be viewed as "pre-prod". I ensure everything compiles and works as expected. The pipeline is the default AWS Amplify provides.

Production Environment - After being "happy" with the Development environment, I merge the environments and deploy the code to production.

Desired Deployment:

After reading Clare Liguori's fantastic blog on AWS Builders, it struck me that the initial three stages are very limited.

I would now like to have full-stack automated backend testing for all the AWS resources, and front-end testing, before allowing new code changes to be deployed into the development and production environments.

What I don't want:

I understand there is a local "mocking" testing. Whilst this is useful, I believe doing this on my IDE is not automated, and thus something outside the scope of my question.


问:
How edit the amounts from a "budgetImport" record in suitscript2.0?
I have made a suitelet that groups accounts, but I need to save the results in the budget account lines, I do a record load of "budgetImport", but it does not return the sublist with the amounts, does anyone know how it can be edited from code? ?

```<code>      var recordExample = record.load({
                    type: 'budgetImport',
                    id: 396,
                    isDynamic: true
                });

                recordExample.setSublistValue({
                    sublistId: 'budget',
                    fieldId: 'amount_10_',
                    line: 0,
                    value: 310001.00
                });
                var save = recordExample.save()
</code>```

I have tried this but it seems to be not a sublist but a 'lineFields'

Body:
I have made a suitelet that groups accounts, but I need to save the results in the budget account lines, I do a record load of "budgetImport", but it does not return the sublist with the amounts, does anyone know how it can be edited from code? ?

      var recordExample = record.load({
                    type: 'budgetImport',
                    id: 396,
                    isDynamic: true
                });

                recordExample.setSublistValue({
                    sublistId: 'budget',
                    fieldId: 'amount_10_',
                    line: 0,
                    value: 310001.00
                });
                var save = recordExample.save()

I have tried this but it seems to be not a sublist but a 'lineFields'


问:
Error launching .NET app on another machine
After publishing my .NET application as self-contained and into a single .exe file and sharing it with two friends I found out it didn't work.

It runs fine for me and one of my friends but the second gets an error:

cannot use file stream for NameOfProject.deps.json: no such file or directory

When I published as a single file it shouldn't depend on any extra files, right? I told him to create a new file with the same name and add an empty object but it also didn't work.

As a side note, all of us are running windows 11 x64 and have .NET's latest version.


问:
URL validation in Python - edge cases
I'm trying to write/use URL validation in python by simply analyzing the string (no http requests) but I get a lot of edge cases with the different solutions I tried.

After looking at django's urlvalidator, I still have some edge cases that are misclassified:

def is_url_valid(url: str) -> bool:
    # from django urlvalidator
    url_pattern = re.compile(
        r'^(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

    return bool(re.match(url_pattern, url))
```
<p>we still get:</p>
<pre class="lang-py prettyprint-override"><code>>>> is_url_valid('contact.html')
True
</code>```

Other approaches we tried:

validators (python package), recommended by this SO Q&A

>>> import validators
>>> validators.url("firespecialties.com/bullseyetwo.html") # this is a valid url
ValidationFailure(func=url, args={'value': 'firespecialties.com/bullseyetwo.html', 'public': False})
```
</li>
<li><p>from this validating urls in python SO Q&A
while <code>urllib.parse.urlparse('contact.html') correctly assess it as a path, it fails with </code>urllib.parse.urlparse('www.images.com/example.html')`:</p>
<pre class="lang-py prettyprint-override"><code>>>> from urllib.parse import urlparse
>>> urlparse('www.images.com/example.html')
ParseResult(scheme='', netloc='', path='www.images.com/example.html', params='', query='', fragment='')
</code>```

Adapting logic from this javascript SO Q&A

Title: URL validation in Python - edge cases

Body:
I'm trying to write/use URL validation in python by simply analyzing the string (no http requests) but I get a lot of edge cases with the different solutions I tried.

After looking at django's urlvalidator, I still have some edge cases that are misclassified:

def is_url_valid(url: str) -> bool:
    # from django urlvalidator
    url_pattern = re.compile(
        r'^(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

    return bool(re.match(url_pattern, url))

we still get:

>>> is_url_valid('contact.html')
True

Other approaches we tried:

validators (python package), recommended by this SO Q&A

>>> import validators
>>> validators.url("firespecialties.com/bullseyetwo.html") # this is a valid url
ValidationFailure(func=url, args={'value': 'firespecialties.com/bullseyetwo.html', 'public': False})

from this validating urls in python SO Q&A
while urllib.parse.urlparse('contact.html') correctly assess it as a path, it fails with urllib.parse.urlparse('www.images.com/example.html')`:

>>> from urllib.parse import urlparse
>>> urlparse('www.images.com/example.html')
ParseResult(scheme='', netloc='', path='www.images.com/example.html', params='', query='', fragment='')

Adapting logic from this javascript SO Q&A


问:
How can a flutter/android background isolate communicate with the foreground app
I have a Flutter app which receives FCM Messages in the background.
Sometimes, I need the foreground app to be aware of the received message when it is next brought to the foreground, for example to re-read shared preferences for new values.

Is there any RPC mechanism I shoud be using to pass a message to the foreground.

Alternatively I can have the foreground re-read shared preferences during a top level build(). Would this be considered an non-performant approach?


问:
Wordpress custom post type child pages not displaying/redirect me to parent page
I would like to achieve a hierarchical structure noted below. The wp-admin pages are set up this way with the parent pages and child pages within the custom post type section.

Custom post type name (clothing)

Custom post type parent (tops)

Custom post type child (t-shirts)

The issue: I'm not able to view the child pages, just the parent. The child pages redirect me to the parent page. Also, I did re-save the permalinks after adding hierarchical = true.

I am able to view: websitename.com/clothing/tops

I am not able to view: websitename.com/clothing/tops/t-shirts

The current functions.php code is

```<code>// Clothing
    register_post_type( 'clothing',
        array(
            'labels' => array(
                'name'                  => __( 'Clothing' ),
                'singular_name'         => __( 'clothing' ),
                'add_new'               => _x( 'Add New', 'Clothing' ),
                'add_new_item'          => __( 'Add New Clothing' ),
                'edit_item'             => __( 'Edit Clothing' ),
                'new_item'              => __( 'New Clothing' ),
                'all_items'             => __( 'All Clothing' ),
                'view_item'             => __( 'View Clothing' ),
                'search_items'          => __( 'Search Clothing' ),
                'not_found'             => __( 'No Clothing found' ),
                'not_found_in_trash'    => __( 'No Clothing found in the Trash' ),
                'parent_item_colon'     => '',
                'menu_name'             => 'Clothing'
            ),
            'public'                    => true,
            'publicly_queryable'        => true,
            'query_var'                 => true,
            'supports'                  => array( 'title', 'editor', 'custom-fields', 'page-attributes', 'thumbnail' ),
            'rewrite'                   => array(
          'slug'                            => 'clothing',
          'with_front'                      => false
        ),
            'hierarchical'              => true,
            'has_archive'               => false,
            'menu_position'             => 5,
            'menu_icon'                 => 'dashicons-building',
            'orderby'                   => 'title',
            'order'                     => 'ASC'
        )
    );
</code>```

Body:
I would like to achieve a hierarchical structure noted below. The wp-admin pages are set up this way with the parent pages and child pages within the custom post type section.

Custom post type name (clothing)

Custom post type parent (tops)

Custom post type child (t-shirts)

The issue: I'm not able to view the child pages, just the parent. The child pages redirect me to the parent page. Also, I did re-save the permalinks after adding hierarchical = true.

I am able to view: websitename.com/clothing/tops

I am not able to view: websitename.com/clothing/tops/t-shirts

The current functions.php code is

// Clothing
    register_post_type( 'clothing',
        array(
            'labels' => array(
                'name'                  => __( 'Clothing' ),
                'singular_name'         => __( 'clothing' ),
                'add_new'               => _x( 'Add New', 'Clothing' ),
                'add_new_item'          => __( 'Add New Clothing' ),
                'edit_item'             => __( 'Edit Clothing' ),
                'new_item'              => __( 'New Clothing' ),
                'all_items'             => __( 'All Clothing' ),
                'view_item'             => __( 'View Clothing' ),
                'search_items'          => __( 'Search Clothing' ),
                'not_found'             => __( 'No Clothing found' ),
                'not_found_in_trash'    => __( 'No Clothing found in the Trash' ),
                'parent_item_colon'     => '',
                'menu_name'             => 'Clothing'
            ),
            'public'                    => true,
            'publicly_queryable'        => true,
            'query_var'                 => true,
            'supports'                  => array( 'title', 'editor', 'custom-fields', 'page-attributes', 'thumbnail' ),
            'rewrite'                   => array(
          'slug'                            => 'clothing',
          'with_front'                      => false
        ),
            'hierarchical'              => true,
            'has_archive'               => false,
            'menu_position'             => 5,
            'menu_icon'                 => 'dashicons-building',
            'orderby'                   => 'title',
            'order'                     => 'ASC'
        )
    );


问:
CakePHP 4 : Error the Authentication Service Interface (auth tutorial)
I am following the tutorial to create a user and authentication system : https://book.cakephp.org/authentication/2/en/index.html

I followed the steps correctly but I got this error:

```<code>Fatal error : Class App\Application contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Authentication\AuthenticationServiceProviderInterface::getAuthenticationService) in **/Users/clementlanot/Sites/CLPRESS/src/Application.php
</code>```

When I add:

```<code>class Application extends BaseApplication implements AuthenticationServiceProviderInterface
</code>```

I searched but I don’t understand how to fix this? Can you help me ? Thank you !!

I tried to update Cake, to start again different version of the tutorial but I don't understand

Body:
I am following the tutorial to create a user and authentication system : https://book.cakephp.org/authentication/2/en/index.html

I followed the steps correctly but I got this error:

Fatal error : Class App\Application contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Authentication\AuthenticationServiceProviderInterface::getAuthenticationService) in **/Users/clementlanot/Sites/CLPRESS/src/Application.php

When I add:

class Application extends BaseApplication implements AuthenticationServiceProviderInterface

I searched but I don’t understand how to fix this? Can you help me ? Thank you !!

I tried to update Cake, to start again different version of the tutorial but I don't understand


问:
How to take bottom navigation menu on android into account in a React Native application?
Im building a React Native application using Expo, and Ive found my bottom navigation menu to be offset by 48 ppi if the built in bottom navigation menu is disabled.

Here is my code:

```<code>  bMenu: {
      position: 'absolute',
      bottom: 0, //-(PixelRatio.getPixelSizeForLayoutSize(48))
      width: '100%',
      height: Dimensions.get('window').height/10,
      flexDirection: 'row',
      justifyContent: 'space-evenly',
      alignItems: 'center'
  },
</code>```

Illustrates problem (the white area at the bottom of the screen)

Navigation menu I need to check for

Desired result (no white gap at the bottom)

Im thinking of settting "bottom" to the negative value of 48dp (the pixelratio comment in the code block does this) if the bottom menu is disabled, but I cant find any way to check if the bottom menu is enabled or disabled. I already use Dimensions from the react-native library to find the height of the screen and from there use bottom: 0 to fix it at the bottom of the screen, but this does appearently not take into account the built in navigation menu. Therefore I find that despite using bottom: 0, there is a white gap of 48dp at the bottom of the screen if the built in navigation bar is disabled.

This picture is from iPhone where everything works fine. It also works fine if the navigation menu is enabled on the android device.

Body:
Im building a React Native application using Expo, and Ive found my bottom navigation menu to be offset by 48 ppi if the built in bottom navigation menu is disabled.

Here is my code:

  bMenu: {
      position: 'absolute',
      bottom: 0, //-(PixelRatio.getPixelSizeForLayoutSize(48))
      width: '100%',
      height: Dimensions.get('window').height/10,
      flexDirection: 'row',
      justifyContent: 'space-evenly',
      alignItems: 'center'
  },

Illustrates problem (the white area at the bottom of the screen)

Navigation menu I need to check for

Desired result (no white gap at the bottom)

Im thinking of settting "bottom" to the negative value of 48dp (the pixelratio comment in the code block does this) if the bottom menu is disabled, but I cant find any way to check if the bottom menu is enabled or disabled. I already use Dimensions from the react-native library to find the height of the screen and from there use bottom: 0 to fix it at the bottom of the screen, but this does appearently not take into account the built in navigation menu. Therefore I find that despite using bottom: 0, there is a white gap of 48dp at the bottom of the screen if the built in navigation bar is disabled.

This picture is from iPhone where everything works fine. It also works fine if the navigation menu is enabled on the android device.


问:
Why is sympy.plot showing graph as ASCII?
I want to draw a simple graph but sympy is drawing it as ASCII text.
How can I show as an image (with lines)?

Image here

Tried different versions of python. Didn't change anything.


问:
Select a column of a condition in python pandas
I think that I'm cleaning my Data in a poor way.
What I need to do is return only a column of a conditional selection of my dataset.

As example:

Heading 1
Heading 2

12
34

99
42

I want to return Heading 2 for every Heading 1 that follow a condition.

What I'm doing is creating a temporary DataFrame:

df = df[df['Heading 1'] > 50]

Then I can get what I want just doing:

df['Heading 2']

But I can probably do it directly. I've tried something like

df['Heading 2'].where(df['Heading 1'] > 50])

But I dont think that that's the way - or maybe I've done something wrong.


问:
Federated Learning - Why does Global Model goes to 10k+?
I am currently working on a Personalized Federated Learning Project. Everything has been going well. I am getting around 95% of average local model accuracy and 93% for global model on a binary classification task. In addition, recall and precision are both returning good numbers. The exact details of the model can be found in this paper.

However! When considering the loss, the local models are at around 0.05~0.1, but the global model goes as high as 10k! Each time the global model aggregates the weights from local models, the loss goes higher and higher. Why is that?

This is my current model architecture:

```<code>def createModel(shape=(100,100,3)):
  tf.random.set_seed(3333)
  model = Sequential()
  model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=shape))
  model.add(layers.MaxPooling2D((2, 2)))
  model.add(layers.Conv2D(64, (3, 3), activation='relu'))
  model.add(layers.MaxPooling2D((2, 2)))
  model.add(layers.Conv2D(64, (3, 3), activation='relu'))
  model.add(layers.Flatten())
  model.add(layers.Dense(64, activation='relu'))
  model.add(layers.Dropout(0.3))
  model.add(layers.Dense(1, activation='sigmoid'))

  model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=[tf.keras.metrics.Recall(),
                       tf.keras.metrics.Precision(),
                       tf.keras.metrics.AUC(
                                                num_thresholds=200,
                                                curve='ROC',
                                                summation_method='interpolation',
                                                name=None,
                                                dtype=None,
                                                thresholds=None,
                                                multi_label=False,
                                                label_weights=None
                                            ),
                       'accuracy'])
  return model
</code>```

Dataset details:
Set of around 20,000 pictures of people either wearing masks or without masks.

Is this normal to happen in personalized federated learning environment? If not, any suggestions on where to look? Could it possibly be the model?

I have tried playing around with hyperparameters, for around 5 hours, they all returned same results.

Body:
I am currently working on a Personalized Federated Learning Project. Everything has been going well. I am getting around 95% of average local model accuracy and 93% for global model on a binary classification task. In addition, recall and precision are both returning good numbers. The exact details of the model can be found in this paper.

However! When considering the loss, the local models are at around 0.05~0.1, but the global model goes as high as 10k! Each time the global model aggregates the weights from local models, the loss goes higher and higher. Why is that?

This is my current model architecture:

def createModel(shape=(100,100,3)):
  tf.random.set_seed(3333)
  model = Sequential()
  model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=shape))
  model.add(layers.MaxPooling2D((2, 2)))
  model.add(layers.Conv2D(64, (3, 3), activation='relu'))
  model.add(layers.MaxPooling2D((2, 2)))
  model.add(layers.Conv2D(64, (3, 3), activation='relu'))
  model.add(layers.Flatten())
  model.add(layers.Dense(64, activation='relu'))
  model.add(layers.Dropout(0.3))
  model.add(layers.Dense(1, activation='sigmoid'))

  model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=[tf.keras.metrics.Recall(),
                       tf.keras.metrics.Precision(),
                       tf.keras.metrics.AUC(
                                                num_thresholds=200,
                                                curve='ROC',
                                                summation_method='interpolation',
                                                name=None,
                                                dtype=None,
                                                thresholds=None,
                                                multi_label=False,
                                                label_weights=None
                                            ),
                       'accuracy'])
  return model

Dataset details:
Set of around 20,000 pictures of people either wearing masks or without masks.

Is this normal to happen in personalized federated learning environment? If not, any suggestions on where to look? Could it possibly be the model?

I have tried playing around with hyperparameters, for around 5 hours, they all returned same results.


问:
Can I change the index pattern for a visualization in OpenSearch
OpenSearch is a fork of ElasticSearch, which includes things like Kibana built in.  According to this question Can I change the index pattern of a visualization in Kibana? in Kibana it was possible using some clever backend to change the index pattern used by a visualization.  AFAICT, this technique no longer works in current OpenSearch builds.

Does anybody know if this is possible without rebuilding the visualizations?


问:
Is it a security risk to publicly show a user's socket.io socket ID?
I have a React chatting application where I'm required to let my API know which socket connection called the API. Because of that, I need to reference the user's current socket ID somewhere on the client-side.

Would it be safe to store the user's socket ID in session storage, and would it matter if another user knew that user's current socket ID?

Would they be able to somehow use the stolen socket ID in their own socket connection to pretend they're them?


问:
How I can catch and save the error in the linux console when I run the .cpp file
I need to write a special programm -- Checker, which will run the transferred file in the compiler in the linux console, later it will output the result to the user, for example: "Correct answer", "Runtime error", "Incorrect answer", "Compilation error".I do not understand how to save the output of the user's program, as well as compilation errors that he may have

Now I have a small script that can run my file in compiler in console linux. There I see some compiler errors, but how i can save them IDK ((

```<code>#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>

using namespace std;
int main() {
   const char* one = "make ";
   const char* name = "check";
   char result[100];
   strcat(result,one);
   strcat(result,name);
   system(result);
}
</code>```

Body:
I need to write a special programm -- Checker, which will run the transferred file in the compiler in the linux console, later it will output the result to the user, for example: "Correct answer", "Runtime error", "Incorrect answer", "Compilation error".I do not understand how to save the output of the user's program, as well as compilation errors that he may have

Now I have a small script that can run my file in compiler in console linux. There I see some compiler errors, but how i can save them IDK ((

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>

using namespace std;
int main() {
   const char* one = "make ";
   const char* name = "check";
   char result[100];
   strcat(result,one);
   strcat(result,name);
   system(result);
}