问:
How to make a progress bar for an Electron app by using child_process on a Python Script?

The problem

I am creating an Electron-React frontend for my Python script.

Electron and Python communicate via Node.js child_process module, using the function spawn to call my Python script.

The script does the following task:

Gets path to a folder, which contains 15 pdf files.

Loads 1 pdf file at a time.

Skims through it to find the first word of the 5th page.

Saves the result in a list.

Continues until all pdf files have been read.

As you can see, this takes some time to process this script.

What I want to do: Once the process is called from Electron, I want the progress bar to appear, indicating how many pdf files are processed out of the 15 given. For example: 1/15 done, 2/15 done, and etc.

I tried googling the answer but after a week I'm at my wits end. I would very much appreciate any help I could get.

Disclaimer: I know of other good packages like Python Eel which does the job (sort of, in a hackish way). But I really want it to work with CLI.

The setup

I used Electron React Boilerplate for my purposes.

For simplicity I used a dummy function for python:

assets/python/main.py

import sys
import time

# Track the progress
progress = 0

def doStuff():
  # Access the global variable
  global progress

  # Simulate time taken to do stuff. Set at 30 seconds per iteration.
  for i in range(15):
    progress += 1
    time.sleep(30)

  # The result
  return "It is done!"

# Print is used to get the result for stdout.
print(doStuff())

```
<p>src/main/main.ts</p>
<pre class="lang-js prettyprint-override"><code>import { spawn } from 'child_process';
import path from 'path';
import { app, BrowserWindow, ipcMain, webContents } from 'electron';

...

let mainWindow: BrowserWindow | null = null;

...

app
  .whenReady()
  .then(() => {
    ipcMain.handle('readPdfs', async (event, arg) => {

      // Spawn a python instance
      const python = spawn('python', [
        path.join(__dirname, '..', '..', 'assets', 'python', 'main.py')
      ]);

      // Get the result and pass it on to the frontend
      python.stdout.on('data', (data) => {
        const result = data.toString('utf8');
        mainWindow.webContents.send('output', result);
      });
    });

...

</code>```

src/main/preload.ts

import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

...

let mainWindow: BrowserWindow | null = null;

...

contextBridge.exposeInMainWorld('electron', {
  ...
  // Just sending a command forward and getting a response.
  readPdfs: async () => ipcRenderer.invoke('readPdfs'),
  readPdfsOutput: (callback: any) => ipcRenderer.on('output', callback),
});

```
<p>src/renderer/App.tsx</p>
<pre class="lang-js prettyprint-override"><code>const Hello = () => {
  const [text, setText] = useState('');

  const handleReadPdfs = async (): Promise<void> => {
    await window.electron.readPdfs();
    await window.electron.output((event: any, response: string) => {
      setText(response);
    });
  };
</code>```

The question

What I have set up works. I manage to get the "It is done!" message all right. The problem is I want to get the value progress from main.py every time it increments, while the process is busy reading the pdfs.

Is there a way to get that value from the python script using child_process without interrupting a time consuming process?

Body:
The problem

I am creating an Electron-React frontend for my Python script.

Electron and Python communicate via Node.js child_process module, using the function spawn to call my Python script.

The script does the following task:

Gets path to a folder, which contains 15 pdf files.

Loads 1 pdf file at a time.

Skims through it to find the first word of the 5th page.

Saves the result in a list.

Continues until all pdf files have been read.

As you can see, this takes some time to process this script.

What I want to do: Once the process is called from Electron, I want the progress bar to appear, indicating how many pdf files are processed out of the 15 given. For example: 1/15 done, 2/15 done, and etc.

I tried googling the answer but after a week I'm at my wits end. I would very much appreciate any help I could get.

Disclaimer: I know of other good packages like Python Eel which does the job (sort of, in a hackish way). But I really want it to work with CLI.

The setup

I used Electron React Boilerplate for my purposes.

For simplicity I used a dummy function for python:

assets/python/main.py

import sys
import time

# Track the progress
progress = 0

def doStuff():
  # Access the global variable
  global progress

  # Simulate time taken to do stuff. Set at 30 seconds per iteration.
  for i in range(15):
    progress += 1
    time.sleep(30)

  # The result
  return "It is done!"

# Print is used to get the result for stdout.
print(doStuff())

src/main/main.ts

import { spawn } from 'child_process';
import path from 'path';
import { app, BrowserWindow, ipcMain, webContents } from 'electron';

...

let mainWindow: BrowserWindow | null = null;

...

