问:
How to rotate camera to point without using lookAt method
I am trying to implement 360 degree rotation camera with offset to another 3d object and lookAt to point. Camera offset and lookAt points are relative to 3d object quaternion.
I have 3d object which locates at center of the world coordinates. Then i want to offset camera like third-person camera implementation. Position isn't a problem, i tried like this:

```<code>    const cameraOffset = new Vector3(0, 2, 3)

    cameraOffset.applyQuaternion(this.ship.quaternion)
    cameraOffset.add(this.ship.position)

    this.position.lerp(cameraOffset, 0.1)
    this.tjsObject.position.copy(this.position)
</code>```

this.tjsObejct: Three.js Object3D type.
It works and the offset vector follows object when it is rotating.
But i want make focus camera at the different direction with the object like so:

```<code>    const cameraLookAt = new Vector3(0, 1, -5)

    cameraLookAt.applyQuaternion(this.ship.quaternion)
    cameraLookAt.add(this.ship.position)

    this.lookAt.lerp(cameraLookAt, 0.1)
    this.tjsObject.lookAt(this.lookAt)
</code>```

lookAt works fine, but when 3d object rotation higher 180 or lower -180 degrees, lookAt method uses camera.up vector, so camera always oriented to it.

I tried find euler angles between cameraLookAt vector and camera world direction, but have no luck with it:

```<code>    const f = new Vector3()
    this.tjsObject.getWorldDirection(f)
    f.sub(this.tjsObject.position)
    f.normalize()

    cameraLookAt.sub(this.tjsObject.position)
    cameraLookAt.normalize()

    const x = new Vector3(1, 0, 0)
    const y = new Vector3(0, 1, 0)
    const z = new Vector3(0, 0, 1)
    x.normalize()
    y.normalize()
    z.normalize()
    const fProjectXY = f.clone().projectOnPlane(z)
    const fProjectXZ = f.clone().projectOnPlane(y)
    const fProjectZY = f.clone().projectOnPlane(x)

    const cameraLookAtProjectXY = cameraLookAt.clone().projectOnPlane(z)
    const cameraLookAtProjectXZ = cameraLookAt.clone().projectOnPlane(y)
    const cameraLookAtProjectZY = cameraLookAt.clone().projectOnPlane(x)

    console.log(fProjectXY, fProjectXZ, fProjectZY)

    const zAngleFCamera = fProjectXY.angleTo(cameraLookAtProjectXY)
    const yAngleFCamera = fProjectXZ.angleTo(cameraLookAtProjectXZ)
    const xAngleFCamera = fProjectZY.angleTo(cameraLookAtProjectZY)

    const eulerRotation = new Euler()
    eulerRotation.set(xAngleFCamera, yAngleFCamera, zAngleFCamera)

    const q = new Quaternion().setFromEuler(eulerRotation)

    this.tjsObject.quaternion.slerp(q, 0.1)
</code>```

I tried change camera.up vector when 3d object rotation higher 180 or lower -180 degrees too, but it was noticeable that she was switching

Body:
I am trying to implement 360 degree rotation camera with offset to another 3d object and lookAt to point. Camera offset and lookAt points are relative to 3d object quaternion.
I have 3d object which locates at center of the world coordinates. Then i want to offset camera like third-person camera implementation. Position isn't a problem, i tried like this:

    const cameraOffset = new Vector3(0, 2, 3)

    cameraOffset.applyQuaternion(this.ship.quaternion)
    cameraOffset.add(this.ship.position)

    this.position.lerp(cameraOffset, 0.1)
    this.tjsObject.position.copy(this.position)

this.tjsObejct: Three.js Object3D type.
It works and the offset vector follows object when it is rotating.
But i want make focus camera at the different direction with the object like so:

    const cameraLookAt = new Vector3(0, 1, -5)

    cameraLookAt.applyQuaternion(this.ship.quaternion)
    cameraLookAt.add(this.ship.position)

    this.lookAt.lerp(cameraLookAt, 0.1)
    this.tjsObject.lookAt(this.lookAt)

lookAt works fine, but when 3d object rotation higher 180 or lower -180 degrees, lookAt method uses camera.up vector, so camera always oriented to it.

I tried find euler angles between cameraLookAt vector and camera world direction, but have no luck with it:

    const f = new Vector3()
    this.tjsObject.getWorldDirection(f)
    f.sub(this.tjsObject.position)
    f.normalize()

    cameraLookAt.sub(this.tjsObject.position)
    cameraLookAt.normalize()

    const x = new Vector3(1, 0, 0)
    const y = new Vector3(0, 1, 0)
    const z = new Vector3(0, 0, 1)
    x.normalize()
    y.normalize()
    z.normalize()
    const fProjectXY = f.clone().projectOnPlane(z)
    const fProjectXZ = f.clone().projectOnPlane(y)
    const fProjectZY = f.clone().projectOnPlane(x)

    const cameraLookAtProjectXY = cameraLookAt.clone().projectOnPlane(z)
    const cameraLookAtProjectXZ = cameraLookAt.clone().projectOnPlane(y)
    const cameraLookAtProjectZY = cameraLookAt.clone().projectOnPlane(x)

    console.log(fProjectXY, fProjectXZ, fProjectZY)

    const zAngleFCamera = fProjectXY.angleTo(cameraLookAtProjectXY)
    const yAngleFCamera = fProjectXZ.angleTo(cameraLookAtProjectXZ)
    const xAngleFCamera = fProjectZY.angleTo(cameraLookAtProjectZY)

    const eulerRotation = new Euler()
    eulerRotation.set(xAngleFCamera, yAngleFCamera, zAngleFCamera)

    const q = new Quaternion().setFromEuler(eulerRotation)

    this.tjsObject.quaternion.slerp(q, 0.1)

I tried change camera.up vector when 3d object rotation higher 180 or lower -180 degrees too, but it was noticeable that she was switching


来源: stackexchange

问:
How to integrate Intellij and Databricks, like when using the jdwp with a regular Spark cluster?
I have been looking online for awhile, but have found nothing, thus this question. I would like to be able to debug my Apache Spark code (written in Scala) remotely on Databricks, similar to the way it can be done on regular Spark clusters using the Java Debug Wire Protocol (or jdwp). Is this possible at all? Can it, perhaps, be done using the Databrick Labs dbx tool? Or just by using a host and port number (and, possibly as well, a Databricks token) with said jdwp?

Any response will be greatly aprreciated.

Thanks in advance.

ContentLicense: CC BY-SA 4.0


问:
how does "is_pressed" in keyboard&mouse module exactly work?
im trying to check if a keybutton or a mousebutton is pressed but 'is_pressed' gives me false.

i dont think im doing anything wrong but is there something im missing?

```<code>import mouse
import keyboard
import time

class Test:
    def keytest(self):
        keyboard.press('a')
        time.sleep(1)
        print (keyboard.is_pressed('a'))
        return

a = Test()
a.keytest()
</code>```

also the below code actually clicks a rightbutton. i thought release was supposed to not click anything but just release the keys that are pressed. so i dont know whats going on with this code as well. can someone explain?

```<code>import mouse
mouse.release('right')
</code>```

Body:
im trying to check if a keybutton or a mousebutton is pressed but 'is_pressed' gives me false.

i dont think im doing anything wrong but is there something im missing?

import mouse
import keyboard
import time

class Test:
    def keytest(self):
        keyboard.press('a')
        time.sleep(1)
        print (keyboard.is_pressed('a'))
        return

a = Test()
a.keytest()

also the below code actually clicks a rightbutton. i thought release was supposed to not click anything but just release the keys that are pressed. so i dont know whats going on with this code as well. can someone explain?

import mouse
mouse.release('right')


问:
The Api is missing records, I'm using Moonge with express Nodejs
I'm fetching the data from the API and the API is showing me different records on reloads. Somethings it shows me the correct data and sometimes misses the records. When I hit the API URL in postman it works fine for me.

The API Url I'm using: https://backend.websouls.com/api/currencies/dump It's a POST request with the body for example like this.

The issue I'm facing is very critical for me.

As you can see in above 3 images that I have attached above. I'm sending the request for 4 Pids data and the API is giving me only 2 records.

If anyone has any idea how to fix this issue kindly help me Thank you!

I tried to console the pids in the backend to check the body gets the pids properly and it's working fine, also I use that pids array in request query to check the API behavior but same behavior.

The Function on the backend where I fetch the records from mongoose is given bellow.

```<code>exports.getPackages = async function (req, res) {
  const pids = req.query.p_id;
  let newObject = [];

  let obj = {};
  for (i = 0; i < pids.length; i++) {
    let cr = [];
    const package = await priceModel
      .find({ pid: pids[i] })
      .select({ pro_config_options: 0 });
    //res.json(package);
    const packageFeatures = await featuresModel
      .find({ pid: pids[i] })
      .select({ pid: 0 });
    //res.json(packageFeatures);
    for (j = 0; j < package.length; j++) {
      let ccr = {
        currency: package[j].currency,
        annually: package[j].annually,
        biennially: package[j].biennially,
        triennially: package[j].triennially,
        monthly: package[j].monthly,
        quarterly: package[j].quarterly,
        semiannually: package[j].semiannually,
        qsetupfee: package[j].qsetupfee,
        ssetupfee: package[j].ssetupfee,
        asetupfee: package[j].asetupfee,
        bsetupfee: package[j].bsetupfee,
        tsetupfee: package[j].tsetupfee,
      };
      cr.push(ccr);
    }

    obj = {
      id: package[0]._id,
      pid: package[0].pid,
      name: package[0].name,
      title: package[0].title,
      tid: "",
      fname: package[0].fname,
      currency: cr,
      addons: [],
      freedomain: [],
      packageFeatures,
      addonids: package[0].addonids,
    };
    // res.json(obj);
    newObject.push(obj);
    //package.push(newObject);
  }
  res.json(newObject);
};
</code>```

