问:
Cannot initialize effect engine
When calling the setEqualizerData() method, namely when initializing myEq = Equalizer(0, musicPlayingId), an error occurs: Caused by java.lang.RuntimeException: Cannot initialize effect engine for type: 0bed4300-ddd6-11db-8f34-0002a5d5c51b Error: -3

```<code>private fun setEqualizerData() {
myEq = Equalizer(0, musicPlayingId) //Error //musicPlayingId = 0
myEq!!.enabled = true
setBoost(sharedPreferences.getFloat(LOUDER_LEVEL, 1f))
myEq!!.setBandLevel(
    0,
    sharedPreferences.getInt(BAND_1_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    1,
    sharedPreferences.getInt(BAND_2_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    2,
    sharedPreferences.getInt(BAND_3_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    3,
    sharedPreferences.getInt(BAND_4_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    4,
    sharedPreferences.getInt(BAND_5_LEVEL, 1500).toShort()
)
mBassBoost = BassBoost(0, musicPlayingId)
mBassBoost!!.enabled = true
setBassBoost()
virtualizer = Virtualizer(0, musicPlayingId)
virtualizer!!.enabled = true
setVirtualizer()
loudness = LoudnessEnhancer(musicPlayingId)
</code>```

}

stacktrace:

```<code>Caused by java.lang.RuntimeException: Cannot initialize effect engine for type: 0bed4300-ddd6-11db-8f34-0002a5d5c51b Error: -3
   at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:468)
   at android.media.audiofx.Equalizer.<init>(Equalizer.java:139)
   at example.androidvolumelouder.presentation.ui.activities.MainActivity.setEqualizerData(MainActivity.kt:343)
   at example.androidvolumelouder.presentation.ui.activities.MainActivity.setDataToView(MainActivity.kt:529)
   at example.androidvolumelouder.presentation.ui.activities.MainActivity.onCreate(MainActivity.kt:147)
   at android.app.Activity.performCreate(Activity.java:7893)
   at android.app.Activity.performCreate(Activity.java:7880)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3310)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3484)
   at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
   at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
   at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2068)
   at android.os.Handler.dispatchMessage(Handler.java:107)
   at android.os.Looper.loop(Looper.java:224)
   at android.app.ActivityThread.main(ActivityThread.java:7551)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
</code>```

Help please, what's the problem?

Title: Cannot initialize effect engine

Body:
When calling the setEqualizerData() method, namely when initializing myEq = Equalizer(0, musicPlayingId), an error occurs: Caused by java.lang.RuntimeException: Cannot initialize effect engine for type: 0bed4300-ddd6-11db-8f34-0002a5d5c51b Error: -3

private fun setEqualizerData() {
myEq = Equalizer(0, musicPlayingId) //Error //musicPlayingId = 0
myEq!!.enabled = true
setBoost(sharedPreferences.getFloat(LOUDER_LEVEL, 1f))
myEq!!.setBandLevel(
    0,
    sharedPreferences.getInt(BAND_1_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    1,
    sharedPreferences.getInt(BAND_2_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    2,
    sharedPreferences.getInt(BAND_3_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    3,
    sharedPreferences.getInt(BAND_4_LEVEL, 1500).toShort()
)
myEq!!.setBandLevel(
    4,
    sharedPreferences.getInt(BAND_5_LEVEL, 1500).toShort()
)
mBassBoost = BassBoost(0, musicPlayingId)
mBassBoost!!.enabled = true
setBassBoost()
virtualizer = Virtualizer(0, musicPlayingId)
virtualizer!!.enabled = true
setVirtualizer()
loudness = LoudnessEnhancer(musicPlayingId)

}

stacktrace:

Caused by java.lang.RuntimeException: Cannot initialize effect engine for type: 0bed4300-ddd6-11db-8f34-0002a5d5c51b Error: -3
   at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:468)
   at android.media.audiofx.Equalizer.<init>(Equalizer.java:139)
   at example.androidvolumelouder.presentation.ui.activities.MainActivity.setEqualizerData(MainActivity.kt:343)
   at example.androidvolumelouder.presentation.ui.activities.MainActivity.setDataToView(MainActivity.kt:529)
   at example.androidvolumelouder.presentation.ui.activities.MainActivity.onCreate(MainActivity.kt:147)
   at android.app.Activity.performCreate(Activity.java:7893)
   at android.app.Activity.performCreate(Activity.java:7880)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3310)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3484)
   at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
   at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
   at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2068)
   at android.os.Handler.dispatchMessage(Handler.java:107)
   at android.os.Looper.loop(Looper.java:224)
   at android.app.ActivityThread.main(ActivityThread.java:7551)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)

Help please, what's the problem?


来源: stackexchange

问:
how to test useContext in conjuction with useReducer while utilizing custom hook to dispatch actions
I'm building a somple todo app and struggling to test my app's functionality.
a user should be able to add, delete and mark items as complete.
I've created a context and a component that will export the provider of the context and all the dependencies of the reducer as well (i.e the dispatch function and the resulting state change).
i already invested around three days trying to write a proper test but couldn't figure it out.
I would highly appreciate your help whether it's a test solution or refactoring advice.
I'm sharing a link to my repo instead of adding the code base to this posts since the code base is a bit big

My repo

ContentLicense: CC BY-SA 4.0


问:
What do I have to do so that a property will show at the datasource?
This is a windows forms question. forgive me if I explain what I do with too much detail but I asked with less detail before and it seems nobody read, because answers were completely off mark and I wasted bouty.

I have a Linq object called XX. It was created when I dropped my table on the .dbml file in visual studio.

Then, to make my interfaces easier to program I go to Data->Show Data Sources on visual Studio and create a object data source. All properties of the object appear at the data source.

But the linq class is partial, so i do:

```<code>partial class XX
{
    private int _myValue;
    public int myValue
    {
        get { return _myValue; }
        set { _myValue = value; }
    }
}
</code>```

are you following so far ?

Then i go and recreate the object data source.

The property myValue does not show on the data source.

I tried decoratin it like this:

```<code>        [Bindable(true)]
        public int myValue
</code>```

to no avail. This usualy does the trick for "non-linq" Plain classes.

So, the question is: What do I have to do so my property will show at the data source ?

ContentLicense: CC BY-SA 3.0

Body:
This is a windows forms question. forgive me if I explain what I do with too much detail but I asked with less detail before and it seems nobody read, because answers were completely off mark and I wasted bouty.

I have a Linq object called XX. It was created when I dropped my table on the .dbml file in visual studio.

Then, to make my interfaces easier to program I go to Data->Show Data Sources on visual Studio and create a object data source. All properties of the object appear at the data source.

But the linq class is partial, so i do:

partial class XX
{
    private int _myValue;
    public int myValue
    {
        get { return _myValue; }
        set { _myValue = value; }
    }
}

are you following so far ?

Then i go and recreate the object data source.

The property myValue does not show on the data source.

I tried decoratin it like this:

        [Bindable(true)]
        public int myValue

to no avail. This usualy does the trick for "non-linq" Plain classes.

So, the question is: What do I have to do so my property will show at the data source ?


问:
vue interceptors retry failed request and get response from component?
How I can get the response from vue axios interceptors to component where the request failed when I retry the failed request inside the interceptor?

code:

Component1.vue

```<code>axios.get('/api-1').then((response) => {
   // Do something here
});
</code>```

Component2.vue (failed API request)

```<code>axios.get('/api-2').then((response) => {
   // Do something here
});
</code>```

code in Interceptors.js

```<code>axios.interceptors.response.use(function (config) {
    // Do something before request is sent

    return config;
}, async function (error) {
    // Do something in Error response
    const status = error?.response?.status || 0
    const originalRequest = error.config;
    if (status === 401) { {
        try {
            setTimeout(async () => {
                const tokenData = await axios.get('/refresh-token');
                return axios(originalRequest); <-- how can I get this response to the components with failed API request?
            }, 2000);
        } catch (error) {
            return false;
        }
    }
    return Promise.reject(error);
});
</code>```

