问:
fastest way to create a new column with the index/id of the row based on a condition of another column - in panda / numpy
Hi I’m looking for help,
i watched a video on how to Loop Iterate over pandads dataframe and found it amazing that you can do it in micro seconds with numpy. I am using pycharrm with panda and numpy  packages and im trying to do the following scenario. If someone can help me tell me how I could do this…

Also is there a way to find out how long it took to execute get result.

```<code>
For rec id 0 =
Find id of value >= 1.17275  (which is <OPEN> + TakeProfit) in <HIGH>  Column starting from row 0. In example shown is in row id 4. Print id of result in <INDEX_LOC_POS_TARGET_PROFIT_HIT>

For rec id 1 =
Find id of value >= 1.17281  (which is <OPEN> + TakeProfit) in the <HIGH> Column starting from row 1. In example shown is in row id 5. Print id of result in <INDEX_LOC_POS_TARGET_PROFIT_HIT> for id 1

And so on for Rex Id 2…
I need to find results for all rows in datafrane until you reach the end of the data frame.

if no row found and and you reach end of data frame then print error for that row
</code>```

i would like this done in the fastest method, as i will want to use the script on a large data set. From my  understanding in Numpy you can do it in microseconds

```<code>
<id>    <DATE>    <TIME>    <OPEN>    <HIGH>    <LOW>        <CLOSE>    <INDEX_LOC_OF_TARGET_PROFIT_HIT>
0    2020.10.05    09:35:00    1.17265    1.17279    1.17265    1.17271    4
1    2020.10.05    09:36:00    1.17271    1.17271    1.17245    1.1725    5
2    2020.10.05    09:37:00    1.17249    1.17251    1.17245    1.17248    ...
3    2020.10.05    09:38:00    1.17249    1.17266    1.17249    1.17265    ...
4    2020.10.05    09:39:00    1.17265    1.17276    1.17235    1.17236    ...
5    2020.10.05    09:40:00    1.17234    1.17289    1.17234    1.17247    ...
6    2020.10.05    09:41:00    1.17247    1.17255    1.17247    1.17249    ...
7    2020.10.05    09:42:00    1.17249    1.17258    1.17245    1.17246    ...
8    2020.10.05    09:43:00    1.17246    1.1725    1.17238    1.17238    ...
9    2020.10.05    09:44:00    1.17238    1.17248    1.17238    1.17246    ...
</code>```

Thanks for your help.

df['<INDEX_LOC_POS_TARGET_PROFIT_HIT>'] = np.where(df[''] >= (np.where(df2['']) & (df2.index > df.index), df2.index, 'error'))

I expected that it would create a new column for each row with the index of the value found in column

Not sure the use of two data frames is required

Body:
Hi I’m looking for help,
i watched a video on how to Loop Iterate over pandads dataframe and found it amazing that you can do it in micro seconds with numpy. I am using pycharrm with panda and numpy  packages and im trying to do the following scenario. If someone can help me tell me how I could do this…

Also is there a way to find out how long it took to execute get result.

For rec id 0 =
Find id of value >= 1.17275  (which is <OPEN> + TakeProfit) in <HIGH>  Column starting from row 0. In example shown is in row id 4. Print id of result in <INDEX_LOC_POS_TARGET_PROFIT_HIT>

For rec id 1 =
Find id of value >= 1.17281  (which is <OPEN> + TakeProfit) in the <HIGH> Column starting from row 1. In example shown is in row id 5. Print id of result in <INDEX_LOC_POS_TARGET_PROFIT_HIT> for id 1

And so on for Rex Id 2…
I need to find results for all rows in datafrane until you reach the end of the data frame.

if no row found and and you reach end of data frame then print error for that row

i would like this done in the fastest method, as i will want to use the script on a large data set. From my  understanding in Numpy you can do it in microseconds

<id>    <DATE>    <TIME>    <OPEN>    <HIGH>    <LOW>        <CLOSE>    <INDEX_LOC_OF_TARGET_PROFIT_HIT>
0    2020.10.05    09:35:00    1.17265    1.17279    1.17265    1.17271    4
1    2020.10.05    09:36:00    1.17271    1.17271    1.17245    1.1725    5
2    2020.10.05    09:37:00    1.17249    1.17251    1.17245    1.17248    ...
3    2020.10.05    09:38:00    1.17249    1.17266    1.17249    1.17265    ...
4    2020.10.05    09:39:00    1.17265    1.17276    1.17235    1.17236    ...
5    2020.10.05    09:40:00    1.17234    1.17289    1.17234    1.17247    ...
6    2020.10.05    09:41:00    1.17247    1.17255    1.17247    1.17249    ...
7    2020.10.05    09:42:00    1.17249    1.17258    1.17245    1.17246    ...
8    2020.10.05    09:43:00    1.17246    1.1725    1.17238    1.17238    ...
9    2020.10.05    09:44:00    1.17238    1.17248    1.17238    1.17246    ...

Thanks for your help.

df['<INDEX_LOC_POS_TARGET_PROFIT_HIT>'] = np.where(df[''] >= (np.where(df2['']) & (df2.index > df.index), df2.index, 'error'))

I expected that it would create a new column for each row with the index of the value found in column

Not sure the use of two data frames is required


来源: stackexchange

问:
Azure Pipeline if exists function
Question:
Does Azure DevOps Pipeline have any sort of ifExist function to check if the branch exists in the Azure repository? - I want to check if the branch exists first before checking out the default branch, this is currently what I have,

```<code>parameters:
- name: branch
  default: main
  type: object

resources:
  repositories:
  - repository: esign_new_svc
    type: git
    name: InternalProjects/esign_new_svc
    ref: ${{ parameters.branch }}
</code>```

but if I put an inexistent branch, I see a pipeline failure with the error "sorry the branch doesn't exist"... I know that branch doesn't exist, but I don't want the pipeline to fail, I want to check out the default branch if given branch in parameters doesn't exist, simple as is.

Thanks

ContentLicense: CC BY-SA 4.0

Title: Azure Pipeline if exists function

Body:
Question:
Does Azure DevOps Pipeline have any sort of ifExist function to check if the branch exists in the Azure repository? - I want to check if the branch exists first before checking out the default branch, this is currently what I have,

parameters:
- name: branch
  default: main
  type: object

resources:
  repositories:
  - repository: esign_new_svc
    type: git
    name: InternalProjects/esign_new_svc
    ref: ${{ parameters.branch }}

but if I put an inexistent branch, I see a pipeline failure with the error "sorry the branch doesn't exist"... I know that branch doesn't exist, but I don't want the pipeline to fail, I want to check out the default branch if given branch in parameters doesn't exist, simple as is.

Thanks


问:
How can I fix gsutil config?
CommandException:Cannot back up existing config file "/home/aduseib/.boto": backup file exists ("/home/aduseib/.boto.bak").

I have searched but have not answers

Title: How can I fix gsutil config?


问:
I don't understand the "mb-sm-0" part in cards (bootstrap 5)?
I did get what I expected but the thing is that I don't quite understand that part which says mb-sm-0</p>
```<code><div class="row">
  <div class="col-lg-4 mb-3 mb-sm-0">
    <div class="card">
      <div class="card-body">
        <h5 class="card-title">Special title treatment</h5>
        <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
      </div>
    </div>
  </div>

</code>```

Body:
I did get what I expected but the thing is that I don't quite understand that part which says mb-sm-0

Special title treatment

With supporting text below as a natural lead-in to additional content.

        Go somewhere


问:
Android TextView displays ATM text as trademark symbol when using GT Haptik font
This is a weird one, maybe someone ran into this --

Android's plain TextView displays any text string that ends with TM as a trademark symbol. As shown below, the text has no formatting, just plain TextView.

This happens only when I use the GT Haptik font but not otherwise: the default font shows plain ATM, as it should.

The TextView doesn't transform (c) or (r), only xxxTM.

Microsoft Office (see picture) doesn't do that, with the same exact font file.

Any suggestions how to prevent this?

Thank you!


问:
Write data to firebase database
So I'm quite new to firebase and I have a project that I need to pass the name of equipment like the one on the picture. I already have a perfectly working real-time database but I can't write new data into it, even after changing the permissions.
This is what the equipment look like

What I need to happen is that when I click this button, the data, or atleast the name of the equipment should be pushed into the firebase database.
This should be  the button to be clicked to push data into firebase

Can someone tell me what is wrong with my code?

My code is stated below. After clicking the button, the name of the equipment should be added into a new portion of the database, just like in this picture:

.

But after using the codes below, nothing happens. Can someone tell me what I am doing wrong and what to do to correct it? Thank you.

```<code><script type="module">
    import {initializeApp} from "https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js";
    import {getDatabase, ref, set} from "https://www.gstatic.com/firebasejs/9.1.0/firebase-database.js";
    const firebaseConfig = { (insert my config here)
    }

    const app = initializeApp(firebaseConfig);
    const db = getDatabase(app);

    document.getElementById("cbutton").addEventListener('click', function writeUserData(equipts)
    {
        equipts = document.getElementsByClassName("shop-item-Description")
        set(ref(db, '/borrow-return/2023-0001'+ equipts), {
            equipments: equipts
        });
    }
        )
</script>
</code>```

Title: Write data to firebase database


问:
how to remove the messages that are being displayed on the (build,run) tab everytime I compile a C++ program in netbeans
most of the messages are useless for me and quite annoying

For example

"/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make[1]: Entering directory /c/Users/kostas/Documents/NetBeansProjects/CppApplication_2'
"/bin/make"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/cppapplication_2.exe
make[2]: Entering directory/c/Users/kostas/Documents/NetBeansProjects/CppApplication_2'
mkdir -p build/Debug/MinGW-Windows
rm -f build/Debug/MinGW-Windows/main.o.d
g++.exe    -c -g -I../../../../../MinGW/lib -MMD -MP -MF build/Debug/MinGW-Windows/main.o.d -o build/Debug/MinGW-Windows/main.o main.cpp
make[2]: Leaving directory /c/Users/kostas/Documents/NetBeansProjects/CppApplication_2'
make[1]: Leaving directory/c/Users/kostas/Documents/NetBeansProjects/CppApplication_2'

I don't need these things to be displayed, how to remove them completely?

ContentLicense: CC BY-SA 3.0


问:
How to build interactive way to learn SQL using Next.js and database?
I'm looking to see how can I make a next.js app that allows a user to learn SQL through interactive lessons. I would like the users to enter the SQL based on a couple instructions like a Codecademy or DataCamp course. Once the user submits the SQL code they entered it is then checked for correctness and the output is displayed in a separate table.