Body:
I'm fetching the data from the API and the API is showing me different records on reloads. Somethings it shows me the correct data and sometimes misses the records. When I hit the API URL in postman it works fine for me.

The API Url I'm using: https://backend.websouls.com/api/currencies/dump It's a POST request with the body for example like this.

The issue I'm facing is very critical for me.

As you can see in above 3 images that I have attached above. I'm sending the request for 4 Pids data and the API is giving me only 2 records.

If anyone has any idea how to fix this issue kindly help me Thank you!

I tried to console the pids in the backend to check the body gets the pids properly and it's working fine, also I use that pids array in request query to check the API behavior but same behavior.

The Function on the backend where I fetch the records from mongoose is given bellow.

exports.getPackages = async function (req, res) {
  const pids = req.query.p_id;
  let newObject = [];

  let obj = {};
  for (i = 0; i < pids.length; i++) {
    let cr = [];
    const package = await priceModel
      .find({ pid: pids[i] })
      .select({ pro_config_options: 0 });
    //res.json(package);
    const packageFeatures = await featuresModel
      .find({ pid: pids[i] })
      .select({ pid: 0 });
    //res.json(packageFeatures);
    for (j = 0; j < package.length; j++) {
      let ccr = {
        currency: package[j].currency,
        annually: package[j].annually,
        biennially: package[j].biennially,
        triennially: package[j].triennially,
        monthly: package[j].monthly,
        quarterly: package[j].quarterly,
        semiannually: package[j].semiannually,
        qsetupfee: package[j].qsetupfee,
        ssetupfee: package[j].ssetupfee,
        asetupfee: package[j].asetupfee,
        bsetupfee: package[j].bsetupfee,
        tsetupfee: package[j].tsetupfee,
      };
      cr.push(ccr);
    }

    obj = {
      id: package[0]._id,
      pid: package[0].pid,
      name: package[0].name,
      title: package[0].title,
      tid: "",
      fname: package[0].fname,
      currency: cr,
      addons: [],
      freedomain: [],
      packageFeatures,
      addonids: package[0].addonids,
    };
    // res.json(obj);
    newObject.push(obj);
    //package.push(newObject);
  }
  res.json(newObject);
};


问:
10-fold cross validation for a logistic regression in google colab python
y3_data is the death variable 0 for alive and 1 for dead, x3_data are my categorical variable the are all have binary output for example Diabetes 0 for yes 1 for no and so on i have around 6 variables in x3_data that have a significant P value with y3_data

```<code>and i want the output to be like this one
     Training_Acc        Testing_Acc
0    76.0586319218241    75.32467532467533
1    75.2442996742671    74.67532467532467
2    73.9413680781759    81.16883116883116
3    77.72357723577235   71.89542483660131
4    76.7479674796748    73.20261437908496
Av   75.94316887794285   75.25337407690348
</code>```

this is the code i wrote

```<code>    #dependant variable y_data:
    y3_data = data['DEATH']
        #dependant variable y_data:
    x3_data = df14
    from sklearn.model_selection import KFold
    from sklearn.model_selection import StratifiedKFold

    from imblearn.under_sampling import RandomUnderSampler

    rus = RandomUnderSampler(random_state=0)
    x3_resampled,y3_resampled = rus.fit_resample(x3_data,y3_data)

        #training and test sample :
    x3_training_data, x3_test_data, y3_training_data, y3_test_data = train_test_split(x3_data, y3_data, test_size = 0.3)

        # Estimation result:
    logit_model=sm.Logit(y3_training_data,x3_training_data)
    result3=logit_model.fit()
    print(result3.summary2())

        # Model Evaluation  :
    logreg=LogisticRegression()
    logreg.fit(x3_training_data,y3_training_data)
    y_pred=logreg.predict(x3_test_data)
    print('Logistic regression model accuracy:{:.2f}'.format(logreg.score(x3_test_data,y3_test_data)))
    print("Logistic Regression F1 Score :",f1_score(y3_test_data,logreg.predict(x3_test_data),average=None))
    sns.heatmap(confusion_matrix(y3_test_data, logreg.predict(x3_test_data)), annot=True, fmt=".0f")
    plt.title("Logistic Regression Confusion Matrix",fontsize=18, color="red");

    num_splits = 10
    kfold = StratifiedKFold(num_splits, shuffle= True, random_state = 1)
    train_accs, test_accs = [], []  #create empty lists to store accurcy values
    for train_index, test_index in kfold.split(x3_data, y3_data):  # the error is for this part Generate indices to split data into training and test set.

        x3_training_data, x3_test_data = x3_data[train_index], x3_data[test_index]
        y3_training_data, y3_test_data = y3_data[train_index], y3_data[test_index]
        logreg.fit(x3_training_data,y3_training_data)
        y3_pred_train = logreg.predict(x3_training_data)
        y3_pred_test = logreg.predict(x3_test_data)

        train_accs.append(metrics.accuracy_score(y3_training_data, y3_pred_train) * 100)
        test_accs.append(metrics.accuracy_score(y3_test_data, y3_pred_test) * 100)

    ave_train_acc = 0
    ave_test_acc = 0

    print("\t","Training_Acc","\t","\t", "Testing_Acc")

    for i in range(num_splits):
        print(i,"\t", train_accs[i],"\t", test_accs[i])

        ave_train_acc+= train_accs[i]/num_splits
        ave_test_acc+= test_accs[i]/num_splits

    print("Av", "\t", ave_train_acc,"\t", ave_test_acc)
</code>```

i keep get this error here
x3_training_data, x3_test_data = x3_data[train_index], x3_data[test_index]

the error is

```<code>"None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n ],\n           dtype='int64', length=943717)] are in the [columns]"
</code>```

please help
thank you

this is the full error

```<code>---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-4-bf19b4c5d314> in <module>
     64 train_accs, test_accs = [], []  #create empty lists to store accurcy values
     65 for train_index, test_index in kfold.split(x3_data, y3_data):  #Generate indices to split data into training and test set.
---> 66     x3_training_data, x3_test_data = x3_data[train_index], x3_data[test_index]
     67     y3_training_data, y3_test_data = y3_data[train_index], y3_data[test_index]
     68     logreg.fit(x3_training_data,y3_training_data)

2 frames

/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis)
   1372                 if use_interval_msg:
   1373                     key = list(key)
-> 1374                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1375
   1376             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

KeyError: "None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n            ...\n            1048565, 1048566, 1048567, 1048568, 1048569, 1048570, 1048571,\n            1048572, 1048573, 1048574],\n           dtype='int64', length=943717)] are in the [columns]"
</code>```

Body:
y3_data is the death variable 0 for alive and 1 for dead, x3_data are my categorical variable the are all have binary output for example Diabetes 0 for yes 1 for no and so on i have around 6 variables in x3_data that have a significant P value with y3_data

and i want the output to be like this one
     Training_Acc        Testing_Acc
0    76.0586319218241    75.32467532467533
1    75.2442996742671    74.67532467532467
2    73.9413680781759    81.16883116883116
3    77.72357723577235   71.89542483660131
4    76.7479674796748    73.20261437908496
Av   75.94316887794285   75.25337407690348

this is the code i wrote

    #dependant variable y_data:
    y3_data = data['DEATH']
        #dependant variable y_data:
    x3_data = df14
    from sklearn.model_selection import KFold
    from sklearn.model_selection import StratifiedKFold

    from imblearn.under_sampling import RandomUnderSampler

    rus = RandomUnderSampler(random_state=0)
    x3_resampled,y3_resampled = rus.fit_resample(x3_data,y3_data)

        #training and test sample :
    x3_training_data, x3_test_data, y3_training_data, y3_test_data = train_test_split(x3_data, y3_data, test_size = 0.3)

        # Estimation result:
    logit_model=sm.Logit(y3_training_data,x3_training_data)
    result3=logit_model.fit()
    print(result3.summary2())

        # Model Evaluation  :
    logreg=LogisticRegression()
    logreg.fit(x3_training_data,y3_training_data)
    y_pred=logreg.predict(x3_test_data)
    print('Logistic regression model accuracy:{:.2f}'.format(logreg.score(x3_test_data,y3_test_data)))
    print("Logistic Regression F1 Score :",f1_score(y3_test_data,logreg.predict(x3_test_data),average=None))
    sns.heatmap(confusion_matrix(y3_test_data, logreg.predict(x3_test_data)), annot=True, fmt=".0f")
    plt.title("Logistic Regression Confusion Matrix",fontsize=18, color="red");

    num_splits = 10
    kfold = StratifiedKFold(num_splits, shuffle= True, random_state = 1)
    train_accs, test_accs = [], []  #create empty lists to store accurcy values
    for train_index, test_index in kfold.split(x3_data, y3_data):  # the error is for this part Generate indices to split data into training and test set.

        x3_training_data, x3_test_data = x3_data[train_index], x3_data[test_index]
        y3_training_data, y3_test_data = y3_data[train_index], y3_data[test_index]
        logreg.fit(x3_training_data,y3_training_data)
        y3_pred_train = logreg.predict(x3_training_data)
        y3_pred_test = logreg.predict(x3_test_data)

        train_accs.append(metrics.accuracy_score(y3_training_data, y3_pred_train) * 100)
        test_accs.append(metrics.accuracy_score(y3_test_data, y3_pred_test) * 100)

    ave_train_acc = 0
    ave_test_acc = 0

    print("\t","Training_Acc","\t","\t", "Testing_Acc")

    for i in range(num_splits):
        print(i,"\t", train_accs[i],"\t", test_accs[i])

        ave_train_acc+= train_accs[i]/num_splits
        ave_test_acc+= test_accs[i]/num_splits

    print("Av", "\t", ave_train_acc,"\t", ave_test_acc)

i keep get this error here
x3_training_data, x3_test_data = x3_data[train_index], x3_data[test_index]