how can I get the response from interceptors.js to Component2.vue without using vuex?

Body:
How I can get the response from vue axios interceptors to component where the request failed when I retry the failed request inside the interceptor?

code:

Component1.vue

axios.get('/api-1').then((response) => {
   // Do something here
});

Component2.vue (failed API request)

axios.get('/api-2').then((response) => {
   // Do something here
});

code in Interceptors.js

axios.interceptors.response.use(function (config) {
    // Do something before request is sent

    return config;
}, async function (error) {
    // Do something in Error response
    const status = error?.response?.status || 0
    const originalRequest = error.config;
    if (status === 401) { {
        try {
            setTimeout(async () => {
                const tokenData = await axios.get('/refresh-token');
                return axios(originalRequest); <-- how can I get this response to the components with failed API request?
            }, 2000);
        } catch (error) {
            return false;
        }
    }
    return Promise.reject(error);
});

how can I get the response from interceptors.js to Component2.vue without using vuex?


问:
how can i push the slider down when hover to mega menu
I'm working on a new wordpress website using elementor pro and slider revolution. I need to add a new function so that the slides push a little downward when I hover over the mega menu. like this (https://www.poggenpohl.com/)

I tried to keep the mega menu and slider in the same div and add some javascript, but it didn't work out.


问:
can't show/display image from mongodb to directly react js component
I am new to MERN stack. I have already tried a lot of youtube videos and google searches to show/display the images stored in mongodb as the schema :

```<code>photograph: {
  data : Buffer,
  contentType : String
}
</code>```

It saved successfully in mongodb after few efforts. I tried to convert it into base64 as done by other youtubers but still no results so far.

All of the commented out- (img tags) and array.map functions  -> (because i tried to convert my data to array instead of json and then use .map function) are the things i have already tried. I am trying to understand the basics here. so please suggest me simple methods to do it. Also remember that {user.name} {user.dateOfBirth} , etc type of all other data showing successfully.

Body:
I am new to MERN stack. I have already tried a lot of youtube videos and google searches to show/display the images stored in mongodb as the schema :

photograph: {
  data : Buffer,
  contentType : String
}

It saved successfully in mongodb after few efforts. I tried to convert it into base64 as done by other youtubers but still no results so far.

All of the commented out- (img tags) and array.map functions  -> (because i tried to convert my data to array instead of json and then use .map function) are the things i have already tried. I am trying to understand the basics here. so please suggest me simple methods to do it. Also remember that {user.name} {user.dateOfBirth} , etc type of all other data showing successfully.


问:
Detecting Mouse Activities in 30FPS - tkinter
I'm using Python's tkinter to create a program that detects Mouse Activities in 30FPS.

This is the code I wrote so far.

```<code>from threading import Thread
from tkinter import *
from datetime import datetime

dtm = 0
touch = False
count = 0

root = Tk()
root.geometry("500x500+0+0")
root.title("Mouse Activity")

def counter():
   global dtm
   global touch
   global count
   if touch == False:
      dtm = datetime.now().isoformat(sep=' ', timespec='milliseconds')
      RightHand = [[0, dtm]]
      print(RightHand, touch)
      root.after(30, counter)

def handler1(e):
   global dtm
   global touch
   global count
   touch=True
   if(count % 3 == 0):
      dtm = datetime.now().isoformat(sep=' ', timespec='milliseconds')
      RightHand = [[1,dtm]]
      print(RightHand, count)
      count+=1
   else: count+=1
   x = canvas.canvasx(e.x)
   y = canvas.canvasx(e.y)

def handler2(e):
   global dtm
   global touch
   touch = False
   dtm = datetime.now().isoformat(sep=' ', timespec='milliseconds')
   RightHand = [[2, dtm]]
   print(RightHand)
   return counter()

canvas = Canvas(root, bd = 10, highlightthickness=0, width = 500, height = 500, bg = "#ABFFFA")
canvas.pack()

box1 = canvas.create_rectangle(100,100,400,400,fill='white')

counter()

canvas.tag_bind(box1,'<B1-Motion>', handler1)
canvas.tag_bind(box1,'<ButtonRelease-1>', handler2)

b = Thread(target = handler2, args = ())
b.start()

root.mainloop()
</code>```

The code detects the time of Left Mouse Button's Drag Motion and when it was released inside the white box. But it also outputs the time when it was not detecting any mouse activities.

The reason why I'm using count in handler1(e) is without it the code will detect the activities in a faster FPS.

As I said at the beggining, I want the code to detect Mouse Activities like drag, Left Mouse Button hold in 30FPS.

However The problem is,

When doing the Left Mouse Button Drag and stop moving while holding the button, the code stops measuring
until I release the button.

After releasing the Left Mouse Button without moving at all the FPS becomes faster.

it's also showing this error at the beggining.

```<code>Exception in thread Thread-1:
Traceback (most recent call last):
  File "D:\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "D:\Python\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: handler2() missing 1 required positional argument: 'e'
</code>```

Maybe this could be the problem?

I tried adding after() but it gives the maximum recursion depth error.
And I tried to solve the error at the beggining, but there's nothing I can do.

I'm still a beginner with Python and I'm also new to these kinds of stuff. So I may not have enough information to know what's wrong and being completly ignorant.

If there's anything missing  please ask me.

Body:
I'm using Python's tkinter to create a program that detects Mouse Activities in 30FPS.

This is the code I wrote so far.

from threading import Thread
from tkinter import *
from datetime import datetime

dtm = 0
touch = False
count = 0

root = Tk()
root.geometry("500x500+0+0")
root.title("Mouse Activity")

def counter():
   global dtm
   global touch
   global count
   if touch == False:
      dtm = datetime.now().isoformat(sep=' ', timespec='milliseconds')
      RightHand = [[0, dtm]]
      print(RightHand, touch)
      root.after(30, counter)

def handler1(e):
   global dtm
   global touch
   global count
   touch=True
   if(count % 3 == 0):
      dtm = datetime.now().isoformat(sep=' ', timespec='milliseconds')
      RightHand = [[1,dtm]]
      print(RightHand, count)
      count+=1
   else: count+=1
   x = canvas.canvasx(e.x)
   y = canvas.canvasx(e.y)

def handler2(e):
   global dtm
   global touch
   touch = False
   dtm = datetime.now().isoformat(sep=' ', timespec='milliseconds')
   RightHand = [[2, dtm]]
   print(RightHand)
   return counter()

canvas = Canvas(root, bd = 10, highlightthickness=0, width = 500, height = 500, bg = "#ABFFFA")
canvas.pack()

box1 = canvas.create_rectangle(100,100,400,400,fill='white')

counter()

canvas.tag_bind(box1,'<B1-Motion>', handler1)
canvas.tag_bind(box1,'<ButtonRelease-1>', handler2)

b = Thread(target = handler2, args = ())
b.start()

root.mainloop()

The code detects the time of Left Mouse Button's Drag Motion and when it was released inside the white box. But it also outputs the time when it was not detecting any mouse activities.

The reason why I'm using count in handler1(e) is without it the code will detect the activities in a faster FPS.

As I said at the beggining, I want the code to detect Mouse Activities like drag, Left Mouse Button hold in 30FPS.

However The problem is,

When doing the Left Mouse Button Drag and stop moving while holding the button, the code stops measuring
until I release the button.

After releasing the Left Mouse Button without moving at all the FPS becomes faster.

it's also showing this error at the beggining.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "D:\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "D:\Python\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: handler2() missing 1 required positional argument: 'e'

Maybe this could be the problem?

I tried adding after() but it gives the maximum recursion depth error.
And I tried to solve the error at the beggining, but there's nothing I can do.

I'm still a beginner with Python and I'm also new to these kinds of stuff. So I may not have enough information to know what's wrong and being completly ignorant.

If there's anything missing  please ask me.


问:
What is the way to serialize data as C# code?
Let's say I would like to serialize points as JSON:

```<code>  var points = new List<Point>();
  points.Add(GetPoint());
</code>```

I would probably get something like this:

```<code>[
  { "x" : 4, "y" : 3 }
]
</code>```

but now I would like to serialize the data as C# code, so I would get:

```<code>  var data = new List<Point>();
  data.Add(new Point(4,3));
</code>```

The serialization should produce valid C# code, so except for root variable name potential conflict, would be ready to copy&paste into actual program.

How to achieve this?

Maybe Expression trees would be useful, I know next to nothing about it, but I will check it out. I am afraid of complexity and I am not sure how it will handle refactoring, see below.

Background: this is for making almost automatic tests, in case of a problem I would dump data as C# code, copy&paste it as unit test, and because it would be C# code, it could be polished, refactored, etc. For example if I ever would like to change property name from "x" to "X" there would be zero problems with it.

Body:
Let's say I would like to serialize points as JSON:

  var points = new List<Point>();
  points.Add(GetPoint());

I would probably get something like this:

[
  { "x" : 4, "y" : 3 }
]

but now I would like to serialize the data as C# code, so I would get:

  var data = new List<Point>();
  data.Add(new Point(4,3));

The serialization should produce valid C# code, so except for root variable name potential conflict, would be ready to copy&paste into actual program.

How to achieve this?

Maybe Expression trees would be useful, I know next to nothing about it, but I will check it out. I am afraid of complexity and I am not sure how it will handle refactoring, see below.

Background: this is for making almost automatic tests, in case of a problem I would dump data as C# code, copy&paste it as unit test, and because it would be C# code, it could be polished, refactored, etc. For example if I ever would like to change property name from "x" to "X" there would be zero problems with it.


问:
Error parsing onnx model while trying to use YOLOv5
I want to use YOLOv5 for object detection Using C++ and OpenCV's DNN. I'm using Windows 10, and VS 2019.

However, the following line of code:

```<code>#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("yolov5s.onnx");

    return 0;
}
</code>```

causes the following error:

```<code> OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:57: error: (-210:Unsupported format or combination of formats) Failed to parse onnx model in function 'cv::dnn::dnn4_v20190621::ONNXImporter::ONNXImporter'

Press any key to continue . . .
</code>```

This is a link to the original .pt file that I downloaded from the Yolov5 repository, and this is a link to the .onnx file that I converted as per the instructions.

Edit:

Seems there was a problem with the path.

After I wrote the full path to the full .onnx file path, as follows:

```<code>#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("C:/Users/hedey/source/repos/Road_Defects_Detector/yolov5s.onnx");

    return 0;
}
</code>```

Now, I'm getting the following error:

```<code>OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:320: error: (-204:Requested object was not found) Blob  not found in const blobs in function 'cv::dnn::dnn4_v20190621::ONNXImporter::getBlob'

Press any key to continue . . .
</code>```

Body:
I want to use YOLOv5 for object detection Using C++ and OpenCV's DNN. I'm using Windows 10, and VS 2019.

However, the following line of code:

#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("yolov5s.onnx");

    return 0;
}