I'm just not sure on the SQL part. Is there a good way to allow a user to type a SQL query and run it against an actual database to see what the output would display? Any Ideas or thoughts on how to go about doing that? and what services you might use? How does Codecademy/DataCamp do it? I played with some Google Cloud SQL, BigQuery, and Supabase methods but found it difficult to send raw SQL to those platforms from client side.


问:
Laravel subdomain configuration on Centos 7 Apache Virtual Host
I was trying to use laravel subdomain on our centos 7 server. The server was using apache and using vhost, the website is up and running but the problem is that all pages that uses a subdomain is unreachable. After researching, I configure the vhost for the subdomain but still no luck.

This is the original configuration of the vhost.

```<code><VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    ServerAlias example.com

    DocumentRoot /var/www/html/example/public
    ErrorLog /var/www/html/example/storage/logs/error.log
    CustomLog /var/www/html/example/storage/logs/requests.log combine

    SSLEngine on
    SSLCertificateFile /etc/ssl/example/certificate.crt
    SSLCertificateKeyFile /etc/ssl/example/private.key
    SSLCertificateChainFile /etc/ssl/example/ca_bundle.crt
    <Directory /var/www/html/example>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>
</code>```

And here is the vhost after setting up the subdomain. I also try to use wildcard which also did not work

```<code><VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    ServerAlias example.com

    DocumentRoot /var/www/html/example/public
    ErrorLog /var/www/html/example/storage/logs/error.log
    CustomLog /var/www/html/example/storage/logs/requests.log combine

    SSLEngine on
    SSLCertificateFile /etc/ssl/example/certificate.crt
    SSLCertificateKeyFile /etc/ssl/example/private.key
    SSLCertificateChainFile /etc/ssl/example/ca_bundle.crt
    <Directory /var/www/html/example>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName subdomain.example.com
    Redirect / https://subdomain.example.com
</VirtualHost>

<VirtualHost *:443>
    ServerName subdomain.example.com
    ServerAlias subdomain.example.com
    #ServerAlias *.example.com

    DocumentRoot /var/www/html/example/public
    ErrorLog /var/www/html/example/storage/logs/error.log
    CustomLog /var/www/html/example/storage/logs/requests.log combine

    SSLEngine on
    SSLCertificateFile /etc/ssl/example/certificate.crt
    SSLCertificateKeyFile /etc/ssl/example/private.key
    SSLCertificateChainFile /etc/ssl/example/ca_bundle.crt
    <Directory /var/www/html/example>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>
</code>```

I also tried to add this subdomain to the list of the hosts which obviously did not work. I also double check the routes files and everything is fine and working locally. Here is my route configuration.

```<code>Route::middleware(['web', 'auth'])
                ->domain('subdomain.'.config('app.url'))
                ->as('subdomain.')
                ->group(base_path('routes/subdomain.php'));

Route::middleware(['web'])
                ->group(base_path('routes/web.php'));
</code>```

Body:
I was trying to use laravel subdomain on our centos 7 server. The server was using apache and using vhost, the website is up and running but the problem is that all pages that uses a subdomain is unreachable. After researching, I configure the vhost for the subdomain but still no luck.

This is the original configuration of the vhost.

<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    ServerAlias example.com

    DocumentRoot /var/www/html/example/public
    ErrorLog /var/www/html/example/storage/logs/error.log
    CustomLog /var/www/html/example/storage/logs/requests.log combine

    SSLEngine on
    SSLCertificateFile /etc/ssl/example/certificate.crt
    SSLCertificateKeyFile /etc/ssl/example/private.key
    SSLCertificateChainFile /etc/ssl/example/ca_bundle.crt
    <Directory /var/www/html/example>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>

And here is the vhost after setting up the subdomain. I also try to use wildcard which also did not work

<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    ServerAlias example.com

    DocumentRoot /var/www/html/example/public
    ErrorLog /var/www/html/example/storage/logs/error.log
    CustomLog /var/www/html/example/storage/logs/requests.log combine

    SSLEngine on
    SSLCertificateFile /etc/ssl/example/certificate.crt
    SSLCertificateKeyFile /etc/ssl/example/private.key
    SSLCertificateChainFile /etc/ssl/example/ca_bundle.crt
    <Directory /var/www/html/example>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName subdomain.example.com
    Redirect / https://subdomain.example.com
</VirtualHost>

<VirtualHost *:443>
    ServerName subdomain.example.com
    ServerAlias subdomain.example.com
    #ServerAlias *.example.com

    DocumentRoot /var/www/html/example/public
    ErrorLog /var/www/html/example/storage/logs/error.log
    CustomLog /var/www/html/example/storage/logs/requests.log combine

    SSLEngine on
    SSLCertificateFile /etc/ssl/example/certificate.crt
    SSLCertificateKeyFile /etc/ssl/example/private.key
    SSLCertificateChainFile /etc/ssl/example/ca_bundle.crt
    <Directory /var/www/html/example>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>

I also tried to add this subdomain to the list of the hosts which obviously did not work. I also double check the routes files and everything is fine and working locally. Here is my route configuration.

Route::middleware(['web', 'auth'])
                ->domain('subdomain.'.config('app.url'))
                ->as('subdomain.')
                ->group(base_path('routes/subdomain.php'));

Route::middleware(['web'])
                ->group(base_path('routes/web.php'));


问:
How to fix error expected string or bytes-like object
I tried to do text preprocessing with several steps. the last step for text preprocessing that I did was normalization and tokenization.

the code i use is as follows:

```<code>#--------Normalizing-------
normalizad_word = pd.read_excel("/content/colloquial.xlsx")

normalizad_word_dict = {}

for index, row in normalizad_word.iterrows():
    if row[0] not in normalizad_word_dict:
        normalizad_word_dict[row[0]] = row[1]

def normalized_term(document):
    result = []
    for term in document:
        if term in normalizad_word_dict:
            for word in normalizad_word_dict[term].split(' '):
                result.append(word)
        else:
            result.append(term)
    return result

dataset['review_normalized'] = dataset['single_char'].apply(normalized_term)

# NLTK word tokenize
def word_tokenize_wrapper(text):
    return word_tokenize(text)

dataset['review_tokens'] = dataset['review_normalized'].apply(word_tokenize_wrapper)
</code>```

But getting error like this:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-26-fe7f23995409> in <module>
     67     return word_tokenize(text)
     68
---> 69 dataset['review_tokens'] = dataset['review_normalized'].apply(word_tokenize_wrapper)
     70
     71 print('Result : \n')

14 frames
/usr/local/lib/python3.8/dist-packages/nltk/tokenize/punkt.py in _match_potential_end_contexts(self, text)
   1373         before_words = {}
   1374         matches = []
-> 1375         for match in reversed(list(self._lang_vars.period_context_re().finditer(text))):
   1376             # Ignore matches that have already been captured by matches to the right of this match
   1377             if matches and match.end() > before_start:

TypeError: expected string or bytes-like object

