问:
Replacing characters from buffer array
I am attempting to create a text file and fill it with text, which contains even outer double quotes. Then I want to open this file, give it read-write access, and read the file. After reading the file, iterate over each character and replace those matching a single quote. However, for each match of a single double quote, I either replace it with two backquotes or two single quotes.

However, my attempt was to insert this one index position higher than the matching index for a double quote. This meant I needed to push all characters one step higher.

When given text input like:

```<code>//sometext.txt
"some text here"
"read it"
</code>```

I get:

```<code>"some text here"
"read it"``````````````````````````````````````````````````
</code>```

When using the following:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_READ 50
int main(){
    int fd;
    fd = open("test.txt", O_RDWR);
    if (fd == -1){
        printf("Failed");
        exit(EXIT_FAILURE);
    }

    char buffer[MAX_READ+1];
    ssize_t numRead;

    numRead = read(fd, buffer, MAX_READ);
    if (numRead == -1){
        printf("Failed");
        exit(EXIT_FAILURE);
    }
    buffer[numRead] = '\0';
    int j = 1;
    size_t chars = sizeof(buffer)/sizeof(buffer[0]);
    for(int i = 0; i < chars; i++){

        if(buffer[i] == '"'){
            if(j % 2 != 0){

                buffer[i] = '`';
                chars++;
                while(i < chars){
                    i++;
                    buffer[i] = buffer[i-1];
                }
            }else{
                buffer[i] = '\'';
                chars++;
                while(i < chars){
                    i++;
                    buffer[i] = buffer[i-1];
                }
            }
            j++;

        }
        printf("\nString characters: %c", buffer[i]);
    }

    ssize_t numWrite;

    numWrite = write(fd, buffer, MAX_READ);

    if (numWrite == -1){
        printf("Failed");
        exit(EXIT_FAILURE);
    }

    return 0;
}
</code>```

Expected output:

```<code>``some text here''
``read it''
</code>```

Title: Replacing characters from buffer array

Body:
I am attempting to create a text file and fill it with text, which contains even outer double quotes. Then I want to open this file, give it read-write access, and read the file. After reading the file, iterate over each character and replace those matching a single quote. However, for each match of a single double quote, I either replace it with two backquotes or two single quotes.

However, my attempt was to insert this one index position higher than the matching index for a double quote. This meant I needed to push all characters one step higher.

When given text input like:

//sometext.txt
"some text here"
"read it"

I get:

"some text here"
"read it"``````````````````````````````````````````````````

When using the following:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_READ 50
int main(){
    int fd;
    fd = open("test.txt", O_RDWR);
    if (fd == -1){
        printf("Failed");
        exit(EXIT_FAILURE);
    }

    char buffer[MAX_READ+1];
    ssize_t numRead;

    numRead = read(fd, buffer, MAX_READ);
    if (numRead == -1){
        printf("Failed");
        exit(EXIT_FAILURE);
    }
    buffer[numRead] = '\0';
    int j = 1;
    size_t chars = sizeof(buffer)/sizeof(buffer[0]);
    for(int i = 0; i < chars; i++){

        if(buffer[i] == '"'){
            if(j % 2 != 0){

                buffer[i] = '`';
                chars++;
                while(i < chars){
                    i++;
                    buffer[i] = buffer[i-1];
                }
            }else{
                buffer[i] = '\'';
                chars++;
                while(i < chars){
                    i++;
                    buffer[i] = buffer[i-1];
                }
            }
            j++;

        }
        printf("\nString characters: %c", buffer[i]);
    }

    ssize_t numWrite;

    numWrite = write(fd, buffer, MAX_READ);

    if (numWrite == -1){
        printf("Failed");
        exit(EXIT_FAILURE);
    }

    return 0;
}

Expected output:

``some text here''
``read it''


来源: stackexchange

问:
Regular expression is 'invalid' mongodb in python
I am trying to query sentences with specific keywords. I am using python btw

my implementation:

```<code>words = ['word1', 'word2']
#dummy set of words, words are fetched dynamically

queryList = sum([[{'title':{'$regex':w, '$options':'i'}}, {'media':{'$regex':w, '$options':'i'}}] for w in words], [])
#creating a list of all queries for passing into an $or operation
query = {'$or':queryList}
#preparing the query

posts = (postsCollection.find(query).sort('points', -1))
</code>```

it is returning me Regular expression is invalid

sometimes it doesn't give me a specific set of words and it gives an error with another particular set of words

ContentLicense: CC BY-SA 4.0

Body:
I am trying to query sentences with specific keywords. I am using python btw

my implementation:

words = ['word1', 'word2']
#dummy set of words, words are fetched dynamically

queryList = sum([[{'title':{'$regex':w, '$options':'i'}}, {'media':{'$regex':w, '$options':'i'}}] for w in words], [])
#creating a list of all queries for passing into an $or operation
query = {'$or':queryList}
#preparing the query

posts = (postsCollection.find(query).sort('points', -1))

it is returning me Regular expression is invalid

sometimes it doesn't give me a specific set of words and it gives an error with another particular set of words


问:
Robot framework Ride : get value of an attribute
I work with robot framework with RIDE development environment for a desktop application, I would like to get the value of element

The attribute has an ID : NeedSupervisorConfirmationPortrait

enter image description here

I want to retrieve the value of the TogglePattern.toggleState of the attribute that has ID:NeedSupervisorConfirmationPortrait

enter image description here


问:
Multiple headerview in tableview in swift
I want to create 3 headers in the tableview given in the images and 8 students in each row, my code is as follows

Screenshot of the example

```<code>class ViewController: UIViewController {

    var schoolOfList: [Any] = [
    [["school": ["VIP", "Bright International", "Motherland"]],
    [["student1": ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"]],
    ["student2": ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"]],
    ["student3": ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"]]]]]

    @IBOutlet weak var mytableview : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension ViewController:UITableViewDelegate,UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> (Int) {
    return schoolOfList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)

    cell.textLabel?.text = schoolOfList["school"] as! [String]indexPath.row
    return cell
   }

    func  tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerview = UIView(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50))
        headerview.backgroundColor = .green
        let lable = UILabel(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50))
        lable.textAlignment = .center
        lable.text = (schoolOfList["school"]as!String)
        headerview.addSubview(lable)
        return  headerview
}
</code>```

Body:
I want to create 3 headers in the tableview given in the images and 8 students in each row, my code is as follows

Screenshot of the example

class ViewController: UIViewController {