the error is

"None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n ],\n           dtype='int64', length=943717)] are in the [columns]"

please help
thank you

this is the full error

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-4-bf19b4c5d314> in <module>
     64 train_accs, test_accs = [], []  #create empty lists to store accurcy values
     65 for train_index, test_index in kfold.split(x3_data, y3_data):  #Generate indices to split data into training and test set.
---> 66     x3_training_data, x3_test_data = x3_data[train_index], x3_data[test_index]
     67     y3_training_data, y3_test_data = y3_data[train_index], y3_data[test_index]
     68     logreg.fit(x3_training_data,y3_training_data)

2 frames

/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis)
   1372                 if use_interval_msg:
   1373                     key = list(key)
-> 1374                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1375
   1376             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

KeyError: "None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n            ...\n            1048565, 1048566, 1048567, 1048568, 1048569, 1048570, 1048571,\n            1048572, 1048573, 1048574],\n           dtype='int64', length=943717)] are in the [columns]"


问:
VSCode - Implement Custom IntelliSense through Extension
I want to provide IntelliSense in VSCode based on a JSON file in the root folder of the project directory. The JSON file is at ./languages/english.json and is a key-value pair like below:

{
    "sidebar.title": "Hello",
    "sidebar.name": "John",
    "sidebar.surname": "Doe",
    "first.aaa": "Hello",
    "first.bbb": "Hi",
}
```

I want VSCode to suggest this JSON's keys whenever I'm writing in a function named i18n().
Something like this:

I figured the best way to write a VSCode extension of my own. I've created one before, but how can I implement this feature?

P.S. I know about the option of using snippet json files directly, however those have the limitation of not being dynamically populated.

* Simillarly asked by yansenlei on an issue on VSCode's repo #133001

Body:
I want to provide IntelliSense in VSCode based on a JSON file in the root folder of the project directory. The JSON file is at ./languages/english.json and is a key-value pair like below:

{
    "sidebar.title": "Hello",
    "sidebar.name": "John",
    "sidebar.surname": "Doe",
    "first.aaa": "Hello",
    "first.bbb": "Hi",
}

I want VSCode to suggest this JSON's keys whenever I'm writing in a function named i18n().
Something like this:

I figured the best way to write a VSCode extension of my own. I've created one before, but how can I implement this feature?

P.S. I know about the option of using snippet json files directly, however those have the limitation of not being dynamically populated.

* Simillarly asked by yansenlei on an issue on VSCode's repo #133001


问:
Server connection status with RxJava in Android
I have a websocket connection

```<code>object StompWrapper {
    private var emitter: ObservableEmitter<Event>? = null
    init {
        val client = OkHttpClient.Builder().build()
        val stomp = StompClient(client)
        stomp.connect()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                 when (it.type) {
                     Event.Type.OPENED -> {
                         Timber.d("Connect OPENED")
                         isConnected = true
                         emitter?.onNext(Event(Event.Type.OPENED))
                     }
                     Event.Type.CLOSED,
                     Event.Type.ERROR -> {
                         Timber.d("Connect ERROR")
                         isConnected = false
                         emitter?.onNext(Event(Event.Type.ERROR))
                     }
                     else -> {}
              }
         }, { e ->
             Timber.e(e)
         })
    }

    fun status(): Observable<Event> {
        return Observable.create {
            Timber.d("Connect CREATE status $isConnected")
            emitter = it
            if (isConnected) {
                emitter?.onNext(Event(Event.Type.OPENED))
            }
        }
    }
}
</code>```

calling like this

```<code>disposable.add(StompWrapper.status().subscribe {
    Timber.d("Connect: %s", it.type)
})
</code>```

It turns out that connection hangs in a static class. It works if there is one subscriber, if you subscribe a couple of times, the last subscription will work and that's it. Please tell me how to make it so that I can find out the current status of the connection to the server anywhere in the application and do this as many times as I like?

Body:
I have a websocket connection

object StompWrapper {
    private var emitter: ObservableEmitter<Event>? = null
    init {
        val client = OkHttpClient.Builder().build()
        val stomp = StompClient(client)
        stomp.connect()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                 when (it.type) {
                     Event.Type.OPENED -> {
                         Timber.d("Connect OPENED")
                         isConnected = true
                         emitter?.onNext(Event(Event.Type.OPENED))
                     }
                     Event.Type.CLOSED,
                     Event.Type.ERROR -> {
                         Timber.d("Connect ERROR")
                         isConnected = false
                         emitter?.onNext(Event(Event.Type.ERROR))
                     }
                     else -> {}
              }
         }, { e ->
             Timber.e(e)
         })
    }

    fun status(): Observable<Event> {
        return Observable.create {
            Timber.d("Connect CREATE status $isConnected")
            emitter = it
            if (isConnected) {
                emitter?.onNext(Event(Event.Type.OPENED))
            }
        }
    }
}

calling like this

disposable.add(StompWrapper.status().subscribe {
    Timber.d("Connect: %s", it.type)
})

It turns out that connection hangs in a static class. It works if there is one subscriber, if you subscribe a couple of times, the last subscription will work and that's it. Please tell me how to make it so that I can find out the current status of the connection to the server anywhere in the application and do this as many times as I like?


问:
Sync SwiftUI ScrollViews offset bidirectionally
I'm trying to place multiple ScrollViews in a view and sync their scroll offset bidirectionally. Let's say there are ScrollView-A and ScrollView-B, if I scroll A, I want B to scroll the same distance, and vice versa.

My code is in-progress as below. It shares one offset State and both ScrollViews update it depending on their own scroll offset.
ScrollView-B uses it with the .offset modifier to catch up with ScrollView-A's scrolling.

However, the thing is, ScrollView-B tracks its own offset and updates the PreferenceKey so that it can update the scroll offset bidirectionally. Hence, it triggers Preference change again and again... kind of infinite loop. Got the following message in the console.

```<code>Bound preference ViewOffsetKey tried to update multiple times per frame.
</code>```

Is there any workaround for that? Better solutions for the same goal are also very welcome.

@State private var offset: CGFloat = .zero

TabView {
  // ScrollView-A
  ScrollView {
    VStack {
      ForEach(0..<100, id: \.self) { index in
        Text("Cell \(index)")
      }
    }
    .background(GeometryReader {
      Color.clear.preference(
        key: ViewOffsetKey.self,
        value: -$0.frame(in: .named("scroll")).minY)
    })
    .onPreferenceChange(ViewOffsetKey.self) { offset = $0 }
    //.offset(y: -offset)
  }
  .coordinateSpace(name: "scroll")

  // ScrollView-B
  ScrollView {
    VStack {
      ForEach(0..<10, id: \.self) { index in
        Text("Cell \(index)")
      }
    }
    .background(GeometryReader {
      Color.clear.preference(
        key: ViewOffsetKey.self,
        value: -$0.frame(in: .named("scroll2")).minY)
    })
    .onPreferenceChange(ViewOffsetKey.self) { offset = $0 }
    .offset(y: -offset)  // It triggers PreferenceChange again and again...
  }
  .coordinateSpace(name: "scroll2")
}

struct ViewOffsetKey: PreferenceKey {
  typealias Value = CGFloat
  static var defaultValue = CGFloat.zero
  static func reduce(value: inout Value, nextValue: () -> Value) {
    value += nextValue()
  }
}
```

UPDATE