</code>```

does anyone know how to solve it? thank you so much.

Body:
I tried to do text preprocessing with several steps. the last step for text preprocessing that I did was normalization and tokenization.

the code i use is as follows:

#--------Normalizing-------
normalizad_word = pd.read_excel("/content/colloquial.xlsx")

normalizad_word_dict = {}

for index, row in normalizad_word.iterrows():
    if row[0] not in normalizad_word_dict:
        normalizad_word_dict[row[0]] = row[1]

def normalized_term(document):
    result = []
    for term in document:
        if term in normalizad_word_dict:
            for word in normalizad_word_dict[term].split(' '):
                result.append(word)
        else:
            result.append(term)
    return result

dataset['review_normalized'] = dataset['single_char'].apply(normalized_term)

# NLTK word tokenize
def word_tokenize_wrapper(text):
    return word_tokenize(text)

dataset['review_tokens'] = dataset['review_normalized'].apply(word_tokenize_wrapper)

But getting error like this:

TypeError                                 Traceback (most recent call last)
<ipython-input-26-fe7f23995409> in <module>
     67     return word_tokenize(text)
     68
---> 69 dataset['review_tokens'] = dataset['review_normalized'].apply(word_tokenize_wrapper)
     70
     71 print('Result : \n')

14 frames
/usr/local/lib/python3.8/dist-packages/nltk/tokenize/punkt.py in _match_potential_end_contexts(self, text)
   1373         before_words = {}
   1374         matches = []
-> 1375         for match in reversed(list(self._lang_vars.period_context_re().finditer(text))):
   1376             # Ignore matches that have already been captured by matches to the right of this match
   1377             if matches and match.end() > before_start:

TypeError: expected string or bytes-like object

does anyone know how to solve it? thank you so much.


问:
Issues with decompressing a .txt file with gzip on Windows
I am attempting to modify savedata in a video game in order to insert text (specifically ASCII art) in a level in such a way that it would normally not accept. In order to do this, I need to find the file where level data is stored (CCLocalLevels.dat), XOR decrypt the data with a key of 11 (0b), Base64 decode it, gunzip it (decompress with gzip), find the relevant part of the encrypted level data, Base64 decode that, gunzip that, find the needed portion, Base64 decode that, and there is the data I need to modify (see this youtube link: https://youtu.be/ObO48TouOpc?t=218, up until 4:29). I have found a tool which does a portion of this process, but I still needed to learn to use gzip. I installed some files that allow me to use its compression and decompression and set it up so it was usable with Command Prompt, but I am having trouble with decompressing. The string I need to decompress is as follows:

```<code>������\]K$
C=UB}
8c{\[#أ �)\*Q2;OK$RU/6Rٷ\~+kR\>/C\[
!-\[|\_CEB\~}0"$�i@FA7arq   LKg6'JVܸAz0\~)?K\>o?\~ewyGsV/e^ƾtK?CB\>d\>9IIHtDWxm#^bkRs3iaLĽ\>FJ2RKD✭&yCo.LKM ,(@\<^°�\<l1NֳE-&˶R"M=PI8H"OA!?yTIۿ?yautY3IaVL|M4)y\\⊦.3$֖1M    %k|�\_XR/EG^خZjtyKF E޲H�DV,oM㸋2O\]pY\>m}^N!:xITVȐg̔Yѧ4rJzG
a_q8֦loKJ{%Rb-
$@z\\yPQ.8yY-˪S5g\]"SyũSѪ ְPc\<V-SؑWBT F:0/tДNz�O7Isx{fIOa.qX 3MB#A-q#i&B\> Y\[
</code>```

(some aspects of the string seem to have been lost with the code block markup)

I saved it in a .txt file, but I am not sure if it is possible to decompress files using gzip if they are in this format.

The most obvious solution would be to save the .txt file as a .gz file instead and decompress it from there, but doing that gives me an error message saying that the file (named "gunzipfile") is "not in gzip format". Attempting to decompress the .txt file itself gives an error of

```<code>gunzipfile.txt: unknown suffix: -- ignored
</code>```

The commands I was using were

```<code>gzip -d gunzipfile.gz
</code>```

and

```<code>gzip -d gunzipfile.txt
</code>```

respectively. I am unfamiliar with gzip and possess only a basic understanding of command prompts and file compression, and this is my first question on Stack Exchange. I need to somehow be able to decompress this file, as seen, albeit not elaborated on, in the youtube video, but gzip seems to only capable of decompressing files already in its format, and when trying otherwise, it gives two different types of errors. I am using Windows 10, and I am not sure how python and MINGW64, as used in the video, affect this. His commands in the video are

```<code>python levelDebug/gunzip.py gunzipfile.gz
</code>```

and

```<code>python levelDebug/gunzip2.py gunzipfile.gz
</code>```

Help would be nice on how I am doing this wrong. Sorry if my question is confusing.

Body:
I am attempting to modify savedata in a video game in order to insert text (specifically ASCII art) in a level in such a way that it would normally not accept. In order to do this, I need to find the file where level data is stored (CCLocalLevels.dat), XOR decrypt the data with a key of 11 (0b), Base64 decode it, gunzip it (decompress with gzip), find the relevant part of the encrypted level data, Base64 decode that, gunzip that, find the needed portion, Base64 decode that, and there is the data I need to modify (see this youtube link: https://youtu.be/ObO48TouOpc?t=218, up until 4:29). I have found a tool which does a portion of this process, but I still needed to learn to use gzip. I installed some files that allow me to use its compression and decompression and set it up so it was usable with Command Prompt, but I am having trouble with decompressing. The string I need to decompress is as follows:

������\]K$
C=UB}
8c{\[#أ �)\*Q2;OK$RU/6Rٷ\~+kR\>/C\[
!-\[|\_CEB\~}0"$�i@FA7arq   LKg6'JVܸAz0\~)?K\>o?\~ewyGsV/e^ƾtK?CB\>d\>9IIHtDWxm#^bkRs3iaLĽ\>FJ2RKD✭&yCo.LKM ,(@\<^°�\<l1NֳE-&˶R"M=PI8H"OA!?yTIۿ?yautY3IaVL|M4)y\\⊦.3$֖1M    %k|�\_XR/EG^خZjtyKF E޲H�DV,oM㸋2O\]pY\>m}^N!:xITVȐg̔Yѧ4rJzG
a_q8֦loKJ{%Rb-
$@z\\yPQ.8yY-˪S5g\]"SyũSѪ ְPc\<V-SؑWBT F:0/tДNz�O7Isx{fIOa.qX 3MB#A-q#i&B\> Y\[

(some aspects of the string seem to have been lost with the code block markup)

I saved it in a .txt file, but I am not sure if it is possible to decompress files using gzip if they are in this format.

The most obvious solution would be to save the .txt file as a .gz file instead and decompress it from there, but doing that gives me an error message saying that the file (named "gunzipfile") is "not in gzip format". Attempting to decompress the .txt file itself gives an error of

gunzipfile.txt: unknown suffix: -- ignored

The commands I was using were

gzip -d gunzipfile.gz

and

gzip -d gunzipfile.txt

respectively. I am unfamiliar with gzip and possess only a basic understanding of command prompts and file compression, and this is my first question on Stack Exchange. I need to somehow be able to decompress this file, as seen, albeit not elaborated on, in the youtube video, but gzip seems to only capable of decompressing files already in its format, and when trying otherwise, it gives two different types of errors. I am using Windows 10, and I am not sure how python and MINGW64, as used in the video, affect this. His commands in the video are

python levelDebug/gunzip.py gunzipfile.gz

and

python levelDebug/gunzip2.py gunzipfile.gz

Help would be nice on how I am doing this wrong. Sorry if my question is confusing.


问:
@Field(type=FieldType.keyword) being ignored on certain properties on ES
I used spring boot 2.2.4-RELEAS with elasticsearc 6.8.6 and spring-boot-starter-data-elasticsearch 3.2.4.

When i created my Document

```<code>
    @Id
    private String transactionId;

    @Field(type = FieldType.Float)
    private BigDecimal amount = new BigDecimal("0");

    @Field(type = FieldType.Float)
    private BigDecimal fees = new BigDecimal("0");

    @Field(type = FieldType.Float) // final amount given to the user
    private BigDecimal total = new BigDecimal("0");

    @Field(type = FieldType.Float)
    private BigDecimal priceinEuro = new BigDecimal("0");

    @Field(type = FieldType.Keyword)
    private String currency;

    @Field(type = FieldType.Date)
    private Date garaTransactionDate;

    @Field(type = FieldType.Date)
    private Date providerTransactionDate;

    @Field(type = FieldType.Boolean)
    private Boolean isCashIn = false;

    @Field(type = FieldType.Keyword)
    private String action;

    @Field(type = FieldType.Keyword)
    private String status;

    //game or ebook
    @Field(type = FieldType.Keyword)
    private String type;

    @Field(type = FieldType.Integer)
    private Long contentId;  //ebook or apk id

    @Field(type = FieldType.Keyword)
    private String provider;

    @Field(type = FieldType.Keyword)
    private String appUserId;

    @Field(type = FieldType.Keyword)
    private String countryCode;

}
</code>```

I don't know why status is not defined as keyword in elastic search. Even in the mapping, it is recognized as text

```<code>  "appusertransaction" : {
    "mappings" : {
      "properties" : {
        "action" : {
          "type" : "text"
        },
        "amount" : {
          "type" : "float"
        },
        "appUserId" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "contentId" : {
          "type" : "long"
        },
        "countryCode" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "currency" : {
          "type" : "text"
        },
        "fees" : {
          "type" : "float"
        },
        "garaTransactionDate" : {
          "type" : "date"
        },
        "isCashIn" : {
          "type" : "boolean"
        },
        "priceinEuro" : {
          "type" : "float"
        },
        "provider" : {
          "type" : "text"
        },
        "providerTransactionDate" : {
          "type" : "date"
        },
        "status" : {
          "type" : "text"
        },
        "total" : {
          "type" : "float"
        },
        "transactionId" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "type" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}
</code>```

What is wrong ? Even currency, provider are also mapped just as Text.

Thanks.

Body:
I used spring boot 2.2.4-RELEAS with elasticsearc 6.8.6 and spring-boot-starter-data-elasticsearch 3.2.4.

When i created my Document

    @Id
    private String transactionId;

    @Field(type = FieldType.Float)
    private BigDecimal amount = new BigDecimal("0");

    @Field(type = FieldType.Float)
    private BigDecimal fees = new BigDecimal("0");

    @Field(type = FieldType.Float) // final amount given to the user
    private BigDecimal total = new BigDecimal("0");

    @Field(type = FieldType.Float)
    private BigDecimal priceinEuro = new BigDecimal("0");

    @Field(type = FieldType.Keyword)
    private String currency;

    @Field(type = FieldType.Date)
    private Date garaTransactionDate;

    @Field(type = FieldType.Date)
    private Date providerTransactionDate;

    @Field(type = FieldType.Boolean)
    private Boolean isCashIn = false;

    @Field(type = FieldType.Keyword)
    private String action;

    @Field(type = FieldType.Keyword)
    private String status;

    //game or ebook
    @Field(type = FieldType.Keyword)
    private String type;

    @Field(type = FieldType.Integer)
    private Long contentId;  //ebook or apk id

    @Field(type = FieldType.Keyword)
    private String provider;

    @Field(type = FieldType.Keyword)
    private String appUserId;

    @Field(type = FieldType.Keyword)
    private String countryCode;

}

I don't know why status is not defined as keyword in elastic search. Even in the mapping, it is recognized as text

  "appusertransaction" : {
    "mappings" : {
      "properties" : {
        "action" : {
          "type" : "text"
        },
        "amount" : {
          "type" : "float"
        },
        "appUserId" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "contentId" : {
          "type" : "long"
        },
        "countryCode" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "currency" : {
          "type" : "text"
        },
        "fees" : {
          "type" : "float"
        },
        "garaTransactionDate" : {
          "type" : "date"
        },
        "isCashIn" : {
          "type" : "boolean"
        },
        "priceinEuro" : {
          "type" : "float"
        },
        "provider" : {
          "type" : "text"
        },
        "providerTransactionDate" : {
          "type" : "date"
        },
        "status" : {
          "type" : "text"
        },
        "total" : {
          "type" : "float"
        },
        "transactionId" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "type" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

What is wrong ? Even currency, provider are also mapped just as Text.

Thanks.


问:
abort Axios request in React apps using async/await while catch error
So i have try to use abortController to cancel all the async request when changing pages, at first it works finely but when i try to catch the error and move to other pages i keep getting this error:

Can't perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix,
cancel all subscriptions and asynchronous tasks in a useEffect cleanup
function.at KSBT (http://localhost:3000/static/js/bundle.js:7724:76)

i try to seek an answer through it but not found any solution to that, the only answer i found is this:

How to abort Axios request in React apps using async/await?

yet its not solving any of my issue, here is my code:

```<code>  useEffect(() => {
    let abortController;

    (async () => {
      try {
        abortController = new AbortController();
        let signal = abortController.signal;
        const { data } = await api.post(
          "/api/master/list_ksbt",
          { page, limit, order, search },
          { signal: signal }
        );

        if (data) {
          setDataRes({
            status: data.status,
            data: data.data,
            message: data.message,
          });
          setData(data.data.data);
          setTotal(data.data.recordsFiltered);
          setTimeout(() => {
            setLoading(false);
          }, 1000);
        }
      } catch (error) {
        console.log("====================================");
        console.log(error);
        setData([]);
        setTimeout(() => {
          setLoading(false);
        }, 1000);
        console.log("====================================");
      }
      return () => abortController.abort();
      // await dispatch(
      //   dataService.getKSBT(page, limit, order, search, signal)
      // ).then((response) => {

      //   if (response.status) {
      //     setDataRes({
      //       status: response.data.status,
      //       data: response.data.data,
      //       message: response.data.message,
      //     });
      //     setData(response.data.data.data);
      //     setTotal(response.data.data.recordsFiltered);
      //     setTimeout(() => {
      //       setLoading(false);
      //     }, 1000);
      //   } else {
      //     setData("");
      //   }
      // });
    })();

        return () => abortController.abort();
      }, [page, limit, order, search, dispatch]);
</code>```

can someone tell me or at least pointing out where to improve or where is the problem actually located...

Body:
So i have try to use abortController to cancel all the async request when changing pages, at first it works finely but when i try to catch the error and move to other pages i keep getting this error:

Can't perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix,
cancel all subscriptions and asynchronous tasks in a useEffect cleanup
function.at KSBT (http://localhost:3000/static/js/bundle.js:7724:76)

i try to seek an answer through it but not found any solution to that, the only answer i found is this:

How to abort Axios request in React apps using async/await?

yet its not solving any of my issue, here is my code:

  useEffect(() => {
    let abortController;

    (async () => {
      try {
        abortController = new AbortController();
        let signal = abortController.signal;
        const { data } = await api.post(
          "/api/master/list_ksbt",
          { page, limit, order, search },
          { signal: signal }
        );

        if (data) {
          setDataRes({
            status: data.status,
            data: data.data,
            message: data.message,
          });
          setData(data.data.data);
          setTotal(data.data.recordsFiltered);
          setTimeout(() => {
            setLoading(false);
          }, 1000);
        }
      } catch (error) {
        console.log("====================================");
        console.log(error);
        setData([]);
        setTimeout(() => {
          setLoading(false);
        }, 1000);
        console.log("====================================");
      }
      return () => abortController.abort();
      // await dispatch(
      //   dataService.getKSBT(page, limit, order, search, signal)
      // ).then((response) => {

      //   if (response.status) {
      //     setDataRes({
      //       status: response.data.status,
      //       data: response.data.data,
      //       message: response.data.message,
      //     });
      //     setData(response.data.data.data);
      //     setTotal(response.data.data.recordsFiltered);
      //     setTimeout(() => {
      //       setLoading(false);
      //     }, 1000);
      //   } else {
      //     setData("");
      //   }
      // });
    })();

        return () => abortController.abort();
      }, [page, limit, order, search, dispatch]);

can someone tell me or at least pointing out where to improve or where is the problem actually located...


问:
Can you replace an xml drawable with a png image?
Actually it's a shape

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="#ff9a0302" android:endColor="#ff14366c" android:angle="135.0" android:type="linear" android:centerColor="#ff000000" />
</shape>
</code>```

anything i tried crashed

Body:
Actually it's a shape

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="#ff9a0302" android:endColor="#ff14366c" android:angle="135.0" android:type="linear" android:centerColor="#ff000000" />
</shape>

anything i tried crashed


问:
"Exception has occurred: RuntimeError: grad can be implicitly created only for scalar outputs" when computing the Hessian Function
I am trying to recreate the Per-FedAvg function with Pytorch, I am using the MNIST dataset to train the Resnet18 network with seperated dataset as following:

```<code>Load data
transform = tv.transforms.Compose([tv.transforms.ToTensor(), tv.transforms.Normalize(0.1307, 0.3081)])
trainset = tv.datasets.MNIST(root='C:/data1', train=True, download=True, transform=transform)
testset = tv.datasets.MNIST(root='C:/data0', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)

Split data
temp = [len(trainset)//size for i in range(size)]
temp[-1] = len(trainset) - sum(temp[:-1])
Worker_data = torch.utils.data.random_split(trainset, temp)
train_loader = [None]*size
for i in range(size):
train_loader[i] = torch.utils.data.DataLoader(Worker_data[i], batch_size=64, shuffle=True)

</code>```

Each client have its dataset implement to the train function. However, the error has been occured when computing the hessian, the hessian function like this:

```<code>def get_hessian(device, dataseq, model):
    loss_fn = torch.nn.CrossEntropyLoss()
    index = np.random.randint(0, high=len(dataseq), size=None, dtype=int)
    data, target = dataseq[index]
    data = data.to(device)
    target = target.to(device)
    output, _ = model(data)
    loss = loss_fn(output, target)
    grads = torch.autograd.grad(loss, model.parameters(), retain_graph=True, create_graph=True)

    hessian_params = []
    for k in range(len(grads)):
        hess_params = torch.zeros_like(grads[k])
        for i in range(grads[k].size(0)):
            if len(grads[k].size()) == 2:
                for j in range(grads[k].size(1)):
                    hess_params[i, j] = torch.autograd.grad(grads[k][i][j], model.parameters(), retain_graph=True)[k][i, j]
            else:
                hess_params[i] = torch.autograd.grad(grads[k][i], model.parameters(), retain_graph=True)[k][i]
        hessian_params.append(hess_params)

    return hessian_params
</code>```

The error has been raised on the torch.autograd.grad as following:

```<code>grad can be implicitly created only for scalar outputs
  File "E:\FYP\Per_FedAvg_test.py", line 115, in get_hessian
    hess_params[i] = torch.autograd.grad(grads[k][i], model.parameters(), retain_graph=True)[k][i]
  File "E:\FYP\Per_FedAvg_test.py", line 57, in train
    hessian_params = get_hessian(device, data, original_model)
  File "E:\FYP\Per_FedAvg_test.py", line 152, in main
    out_weight = train(rank, init_model, lr, train_loader[rank], device, local_epoch, alpha, beta)
  File "E:\FYP\Per_FedAvg_test.py", line 177, in <module>
    main()
</code>```

What is the problem?

By the way, I am using Pytorch 1.8 as this is my project limitation.

Body:
I am trying to recreate the Per-FedAvg function with Pytorch, I am using the MNIST dataset to train the Resnet18 network with seperated dataset as following:

Load data
transform = tv.transforms.Compose([tv.transforms.ToTensor(), tv.transforms.Normalize(0.1307, 0.3081)])
trainset = tv.datasets.MNIST(root='C:/data1', train=True, download=True, transform=transform)
testset = tv.datasets.MNIST(root='C:/data0', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)

Split data
temp = [len(trainset)//size for i in range(size)]
temp[-1] = len(trainset) - sum(temp[:-1])
Worker_data = torch.utils.data.random_split(trainset, temp)
train_loader = [None]*size
for i in range(size):
train_loader[i] = torch.utils.data.DataLoader(Worker_data[i], batch_size=64, shuffle=True)

Each client have its dataset implement to the train function. However, the error has been occured when computing the hessian, the hessian function like this:

def get_hessian(device, dataseq, model):
    loss_fn = torch.nn.CrossEntropyLoss()
    index = np.random.randint(0, high=len(dataseq), size=None, dtype=int)
    data, target = dataseq[index]
    data = data.to(device)
    target = target.to(device)
    output, _ = model(data)
    loss = loss_fn(output, target)
    grads = torch.autograd.grad(loss, model.parameters(), retain_graph=True, create_graph=True)

    hessian_params = []
    for k in range(len(grads)):
        hess_params = torch.zeros_like(grads[k])
        for i in range(grads[k].size(0)):
            if len(grads[k].size()) == 2:
                for j in range(grads[k].size(1)):
                    hess_params[i, j] = torch.autograd.grad(grads[k][i][j], model.parameters(), retain_graph=True)[k][i, j]
            else:
                hess_params[i] = torch.autograd.grad(grads[k][i], model.parameters(), retain_graph=True)[k][i]
        hessian_params.append(hess_params)

    return hessian_params

The error has been raised on the torch.autograd.grad as following:

grad can be implicitly created only for scalar outputs
  File "E:\FYP\Per_FedAvg_test.py", line 115, in get_hessian
    hess_params[i] = torch.autograd.grad(grads[k][i], model.parameters(), retain_graph=True)[k][i]
  File "E:\FYP\Per_FedAvg_test.py", line 57, in train
    hessian_params = get_hessian(device, data, original_model)
  File "E:\FYP\Per_FedAvg_test.py", line 152, in main
    out_weight = train(rank, init_model, lr, train_loader[rank], device, local_epoch, alpha, beta)
  File "E:\FYP\Per_FedAvg_test.py", line 177, in <module>
    main()

What is the problem?

By the way, I am using Pytorch 1.8 as this is my project limitation.


问:
MS Graph API - List channels API doesn't return full list of channels

I'm trying to list all the channels with a specific team. However, there are some missing channels in the API response. There are 30 "active" private channels (as the creation limit) in my team, and it shows correctly in Microsoft Teams application. But when I list channels with API, it only response 24 private channels and there is no @odata.nextLink in the response. The same scenario happens when I list standard channels in that team.

Here is the format I send the request:
GET /teams/{team-id}/channels?$filter=membershipType eq 'private'

I tried to use /allChannels API as well, but it still acts like /channels API.

Below is the additional information:

tenant-id: dcb0e1d1-6cde-4420-a658-ede52a8bead1

team-id: bccdf0a4-ae60-45bc-8d4c-bd63a3106000

request-id: 7bdadf71-729a-49dc-b677-769fbec2d91a

client-request-id: 7bdadf71-729a-49dc-b677-769fbec2d91a

Date: Thu, 05 Jan 2023 02:15:26 GMT

Thank you.


问:
How do I make the icons bigger in rule designer for the decision table?
I am using Eclipse version 2020-06 with IBM ODM Rule Designer v 8.11.0.1 installed.
I realise that the icons are very small as shown below:

I am not sure how to enlarge it. I tried to explore the settings on eclipse (Window > Preferences) and also to uninstall the rule designer and install back and update it. Yet, the issue is still not resolved. Can anyone help me, please?


问:
Is there any public protocol standard for such requests browser sends to the os?
I have an idea to restrict the selection of files in the selection window that are larger than the specified file size from being selected.

And all results I have searched like this code which only can do this in the browser.

const maxSize = 1024 * 1024 * 10; // 10MB

fileInput.addEventListener('change', () => {
  const file = fileInput.files[0];
  if (file.size > maxSize) {
    alert('Error: File is too large. Please choose a file less than 10MB.');
  }
  // ...
});

```
<p>However, I find a cool attribute called <em>accept</em>.</p>
<p>The <em>accept</em> attribute of the input tag in the html tag controls the client's selection window.
For example, I can use the follow code allows you to only select jpg files <strong>in the selection window.</strong></p>
<pre class="lang-js prettyprint-override"><code><input type="file" accept=".jpg" />
</code>```

I searched for the implementation principle and got the result that the browser sends a request to os.
But when I continue to search the request implementation, I got nothing.

Is there a similar browser api that can do this, affecting the client's (os) selection window, and is there a public protocol standard for such requests?

Body:
I have an idea to restrict the selection of files in the selection window that are larger than the specified file size from being selected.

And all results I have searched like this code which only can do this in the browser.

const maxSize = 1024 * 1024 * 10; // 10MB

fileInput.addEventListener('change', () => {
  const file = fileInput.files[0];
  if (file.size > maxSize) {
    alert('Error: File is too large. Please choose a file less than 10MB.');
  }
  // ...
});

However, I find a cool attribute called accept.

The accept attribute of the input tag in the html tag controls the client's selection window.
For example, I can use the follow code allows you to only select jpg files in the selection window.

<input type="file" accept=".jpg" />

I searched for the implementation principle and got the result that the browser sends a request to os.
But when I continue to search the request implementation, I got nothing.

Is there a similar browser api that can do this, affecting the client's (os) selection window, and is there a public protocol standard for such requests?


问:
Creating New Invoice Line if Item Count is Non-Zero
I'm attempting to create a Google Sheet that automatically adds lines to an invoice based on data inputted into a table. This is for a vending machine, so when filling, I would like to add a number to the Units Sold column on the "Products" sheet. To send the invoice, I would like each item with a non-zero Units Sold to be added to the more aesthetically pleasing "Invoice" sheet.

Here is a link to the Sheet I have started tinkering with: https://docs.google.com/spreadsheets/d/1_VBPxOVIfnHYqqrZHxaXdqW-Q5JcPSYS4fu5VeLYcho/edit?usp=sharing

Is this idea possible using scripts in Google Sheets?


问:
Python won't recognize .mpy files
I followed a guide online to compile C code to .mpy files for micropython on the esp32.

I did this by creating a dockerfile to create my work environment:

```<code>  FROM ubuntu:23.04

  RUN apt-get update
  RUN apt-get -y install git wget flex bison gperf python3 python3-pip \
      python3-setuptools cmake ninja-build ccache libffi-dev libssl-dev dfu-util
  RUN apt-get -y install python-is-python3 python3 python3-pip

  RUN pip3 install pyelftools>=0.29

  WORKDIR /src/esp
  RUN git clone -b v4.4.3 --recursive https://github.com/espressif/esp-idf.git
  RUN git clone https://github.com/micropython/micropython.git

  WORKDIR /src/esp/esp-idf
  RUN ./install.sh
  RUN echo "#! /bin/bash\n. /src/esp/esp-idf/export.sh" > esp32_idf
  RUN chown 777 esp32_idf
  RUN chmod +x esp32_idf
  ENV PATH="${PATH}:/src/esp/esp-idf/"

  WORKDIR /src/esp/micropython/mpy-cross
  RUN make
  ENV PATH="${PATH}:/src/esp/micropython/mpy-cross/build/"

  WORKDIR /src/esp/bin
  RUN wget https://github.com/espressif/crosstool-NG/releases/download/esp-2022r1/xtensa-esp32-elf-gcc11_2_0-esp-2022r1-linux-amd64.tar.xz
  RUN tar -xvf xtensa-esp32-elf-gcc11_2_0-esp-2022r1-linux-amd64.tar.xz
  ENV PATH="${PATH}:/src/xtensa-esp32-elf/bin"

  WORKDIR /src/mylib
</code>```

I then built and ran the image using

docker build -t mpy-lib-builder:t1 .
docker run -it --rm -v "$(pwd)"/lib:/src/mylib mpy-lib-builder:t1 bash
```
<p>I then copied some files from the micropython examples that can be seen here. I wanteed to use womthing pre-written to test it out. I updated the Makefile to use <code>ARCH = xtensawin</code> (which I am told is the one to use for the esp32 board).</p>
<p>Inside the docker container, I ran the make command, which produced the files:</p>
```-lib/
--features0.mpy
--features0.c
--Makefile
--build/
---features0.config.h
---features0.native.mpy
---features0.o
```

I moved all these files and folder to the root directory of my main application. I then flashed the application to my esp32. When I try to import features0, I get ImportError: no module named 'features0'. Everything else, including other *.py files import just fine. Any ideas what I am doing wrong?

If anyone wants the source code to try it out, just ask and I'll push it to a public repo.

Title: Python won't recognize .mpy files

Body:
I followed a guide online to compile C code to .mpy files for micropython on the esp32.

I did this by creating a dockerfile to create my work environment:

  FROM ubuntu:23.04

  RUN apt-get update
  RUN apt-get -y install git wget flex bison gperf python3 python3-pip \
      python3-setuptools cmake ninja-build ccache libffi-dev libssl-dev dfu-util
  RUN apt-get -y install python-is-python3 python3 python3-pip

  RUN pip3 install pyelftools>=0.29

  WORKDIR /src/esp
  RUN git clone -b v4.4.3 --recursive https://github.com/espressif/esp-idf.git
  RUN git clone https://github.com/micropython/micropython.git

  WORKDIR /src/esp/esp-idf
  RUN ./install.sh
  RUN echo "#! /bin/bash\n. /src/esp/esp-idf/export.sh" > esp32_idf
  RUN chown 777 esp32_idf
  RUN chmod +x esp32_idf
  ENV PATH="${PATH}:/src/esp/esp-idf/"

  WORKDIR /src/esp/micropython/mpy-cross
  RUN make
  ENV PATH="${PATH}:/src/esp/micropython/mpy-cross/build/"

  WORKDIR /src/esp/bin
  RUN wget https://github.com/espressif/crosstool-NG/releases/download/esp-2022r1/xtensa-esp32-elf-gcc11_2_0-esp-2022r1-linux-amd64.tar.xz
  RUN tar -xvf xtensa-esp32-elf-gcc11_2_0-esp-2022r1-linux-amd64.tar.xz
  ENV PATH="${PATH}:/src/xtensa-esp32-elf/bin"

  WORKDIR /src/mylib

I then built and ran the image using

docker build -t mpy-lib-builder:t1 .
docker run -it --rm -v "$(pwd)"/lib:/src/mylib mpy-lib-builder:t1 bash

I then copied some files from the micropython examples that can be seen here. I wanteed to use womthing pre-written to test it out. I updated the Makefile to use ARCH = xtensawin (which I am told is the one to use for the esp32 board).

Inside the docker container, I ran the make command, which produced the files:

-lib/
--features0.mpy
--features0.c
--Makefile
--build/
---features0.config.h
---features0.native.mpy
---features0.o

I moved all these files and folder to the root directory of my main application. I then flashed the application to my esp32. When I try to import features0, I get ImportError: no module named 'features0'. Everything else, including other *.py files import just fine. Any ideas what I am doing wrong?

If anyone wants the source code to try it out, just ask and I'll push it to a public repo.


问:
Getting error while scraping data from Yahoo Finance using Google Apps Script
I am trying to get a value from Yahoo Finance using Google Apps Script and Cheerio Library. In the following screenshot, I want to get table last row value Long Term Debt (2,466,000):

The following answer is proposed from this source to get the required value:

```<code>function pressReleases() {
  var url = 'https://finance.yahoo.com/quote/AMD/balance-sheet?p=AMD'
  var html = UrlFetchApp.fetch(url).getContentText().match(/root.App.main = ([\s\S\w]+?);\n/);
  if (!html || html.length == 1) return;
  var obj = JSON.parse(html[1].trim());

  const { _cs, _cr } = obj;
  if (!_cs || !_cr) return;
  const key = CryptoJS.algo.PBKDF2.create({ keySize: 8 }).compute(_cs, JSON.parse(_cr)).toString();
  const obj2 = JSON.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(obj.context.dispatcher.stores, key)));
  var res = obj2.QuoteSummaryStore.balanceSheetHistoryQuarterly.balanceSheetStatements[0].longTermDebt.raw/1000;

  return res || "No value";
}
</code>```

However after running this script, I am getting the following error:

CryptoJS is not defined

I suppose, there is some library that needs to be added in order to make it work, Any help would be much appreciated to get it running. Thank you

Body:
I am trying to get a value from Yahoo Finance using Google Apps Script and Cheerio Library. In the following screenshot, I want to get table last row value Long Term Debt (2,466,000):

The following answer is proposed from this source to get the required value:

function pressReleases() {
  var url = 'https://finance.yahoo.com/quote/AMD/balance-sheet?p=AMD'
  var html = UrlFetchApp.fetch(url).getContentText().match(/root.App.main = ([\s\S\w]+?);\n/);
  if (!html || html.length == 1) return;
  var obj = JSON.parse(html[1].trim());

  const { _cs, _cr } = obj;
  if (!_cs || !_cr) return;
  const key = CryptoJS.algo.PBKDF2.create({ keySize: 8 }).compute(_cs, JSON.parse(_cr)).toString();
  const obj2 = JSON.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(obj.context.dispatcher.stores, key)));
  var res = obj2.QuoteSummaryStore.balanceSheetHistoryQuarterly.balanceSheetStatements[0].longTermDebt.raw/1000;

  return res || "No value";
}

However after running this script, I am getting the following error:

CryptoJS is not defined

I suppose, there is some library that needs to be added in order to make it work, Any help would be much appreciated to get it running. Thank you


问:
Getting values from inner class in a method
I am trying to get the values of an inner class.
I believe I am doing this wrong because I am getting a null value.
Basically I wanted to get values of two hashsets. So I created a class to store those values and I have method to feed those values which returns the inner class.</p>
```<code>outter class {
//some code

public myFunction(...){

//This method getAllResults should returns the class that have the sets stored
MyInnerClass allResult = getAllResults(resultSets);
Set<People> visiblePeople = allResult.visibleInfo;
 Set<People> allPeopleFromTable = allResult.allPeople;
}

//Using Lombok here
  @Data
    private class MyInnerClass {
        private Set<People> allPeople;
        private Set<People> visibleInfo;
    }

private MyInnerClass getAllResults(Foo resultSets) {

MyInnerClass inner = new MyInnerClass();

        for (Foo rs : resultSets) {
            while (rs.next()) {
                final Table people = new Table(rs);

                inner.allPeople.add(people);
                if (isVisible(people)) {
                    inner.visibleInfo.add(people);
                }
            }
        }
return inner;
}

}

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

Body:
I am trying to get the values of an inner class.
I believe I am doing this wrong because I am getting a null value.
Basically I wanted to get values of two hashsets. So I created a class to store those values and I have method to feed those values which returns the inner class.

outter class {
//some code

public myFunction(...){

//This method getAllResults should returns the class that have the sets stored
MyInnerClass allResult = getAllResults(resultSets);
Set<People> visiblePeople = allResult.visibleInfo;
 Set<People> allPeopleFromTable = allResult.allPeople;
}

//Using Lombok here
  @Data
    private class MyInnerClass {
        private Set<People> allPeople;
        private Set<People> visibleInfo;
    }

private MyInnerClass getAllResults(Foo resultSets) {

MyInnerClass inner = new MyInnerClass();

        for (Foo rs : resultSets) {
            while (rs.next()) {
                final Table people = new Table(rs);

                inner.allPeople.add(people);
                if (isVisible(people)) {
                    inner.visibleInfo.add(people);
                }
            }
        }
return inner;
}

}


问:
How to get value from keyboard when running program with path ci/cd
I have a code file (run_data_flow.py) with a style function like this:

```<code>def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
            It must be "yes" (the default), "no" or None (meaning
            an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
</code>```

And I have another run_test.py file to run the above code file like this:

```<code>def run_etl(table, date):
    command = f"cd {PROJECT_ROOT}; " \
              f"export PYTHONPATH={PROJECT_ROOT}:$PYTHONPATH; " \
              f"python3 -u testing/etl/run_data_flow.py " \
              f"--table {table} " \
              f"--date {date}"
    print(datetime.now(), command)
    run_status = os.popen(f"{command}; echo $?").read().strip().split('\n')[-1]
    if run_status != '0':
        print(f"JOB FAILED: {run_status}")
        raise exit(1)
</code>```

But when running the file run_test.py with the parameters passed, the input input step from the keyboard seems to have been skipped.
What is its true nature?

Body:
I have a code file (run_data_flow.py) with a style function like this:

def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
            It must be "yes" (the default), "no" or None (meaning
            an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

And I have another run_test.py file to run the above code file like this:

def run_etl(table, date):
    command = f"cd {PROJECT_ROOT}; " \
              f"export PYTHONPATH={PROJECT_ROOT}:$PYTHONPATH; " \
              f"python3 -u testing/etl/run_data_flow.py " \
              f"--table {table} " \
              f"--date {date}"
    print(datetime.now(), command)
    run_status = os.popen(f"{command}; echo $?").read().strip().split('\n')[-1]
    if run_status != '0':
        print(f"JOB FAILED: {run_status}")
        raise exit(1)

But when running the file run_test.py with the parameters passed, the input input step from the keyboard seems to have been skipped.
What is its true nature?


问:
Uncaught SyntaxError: Invalid or unexpected token (at react.js?v=ce04ce93:1:1)
I have this error on my react app anytime I start the server.
i do not know what is wrong here, can some help me out

i was expecting my react app to render properly

Below is the error i usually encounter when i start the development

```<code>Uncaught SyntaxError: Invalid or unexpected token (at react.js?v=ce04ce93:1:1)
</code>```

Body:
I have this error on my react app anytime I start the server.
i do not know what is wrong here, can some help me out

i was expecting my react app to render properly

Below is the error i usually encounter when i start the development

Uncaught SyntaxError: Invalid or unexpected token (at react.js?v=ce04ce93:1:1)


问:
Swift Firebase setting data error, cannot add .collection to query
I am trying to set data in my Firestore database. I want to find a document in a collection using the where method and then navigates to its sub collection and set data. I think I'm getting an error because the where the method returns a query that doesn't have a .collection. Does anyone know how I can reformat this code so it performs such an action?</p>
```<code>let placeHolder = ["place": ""]
let document = Firestore.firestore().collection("tweets").whereField("uid", isEqualTo: uid).collection("comments").document("hello")

document.setData(placeHolder)
</code>```

Body:
I am trying to set data in my Firestore database. I want to find a document in a collection using the where method and then navigates to its sub collection and set data. I think I'm getting an error because the where the method returns a query that doesn't have a .collection. Does anyone know how I can reformat this code so it performs such an action?

let placeHolder = ["place": ""]
let document = Firestore.firestore().collection("tweets").whereField("uid", isEqualTo: uid).collection("comments").document("hello")

document.setData(placeHolder)


问:
Attention Score Visualization for Time Series
As I am learning the Timeseries classification with a Transformer model example, I wonder if the attention scores (weights) can be visualized to see the similarity between two time series. Can anyone please help?

I have revised the following line to try to retrieve the attention_scores value:

```<code>x, attention_scores = layers.MultiHeadAttention(
    key_dim=head_size, num_heads=num_heads, dropout=dropout
)(x, x, return_attention_scores=True)

print(attention_scores)
</code>```

But I only got the following returned:

```<code>KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention/softmax/Softmax:0', description="created by layer 'multi_head_attention'")
KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention_1/softmax/Softmax:0', description="created by layer 'multi_head_attention_1'")
KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention_2/softmax/Softmax:0', description="created by layer 'multi_head_attention_2'")
KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention_3/softmax/Softmax:0', description="created by layer 'multi_head_attention_3'")
</code>```

Body:
As I am learning the Timeseries classification with a Transformer model example, I wonder if the attention scores (weights) can be visualized to see the similarity between two time series. Can anyone please help?

I have revised the following line to try to retrieve the attention_scores value:

x, attention_scores = layers.MultiHeadAttention(
    key_dim=head_size, num_heads=num_heads, dropout=dropout
)(x, x, return_attention_scores=True)

print(attention_scores)

But I only got the following returned:

KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention/softmax/Softmax:0', description="created by layer 'multi_head_attention'")
KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention_1/softmax/Softmax:0', description="created by layer 'multi_head_attention_1'")
KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention_2/softmax/Softmax:0', description="created by layer 'multi_head_attention_2'")
KerasTensor(type_spec=TensorSpec(shape=(None, 4, 500, 500), dtype=tf.float32, name=None), name='multi_head_attention_3/softmax/Softmax:0', description="created by layer 'multi_head_attention_3'")


问:
Confusing IllegalStateException: Attempting to launch an unregistered ActivityResultLauncher
I have looked at the other questions/answers and they don't seem to apply here.

As you can see I am declaring and registering the ActivityResultLauncher as a top level property.

Yet I am still experiencing the IllegalStateException in production which I am unable to reproduce, so the confusion is how can this be? Wouldn't it always register before it is accessed?

I suspect maybe it the fact that the launch call is in a coroutine but I'm just guessing. The error does seem to be happening when the activity is resumed after being killed of by Android from what I can tell from the logs.

```<code>class MainActivity {

    private val startAnotherActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
        //Does stuff with the result
    }

    override fun onResume(){
        if(someConditionTrue) launchAnotherActivity()
    }

    fun launchAnotherActivity(){
        lifecycleScope.launch {
            val user = viewModel.someSuspendDBCall()
            val intent = Intent(this@MainActivity, TheOtherActivity::class.java)
            intent.putExtra(USERID, user.id)
            startAnotherActivityResult.launch(intent) //<--- The error happens here
        }
    }

}
</code>```

Body:
I have looked at the other questions/answers and they don't seem to apply here.

As you can see I am declaring and registering the ActivityResultLauncher as a top level property.

Yet I am still experiencing the IllegalStateException in production which I am unable to reproduce, so the confusion is how can this be? Wouldn't it always register before it is accessed?

I suspect maybe it the fact that the launch call is in a coroutine but I'm just guessing. The error does seem to be happening when the activity is resumed after being killed of by Android from what I can tell from the logs.

class MainActivity {

    private val startAnotherActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
        //Does stuff with the result
    }

    override fun onResume(){
        if(someConditionTrue) launchAnotherActivity()
    }

    fun launchAnotherActivity(){
        lifecycleScope.launch {
            val user = viewModel.someSuspendDBCall()
            val intent = Intent(this@MainActivity, TheOtherActivity::class.java)
            intent.putExtra(USERID, user.id)
            startAnotherActivityResult.launch(intent) //<--- The error happens here
        }
    }

}


问:
Vaadin Flow 24.0.0.alpha7 doesn't work with Payara Micro
I tried to run Vaadin Flow 24.0.0.alpha7 (because it supports Jakarta EE 9) on Payara Micro but Vaadin servlet didn't deploy.

I believe Payara Micro 6.2022.2 should support it theoretically however when I tried to run it on Java 17 I got multiple errors of this sort:

```<code>Exception while visiting com/vaadin/flow/data/provider/SortDirection.class of size 1425
java.lang.UnsupportedOperationException: PermittedSubclasses requires ASM9
</code>```

When I switched to Java 19 I got the same ASM9 errors plus a bunch of new ones like this:

```<code>Exception while visiting WEB-INF/classes/ui/views/MainLayout.class of size 3967
java.lang.IllegalArgumentException: Unsupported class file major version 63
</code>```

Is there any way to make it work?

Body:
I tried to run Vaadin Flow 24.0.0.alpha7 (because it supports Jakarta EE 9) on Payara Micro but Vaadin servlet didn't deploy.

I believe Payara Micro 6.2022.2 should support it theoretically however when I tried to run it on Java 17 I got multiple errors of this sort:

Exception while visiting com/vaadin/flow/data/provider/SortDirection.class of size 1425
java.lang.UnsupportedOperationException: PermittedSubclasses requires ASM9

When I switched to Java 19 I got the same ASM9 errors plus a bunch of new ones like this:

Exception while visiting WEB-INF/classes/ui/views/MainLayout.class of size 3967
java.lang.IllegalArgumentException: Unsupported class file major version 63

Is there any way to make it work?


问:
Clicking a button on a webpage using Selenium
I am trying to scrape a webpage and need to virtually click a next page button

The html is below for the button.

```<code><li class="one-list-1hm87c3 e13hbd3c2">
     <a href="#" class="e13hbd3c1 one-list-qweso6 e19uw93u1">›</a>
</li>
</code>```

How would I go about this?
Thanks!

The code doesn't work but thats what I have

l = driver.find_element(By.XPATH, '//a[@href="#"]') driver.execute_script("arguments[0].click();", l);

I get this error.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href="#"]"}

Body:
I am trying to scrape a webpage and need to virtually click a next page button

The html is below for the button.

     ›

How would I go about this?
Thanks!

The code doesn't work but thats what I have

l = driver.find_element(By.XPATH, '//a[@href="#"]') driver.execute_script("arguments[0].click();", l);

I get this error.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href="#"]"}