app
  .whenReady()
  .then(() => {
    ipcMain.handle('readPdfs', async (event, arg) => {

      // Spawn a python instance
      const python = spawn('python', [
        path.join(__dirname, '..', '..', 'assets', 'python', 'main.py')
      ]);

      // Get the result and pass it on to the frontend
      python.stdout.on('data', (data) => {
        const result = data.toString('utf8');
        mainWindow.webContents.send('output', result);
      });
    });

...

src/main/preload.ts

import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

...

let mainWindow: BrowserWindow | null = null;

...

contextBridge.exposeInMainWorld('electron', {
  ...
  // Just sending a command forward and getting a response.
  readPdfs: async () => ipcRenderer.invoke('readPdfs'),
  readPdfsOutput: (callback: any) => ipcRenderer.on('output', callback),
});

src/renderer/App.tsx

const Hello = () => {
  const [text, setText] = useState('');

  const handleReadPdfs = async (): Promise<void> => {
    await window.electron.readPdfs();
    await window.electron.output((event: any, response: string) => {
      setText(response);
    });
  };

The question

What I have set up works. I manage to get the "It is done!" message all right. The problem is I want to get the value progress from main.py every time it increments, while the process is busy reading the pdfs.

Is there a way to get that value from the python script using child_process without interrupting a time consuming process?


来源: stackexchange

问:
Typo3 10.4 specific actions on pages
I haven't found anyone asking this question yet although it seems like this should be a more commonly asked question.

Is there a way of selecting which action a plugin should use depending on the page?
If I go to example.com/news then the news plugin should use the listAction but if I go to example.com/clear the news plugin should be using the deleteAllAction. Is there a way to accomplish this? Or rather is there an easier way than using extbase routeEnhancers?
I guess the easiest way would be to register a new plugin with a different action but the same base.

ContentLicense: CC BY-SA 4.0

Title: Typo3 10.4 specific actions on pages


问:
Pop notification in airplane mode
Is there any way to show the notification from alarm manager while the phone is in airplane mode?

I'm working on an app that uses the background service to display notifications and is testing the ability to display notifications in airplane mode. Is it possible?

Title: Pop notification in airplane mode


问:
Different results when generating PDF417
I am using pdf417gen to generate an AAMVA barcode. The generated barcode is perfectly readable and easy to read. But if I enter the original data and compare my barcode with the original, visually, they are different, but decoding gives the same result.

My Code

```<code>from pdf417gen import encode, render_image

# Some data to encode

text = '@\n\x1E\rANSI 636015080001DL00310290DLDCAC\nDDAF\nDDB10102016\nDCBA\nDCDNONE\nDBA04062025\nDCSPERELLA\nDDEN\nDACCODY\nDDFN\nDADGLENN\nDDGN\nDBD04192019\nDBB04061995\nDBC1\nDAYGRN\nDAZBLN\nDAU064 IN\nDAW125\nDCLW\nDAG6615 STICHTER AVE               \nDAIDALLAS\nDAJTX\nDAK752300000  \nDCK34509203  20190419\nDAQ34509203\nDCF00619980045119245470\nDCGUSA\n\r'

codes = encode(text, columns=15, security_level=3)

# Generate barcode as image
image = render_image(codes, scale=2, ratio=2, padding=0)  # Pillow Image object
image.save('barcode.jpg')
</code>```

My barcode
enter image description here

Original barcode
enter image description here

Barcodes differ in the number of lines. They also have different left and right columns, which are responsible for the barcode data.
If you change the protection level and add spaces to the end of the data, you can get approximately the same result. But it's still not a complete repeat.
I think the original uses a fixed value of rows and columns, if there are not enough characters to fill, they are replaced with blanks or service characters, but there is no such information in documents and on the Internet.

I don't know what I'm missing, for a complete repetition of the original. I would be very grateful for any help

Body:
I am using pdf417gen to generate an AAMVA barcode. The generated barcode is perfectly readable and easy to read. But if I enter the original data and compare my barcode with the original, visually, they are different, but decoding gives the same result.

My Code

from pdf417gen import encode, render_image

# Some data to encode

text = '@\n\x1E\rANSI 636015080001DL00310290DLDCAC\nDDAF\nDDB10102016\nDCBA\nDCDNONE\nDBA04062025\nDCSPERELLA\nDDEN\nDACCODY\nDDFN\nDADGLENN\nDDGN\nDBD04192019\nDBB04061995\nDBC1\nDAYGRN\nDAZBLN\nDAU064 IN\nDAW125\nDCLW\nDAG6615 STICHTER AVE               \nDAIDALLAS\nDAJTX\nDAK752300000  \nDCK34509203  20190419\nDAQ34509203\nDCF00619980045119245470\nDCGUSA\n\r'

codes = encode(text, columns=15, security_level=3)

# Generate barcode as image
image = render_image(codes, scale=2, ratio=2, padding=0)  # Pillow Image object
image.save('barcode.jpg')

My barcode
enter image description here

Original barcode
enter image description here

Barcodes differ in the number of lines. They also have different left and right columns, which are responsible for the barcode data.
If you change the protection level and add spaces to the end of the data, you can get approximately the same result. But it's still not a complete repeat.
I think the original uses a fixed value of rows and columns, if there are not enough characters to fill, they are replaced with blanks or service characters, but there is no such information in documents and on the Internet.

I don't know what I'm missing, for a complete repetition of the original. I would be very grateful for any help


问:
How to equate a value in encoded URL?
We have multiple URL's, wanted to compare

```<code>   https://securepubads.g.doubleclick.net/gampad/ads?ssp%3D0
</code>```

if you can see in below URL ssp=0 can be present anywhere. I want a wildcard code that can be replace ssp%3D0.

```<code> https://securepubads.g.doubleclick.net/gampad/ads?pvsid%3D326202298883096&correlator%3D3063969260360993&output%3Dldjh&gdfp_req%3D0&vrg%3D2022030600&ptt%3D08&impl%3Dfifs&iu_parts%3D3302333,profpromo,medscpnewsdesktop&enc_prev_ius%3D/0/0/2,/0/0/2,/0/0/2,/0/0/2,/0/0/2,/0/0/2,/0/0/2&prev_iu_szs%3D320x90|828x90|980x90|980x290,320x90|300x290|300x600|300x390,320x90|0x2,0x2,320x90|2x9,320x90|2x9,320x90|828x90|828x90&fluid%3Dheight,height,height,0,height,height,height&ifi%3D0&adks%3D838338968,2333289989,3296303628,0699999960,3982038306,3982003000,883988630&sfv%3D0-0-38&ecs%3D20220323&fsapi%3Dfalse&prev_scp%3Dpos%3D003&ad_slot%3Dads-pos-003&mnetPageID%3D9&mnetCC%3DIN&mnetCV%3D0&mnetUGD%3D3&mnetCID%3D8CU9I96G3&hb_abt%3Dhb&mnetDNB%3D0|pos%3D022&ad_slot%3Dads-pos-022&mnetPageID%3D3&mnetCC%3DIN&mnetCV%3D0&mnetUGD%3D3&mnetCID%3D8CU9I96G3&hb_abt%3Dhb&mnetDNB%3D0|pos%3D900&ad_slot%3Dads-pos-900|pos%3D009&ad_slot%3Dads-pos-009|pos%3D622&ad_slot%3Dads-pos-622|pos%3D822&ad_slot%3Dads-pos-822|pos%3D030&ad_slot%3Dads-pos-030&mnetPageID%3D0&mnetCC%3DIN&mnetCV%3D0&mnetUGD%3D3&mnetCID%3D8CU9I96G3&hb_abt%3Dhb&mnetDNB%3D0&eri%3D0&cust_params%3Dlif%3D0&val%3D0&vit%3D&pbs%3D&st%3D0&tar%3D0&actid%3D0&occ%3D0&sa%3D0&tc%3D0&ct%3D0&pb%3D0&usp%3D0&pf%3D0&masid%3D0&gd%3D0&pbp%3D&ssp%3D08&ac%3D0&art%3D0&as%3D0&cg%3D0&ssp%3D0&scg%3D0&ck%3D0&pub%3D0&pc%3Dhp&auth%3D0&spon%3D08&env%3D0&envp%3Dprod&ep%3D0&
</code>```

Sorry for bit confused question

Title: How to equate a value in encoded URL?

Body:
We have multiple URL's, wanted to compare

   https://securepubads.g.doubleclick.net/gampad/ads?ssp%3D0

if you can see in below URL ssp=0 can be present anywhere. I want a wildcard code that can be replace ssp%3D0.

 https://securepubads.g.doubleclick.net/gampad/ads?pvsid%3D326202298883096&correlator%3D3063969260360993&output%3Dldjh&gdfp_req%3D0&vrg%3D2022030600&ptt%3D08&impl%3Dfifs&iu_parts%3D3302333,profpromo,medscpnewsdesktop&enc_prev_ius%3D/0/0/2,/0/0/2,/0/0/2,/0/0/2,/0/0/2,/0/0/2,/0/0/2&prev_iu_szs%3D320x90|828x90|980x90|980x290,320x90|300x290|300x600|300x390,320x90|0x2,0x2,320x90|2x9,320x90|2x9,320x90|828x90|828x90&fluid%3Dheight,height,height,0,height,height,height&ifi%3D0&adks%3D838338968,2333289989,3296303628,0699999960,3982038306,3982003000,883988630&sfv%3D0-0-38&ecs%3D20220323&fsapi%3Dfalse&prev_scp%3Dpos%3D003&ad_slot%3Dads-pos-003&mnetPageID%3D9&mnetCC%3DIN&mnetCV%3D0&mnetUGD%3D3&mnetCID%3D8CU9I96G3&hb_abt%3Dhb&mnetDNB%3D0|pos%3D022&ad_slot%3Dads-pos-022&mnetPageID%3D3&mnetCC%3DIN&mnetCV%3D0&mnetUGD%3D3&mnetCID%3D8CU9I96G3&hb_abt%3Dhb&mnetDNB%3D0|pos%3D900&ad_slot%3Dads-pos-900|pos%3D009&ad_slot%3Dads-pos-009|pos%3D622&ad_slot%3Dads-pos-622|pos%3D822&ad_slot%3Dads-pos-822|pos%3D030&ad_slot%3Dads-pos-030&mnetPageID%3D0&mnetCC%3DIN&mnetCV%3D0&mnetUGD%3D3&mnetCID%3D8CU9I96G3&hb_abt%3Dhb&mnetDNB%3D0&eri%3D0&cust_params%3Dlif%3D0&val%3D0&vit%3D&pbs%3D&st%3D0&tar%3D0&actid%3D0&occ%3D0&sa%3D0&tc%3D0&ct%3D0&pb%3D0&usp%3D0&pf%3D0&masid%3D0&gd%3D0&pbp%3D&ssp%3D08&ac%3D0&art%3D0&as%3D0&cg%3D0&ssp%3D0&scg%3D0&ck%3D0&pub%3D0&pc%3Dhp&auth%3D0&spon%3D08&env%3D0&envp%3Dprod&ep%3D0&

Sorry for bit confused question


问:
Cannot install CocoaPod which includes iOS framework with 'LibTorch-Lite' CocoaPod dependency

MyLibrary: CocoaPod that I am trying to install and run but failing. (https://github.com/steve-ham/MyLibrary) (Includes below 'MyFramework')

MyFramework: iOS framework with 'LibTorch-Lite' CocoaPod dependency. (https://github.com/steve-ham/MyFramework)

When I run 'MyLibrary App' (https://github.com/steve-ham/MyLibrary) I get below error:

```<code>libc++abi: terminating with uncaught exception of type torch::jit::ErrorReport:
Unknown custom class type quantized.Conv2dPackedParamsBase. Please ensure it is registered.:
quantized::conv1d(Tensor qx, __torch__.torch.classes.quantized.Conv2dPackedParamsBase packed_weight, float output_scale, int output_zero_point) -> Tensor
                                                               ~~~~~~~~~~~~~~~~~~~~~~ <--- HERE

terminating with uncaught exception of type torch::jit::ErrorReport:
Unknown custom class type quantized.Conv2dPackedParamsBase. Please ensure it is registered.:
quantized::conv1d(Tensor qx, __torch__.torch.classes.quantized.Conv2dPackedParamsBase packed_weight, float output_scale, int output_zero_point) -> Tensor
                                                               ~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
</code>```

I used below code to create MyFramework.xcframework from MyFramework project (https://github.com/steve-ham/MyFramework)

```<code>xcodebuild archive -workspace MyFramework.xcworkspace \
  -scheme MyFramework \
  -sdk iphoneos \
  -archivePath "./MyFramework.xcarchive" \
  BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
  SKIP_INSTALL=NO

xcodebuild archive -workspace MyFramework.xcworkspace \
  -scheme MyFramework \
  -sdk iphonesimulator \
  -archivePath "./MyFramework_sim.xcarchive" \
  BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
  SKIP_INSTALL=NO \
  EXCLUDED_ARCHS=arm64

xcodebuild -create-xcframework \
    -framework "MyFramework.xcarchive/Products/Library/Frameworks/MyFramework.framework" \
    -framework "MyFramework_sim.xcarchive/Products/Library/Frameworks/MyFramework.framework" \
    -output MyFramework.xcframework
</code>```

There's no error like this when I do this with other CocoaPod projects instead of 'LibTorch-Lite'. Is it merely impossible to wrap 'LibTorch-Lite' into .xcframework and deploy it like above wrapping into CocoaPod? Thanks.

Body:
MyLibrary: CocoaPod that I am trying to install and run but failing. (https://github.com/steve-ham/MyLibrary) (Includes below 'MyFramework')

MyFramework: iOS framework with 'LibTorch-Lite' CocoaPod dependency. (https://github.com/steve-ham/MyFramework)

When I run 'MyLibrary App' (https://github.com/steve-ham/MyLibrary) I get below error:

libc++abi: terminating with uncaught exception of type torch::jit::ErrorReport:
Unknown custom class type quantized.Conv2dPackedParamsBase. Please ensure it is registered.:
quantized::conv1d(Tensor qx, __torch__.torch.classes.quantized.Conv2dPackedParamsBase packed_weight, float output_scale, int output_zero_point) -> Tensor
                                                               ~~~~~~~~~~~~~~~~~~~~~~ <--- HERE

terminating with uncaught exception of type torch::jit::ErrorReport:
Unknown custom class type quantized.Conv2dPackedParamsBase. Please ensure it is registered.:
quantized::conv1d(Tensor qx, __torch__.torch.classes.quantized.Conv2dPackedParamsBase packed_weight, float output_scale, int output_zero_point) -> Tensor
                                                               ~~~~~~~~~~~~~~~~~~~~~~ <--- HERE

I used below code to create MyFramework.xcframework from MyFramework project (https://github.com/steve-ham/MyFramework)

xcodebuild archive -workspace MyFramework.xcworkspace \
  -scheme MyFramework \
  -sdk iphoneos \
  -archivePath "./MyFramework.xcarchive" \
  BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
  SKIP_INSTALL=NO

xcodebuild archive -workspace MyFramework.xcworkspace \
  -scheme MyFramework \
  -sdk iphonesimulator \
  -archivePath "./MyFramework_sim.xcarchive" \
  BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
  SKIP_INSTALL=NO \
  EXCLUDED_ARCHS=arm64

xcodebuild -create-xcframework \
    -framework "MyFramework.xcarchive/Products/Library/Frameworks/MyFramework.framework" \
    -framework "MyFramework_sim.xcarchive/Products/Library/Frameworks/MyFramework.framework" \
    -output MyFramework.xcframework

There's no error like this when I do this with other CocoaPod projects instead of 'LibTorch-Lite'. Is it merely impossible to wrap 'LibTorch-Lite' into .xcframework and deploy it like above wrapping into CocoaPod? Thanks.


问:
Is there a way to open ios shortcuts app from flutter app?
I have used  flutter_siri_suggestions  package to to add a user activity.

after I add the activity I can add shortcut in the shortcut app to siri.

But I want to add the shortcut programmatically, when click 'Hey Siri, open my app' button I want to open the shortcut app and fill the when I say: and Do: field to be filled with data from the flutter app.

I tried to find a way but I couldn't find a way to do this.

Is there a any way to open the shortcuts app from flutter programmatically and add a shortcut to siri?flutter_image and shortcuts_image


问:
How to install geos_c on Amazon Linux when it is not appearing in EPEL?
I'm running some python code on EC2 that uses shape files and has a dependency on the geos_c library. It's raising a Could not find lib geos_c or load any of its variants error.

I've applied updates and followed the steps from https://libgeos.org/usage/install/#amazon-linux, namely:

```<code># Apply updates
sudo yum update -y

# Install geos
sudo yum install -y amazon-linux-extras
sudo amazon-linux-extras enable epel
sudo yum search geos
sudo yum install geos geos-devel
</code>```

Unfortunately this returns Warning: No matches found for: geos, so it looks like this package is not currently available in the EPEL version in Amazon Linux.

This is a vanilla instance of Amazon Linux using Amazon Linux 2 AMI (HVM) - Kernel 5.10 with 64-bit (Arm) architecture.

What's the best way to install the geos library?

Body:
I'm running some python code on EC2 that uses shape files and has a dependency on the geos_c library. It's raising a Could not find lib geos_c or load any of its variants error.

I've applied updates and followed the steps from https://libgeos.org/usage/install/#amazon-linux, namely:

# Apply updates
sudo yum update -y

# Install geos
sudo yum install -y amazon-linux-extras
sudo amazon-linux-extras enable epel
sudo yum search geos
sudo yum install geos geos-devel

Unfortunately this returns Warning: No matches found for: geos, so it looks like this package is not currently available in the EPEL version in Amazon Linux.

This is a vanilla instance of Amazon Linux using Amazon Linux 2 AMI (HVM) - Kernel 5.10 with 64-bit (Arm) architecture.

What's the best way to install the geos library?


问:
Plotting a determinant of a 2by2 matrix with respect to independent variable in matlab
Th`anks in advance. I'm plotting a figure in Matlab but
I'm facing difficulty, my code is:

```<code>clear
clc
n2=1.45:1.5;
x=0:100;k2z=6.28.*n2./x;a=0.01;u1=1;u2=1;k1z=6.28./x;
for j=1:numel(k1z)
  for i=1:numel(k2z)
        M12=1./2*[1+((u2./u1)*(k1z(j))./(k2z(i))),1-((u2./u1)*(k1z(j))./(k2z(i))) ; 1-((u2./u1)*(k1z(j))./(k2z(i))),1+((u2./u1)*(k1z(j))./(k2z(i)))];
Ms=det(M12);

  end
end
plot(x,Ms)
</code>```

I'm expecting an array of Ms and its plot vs x.

Body:
Th`anks in advance. I'm plotting a figure in Matlab but
I'm facing difficulty, my code is:

clear
clc
n2=1.45:1.5;
x=0:100;k2z=6.28.*n2./x;a=0.01;u1=1;u2=1;k1z=6.28./x;
for j=1:numel(k1z)
  for i=1:numel(k2z)
        M12=1./2*[1+((u2./u1)*(k1z(j))./(k2z(i))),1-((u2./u1)*(k1z(j))./(k2z(i))) ; 1-((u2./u1)*(k1z(j))./(k2z(i))),1+((u2./u1)*(k1z(j))./(k2z(i)))];
Ms=det(M12);

  end
end
plot(x,Ms)

I'm expecting an array of Ms and its plot vs x.


问:
ReactJS - Sending data from Main Form and Dynamic Form (react-modal) with Formik
I have a problem for send data on multiple form.

I have a main form and modals form.

For main form I want to send an Email, and for modals form I want to send comment with dynamic data.

My big problem is for Modals Form, I have some dynamic modals form and I want to sent together with the main form.

My expected resutl is:

```<code>{
  "comment": {
    "data_1": {
        "value": "Comment 1"
    },
    "data_2": {
        "value": "Comment 2"
    },
    "data_3": {
        "value": "Comment 3"
    }
  },
  "email": "test@test.com"
}
</code>```

Here's my script.

https://codesandbox.io/s/question-for-sending-multiple-form-97tt74

Please help if you guys have better solution.

Many Thanks

*notes: I use formik and react-modals.

Body:
I have a problem for send data on multiple form.

I have a main form and modals form.

For main form I want to send an Email, and for modals form I want to send comment with dynamic data.

My big problem is for Modals Form, I have some dynamic modals form and I want to sent together with the main form.

My expected resutl is:

{
  "comment": {
    "data_1": {
        "value": "Comment 1"
    },
    "data_2": {
        "value": "Comment 2"
    },
    "data_3": {
        "value": "Comment 3"
    }
  },
  "email": "test@test.com"
}

Here's my script.

https://codesandbox.io/s/question-for-sending-multiple-form-97tt74

Please help if you guys have better solution.

Many Thanks

*notes: I use formik and react-modals.


问:
How to configure SSH options on CLION for remote development? I've configured a SSH login with proxyjumps using id_rsa private key
I want to develop a C++ project remotely. I've configured a SSH login with proxyjumps using id_rsa private key.
The SSH config file:

```<code>Host jump1
        User user1
        Port port1
        IdentityFile ~/.ssh/id_rsa
        HostName aa.bb.cc.dd
Host jump2
        User user2
        Port port2
        HostName ee.ff.gg.hh
        IdentityFile ~/.ssh/id_rsa
        ProxyJump jump1
Host dest
    User dest_user
    HostName ii.jj.kk.ll
    ProxyJump jump2
</code>```

And I can use command "ssh real" to log in to the remote machine dest in cmd successfully, but I don't know how to configure options on CLION(version 2022.3). The SSH configurations panel looks like this:

Desperately need help!! Thanks! Love from earth.

Body:
I want to develop a C++ project remotely. I've configured a SSH login with proxyjumps using id_rsa private key.
The SSH config file:

Host jump1
        User user1
        Port port1
        IdentityFile ~/.ssh/id_rsa
        HostName aa.bb.cc.dd
Host jump2
        User user2
        Port port2
        HostName ee.ff.gg.hh
        IdentityFile ~/.ssh/id_rsa
        ProxyJump jump1
Host dest
    User dest_user
    HostName ii.jj.kk.ll
    ProxyJump jump2

And I can use command "ssh real" to log in to the remote machine dest in cmd successfully, but I don't know how to configure options on CLION(version 2022.3). The SSH configurations panel looks like this:

Desperately need help!! Thanks! Love from earth.


问:
How to extract nupkg package which was downloaded by release pipeline into target machines from azure artifacts
I'm trying to extract the nupkg package which was downloaded into target machine by azure release pipeline from azure artifacts. i tried using nuget cli commands but i'm getting errors like file was not found errors.</p>


问:
NoMethodError - undefined method - Trying to register new products - rails 7
I'm trying to build a screen to register new products, but i keep getting this error:
Image of the error

routes:

```<code>Rails.application.routes.draw do

    post "despensa", to:"despensa#create"
    get "despensa/new", to: "despensa#new"
    root to: "despensa#index"
end
</code>```

despensa_controller.rb:

```<code>class DespensaController < ApplicationController

    def index
        @produtos = Produto.order :nome
        @produto_menor_quantidade = Produto.order(:quantidade).limit 1
    end

    def create
       produto = params.require(:produto).permit(:nome, :quantidade, :unidade_de_medida)
       Produto.create produto
    end
end
</code>```

new:

```<code><html>
    <body>
        <%= form_for Produto.new do |form|%>
            Nome <input type="text" name="nome"><br/>
            Quantidade<input type="number" step="0.01" name="quantidade"><br/>
            Unidade de medida <input type="text" name="unidade_de_medida"><br/>

            <button type="submit">Adicionar produto</button>
        <% end %>
    </body>
</html>
</code>```

I really don't know what is causing it. It was suppose to open a form page to register the new products. please help

Body:
I'm trying to build a screen to register new products, but i keep getting this error:
Image of the error

routes:

Rails.application.routes.draw do

    post "despensa", to:"despensa#create"
    get "despensa/new", to: "despensa#new"
    root to: "despensa#index"
end

despensa_controller.rb:

class DespensaController < ApplicationController

    def index
        @produtos = Produto.order :nome
        @produto_menor_quantidade = Produto.order(:quantidade).limit 1
    end

    def create
       produto = params.require(:produto).permit(:nome, :quantidade, :unidade_de_medida)
       Produto.create produto
    end
end

new:

        <%= form_for Produto.new do |form|%>
            Nome <input type="text" name="nome">

            Quantidade<input type="number" step="0.01" name="quantidade">

            Unidade de medida <input type="text" name="unidade_de_medida">

            <button type="submit">Adicionar produto</button>
        <% end %>

I really don't know what is causing it. It was suppose to open a form page to register the new products. please help


问:
Mongoose graphLookup
I am Trying to Implement Mongoose GraphlookUp in Node JS. but i am not able to find the example code. below code is Copied from mongoose documentation but its not working.

```<code>aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites
</code>```

Here is My Code Can You please help me with exact syntax of using graphlook in mongoose using node js

```<code>const UserTree = require('./model/usertree')
const trees= await  UserTree.aggregate.graphLookup({
                    from: 'user_tree',
                    startWith: '$userpid',
                    connectFromField: 'userpid',
                    connectToField: 'userid',
                    as: 'prerequisites',
                    maxDepth: 3 })
</code>```

Sample Document

```<code>  {userid: "MongoDB", userpid: "Databases" },
   {userid: "dbm", userpid: "Databases" },
   {userid: "Databases", userpid: "Programming" },
   {userid: "Languages", userpid: "Programming" },
   {userid: "Programming", userpid: "Books" },
   {userid: "Books", userpid: null }
</code>```

Title: Mongoose graphLookup

Body:
I am Trying to Implement Mongoose GraphlookUp in Node JS. but i am not able to find the example code. below code is Copied from mongoose documentation but its not working.

aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites

Here is My Code Can You please help me with exact syntax of using graphlook in mongoose using node js

const UserTree = require('./model/usertree')
const trees= await  UserTree.aggregate.graphLookup({
                    from: 'user_tree',
                    startWith: '$userpid',
                    connectFromField: 'userpid',
                    connectToField: 'userid',
                    as: 'prerequisites',
                    maxDepth: 3 })

Sample Document

  {userid: "MongoDB", userpid: "Databases" },
   {userid: "dbm", userpid: "Databases" },
   {userid: "Databases", userpid: "Programming" },
   {userid: "Languages", userpid: "Programming" },
   {userid: "Programming", userpid: "Books" },
   {userid: "Books", userpid: null }


问:
android slideshow view with wipe gesture and pinch zoom
How to implement android slide show effect for displaying set of images (one at time) and sliding between them using gestures (wipe left/right)?
How to implement zooming of image using pinch gesture?
Are there any examples?

Thanks

ContentLicense: CC BY-SA 3.0


问:
Why capture node screenshot not capturing IFrame images correctly?
I am trying to get the images with capture node screenshot option in chrome. It's working on all elements and images except iframe images. For example go to this link ( https://www.w3schools.com/html/tryit.asp?filename=tryhtml_iframe_height_width_css ) inspect the page and right click on this (
This page is displayed in an iframe
) tag then select Capture node screenshot you will not get actual image.

I have also tried with element capture screenshot extensions  which are available in chrome store but non of them worked on iframe. Please any one tell how to capture of element or image in iframe properly with extensions or any JavaScript library like html2canvas?


问:
Cannot match to tuple including function pointers
If I try to compile this code:

fn main() {
    let a = 0;
    let (fun, i) = match a {
        0 => (fun1, 1), _ => (fun2, 2),
    };
    fun(i);
}

fn fun1(a: i32) -> i32 {
    a
}

fn fun2(a: i32) -> i32 {
    a
}
```
<p>I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>error[E0308]: `match` arms have incompatible types
 --> src/main.rs:4:30
  |
3 |       let (fun, i) = match a {
  |  ____________________-
4 | |         0 => (fun1, 1), _ => (fun2, 2),
  | |              ---------       ^^^^^^^^^ expected fn item, found a different fn item
  | |              |
  | |              this is found to be of type `(fn(i32) -> i32 {fun1}, {integer})`
5 | |     };
  | |_____- `match` arms have incompatible types
  |
  = note: expected tuple `(fn(_) -> _ {fun1}, {integer})`
             found tuple `(fn(_) -> _ {fun2}, {integer})`

For more information about this error, try `rustc --explain E0308`.
</code>```

However, this functionally equivalent but less concise version:

fn main() {
    let a = 0;
    let fun = match a {
        0 => fun1, _ => fun2,
    };
    let i = match a {
        0 => 1, _ => 2,
    };
    fun(i);
}

fn fun1(a: i32) -> i32 {
    a
}

fn fun2(a: i32) -> i32 {
    a
}
```

Compiles and runs fine.

Why is this? Is it possible to make the first version work with some type hint, or somehow else?

Body:
If I try to compile this code:

fn main() {
    let a = 0;
    let (fun, i) = match a {
        0 => (fun1, 1), _ => (fun2, 2),
    };
    fun(i);
}

fn fun1(a: i32) -> i32 {
    a
}

fn fun2(a: i32) -> i32 {
    a
}

I get the following error:

error[E0308]: `match` arms have incompatible types
 --> src/main.rs:4:30
  |
3 |       let (fun, i) = match a {
  |  ____________________-
4 | |         0 => (fun1, 1), _ => (fun2, 2),
  | |              ---------       ^^^^^^^^^ expected fn item, found a different fn item
  | |              |
  | |              this is found to be of type `(fn(i32) -> i32 {fun1}, {integer})`
5 | |     };
  | |_____- `match` arms have incompatible types
  |
  = note: expected tuple `(fn(_) -> _ {fun1}, {integer})`
             found tuple `(fn(_) -> _ {fun2}, {integer})`

For more information about this error, try `rustc --explain E0308`.

However, this functionally equivalent but less concise version:

fn main() {
    let a = 0;
    let fun = match a {
        0 => fun1, _ => fun2,
    };
    let i = match a {
        0 => 1, _ => 2,
    };
    fun(i);
}

fn fun1(a: i32) -> i32 {
    a
}

fn fun2(a: i32) -> i32 {
    a
}

Compiles and runs fine.

Why is this? Is it possible to make the first version work with some type hint, or somehow else?


问:
Is there anyway to debug "go test -msan" command?
I've recently looking for any way to debug "go test -msan".
I am facing with a core-dump (Segmentation Fault) when pipeline executing this command and I need more detailed background informations about what is going on.
So, I need to a way to debug "go test" with included "-msan"(MemorySanitizer) option.

Thanks in advance!

I had a quick search on google about this subject but could not find any thing useful.


问:
GPU acceleration using ffmpeg commands
I'm using ffmpeg for complex filters like cutting video, merging two or more videos, slow down, blur video, speed up video, converting from HEVC to h264. However, I want to parallelize/speed up by using hwaccel for all these operations. I had rebuild ffmpeg source and enabled --enable-libnpp, --enable-cuda-nvcc but none of the operation is working when I use hwaccel.

Which filter complex operations can I use GPU with hwaccel?. I tried using it for filter complex operations like below but did not work.

```<code>ffmpeg -y -vsync 0 -hwaccel cuda -hwaccel_output_format cuda -i inputfile.mp4 -vf "boxblur=10:enable='between(t,2,8)'" -codec:a copy outputfile.mp4
</code>```

Regards,
mgba

I tried below command but failed

```<code>ffmpeg -y -vsync 0 -hwaccel cuda -hwaccel_output_format cuda -i inputfile.mp4 -vf "boxblur=10:enable='between(t,2,8)'" -codec:a copy outputfile.mp4
</code>```

Title: GPU acceleration using ffmpeg commands

Body:
I'm using ffmpeg for complex filters like cutting video, merging two or more videos, slow down, blur video, speed up video, converting from HEVC to h264. However, I want to parallelize/speed up by using hwaccel for all these operations. I had rebuild ffmpeg source and enabled --enable-libnpp, --enable-cuda-nvcc but none of the operation is working when I use hwaccel.

Which filter complex operations can I use GPU with hwaccel?. I tried using it for filter complex operations like below but did not work.

ffmpeg -y -vsync 0 -hwaccel cuda -hwaccel_output_format cuda -i inputfile.mp4 -vf "boxblur=10:enable='between(t,2,8)'" -codec:a copy outputfile.mp4

Regards,
mgba

I tried below command but failed

ffmpeg -y -vsync 0 -hwaccel cuda -hwaccel_output_format cuda -i inputfile.mp4 -vf "boxblur=10:enable='between(t,2,8)'" -codec:a copy outputfile.mp4


问:
Vowpal wabbit - Model's output distribution (for action set) is same for all epsilon values [0.2, 0.5, 0.9] when using --cb_explore -- epsilon <val>
I am trying to run epsilon-greedy contextual bandit for my problem.

```<code>Contextual_model = vowpalwabbit.Workspace("--cb_explore 29 --epsilon 0.2 ")
</code>```

I am able to train the model successfully.

But during inference on test set. I get the output distribution to be same for different epsilon models.

Is that an expected behavior? Or Is my model not learning anything/bug?

How can one debug such models?

I tried different epsilon values and re-trained.
I have checked my input format which is accordance with the req.
I am able to successfully train and infer.

Body:
I am trying to run epsilon-greedy contextual bandit for my problem.

Contextual_model = vowpalwabbit.Workspace("--cb_explore 29 --epsilon 0.2 ")

I am able to train the model successfully.

But during inference on test set. I get the output distribution to be same for different epsilon models.

Is that an expected behavior? Or Is my model not learning anything/bug?

How can one debug such models?

I tried different epsilon values and re-trained.
I have checked my input format which is accordance with the req.
I am able to successfully train and infer.


问:
Python how to run and code another terminal (linux)
I am wanting a good script for sftp and i am trying to code but when i entered sftp my code is broking so i am wanting open sftp in another terminal and wanting still run code (mput, mget etc.) the terminal which is opened with sftp.

A little code:

```<code>Login = input("SFTP login (like root@127.0.0.1): ")
os.system("sftp " + Login)
print("Good Job!")

print("---------------------------------------------")
print("Your Files: ")
os.system("lls")
print(" ")
print("Files: ")
os.system("ls")
print("-------------------------------------------"
</code>```

Body:
I am wanting a good script for sftp and i am trying to code but when i entered sftp my code is broking so i am wanting open sftp in another terminal and wanting still run code (mput, mget etc.) the terminal which is opened with sftp.

A little code:

Login = input("SFTP login (like root@127.0.0.1): ")
os.system("sftp " + Login)
print("Good Job!")

print("---------------------------------------------")
print("Your Files: ")
os.system("lls")
print(" ")
print("Files: ")
os.system("ls")
print("-------------------------------------------"


问:
Right way to kill a python process (python-shell - NodeJS)?
I have a synchronization project, which invokes a python file to execute loads, so I initialize the application with nodejs.
There is a node-cron that does the event every 1min, and I would like to know what is the best strategy to not jam or leave the python in memory, I would like to kill the open python as soon as its process is finished

my event.ts

```<code>import { ChildProcess } from 'child_process'
import { schedule } from 'node-cron'
import { PythonShell } from 'python-shell'
import util from 'util'

interface IDocumentEvent {
    eventName: string
    arquive: string
    scriptPath: string
    pythonOptions: [string]
    mode: 'text'
}

export class EventManager {
    public static timer: string = '0 */1 * * * *'

    public static async running (input: IDocumentEvent) {
        schedule(this.timer, () => {
            console.log(util.inspect(process.memoryUsage()))
            let python_process: ChildProcess
            let processId = process.pid

            const pyshell = new PythonShell(input.arquive,{
                scriptPath: input.scriptPath,
                pythonOptions: input.pythonOptions,
                mode: input.mode
            })
            pyshell.send('Process started with ' + input.eventName.toUpperCase())
            pyshell.on('message', (message: string) => {
                console.log(input.eventName.toLocaleUpperCase() + ': ' + message);
            })
            pyshell.end(function (err, code, output) {
                if (err) {
                    console.log(input.eventName.toLocaleUpperCase() + ': ' + err)

                };
                console.log('The exit code was: ' + code);
                console.log('Clean condicoesResdepacho Process');
            });
            python_process = pyshell.childProcess
            python_process.kill('SIGTERM')
            python_process.kill('SIGINT')

        }, {
            scheduled: true,
            timezone: 'America/Sao_Paulo'
        })
    }
}
</code>```

I am using node-cron, and there are 4 events with it.

Body:
I have a synchronization project, which invokes a python file to execute loads, so I initialize the application with nodejs.
There is a node-cron that does the event every 1min, and I would like to know what is the best strategy to not jam or leave the python in memory, I would like to kill the open python as soon as its process is finished

my event.ts

import { ChildProcess } from 'child_process'
import { schedule } from 'node-cron'
import { PythonShell } from 'python-shell'
import util from 'util'

interface IDocumentEvent {
    eventName: string
    arquive: string
    scriptPath: string
    pythonOptions: [string]
    mode: 'text'
}

export class EventManager {
    public static timer: string = '0 */1 * * * *'

    public static async running (input: IDocumentEvent) {
        schedule(this.timer, () => {
            console.log(util.inspect(process.memoryUsage()))
            let python_process: ChildProcess
            let processId = process.pid

            const pyshell = new PythonShell(input.arquive,{
                scriptPath: input.scriptPath,
                pythonOptions: input.pythonOptions,
                mode: input.mode
            })
            pyshell.send('Process started with ' + input.eventName.toUpperCase())
            pyshell.on('message', (message: string) => {
                console.log(input.eventName.toLocaleUpperCase() + ': ' + message);
            })
            pyshell.end(function (err, code, output) {
                if (err) {
                    console.log(input.eventName.toLocaleUpperCase() + ': ' + err)

                };
                console.log('The exit code was: ' + code);
                console.log('Clean condicoesResdepacho Process');
            });
            python_process = pyshell.childProcess
            python_process.kill('SIGTERM')
            python_process.kill('SIGINT')

        }, {
            scheduled: true,
            timezone: 'America/Sao_Paulo'
        })
    }
}

I am using node-cron, and there are 4 events with it.


问:
Save txt file using apache cordova
I am using Apache Cordova version 10. I added to my project these plugins

cordova-plugin-camera 5.0.2 "Camera"

cordova-plugin-chooser 1.3.1 "Chooser"

cordova-plugin-device-orientation 2.0.1 "Device Orientation"

cordova-plugin-device 2.0.3 "Device"

cordova-plugin-dialogs 2.0.2 "Notification"

cordova-plugin-file 6.0.2 "File"

cordova-plugin-inappbrowser 5.0.0 "InAppBrowser"

cordova-plugin-media-capture 3.0.3 "Capture"

cordova-plugin-media 5.0.3 "Media"

cordova-plugin-network-information 2.0.2 "Network Information"

cordova-plugin-restartapp 0.0.1 "cordova-plugin-restartapp"

cordova-plugin-screen-orientation 3.0.2 "Screen Orientation"

cordova-plugin-splashscreen 6.0.0 "Splashscreen"

cordova-plugin-statusbar 2.4.3 "StatusBar"

cordova-plugin-vibration 3.1.1 "Vibration"

cordova-plugin-whitelist 1.3.5 "Whitelist"

es6-promise-plugin 4.2.2 "Promise"

nl.madebymark.share 0.1.1 "Share"

phonegap-plugin-barcodescanner 8.1.0 "BarcodeScanner"

I tried save text file using this code

```<code>    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
    const path: string = cordova.file.dataDirectory;
            fs.root.getFile("myTextFile.txt", { create: true, exclusive: false }, function(fileEntry) {
        console.log("FileEntry Is File? " + fileEntry.isFile.toString() +
                    "fileEntry.name " + fileEntry.name +
                    "fileEntry.fullPath " + fileEntry.fullPath);
                writeFile(fileEntry, null, callback);

            }, onErrorCreateFile);

        }, onErrorLoadFs);

    }

</code>```

In confix.xml I have this

```<code>    <preference name="AndroidPersistentFileLocation" value="Internal" />
    <preference name="AndroidPersistentFileLocation" value="Compatibility" />
    <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />
</code>```

When code runs, I get error code 5;

I tried to change

fs.root.getFile("mytextfile.txt"   to
fs.root.getFile(path + "mytextfile.txt"

After this I got error code 9

Next I tried to change (with or witout path + "myTextFile.txt")

```<code> window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, async fs => {

                  window.resolveLocalFileSystemURL(window.cordova.file.dataDirectory, async dirEntry  => {
  dirEntry.getFile("myTextFile.txt", { create: true, exclusive: false }, fileEntry => {

 console.log("FileEntry Is File? " + fileEntry.isFile.toString() +
                             "fileEntry.name " + fileEntry.name +
                             "fileEntry.fullPath " + fileEntry.fullPath);
                        }, onErrorCreateFile)
                  });
            })
</code>```

Thanks for help me.

Title: Save txt file using apache cordova

Body:
I am using Apache Cordova version 10. I added to my project these plugins

cordova-plugin-camera 5.0.2 "Camera"

cordova-plugin-chooser 1.3.1 "Chooser"

cordova-plugin-device-orientation 2.0.1 "Device Orientation"

cordova-plugin-device 2.0.3 "Device"

cordova-plugin-dialogs 2.0.2 "Notification"

cordova-plugin-file 6.0.2 "File"

cordova-plugin-inappbrowser 5.0.0 "InAppBrowser"

cordova-plugin-media-capture 3.0.3 "Capture"

cordova-plugin-media 5.0.3 "Media"

cordova-plugin-network-information 2.0.2 "Network Information"

cordova-plugin-restartapp 0.0.1 "cordova-plugin-restartapp"

cordova-plugin-screen-orientation 3.0.2 "Screen Orientation"

cordova-plugin-splashscreen 6.0.0 "Splashscreen"

cordova-plugin-statusbar 2.4.3 "StatusBar"

cordova-plugin-vibration 3.1.1 "Vibration"

cordova-plugin-whitelist 1.3.5 "Whitelist"

es6-promise-plugin 4.2.2 "Promise"

nl.madebymark.share 0.1.1 "Share"

phonegap-plugin-barcodescanner 8.1.0 "BarcodeScanner"

I tried save text file using this code

    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
    const path: string = cordova.file.dataDirectory;
            fs.root.getFile("myTextFile.txt", { create: true, exclusive: false }, function(fileEntry) {
        console.log("FileEntry Is File? " + fileEntry.isFile.toString() +
                    "fileEntry.name " + fileEntry.name +
                    "fileEntry.fullPath " + fileEntry.fullPath);
                writeFile(fileEntry, null, callback);

            }, onErrorCreateFile);

        }, onErrorLoadFs);

    }

In confix.xml I have this

    <preference name="AndroidPersistentFileLocation" value="Internal" />
    <preference name="AndroidPersistentFileLocation" value="Compatibility" />
    <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />

When code runs, I get error code 5;

I tried to change

fs.root.getFile("mytextfile.txt"   to
fs.root.getFile(path + "mytextfile.txt"

After this I got error code 9

Next I tried to change (with or witout path + "myTextFile.txt")

 window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, async fs => {

                  window.resolveLocalFileSystemURL(window.cordova.file.dataDirectory, async dirEntry  => {
  dirEntry.getFile("myTextFile.txt", { create: true, exclusive: false }, fileEntry => {

 console.log("FileEntry Is File? " + fileEntry.isFile.toString() +
                             "fileEntry.name " + fileEntry.name +
                             "fileEntry.fullPath " + fileEntry.fullPath);
                        }, onErrorCreateFile)
                  });
            })

Thanks for help me.


问:
Display XLS / XLSX files (using Base64 data as input) on Reactjs website
I have a base64 data (of mimetype : application/vnd.openxmlformats-officedocument.spreadsheetml.sheet )

I'm using xlsx library , where datas are collected and plotted well, but for some xlsx files where there are images , I m unable to fetch the image(s) (below example SAP Logo) and exact point to point alignments. Example screenshots attached below:

Original File:

Displayed view at the React webpage using xlsx library:

How can I be able to display the XLSX / XLS files perfectly ?


问:
Powerbuilder 21 Single Line Edit field colours when not enabled
I have a Powerbuilder 21 screen with several Single Line Edit fields on it. The colours have been neatly set up so that if you can access a field (the Tab Order is greater than 0), it is coloured white; if you cannot then it is the same colour as the main window, thus still able to display the text while having it inaccessible.

If I do a piece of dynamic coding and Disable a field (set Enabled to False) then the colour changes to a rather nasty greeny-grey text on a rather revolting background. If, on the other hand, I try setting the Tab Order to 0, this is no problem except that the actual "Tab Ordering" is lost and you end up tabbing wildly.

Is there a solution please to a way to "disable" the Single Line Edit field?


问:
ACL lost after save the file using gedit editor
I have a file that have ACL info, added by setfacl -m u:user:rw file. If I use gedit(started by root) open this file, make some edit and then save the file, this file's ACL info will be lost, the vim does not have that problem, what going wrong?


问:
Colored dataframe becomes black in excel but is beautiful in notebook
Hello I have this code that colors duplicates in a pandas dataframe. It looks great in notebook but when I save it to excel and view it there are the cells completely black. What am I doing wrong and how to fix it?</p>
```<code># Define a custom color palette
custom_colors = ['#03254c', '#173F5F', '#20639B', '#3CAEA3', '#008000', '#00c04b', '#808000', '#B4C424', '#5cb7aa', '#808000']

# Define a dictionary that maps each unique value in the 'IMSI' column to a different color from the custom palette
color_map = dict(zip(unique_fraud['IMSI'].unique(), custom_colors))

# Define a function that assigns a background color based on the value in a cell

def color_duplicates(val):
    if val in color_map:
        return f'background-color: {color_map[val]}'
    else:
        return ''

# Use the 'style.applymap' method to apply the function to each cell in the DataFrame
colors = unique_fraud.style.applymap(color_duplicates)

# Use the 'set_properties' method to save the colors applied to the cells in the DataFrame
colors.set_properties(**{'background-color': color_map.values()})

# Save the colored DataFrame as the 'unique_fraud' object
unique_fraud = colors

# Save in folder
unique_fraud.to_excel('C:/path/unique_fraud.xlsx', index = False)
</code>```

Body:
Hello I have this code that colors duplicates in a pandas dataframe. It looks great in notebook but when I save it to excel and view it there are the cells completely black. What am I doing wrong and how to fix it?

# Define a custom color palette
custom_colors = ['#03254c', '#173F5F', '#20639B', '#3CAEA3', '#008000', '#00c04b', '#808000', '#B4C424', '#5cb7aa', '#808000']

# Define a dictionary that maps each unique value in the 'IMSI' column to a different color from the custom palette
color_map = dict(zip(unique_fraud['IMSI'].unique(), custom_colors))

# Define a function that assigns a background color based on the value in a cell

def color_duplicates(val):
    if val in color_map:
        return f'background-color: {color_map[val]}'
    else:
        return ''

# Use the 'style.applymap' method to apply the function to each cell in the DataFrame
colors = unique_fraud.style.applymap(color_duplicates)

# Use the 'set_properties' method to save the colors applied to the cells in the DataFrame
colors.set_properties(**{'background-color': color_map.values()})

# Save the colored DataFrame as the 'unique_fraud' object
unique_fraud = colors

# Save in folder
unique_fraud.to_excel('C:/path/unique_fraud.xlsx', index = False)


问:
Python web-scraping script returning nothing in Laravel variable
This is my Python Script

```<code>import sys
import pandas as pd
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'}

url = sys.argv[1]

response=requests.get(url,headers=headers)
soup=BeautifulSoup(response.content,'lxml')
table = soup.find('table',{'id':'gsc_a_t'})

titles = []
for item in table.find_all(class_='gsc_a_at'):
  title = item.text
  titles.append(title)

print(titles)

</code>```

This is my Controller in Laravel.
After displaying $title it shows null

```<code>$client = new Client();
$a = 'https://scholar.google.com/citations?user=';
$gscID = 'EnegzCwAAAAJ';
$b = '&hl=en&oi=ao';
$url = $a.$gscID.$b;

$title = shell_exec("python title.py $url");

dd($title);
</code>```

BUT When I run this python script it runs perfectly and shows the output

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

url = sys.argv[1]
df = pd.read_html(url)

print(df[1])
</code>```

I don't know what is wrong with this, I guess its because of the web scraping library BeautifulSoup used in it and the script is also running perfectly on Google Collab, I didn't find any resource on the internet which solves this problem, Any Help would be really appreciated

Body:
This is my Python Script

import sys
import pandas as pd
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'}

url = sys.argv[1]

response=requests.get(url,headers=headers)
soup=BeautifulSoup(response.content,'lxml')
table = soup.find('table',{'id':'gsc_a_t'})

titles = []
for item in table.find_all(class_='gsc_a_at'):
  title = item.text
  titles.append(title)

print(titles)

This is my Controller in Laravel.
After displaying $title it shows null

$client = new Client();
$a = 'https://scholar.google.com/citations?user=';
$gscID = 'EnegzCwAAAAJ';
$b = '&hl=en&oi=ao';
$url = $a.$gscID.$b;

$title = shell_exec("python title.py $url");

dd($title);

BUT When I run this python script it runs perfectly and shows the output

import sys
import pandas as pd

url = sys.argv[1]
df = pd.read_html(url)

print(df[1])

I don't know what is wrong with this, I guess its because of the web scraping library BeautifulSoup used in it and the script is also running perfectly on Google Collab, I didn't find any resource on the internet which solves this problem, Any Help would be really appreciated


问:
How to expose a class's callable methods from an asyncio server protocol for use in main()
How do I expose the method send() in EchoServerProtocol class for use in main()?

import socket
import asyncio

class EchoServerProtocol(asyncio.Protocol):
    def __init__(self):
        self.transport = None

    def connection_made(self, transport):
        peer_name = transport.get_extra_info('peername')
        print('Connection from {}'.format(peer_name))
        self.transport = transport

    def data_received(self, data):
        message = data.decode()
        print('Data received: {!r}'.format(message))
        print('Send: {!r}'.format(message))
        self.transport.write(data)
        self.close()

    def send(self, data):
        self.transport.write(data)

    def close(self):
        print('Close the client socket')
        self.transport.close()

    def connection_lost(self, exc):
        print('The client closed the connection')
        asyncio.get_event_loop().stop()

async def main():
    loop = asyncio.get_running_loop()

    server = await loop.create_server(
        lambda: EchoServerProtocol(),
        '127.0.0.1', 8888)

    server.send("Some text".encode())

    async with server:
        await server.serve_forever()

asyncio.run(main())
```


问:
Nginx config : How to exclude context path in proxy_pass rule?
Nginx server on localhost:80

```<code>    location / {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        add_header X-location websocket always;
        proxy_set_header Host $host;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_pass http://mydomain:8888;
        proxy_connect_timeout       300;
        proxy_send_timeout          300;
        proxy_read_timeout          300;
    }
</code>```

The above code works : when client (webSocket) (socketio-client) hit ws://localhost:80  as a proxy it pass the request to mydomain:8888 where the webSocket is listening on port 8888 and webSocket (socketio) connects successfully.

```<code>    location /tunnel/server {
        rewrite  ^/tunnel/server(.*)$ $1 break;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        add_header X-location websocket always;
        proxy_set_header Host $host;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_pass http://mydomain:8888;
        proxy_connect_timeout       300;
        proxy_send_timeout          300;
        proxy_read_timeout          300;
    }
</code>```

I expect similar behavior from these -- just a little difference - now my client (socketio-client) try to make webSocket connection with ws://localhost:80/tunnel/server but the nginx server Add tunnel/server to end -- making proxy_pass -> http://mydomain:8888/tunnel/server -- for this i'm using rewrite rule
Still webSocket never connects
Nginx Logs

Body:
Nginx server on localhost:80

    location / {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        add_header X-location websocket always;
        proxy_set_header Host $host;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_pass http://mydomain:8888;
        proxy_connect_timeout       300;
        proxy_send_timeout          300;
        proxy_read_timeout          300;
    }

The above code works : when client (webSocket) (socketio-client) hit ws://localhost:80  as a proxy it pass the request to mydomain:8888 where the webSocket is listening on port 8888 and webSocket (socketio) connects successfully.

    location /tunnel/server {
        rewrite  ^/tunnel/server(.*)$ $1 break;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        add_header X-location websocket always;
        proxy_set_header Host $host;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_pass http://mydomain:8888;
        proxy_connect_timeout       300;
        proxy_send_timeout          300;
        proxy_read_timeout          300;
    }

I expect similar behavior from these -- just a little difference - now my client (socketio-client) try to make webSocket connection with ws://localhost:80/tunnel/server but the nginx server Add tunnel/server to end -- making proxy_pass -> http://mydomain:8888/tunnel/server -- for this i'm using rewrite rule
Still webSocket never connects
Nginx Logs


问:
How to write a custom configuration for hugging face model for Token Classification
Model description

I add simple custom pytorch-crf layer on top of TokenClassification model for NER. It will make the model more robust.

I train the model and I get the error:

```<code>***** Running training *****
  Num examples = 4
  Num Epochs = 2
  Instantaneous batch size per device = 2
  Total train batch size (w. parallel, distributed & accumulation) = 2
  Gradient Accumulation steps = 1
  Total optimization steps = 4
TypeError: __init__() missing 3 required positional arguments: 'id2label', 'label2id', and 'num_labels'
</code>```

Code

```<code>from torchcrf import CRF

model_checkpoint = "spanbert"
tokenizer = BertTokenizer.from_pretrained(model_checkpoint,add_prefix_space=True)
bert_model = BertForTokenClassification.from_pretrained(
                        model_checkpoint,id2label=id2label,label2id=label2id)
bert_model.config.output_hidden_states=True

class BertClassifierConfig(PretrainedConfig):

    model_type="BertForTokenClassification"

    def __init__(self,id2label ,label2id,num_labels,**kwargs):

        self.num_labels=num_labels
        self.id2label=id2label
        self.label2id=label2id
        self.output_hidden_states=True

        super().__init__(**kwargs)
</code>```

Model

```<code>class BertForTokenClassification(PreTrainedModel):

    config_class =BertClassifierConfig
    def __init__(self, config,bert_model, num_labels):
      super(BertForTokenClassification, self).__init__(config)
      self.bert = bert_model
      self.dropout = nn.Dropout(0.25)
      self.classifier = nn.Linear(768, num_labels)
      self.crf = CRF(num_labels, batch_first = True)

    def forward(self, input_ids, attention_mask,  labels=None, token_type_ids=None):
        outputs = self.bert(input_ids, attention_mask=attention_mask)
        sequence_output = torch.stack((outputs[1][-1], outputs[1][-2], outputs[1][-3], outputs[1][-4])).mean(dim=0)
        sequence_output = self.dropout(sequence_output)

        emission = self.classifier(sequence_output) # [32,256,17]

        labels=labels.reshape(attention_mask.size()[0],attention_mask.size()[1])

        if labels is not None:

            loss = -self.crf(log_soft(emission, 2), labels, mask=attention_mask.type(torch.uint8), reduction='mean')
            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return [loss, prediction]

        else:

            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return prediction
</code>```

Saving

```<code>configuration = BertClassifierConfig(id2label ,label2id,num_labels=len(label2id))
model = BertForTokenClassification(configuration,bert_model, num_labels=len(label2id))
model.to(device)

args = TrainingArguments(
    "test0000",
    # evaluation_strategy="epoch",
    save_strategy="epoch",
    learning_rate=2e-5,
    num_train_epochs=2,
    weight_decay=0.01,
    per_device_train_batch_size=2,
    # per_device_eval_batch_size=32
    fp16=True
    # bf16=True #Ampere GPU
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=train_data,
    # eval_dataset=train_data,
    # data_collator=data_collator,
    # compute_metrics=compute_metrics,
    tokenizer=tokenizer)
</code>```

Saving

```<code>trainer.train()
trainer.save_model("modeltest")

AutoConfig.register("BertForTokenClassification", BertClassifierConfig)
AutoModel.register(BertClassifierConfig, BertForTokenClassification)
</code>```

ERROR

```<code> ***** Running training *****
      Num examples = 4
      Num Epochs = 2
      Instantaneous batch size per device = 2
      Total train batch size (w. parallel, distributed & accumulation) = 2
      Gradient Accumulation steps = 1
      Total optimization steps = 4
    TypeError: __init__() missing 3 required positional arguments: 'id2label', 'label2id', and 'num_labels'
</code>```

Body:
Model description

I add simple custom pytorch-crf layer on top of TokenClassification model for NER. It will make the model more robust.

I train the model and I get the error:

***** Running training *****
  Num examples = 4
  Num Epochs = 2
  Instantaneous batch size per device = 2
  Total train batch size (w. parallel, distributed & accumulation) = 2
  Gradient Accumulation steps = 1
  Total optimization steps = 4
TypeError: __init__() missing 3 required positional arguments: 'id2label', 'label2id', and 'num_labels'

Code

from torchcrf import CRF

model_checkpoint = "spanbert"
tokenizer = BertTokenizer.from_pretrained(model_checkpoint,add_prefix_space=True)
bert_model = BertForTokenClassification.from_pretrained(
                        model_checkpoint,id2label=id2label,label2id=label2id)
bert_model.config.output_hidden_states=True

class BertClassifierConfig(PretrainedConfig):

    model_type="BertForTokenClassification"

    def __init__(self,id2label ,label2id,num_labels,**kwargs):

        self.num_labels=num_labels
        self.id2label=id2label
        self.label2id=label2id
        self.output_hidden_states=True

        super().__init__(**kwargs)

Model

class BertForTokenClassification(PreTrainedModel):

    config_class =BertClassifierConfig
    def __init__(self, config,bert_model, num_labels):
      super(BertForTokenClassification, self).__init__(config)
      self.bert = bert_model
      self.dropout = nn.Dropout(0.25)
      self.classifier = nn.Linear(768, num_labels)
      self.crf = CRF(num_labels, batch_first = True)

    def forward(self, input_ids, attention_mask,  labels=None, token_type_ids=None):
        outputs = self.bert(input_ids, attention_mask=attention_mask)
        sequence_output = torch.stack((outputs[1][-1], outputs[1][-2], outputs[1][-3], outputs[1][-4])).mean(dim=0)
        sequence_output = self.dropout(sequence_output)

        emission = self.classifier(sequence_output) # [32,256,17]

        labels=labels.reshape(attention_mask.size()[0],attention_mask.size()[1])

        if labels is not None:

            loss = -self.crf(log_soft(emission, 2), labels, mask=attention_mask.type(torch.uint8), reduction='mean')
            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return [loss, prediction]

        else:

            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return prediction

Saving

configuration = BertClassifierConfig(id2label ,label2id,num_labels=len(label2id))
model = BertForTokenClassification(configuration,bert_model, num_labels=len(label2id))
model.to(device)

args = TrainingArguments(
    "test0000",
    # evaluation_strategy="epoch",
    save_strategy="epoch",
    learning_rate=2e-5,
    num_train_epochs=2,
    weight_decay=0.01,
    per_device_train_batch_size=2,
    # per_device_eval_batch_size=32
    fp16=True
    # bf16=True #Ampere GPU
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=train_data,
    # eval_dataset=train_data,
    # data_collator=data_collator,
    # compute_metrics=compute_metrics,
    tokenizer=tokenizer)

Saving

trainer.train()
trainer.save_model("modeltest")

AutoConfig.register("BertForTokenClassification", BertClassifierConfig)
AutoModel.register(BertClassifierConfig, BertForTokenClassification)

ERROR

 ***** Running training *****
      Num examples = 4
      Num Epochs = 2
      Instantaneous batch size per device = 2
      Total train batch size (w. parallel, distributed & accumulation) = 2
      Gradient Accumulation steps = 1
      Total optimization steps = 4
    TypeError: __init__() missing 3 required positional arguments: 'id2label', 'label2id', and 'num_labels'


问:
Flutter: How to store data from firebase to specific user
The problem that I facing right now is I did add and retrieve data from Firebase but it didn't store under the user that perform the operation I mentioned. When I log in to another account the same data also display under different user.

This is my code:

```<code> final CollectionReference _timeline =
  FirebaseFirestore.instance.collection('timeline');
</code>```

This is my code to display in UI:

```<code> StreamBuilder(
              stream: _timeline.snapshots(),
              builder:
                  (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
                if (streamSnapshot.hasData) {
                  return Expanded(
                    child: ListView.builder(
                        itemCount: streamSnapshot.data!.docs.length,
                        itemBuilder: (context, index) {
                          final DocumentSnapshot documentSnapshot =
                              streamSnapshot.data!.docs[index];
                          return Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 30, vertical: 5),
                            child: FadeInUp(
                              duration: const Duration(milliseconds: 500),
                              child: ListTile(
                                onLongPress: () => udFunction(),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5)),
                                tileColor: Colors
                                    .primaries[Random()
                                        .nextInt(Colors.primaries.length)]
                                    .shade200,
                                title: Text(
                                  documentSnapshot['topic'],
                                  style: const TextStyle(
                                      fontFamily: 'poppins',
                                      fontWeight: FontWeight.w500,
                                      fontSize: 16,
                                      color: Colors.black),
                                ),
                                subtitle: Text(
                                  documentSnapshot['time'],
                                  style: TextStyle(
                                      fontFamily: 'poppins',
                                      fontWeight: FontWeight.w400,
                                      fontSize: 14,
                                      color: Colors.black.withOpacity(.6)),
                                ),
                                trailing: RotatedBox(
                                  quarterTurns: 3,
                                  child: Text(
                                    documentSnapshot['isDone'] ==
                                            !documentSnapshot['isDone']
                                        ? 'ToDo'
                                        : 'Done',
                                    style: TextStyle(
                                        fontFamily: 'poppins',
                                        fontWeight: FontWeight.w600,
                                        fontSize: 14,
                                        color: documentSnapshot['isDone'] ==
                                                !documentSnapshot['isDone']
                                            ? Colors.black.withOpacity(.6)
                                            : Colors.green),
                                  ),
                                ),
                              ),
                            ),
                          );
                        }),
                  );
                }
                return const Center(
                  child: CircularProgressIndicator(),
                );
              })
</code>```

What I want to achieve is whenever user perform any CRUD operation, the data is saved under the user who perform that operation and how can I do that? Thank you.

Body:
The problem that I facing right now is I did add and retrieve data from Firebase but it didn't store under the user that perform the operation I mentioned. When I log in to another account the same data also display under different user.

This is my code:

 final CollectionReference _timeline =
  FirebaseFirestore.instance.collection('timeline');

This is my code to display in UI:

 StreamBuilder(
              stream: _timeline.snapshots(),
              builder:
                  (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
                if (streamSnapshot.hasData) {
                  return Expanded(
                    child: ListView.builder(
                        itemCount: streamSnapshot.data!.docs.length,
                        itemBuilder: (context, index) {
                          final DocumentSnapshot documentSnapshot =
                              streamSnapshot.data!.docs[index];
                          return Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 30, vertical: 5),
                            child: FadeInUp(
                              duration: const Duration(milliseconds: 500),
                              child: ListTile(
                                onLongPress: () => udFunction(),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5)),
                                tileColor: Colors
                                    .primaries[Random()
                                        .nextInt(Colors.primaries.length)]
                                    .shade200,
                                title: Text(
                                  documentSnapshot['topic'],
                                  style: const TextStyle(
                                      fontFamily: 'poppins',
                                      fontWeight: FontWeight.w500,
                                      fontSize: 16,
                                      color: Colors.black),
                                ),
                                subtitle: Text(
                                  documentSnapshot['time'],
                                  style: TextStyle(
                                      fontFamily: 'poppins',
                                      fontWeight: FontWeight.w400,
                                      fontSize: 14,
                                      color: Colors.black.withOpacity(.6)),
                                ),
                                trailing: RotatedBox(
                                  quarterTurns: 3,
                                  child: Text(
                                    documentSnapshot['isDone'] ==
                                            !documentSnapshot['isDone']
                                        ? 'ToDo'
                                        : 'Done',
                                    style: TextStyle(
                                        fontFamily: 'poppins',
                                        fontWeight: FontWeight.w600,
                                        fontSize: 14,
                                        color: documentSnapshot['isDone'] ==
                                                !documentSnapshot['isDone']
                                            ? Colors.black.withOpacity(.6)
                                            : Colors.green),
                                  ),
                                ),
                              ),
                            ),
                          );
                        }),
                  );
                }
                return const Center(
                  child: CircularProgressIndicator(),
                );
              })

What I want to achieve is whenever user perform any CRUD operation, the data is saved under the user who perform that operation and how can I do that? Thank you.


问:
Can not found valid font in ffmpeg android
I want to add text over video using ffmpeg. But it gives me error of Cannot find a valid font.

I used this command

```<code>ffmpeg -y -ss 0 -i /data/user/0/com.example.videoeditor/cache/LMS_1670500883503.mp4 -filter_complex drawtext="fontfile=/usr/share/fonts/truetype/freefont/FreeSans.ttf:text='Stack Overflow':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2" -t 7 -movflags faststart -strict experimental -vcodec mpeg4 -b:v 2097152 -b:a 48000 -ac 2 -ar 22050 /storage/emulated/0/Download/LMS_1670500883824.mp4
</code>```

but it gives me error

```<code> Cannot find a valid font for the family Sans
Error initializing filter 'drawtext'
with args 'fontfile=/usr/share/fonts/truetype/freefont/FreeSans.ttf:text=Stack Overflow:fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2'
</code>```

I'm using ubuntu OS.
And also is there any way to get font file from android studio assets folder?

Thanks in Advance!!

Body:
I want to add text over video using ffmpeg. But it gives me error of Cannot find a valid font.

I used this command

ffmpeg -y -ss 0 -i /data/user/0/com.example.videoeditor/cache/LMS_1670500883503.mp4 -filter_complex drawtext="fontfile=/usr/share/fonts/truetype/freefont/FreeSans.ttf:text='Stack Overflow':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2" -t 7 -movflags faststart -strict experimental -vcodec mpeg4 -b:v 2097152 -b:a 48000 -ac 2 -ar 22050 /storage/emulated/0/Download/LMS_1670500883824.mp4

but it gives me error

 Cannot find a valid font for the family Sans
Error initializing filter 'drawtext'
with args 'fontfile=/usr/share/fonts/truetype/freefont/FreeSans.ttf:text=Stack Overflow:fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2'

I'm using ubuntu OS.
And also is there any way to get font file from android studio assets folder?

Thanks in Advance!!


问:
FFMPEG CUDA Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scale_0'
I am trying to convert an FFMPEG RTMP source, resize it, and pass it to another RTMP source. My command is as follows:

```<code>/usr/bin/ffmpeg -hide_banner -hwaccel cuda -hwaccel_output_format cuda -extra_hw_frames 8 -i rtmp://127.0.0.1:1935/live/xxxxxx -c:v libx264 -preset veryfast -maxrate 8000k -bufsize 8000k -g 60 -r 30 -s 640x360 -c:a aac -b:a 64k -f flv rtmp://127.0.0.1:1935/live/xxxxx_360
</code>```

But I keep getting this error

```<code>Input #0, flv, from 'rtmp://127.0.0.1:1935/live/xxxxxxxx':
  Metadata:
    |RtmpSampleAccess: false
  Duration: N/A, start: 1461.149000, bitrate: N/A
  Stream #0:0: Audio: aac (LC), 44100 Hz, stereo, fltp
  Stream #0:1: Video: h264 (High), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 24.42 fps, 23.98 tbr, 1k tbn
Stream mapping:
  Stream #0:1 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #0:0 -> #0:1 (aac (native) -> aac (native))
Press [q] to stop, [?] for help
Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scale_0'
Error reinitializing filters!
Failed to inject frame into filter network: Function not implemented
Error while processing the decoded data for stream #0:1
[aac @ 0x56096f201540] Qavg: 1955.047
[aac @ 0x56096f201540] 2 frames left in the queue on closing
Conversion failed!
</code>```

Any guidance on the conversion error?

Body:
I am trying to convert an FFMPEG RTMP source, resize it, and pass it to another RTMP source. My command is as follows:

/usr/bin/ffmpeg -hide_banner -hwaccel cuda -hwaccel_output_format cuda -extra_hw_frames 8 -i rtmp://127.0.0.1:1935/live/xxxxxx -c:v libx264 -preset veryfast -maxrate 8000k -bufsize 8000k -g 60 -r 30 -s 640x360 -c:a aac -b:a 64k -f flv rtmp://127.0.0.1:1935/live/xxxxx_360

But I keep getting this error

Input #0, flv, from 'rtmp://127.0.0.1:1935/live/xxxxxxxx':
  Metadata:
    |RtmpSampleAccess: false
  Duration: N/A, start: 1461.149000, bitrate: N/A
  Stream #0:0: Audio: aac (LC), 44100 Hz, stereo, fltp
  Stream #0:1: Video: h264 (High), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 24.42 fps, 23.98 tbr, 1k tbn
Stream mapping:
  Stream #0:1 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #0:0 -> #0:1 (aac (native) -> aac (native))
Press [q] to stop, [?] for help
Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scale_0'
Error reinitializing filters!
Failed to inject frame into filter network: Function not implemented
Error while processing the decoded data for stream #0:1
[aac @ 0x56096f201540] Qavg: 1955.047
[aac @ 0x56096f201540] 2 frames left in the queue on closing
Conversion failed!

Any guidance on the conversion error?


问:
How to check the container for integrity in podman
I'm trying to check the container for integrity in pacman, but I don't know how to do it
There is an inspect command that outputs the json format
Can you help me figure this out please

I try to use "inspect" command, but i understand info in json file


问:
I want to create Animated Carousel like below video
Video Link - https://youtube.com/shorts/Wbh-dpHzwuo

I want to create this animated slider, But I haven't any idea to create this animated carousel.
I want to know helpfull resouses for create this carousel.

Video Link - https://youtube.com/shorts/Wbh-dpHzwuo

I want to create this animated slider, But I haven't any idea to create this animated carousel.
I want to know helpfull resouses for create this carousel.


问:
How to Send simple variable/Data to Django model field with pure Javascript/Ajax?
I want to insert an integer to django class Field but when I click POST it fails

More specificly, there is a problem to send a post request to a django server. When I click on the "post" Button, I get the following error on the Terminal. I tried by changing the variables, Functions etc...

File "/home/nick/Desktop/new_venv/lib/python3.8/site-packages/django/utils/datastructures.py", line 86, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'age'
[08/Dec/2022 11:21:03] "POST /post/ HTTP/1.1" 500 72563
```
<p>This is the Ajax Script including the buttons and the Id's:</p>
<pre class="lang-html prettyprint-override"><code><button id="get">Send GET Request</button><br>
<button id="post">Send POST Request</button>
<script>

var csrftoken = '{{ csrf_token }}'

document.getElementById('get').onclick = () => {
    const requestObj = new XMLHttpRequest()
    requestObj.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText)
        }
    }

    requestObj.open("GET", '/get/')
    requestObj.send()
}