I found the above warning message is gone if I move the .offset(y: -offset) before the definition of .background(GeometryReader ...

It seems to be my misunderstanding on iOS 16 simulator. I tried on iOS 15 real device and the same warning still appears.

Body:
I'm trying to place multiple ScrollViews in a view and sync their scroll offset bidirectionally. Let's say there are ScrollView-A and ScrollView-B, if I scroll A, I want B to scroll the same distance, and vice versa.

My code is in-progress as below. It shares one offset State and both ScrollViews update it depending on their own scroll offset.
ScrollView-B uses it with the .offset modifier to catch up with ScrollView-A's scrolling.

However, the thing is, ScrollView-B tracks its own offset and updates the PreferenceKey so that it can update the scroll offset bidirectionally. Hence, it triggers Preference change again and again... kind of infinite loop. Got the following message in the console.

Bound preference ViewOffsetKey tried to update multiple times per frame.

Is there any workaround for that? Better solutions for the same goal are also very welcome.

@State private var offset: CGFloat = .zero

TabView {
  // ScrollView-A
  ScrollView {
    VStack {
      ForEach(0..<100, id: \.self) { index in
        Text("Cell \(index)")
      }
    }
    .background(GeometryReader {
      Color.clear.preference(
        key: ViewOffsetKey.self,
        value: -$0.frame(in: .named("scroll")).minY)
    })
    .onPreferenceChange(ViewOffsetKey.self) { offset = $0 }
    //.offset(y: -offset)
  }
  .coordinateSpace(name: "scroll")

  // ScrollView-B
  ScrollView {
    VStack {
      ForEach(0..<10, id: \.self) { index in
        Text("Cell \(index)")
      }
    }
    .background(GeometryReader {
      Color.clear.preference(
        key: ViewOffsetKey.self,
        value: -$0.frame(in: .named("scroll2")).minY)
    })
    .onPreferenceChange(ViewOffsetKey.self) { offset = $0 }
    .offset(y: -offset)  // It triggers PreferenceChange again and again...
  }
  .coordinateSpace(name: "scroll2")
}

struct ViewOffsetKey: PreferenceKey {
  typealias Value = CGFloat
  static var defaultValue = CGFloat.zero
  static func reduce(value: inout Value, nextValue: () -> Value) {
    value += nextValue()
  }
}

UPDATE

I found the above warning message is gone if I move the .offset(y: -offset) before the definition of .background(GeometryReader ...

It seems to be my misunderstanding on iOS 16 simulator. I tried on iOS 15 real device and the same warning still appears.


问:
Sign in with Facebook error with next-auth : self_signed_cert_in_chain
I am following clone project youtube (https://youtu.be/g7nZ1R-5K40) and encountered problems applying facebook oauth.

My (1) codes (2) error message on the console (3) browser message are below.

Problem is, I made a consumer application for a Facebook developer but when I used it (its credential) with next-auth and tried sign-in, I get these errors.

URL is localhost:3000

How can I fix this?

(1) code:

```<code>import NextAuth from "next-auth";
import FacebookProvider from "next-auth/providers/facebook";
export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
};
export default NextAuth(authOptions);

</code>```

(2) Console:

```<code>[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error self signed certificate in certificate chain {
  error: Error: self signed certificate in certificate chain
      at TLSSocket.onConnectSecure (node:_tls_wrap:1532:34)
      at TLSSocket.emit (node:events:527:28)
      at TLSSocket.emit (node:domain:475:12)
      at TLSSocket._finishInit (node:_tls_wrap:946:8)
      at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:727:12) {
    name: 'OAuthCallbackError',
    code: 'SELF_SIGNED_CERT_IN_CHAIN'
  },
  providerId: 'facebook',
  message: 'self signed certificate in certificate chain'
}
</code>```

(3) Browser:

Body:
I am following clone project youtube (https://youtu.be/g7nZ1R-5K40) and encountered problems applying facebook oauth.

My (1) codes (2) error message on the console (3) browser message are below.

Problem is, I made a consumer application for a Facebook developer but when I used it (its credential) with next-auth and tried sign-in, I get these errors.

URL is localhost:3000

How can I fix this?

(1) code:

import NextAuth from "next-auth";
import FacebookProvider from "next-auth/providers/facebook";
export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
};
export default NextAuth(authOptions);

(2) Console:

[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error self signed certificate in certificate chain {
  error: Error: self signed certificate in certificate chain
      at TLSSocket.onConnectSecure (node:_tls_wrap:1532:34)
      at TLSSocket.emit (node:events:527:28)
      at TLSSocket.emit (node:domain:475:12)
      at TLSSocket._finishInit (node:_tls_wrap:946:8)
      at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:727:12) {
    name: 'OAuthCallbackError',
    code: 'SELF_SIGNED_CERT_IN_CHAIN'
  },
  providerId: 'facebook',
  message: 'self signed certificate in certificate chain'
}

(3) Browser:


问:
Problem getting image URI from the Activity to a keyboard IME service
I am creating a keyboard IME, whose one feature is ImageToText conversion using google MLKit
When user presses the image button
Image button that user presses

A transparent activity(ImageGetterActivity) starts that gets the image

```<code>Intent intent = new Intent(context, ImageGetterActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
</code>```

This activity opens gallery and gets the image in the variable

```<code>private void getImage(){
    Intent gallery = new Intent(Intent.ACTION_PICK);
    gallery.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(gallery, REQ_CODE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK){
            if(requestCode == REQ_CODE){
                image =  data.getData();
                finish();
            }
        }
}
</code>```

The image variable gets filled with correct URI. I can then also decode the image to text using MLKit.

Problem
I need to put decoded text in the InputConnection, for that I need to return the text back to the keyboard service that started it.

Things I have tried

Create a global variable that stores the text and then get that inside the service, but I dont know how to wait for ImageGetterActivity to finish before getting the global variable. Can't do startActivityForResult() since activity started from service.

Copy the image URI to clipboard and then on click this button, decoding happens inside the KeyboardIME class and I also have access to InputConnection, but this method doesn't seem right
Clipboard button

So, is there any better way to return data back from an activity to a service?

Body:
I am creating a keyboard IME, whose one feature is ImageToText conversion using google MLKit
When user presses the image button
Image button that user presses

A transparent activity(ImageGetterActivity) starts that gets the image

Intent intent = new Intent(context, ImageGetterActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

This activity opens gallery and gets the image in the variable

private void getImage(){
    Intent gallery = new Intent(Intent.ACTION_PICK);
    gallery.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(gallery, REQ_CODE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK){
            if(requestCode == REQ_CODE){
                image =  data.getData();
                finish();
            }
        }
}

The image variable gets filled with correct URI. I can then also decode the image to text using MLKit.

Problem
I need to put decoded text in the InputConnection, for that I need to return the text back to the keyboard service that started it.

Things I have tried

Create a global variable that stores the text and then get that inside the service, but I dont know how to wait for ImageGetterActivity to finish before getting the global variable. Can't do startActivityForResult() since activity started from service.

Copy the image URI to clipboard and then on click this button, decoding happens inside the KeyboardIME class and I also have access to InputConnection, but this method doesn't seem right
Clipboard button

So, is there any better way to return data back from an activity to a service?


问:
Unresolved reference: setPluginRegistrant in Application.kt
I was facing this error when running my flutter application, I changed the kotlin version  to the recommended version but still unable to solve the problem.

Error

```<code>e: C:\Users\wesle\AndroidStudioProjects\Aipetnion\android\app\src\main\kotlin\com\example\aipetnion\Application.kt: (13, 51): Unresolved reference: setPluginRegistrant

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
   > Compilation error. See log for more details
</code>```

Application.kt

```<code>class Application : FlutterApplication(), PluginRegistrantCallback {

    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingBackgroundService.setPluginRegistrant(this);
        FlutterMain.startInitialization(this)
    }

    override fun registerWith(registry: PluginRegistry) {
    }
}
</code>```

Body:
I was facing this error when running my flutter application, I changed the kotlin version  to the recommended version but still unable to solve the problem.

Error

e: C:\Users\wesle\AndroidStudioProjects\Aipetnion\android\app\src\main\kotlin\com\example\aipetnion\Application.kt: (13, 51): Unresolved reference: setPluginRegistrant

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
   > Compilation error. See log for more details

Application.kt

class Application : FlutterApplication(), PluginRegistrantCallback {

    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingBackgroundService.setPluginRegistrant(this);
        FlutterMain.startInitialization(this)
    }

    override fun registerWith(registry: PluginRegistry) {
    }
}


问:
Getting an upload error of ESP8266 using Arduino IDE with this report
The report is like this :

Executable segment sizes:

```<code>ICACHE : 32768           - flash instruction cache

IROM   : 252980          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 28261   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)

DATA   : 1560  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 2484  ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 26704 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 285285 bytes (27%) of program storage space. Maximum is 1044464 bytes.
Global variables use 30748 bytes (37%) of dynamic memory, leaving 51172 bytes for local variables. Maximum is 81920 bytes.
"C:\Users\hp\AppData\Local\Arduino15\packages\esp8266\tools\python3\3.7.2-post1/python3" "C:\Users\hp\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.1/tools/upload.py" --chip esp8266 --port "COM4" --baud "115200" ""  --before default_reset --after hard_reset write_flash 0x0 "C:\Users\hp\AppData\Local\Temp\arduino-sketch-A88D8C3CC17CAE2361CEB8CD194D0EE6/sketch_dec24a.ino.bin"
esptool.py v3.0
Serial port COM4
Connecting...
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.1/tools/upload.py", line 66, in <module>
    esptool.main(cmdline)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 3552, in main
    esp.connect(args.before, args.connect_attempts)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 519, in connect
    last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 499, in _connect_attempt
    self.sync()
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 438, in sync
    timeout=SYNC_TIMEOUT)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 376, in command
    self.write(pkt)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 339, in write
    self._port.write(buf)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/pyserial\serial\serialwin32.py", line 325, in write
    raise SerialTimeoutException('Write timeout')
serial.serialutil.SerialTimeoutException: Write timeout
Failed uploading: uploading error: exit status 1
</code>```

I already installed all drivers and needed libraries.

Body:
The report is like this :

Executable segment sizes:

ICACHE : 32768           - flash instruction cache

IROM   : 252980          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 28261   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)

DATA   : 1560  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 2484  ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 26704 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 285285 bytes (27%) of program storage space. Maximum is 1044464 bytes.
Global variables use 30748 bytes (37%) of dynamic memory, leaving 51172 bytes for local variables. Maximum is 81920 bytes.
"C:\Users\hp\AppData\Local\Arduino15\packages\esp8266\tools\python3\3.7.2-post1/python3" "C:\Users\hp\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.1/tools/upload.py" --chip esp8266 --port "COM4" --baud "115200" ""  --before default_reset --after hard_reset write_flash 0x0 "C:\Users\hp\AppData\Local\Temp\arduino-sketch-A88D8C3CC17CAE2361CEB8CD194D0EE6/sketch_dec24a.ino.bin"
esptool.py v3.0
Serial port COM4
Connecting...
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.1/tools/upload.py", line 66, in <module>
    esptool.main(cmdline)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 3552, in main
    esp.connect(args.before, args.connect_attempts)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 519, in connect
    last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 499, in _connect_attempt
    self.sync()
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 438, in sync
    timeout=SYNC_TIMEOUT)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 376, in command
    self.write(pkt)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/esptool\esptool.py", line 339, in write
    self._port.write(buf)
  File "C:/Users/hp/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.1/tools/pyserial\serial\serialwin32.py", line 325, in write
    raise SerialTimeoutException('Write timeout')
serial.serialutil.SerialTimeoutException: Write timeout
Failed uploading: uploading error: exit status 1

I already installed all drivers and needed libraries.


问:
Webklex\PHPIMAP Modern Auth Not Working 365
As with most people, Microsoft are turning off basic authentication. This means we need to use Modern Auth to retrieve emails from a mailbox.

However,when we retrie the access token fails with "

```<code>Client error: `POST https://login.microsoftonline.com/aea9a7d8-73fb-41af-987b-6fe14277421e/oauth2/v2.0/token` resulted in a `400 Bad Request` response:\n
    {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier '\"014438b9-82dc-4a4c-9584 (truncated...)
</code>```

"

Here is the code we have for retrieving and connecting to IMAP. I am passing actual email and password in usename and password field

```<code>/* Get the access Token */
$Secret = '**REMOVED**';
$AppID = '**REMOVED**';
$TenantID = '**REMOVED**';
$AccessToken = '';
try {
    $guzzle = new \GuzzleHttp\Client(['headers' => ['User-Agent' => 'App-Token-Request']]);
    $url = 'https://login.microsoftonline.com/'.$TenantID.'/oauth2/v2.0/token';
    $token = json_decode($guzzle->post($url, [
    'form_params' => [
        'grant_type'    => 'password',
        'client_id'     => $AppID,
        'client_secret' => $Secret,
        'scope'         => 'https://graph.microsoft.com/.default', //'https://outlook.office365.com/IMAP.AccessAsUser.All',// 'https://graph.microsoft.com/.default',
        'username'      => '**REMOVED**',
        'password'      => '**REMOVED**',
    ],
    ])->getBody()->getContents());

    $this->info(var_dump($token));
    $AccessToken = $token->access_token;

} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
    dd($e);
    return redirect('/')->with('error', 'Error requesting access token')->with('errorDetail', json_encode($e->getResponseBody()));
}
</code>```

Body:
As with most people, Microsoft are turning off basic authentication. This means we need to use Modern Auth to retrieve emails from a mailbox.

However,when we retrie the access token fails with "

Client error: `POST https://login.microsoftonline.com/aea9a7d8-73fb-41af-987b-6fe14277421e/oauth2/v2.0/token` resulted in a `400 Bad Request` response:\n
    {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier '\"014438b9-82dc-4a4c-9584 (truncated...)

"

Here is the code we have for retrieving and connecting to IMAP. I am passing actual email and password in usename and password field

/* Get the access Token */
$Secret = '**REMOVED**';
$AppID = '**REMOVED**';
$TenantID = '**REMOVED**';
$AccessToken = '';
try {
    $guzzle = new \GuzzleHttp\Client(['headers' => ['User-Agent' => 'App-Token-Request']]);
    $url = 'https://login.microsoftonline.com/'.$TenantID.'/oauth2/v2.0/token';
    $token = json_decode($guzzle->post($url, [
    'form_params' => [
        'grant_type'    => 'password',
        'client_id'     => $AppID,
        'client_secret' => $Secret,
        'scope'         => 'https://graph.microsoft.com/.default', //'https://outlook.office365.com/IMAP.AccessAsUser.All',// 'https://graph.microsoft.com/.default',
        'username'      => '**REMOVED**',
        'password'      => '**REMOVED**',
    ],
    ])->getBody()->getContents());

    $this->info(var_dump($token));
    $AccessToken = $token->access_token;

} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
    dd($e);
    return redirect('/')->with('error', 'Error requesting access token')->with('errorDetail', json_encode($e->getResponseBody()));
}


问:
@page left-margin greater than right-margin
I am printing a div using printMe.js plugin. And I have defined @page left-margin and right-margin both to be equal to 1mm in the CSS. However, as can be seen from this image image of print-view , the left margin generated in the print-view is wider than the right margin (margin-widths have been indicated in red markings). What is the explanation for this? Is it a bug? I am facing this issue in both google-chrome and mozilla-firefox.</p>


问:
How to show local video in react-native app
I don't have any idea about video player... I need to play any video from my phone in my app with controls like Vlc media player
I tried may library from google but it doesn't work...can any explain code....</p>


问:
Is there a way to stop a React component from losing focus after my event listener callback function fires?
I created an event listener for an Autocomplete component from the Mantine UI library in order to listen for keydown events and navigate to a new page for search results. Unfortunately, whenever I click on the component and type a key (in other words, when the keydown event fires), the input loses focus. I'd like to know how to prevent this while preserving the current behavior of my component, as everything else is working as expected.

```<code>function SearchComponent(props: {
        searchQuery;
        setSearchQuery;
        essayTitleArray;
    }) {
        // Define an event listener callback function
        const handleKeyDown = useCallback((event) => {
            if (event.key === "Enter") {
                navigate({
                    pathname: "/",
                    search: `?${createSearchParams({ searchQuery: props.searchQuery })}`,
                });
            }
        }, []);

        // Add the event listener
        const ref = useEventListener("keydown", handleKeyDown);

        return (
            <Autocomplete
                ref={ref}
                value={searchQuery}
                radius={"md"}
                onChange={(event: string) => {
                    setSearchQuery(event);
                }}
                className={classes.search}
                placeholder="Search"
                icon={<IconSearch size={16} stroke={1.5} />}
                data={essayTitleArray}
                limit={4}
                onItemSubmit={(item) => {
                    navigate({
                        pathname: "/compose",
                        search: `?${createSearchParams({ essayId: item.key })}`,
                    });
                }}
            />
        );
    }
</code>```

Relevant variables/hooks

```<code>const [searchQuery, setSearchQuery] = useState("");
const [essayTitleArray, setEssayTitleArray] = useState([]);
const navigate = useNavigate();
</code>```

The state variables here are declared and populated elsewhere, they work fine.

```<code>import { createSearchParams, useNavigate } from "react-router-dom";
import { useEventListener } from "@mantine/hooks";
import React, { useCallback, useEffect, useRef, useState } from "react";
</code>```

I tried to use event.preventDefault() in an else block in the handleKeyDown callback function of my code, which stopped the component from losing focus but also stopped me from being able to enter text into the input. Similarly, I tried using event.stopPropagation() in the same place, but it didn't seem to do anything.

```<code>function SearchComponent(props: {
        searchQuery;
        setSearchQuery;
        essayTitleArray;
    }) {
        // Define an event listener callback function
        const handleKeyDown = useCallback((event) => {
            if (event.key === "Enter") {
                navigate({
                    pathname: "/",
                    search: `?${createSearchParams({ searchQuery: props.searchQuery })}`,
                });
            } else {
                event.preventDefault();
            }
        }, []);

        // Add the event listener
        const ref = useEventListener("keydown", handleKeyDown);

        return (
            <Autocomplete
                ref={ref}
                value={searchQuery}
                radius={"md"}
                onChange={(event: string) => {
                    setSearchQuery(event);
                }}
                className={classes.search}
                placeholder="Search"
                icon={<IconSearch size={16} stroke={1.5} />}
                data={essayTitleArray}
                limit={4}
                onItemSubmit={(item) => {
                    navigate({
                        pathname: "/compose",
                        search: `?${createSearchParams({ essayId: item.key })}`,
                    });
                }}
            />
        );
    }

</code>```

Body:
I created an event listener for an Autocomplete component from the Mantine UI library in order to listen for keydown events and navigate to a new page for search results. Unfortunately, whenever I click on the component and type a key (in other words, when the keydown event fires), the input loses focus. I'd like to know how to prevent this while preserving the current behavior of my component, as everything else is working as expected.

function SearchComponent(props: {
        searchQuery;
        setSearchQuery;
        essayTitleArray;
    }) {
        // Define an event listener callback function
        const handleKeyDown = useCallback((event) => {
            if (event.key === "Enter") {
                navigate({
                    pathname: "/",
                    search: `?${createSearchParams({ searchQuery: props.searchQuery })}`,
                });
            }
        }, []);

        // Add the event listener
        const ref = useEventListener("keydown", handleKeyDown);

        return (
            <Autocomplete
                ref={ref}
                value={searchQuery}
                radius={"md"}
                onChange={(event: string) => {
                    setSearchQuery(event);
                }}
                className={classes.search}
                placeholder="Search"
                icon={<IconSearch size={16} stroke={1.5} />}
                data={essayTitleArray}
                limit={4}
                onItemSubmit={(item) => {
                    navigate({
                        pathname: "/compose",
                        search: `?${createSearchParams({ essayId: item.key })}`,
                    });
                }}
            />
        );
    }

Relevant variables/hooks

const [searchQuery, setSearchQuery] = useState("");
const [essayTitleArray, setEssayTitleArray] = useState([]);
const navigate = useNavigate();

The state variables here are declared and populated elsewhere, they work fine.

import { createSearchParams, useNavigate } from "react-router-dom";
import { useEventListener } from "@mantine/hooks";
import React, { useCallback, useEffect, useRef, useState } from "react";

I tried to use event.preventDefault() in an else block in the handleKeyDown callback function of my code, which stopped the component from losing focus but also stopped me from being able to enter text into the input. Similarly, I tried using event.stopPropagation() in the same place, but it didn't seem to do anything.

function SearchComponent(props: {
        searchQuery;
        setSearchQuery;
        essayTitleArray;
    }) {
        // Define an event listener callback function
        const handleKeyDown = useCallback((event) => {
            if (event.key === "Enter") {
                navigate({
                    pathname: "/",
                    search: `?${createSearchParams({ searchQuery: props.searchQuery })}`,
                });
            } else {
                event.preventDefault();
            }
        }, []);

        // Add the event listener
        const ref = useEventListener("keydown", handleKeyDown);

        return (
            <Autocomplete
                ref={ref}
                value={searchQuery}
                radius={"md"}
                onChange={(event: string) => {
                    setSearchQuery(event);
                }}
                className={classes.search}
                placeholder="Search"
                icon={<IconSearch size={16} stroke={1.5} />}
                data={essayTitleArray}
                limit={4}
                onItemSubmit={(item) => {
                    navigate({
                        pathname: "/compose",
                        search: `?${createSearchParams({ essayId: item.key })}`,
                    });
                }}
            />
        );
    }


问:
remote vscode python extension, connot import installed package
As is shown in the following picture, whenever I enable the python extension in my remote linux server, there will be a 'cannnot import' problem.

I use conda in my remote server, and torch is already installed in my virtual environment. I've looked through all the settings in the python extension, but failed to find one that can close this annoying problem.


问:
Is there a way to open a file stored in andorid assets with a specific application?
I'm trying to open a file from assets with an application using the code below:

```<code>                            String fileUri = "file:///android_asset/extensions/file.novabackup";

                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.parse(fileUri), "application/octet-stream");
                            intent.setPackage("com.teslacoilsw.launcher");

                            startActivity(intent);
</code>```

However, it does nothing and simply returns me to the MainActivity. I've also granted READ and WRITE access.

Body:
I'm trying to open a file from assets with an application using the code below:

                            String fileUri = "file:///android_asset/extensions/file.novabackup";

                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.parse(fileUri), "application/octet-stream");
                            intent.setPackage("com.teslacoilsw.launcher");

                            startActivity(intent);