问:
how to store django static and media files on client virtual machine
i have a requirement to separate application server and datbase server such that the data resides with client and application will be hosted by the company where i work. The problem here is how do i store the media file uploaded by client in some virtual machine hosted on client side, so that client will have an idea that all the data and files resides on their side(encyption will also be implemented)

I did try django-storages library, but client is not opting for any cloud provider to store media files over ther, and there is pretty less documentation for ftp and sftp methods in django-storages library


问:
How can I identify if I will add or less time keep date before concatenating it to my time columns?
I am having a hard time in computing the timekeeping I am creating.

these are the sample data.

Timekeep Date
Schedule In
Schedule OUT
Actual In
Break Out
Break In
Actual Out

2022-12-01
00:00AM
9:00AM
23:00PM
4:00AM
5:00AM
9:00AM

2022-12-02
23:00PM
8:00AM
22:00PM
4:00AM
5:00AM
8:00AM

What I want to do is to convert the time columns into datetime using SQL query so I can compute it using timediff().

what I did is compare the time column to each other like these.

```<code>select
cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_timein , '%H:%i')) as datetime) as 'Actual In',

if(time_format(act_breakout , '%H:%i') >= time_format(act_timein , '%H:%i'),cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_breakout , '%H:%i')) as datetime) , cast(concat(date_add(a.date,interval 1 day),' ',time_format(act_breakout , '%H:%i')) as datetime)) as 'Break Out',

if(time_format(act_breakin , '%H:%i') >= time_format(act_timein , '%H:%i'),cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_breakin , '%H:%i')) as datetime) , cast(concat(date_add(a.date,interval 1 day),' ',time_format(act_breakin , '%H:%i')) as datetime)) as 'Break In',

if(time_format(act_timeout , '%H:%i') >= time_format(act_timein , '%H:%i'),cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_timeout , '%H:%i')) as datetime) , cast(concat(date_add(a.date,interval 1 day),' ',time_format(act_timeout , '%H:%i')) as datetime)) as 'Actual Out'

from sample table

</code>```