document.getElementById('post').onclick = () => {
    const requestObj = new XMLHttpRequest()
    requestObj.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText)
        }
    }

    requestObj.open("POST", '/post/')
    requestObj.setRequestHeader("X-CSRFToken", csrftoken)

    // const formdata = new FormData()
    // formdata.append('name', 'John')
    // formdata.append('age', '17')
    // requestObj.send(formdata)
    var age = 16;
    requestObj.send(age)
}
</script>
</code>```

the Views.py File

These are the routes functions

def home_page(request):
    return render(request, 'home.html', {})

def get_request(request):
    return HttpResponse("Hello World!")

def post_request(request):
    if request.method == "POST":
        age = request.POST['age'] # trying to insert the value
        new_age = Age.objects.all()
        new_age = Age(age = age)#New instance
        new_age.save()#saving the instance
    return HttpResponse("POST request") # return the httpResponse
```
<h3>the models.py file</h3>
<p>the class Model</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models ##including the models

class Age(models.Model):
    age = models.IntegerField(default = 1) # the integer field
</code>```

the urls.py file inludes all the routes

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', home_page),
    path('get/', get_request),
    path('post/', post_request),
]
```

I have tried numerous ways to change the datatype on the send function but without success. I expect to insert an integer to the integer Age class Field.