    var schoolOfList: [Any] = [
    [["school": ["VIP", "Bright International", "Motherland"]],
    [["student1": ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"]],
    ["student2": ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"]],
    ["student3": ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"]]]]]

    @IBOutlet weak var mytableview : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension ViewController:UITableViewDelegate,UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> (Int) {
    return schoolOfList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)

    cell.textLabel?.text = schoolOfList["school"] as! [String]indexPath.row
    return cell
   }

    func  tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerview = UIView(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50))
        headerview.backgroundColor = .green
        let lable = UILabel(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50))
        lable.textAlignment = .center
        lable.text = (schoolOfList["school"]as!String)
        headerview.addSubview(lable)
        return  headerview
}


问:
How do I find out if one of the dual SIM cards is roaming?
so I need to find out if the user is using roaming and I'm having trouble with phones with multiple SIM cards.
My problem occurs when they have 1 sim card that's not roaming and 1 sim card that is roaming then TelephonyManager isNetworkRoaming returns false. I'd like it to return true if even 1 of the cards is roaming. Any idea how to do this?

This is my code

```<code> boolean isRoaming = false;
 TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
 if (telephonyManager != null)
 {
    isRoaming = telephonyManager.isNetworkRoaming();
 }

</code>```

I'm getting false if 1 of the cards is roaming.

Body:
so I need to find out if the user is using roaming and I'm having trouble with phones with multiple SIM cards.
My problem occurs when they have 1 sim card that's not roaming and 1 sim card that is roaming then TelephonyManager isNetworkRoaming returns false. I'd like it to return true if even 1 of the cards is roaming. Any idea how to do this?

This is my code

 boolean isRoaming = false;
 TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
 if (telephonyManager != null)
 {
    isRoaming = telephonyManager.isNetworkRoaming();
 }

I'm getting false if 1 of the cards is roaming.


问:
Error when installing serverless benchmark
```<code> Running setup.py install for pycurl: started
  Running setup.py install for pycurl: finished with status 'error'
  error: subprocess-exited-with-error

  × Running setup.py install for pycurl did not run successfully.
  │ exit code: 1
  ╰─> [22 lines of output]
      Using curl-config (libcurl 7.81.0)
      Using SSL library: GnuTLS
</code>```

justinchigu@justinchigu-VirtualBox:~/serverless-benchmarks$ ./install.py --aws --azure --gcp --openwhisk --local

I am trying to install the above serverless benchmark which I git cloned

Body:
 Running setup.py install for pycurl: started
  Running setup.py install for pycurl: finished with status 'error'
  error: subprocess-exited-with-error

  × Running setup.py install for pycurl did not run successfully.
  │ exit code: 1
  ╰─> [22 lines of output]
      Using curl-config (libcurl 7.81.0)
      Using SSL library: GnuTLS

justinchigu@justinchigu-VirtualBox:~/serverless-benchmarks$ ./install.py --aws --azure --gcp --openwhisk --local

I am trying to install the above serverless benchmark which I git cloned


问:
Getting error while trying to access mobile reports through web server url
Getting error while trying to access mobile reports in server through report server url of report configuration manager The operation you are attempting on item '/MobileReports/DemClient/MobileReport' is not allowed for this item type. (rsWrongItemType)

The folder have all required permission. While I am able to access SSRS reports using Web server URL


问:
Create list of dataframes of a single dataframe based on repeating binary column
I have a dataframe with some primary key idx, a binary column cat and a column with values y. See example data below.

The binary column can be seen as a category, the first couple of rows with 0 are category 1, the following couple of rows with 1 are category 2, the next couple of rows with 0 are category 3 and so forth... where each category has a different number of rows. So there's 5 categories in this example dataframe split up by consecutive binaries, the actual dataframe consists of many more categories with many more rows per category.

I'd like to make a list of dataframes where each dataframe corresponds to a category. So this example data would be split up in a list of 5 dataframes.

What's the best way to do this with a large dataframe?

```<code>import pandas as pd
import numpy as np
import random

idx = [i for i in range(55)]
cat = [0,0,0,0,0,0,0,0,0,0,0,
     1,1,1,1,1,1,1,1,1,1,
     0,0,0,0,0,0,0,0,0,0,0,0,0,
     1,1,1,1,1,1,1,1,1,1,
     0,0,0,0,0,0,0,0,0,0,0]
y = [random.random()*10 for _ in range(55)]

df = pd.DataFrame({'idx':idx, 'cat':cat, 'y':y})
</code>```

Body:
I have a dataframe with some primary key idx, a binary column cat and a column with values y. See example data below.

The binary column can be seen as a category, the first couple of rows with 0 are category 1, the following couple of rows with 1 are category 2, the next couple of rows with 0 are category 3 and so forth... where each category has a different number of rows. So there's 5 categories in this example dataframe split up by consecutive binaries, the actual dataframe consists of many more categories with many more rows per category.

I'd like to make a list of dataframes where each dataframe corresponds to a category. So this example data would be split up in a list of 5 dataframes.

What's the best way to do this with a large dataframe?

import pandas as pd
import numpy as np
import random

idx = [i for i in range(55)]
cat = [0,0,0,0,0,0,0,0,0,0,0,
     1,1,1,1,1,1,1,1,1,1,
     0,0,0,0,0,0,0,0,0,0,0,0,0,
     1,1,1,1,1,1,1,1,1,1,
     0,0,0,0,0,0,0,0,0,0,0]
y = [random.random()*10 for _ in range(55)]

df = pd.DataFrame({'idx':idx, 'cat':cat, 'y':y})


问:
Dask hot encoding - ValueError: All columns must be Categorical dtype when 'categories="auto"'
I am dealing with an error that I am unable to handle. Considering that I am using a simple dataset that has both categorical and numerical features, I am a bit suprised by the error ValueError: All columns must be Categorical dtype when 'categories="auto"'.

The dataset before any transformation looks like that

As I am using dask instead of sklearn, I cannot rely on something like  OneHotEncoder(handle_unknown='ignore')

What would you recommend to fix that?

```<code>from dask import dataframe as pd
from dask_ml.model_selection import train_test_split
from dask_ml.preprocessing import MinMaxScaler, OneHotEncoder
from dask_ml.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from dask_ml.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedKFold

from numpy import mean
from numpy import std
from numpy import absolute

numeric_features = ['prob','opp','win_proba','checker']

categorical_features = ['card1_hand','card2_hand','card1_table','card2_table','card3_table',
                        'card1_color_hand','card2_color_hand','card1_color_table','card2_color_table',
                        'card3_color_table','actions_preflop','actions_flop','actions_turn','actions_river','best_hand']

all_features = ['card1_hand','card2_hand','card1_table','card2_table','card3_table','card1_color_hand',
                'card2_color_hand','card1_color_table','card2_color_table','card3_color_table',
                'actions_preflop','actions_flop','actions_turn','actions_river','best_hand',
                'call','prob','opp','win_proba','checker']

output_col = 'call'

def train(x_train, y_train):
    numeric_transformer = MinMaxScaler()
    categorical_transformer = OneHotEncoder()

    preprocessor = ColumnTransformer(
        transformers=[
            ("num", numeric_transformer, numeric_features),
            ("cat", categorical_transformer, categorical_features),
        ]
    )
    model = Pipeline(
        steps=[
            ("preprocessor", preprocessor),
            ("classifier", LinearRegression())
        ]
    )
    model.fit(x_train, y_train)
    return model

'''

def evaluate_model(model, x_test, y_test):

    #predict_test = model.predict(x_test)
    cv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)
    # evaluate model
    scores = cross_val_score(model, x_test, y_test, scoring='neg_mean_absolute_error', cv=cv, n_jobs=-1)
    scores = absolute(scores)
    print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))
'''

def predict_from_dict(model, data):
    x = pd.DataFrame.from_dict({key:[value] for key, value in data.items()})
    return model.predict(x)[0]

if __name__ == '__main__':
    df = pd.read_csv('output_test.csv')
    df = df[all_features]
    y = df[output_col]
    x = df.drop(['call'], axis=1)
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
    model = train(x_train, y_train)

</code>```

Traceback below

```<code>Traceback (most recent call last):

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 73, in <module>
    model = train(x_train, y_train)

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 46, in train
    model.fit(x_train, y_train)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 390, in fit
    Xt = self._fit(X, y, **fit_params_steps)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 355, in _fit
    **fit_params_steps[name],

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\memory.py", line 355, in __call__
    return self.func(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 675, in fit_transform
    result = self._fit_transform(X, y, _fit_transform_one)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 615, in _fit_transform
    for idx, (name, trans, column, weight) in enumerate(transformers, 1)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 1007, in __call__
    while self.dispatch_one_batch(iterator):

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 835, in dispatch_one_batch
    self._dispatch(tasks)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 754, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 209, in apply_async
    result = ImmediateResult(func)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 590, in __init__
    self.results = batch()

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in __call__
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in <listcomp>
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\preprocessing\_encoders.py", line 488, in fit_transform
    return super().fit_transform(X, y)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\base.py", line 855, in fit_transform
    return self.fit(X, y, **fit_params).transform(X)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 153, in fit
    self._fit(X, handle_unknown=self.handle_unknown)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 225, in _fit
    "All columns must be Categorical dtype when "

ValueError: All columns must be Categorical dtype when 'categories="auto"'.

runfile('C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask/dask regression.py', wdir='C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask')
Dask DataFrame Structure:
              card1_hand card2_hand card1_table card2_table card3_table card1_color_hand card2_color_hand card1_color_table card2_color_table card3_color_table actions_preflop actions_flop actions_turn actions_river best_hand     prob      opp win_proba  checker
npartitions=1
                   int64      int64       int64       int64       int64           object           object            object            object            object          object       object       object        object    object  float64  float64   float64  float64
       ...         ...         ...         ...              ...              ...               ...               ...               ...             ...          ...          ...           ...       ...      ...      ...       ...      ...
Dask Name: split, 7 tasks

runfile('C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask/dask regression.py', wdir='C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask')
Traceback (most recent call last):

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 73, in <module>
    model = train(x_train, y_train)

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 46, in train
    model.fit(x_train, y_train)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 390, in fit
    Xt = self._fit(X, y, **fit_params_steps)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 355, in _fit
    **fit_params_steps[name],

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\memory.py", line 355, in __call__
    return self.func(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 675, in fit_transform
    result = self._fit_transform(X, y, _fit_transform_one)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 615, in _fit_transform
    for idx, (name, trans, column, weight) in enumerate(transformers, 1)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 1007, in __call__
    while self.dispatch_one_batch(iterator):

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 835, in dispatch_one_batch
    self._dispatch(tasks)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 754, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 209, in apply_async
    result = ImmediateResult(func)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 590, in __init__
    self.results = batch()

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in __call__
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in <listcomp>
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\preprocessing\_encoders.py", line 488, in fit_transform
    return super().fit_transform(X, y)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\base.py", line 855, in fit_transform
    return self.fit(X, y, **fit_params).transform(X)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 153, in fit
    self._fit(X, handle_unknown=self.handle_unknown)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 225, in _fit
    "All columns must be Categorical dtype when "

ValueError: All columns must be Categorical dtype when 'categories="auto"'.
</code>```

Body:
I am dealing with an error that I am unable to handle. Considering that I am using a simple dataset that has both categorical and numerical features, I am a bit suprised by the error ValueError: All columns must be Categorical dtype when 'categories="auto"'.

The dataset before any transformation looks like that

As I am using dask instead of sklearn, I cannot rely on something like  OneHotEncoder(handle_unknown='ignore')

What would you recommend to fix that?

from dask import dataframe as pd
from dask_ml.model_selection import train_test_split
from dask_ml.preprocessing import MinMaxScaler, OneHotEncoder
from dask_ml.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from dask_ml.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedKFold

from numpy import mean
from numpy import std
from numpy import absolute

numeric_features = ['prob','opp','win_proba','checker']

categorical_features = ['card1_hand','card2_hand','card1_table','card2_table','card3_table',
                        'card1_color_hand','card2_color_hand','card1_color_table','card2_color_table',
                        'card3_color_table','actions_preflop','actions_flop','actions_turn','actions_river','best_hand']

all_features = ['card1_hand','card2_hand','card1_table','card2_table','card3_table','card1_color_hand',
                'card2_color_hand','card1_color_table','card2_color_table','card3_color_table',
                'actions_preflop','actions_flop','actions_turn','actions_river','best_hand',
                'call','prob','opp','win_proba','checker']

output_col = 'call'

def train(x_train, y_train):
    numeric_transformer = MinMaxScaler()
    categorical_transformer = OneHotEncoder()

    preprocessor = ColumnTransformer(
        transformers=[
            ("num", numeric_transformer, numeric_features),
            ("cat", categorical_transformer, categorical_features),
        ]
    )
    model = Pipeline(
        steps=[
            ("preprocessor", preprocessor),
            ("classifier", LinearRegression())
        ]
    )
    model.fit(x_train, y_train)
    return model

'''

def evaluate_model(model, x_test, y_test):

    #predict_test = model.predict(x_test)
    cv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)
    # evaluate model
    scores = cross_val_score(model, x_test, y_test, scoring='neg_mean_absolute_error', cv=cv, n_jobs=-1)
    scores = absolute(scores)
    print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))
'''

def predict_from_dict(model, data):
    x = pd.DataFrame.from_dict({key:[value] for key, value in data.items()})
    return model.predict(x)[0]

if __name__ == '__main__':
    df = pd.read_csv('output_test.csv')
    df = df[all_features]
    y = df[output_col]
    x = df.drop(['call'], axis=1)
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
    model = train(x_train, y_train)

Traceback below

Traceback (most recent call last):

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 73, in <module>
    model = train(x_train, y_train)

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 46, in train
    model.fit(x_train, y_train)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 390, in fit
    Xt = self._fit(X, y, **fit_params_steps)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 355, in _fit
    **fit_params_steps[name],

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\memory.py", line 355, in __call__
    return self.func(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 675, in fit_transform
    result = self._fit_transform(X, y, _fit_transform_one)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 615, in _fit_transform
    for idx, (name, trans, column, weight) in enumerate(transformers, 1)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 1007, in __call__
    while self.dispatch_one_batch(iterator):

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 835, in dispatch_one_batch
    self._dispatch(tasks)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 754, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 209, in apply_async
    result = ImmediateResult(func)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 590, in __init__
    self.results = batch()

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in __call__
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in <listcomp>
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\preprocessing\_encoders.py", line 488, in fit_transform
    return super().fit_transform(X, y)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\base.py", line 855, in fit_transform
    return self.fit(X, y, **fit_params).transform(X)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 153, in fit
    self._fit(X, handle_unknown=self.handle_unknown)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 225, in _fit
    "All columns must be Categorical dtype when "

ValueError: All columns must be Categorical dtype when 'categories="auto"'.

runfile('C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask/dask regression.py', wdir='C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask')
Dask DataFrame Structure:
              card1_hand card2_hand card1_table card2_table card3_table card1_color_hand card2_color_hand card1_color_table card2_color_table card3_color_table actions_preflop actions_flop actions_turn actions_river best_hand     prob      opp win_proba  checker
npartitions=1
                   int64      int64       int64       int64       int64           object           object            object            object            object          object       object       object        object    object  float64  float64   float64  float64
       ...         ...         ...         ...              ...              ...               ...               ...               ...             ...          ...          ...           ...       ...      ...      ...       ...      ...
Dask Name: split, 7 tasks

runfile('C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask/dask regression.py', wdir='C:/Users/rapha/Desktop/Consulting/Poker/Cepheus/Model/Dask')
Traceback (most recent call last):

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 73, in <module>
    model = train(x_train, y_train)

  File "C:\Users\rapha\Desktop\Consulting\Poker\Cepheus\Model\Dask\dask regression.py", line 46, in train
    model.fit(x_train, y_train)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 390, in fit
    Xt = self._fit(X, y, **fit_params_steps)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 355, in _fit
    **fit_params_steps[name],

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\memory.py", line 355, in __call__
    return self.func(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 675, in fit_transform
    result = self._fit_transform(X, y, _fit_transform_one)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\compose\_column_transformer.py", line 615, in _fit_transform
    for idx, (name, trans, column, weight) in enumerate(transformers, 1)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 1007, in __call__
    while self.dispatch_one_batch(iterator):

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 835, in dispatch_one_batch
    self._dispatch(tasks)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 754, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 209, in apply_async
    result = ImmediateResult(func)

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 590, in __init__
    self.results = batch()

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in __call__
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\anaconda3\lib\site-packages\joblib\parallel.py", line 256, in <listcomp>
    for func, args, kwargs in self.items]

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\pipeline.py", line 893, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\preprocessing\_encoders.py", line 488, in fit_transform
    return super().fit_transform(X, y)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\sklearn\base.py", line 855, in fit_transform
    return self.fit(X, y, **fit_params).transform(X)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 153, in fit
    self._fit(X, handle_unknown=self.handle_unknown)

  File "C:\Users\rapha\AppData\Roaming\Python\Python37\site-packages\dask_ml\preprocessing\_encoders.py", line 225, in _fit
    "All columns must be Categorical dtype when "

ValueError: All columns must be Categorical dtype when 'categories="auto"'.


问:
I can not change the properties (size, alignment, font properties) of a QLabel
I'm trying to change the properties of a QLabel but it does not work. I want to change the size, the alignment and sometimes make it bold. I'm working with Qt Designer and I heard that maybe it can "lock" some changes but I'm sure if it is this. I would like to understand why it does not work.

I tried this.

```<code>QFont font = ui.text->font();
font.setPointSize(150);
font.setBold(true);
ui.text->setFont(font);
ui.text->setAlignment(Qt::AlignCenter);`
</code>```

It does not have any effect and the QLabel stays the way it is in the Qt Designer.

Body:
I'm trying to change the properties of a QLabel but it does not work. I want to change the size, the alignment and sometimes make it bold. I'm working with Qt Designer and I heard that maybe it can "lock" some changes but I'm sure if it is this. I would like to understand why it does not work.

I tried this.

QFont font = ui.text->font();
font.setPointSize(150);
font.setBold(true);
ui.text->setFont(font);
ui.text->setAlignment(Qt::AlignCenter);`

It does not have any effect and the QLabel stays the way it is in the Qt Designer.


问:
Webpack 5 and get svg xml
I'm trying to get the xml inside my svgs. But I have no luck no matter what I do. I have a new webpack 5 project. Created the webpack.config.js file with the following code.

```<code>module.exports = {
  resolve: { extensions: [".svg"] },
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: "raw-loader",
          },
          {
            loader: "svgo-loader",
            options: {
              removeTitle: true,
              convertColors: {
                shorthex: false,
              },
              convertPathData: true,
              removeDimensions: false,
              removeViewBox: false,
              mergePaths: true,
              prefixIds: true,
              cleanupIDs: true,
            },
          },
        ],
      },
    ],
  },
};
</code>```

Just keep getting the filename with a random hash in the name.

Title: Webpack 5 and get svg xml

Body:
I'm trying to get the xml inside my svgs. But I have no luck no matter what I do. I have a new webpack 5 project. Created the webpack.config.js file with the following code.

module.exports = {
  resolve: { extensions: [".svg"] },
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: "raw-loader",
          },
          {
            loader: "svgo-loader",
            options: {
              removeTitle: true,
              convertColors: {
                shorthex: false,
              },
              convertPathData: true,
              removeDimensions: false,
              removeViewBox: false,
              mergePaths: true,
              prefixIds: true,
              cleanupIDs: true,
            },
          },
        ],
      },
    ],
  },
};