the result I get is actual time date is same to schedule in date. what formula should I use to make it less than a date of schedule in.

Body:
I am having a hard time in computing the timekeeping I am creating.

these are the sample data.

Timekeep Date
Schedule In
Schedule OUT
Actual In
Break Out
Break In
Actual Out

2022-12-01
00:00AM
9:00AM
23:00PM
4:00AM
5:00AM
9:00AM

2022-12-02
23:00PM
8:00AM
22:00PM
4:00AM
5:00AM
8:00AM

What I want to do is to convert the time columns into datetime using SQL query so I can compute it using timediff().

what I did is compare the time column to each other like these.

select
cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_timein , '%H:%i')) as datetime) as 'Actual In',

if(time_format(act_breakout , '%H:%i') >= time_format(act_timein , '%H:%i'),cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_breakout , '%H:%i')) as datetime) , cast(concat(date_add(a.date,interval 1 day),' ',time_format(act_breakout , '%H:%i')) as datetime)) as 'Break Out',

if(time_format(act_breakin , '%H:%i') >= time_format(act_timein , '%H:%i'),cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_breakin , '%H:%i')) as datetime) , cast(concat(date_add(a.date,interval 1 day),' ',time_format(act_breakin , '%H:%i')) as datetime)) as 'Break In',

if(time_format(act_timeout , '%H:%i') >= time_format(act_timein , '%H:%i'),cast(concat(date_add(a.date,interval 0 day),' ',time_format(act_timeout , '%H:%i')) as datetime) , cast(concat(date_add(a.date,interval 1 day),' ',time_format(act_timeout , '%H:%i')) as datetime)) as 'Actual Out'