However, it does nothing and simply returns me to the MainActivity. I've also granted READ and WRITE access.


问:
RuntimeError: Timeout context manager should be used inside a task when using threading and async io in aiogram
i tried to create a telegram bot in aiogram to send messages if a particular share price is reached. im using threading in order to run this in background as the bot takes user inputs. basically it takes a dict and takes the key as ticker for yfinance and gets the current price and compares with the given condition and if its a true condition it will send the alert to a chat. this is the code

```<code>
#bot info
import yfinance as yf
import logging
logging.basicConfig(level=logging.INFO)
from aiogram import Bot, Dispatcher, executor
import asyncio
import threading
bot = Bot(token='bot api key')
dp = Dispatcher(bot)

sh={}
jk={}

#reads a dict from a text file
with open('shares.txt','r') as f:
    a=f.read()
b=a.rstrip('}').lstrip('{').split(',')
for i in b:
    try:
        c=i.split(':')
        com_name=c[0].strip().strip(''' ' ''').strip()
        com_price=float(c[1])
        sh[com_name]=com_price
    except:
        sh={}
        break

async def send_price(pp: str):
    await bot.send_message(chat_id=user chat id, text=str(pp))

#price updater

def pp():

    while True:
        pl = sh.copy()
        index = ''
        for keys, values in list(pl.items()):
            if keys in jk and pl[keys] == jk[keys]:
                del pl[keys]
        print(pl)
        kj = pl
        if len(kj)==0:
            break
        for i in kj:
            if kj[i]==0:
                break
            s = yf.Ticker(i)
            a = (s.info)['currentPrice']
          #  print(s,a)
            if kj[i] == 0:
                continue
         #   print('kj',kj[i])
            if kj[i] <= a:
                index += (f'{i} is currently up rn up with current price being {str(a)} \n')
                jk[i] = kj[i]
        #print(index)
        if len(index) != 0:

            asyncio.run(send_price(index))

threading.Thread(target=pp).start()
if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)
</code>```