Just keep getting the filename with a random hash in the name.


问:
Select specific fields in relation and limit results
How can I select with typeorm query builder 100 results of SingleSyncProduct with all shopProducts relations? (selecting only productId, productName, and name from relation)

single-sync-product.entity.ts

import {BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn} from "typeorm";
import {SingleProduct} from "../products/single-product.entity";

@Entity()
export class SingleSyncProduct extends BaseEntity {

    @PrimaryGeneratedColumn()
    productId: number;

    @Column({
        length: 150,
    })
    productName: string;

    @Column({
        unique: true,
        length: 40,
    })
    productSKU: string;

    @OneToMany(type => SingleProduct, entity => entity.syncProduct)
    shopProducts: SingleProduct[];

}
```
<p><strong>single-product.entity.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import {BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn, Unique} from "typeorm";
import {SingleSyncProduct} from "../sync-products/single-sync-product.entity";

@Entity()
@Unique(["id", "extraShopName"])
export class SingleProduct extends BaseEntity {

    @PrimaryGeneratedColumn('uuid')
    mainId: string;

    @Column({
        type: "integer",
    })
    id: number;

    @Column({
        length: 40,
    })
    extraShopName: string;

    @Column({
        length: 150
    })
    name: string;

    @Column({
        length: 40,
    })
    sku: string;

    @Column({
        length: 9,
    })
    regular_price: string;

    @ManyToOne(type => SingleSyncProduct, entity => entity.shopProducts)
    syncProduct: SingleSyncProduct;
}
</code>```

How can I construct query builder to limit results to 100 SingleSyncProduct with
shopProducts relations?
Select only SingleSyncProduct: id, productName; shopProducts: name

Code below selects 100 results, but it has no more than 1 shopProducts relation result

return await this.dataSource
            .createQueryBuilder(SingleSyncProduct, 'SCP')
            .leftJoinAndSelect('SCP.shopProducts', 'SP')
            .select(['SCP.productId', 'SCP.productName', 'SP.name' ])
            .take(100)
            .getMany();
```
<p><strong>Result</strong></p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "productId": 100000,
    "productName": "Product no 1",
    "shopProducts": [
      {
        "name": "Product 1 from shop no1"
      } // only one result from relation (could be 3 there)
    ]
  },
...99 more results in each only one shopProducts
]
</code>```

Body:
How can I select with typeorm query builder 100 results of SingleSyncProduct with all shopProducts relations? (selecting only productId, productName, and name from relation)

single-sync-product.entity.ts