causes the following error:

 OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:57: error: (-210:Unsupported format or combination of formats) Failed to parse onnx model in function 'cv::dnn::dnn4_v20190621::ONNXImporter::ONNXImporter'

Press any key to continue . . .

This is a link to the original .pt file that I downloaded from the Yolov5 repository, and this is a link to the .onnx file that I converted as per the instructions.

Edit:

Seems there was a problem with the path.

After I wrote the full path to the full .onnx file path, as follows:

#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("C:/Users/hedey/source/repos/Road_Defects_Detector/yolov5s.onnx");

    return 0;
}

Now, I'm getting the following error:

OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:320: error: (-204:Requested object was not found) Blob  not found in const blobs in function 'cv::dnn::dnn4_v20190621::ONNXImporter::getBlob'

Press any key to continue . . .


问:
PHP generated ICS file - "Safari cannot download this file"
I've written some PHP code to generate an ICS file for a user to download and add to their own calendar. It works fine on desktop Safari (macOS 12.6), and it also works fine if I airdrop the downloaded ICS file to my iPhone. However, if I try to download the ICS file directly on mobile safari (iOS 16.1.2) I get the message "Safari cannot download this file".

Do I need to sign the file somehow? or is the PHP 'readfile' command not allowed on iOS?

Thanks!

```<code>`<?php

// Get the event details from the form data
$result_sched = json_decode($_POST['result_sched'], true);
$returnedCountSched = json_decode($_POST['returnedCountSched'], true);

// Open the ICS file for writing
$icsFile = fopen("events.ics", "w");

// Write the ICS file header
fwrite($icsFile, "BEGIN:VCALENDAR\n");
fwrite($icsFile, "PRODID:-//Your Company//Product//Language\n");
fwrite($icsFile, "VERSION:2.0\n");
fwrite($icsFile, "METHOD:PUBLISH\n");

// Iterate through the loop and write each event to the ICS file
for ($j = 0; $j < $returnedCountSched; $j++) {
    // Get the date and time strings from the result_sched array
    $date_string = $result_sched['response']['data'][$j]['fieldData']['service_date'];
    $start_time_string = $result_sched['response']['data'][$j]['fieldData']['service_start_time'];
    $end_time_string = $result_sched['response']['data'][$j]['fieldData']['service_end_time'];

    // set time zone to los angeles
    date_default_timezone_set('America/Los_Angeles');

    // Format the date and time strings
    $date = date("Ymd", strtotime($date_string));
    $start_time = date("His", strtotime($start_time_string));
    $end_time = date("His", strtotime($end_time_string));

    // Combine the date and time strings and convert to a timestamp
    $start_timestamp = strtotime("$date $start_time");
    $end_timestamp = strtotime("$date $end_time");

    // Format the timestamp as an ICS-formatted DTSTART string
    $dtstart = gmdate("Ymd\THis\Z", $start_timestamp);
    $dtend = gmdate("Ymd\THis\Z", $end_timestamp);

    $location = $result_sched['response']['data'][$j]['fieldData']['service_venue_name'];
    $summary = $result_sched['response']['data'][$j]['fieldData']['service_title'];
    $description = $result_sched['response']['data'][$j]['fieldData']['rehearsal_order_summary'];

    // Write the event to the ICS file
    fwrite($icsFile, "BEGIN:VEVENT\n");
    fwrite($icsFile, "DTSTART:$dtstart\n");
    fwrite($icsFile, "DTEND:$dtend\n");
    fwrite($icsFile, "LOCATION:$location\n");
    fwrite($icsFile, "SUMMARY:$summary\n");
    fwrite($icsFile, "DESCRIPTION:$description\n");
    fwrite($icsFile, "END:VEVENT\n");
}

fwrite($icsFile, "END:VCALENDAR\n");

fclose($icsFile);

// Output the ICS file as a download
header('Content-Description: File Transfer');
header('Content-Type: text/calendar; charset=utf-8');
//header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=events.ics');
// header('Content-Transfer-Encoding: binary');
// header('Expires: 0');
// header('Cache-Control: must-revalidate');
// header('Pragma: public');

// Output the ICS file
readfile('events.ics');

?>`
</code>```

I've also tried this in Chrome on the desktop and I get 0 byte download files, whereas I get the expected ICS file when download on desktop Safari. I must be doing something wrong!

I feel like it has something to do with how I'm setting the headers, but I'm at a loss.

Body:
I've written some PHP code to generate an ICS file for a user to download and add to their own calendar. It works fine on desktop Safari (macOS 12.6), and it also works fine if I airdrop the downloaded ICS file to my iPhone. However, if I try to download the ICS file directly on mobile safari (iOS 16.1.2) I get the message "Safari cannot download this file".

Do I need to sign the file somehow? or is the PHP 'readfile' command not allowed on iOS?

Thanks!