I found a lot of examples with jQuery which is the shortest way, but how can I do the task with vanilla Javascript?

What am I doing wrong?

Body:
I want to insert an integer to django class Field but when I click POST it fails

More specificly, there is a problem to send a post request to a django server. When I click on the "post" Button, I get the following error on the Terminal. I tried by changing the variables, Functions etc...

File "/home/nick/Desktop/new_venv/lib/python3.8/site-packages/django/utils/datastructures.py", line 86, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'age'
[08/Dec/2022 11:21:03] "POST /post/ HTTP/1.1" 500 72563

This is the Ajax Script including the buttons and the Id's:

<button id="get">Send GET Request</button>

<button id="post">Send POST Request</button>

the Views.py File

These are the routes functions

def home_page(request):
    return render(request, 'home.html', {})

def get_request(request):
    return HttpResponse("Hello World!")

def post_request(request):
    if request.method == "POST":
        age = request.POST['age'] # trying to insert the value
        new_age = Age.objects.all()
        new_age = Age(age = age)#New instance
        new_age.save()#saving the instance
    return HttpResponse("POST request") # return the httpResponse

the models.py file

the class Model

from django.db import models ##including the models

class Age(models.Model):
    age = models.IntegerField(default = 1) # the integer field

the urls.py file inludes all the routes

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', home_page),
    path('get/', get_request),
    path('post/', post_request),
]