import {BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn} from "typeorm";
import {SingleProduct} from "../products/single-product.entity";

@Entity()
export class SingleSyncProduct extends BaseEntity {

    @PrimaryGeneratedColumn()
    productId: number;

    @Column({
        length: 150,
    })
    productName: string;

    @Column({
        unique: true,
        length: 40,
    })
    productSKU: string;

    @OneToMany(type => SingleProduct, entity => entity.syncProduct)
    shopProducts: SingleProduct[];

}

single-product.entity.ts

import {BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn, Unique} from "typeorm";
import {SingleSyncProduct} from "../sync-products/single-sync-product.entity";

@Entity()
@Unique(["id", "extraShopName"])
export class SingleProduct extends BaseEntity {

    @PrimaryGeneratedColumn('uuid')
    mainId: string;

    @Column({
        type: "integer",
    })
    id: number;

    @Column({
        length: 40,
    })
    extraShopName: string;

    @Column({
        length: 150
    })
    name: string;

    @Column({
        length: 40,
    })
    sku: string;

    @Column({
        length: 9,
    })
    regular_price: string;

    @ManyToOne(type => SingleSyncProduct, entity => entity.shopProducts)
    syncProduct: SingleSyncProduct;
}

How can I construct query builder to limit results to 100 SingleSyncProduct with
shopProducts relations?
Select only SingleSyncProduct: id, productName; shopProducts: name

Code below selects 100 results, but it has no more than 1 shopProducts relation result

return await this.dataSource
            .createQueryBuilder(SingleSyncProduct, 'SCP')
            .leftJoinAndSelect('SCP.shopProducts', 'SP')
            .select(['SCP.productId', 'SCP.productName', 'SP.name' ])
            .take(100)
            .getMany();

Result

[
  {
    "productId": 100000,
    "productName": "Product no 1",
    "shopProducts": [
      {
        "name": "Product 1 from shop no1"
      } // only one result from relation (could be 3 there)
    ]
  },
...99 more results in each only one shopProducts
]


问:
Android Automotive Emulator (ARM): Fused Location Provider API provides invalid locations
The Fused Location Provider API seems to be broken on the Android Automotive Emulator image Sv2 (API 32, arm64-v8a, with Play Store). Does anyone know of a workaround? It's the only Automotive OS image currently available for ARM-based architectures in Android Studio.

During the first run of the emulator it works perfectly fine. However, as soon as the emulator is stopped and started again (cold boot or not) the following exception is thrown on each location request:

```<code>2023-01-02 15:17:59.431  1827-2496  FusedLocation           com.google.android.gms.persistent    E
dropping invalid locations [CONTEXT service_id=6 ]
vqy: location must not have realtime in the future
    at vts.i(:com.google.android.gms@220221082@22.02.21 (060408-428111784):34)
    at vrd.j(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at vrr.i(:com.google.android.gms@220221082@22.02.21 (060408-428111784):1)
    at vrd.j(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at vrl.a(:com.google.android.gms@220221082@22.02.21 (060408-428111784):3)
    at arsp.d(:com.google.android.gms@220221082@22.02.21 (060408-428111784):10)
    at arvk.i(:com.google.android.gms@220221082@22.02.21 (060408-428111784):18)
    at arve.a(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at vhn.onLocationChanged(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at android.location.LocationListener.onLocationChanged(LocationListener.java:63)
    at android.location.LocationManager$LocationListenerTransport$1.operate(LocationManager.java:3180)
    at android.location.LocationManager$LocationListenerTransport$1.operate(LocationManager.java:3177)
    at com.android.internal.listeners.ListenerExecutor.lambda$executeSafely$0(ListenerExecutor.java:127)
    at com.android.internal.listeners.ListenerExecutor$$ExternalSyntheticLambda0.run(Unknown Source:8)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.os.HandlerThread.run(HandlerThread.java:67)
</code>```

Since "location must not have realtime in the future" seems to suggest a timing problem, I played around with setting the system time manually and cold booting the emulator each time, but had no success.

I request the location periodically with high accuracy like this:

val locationCallback = object : LocationCallback() {
    override fun onLocationResult(result: LocationResult) {
        Log.d("GoogleLocationApi", "onLocationResult: ${result.locations}")
    }
}

val locationRequest = LocationRequest.Builder(2000)
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setMinUpdateIntervalMillis(1000)
    .build()

val fusedLocationClient: FusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(context)

fusedLocationClient.requestLocationUpdates(
    locationRequest,
    locationCallback,
    Looper.getMainLooper()
)
```

Body:
The Fused Location Provider API seems to be broken on the Android Automotive Emulator image Sv2 (API 32, arm64-v8a, with Play Store). Does anyone know of a workaround? It's the only Automotive OS image currently available for ARM-based architectures in Android Studio.

During the first run of the emulator it works perfectly fine. However, as soon as the emulator is stopped and started again (cold boot or not) the following exception is thrown on each location request:

2023-01-02 15:17:59.431  1827-2496  FusedLocation           com.google.android.gms.persistent    E
dropping invalid locations [CONTEXT service_id=6 ]
vqy: location must not have realtime in the future
    at vts.i(:com.google.android.gms@220221082@22.02.21 (060408-428111784):34)
    at vrd.j(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at vrr.i(:com.google.android.gms@220221082@22.02.21 (060408-428111784):1)
    at vrd.j(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at vrl.a(:com.google.android.gms@220221082@22.02.21 (060408-428111784):3)
    at arsp.d(:com.google.android.gms@220221082@22.02.21 (060408-428111784):10)
    at arvk.i(:com.google.android.gms@220221082@22.02.21 (060408-428111784):18)
    at arve.a(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at vhn.onLocationChanged(:com.google.android.gms@220221082@22.02.21 (060408-428111784):0)
    at android.location.LocationListener.onLocationChanged(LocationListener.java:63)
    at android.location.LocationManager$LocationListenerTransport$1.operate(LocationManager.java:3180)
    at android.location.LocationManager$LocationListenerTransport$1.operate(LocationManager.java:3177)
    at com.android.internal.listeners.ListenerExecutor.lambda$executeSafely$0(ListenerExecutor.java:127)
    at com.android.internal.listeners.ListenerExecutor$$ExternalSyntheticLambda0.run(Unknown Source:8)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.os.HandlerThread.run(HandlerThread.java:67)

Since "location must not have realtime in the future" seems to suggest a timing problem, I played around with setting the system time manually and cold booting the emulator each time, but had no success.

I request the location periodically with high accuracy like this:

val locationCallback = object : LocationCallback() {
    override fun onLocationResult(result: LocationResult) {
        Log.d("GoogleLocationApi", "onLocationResult: ${result.locations}")
    }
}

val locationRequest = LocationRequest.Builder(2000)
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setMinUpdateIntervalMillis(1000)
    .build()

val fusedLocationClient: FusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(context)

fusedLocationClient.requestLocationUpdates(
    locationRequest,
    locationCallback,
    Looper.getMainLooper()
)


问:
numpy thread 2 arrays together
I have 3 unequal arrays that I want to thread together as fast as possible. By threading, I mean, given two arrays, a and b:

```<code>a = [1,2]
b = [3,4,5]
</code>```

I want a new array to be given by

```<code>result = [[1,3], [1,4], [1,5], [2,3],[2,4],[2,5]]
</code>```

or another example

```<code>a = 0.5
b = [1,2,3]
result = [[0.5,1],[0.5,2],[0.5,3]]
</code>```

I could obviously do this with list comprehension like [[i,j] for i in a for j in b] but for large lists on the order of 1000 elements, this takes about 0.3 seconds. I thought the list comprehension wouldn't be so slow but I need this to be much faster, if possible. This looks similar to a tensor product, but I obviously don't want the elements to be multiplied.

Title: numpy thread 2 arrays together

Body:
I have 3 unequal arrays that I want to thread together as fast as possible. By threading, I mean, given two arrays, a and b:

a = [1,2]
b = [3,4,5]

I want a new array to be given by

result = [[1,3], [1,4], [1,5], [2,3],[2,4],[2,5]]

or another example

a = 0.5
b = [1,2,3]
result = [[0.5,1],[0.5,2],[0.5,3]]

I could obviously do this with list comprehension like [[i,j] for i in a for j in b] but for large lists on the order of 1000 elements, this takes about 0.3 seconds. I thought the list comprehension wouldn't be so slow but I need this to be much faster, if possible. This looks similar to a tensor product, but I obviously don't want the elements to be multiplied.


问:
Cannot Push To Origin In Github Desktop Interface (Windows)
I cannot push to origin using Github Desktop. Below is the screenshot.

I have already setup the personal access token.

I try to sign out and then sign in again from github desktop app.

But still got error :

```<code>Authentication failed. Some common reasons include:

- You are not logged in to your account: see File > Options.
- You may need to log out and log back in to refresh your token.
- You do not have permission to access this repository.
- The repository is archived on GitHub. Check the repository settings to confirm you are still permitted to push commits.
- If you use SSH authentication, check that your key is added to the ssh-agent and associated with your account.
- If you use SSH authentication, ensure the host key verification passes for your repository hosting service.
- If you used username / password authentication, you might need to use a Personal Access Token instead of your account password. Check the documentation of your repository hosting service.
</code>```

For note :

I have reset my PC and then install back the github desktop app then clone the repository.

Then I cannot push to origin. What could cause the issue and how to solve this?

This is github desktop app. I didn't use git bash. But I have installed the git bash too.

Body:
I cannot push to origin using Github Desktop. Below is the screenshot.

I have already setup the personal access token.

I try to sign out and then sign in again from github desktop app.

But still got error :

Authentication failed. Some common reasons include:

- You are not logged in to your account: see File > Options.
- You may need to log out and log back in to refresh your token.
- You do not have permission to access this repository.
- The repository is archived on GitHub. Check the repository settings to confirm you are still permitted to push commits.
- If you use SSH authentication, check that your key is added to the ssh-agent and associated with your account.
- If you use SSH authentication, ensure the host key verification passes for your repository hosting service.
- If you used username / password authentication, you might need to use a Personal Access Token instead of your account password. Check the documentation of your repository hosting service.

For note :

I have reset my PC and then install back the github desktop app then clone the repository.

Then I cannot push to origin. What could cause the issue and how to solve this?

This is github desktop app. I didn't use git bash. But I have installed the git bash too.


问:
Find synonyms words
How to extract the synonym words the file of elements in Array?

I was able to read from the file, but the elements given in the array are matched in the file, but I want the elements given in the array to show the synonym words of the elements from the file, that is, the synonym word of the element will be shown.

package file;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();

        // Read the words from the file and add them to the ArrayList
        try (Scanner fileScanner = new Scanner(new File("C:\\File\\src\\file\\words.txt"))) {
            while (fileScanner.hasNext()) {
                words.add(fileScanner.next());
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        }

        String wordToFind = "apple";
        String another = "mango";
        int index = words.indexOf(wordToFind);

        if (index != -1) {
            // Get the content of the element at the index
            String content = words.get(index);
            // Print the synonyms of the element
            String[] synonyms = getSynonyms(content);

            for (String synonym : synonyms) {
                System.out.println(synonym);
            }

        } else {
            System.out.println("The word " + wordToFind + " was not found in the ArrayList");
        }
    }

    public static String[] getSynonyms(String word) {
        // TODO: Implement this method to return the synonyms of the given word
        return new String[0];
    }
}
```

Title: Find synonyms words


问:
PHP8.2 Refactoring: How do I refactor dynamic parameters in PHP 8.2 since they are deprecated?
I have used an interface and a trait to fulfill the interface.

```<code>interface Attachable {
    public function getAttachment();
    public function setAttachment($attachment);
}

trait HasAttachment {
    public $attachment = null;

    public function getAttachment() {
        return $this->attachment;
    }

    public function setAttachment($attachment) {
        $this->attachment = $attachment;
    }
}

class SomeClass implements Attachable {
    use HasAttachment;

}
</code>```

I need to unset the attachment in order to serialize and store the data. But when I try this, PHPStan shows error saying it is not a known property of Attachable

```<code>/** @var $data */
if ($data instanceof Attachable) {

    unset($data->attachment); // PHPStan cries here
}
</code>```

I need some way to make phpstan happy in this scenario.

Body:
I have used an interface and a trait to fulfill the interface.

interface Attachable {
    public function getAttachment();
    public function setAttachment($attachment);
}

trait HasAttachment {
    public $attachment = null;

    public function getAttachment() {
        return $this->attachment;
    }

    public function setAttachment($attachment) {
        $this->attachment = $attachment;
    }
}

class SomeClass implements Attachable {
    use HasAttachment;

}

I need to unset the attachment in order to serialize and store the data. But when I try this, PHPStan shows error saying it is not a known property of Attachable

/** @var $data */
if ($data instanceof Attachable) {

    unset($data->attachment); // PHPStan cries here
}

I need some way to make phpstan happy in this scenario.


问:
Is there a way to program VSCode "run button" to execute only a particular file in a directory regardless of active file?
I want to program the VS code button such that I executes only a particular file(whose path will be provided) regardless of the active file in the running directory.</p>


问:
Runtime too slow for minimax implementation (Python 3)
I'm writing a 3D tic tac toe game and I wanted to code an unbeatable ai. I tried to write a minimax function with alpha beta pruning since the search space for 3D tic-tac-toe is very large. However, despite this, my function seems to running indefinitely for a test case I made. Below is the code and the test case. P1 is signified by 1 and p2 by -1.

```<code>def generate_winning_lines(board):
    n = len(board)
    winning_lines = set()

    # Add lines in xy plane
    winning_lines |= {tuple([(x, y, z) for y in range(n)]) for x in range(n) for z in range(n)}

    # Add lines in yz plane
    winning_lines |= {tuple([(x, y, z) for y in range(n)]) for z in range(n) for x in range(n)}

    # Add lines in zx plane
    winning_lines |= {tuple([(x, y, z) for x in range(n)]) for z in range(n) for y in range(n)}

    # Add lines in x direction
    winning_lines |= {tuple([(x, y, z) for x in range(n)]) for y in range(n) for z in range(n)}

    # Add lines in y direction
    winning_lines |= {tuple([(x, y, z) for y in range(n)]) for x in range(n) for z in range(n)}

    # Add lines in z direction
    winning_lines |= {tuple([(x, y, z) for z in range(n)]) for x in range(n) for y in range(n)}

    # Add diagonal lines
    winning_lines |= {tuple([(x, x, x) for x in range(n)])}
    winning_lines |= {tuple([(x, x, n-1-x) for x in range(n)])}
    winning_lines |= {tuple([(x, n-1-x, x) for x in range(n)])}
    winning_lines |= {tuple([(x, n-1-x, n-1-x) for x in range(n)])}
    winning_lines |= {tuple([(x, x, y) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(y, x, x) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(x, y, x) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(x, n -1 -x, y) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(y, x, n -1 -x) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(x, y, n -1 -x) for x in range(n)]) for y in range(n)}

    return winning_lines
def victory_check(board, winning_lines):
    p1, p2 = None, None
    for line in winning_lines:
        values = [board[x][y][z] for x, y, z in line]
        if all(v == 1 for v in values):
            p1 = True, 1
        elif all(v == -1 for v in values):
            p2 = True, -1
        if p1 and p2:
            return True, 0
        elif p1:
            return p1
        elif p2:
            return p2
     return False, 0

def get_possible_moves(board):
    n = len(board)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                if board[i][j][k] == 0:
                    yield i,j,k

def best_move(board, winning_lines):
    n = len(board)
    best_score = float('-inf')
    move = (-1, -1, -1)
    for i,j,k in get_possible_moves(board):
        board[i][j][k] = -1
        curr_score = minimax(board, float('-inf'), float('inf'), False, winning_lines, 0)
        board[i][j][k] = 0
        if curr_score > best_score:
            move = (i,j,k)
            best_score = curr_score
    return move

def minimax(board, alpha, beta, to_max, winning_lines, depth):
    terminal = victory_check(board, winning_lines)
    if terminal[0]:
        return terminal[1]
    if to_max:
        best = float('-inf')
        for i,j,k in get_possible_moves(board):
            board[i][j][k] = -1
            score = minimax(board, alpha, beta, False, winning_lines, depth + 1)
            board[i][j][k] = 0
            best = max(score, best)
            alpha = max(alpha, best)
            if beta <= alpha:
                break
        return best
    else:
        best = float('inf')
        for i,j,k in get_possible_moves(board):
            board[i][j][k] = 1
            score = minimax(board, alpha, beta, True, winning_lines, depth + 1)
            board[i][j][k] = 0
            best = min(score, best)
            beta = min(beta, best)
            if beta <= alpha:
                break
        return best

# Testcase

board = [ # We want the function to return (0, 1, 1)
        [
            [1,-1,0],
            [0,0,0],
            [0,0,1],
        ],
        [
            [0,0,0],
            [0,0,0],
            [0,0,0],
        ],
        [
            [0,0,0],
            [0,0,0],
            [0,0,0],
        ],
    ]

</code>```

I've tried introducing a depth variable to stop the function from getting arbitrarily deep but it returns an incorrect move.

Body:
I'm writing a 3D tic tac toe game and I wanted to code an unbeatable ai. I tried to write a minimax function with alpha beta pruning since the search space for 3D tic-tac-toe is very large. However, despite this, my function seems to running indefinitely for a test case I made. Below is the code and the test case. P1 is signified by 1 and p2 by -1.

def generate_winning_lines(board):
    n = len(board)
    winning_lines = set()

    # Add lines in xy plane
    winning_lines |= {tuple([(x, y, z) for y in range(n)]) for x in range(n) for z in range(n)}

    # Add lines in yz plane
    winning_lines |= {tuple([(x, y, z) for y in range(n)]) for z in range(n) for x in range(n)}

    # Add lines in zx plane
    winning_lines |= {tuple([(x, y, z) for x in range(n)]) for z in range(n) for y in range(n)}

    # Add lines in x direction
    winning_lines |= {tuple([(x, y, z) for x in range(n)]) for y in range(n) for z in range(n)}

    # Add lines in y direction
    winning_lines |= {tuple([(x, y, z) for y in range(n)]) for x in range(n) for z in range(n)}

    # Add lines in z direction
    winning_lines |= {tuple([(x, y, z) for z in range(n)]) for x in range(n) for y in range(n)}

    # Add diagonal lines
    winning_lines |= {tuple([(x, x, x) for x in range(n)])}
    winning_lines |= {tuple([(x, x, n-1-x) for x in range(n)])}
    winning_lines |= {tuple([(x, n-1-x, x) for x in range(n)])}
    winning_lines |= {tuple([(x, n-1-x, n-1-x) for x in range(n)])}
    winning_lines |= {tuple([(x, x, y) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(y, x, x) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(x, y, x) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(x, n -1 -x, y) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(y, x, n -1 -x) for x in range(n)]) for y in range(n)}
    winning_lines |= {tuple([(x, y, n -1 -x) for x in range(n)]) for y in range(n)}

    return winning_lines