from sample table

the result I get is actual time date is same to schedule in date. what formula should I use to make it less than a date of schedule in.


问:
Calculated price of item doesn't reflect on Cart & Checkout page
We are developing a Gold Jewelry Store. We've managed to write a code that determines a product’s category - whether it’s 24K or 22K, then it assigns a formula that multiplies the daily gold price to the product's weight.

All is good, and the price gets updated on the Single Product Page, however when I check out the product, the price doesn’t reflect on the Cart/Checkout page. It would say the base price which is "$0.00".

What am I missing? Thank you for any help.

```<code>add_filter( 'woocommerce_get_price_html', 'calculate_price_by_weight', 10, 2 );

function calculate_price_by_weight($price, $product){
    // define gold type prices
    $GOLD24K_PRICE = 98.00;
    $GOLD22K_PRICE = 92.00;

    // get the product weight and regular price
    $weight = $product->get_weight();
    $regular_price = $product->get_regular_price();

    // check if the product has a 24k and 22k category
    // 1. get product category list
    $product_categories = wc_get_product_category_list($product->ID);
    // 2. check if the category list has a 24k in it
    $has_24k_category = strpos(strtolower($product_categories), '24k') !== false;
    $has_22k_category = strpos(strtolower($product_categories), '22k') !== false;

    // get the final gold price base on the category
    if ($has_24k_category) {
        $gold_price = $GOLD24K_PRICE;
    } else if ($has_22k_category) {
        $gold_price = $GOLD22K_PRICE;
    } else {
        // non gold products
        return $regular_price;
    }

    // calculate product price based on gold type price, product weight
    $price = $gold_price * $weight;
    return $price;
    }
</code>```