when i run the code i get this error .

```<code>RuntimeError: Timeout context manager should be used inside a task
</code>```

Body:
i tried to create a telegram bot in aiogram to send messages if a particular share price is reached. im using threading in order to run this in background as the bot takes user inputs. basically it takes a dict and takes the key as ticker for yfinance and gets the current price and compares with the given condition and if its a true condition it will send the alert to a chat. this is the code

#bot info
import yfinance as yf
import logging
logging.basicConfig(level=logging.INFO)
from aiogram import Bot, Dispatcher, executor
import asyncio
import threading
bot = Bot(token='bot api key')
dp = Dispatcher(bot)

sh={}
jk={}

#reads a dict from a text file
with open('shares.txt','r') as f:
    a=f.read()
b=a.rstrip('}').lstrip('{').split(',')
for i in b:
    try:
        c=i.split(':')
        com_name=c[0].strip().strip(''' ' ''').strip()
        com_price=float(c[1])
        sh[com_name]=com_price
    except:
        sh={}
        break

async def send_price(pp: str):
    await bot.send_message(chat_id=user chat id, text=str(pp))

#price updater

def pp():

    while True:
        pl = sh.copy()
        index = ''
        for keys, values in list(pl.items()):
            if keys in jk and pl[keys] == jk[keys]:
                del pl[keys]
        print(pl)
        kj = pl
        if len(kj)==0:
            break
        for i in kj:
            if kj[i]==0:
                break
            s = yf.Ticker(i)
            a = (s.info)['currentPrice']
          #  print(s,a)
            if kj[i] == 0:
                continue
         #   print('kj',kj[i])
            if kj[i] <= a:
                index += (f'{i} is currently up rn up with current price being {str(a)} \n')
                jk[i] = kj[i]
        #print(index)
        if len(index) != 0:

            asyncio.run(send_price(index))

threading.Thread(target=pp).start()
if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

when i run the code i get this error .

RuntimeError: Timeout context manager should be used inside a task


问:
How I can apply group by on one field with MongoDB and Spring Boot?
I want to apply group by only on one filed with Spring Boot and MongoDB. Let say I've one collection in Mongo which consist following fields

```<code>{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "CRICKET",
  "description": "I like Cricket",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "FOOTBALL",
  "description": "I love Footbal",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "CRICKET",
  "description": "I love Cricket",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "Martial Art",
  "description": "Martial Art",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "FOOTBALL",
  "description": "Football",
}
</code>```

My purpose is to display records by their group. So how I can apply group by with Spring Boot and MongoDB?

Body:
I want to apply group by only on one filed with Spring Boot and MongoDB. Let say I've one collection in Mongo which consist following fields

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "CRICKET",
  "description": "I like Cricket",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "FOOTBALL",
  "description": "I love Footbal",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "CRICKET",
  "description": "I love Cricket",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "Martial Art",
  "description": "Martial Art",
}

{
  "_id": {
    "$binary": {
      "base64": "RZX+2GWyTD2DWyD/01ZPmA==",
      "subType": "04"
    }
  },
  "categoryType": "FOOTBALL",
  "description": "Football",
}

My purpose is to display records by their group. So how I can apply group by with Spring Boot and MongoDB?


问:
How to use canvas HTML5 on smartphone
I have code written on react js, using canvas html 5. It is image eraser: it should properly erase front image and when only some persent of it left, it trigger another action(i haven not done another action yet). It works fine in browser, but when i choose adaptive for any smatphone, it stops working. I tried to change mouse events to touch events but it didn't help.
Here is the code:

import './DrawingCanvas.css';
import {useEffect, useRef, useState} from 'react';

const DrawingCanvas = () => {
    const canvasRef = useRef(null);
    const contextRef = useRef(null);

    const [isDrawing, setIsDrawing] = useState(false);
    const [persent, setPersent] = useState(100);

    useEffect(() => {
        const url = require('../../images/one.jpg');
        const canvas = canvasRef.current;
        const img = new Image();
        img.src = url;
        const context = canvas.getContext("2d");
        img.onload = function () {
            let width = Math.min(500, img.width);
            let height = img.height * (width / img.width);
            canvas.width = width;
            canvas.height = height;
            context.drawImage(img, 0, 0, width, height);

            contextRef.current = context;
            context.lineCap = "round";
            context.lineWidth = 350;

            contextRef.current.globalCompositeOperation = 'destination-out';

        };

    }, []);
    useEffect(() => {
        console.log(persent);
        if(persent<=0.1) return alert('hello')
    }, [persent]);

    const startDrawing = ({nativeEvent}) => {
        const {offsetX, offsetY} = nativeEvent;
        contextRef.current.beginPath();
        contextRef.current.moveTo(offsetX, offsetY);
        contextRef.current.lineTo(offsetX, offsetY);
        // contextRef.current.stroke();
        setIsDrawing(true);
        nativeEvent.preventDefault();
    };

    const draw = ({nativeEvent}) => {
        if (!isDrawing) {
            return;
        }

        const {offsetX, offsetY} = nativeEvent;
        contextRef.current.lineTo(offsetX, offsetY);
        contextRef.current.stroke();
        nativeEvent.preventDefault();

        let pixels = contextRef.current.getImageData(0, 0, canvasRef.current.width, canvasRef.current.height);
        let transPixels = [];
        for (let i = 3; i < pixels.data.length; i += 4) {
            transPixels.push(pixels.data[i]);
        }
        let transPixelsCount = transPixels.filter(Boolean).length;
        setPersent((transPixelsCount / transPixels.length) * 100);
    };

    const stopDrawing = () => {
        contextRef.current.closePath();
        setIsDrawing(false);

    };

    return (

            <canvas className="canvas-container"
                    ref={canvasRef}
                    onMouseDown={startDrawing}
                    onMouseMove={draw}
                    onMouseUp={stopDrawing}
                    onMouseLeave={stopDrawing}
            >

            </canvas>

    )
}

export default DrawingCanvas;
```
<pre class="lang-js prettyprint-override"><code>.canvas-container {
    background-image: url("https://media.istockphoto.com/id/1322277517/photo/wild-grass-in-the-mountains-at-sunset.jpg?s=612x612&w=0&k=20&c=6mItwwFFGqKNKEAzv0mv6TaxhLN3zSE43bWmFN--J5w=");
}
</code>```

Maybe it all can be done through touch events, but idk how to do that properly

Title: How to use canvas HTML5 on smartphone

Body:
I have code written on react js, using canvas html 5. It is image eraser: it should properly erase front image and when only some persent of it left, it trigger another action(i haven not done another action yet). It works fine in browser, but when i choose adaptive for any smatphone, it stops working. I tried to change mouse events to touch events but it didn't help.
Here is the code:

import './DrawingCanvas.css';
import {useEffect, useRef, useState} from 'react';