def victory_check(board, winning_lines):
    p1, p2 = None, None
    for line in winning_lines:
        values = [board[x][y][z] for x, y, z in line]
        if all(v == 1 for v in values):
            p1 = True, 1
        elif all(v == -1 for v in values):
            p2 = True, -1
        if p1 and p2:
            return True, 0
        elif p1:
            return p1
        elif p2:
            return p2
     return False, 0

def get_possible_moves(board):
    n = len(board)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                if board[i][j][k] == 0:
                    yield i,j,k

def best_move(board, winning_lines):
    n = len(board)
    best_score = float('-inf')
    move = (-1, -1, -1)
    for i,j,k in get_possible_moves(board):
        board[i][j][k] = -1
        curr_score = minimax(board, float('-inf'), float('inf'), False, winning_lines, 0)
        board[i][j][k] = 0
        if curr_score > best_score:
            move = (i,j,k)
            best_score = curr_score
    return move

def minimax(board, alpha, beta, to_max, winning_lines, depth):
    terminal = victory_check(board, winning_lines)
    if terminal[0]:
        return terminal[1]
    if to_max:
        best = float('-inf')
        for i,j,k in get_possible_moves(board):
            board[i][j][k] = -1
            score = minimax(board, alpha, beta, False, winning_lines, depth + 1)
            board[i][j][k] = 0
            best = max(score, best)
            alpha = max(alpha, best)
            if beta <= alpha:
                break
        return best
    else:
        best = float('inf')
        for i,j,k in get_possible_moves(board):
            board[i][j][k] = 1
            score = minimax(board, alpha, beta, True, winning_lines, depth + 1)
            board[i][j][k] = 0
            best = min(score, best)
            beta = min(beta, best)
            if beta <= alpha:
                break
        return best

# Testcase

board = [ # We want the function to return (0, 1, 1)
        [
            [1,-1,0],
            [0,0,0],
            [0,0,1],
        ],
        [
            [0,0,0],
            [0,0,0],
            [0,0,0],
        ],
        [
            [0,0,0],
            [0,0,0],
            [0,0,0],
        ],
    ]

I've tried introducing a depth variable to stop the function from getting arbitrarily deep but it returns an incorrect move.


问:
Why my ReactJS navbar toggle button not responsive in mobile when I scroll up
I am creating a Web Page. My ReactJS Bootstrap toggle button not working properly in Mobile browser (chorme and other mobile browsers). Everything is working in my Laptop very well, but when I check in mobile phone then I am getting responsive issue only in toggle button.

When I scroll down to the FOOTER then the button WORKS fine very well responsively but when when I scroll up again then the button does not work responsively like the below image.

Please check my screenshot image and code. I uploaded here only css part of navbar and jsx file of navbar.
Thanks in advance for your great support.!

```<code>import './mynavvv.css';
import { Link } from 'react-router-dom';
import "bootstrap/dist/css/bootstrap.min.css";

import {
  Navbar,
  Container,
  NavDropdown,
  Nav
} from "react-bootstrap";
import {useState} from "react"
import Mysvg from '../../pagess/Mysvg';

const Mynavvv = ()=> {

  const [colorChange, setColorchange] = useState(false);
  const changeNavbarColor = () =>{
     if(window.scrollY >= 80){
       setColorchange(true);
     }
     else{
       setColorchange(false);
     }
  };
  window.addEventListener('scroll', changeNavbarColor);

const design=(
      <>

       <Navbar className="justify-content-center" expand="lg" id="MyNav" fixed="top" style={{ transition: '1s ease',backgroundColor: colorChange ? '#212529' : 'transparent'}}>
       <Container>
  <Link className="navbar-brand" to="./">
  <Mysvg/>
    </Link>
       <Navbar.Toggle aria-controls="responsive-navbar-nav" />
           <Navbar.Collapse id="responsive-navbar-nav">
           <Nav className="ms-auto">
      <ul className="navbar-nav">
        <li className="nav-item">
        <Link className="nav-link active" to="./">Home</Link>
        </li>

        <li className="nav-item">
        <Link className="nav-link" to="/About">About</Link>
        </li>

        <li className="nav-item">
        <Link className="nav-link" to="/Contact">Contact</Link>
        </li>

        <li className="nav-item">
        <Link className="nav-link" to="/Phone">Phone</Link>
        </li>

        <li className="nav-item dropdown">
        <Link  className="nav-link dropdown-toggle" to="#" role="button" data-bs-toggle="dropdown">Services</Link>
          <ul className="dropdown-menu">
<li><Link className="nav-link" to="/DropDownOne">Drop Down One</Link> </li>
           </ul>
        </li>
      </ul>
    </Nav>
      </Navbar.Collapse>
    </Container>
  </Navbar>
</>
);
  return design;
  }
  export default Mynavvv;
</code>```

CSS PART

```<code>#MyNav {
    background-color:#212529;

  }

  #MyNav .navbar-toggler:focus {

  box-shadow:none !important;
  outline: none;

  }

  #MyNav .navbar-toggler {
    font-size: 14px;
    right: 0;
    padding: 13px;
    text-transform: uppercase;
    color: white;
    border: 0;
    background-color: #FFA500;
   font-family: 'Ubuntu', sans-serif;
  }

  #MyNav .navbar-nav .nav-item .nav-link {
    font-size: 88%;
    font-weight: 400;
    padding: 0.72em 0;
    letter-spacing: 1px;
    color: white;
   font-family: 'Ubuntu', sans-serif;
  }

  #MyNav .navbar-nav .nav-item .nav-link.active, #MyNav .navbar-nav .nav-item .nav-link:hover {
    color: #FFA500;
  }

   .dropdown-menu {
    background-color: #212529;
    opacity: 1.8;

   }

  .dropdown-item{
  color: white;
   font-size: 88%;
  font-weight: 400;
  letter-spacing: 1px;

  font-family: 'Ubuntu', sans-serif;
  }
  .dropdown-item:hover{
  color: #FFA500;
  }
  .dropdown:hover>.dropdown-menu {
    display: block;
  }

  .dropdown>.dropdown-toggle:active {
    /*Without this, clicking will make it sticky*/
      pointer-events: none;
  }

  @media (min-width: 992px) {
    #MyNav {
      padding-top: 25px;
      padding-bottom: 25px;
      -webkit-transition: padding-top 0.3s, padding-bottom 0.3s;
      transition: padding-top 0.3s, padding-bottom 0.3s;
      border: none;
      background-color: transparent;
    }

    #MyNav .navbar-brand{
      -webkit-transition: all 0.5s;
      transition: all 0.5s;
      padding: 0px;
      margin: 0px;
    }
    #MyNav .navbar-nav .nav-item .nav-link {
      padding: 0.2em 1em !important;
    }
    #MyNav.navbar-shrink {
      padding-top: 0;
      padding-bottom: 0;
      background-color: #212529;
    }
    #MyNav.navbar-shrink .navbar-brand{
      padding: 12px 0;
    }
  }
  @media (max-width: 767px){
    #MyNav .navbar-nav .nav-item .nav-link {
      padding: 0.4em 1em !important;
    }

      }

</code>```

Body:
I am creating a Web Page. My ReactJS Bootstrap toggle button not working properly in Mobile browser (chorme and other mobile browsers). Everything is working in my Laptop very well, but when I check in mobile phone then I am getting responsive issue only in toggle button.

When I scroll down to the FOOTER then the button WORKS fine very well responsively but when when I scroll up again then the button does not work responsively like the below image.

Please check my screenshot image and code. I uploaded here only css part of navbar and jsx file of navbar.
Thanks in advance for your great support.!

import './mynavvv.css';
import { Link } from 'react-router-dom';
import "bootstrap/dist/css/bootstrap.min.css";

import {
  Navbar,
  Container,
  NavDropdown,
  Nav
} from "react-bootstrap";
import {useState} from "react"
import Mysvg from '../../pagess/Mysvg';

const Mynavvv = ()=> {

  const [colorChange, setColorchange] = useState(false);
  const changeNavbarColor = () =>{
     if(window.scrollY >= 80){
       setColorchange(true);
     }
     else{
       setColorchange(false);
     }
  };
  window.addEventListener('scroll', changeNavbarColor);

const design=(
      <>

       <Navbar className="justify-content-center" expand="lg" id="MyNav" fixed="top" style={{ transition: '1s ease',backgroundColor: colorChange ? '#212529' : 'transparent'}}>
       <Container>
  <Link className="navbar-brand" to="./">
  <Mysvg/>
    </Link>
       <Navbar.Toggle aria-controls="responsive-navbar-nav" />
           <Navbar.Collapse id="responsive-navbar-nav">

        <Link className="nav-link active" to="./">Home</Link>

        <Link className="nav-link" to="/About">About</Link>

        <Link className="nav-link" to="/Contact">Contact</Link>

        <Link className="nav-link" to="/Phone">Phone</Link>

        <Link  className="nav-link dropdown-toggle" to="#" role="button" data-bs-toggle="dropdown">Services</Link>

<Link className="nav-link" to="/DropDownOne">Drop Down One</Link>

      </Navbar.Collapse>
    </Container>
  </Navbar>
</>
);
  return design;
  }
  export default Mynavvv;

CSS PART