Body:
We are developing a Gold Jewelry Store. We've managed to write a code that determines a product’s category - whether it’s 24K or 22K, then it assigns a formula that multiplies the daily gold price to the product's weight.

All is good, and the price gets updated on the Single Product Page, however when I check out the product, the price doesn’t reflect on the Cart/Checkout page. It would say the base price which is "$0.00".

What am I missing? Thank you for any help.

add_filter( 'woocommerce_get_price_html', 'calculate_price_by_weight', 10, 2 );

function calculate_price_by_weight($price, $product){
    // define gold type prices
    $GOLD24K_PRICE = 98.00;
    $GOLD22K_PRICE = 92.00;

    // get the product weight and regular price
    $weight = $product->get_weight();
    $regular_price = $product->get_regular_price();

    // check if the product has a 24k and 22k category
    // 1. get product category list
    $product_categories = wc_get_product_category_list($product->ID);
    // 2. check if the category list has a 24k in it
    $has_24k_category = strpos(strtolower($product_categories), '24k') !== false;
    $has_22k_category = strpos(strtolower($product_categories), '22k') !== false;

    // get the final gold price base on the category
    if ($has_24k_category) {
        $gold_price = $GOLD24K_PRICE;
    } else if ($has_22k_category) {
        $gold_price = $GOLD22K_PRICE;
    } else {
        // non gold products
        return $regular_price;
    }

    // calculate product price based on gold type price, product weight
    $price = $gold_price * $weight;
    return $price;
    }


问:
Writing a dataframe to a csv file that has a lot of punctuation - but getting it broken into multiple rows
I have this data frame with one URL:

```<code>df <- data.frame("url" = "http://www.nycourts.gov/reporter/3dseries/2011/2011_00286.htm", "text" = "")
</code>```

I am trying to get the entire text of the webpage (including HTML tags) and save it to a CSV file.

I've tried:

```<code>df$text[1] <- getURL(url=df$url[1])
</code>```

and

```<code>df$text[1] <- paste(readLines(df$url[1]), collapse="")
</code>```

These work fine, the problem is when I try to save it to a CSV. I've used:

```<code>write.csv(df, "file.csv")
write_csv(df, "file.csv")
write_delim(df1, "file.csv", delim = ",")
</code>```

But the csv that result doesn't contain all of the text in the "text" column in one row. Instead, depending on the write function I use, it saves it in different rows / columns.

I've tried playing with write_delim's quote and escape parameters but nothing worked. I don't understand what's going wrong with the text in this url.

Body:
I have this data frame with one URL:

df <- data.frame("url" = "http://www.nycourts.gov/reporter/3dseries/2011/2011_00286.htm", "text" = "")

I am trying to get the entire text of the webpage (including HTML tags) and save it to a CSV file.

I've tried:

df$text[1] <- getURL(url=df$url[1])

and

df$text[1] <- paste(readLines(df$url[1]), collapse="")

These work fine, the problem is when I try to save it to a CSV. I've used:

write.csv(df, "file.csv")
write_csv(df, "file.csv")
write_delim(df1, "file.csv", delim = ",")

But the csv that result doesn't contain all of the text in the "text" column in one row. Instead, depending on the write function I use, it saves it in different rows / columns.

I've tried playing with write_delim's quote and escape parameters but nothing worked. I don't understand what's going wrong with the text in this url.


问:
How can I add scrollbar to my labels using Tkinter?
As a part of my prep for the GRE exam I developed this small quiz app. The idea is very simple, it generates random sentences using GRE words and then substitutes the roots of GRE words to a blank. The app is not ideal, but it does the job. One big issue I am trying to tackle in the code is the addition of a scrollbar on the side. I do not want to reengineer the structure of the code too much... and make it work with a quick and easy adjustment... but cannot think of anything simple...

Let me know what would be the most frictionless way to create a functional scrollbar on the side.

There were a few answers I was able to find online, but most of them discussed the usage of text instead of labels...

```<code>import pandas as pd
import numpy as np
from nltk.stem.snowball import EnglishStemmer
import random
import requests
from bs4 import BeautifulSoup
from PyDictionary import PyDictionary
import time
import webbrowser
from tkinter import *
import tkinter as tk
window = Tk()
window.wm_title('GRE prep')
dictionary=PyDictionary()

df = pd.read_csv("/Users/vladimirbarshchuk/Downloads/DictionaryV21.csv")
for x in range(len(df["Word"])):
    df["Links"]= "https://www.wordhippo.com/what-is/sentences-with-the-word/{}.html"
for x in range(len(df["Word"])):
    df["Links"][x] = "https://www.wordhippo.com/what-is/sentences-with-the-word/{}.html".format(df["Word"][x])

pd.set_option('display.max_colwidth', None)
df["Word"][141]="hegemonic"
stemmer = EnglishStemmer()
def getdata(url):
    r = requests.get(url)
    return r.text

from tkinter import *

e = Entry(window, width =50)
e.pack()
count = 0
given_word = []
answers = []
def work():
    random_link = random.choice(df["Links"])
    word_index = df[df['Links'] == random_link].index[0]
    htmldata = getdata(random_link)
    soup = BeautifulSoup(htmldata, 'html.parser')
    text = soup.find_all(id="gexv2row1")
    word= df["Word"].loc[word_index]
    answers.append(word)
    stem = stemmer.stem(word)
    clean_text = text[0].get_text().replace("\n"or"'\n"or"\n'", "")

    if stem not in clean_text:
        stem = stem[:-1]
        #print(clean_text.replace(stem_1, "_____"))
        message = Label(window, text = "EX : " + clean_text.replace(stem, "_____"), fg="black")
        context = Label(window, text ="Definition : " + df["My explanation"].loc[word_index], fg = "grey")
        message.pack()
        context.pack()

    else:
        #print(clean_text.replace(stem, "_____"))
        message = Label(window,  text = "EX : " + clean_text.replace(stem, "_____"),fg="black")
        context = Label(window, text ="Definition : " + df["My explanation"].loc[word_index], fg = "grey")
        message.pack()
        context.pack()
        name = e.get()

    return

sentenceButton = Button(window, text = "Show Sentence", command = work)
sentenceButton.pack()

for x in range(len(answers)):
    count=count+1
    print(count)

def check():
    print("Correct answer:", answers[count-1])
    correct_answer = Label(window, text = answers[count-1], fg = "green")
    incorrect_answer = Label(window, text = answers[count-1], fg = "red")
    a = e.get()

    if a == correct_answer.cget("text"):
            correct_answer.pack()
    else:
            incorrect_answer.pack()

new = Button(window, text = "Check!", command = check)
new.pack()
window.mainloop()
</code>```