`<?php

// Get the event details from the form data
$result_sched = json_decode($_POST['result_sched'], true);
$returnedCountSched = json_decode($_POST['returnedCountSched'], true);

// Open the ICS file for writing
$icsFile = fopen("events.ics", "w");

// Write the ICS file header
fwrite($icsFile, "BEGIN:VCALENDAR\n");
fwrite($icsFile, "PRODID:-//Your Company//Product//Language\n");
fwrite($icsFile, "VERSION:2.0\n");
fwrite($icsFile, "METHOD:PUBLISH\n");

// Iterate through the loop and write each event to the ICS file
for ($j = 0; $j < $returnedCountSched; $j++) {
    // Get the date and time strings from the result_sched array
    $date_string = $result_sched['response']['data'][$j]['fieldData']['service_date'];
    $start_time_string = $result_sched['response']['data'][$j]['fieldData']['service_start_time'];
    $end_time_string = $result_sched['response']['data'][$j]['fieldData']['service_end_time'];

    // set time zone to los angeles
    date_default_timezone_set('America/Los_Angeles');

    // Format the date and time strings
    $date = date("Ymd", strtotime($date_string));
    $start_time = date("His", strtotime($start_time_string));
    $end_time = date("His", strtotime($end_time_string));

    // Combine the date and time strings and convert to a timestamp
    $start_timestamp = strtotime("$date $start_time");
    $end_timestamp = strtotime("$date $end_time");

    // Format the timestamp as an ICS-formatted DTSTART string
    $dtstart = gmdate("Ymd\THis\Z", $start_timestamp);
    $dtend = gmdate("Ymd\THis\Z", $end_timestamp);

    $location = $result_sched['response']['data'][$j]['fieldData']['service_venue_name'];
    $summary = $result_sched['response']['data'][$j]['fieldData']['service_title'];
    $description = $result_sched['response']['data'][$j]['fieldData']['rehearsal_order_summary'];

    // Write the event to the ICS file
    fwrite($icsFile, "BEGIN:VEVENT\n");
    fwrite($icsFile, "DTSTART:$dtstart\n");
    fwrite($icsFile, "DTEND:$dtend\n");
    fwrite($icsFile, "LOCATION:$location\n");
    fwrite($icsFile, "SUMMARY:$summary\n");
    fwrite($icsFile, "DESCRIPTION:$description\n");
    fwrite($icsFile, "END:VEVENT\n");
}

fwrite($icsFile, "END:VCALENDAR\n");

fclose($icsFile);

// Output the ICS file as a download
header('Content-Description: File Transfer');
header('Content-Type: text/calendar; charset=utf-8');
//header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=events.ics');
// header('Content-Transfer-Encoding: binary');
// header('Expires: 0');
// header('Cache-Control: must-revalidate');
// header('Pragma: public');

// Output the ICS file
readfile('events.ics');

?>`

I've also tried this in Chrome on the desktop and I get 0 byte download files, whereas I get the expected ICS file when download on desktop Safari. I must be doing something wrong!

I feel like it has something to do with how I'm setting the headers, but I'm at a loss.


问:
Python conditional return
Quite frequently, I have written lines like

if arg == foo: return bar

It is naturally a one-liner, at the beginning of a function body. Notice there is no else, it just returns on  a special value of the parameter, and proceeds with the normal flow of the function otherwise.

Still, it feels like the order is wrong.  In perl it is possible to write (modulo some $'s)

return bar if arg == foo

which feels more natural.  Matter of taste, I know.

Is there a pythonic way of writing something after a return word that would impose a condition on the return statement?

It is, of course, possible, that there is no way.

Title: Python conditional return


问:
Is it possible to make a ThreadPoolExecutor with a PriorityBlockingQueue<Callable<Object>> queue?
I have tried to write a code for an assignment that I have. In that assignment I need to create a callable and to put it in a threadpool with a priority. I didnt succeed because I am unable to put a callable<Object> queue in the ThreadPoolExecutor queue section.

Here is the customExecuter code which uses ThreadPoolExecuter. the queue part in the new ThreadPoolExecuter is marked in red.

```<code>package Ex2Part2;

import java.util.concurrent.*;
public class CustomExecutor {
    private final int minPoolSize;
    private final int maxPoolSize;
    private final PriorityBlockingQueue<Callable<Object>> queue;
    private final ThreadPoolExecutor executor;

    private int maxPriority = 0;
    private boolean isShutdown = false;
        public CustomExecutor() {
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        this.minPoolSize = availableProcessors / 2;
        this.maxPoolSize = availableProcessors - 1;
        this.queue = new PriorityBlockingQueue<>();
        this.executor = new ThreadPoolExecutor(minPoolSize, maxPoolSize, 0, TimeUnit.MILLISECONDS, queue);
    }

    public <T> CompletableFuture<T> submit(Callable<T> task, TaskType priority) throws Exception {
        if (isShutdown) {
            throw new IllegalStateException("Thread pool has already been shut down");
        }
        CompletableFuture<T> future = new CompletableFuture<>();
        Task callable = new Task(task, priority);
        future=callable.call();
        maxPriority = Math.max(maxPriority, priority.getPriorityValue());
        queue.put(callable);
        return future;
    }

    public int getCurrentMax() {
        return maxPriority;
    }

    public void gracefullyTerminate() {
        isShutdown = true;
        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            // Handle interrupted exception
        }
    }
}
</code>```

Here is my task code:

```<code>public class Task implements Callable<Object> {
        private  Callable<?> task;
        private  TaskType priority;

        public Task(Callable<?> task, TaskType priority) {
            this.task = task;
            this.priority = priority;
        }
    public static  <T> Task createTask(Callable<T> task,TaskType priority)
    {
        Task newTask=new Task(task,priority);
        return newTask;
    }
    @Override
    public Object call() throws Exception {
        return task.call();
    }

    public int Comperator(Task other) {
            return Integer.compare(priority.getPriorityValue(), other.priority.getPriorityValue());
        }
    }
</code>```

Another question that I have is in the CustomExecuter in the submit part I dont know how to return the future part so that I will be able to get it in my tests.

......................

Body:
I have tried to write a code for an assignment that I have. In that assignment I need to create a callable and to put it in a threadpool with a priority. I didnt succeed because I am unable to put a callable<Object> queue in the ThreadPoolExecutor queue section.

Here is the customExecuter code which uses ThreadPoolExecuter. the queue part in the new ThreadPoolExecuter is marked in red.

package Ex2Part2;

import java.util.concurrent.*;
public class CustomExecutor {
    private final int minPoolSize;
    private final int maxPoolSize;
    private final PriorityBlockingQueue<Callable<Object>> queue;
    private final ThreadPoolExecutor executor;

    private int maxPriority = 0;
    private boolean isShutdown = false;
        public CustomExecutor() {
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        this.minPoolSize = availableProcessors / 2;
        this.maxPoolSize = availableProcessors - 1;
        this.queue = new PriorityBlockingQueue<>();
        this.executor = new ThreadPoolExecutor(minPoolSize, maxPoolSize, 0, TimeUnit.MILLISECONDS, queue);
    }

    public <T> CompletableFuture<T> submit(Callable<T> task, TaskType priority) throws Exception {
        if (isShutdown) {
            throw new IllegalStateException("Thread pool has already been shut down");
        }
        CompletableFuture<T> future = new CompletableFuture<>();
        Task callable = new Task(task, priority);
        future=callable.call();
        maxPriority = Math.max(maxPriority, priority.getPriorityValue());
        queue.put(callable);
        return future;
    }

    public int getCurrentMax() {
        return maxPriority;
    }

    public void gracefullyTerminate() {
        isShutdown = true;
        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            // Handle interrupted exception
        }
    }
}

Here is my task code:

public class Task implements Callable<Object> {
        private  Callable<?> task;
        private  TaskType priority;

        public Task(Callable<?> task, TaskType priority) {
            this.task = task;
            this.priority = priority;
        }
    public static  <T> Task createTask(Callable<T> task,TaskType priority)
    {
        Task newTask=new Task(task,priority);
        return newTask;
    }
    @Override
    public Object call() throws Exception {
        return task.call();
    }