#MyNav {
    background-color:#212529;

  }

  #MyNav .navbar-toggler:focus {

  box-shadow:none !important;
  outline: none;

  }

  #MyNav .navbar-toggler {
    font-size: 14px;
    right: 0;
    padding: 13px;
    text-transform: uppercase;
    color: white;
    border: 0;
    background-color: #FFA500;
   font-family: 'Ubuntu', sans-serif;
  }

  #MyNav .navbar-nav .nav-item .nav-link {
    font-size: 88%;
    font-weight: 400;
    padding: 0.72em 0;
    letter-spacing: 1px;
    color: white;
   font-family: 'Ubuntu', sans-serif;
  }

  #MyNav .navbar-nav .nav-item .nav-link.active, #MyNav .navbar-nav .nav-item .nav-link:hover {
    color: #FFA500;
  }

   .dropdown-menu {
    background-color: #212529;
    opacity: 1.8;

   }

  .dropdown-item{
  color: white;
   font-size: 88%;
  font-weight: 400;
  letter-spacing: 1px;

  font-family: 'Ubuntu', sans-serif;
  }
  .dropdown-item:hover{
  color: #FFA500;
  }
  .dropdown:hover>.dropdown-menu {
    display: block;
  }

  .dropdown>.dropdown-toggle:active {
    /*Without this, clicking will make it sticky*/
      pointer-events: none;
  }

  @media (min-width: 992px) {
    #MyNav {
      padding-top: 25px;
      padding-bottom: 25px;
      -webkit-transition: padding-top 0.3s, padding-bottom 0.3s;
      transition: padding-top 0.3s, padding-bottom 0.3s;
      border: none;
      background-color: transparent;
    }

    #MyNav .navbar-brand{
      -webkit-transition: all 0.5s;
      transition: all 0.5s;
      padding: 0px;
      margin: 0px;
    }
    #MyNav .navbar-nav .nav-item .nav-link {
      padding: 0.2em 1em !important;
    }
    #MyNav.navbar-shrink {
      padding-top: 0;
      padding-bottom: 0;
      background-color: #212529;
    }
    #MyNav.navbar-shrink .navbar-brand{
      padding: 12px 0;
    }
  }
  @media (max-width: 767px){
    #MyNav .navbar-nav .nav-item .nav-link {
      padding: 0.4em 1em !important;
    }

      }


问:
find: 'home/': No such file or directory while trying to automate maintenance tasks
I'm trying to create a bash script to perform some maintenance tasks on a remote server using ssh. I've been trying to figure it out on my own, but I'm having some difficulty. I was hoping someone here on Stack Overflow might be able to help me out.

I'm not very familiar with bash scripting, so any guidance or suggestions you could provide would be greatly appreciated.

Here's what I'm trying to accomplish:

Connect to a remote server via ssh

Delete files that are older than 3 months

Update server packages

Check disk sizes and send a notification if the disk is 75% full

Commands:

SSH into the remote server.

Update server packages.

Delete files older than 3 months.

Check disk sizes and send notification if 75% full.

```<code># maintenance.sh
# Connect to the remote server
ssh username@remote_server_ip "cd /"

# Update server packages
ssh username@server "apt-get update && apt-get upgrade"

# Delete files older than 3 months
ssh username@server "find home/ -mtime +90 -delete"

# Check disk sizes and send notification if 75% full
ssh username@server "disk_size=$(df -h / | grep -v Filesystem | awk '{print $5}')
if [[ $disk_size > 75 ]]; then
  echo 'Low disk space on server. Disk usage is currently at $disk_size%' | mail -s 'Low Disk $ip a Alert' admin@example.com "
</code>```

Problems:

The find command doesn't seem to be working as intended. It's not deleting any files.

```<code>codemastermind@ThinkPad-X230:~/scripts$ ./maintenance.sh
find: 'home/': No such file or directory
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
codemastermind@ThinkPad-X230:~/scripts$
</code>```

Body:
I'm trying to create a bash script to perform some maintenance tasks on a remote server using ssh. I've been trying to figure it out on my own, but I'm having some difficulty. I was hoping someone here on Stack Overflow might be able to help me out.

I'm not very familiar with bash scripting, so any guidance or suggestions you could provide would be greatly appreciated.

Here's what I'm trying to accomplish:

Connect to a remote server via ssh

Delete files that are older than 3 months

Update server packages

Check disk sizes and send a notification if the disk is 75% full

Commands:

SSH into the remote server.

Update server packages.

Delete files older than 3 months.

Check disk sizes and send notification if 75% full.

# maintenance.sh
# Connect to the remote server
ssh username@remote_server_ip "cd /"

# Update server packages
ssh username@server "apt-get update && apt-get upgrade"

# Delete files older than 3 months
ssh username@server "find home/ -mtime +90 -delete"

# Check disk sizes and send notification if 75% full
ssh username@server "disk_size=$(df -h / | grep -v Filesystem | awk '{print $5}')
if [[ $disk_size > 75 ]]; then
  echo 'Low disk space on server. Disk usage is currently at $disk_size%' | mail -s 'Low Disk $ip a Alert' admin@example.com "

Problems:

The find command doesn't seem to be working as intended. It's not deleting any files.

codemastermind@ThinkPad-X230:~/scripts$ ./maintenance.sh
find: 'home/': No such file or directory
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
codemastermind@ThinkPad-X230:~/scripts$


问:
trouble with WebAssembly from swc and vite
My application tries to load swc with a dynamic import:

```<code>const swcWasmWeb = await import("@swc/wasm-web");

await swcWasmWeb.default();
</code>```

this works fine, if the WASM-file is copied manually to

```<code>..\node_modules\.vite\deps
</code>```

How can i configure vite to copy the file automatically and treat it as a dependency?