const DrawingCanvas = () => {
    const canvasRef = useRef(null);
    const contextRef = useRef(null);

    const [isDrawing, setIsDrawing] = useState(false);
    const [persent, setPersent] = useState(100);

    useEffect(() => {
        const url = require('../../images/one.jpg');
        const canvas = canvasRef.current;
        const img = new Image();
        img.src = url;
        const context = canvas.getContext("2d");
        img.onload = function () {
            let width = Math.min(500, img.width);
            let height = img.height * (width / img.width);
            canvas.width = width;
            canvas.height = height;
            context.drawImage(img, 0, 0, width, height);

            contextRef.current = context;
            context.lineCap = "round";
            context.lineWidth = 350;

            contextRef.current.globalCompositeOperation = 'destination-out';

        };

    }, []);
    useEffect(() => {
        console.log(persent);
        if(persent<=0.1) return alert('hello')
    }, [persent]);

    const startDrawing = ({nativeEvent}) => {
        const {offsetX, offsetY} = nativeEvent;
        contextRef.current.beginPath();
        contextRef.current.moveTo(offsetX, offsetY);
        contextRef.current.lineTo(offsetX, offsetY);
        // contextRef.current.stroke();
        setIsDrawing(true);
        nativeEvent.preventDefault();
    };

    const draw = ({nativeEvent}) => {
        if (!isDrawing) {
            return;
        }

        const {offsetX, offsetY} = nativeEvent;
        contextRef.current.lineTo(offsetX, offsetY);
        contextRef.current.stroke();
        nativeEvent.preventDefault();

        let pixels = contextRef.current.getImageData(0, 0, canvasRef.current.width, canvasRef.current.height);
        let transPixels = [];
        for (let i = 3; i < pixels.data.length; i += 4) {
            transPixels.push(pixels.data[i]);
        }
        let transPixelsCount = transPixels.filter(Boolean).length;
        setPersent((transPixelsCount / transPixels.length) * 100);
    };

    const stopDrawing = () => {
        contextRef.current.closePath();
        setIsDrawing(false);

    };

    return (

            <canvas className="canvas-container"
                    ref={canvasRef}
                    onMouseDown={startDrawing}
                    onMouseMove={draw}
                    onMouseUp={stopDrawing}
                    onMouseLeave={stopDrawing}
            >

            </canvas>

    )
}

export default DrawingCanvas;

.canvas-container {
    background-image: url("https://media.istockphoto.com/id/1322277517/photo/wild-grass-in-the-mountains-at-sunset.jpg?s=612x612&w=0&k=20&c=6mItwwFFGqKNKEAzv0mv6TaxhLN3zSE43bWmFN--J5w=");
}

Maybe it all can be done through touch events, but idk how to do that properly


问:
dotnet-gcdump - ETL file shows the start of a heap dump but not its completion
I have a .NET Core v6 self-contained application running in K8S pod, base image is mcr.microsoft.com/dotnet/runtime-deps:6.0-bullseye-slim.

First I open a shell in the pod, and installed DotNet SDK and tools

Then when I execute dotnet-gcdump collect -v -p PID , it ends with following error.

Writing gcdump to '/app/20221224_072905_8.gcdump'...
  0.0s: Creating type table flushing task
  0.3s: Flushing the type table
  0.5s: Done flushing the type table
  0.5s: Requesting a .NET Heap Dump
 17.0s: gcdump EventPipe Session started
 17.1s: Starting to process events
 17.2s: .NET Dump Started...
Found a Gen2 Induced non-background GC Start at 3.562 msec GC Count 138
 17.3s: Making GC Heap Progress...
 30.1s: Timed out after 30 seconds
 30.1s: Shutting down gcdump EventPipe session
 30.7s: EventPipe Listener dying
 31.1s: still reading...
 32.1s: still reading...
 33.1s: still reading...
 34.1s: still reading...
 35.1s: still reading...
 36.1s: still reading...
 37.1s: still reading...
 38.1s: still reading...
 39.1s: still reading...
 40.1s: still reading...
 41.1s: still reading...
 42.1s: still reading...
 43.1s: still reading...
 43.3s: gcdump EventPipe session shut down
 43.3s: gcdump EventPipe Session closed
 43.4s: [Error] Exception during gcdump: System.ApplicationException: ETL file shows the start of a heap dump but not its completion.
   at DotNetHeapDumpGraphReader.ConvertHeapDataToGraph() in /_/src/Tools/dotnet-gcdump/DotNetHeapDump/DotNetHeapDumpGraphReader.cs:line 512
   at Microsoft.Diagnostics.Tools.GCDump.EventPipeDotNetHeapDumper.DumpFromEventPipe(CancellationToken ct, Int32 processID, MemoryGraph memoryGraph, TextWriter log, Int32 timeout, DotNetHeapInfo dotNetInfo) in /_/src/Tools/dotnet-gcdump/DotNetHeapDump/EventPipeDotNetHeapDumper.cs:line 205
[ 43.6s: Done Dumping .NET heap success=False]
```

According to this documentation,

dotnet-gcdump is unable to generate a .gcdump file due to missing
information, for example, [Error] Exception during gcdump:
System.ApplicationException: ETL file shows the start of a heap dump
but not its completion.. Or, the .gcdump file doesn't include the
entire heap.

Can't I dump a self-contained dotnet process?

Body:
I have a .NET Core v6 self-contained application running in K8S pod, base image is mcr.microsoft.com/dotnet/runtime-deps:6.0-bullseye-slim.

First I open a shell in the pod, and installed DotNet SDK and tools

Then when I execute dotnet-gcdump collect -v -p PID , it ends with following error.

Writing gcdump to '/app/20221224_072905_8.gcdump'...
  0.0s: Creating type table flushing task
  0.3s: Flushing the type table
  0.5s: Done flushing the type table
  0.5s: Requesting a .NET Heap Dump
 17.0s: gcdump EventPipe Session started
 17.1s: Starting to process events
 17.2s: .NET Dump Started...
Found a Gen2 Induced non-background GC Start at 3.562 msec GC Count 138
 17.3s: Making GC Heap Progress...
 30.1s: Timed out after 30 seconds
 30.1s: Shutting down gcdump EventPipe session
 30.7s: EventPipe Listener dying
 31.1s: still reading...
 32.1s: still reading...
 33.1s: still reading...
 34.1s: still reading...
 35.1s: still reading...
 36.1s: still reading...
 37.1s: still reading...
 38.1s: still reading...
 39.1s: still reading...
 40.1s: still reading...
 41.1s: still reading...
 42.1s: still reading...
 43.1s: still reading...
 43.3s: gcdump EventPipe session shut down
 43.3s: gcdump EventPipe Session closed
 43.4s: [Error] Exception during gcdump: System.ApplicationException: ETL file shows the start of a heap dump but not its completion.
   at DotNetHeapDumpGraphReader.ConvertHeapDataToGraph() in /_/src/Tools/dotnet-gcdump/DotNetHeapDump/DotNetHeapDumpGraphReader.cs:line 512
   at Microsoft.Diagnostics.Tools.GCDump.EventPipeDotNetHeapDumper.DumpFromEventPipe(CancellationToken ct, Int32 processID, MemoryGraph memoryGraph, TextWriter log, Int32 timeout, DotNetHeapInfo dotNetInfo) in /_/src/Tools/dotnet-gcdump/DotNetHeapDump/EventPipeDotNetHeapDumper.cs:line 205
[ 43.6s: Done Dumping .NET heap success=False]

According to this documentation,

dotnet-gcdump is unable to generate a .gcdump file due to missing
information, for example, [Error] Exception during gcdump:
System.ApplicationException: ETL file shows the start of a heap dump
but not its completion.. Or, the .gcdump file doesn't include the
entire heap.

Can't I dump a self-contained dotnet process?


问:
Set mode to control individual joysticks with pygame
I was wondering if there is a way to set up a 1 button mode that switches the function of my controller to use the left or right stick depending on if the button was press or not using pygame?

Basically
press button = control left joystick
press button (again) = control right joystick

currently I have tried running this

```<code>joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
events = pygame.event.get()
with self.lock:
    for event in events:
       " Detect middle x-box button"
       if event.type == pygame.JOYBUTTONDOWN:
          if event.button == 8:
             t = pygame.event.get()
             for r in t:
                if r.type == pygame.JOYAXISMOTION:
        # " Left stick"
                    if r.axis == 0:
                       if r.value > 1:
                           r.value = 1
                       if r.value < -1:
                           r.value = -1
                       print(r.value)
                       self.left_stick.update_x(r.value)
                    if r.axis == 1:
                       if r.value > 1:
                           r.value = 1
                       if r.value < -1:
                           r.value = -1
                       print(r.value)
                       self.left_stick.update_y(r.value)
              self.middle_led_ring_button.update(1)
</code>```

This detects that the xbox button when is press and should then detect if the jostick is moved, but it doesn't. I think is because it has 2 events in it self?

I am looking for something like

```<code>       if event.type == pygame.JOYBUTTONDOWN:
          if event.button == 8:
             if button_press:
                c = joystick.value
                move_left_stick(c)
             if button_press_again:
                c = joystick.value
                move_right_stick(c)