    public int Comperator(Task other) {
            return Integer.compare(priority.getPriorityValue(), other.priority.getPriorityValue());
        }
    }

Another question that I have is in the CustomExecuter in the submit part I dont know how to return the future part so that I will be able to get it in my tests.

......................


问:
In Spark streaming, getting no output in append mode
I am reading data from Kaka topic and then doing a group by on the message received from topic
val lines = spark.readStream.format("Kafka")...
val df1 = lines.select($"timestamp", $"value".cast("STRING"))
...// Created a schema and fetched message from value and now df3 has schema timestamp and message string

Now, doing a group by on message to find the count and tried writing the result in file in append output mode. But it gave watermark error so in group by included timestamp like screenshot

My code snapshot

Can someone help how can I dump the count in file in append output mode

I expect the message count to be written in file for new data received in Kafka topic. Console mode is not suitable for my usecase


问:
How to add popconfirm to upload in antd react?
i need to add popconfirm element to upload element. i've tried to do this:

```<code>                    <Popconfirm
                      title="Add file to CDS?"
                      onConfirm={() => this.cleanGroup(group.key)}
                      okText="Да"
                      cancelText="Отмена"
                      disabled={group.items.length === 0}
                      open={this.state.open}
                    >
                      <Upload
                        style={{ width: '100%' }}
                        name="fileManager"
                        action={uploadUrl}
                        headers={headers}
                        data={{
                         group: group.key,
                         }}
                        showUploadList={false}
                        onChange={(info => this.uploadHandler(info))}
                        }}

                      >
                        <Tooltip title="Add file">
                          <Button icon={<PlusOutlined />} type="primary" />
                        </Tooltip>
                      </Upload>
                    </Popconfirm>
</code>```

But in such case it ignore popconfirm. then i hsve tired manual download in upload element:

```<code>                      title="Вы хотите добавить файл в анкету ЦДС?"
                      onConfirm={() => this.cleanGroup(group.key)}
                      okText="Да"
                      cancelText="Отмена"
                      disabled={group.items.length === 0}
                      open={this.state.open}
                    >
                      <Upload
                        style={{ width: '100%' }}
                        name="fileManager"
                        beforeUpload={(file) => {
                          console.log("fgfd");
                          this.setState({
                            fileList: [...this.state.fileList, file],
                          });
                          this.setState({
                            open: true,
                          })
                          return false;
                        }}
                      >
                        <Tooltip title="Добавить файл">
                          <Button icon={<PlusOutlined />} type="primary" />
                        </Tooltip>
                      </Upload>
                    </Popconfirm>
</code>```

this solution works, but the problem is that popconfirm and upload components are being rendered in array, so i get 5 popconfirms modals insteasd of one. i don't understand how to render popconfirm only for this upload element, not for all elements. any help will be appreciated!

Body:
i need to add popconfirm element to upload element. i've tried to do this:

                    <Popconfirm
                      title="Add file to CDS?"
                      onConfirm={() => this.cleanGroup(group.key)}
                      okText="Да"
                      cancelText="Отмена"
                      disabled={group.items.length === 0}
                      open={this.state.open}
                    >
                      <Upload
                        style={{ width: '100%' }}
                        name="fileManager"
                        action={uploadUrl}
                        headers={headers}
                        data={{
                         group: group.key,
                         }}
                        showUploadList={false}
                        onChange={(info => this.uploadHandler(info))}
                        }}

                      >
                        <Tooltip title="Add file">
                          <Button icon={<PlusOutlined />} type="primary" />
                        </Tooltip>
                      </Upload>
                    </Popconfirm>

But in such case it ignore popconfirm. then i hsve tired manual download in upload element:

                      title="Вы хотите добавить файл в анкету ЦДС?"
                      onConfirm={() => this.cleanGroup(group.key)}
                      okText="Да"
                      cancelText="Отмена"
                      disabled={group.items.length === 0}
                      open={this.state.open}
                    >
                      <Upload
                        style={{ width: '100%' }}
                        name="fileManager"
                        beforeUpload={(file) => {
                          console.log("fgfd");
                          this.setState({
                            fileList: [...this.state.fileList, file],
                          });
                          this.setState({
                            open: true,
                          })
                          return false;
                        }}
                      >
                        <Tooltip title="Добавить файл">
                          <Button icon={<PlusOutlined />} type="primary" />
                        </Tooltip>
                      </Upload>
                    </Popconfirm>

this solution works, but the problem is that popconfirm and upload components are being rendered in array, so i get 5 popconfirms modals insteasd of one. i don't understand how to render popconfirm only for this upload element, not for all elements. any help will be appreciated!


问:
Playstore promo video is not visible after changing it
Recently I changed the Google play store video of  Vinota International calling app  but after changing its not visible anymore, this is the video I used

https://www.youtube.com/watch?v=RCKb0socOZk

This meets the PlayStore guidlines, any suggetions?

I checked the guildlines


问:
Trying to train a spacy model using GPU but PyTorch throws the "Out Of Memory Error"
I'm Trying to build a parser to recognize entities from text given and to train the spacy model with GPU I went ahead and installed all the necessary packages but while training it runs the first iteration and throws the "Cuda Out Of Memory Error"

i was using this command on my terminal to train the model: python -m spacy train C:\Users\User\PycharmProjects\pythonProject\pythonProject3\config.cfg --output ./output --paths.train ./train_data.spacy --paths.dev ./test_data.spacy --gpu-id 0