I have tried to add an import like that (see https://vitejs.dev/guide/assets.html):

```<code>import _ from "@swc/wasm-web/wasm-web_bg.wasm?url";
</code>```

also tried to add it to the vite.config.ts like:

```<code>assetsInclude: ["@swc/wasm-web/wasm-web_bg.wasm"],
</code>```

So what is the right notation?

I'm using Vite 4.0.3 with React 18.2 and Typescript.

Body:
My application tries to load swc with a dynamic import:

const swcWasmWeb = await import("@swc/wasm-web");

await swcWasmWeb.default();

this works fine, if the WASM-file is copied manually to

..\node_modules\.vite\deps

How can i configure vite to copy the file automatically and treat it as a dependency?

I have tried to add an import like that (see https://vitejs.dev/guide/assets.html):

import _ from "@swc/wasm-web/wasm-web_bg.wasm?url";

also tried to add it to the vite.config.ts like:

assetsInclude: ["@swc/wasm-web/wasm-web_bg.wasm"],

So what is the right notation?

I'm using Vite 4.0.3 with React 18.2 and Typescript.


问:
Adding Patient Information Failure in form and database
I am a student and I a am making a system for our project. I want to Add information but when I input data in my form, no data has been added. I tried checking my database and there's no data added. Please help.

I tried checking my database and everything are all good. EVerything are matched in my codes but I still cant add information in my database

```<code>Here are my codes:

`<?php

session_start();

if(!isset($_SESSION['UserLogin'])){

  header("Location: login.php");
  exit;
}

include_once('connections.php');
$con = connection();

if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['date_of_birth']) && isset($_POST['gender']) && isset($_POST['address']) && isset($_POST['category']) && isset($_POST['state']) && isset($_POST['medical_history']) && isset($_POST['date_of_admission']) && isset($_POST['diagnoses']) && isset($_POST['prescription']) && isset($_POST['phone_number'])) {

    $first_name = mysqli_real_escape_string($con, $_POST['first_name']);
    $last_name = mysqli_real_escape_string($con, $_POST['last_name']);
    $date_of_birth = mysqli_real_escape_string($con, $_POST['date_of_birth']);
    $gender = mysqli_real_escape_string($con, $_POST['gender']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    $category = mysqli_real_escape_string($con, $_POST['category']);
    $state = mysqli_real_escape_string($con, $_POST['state']);
    $medical_history = mysqli_real_escape_string($con, $_POST['medical_history']);
    $date_of_admission = mysqli_real_escape_string($con, $_POST['date_of_admission']);
    $diagnoses = mysqli_real_escape_string($con, $_POST['diagnoses']);
    $prescription = mysqli_real_escape_string($con, $_POST['prescription']);
    $phone_number = mysqli_real_escape_string($con, $_POST['phone_number']);
    $sql = "INSERT INTO patient_rec (First_name, Last_name, Date_of_birth, Gender, Address, Category, State, Medical_history, Date_of_admission, Diagnoses, Prescription, Phone_number) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("sssssssssss", $first_name, $last_name, $date_of_birth, $gender, $address, $category, $state, $medical_history, $date_of_admission, $diagnoses, $prescription, $phone_number);
    $stmt->execute();
    }

    mysqli_close($con);
    session_write_close();

    header("Location: index.php");
    exit;

    ?>

<?php

session_start();

if (!isset($_SESSION['UserLogin']) || !$_SESSION['UserLogin']) {

  header('Location: login.php');
  exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content ="width=device-width, initial-scale=.75">
  <link rel="stylesheet" type="text/css" href="addform.css">
  <body>
</br>
<h1>Add Patient Information</h1>
<h2>Bayawan District hospital</h2>
<h3>236 Zamora St, Bayawan City, 6221 Negros Oriental</h3>
</br>
  <img src="logo.png" alt="Logo" class="logo">
  <form action="add.php" method="POST">
  <label for="first_name">First Name:</label><br>
  <input type="text" name="first_name" id="first_name" placeholder="Please type your first name" required><br>
  <label for="last_name">Last Name:</label><br>
  <input type="text" name="last_name" id="last_name" placeholder="Please type your last name" required><br>
  <label for="date_of_birth">Date of Birth:</label><br>
  <input type="date" name="date_of_birth" id="date_of_birth" required><br>
  <label for="gender">Gender:</label><br>
  <input type="radio" name="gender" value="male" id="gender_male"> Male
  <input type="radio" name="gender" value="female" id="gender_female"> Female<br>
  <label for="address">Address:</label><br>
  <input type="text" name="address" id="address" placeholder="Please type your address" required><br>
  <label for="phone_number">Phone Number:</label><br>
<input type="text" name="phone_number" id="phone_number" pattern="[0-9]{11}" required>

  <label for="category">Category:</label><br>
  <select name="category" id="category" required>
    <option value="">-Select Choices-</option>
    <option value="Primary Care">Primary Care</option>
    <option value="Specialty Care">Specialty Care</option>
    <option value="Emergency Care">Emergency Care</option>
    <option value="Urgent Care">Urgent Care</option>
    <option value="Long-term Care">Long-term Care</option>
    <option value="Hospice Care">Hospice Care</option>
    <option value="Mental Healthcare">Mental Healthcare</option>

  </select><br>
  <label for="state">Status:</label><br>
  <select name="state" id="state" required><br>
  <option value="">-Select Choices-</option>
  <option value="New patient">New patient</option>
  <option value="Established patient">Established patient</option>
  <option value="Outpatient">Outpatient</option>
  <option value="Inpatient">Inpatient</option>
</select><br>

  <label for="medical_history">Medical History:</label><br>
  <textarea name="medical_history" id="medical_history" placeholder="Please type here..." rows="4" cols="50" required></textarea><br>
<label for="date_of_admission">Date of Admission:</label><br>
<input type="date" name="date_of_admission" id="date_of_admission" required><br>
<label for="diagnoses">Diagnoses:</label><br>
<textarea name="diagnoses" id="diagnoses" placeholder="Please type here..." rows="4" cols="50" required></textarea><br>
<label for="prescription">Prescription:</label><br>
<textarea name="prescription" id="prescription" placeholder="Please type here..." rows="4" cols="50" required></textarea><br>
<input type="submit" value="Add Patient">
<a href="index.php"><button type="button" class="logbtn">Cancel</button></a>
</form>
</body>
`
</code>```

Body:
I am a student and I a am making a system for our project. I want to Add information but when I input data in my form, no data has been added. I tried checking my database and there's no data added. Please help.

I tried checking my database and everything are all good. EVerything are matched in my codes but I still cant add information in my database

Here are my codes:

`<?php

session_start();

if(!isset($_SESSION['UserLogin'])){

  header("Location: login.php");
  exit;
}

include_once('connections.php');
$con = connection();

if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['date_of_birth']) && isset($_POST['gender']) && isset($_POST['address']) && isset($_POST['category']) && isset($_POST['state']) && isset($_POST['medical_history']) && isset($_POST['date_of_admission']) && isset($_POST['diagnoses']) && isset($_POST['prescription']) && isset($_POST['phone_number'])) {

    $first_name = mysqli_real_escape_string($con, $_POST['first_name']);
    $last_name = mysqli_real_escape_string($con, $_POST['last_name']);
    $date_of_birth = mysqli_real_escape_string($con, $_POST['date_of_birth']);
    $gender = mysqli_real_escape_string($con, $_POST['gender']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    $category = mysqli_real_escape_string($con, $_POST['category']);
    $state = mysqli_real_escape_string($con, $_POST['state']);
    $medical_history = mysqli_real_escape_string($con, $_POST['medical_history']);
    $date_of_admission = mysqli_real_escape_string($con, $_POST['date_of_admission']);
    $diagnoses = mysqli_real_escape_string($con, $_POST['diagnoses']);
    $prescription = mysqli_real_escape_string($con, $_POST['prescription']);
    $phone_number = mysqli_real_escape_string($con, $_POST['phone_number']);
    $sql = "INSERT INTO patient_rec (First_name, Last_name, Date_of_birth, Gender, Address, Category, State, Medical_history, Date_of_admission, Diagnoses, Prescription, Phone_number) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("sssssssssss", $first_name, $last_name, $date_of_birth, $gender, $address, $category, $state, $medical_history, $date_of_admission, $diagnoses, $prescription, $phone_number);
    $stmt->execute();
    }

    mysqli_close($con);
    session_write_close();

    header("Location: index.php");
    exit;

    ?>

<?php

session_start();

if (!isset($_SESSION['UserLogin']) || !$_SESSION['UserLogin']) {

  header('Location: login.php');
  exit;
}
?>
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content ="width=device-width, initial-scale=.75">
  <link rel="stylesheet" type="text/css" href="addform.css">

Add Patient Information

Bayawan District hospital

236 Zamora St, Bayawan City, 6221 Negros Oriental

  <form action="add.php" method="POST">
  First Name:

  <input type="text" name="first_name" id="first_name" placeholder="Please type your first name" required>

  Last Name:

  <input type="text" name="last_name" id="last_name" placeholder="Please type your last name" required>

  Date of Birth:

  <input type="date" name="date_of_birth" id="date_of_birth" required>

  Gender:

  <input type="radio" name="gender" value="male" id="gender_male"> Male
  <input type="radio" name="gender" value="female" id="gender_female"> Female

  Address:

  <input type="text" name="address" id="address" placeholder="Please type your address" required>

  Phone Number:

<input type="text" name="phone_number" id="phone_number" pattern="[0-9]{11}" required>

  Category:

  <select name="category" id="category" required>
    <option value="">-Select Choices-</option>
    <option value="Primary Care">Primary Care</option>
    <option value="Specialty Care">Specialty Care</option>
    <option value="Emergency Care">Emergency Care</option>
    <option value="Urgent Care">Urgent Care</option>
    <option value="Long-term Care">Long-term Care</option>
    <option value="Hospice Care">Hospice Care</option>
    <option value="Mental Healthcare">Mental Healthcare</option>

  </select>

  Status:

  <select name="state" id="state" required>

  <option value="">-Select Choices-</option>
  <option value="New patient">New patient</option>
  <option value="Established patient">Established patient</option>
  <option value="Outpatient">Outpatient</option>
  <option value="Inpatient">Inpatient</option>
</select>

  Medical History:

  <textarea name="medical_history" id="medical_history" placeholder="Please type here..." rows="4" cols="50" required></textarea>

Date of Admission:

<input type="date" name="date_of_admission" id="date_of_admission" required>

Diagnoses:

<textarea name="diagnoses" id="diagnoses" placeholder="Please type here..." rows="4" cols="50" required></textarea>

Prescription:

<textarea name="prescription" id="prescription" placeholder="Please type here..." rows="4" cols="50" required></textarea>

<input type="submit" value="Add Patient">
<button type="button" class="logbtn">Cancel</button>
</form>

`


问:
How to register Exec callbacks in gorm?
I want to globally capture the case of db write failure, and then do something.

Now I capture the results of create, update, and delete by registering callbacks.but I found that in addition to these three write methods, there is also Exec. , now I don't know how to capture the result of the operation performed through Exec.

Title: How to register Exec callbacks in gorm?


问:
python watchdog getting the last file created
I'm using watchdog to track the creation of files on a file-system.

`

```<code>def watch_new_files_local():
    """
    Method that checks changes in a local filesystem for a give root directory.
    The root directory is defined in the config.ini file.
    """
    conf = ConfigParser()
    patterns = "*"
    ignore_patterns = ""
    ignore_directories = True
    case_sensitive = False
    event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)

    # relevant event handlers (methods for each handler are created):
    event_handler.on_created = on_created
    event_handler.on_deleted = on_deleted
    event_handler.on_modified = on_modified

    path = str(conf.get_config_value('IMAGE_FILES', 'local_path'))
    my_observer = Observer()
    my_observer.schedule(event_handler, path, recursive=True)

    my_observer.start()
    logging.info("starting to watch files")

    try:
        while True:
            t.sleep(int(conf.get_config_value('IMAGE_FILES', 'interval')))
    except KeyboardInterrupt:
        my_observer.stop()
        my_observer.join()
</code>```

`

in the specific on_created or on_modified method the processing happens. However, if the processing takes longer and new files arrives in the meantime, I need a way to access the event queue and only start the processing on the last arriving file and ignore other irrelevant files.

I have tried to access the watchdog.observers.api.EventQueue but have not found a way to access the queue.

Body:
I'm using watchdog to track the creation of files on a file-system.

`

def watch_new_files_local():
    """
    Method that checks changes in a local filesystem for a give root directory.
    The root directory is defined in the config.ini file.
    """
    conf = ConfigParser()
    patterns = "*"
    ignore_patterns = ""
    ignore_directories = True
    case_sensitive = False
    event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)

    # relevant event handlers (methods for each handler are created):
    event_handler.on_created = on_created
    event_handler.on_deleted = on_deleted
    event_handler.on_modified = on_modified

    path = str(conf.get_config_value('IMAGE_FILES', 'local_path'))
    my_observer = Observer()
    my_observer.schedule(event_handler, path, recursive=True)

    my_observer.start()
    logging.info("starting to watch files")

    try:
        while True:
            t.sleep(int(conf.get_config_value('IMAGE_FILES', 'interval')))
    except KeyboardInterrupt:
        my_observer.stop()
        my_observer.join()

`

in the specific on_created or on_modified method the processing happens. However, if the processing takes longer and new files arrives in the meantime, I need a way to access the event queue and only start the processing on the last arriving file and ignore other irrelevant files.

I have tried to access the watchdog.observers.api.EventQueue but have not found a way to access the queue.