I have tried numerous ways to change the datatype on the send function but without success. I expect to insert an integer to the integer Age class Field.

I found a lot of examples with jQuery which is the shortest way, but how can I do the task with vanilla Javascript?

What am I doing wrong?


问:
Node.js/React.js How to post tweet from user behalf?
I have a React.js application, where I want to add an opportunity for users to post tweets on their feeds, I am using Node.js server for the backend,  everything works fine I can post a new tweet on my news feed, but I don't know how I can post tweet from user behalf,
I can get consumer_key and consumer_secret from my Twitter App, but I can't figure out how I can get access_token_key and access_token_secret from the user, I know I need to implement  Authorization to get user details, but Twitter docs for a newbie like me is quite complicated.

What is the best way to achieve the desired result?

Any useful recourses will be appreciated.

//App.js

const express = require("express");
const app = express();
const axios = require("axios");
const Twitter = require("twitter");
const path = require("path");
const fs = require("fs");

const client = new Twitter({
  consumer_key: "consumer_key",
  consumer_secret: "consumer_secret",
  access_token_key: "access_token_key",
  access_token_secret: "access_token_secret",
});

app.get("/", (req, res) => {
  //upload media and get media id
  client.post(
    "statuses/update",
    { status: `Look at the chart now ${Date.now()}`},
    function (error, tweet, response) {
      if (error) {
        res.send({ error: error });
        return;
      } else {
        res.send({ data: 'Success' });
      }
    }
  );

});