</code>```

Body:
I was wondering if there is a way to set up a 1 button mode that switches the function of my controller to use the left or right stick depending on if the button was press or not using pygame?

Basically
press button = control left joystick
press button (again) = control right joystick

currently I have tried running this

joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
events = pygame.event.get()
with self.lock:
    for event in events:
       " Detect middle x-box button"
       if event.type == pygame.JOYBUTTONDOWN:
          if event.button == 8:
             t = pygame.event.get()
             for r in t:
                if r.type == pygame.JOYAXISMOTION:
        # " Left stick"
                    if r.axis == 0:
                       if r.value > 1:
                           r.value = 1
                       if r.value < -1:
                           r.value = -1
                       print(r.value)
                       self.left_stick.update_x(r.value)
                    if r.axis == 1:
                       if r.value > 1:
                           r.value = 1
                       if r.value < -1:
                           r.value = -1
                       print(r.value)
                       self.left_stick.update_y(r.value)
              self.middle_led_ring_button.update(1)

This detects that the xbox button when is press and should then detect if the jostick is moved, but it doesn't. I think is because it has 2 events in it self?

I am looking for something like

       if event.type == pygame.JOYBUTTONDOWN:
          if event.button == 8:
             if button_press:
                c = joystick.value
                move_left_stick(c)
             if button_press_again:
                c = joystick.value
                move_right_stick(c)


问:
I am making nav icon which appears when hovered upon but while runtime why some images are disappearing and behaving weird? where am i wrong?
I am trying to make the hovering navbar at the left side of the screen appear at its full size when being hovered open and gets disappear when not being hovered upon.

But when the nav_outtermost element is hovered upon, some of the images of the nav_bottom element disappear and appear rapidly. But why this is happening?

Code:

let sidenav = document.getElementById('nav_outtermost');
let nav_bottomm = document.getElementById('nav_bottom');

document.getElementById('nav_icon').addEventListener('mouseover', function showicons() {
  let sidenav = document.getElementById('nav_outtermost');
  sidenav.style.height = "60vh";
  sidenav.style.gridTemplateRows = "1fr 5fr";
  sidenav.style.boxShadow = "var(--hovershadow)";

  nav_bottomm.style.display = "grid";

  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-1').style.opacity = "1";
  }, 75);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-2').style.opacity = "1";
  }, 100);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-3').style.opacity = "1";
  }, 125);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-4').style.opacity = "1";
  }, 150);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-5').style.opacity = "1";
  }, 175);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-6').style.opacity = "1";
  }, 200);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-7').style.opacity = "1";
  }, 225);

})
sidenav.addEventListener('mouseover', function showicons() {

  sidenav.style.height = "60vh";
  sidenav.style.gridTemplateRows = "1fr 5fr";
  sidenav.style.boxShadow = "var(--hovershadow)";

  let nav_bottomm = document.getElementById('nav_bottom');
  nav_bottomm.style.display = "grid";

  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-1').style.opacity = "1";
  }, 75);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-2').style.opacity = "1";
  }, 100);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-3').style.opacity = "1";
  }, 125);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-4').style.opacity = "1";
  }, 150);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-5').style.opacity = "1";
  }, 175);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-6').style.opacity = "1";
  }, 200);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-7').style.opacity = "1";
  }, 225);

})

sidenav.addEventListener('mouseout', function showicons() {

  sidenav.style.height = "9vh";
  sidenav.style.gridTemplateRows = "none";
  sidenav.style.boxShadow = "none";

  nav_bottomm.style.display = "none";

  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-1').style.opacity = "0";
  }, 225);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-2').style.opacity = "0";
  }, 200);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-3').style.opacity = "0";
  }, 175);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-4').style.opacity = "0";
  }, 150);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-5').style.opacity = "0";
  }, 125);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-6').style.opacity = "0";
  }, 100);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-7').style.opacity = "0";
  }, 75);

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  :root {
  --borderr: 2px solid;
  --depthshadow: inset -5px -5px 5px rgba(255, 255, 255, 1), inset 5px 5px 5px rgba(0, 0, 0, 0.15);
  --hovershadow: 5px 5px 5px rgba(0, 0, 0, 0.20), inset 5px 5px 5px rgba(255, 255, 255, 1);
}

* {
  margin: 0px;
  padding: 0px
}

body {
  height: 200vh;
  background-color: #ecf0f3;
}

#nav_outtermost {
  display: grid;
  position: fixed;
  top: 25vh;
  width: 5vw;
  height: 9vh;
  border-radius: 15px;
  transition: all;
  transition-duration: 0.5s;
}

#nav_top {
  display: grid;
}

#nav_top_icon_div {
  display: flex;
  justify-content: center;
  align-items: center;
}

#nav_icon {
  width: 50%;
  box-shadow: var(--hovershadow);
  border-radius: 100%;
  /* width: 20%; when right nav bar is present */
}

/* //////////////////////////////////////bottom//////////////////////////////////////// */

#nav_bottom {
  display: none;
  #bottom_left_icons_div-1 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-2 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-3 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-4 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-5 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-6 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-7 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
    opacity: 0;
  }
  #bottom_left {
    display: grid;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  }
  .bottom_left_icons {
    width: 50%;
  }
  * {
    border: var(--borderr);
  }
  body {
    border-color: blue;
  }
  #nav_outtermost {
    border-color: red;
  }
  #nav_top {
    border-color: aqua;
  }
  #nav_bottom {
    border-color: green;
  }
  #nav_top_icon_div {
    border-color: purple;
  }
  #top_right_gap {
    border-color: crimson;
  }
  #bottom_left {
    border-color: purple;
  }
  #bottom_right {
    border-color: yellowgreen;
  }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>sidenavbar2
  </title>

<link rel="stylesheet" type="text/css" href="sidenavbar2.css">

```

I was expecting it to be like this.. but when hovered upon nav_outtermost element .. the image icons
behaves weirdly

Body:
I am trying to make the hovering navbar at the left side of the screen appear at its full size when being hovered open and gets disappear when not being hovered upon.

But when the nav_outtermost element is hovered upon, some of the images of the nav_bottom element disappear and appear rapidly. But why this is happening?

Code:

let sidenav = document.getElementById('nav_outtermost');
let nav_bottomm = document.getElementById('nav_bottom');

document.getElementById('nav_icon').addEventListener('mouseover', function showicons() {
  let sidenav = document.getElementById('nav_outtermost');
  sidenav.style.height = "60vh";
  sidenav.style.gridTemplateRows = "1fr 5fr";
  sidenav.style.boxShadow = "var(--hovershadow)";

  nav_bottomm.style.display = "grid";

  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-1').style.opacity = "1";
  }, 75);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-2').style.opacity = "1";
  }, 100);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-3').style.opacity = "1";
  }, 125);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-4').style.opacity = "1";
  }, 150);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-5').style.opacity = "1";
  }, 175);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-6').style.opacity = "1";
  }, 200);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-7').style.opacity = "1";
  }, 225);

})
sidenav.addEventListener('mouseover', function showicons() {

  sidenav.style.height = "60vh";
  sidenav.style.gridTemplateRows = "1fr 5fr";
  sidenav.style.boxShadow = "var(--hovershadow)";

  let nav_bottomm = document.getElementById('nav_bottom');
  nav_bottomm.style.display = "grid";

  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-1').style.opacity = "1";
  }, 75);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-2').style.opacity = "1";
  }, 100);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-3').style.opacity = "1";
  }, 125);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-4').style.opacity = "1";
  }, 150);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-5').style.opacity = "1";
  }, 175);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-6').style.opacity = "1";
  }, 200);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-7').style.opacity = "1";
  }, 225);

})

sidenav.addEventListener('mouseout', function showicons() {

  sidenav.style.height = "9vh";
  sidenav.style.gridTemplateRows = "none";
  sidenav.style.boxShadow = "none";

  nav_bottomm.style.display = "none";

  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-1').style.opacity = "0";
  }, 225);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-2').style.opacity = "0";
  }, 200);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-3').style.opacity = "0";
  }, 175);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-4').style.opacity = "0";
  }, 150);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-5').style.opacity = "0";
  }, 125);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-6').style.opacity = "0";
  }, 100);
  setTimeout(() => {
    document.getElementById('bottom_left_icons_div-7').style.opacity = "0";
  }, 75);

})

  :root {
  --borderr: 2px solid;
  --depthshadow: inset -5px -5px 5px rgba(255, 255, 255, 1), inset 5px 5px 5px rgba(0, 0, 0, 0.15);
  --hovershadow: 5px 5px 5px rgba(0, 0, 0, 0.20), inset 5px 5px 5px rgba(255, 255, 255, 1);
}

* {
  margin: 0px;
  padding: 0px
}

body {
  height: 200vh;
  background-color: #ecf0f3;
}

#nav_outtermost {
  display: grid;
  position: fixed;
  top: 25vh;
  width: 5vw;
  height: 9vh;
  border-radius: 15px;
  transition: all;
  transition-duration: 0.5s;
}

#nav_top {
  display: grid;
}

#nav_top_icon_div {
  display: flex;
  justify-content: center;
  align-items: center;
}

#nav_icon {
  width: 50%;
  box-shadow: var(--hovershadow);
  border-radius: 100%;
  /* width: 20%; when right nav bar is present */
}

/* //////////////////////////////////////bottom//////////////////////////////////////// */

#nav_bottom {
  display: none;
  #bottom_left_icons_div-1 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-2 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-3 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-4 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-5 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-6 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
  }
  #bottom_left_icons_div-7 {
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all;
    transition-duration: 0.5s;
    opacity: 0;
  }
  #bottom_left {
    display: grid;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  }
  .bottom_left_icons {
    width: 50%;
  }
  * {
    border: var(--borderr);
  }
  body {
    border-color: blue;
  }
  #nav_outtermost {
    border-color: red;
  }
  #nav_top {
    border-color: aqua;
  }
  #nav_bottom {
    border-color: green;
  }
  #nav_top_icon_div {
    border-color: purple;
  }
  #top_right_gap {
    border-color: crimson;
  }
  #bottom_left {
    border-color: purple;
  }
  #bottom_right {
    border-color: yellowgreen;
  }

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>sidenavbar2
  </title>

<link rel="stylesheet" type="text/css" href="sidenavbar2.css">

I was expecting it to be like this.. but when hovered upon nav_outtermost element .. the image icons
behaves weirdly


问:
yarn pnp RangeError: Maximum call stack size exceeded
I am creating a yarn Plug'n'Play workspace. But when I tried to use the yarn dlx @yarnpkg/sdks vscode it gave me a "RangeError: Maximum call stack size exceeded" error. But I manually created the file and the sdks folder and resolved the issue.

But after that when I tried to install the React app it gave me the same error.

The command I used was: yarn create react-app frontend --use-pnp

Above is the response I am getting.

Node: v18.12.0

Yarn: v3.3.1


问:
I try to use GPU pytorch on WSL2，but GPU only work in Windows terminal，not work in vscode terminal，why？
Windows terminal：enter image description here

vscode terminal： enter image description here

i try uninstall pytorch and change pytorch version，uninstall and reinstall wsl