And after the First Iteration it gives me this error:
RuntimeError: CUDA out of memory. Tried to allocate 12.00 MiB (GPU 0; 6.00 GiB total capacity; 4.99 GiB already allocated; 0 bytes free; 5.33 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

What i dont seem to understand here is it mentions 0 bytes free. is there anything i can possibly do to provide some space and train my Model?


问:
How do I get Xcode to show dots instead of spaces in the editor?
How do I get dots instead of spaces in the Xcode editor similar to this image below?

The dots on the left side of the code.


问:
Trying to upgrade PDFJS from 2.6.146 -> absolute (scroll) problem
I´m trying to upgrade the Mozilla pdf.js library from 2.6.347 but get the error

```<code>pdf_viewer.js:254 Uncaught Error: The container must be absolutely positioned.
</code>```

But when upgrading to a later version and setting the container to be absolutely positioned I obviously get a different behavior. I´m trying to use the browser scroll not the scroll of the container. How can I do this?

Expected behavior with  2.6.347:

https://stackblitz.com/edit/bootstrap-5-3v7wgs?file=src/index.html

What went wrong:

https://stackblitz.com/edit/bootstrap-5-brshqu?file=src/index.html

Body:
I´m trying to upgrade the Mozilla pdf.js library from 2.6.347 but get the error

pdf_viewer.js:254 Uncaught Error: The container must be absolutely positioned.

But when upgrading to a later version and setting the container to be absolutely positioned I obviously get a different behavior. I´m trying to use the browser scroll not the scroll of the container. How can I do this?

Expected behavior with  2.6.347:

https://stackblitz.com/edit/bootstrap-5-3v7wgs?file=src/index.html

What went wrong:

https://stackblitz.com/edit/bootstrap-5-brshqu?file=src/index.html


问:
How to prevent multiple builds of a library in a workspace, when binaries enable different features?
I have a Cargo workspace with a library and multiple binaries. The binaries enable different features in the library, and I would like to build the library only once (because it's big and building it takes a lot of time).

However, if I invoke cargo run/cargo test/clippy in the directory of one of the packages, the library is rebuilt with only the features enabled by the package I'm building.

Is it possible to tell cargo to apply feature unification as if the whole workspace is being built, when building only one package?


问:
WinError 10060 error in Jupyter python coding when I can access a URL and its csv file in browser directely
I have a strange problem when I use Jupyter for python programming, I can access a URL and the corresponding csv file in my browser directely, but I get an error when reading it with the following command [WinError 10060].
For example:
df_rating=pd.read_csv("https://frankxu1987.weebly.com/uploads/6/2/5/8/62583677/acf351b_ratings.csv")
and the error message is:
URLError: <urlopen error [WinError 10060] (Connection attempt failed because the connecting party did not reply correctly after some time or the connected host did not respond)
(I am using a Chinese environment in win 10, if this could help. Also, I am using VPN but this error occurs with or without VPN)

I tried start and shut down VPN for many times but it didn't help anyway. Could anyone tell me the reason? Much thanks.


问:
Chromedriver autoinstaller not updating webdriver
I'm trying to auto-update Chrome webdriver using Chromedriver Auto-installer but it's not updating the webdriver. I get this error:

```<code>DevTools listening on ws://127.0.0.1:61707/devtools/browser/d1fc6270-6f69-47a3-90f3-54df9350bb0f
Traceback (most recent call last):
  File "C:\Users\Kevin\Desktop\test2.py", line 9, in <module>
    driver = webdriver.Chrome()
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 69, in __init__
    super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 92, in __init__
    super().__init__(
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 272, in __init__
    self.start_session(capabilities, browser_profile)
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 364, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 243, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 106
Current browser version is 108.0.5359.125 with binary path C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
Stacktrace:
Backtrace:
        Ordinal0 [0x00901ED3+2236115]
        Ordinal0 [0x008992F1+1807089]
        Ordinal0 [0x007A66FD+812797]
        Ordinal0 [0x007C8C6D+953453]
        Ordinal0 [0x007C4200+934400]
        Ordinal0 [0x007C19C9+924105]
        Ordinal0 [0x007F806C+1146988]
        Ordinal0 [0x007F7A6A+1145450]
        Ordinal0 [0x007F18A6+1120422]
        Ordinal0 [0x007CA73D+960317]
        Ordinal0 [0x007CB71F+964383]
        GetHandleVerifier [0x00BAE7E2+2743074]
        GetHandleVerifier [0x00BA08D4+2685972]
        GetHandleVerifier [0x00992BAA+532202]
        GetHandleVerifier [0x00991990+527568]
        Ordinal0 [0x008A080C+1837068]
        Ordinal0 [0x008A4CD8+1854680]
        Ordinal0 [0x008A4DC5+1854917]
        Ordinal0 [0x008AED64+1895780]
        BaseThreadInitThunk [0x75A000F9+25]
        RtlGetAppContainerNamedObjectPath [0x774F7BBE+286]
        RtlGetAppContainerNamedObjectPath [0x774F7B8E+238]
</code>```

I'm using code straight from the documentation.

```<code>from selenium import webdriver
import chromedriver_autoinstaller

chromedriver_autoinstaller.install()  # Check if the current version of chromedriver exists
                                      # and if it doesn't exist, download it automatically,
                                      # then add chromedriver to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")
assert "Python" in driver.title

</code>```

It should check my version of chromedriver and update if needed, but that isn't happening at all.

Body:
I'm trying to auto-update Chrome webdriver using Chromedriver Auto-installer but it's not updating the webdriver. I get this error:

DevTools listening on ws://127.0.0.1:61707/devtools/browser/d1fc6270-6f69-47a3-90f3-54df9350bb0f
Traceback (most recent call last):
  File "C:\Users\Kevin\Desktop\test2.py", line 9, in <module>
    driver = webdriver.Chrome()
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 69, in __init__
    super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 92, in __init__
    super().__init__(
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 272, in __init__
    self.start_session(capabilities, browser_profile)
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 364, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Kevin\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 243, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 106
Current browser version is 108.0.5359.125 with binary path C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
Stacktrace:
Backtrace:
        Ordinal0 [0x00901ED3+2236115]
        Ordinal0 [0x008992F1+1807089]
        Ordinal0 [0x007A66FD+812797]
        Ordinal0 [0x007C8C6D+953453]
        Ordinal0 [0x007C4200+934400]
        Ordinal0 [0x007C19C9+924105]
        Ordinal0 [0x007F806C+1146988]
        Ordinal0 [0x007F7A6A+1145450]
        Ordinal0 [0x007F18A6+1120422]
        Ordinal0 [0x007CA73D+960317]
        Ordinal0 [0x007CB71F+964383]
        GetHandleVerifier [0x00BAE7E2+2743074]
        GetHandleVerifier [0x00BA08D4+2685972]
        GetHandleVerifier [0x00992BAA+532202]
        GetHandleVerifier [0x00991990+527568]
        Ordinal0 [0x008A080C+1837068]
        Ordinal0 [0x008A4CD8+1854680]
        Ordinal0 [0x008A4DC5+1854917]
        Ordinal0 [0x008AED64+1895780]
        BaseThreadInitThunk [0x75A000F9+25]
        RtlGetAppContainerNamedObjectPath [0x774F7BBE+286]
        RtlGetAppContainerNamedObjectPath [0x774F7B8E+238]

I'm using code straight from the documentation.

from selenium import webdriver
import chromedriver_autoinstaller

chromedriver_autoinstaller.install()  # Check if the current version of chromedriver exists
                                      # and if it doesn't exist, download it automatically,
                                      # then add chromedriver to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")
assert "Python" in driver.title

It should check my version of chromedriver and update if needed, but that isn't happening at all.


问:
python: how to find name of currently evaluating argument during function call
given the code example below: how can I get the name of argument corresponding to particular evaluation of function get_arg_val.</p>
```<code>def do_sum(a, b, c):
    return a + b + c

def get_arg_val():
    print("call f") # what argument this call corresponds to: a, b or c ???
    return 1

x = do_sum(get_arg_val(), get_arg_val(), get_arg_val())
print(x)
</code>```

Body:
given the code example below: how can I get the name of argument corresponding to particular evaluation of function get_arg_val.

def do_sum(a, b, c):
    return a + b + c

def get_arg_val():
    print("call f") # what argument this call corresponds to: a, b or c ???
    return 1

x = do_sum(get_arg_val(), get_arg_val(), get_arg_val())
print(x)


问:
Fastify openapi 3 create alway required fields
i use @fastify/swagger and @fastify/swagger-ui,
my config

import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';
import { FastifyInstance } from 'fastify';
import fp from 'fastify-plugin';

const swagger = async (fastify: FastifyInstance) => {
  await fastify.register(fastifySwagger, {
    mode: 'dynamic',
    openapi: {
      openapi: '3.0.3',
      info: {
        title: 'openapi',
        version: '0.1.0'
      }
    }
  });

  await fastify.register(fastifySwaggerUi, {
    routePrefix: '/openapi',
    uiConfig: {
      deepLinking: true
    },
    uiHooks: {
      onRequest: function (request, reply, next) {
        next();
      },
      preHandler: function (request, reply, next) {
        next();
      }
    },
    staticCSP: true,
    transformStaticCSP: (header) => header,
    transformSpecification: (swaggerObject, request, reply) => {
      return swaggerObject;
    },
    transformSpecificationClone: true
  });
};

export default fp(swagger);
```
<p>my routes like this</p>
<pre class="lang-js prettyprint-override"><code>export const articleRouter = async (fastify: FastifyInstance) => {
  fastify.get(
    '/list',
    {
      schema: {
        tags: ['article'],
        summary: 'getting artilce list',
        description: 'description in routes',
        params: {
          type: 'object',
          description: 'some params',
          properties: {
            limit: {
              type: 'number',
              description: 'limit articles'
            },
            sort: {
              type: 'string',
              description: 'asc or desc'
            }
          },
          required: ['sort']
        },
      }
    },
    async (req, resp) => {
      const articles = await articleService.findArticles();
      resp.send(articles);
    }
  );
};
</code>```

swagger screenshot

enter image description here

All works, but field 'limit' is alway required. Why?

Please, help me.

I'm playing with all properties in config and routes but no one helpe me.

@fastify/swagger @fastify/swagger-ui

Body:
i use @fastify/swagger and @fastify/swagger-ui,
my config

import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';
import { FastifyInstance } from 'fastify';
import fp from 'fastify-plugin';

const swagger = async (fastify: FastifyInstance) => {
  await fastify.register(fastifySwagger, {
    mode: 'dynamic',
    openapi: {
      openapi: '3.0.3',
      info: {
        title: 'openapi',
        version: '0.1.0'
      }
    }
  });

  await fastify.register(fastifySwaggerUi, {
    routePrefix: '/openapi',
    uiConfig: {
      deepLinking: true
    },
    uiHooks: {
      onRequest: function (request, reply, next) {
        next();
      },
      preHandler: function (request, reply, next) {
        next();
      }
    },
    staticCSP: true,
    transformStaticCSP: (header) => header,
    transformSpecification: (swaggerObject, request, reply) => {
      return swaggerObject;
    },
    transformSpecificationClone: true
  });
};

export default fp(swagger);

my routes like this

export const articleRouter = async (fastify: FastifyInstance) => {
  fastify.get(
    '/list',
    {
      schema: {
        tags: ['article'],
        summary: 'getting artilce list',
        description: 'description in routes',
        params: {
          type: 'object',
          description: 'some params',
          properties: {
            limit: {
              type: 'number',
              description: 'limit articles'
            },
            sort: {
              type: 'string',
              description: 'asc or desc'
            }
          },
          required: ['sort']
        },
      }
    },
    async (req, resp) => {
      const articles = await articleService.findArticles();
      resp.send(articles);
    }
  );
};

swagger screenshot

enter image description here

All works, but field 'limit' is alway required. Why?

Please, help me.

I'm playing with all properties in config and routes but no one helpe me.

@fastify/swagger @fastify/swagger-ui


问:
DataStore - User is unauthorized to query syncLands with auth mode API_KEY
I have an expo app powered by aws amplify that was working fine till a few days ago when I tried to use subscription on a useEffect query. Now even after removing the subscription I get the following error

DataStore - User is unauthorized to query syncCustomers with auth mode API_KEY. No data could be returned.

Therefore no data is being fetched from the backend. I searched around the net to find out if there was a known solution but I couldn't find any. According to some it is related to the Auth mode but even that didn't work.

Here's a sample of the code

```<code>import { useWindowDimensions, TouchableOpacity } from "react-native";
import React, { useEffect,  useState } from "react";
import MapView, { PROVIDER_GOOGLE } from "react-native-maps";
import { Amplify, AuthModeStrategyType } from "aws-amplify";
import awsconfig from "../aws-exports";
import { DataStore } from "@aws-amplify/datastore";
import { House, Lands } from "../models";
import LandMark from "../components/LandMark";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import HouseMark from "../components/HouseMark";
import { mapStyle } from "../utils";

Amplify.configure({
  ...awsconfig,
  Analytics: {
    disabled: true,
  },
  DataStore: {
    authModeStrategyType: AuthModeStrategyType.MULTI_AUTH,
  },
});

const SellScreen = () => {
  const [houses, setHouses] = useState();
  const [terrain, setTerrain] = useState();
  const { width, height } = useWindowDimensions();

  useEffect(() => {

    try {
      DataStore.query(Lands, (l) => l.available.eq(true)).then(setTerrain);

      DataStore.query(House, (h) => h.available.eq(true)).then(setHouses);

    } catch (error) {
      console.log(error);
    }
  }, []);

  return (
    <GestureHandlerRootView className=" flex-1">
      <MapView
        provider={PROVIDER_GOOGLE}
        style={{
          width,
          height,
        }}
        customMapStyle={mapStyle}
        initialRegion={{
          latitude: 1,
          longitude: 2,
          latitudeDelta: 0.7,
          longitudeDelta: 0.7,
        }}
      >

        {terrain &&
          terrain.map((land, id) => (
            <TouchableOpacity key={id}>
              <LandMark land={land} />
            </TouchableOpacity>
          ))}

        {houses &&
          houses.map((house, id) => (
            <TouchableOpacity key={id}>
              <HouseMark house={house} />
            </TouchableOpacity>
          ))}
      </MapView>
    </GestureHandlerRootView>
  );
};

export default SellScreen;
</code>```

I am using Amplify Studio and there's no place where I'm explicitly using GraphQL

Here's the error...

Body:
I have an expo app powered by aws amplify that was working fine till a few days ago when I tried to use subscription on a useEffect query. Now even after removing the subscription I get the following error

DataStore - User is unauthorized to query syncCustomers with auth mode API_KEY. No data could be returned.

Therefore no data is being fetched from the backend. I searched around the net to find out if there was a known solution but I couldn't find any. According to some it is related to the Auth mode but even that didn't work.

Here's a sample of the code

import { useWindowDimensions, TouchableOpacity } from "react-native";
import React, { useEffect,  useState } from "react";
import MapView, { PROVIDER_GOOGLE } from "react-native-maps";
import { Amplify, AuthModeStrategyType } from "aws-amplify";
import awsconfig from "../aws-exports";
import { DataStore } from "@aws-amplify/datastore";
import { House, Lands } from "../models";
import LandMark from "../components/LandMark";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import HouseMark from "../components/HouseMark";
import { mapStyle } from "../utils";

Amplify.configure({
  ...awsconfig,
  Analytics: {
    disabled: true,
  },
  DataStore: {
    authModeStrategyType: AuthModeStrategyType.MULTI_AUTH,
  },
});

const SellScreen = () => {
  const [houses, setHouses] = useState();
  const [terrain, setTerrain] = useState();
  const { width, height } = useWindowDimensions();

  useEffect(() => {

    try {
      DataStore.query(Lands, (l) => l.available.eq(true)).then(setTerrain);

      DataStore.query(House, (h) => h.available.eq(true)).then(setHouses);

    } catch (error) {
      console.log(error);
    }
  }, []);

  return (
    <GestureHandlerRootView className=" flex-1">
      <MapView
        provider={PROVIDER_GOOGLE}
        style={{
          width,
          height,
        }}
        customMapStyle={mapStyle}
        initialRegion={{
          latitude: 1,
          longitude: 2,
          latitudeDelta: 0.7,
          longitudeDelta: 0.7,
        }}
      >

        {terrain &&
          terrain.map((land, id) => (
            <TouchableOpacity key={id}>
              <LandMark land={land} />
            </TouchableOpacity>
          ))}

        {houses &&
          houses.map((house, id) => (
            <TouchableOpacity key={id}>
              <HouseMark house={house} />
            </TouchableOpacity>
          ))}
      </MapView>
    </GestureHandlerRootView>
  );
};

export default SellScreen;

I am using Amplify Studio and there's no place where I'm explicitly using GraphQL

Here's the error...


问:
How to extract the sign bit, the exponent and the mantissa from the fpu stack
Now I'm working with floating point numbers IEEE 754 (single precision) and I wonder if I can somehow extract the parts of the floating point value to 64 bits registers (rax, rbx, rcx for example)

I'm using nasm so I've tried this code:

```<code>section .data
        num dq -5.24324
        num2 dq 1.53453

section .bss
        ans1 resb 8

section .text
        global _start

_start:
        fld qword [num]
        fxtract
        fst ans1 ; extracting the exponent
        mov rax, [ans1]
        jmp _exit
</code>```

But I got error here:
main.asm:16:
error: invalid combination of opcode and operands
What do I do wrong?

Body:
Now I'm working with floating point numbers IEEE 754 (single precision) and I wonder if I can somehow extract the parts of the floating point value to 64 bits registers (rax, rbx, rcx for example)

I'm using nasm so I've tried this code:

section .data
        num dq -5.24324
        num2 dq 1.53453

section .bss
        ans1 resb 8

section .text
        global _start

_start:
        fld qword [num]
        fxtract
        fst ans1 ; extracting the exponent
        mov rax, [ans1]
        jmp _exit

But I got error here:
main.asm:16:
error: invalid combination of opcode and operands
What do I do wrong?


问:
How to remove container for menu in Navigation Menu
I have a footer widget that has a Navigation Menu block. I want the wrapper div for the ul to be a nav tag. How can i do this? I tried it with the 'wp_nav_menu_args' hook, but it doesn't work. Although for a header menu made with wp_nav_menu it works.

register_sidebar(array(
  'name' => 'Footer Widget Area',
  'id' => 'footer-widget',
  'description' => 'Footer Widget for blocks',
  'before_widget' => '
',
  'after_widget' => '
',
));

function my_nav_menu_args($args = '') {

  if ('footer' == $args['theme_location']) {
    if ($args['container'] == 'div') {
      $args['container'] = 'nav';
    }
  }

  return $args;
}

add_filter('wp_nav_menu_args', 'my_nav_menu_args');```


问:
Exporting Game in UnrealEngine 5
So here is my problem. I made a game in ue5 with few levels. But the problem is when i want to pack and export it, but when i do it, unreal pack and export only one level and skip the rest.

I exported every single level to check where is a problem but it wasnt possible to export whole game

Title: Exporting Game in UnrealEngine 5


问:
Notion OAuth using launchWebAuthFlow “Uncaught TypeError: Cannot read properties of null (reading 'postMessage’)"
I am trying to create a Chrome extension that uses the current Notion OAuth authentication.

When I pass the following authentication URL to launchWebAuthFlow, it will open with Identity api scope approval ui and ask me to login to notion.

https://api.notion.com/v1/oauth/authorize?owner=user&client_id={clientId}&redirect_uri={redirectUrl}&response_type=code

When logging in to notion with an email address or Apple ID, the subsequent flow also proceeds in the Identity api scope approval ui and is successful.

However, if you try to log in to Notion using Google, a new Chrome tab will open and the flow will proceed in Chrome, eventually resulting in a blank page with the following URL and failure.

https://www.notion.so/googlepopupcallback

The following error message was displayed in the console
Uncaught TypeError: Cannot read properties of null (reading 'postMessage')

I have done a lot of research, but I am at a loss as to the cause of the problem and how to fix it.
If you have any knowledge, please advise me if you can.


问:
FileReader API: Mobile Chrome is not responding
I have some JS FileReader API Script which should convert PDFs into base64 strings.
Everything works fine on Desktop Browser but in mobile Chrome and Firefox it doesn't work when I select a PDF
Mobile Chrome will not respond and I have to kill the App. Mobile Firefox console says "too much recursion".

HTML:

```<code><input type="file" accept=".pdf" id="file" name="file" required />
<br/>
<br/>
<h2>
output:
</h2>
<div id="output"></div>
</code>```

JavaScript:

```<code>function readFile(file, description, callback) {
  const fileReader = new FileReader();
  fileReader.readAsDataURL(file);
  fileReader.onload = () => {
    const fileData = fileReader.result.replace(/data:(.*)\/(.*);base64,/, "");
    callback({
      name: file.name,
      description: description,
      size: file.size,
      mimetype: file.type,
      bytes: fileData
    });
  }
}

document.getElementById("file").addEventListener('change', function(event) {

    const input = event.target;
  const result = readFile(input.files[0], input.name, function(result) {
    console.log(result);
    document.getElementById("output").innerHTML = result.bytes;
  });

});
</code>```

You can test test the whole thing here: https://jsfiddle.net/fnoq8gs3/9/

Body:
I have some JS FileReader API Script which should convert PDFs into base64 strings.
Everything works fine on Desktop Browser but in mobile Chrome and Firefox it doesn't work when I select a PDF
Mobile Chrome will not respond and I have to kill the App. Mobile Firefox console says "too much recursion".

HTML:

<input type="file" accept=".pdf" id="file" name="file" required />

output:

JavaScript:

function readFile(file, description, callback) {
  const fileReader = new FileReader();
  fileReader.readAsDataURL(file);
  fileReader.onload = () => {
    const fileData = fileReader.result.replace(/data:(.*)\/(.*);base64,/, "");
    callback({
      name: file.name,
      description: description,
      size: file.size,
      mimetype: file.type,
      bytes: fileData
    });
  }
}

document.getElementById("file").addEventListener('change', function(event) {

    const input = event.target;
  const result = readFile(input.files[0], input.name, function(result) {
    console.log(result);
    document.getElementById("output").innerHTML = result.bytes;
  });

});

You can test test the whole thing here: https://jsfiddle.net/fnoq8gs3/9/


问:
visualvm does not show profiling information but shows sampling information
I am running a simple java program and trying to study the same using visual vm .
Not trying to debug application performance. app consist of 2 simple classes and creates 2 thread , which does nothing but sleep.

```<code>public class ThreadRunExample {
        public static void main(String[] args){
            Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
            Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
            System.out.println("Starting Runnable threads");
            t1.start();
            t2.start();
            System.out.println("Runnable Threads has been started");

        }

}

public class HeavyWorkRunnable implements Runnable{

        @Override
        public void run() {
            System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
                //Get database connection, delete unused data from DB
                doDBProcessing();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
        }

        private void doDBProcessing() throws InterruptedException {
            System.out.println("Doing heavy processing - start "+Thread.currentThread().getName());
            Thread.sleep(50000);
        }

}
</code>```

Visual VM Sampler tab shows the thread sleeping correctly

However profiler tab , after clicking for CPU profiling shows nothing .

During running of the app , profiler tab is blank . Any idea

Body:
I am running a simple java program and trying to study the same using visual vm .
Not trying to debug application performance. app consist of 2 simple classes and creates 2 thread , which does nothing but sleep.

public class ThreadRunExample {
        public static void main(String[] args){
            Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
            Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
            System.out.println("Starting Runnable threads");
            t1.start();
            t2.start();
            System.out.println("Runnable Threads has been started");

        }

}

public class HeavyWorkRunnable implements Runnable{

        @Override
        public void run() {
            System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
                //Get database connection, delete unused data from DB
                doDBProcessing();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
        }

        private void doDBProcessing() throws InterruptedException {
            System.out.println("Doing heavy processing - start "+Thread.currentThread().getName());
            Thread.sleep(50000);
        }

}

Visual VM Sampler tab shows the thread sleeping correctly

However profiler tab , after clicking for CPU profiling shows nothing .

During running of the app , profiler tab is blank . Any idea


问:
Long file path in VSCode peek definition window
When I use the peek definition in VSCode, and the title of the peek window is a long file path I cannot see the filename. Is there any setting we can change so that we can show the filename/the end of the file path?


问:
Why I receive "too many documents writes sent to bulkwriter" when using the 'serverTimestamp' tag?

I wanted to test the batch use case and I'm a bit confused.
Initially I've used the Batch() method from the firestore GO SDK. When I use this method I don't receive any error.

I've seen a message on my IDE when I was using Batch():

Deprecated: The WriteBatch API has been replaced with the transaction and the bulk  writer API. For atomic transaction operations, use Transaction. For bulk read and write operations, use BulkWriter.

By reading the message I started using the BulkWriter but when I'm using it I receive an error:

too many document writes sent to bulkwriter

When I remove the serverTimestamp there is no error.

The code:

// Storer persists tickets in Firestore.
type Storer struct {
    client *firestore.Client
}

// createTicket contains the data needed to create a Ticket in Firestore.
type createTicket struct {
        Title       string    `firestore:"title"`
        Price       float64   `firestore:"price"`
        DateCreated time.Time `firestore:"dateCreated,serverTimestamp"`
    }

func (s *Storer) CreateTicket(ctx context.Context, ticket tixer.Ticket) error {
    bulk := s.client.BulkWriter(ctx)

    ticketRef := s.client.Collection("tickets").Doc(ticket.ID.String())
    _, err := bulk.Create(ticketRef, createTicket{
        Title: ticket.Title,
        Price: ticket.Price,
    })
    if err != nil {
        return err
    }

    bulk.Flush()

    return nil
}
```