app.listen(8000);```


问:
how to convert datatable to list and use that list as datasource to datagrid vb.net
I have Datatable that has many rows, what I need is to convert this Datatable to a list to use it as data source for Datagrid, I know that I can use the Datatable as data source but I don't want that because I have a lot of rows so using the Datatable make the Datagrid so slow so I need to inject the Datagrid with a list.
I found the following code but I couldn't apply it because it uses a name to the Datatable.

```<code>public void StudentList()
{

    DataTable dt = new DataTable("Student");
    dt.Columns.Add("StudentId", typeof(Int32));
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("Address", typeof(string));
    dt.Columns.Add("MobileNo", typeof(string));
    //Data
    dt.Rows.Add(1, "Manish", "Hyderabad", "0000000000");
    dt.Rows.Add(2, "Venkat", "Hyderabad", "111111111");
    dt.Rows.Add(3, "Namit", "Pune", "1222222222");
    dt.Rows.Add(4, "Abhinav", "Bhagalpur", "3333333333");

    List<Student> studentList = new List<Student>();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        Student student = new Student();
        student.StudentId = Convert .ToInt32 (dt.Rows[i]["StudentId"]);
        student.StudentName = dt.Rows[i]["StudentName"].ToString();
        student.Address = dt.Rows[i]["Address"].ToString();
        student.MobileNo = dt.Rows[i]["MobileNo"].ToString();
        studentList.Add(student);
    }
}
</code>```

see that the Datatable has named as "DataTable dt = new DataTable("Student")"

but my Datatable has no name, it's just "dim xDt as new Datatable"
and the code is "C#" but I need "Vb.Net", I tried to convert it but I couldn't.

my second question is: is there any way to use the fast Datasource to Datagrid?

Body:
I have Datatable that has many rows, what I need is to convert this Datatable to a list to use it as data source for Datagrid, I know that I can use the Datatable as data source but I don't want that because I have a lot of rows so using the Datatable make the Datagrid so slow so I need to inject the Datagrid with a list.
I found the following code but I couldn't apply it because it uses a name to the Datatable.

public void StudentList()
{

    DataTable dt = new DataTable("Student");
    dt.Columns.Add("StudentId", typeof(Int32));
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("Address", typeof(string));
    dt.Columns.Add("MobileNo", typeof(string));
    //Data
    dt.Rows.Add(1, "Manish", "Hyderabad", "0000000000");
    dt.Rows.Add(2, "Venkat", "Hyderabad", "111111111");
    dt.Rows.Add(3, "Namit", "Pune", "1222222222");
    dt.Rows.Add(4, "Abhinav", "Bhagalpur", "3333333333");

    List<Student> studentList = new List<Student>();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        Student student = new Student();
        student.StudentId = Convert .ToInt32 (dt.Rows[i]["StudentId"]);
        student.StudentName = dt.Rows[i]["StudentName"].ToString();
        student.Address = dt.Rows[i]["Address"].ToString();
        student.MobileNo = dt.Rows[i]["MobileNo"].ToString();
        studentList.Add(student);
    }
}

see that the Datatable has named as "DataTable dt = new DataTable("Student")"

but my Datatable has no name, it's just "dim xDt as new Datatable"
and the code is "C#" but I need "Vb.Net", I tried to convert it but I couldn't.

my second question is: is there any way to use the fast Datasource to Datagrid?


问:
Uvicorn save whole log in log file
Does anyone have an idea why my Uvicorn log is not logging the important things like this:

```<code>INFO:     127.0.0.1:63695 - "POST /uploadfile2/ HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:63699 - "POST /uploadfile/ HTTP/1.1" 200 OK
</code>```

But it shows some lines of the log - only system Start and System Stop? How to do it correctly, that's my recent code block to setup the log file:

```<code>        formatter = Formatter('%(asctime)s | %(levelname)-8s | %(funcName)-19s | %(message)s')
        handler = TimedRotatingFileHandler(conf_args["logPath"], when="midnight")
        handler.setFormatter(formatter)
        log = getLogger('log')
        fastapi_logger = getLogger("uvicorn")
        log.addHandler(handler)
        fastapi_logger.addHandler(handler)
        log.setLevel(logging_level)