Body:
As a part of my prep for the GRE exam I developed this small quiz app. The idea is very simple, it generates random sentences using GRE words and then substitutes the roots of GRE words to a blank. The app is not ideal, but it does the job. One big issue I am trying to tackle in the code is the addition of a scrollbar on the side. I do not want to reengineer the structure of the code too much... and make it work with a quick and easy adjustment... but cannot think of anything simple...

Let me know what would be the most frictionless way to create a functional scrollbar on the side.

There were a few answers I was able to find online, but most of them discussed the usage of text instead of labels...

import pandas as pd
import numpy as np
from nltk.stem.snowball import EnglishStemmer
import random
import requests
from bs4 import BeautifulSoup
from PyDictionary import PyDictionary
import time
import webbrowser
from tkinter import *
import tkinter as tk
window = Tk()
window.wm_title('GRE prep')
dictionary=PyDictionary()

df = pd.read_csv("/Users/vladimirbarshchuk/Downloads/DictionaryV21.csv")
for x in range(len(df["Word"])):
    df["Links"]= "https://www.wordhippo.com/what-is/sentences-with-the-word/{}.html"
for x in range(len(df["Word"])):
    df["Links"][x] = "https://www.wordhippo.com/what-is/sentences-with-the-word/{}.html".format(df["Word"][x])

pd.set_option('display.max_colwidth', None)
df["Word"][141]="hegemonic"
stemmer = EnglishStemmer()
def getdata(url):
    r = requests.get(url)
    return r.text

from tkinter import *

e = Entry(window, width =50)
e.pack()
count = 0
given_word = []
answers = []
def work():
    random_link = random.choice(df["Links"])
    word_index = df[df['Links'] == random_link].index[0]
    htmldata = getdata(random_link)
    soup = BeautifulSoup(htmldata, 'html.parser')
    text = soup.find_all(id="gexv2row1")
    word= df["Word"].loc[word_index]
    answers.append(word)
    stem = stemmer.stem(word)
    clean_text = text[0].get_text().replace("\n"or"'\n"or"\n'", "")

    if stem not in clean_text:
        stem = stem[:-1]
        #print(clean_text.replace(stem_1, "_____"))
        message = Label(window, text = "EX : " + clean_text.replace(stem, "_____"), fg="black")
        context = Label(window, text ="Definition : " + df["My explanation"].loc[word_index], fg = "grey")
        message.pack()
        context.pack()

    else:
        #print(clean_text.replace(stem, "_____"))
        message = Label(window,  text = "EX : " + clean_text.replace(stem, "_____"),fg="black")
        context = Label(window, text ="Definition : " + df["My explanation"].loc[word_index], fg = "grey")
        message.pack()
        context.pack()
        name = e.get()

    return

sentenceButton = Button(window, text = "Show Sentence", command = work)
sentenceButton.pack()

for x in range(len(answers)):
    count=count+1
    print(count)

def check():
    print("Correct answer:", answers[count-1])
    correct_answer = Label(window, text = answers[count-1], fg = "green")
    incorrect_answer = Label(window, text = answers[count-1], fg = "red")
    a = e.get()

    if a == correct_answer.cget("text"):
            correct_answer.pack()
    else:
            incorrect_answer.pack()

new = Button(window, text = "Check!", command = check)
new.pack()
window.mainloop()


问:
Response to Clear Input Textbox Validating Form
So I'm validating a form, and I'm sending the value of a textbox to be checked in the database if it's already there. If a match is found, I want a warning like change the placeholder of the textbox to say something like duplicate value found. Otherwise, just go to the next input.

On my HTML, I have:

```<code><div class="inventry" id="myInventry">
<h2>Invoice entry:</h2>
    <form action="/inventry" method="post">
        <label for="invoicenumber"><b>Invoice Number:</b></label>
        <input type="text" name="invoicenumber" id="invoicenumber" onchange="this.form.submit()" required>
</code>```

On my server, I have:

```<code>app.post('/inventry', function(request, response) {
let invoicenumber = request.body.invoicenumber;

if(invoicenumber) {
    connection.query('SELECT Factura FROM tbl1facturas WHERE Factura = ?',[invoicenumber], function(error, results, fields) {
        if (error) throw error;
        if(results.length > 0) {
            response.set.body.invoicenumber("")
        }
        response.end();
    })
}
</code>```

However, this is crashing the server, and I'm getting this error:

ql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^

TypeError: Cannot read properties of undefined (reading 'invoicenumber')

I'm having no problem checking the code is working I know it works I'm only having trouble sending a response message to the form or the textbox itself.

I checked with this code and it's working:

```<code>app.post('/inventry', function(request, response) {
let invoicenumber = request.body.invoicenumber;

if(invoicenumber) {
    connection.query('SELECT Factura FROM tbl1facturas WHERE Factura = ?',[invoicenumber], function(error, results, fields) {
        if (error) throw error;
        if(results.length > 0) {
            response.send('Success!');
        } else {
            response.send('Fail!');
        }
        response.end();
    });
}
</code>```

Body:
So I'm validating a form, and I'm sending the value of a textbox to be checked in the database if it's already there. If a match is found, I want a warning like change the placeholder of the textbox to say something like duplicate value found. Otherwise, just go to the next input.

On my HTML, I have:

Invoice entry:

    <form action="/inventry" method="post">
        Invoice Number:
        <input type="text" name="invoicenumber" id="invoicenumber" onchange="this.form.submit()" required>

On my server, I have:

app.post('/inventry', function(request, response) {
let invoicenumber = request.body.invoicenumber;

if(invoicenumber) {
    connection.query('SELECT Factura FROM tbl1facturas WHERE Factura = ?',[invoicenumber], function(error, results, fields) {
        if (error) throw error;
        if(results.length > 0) {
            response.set.body.invoicenumber("")
        }
        response.end();
    })
}

However, this is crashing the server, and I'm getting this error:

ql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^

TypeError: Cannot read properties of undefined (reading 'invoicenumber')

I'm having no problem checking the code is working I know it works I'm only having trouble sending a response message to the form or the textbox itself.

I checked with this code and it's working:

app.post('/inventry', function(request, response) {
let invoicenumber = request.body.invoicenumber;

if(invoicenumber) {
    connection.query('SELECT Factura FROM tbl1facturas WHERE Factura = ?',[invoicenumber], function(error, results, fields) {
        if (error) throw error;
        if(results.length > 0) {
            response.send('Success!');
        } else {
            response.send('Fail!');
        }
        response.end();
    });
}


问:
WebGLOverlay Google Maps API
Is it possible to scale the size of the buildings in webgloverlay by a positive factor. All of the buildings in the area i'm displaying in the application are close to the ground and I want to vertically scale them. Is it possible to scale matrix or THREE.Matrix4() just its y-component so all the buildings are stretched vertically</p>

Title: WebGLOverlay Google Maps API


问:
How to set limit in consuming message from google Pub/Sub?
I just want to consume 1000 messages per minute from google pub/sup in my spring boot application. Is there a way to set it like this in spring boot application? I searched many websites but didn't find anything helpful.</p>


问:
How can we enable Transport layer Security in Hive metastore?
I need to know how to enable Transport layer security in Hive Metastore and how to verify it. Should we create another .xml file specifying the property? This should be based on Thrift url.

I tried to edit two files in hive-metastore by specifying the properties -metastore-site.xml and conf-site.xml. And I am getting the following error even after creating the keys:

```<code>[root@primmer1 lh-hms-poc]# openssl s_client -connect 9.30.94.163:9083 -cert cert.crt -key cert.key
CONNECTED(00000003)
139828257847184:error:140790E5:SSL routines:ssl23_write:ssl handshake failure:s23_lib.c:177:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 289 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    Start Time: 1672830872
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

</code>```

Body:
I need to know how to enable Transport layer security in Hive Metastore and how to verify it. Should we create another .xml file specifying the property? This should be based on Thrift url.

I tried to edit two files in hive-metastore by specifying the properties -metastore-site.xml and conf-site.xml. And I am getting the following error even after creating the keys:

[root@primmer1 lh-hms-poc]# openssl s_client -connect 9.30.94.163:9083 -cert cert.crt -key cert.key
CONNECTED(00000003)
139828257847184:error:140790E5:SSL routines:ssl23_write:ssl handshake failure:s23_lib.c:177:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 289 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    Start Time: 1672830872
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---


问:
Django ORM model to sync with db record changed by external
In Django model, is there anyway for instant sync of loaded model object with db records updated by external?

Here is sample scenario.

I load record in Django model by get method.

```<code>book = Book.objects.get(id=1)
print(book.title) # It will print '21 century'
</code>```

I update relevant db data manually in database using query in PGAdmin

```<code>update book set title='22 century' where id=1
</code>```

the model obj loaded in 1st step still retains old data instead of latest update from 2 step

```<code>print(book.title) # It still print '21 century' instead of '22 century'
</code>```

I have no solution yet and need help for this

Body:
In Django model, is there anyway for instant sync of loaded model object with db records updated by external?

Here is sample scenario.

I load record in Django model by get method.

book = Book.objects.get(id=1)
print(book.title) # It will print '21 century'

I update relevant db data manually in database using query in PGAdmin

update book set title='22 century' where id=1

the model obj loaded in 1st step still retains old data instead of latest update from 2 step

print(book.title) # It still print '21 century' instead of '22 century'

I have no solution yet and need help for this


问:
How to config quarkus application not build again?
Enviroment :k8s

Issue : I change ip,port,username,password database in application.properties file, I must build my application again to update new information.

Expect :
When I change database information(Example: ip,port) in application.properties, I want my quarkus application will not build again.


问:
How to Get Email Notification for Post Changes in WordPress
By default, WordPress doesn’t send notifications when posts are changed by a user.

How to Get Email Notification for Post Changes in WordPress?

I want to get notification when user update/change post