</code>```

Here I start the script like every noob:

```<code>if __name__ == '__main__':
    uvicorn.run(app, port=8009)
</code>```

Title: Uvicorn save whole log in log file

Body:
Does anyone have an idea why my Uvicorn log is not logging the important things like this:

INFO:     127.0.0.1:63695 - "POST /uploadfile2/ HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:63699 - "POST /uploadfile/ HTTP/1.1" 200 OK

But it shows some lines of the log - only system Start and System Stop? How to do it correctly, that's my recent code block to setup the log file:

        formatter = Formatter('%(asctime)s | %(levelname)-8s | %(funcName)-19s | %(message)s')
        handler = TimedRotatingFileHandler(conf_args["logPath"], when="midnight")
        handler.setFormatter(formatter)
        log = getLogger('log')
        fastapi_logger = getLogger("uvicorn")
        log.addHandler(handler)
        fastapi_logger.addHandler(handler)
        log.setLevel(logging_level)

Here I start the script like every noob:

if __name__ == '__main__':
    uvicorn.run(app, port=8009)


问:
Does netlify service (netlify.com) support deploying backend-only apps?
Having a backend-only app (e.g an API server made with express.js or adonis.js), is there any way to deploy the app on netlify?

(Instead of getting a vps and configuring for example a debian and installing nginx and database and other stuff?)

does netlify suggest a better solution to deploy api-only apps?


问:
How to test if a private method eventually throws?
I have a class with only one public method: run().

When I call run() it calls two other methods, where one of the methods eventually throws.

```<code>expect(await object.run()).toThrow(Error);

// run() -> this.handler() -> this.validate() -> this.getObject()
</code>```

this.getObject() returns false, which in turn means this.validate() is false, and so one of the conditions inside this.handler fails, resulting in a throw.

The throw works as expected, but my current test does not pass.

Typically, how can one test that a private method, triggered eventually by a public method, throws?

Body:
I have a class with only one public method: run().

When I call run() it calls two other methods, where one of the methods eventually throws.

expect(await object.run()).toThrow(Error);

// run() -> this.handler() -> this.validate() -> this.getObject()

this.getObject() returns false, which in turn means this.validate() is false, and so one of the conditions inside this.handler fails, resulting in a throw.

The throw works as expected, but my current test does not pass.

Typically, how can one test that a private method, triggered eventually by a public method, throws?