问:
using google signup forms using form action, how to catch error in javascript
I have a form like this that submits an email address to a 3rd party provider like this.

```<code><form action="https://gmail.us11.list-manage.com/subscribe/post?u=XXXXXX" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll" style="display: flex;flex-direction: row;">
        <div class="mc-field-group">
            <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
            <span id="mce-EMAIL-HELPERTEXT" class="helper_text"></span>

        </div>
        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_fb16c0b54b243c41cf0ba431c_6cbe3da72c" tabindex="-1" value=""></div>
        <div class="optionalParent">
            <div class="clear foot">
                <button type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="rehab-btn-secondary">Send</button>
            </div>
        </div>
    </div>
</form>
</code>```

However, sometimes when user input an invalid email format like say "test@test", I need to handle the error coming from the external API, right now it just display on the mce-EMAIL-HELPERTEXT but my issue is the error returned by them is kind of long and messes up the formatting and I want to catch the error so I can custom format it on my page.

Any idea how to do it?

Body:
I have a form like this that submits an email address to a 3rd party provider like this.

<form action="https://gmail.us11.list-manage.com/subscribe/post?u=XXXXXX" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

            <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

<input type="text" name="b_fb16c0b54b243c41cf0ba431c_6cbe3da72c" tabindex="-1" value="">

                <button type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="rehab-btn-secondary">Send</button>

</form>

However, sometimes when user input an invalid email format like say "test@test", I need to handle the error coming from the external API, right now it just display on the mce-EMAIL-HELPERTEXT but my issue is the error returned by them is kind of long and messes up the formatting and I want to catch the error so I can custom format it on my page.

Any idea how to do it?


来源: stackexchange

问:
Object of class DateTime could not be converted to string Typo3
I have a table filled with DateTime values in the format of 2022-12-08 in a field called date.

I got all the values with findAll() function but I can't display the date value event by using

```<code><div class="event-date"><f:format.date format="%d %B %Y">{event.date}</f:format.date></div>
</code>```

my tca:

```<code>'date' => [
   'exclude' => true,
   'label' => 'LLL:EXT:events/Resources/Private/Language/locallang_db.xlf:tx_events_domain_model_event.date',
   'config' => [
      'dbType' => 'date',
      'type' => 'input',
      'renderType' => 'inputDateTime',
      'size' => 7,
      'eval' => 'date',
      'default' => null,
   ],
],
</code>```

my model:

```<code>/**
     * Returns the date
     *
     * @return \DateTime $date
     */
    public function getDate()
    {
        $date = $this->date;
    if($date) {
        $date->setTimezone(new \DateTimeZone('UTC'));
    }
    return $date;
    }

    /**
     * Sets the date
     *
     * @param \DateTime $date
     * @return void
     */
    public function setDate(\DateTime $date)
    {
        $this->date = $date;
    }

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table filled with DateTime values in the format of 2022-12-08 in a field called date.

I got all the values with findAll() function but I can't display the date value event by using

<f:format.date format="%d %B %Y">{event.date}</f:format.date>

my tca:

'date' => [
   'exclude' => true,
   'label' => 'LLL:EXT:events/Resources/Private/Language/locallang_db.xlf:tx_events_domain_model_event.date',
   'config' => [
      'dbType' => 'date',
      'type' => 'input',
      'renderType' => 'inputDateTime',
      'size' => 7,
      'eval' => 'date',
      'default' => null,
   ],
],

my model:

/**
     * Returns the date
     *
     * @return \DateTime $date
     */
    public function getDate()
    {
        $date = $this->date;
    if($date) {
        $date->setTimezone(new \DateTimeZone('UTC'));
    }
    return $date;
    }

    /**
     * Sets the date
     *
     * @param \DateTime $date
     * @return void
     */
    public function setDate(\DateTime $date)
    {
        $this->date = $date;
    }


问:
Angular15-Unit Test : Reactive FormGroup.value not reflected appropriately, after setting value to HTML Input via querySelector('#searchInput')

/** component.ts file */

import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-typeahead',
  templateUrl: './typeahead.component.html',
  styleUrls: ['./typeahead.component.scss']
})
export class TypeaheadComponent implements OnInit {

  constructor(private fb: FormBuilder, private service: DataFetchService) { }
  searchForm!: FormGroup;

  ngOnInit(): void {

    this.searchForm = this.fb.group({
      'searchInput': ['', Validators.required]
    })

  }
}

/** component.spec.ts UNIT TESTING file */

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { TypeaheadComponent } from './typeahead.component';

describe('TypeaheadComponent', () => {
  let component: TypeaheadComponent;
  let fixture: ComponentFixture<TypeaheadComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({

      imports: [
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [TypeaheadComponent]
    })
      .compileComponents();

    fixture = TestBed.createComponent(TypeaheadComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  afterAll(() => {
    fixture.destroy();
    TestBed.resetTestingModule();
  });

  it('Form controls into FormGroup', () => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const searchElement = fixture.nativeElement.querySelector('#searchInput');
      searchElement.value = "Goog";
      searchElement.dispatchEvent(new Event('input'));

      fixture.detectChanges();
      fixture.whenStable().then(() => {
        expect(component.searchForm.value).toEqual({ searchInput: 'Goog' });

        /** form
         * Chrome 108.0.0.0 (Windows 10) ERROR
            An error was thrown in afterAll
            Expected '' to equal 'Goog'.
                at <Jasmine>
         */
      })
    });
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- component template file -->

<div>
    <form [formGroup]="searchForm">
        <input type="text" class="searchInputStyle" formControlName="searchInput" id="searchInput" />
    </form>

</div></code>```

Error Getting when $>ng test

````
Chrome 108.0.0.0 (Windows 10) ERROR
An error was thrown in afterAll
**  Expected $.searchInput = '' to equal 'Goog'.
at <Jasmine>**
at apply (http://localhost:9876/_karma_webpack_/webpack:/src/app/typeahead/typeahead.component.spec.ts:40:44)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:375:26)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:39)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:374:52)
Chrome 108.0.0.0 (Windows 10): Executed 1 of 2 ERROR (0 secs / 0.033 secs)
Chrome 108.0.0.0 (Windows 10) ERROR
An error was thrown in afterAll
Expected $.searchInput = '' to equal 'Goog'.
at <Jasmine>
at apply (http://localhost:9876/_karma_webpack_/webpack:/src/app/typeahead/typeahead.component.spec.ts:40:44)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:375:26)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:39)
Chrome 108.0.0.0 (Windows 10): Executed 1 of 2 ERROR (0.119 secs / 0.033 secs)`
```

Tried googling similar on Stack overflow example and also followed following youtube
https://www.youtube.com/watch?v=Tam0ruVGcnk

my code is exactly the same, but still formGroup value is {searchInput:''}
however expecting to get {searchInput:'Goog'}

Body:
/** component.ts file */

import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-typeahead',
  templateUrl: './typeahead.component.html',
  styleUrls: ['./typeahead.component.scss']
})
export class TypeaheadComponent implements OnInit {

  constructor(private fb: FormBuilder, private service: DataFetchService) { }
  searchForm!: FormGroup;

  ngOnInit(): void {

    this.searchForm = this.fb.group({
      'searchInput': ['', Validators.required]
    })

  }
}

/** component.spec.ts UNIT TESTING file */

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { TypeaheadComponent } from './typeahead.component';

describe('TypeaheadComponent', () => {
  let component: TypeaheadComponent;
  let fixture: ComponentFixture<TypeaheadComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({

      imports: [
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [TypeaheadComponent]
    })
      .compileComponents();

    fixture = TestBed.createComponent(TypeaheadComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  afterAll(() => {
    fixture.destroy();
    TestBed.resetTestingModule();
  });

  it('Form controls into FormGroup', () => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const searchElement = fixture.nativeElement.querySelector('#searchInput');
      searchElement.value = "Goog";
      searchElement.dispatchEvent(new Event('input'));

      fixture.detectChanges();
      fixture.whenStable().then(() => {
        expect(component.searchForm.value).toEqual({ searchInput: 'Goog' });

        /** form
         * Chrome 108.0.0.0 (Windows 10) ERROR
            An error was thrown in afterAll
            Expected '' to equal 'Goog'.
                at <Jasmine>
         */
      })
    });
  });

});

    <form [formGroup]="searchForm">
        <input type="text" class="searchInputStyle" formControlName="searchInput" id="searchInput" />
    </form>

Error Getting when $>ng test

````
Chrome 108.0.0.0 (Windows 10) ERROR
An error was thrown in afterAll
**  Expected $.searchInput = '' to equal 'Goog'.
at <Jasmine>**
at apply (http://localhost:9876/_karma_webpack_/webpack:/src/app/typeahead/typeahead.component.spec.ts:40:44)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:375:26)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:39)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:374:52)
Chrome 108.0.0.0 (Windows 10): Executed 1 of 2 ERROR (0 secs / 0.033 secs)
Chrome 108.0.0.0 (Windows 10) ERROR
An error was thrown in afterAll
Expected $.searchInput = '' to equal 'Goog'.
at <Jasmine>
at apply (http://localhost:9876/_karma_webpack_/webpack:/src/app/typeahead/typeahead.component.spec.ts:40:44)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:375:26)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:39)
Chrome 108.0.0.0 (Windows 10): Executed 1 of 2 ERROR (0.119 secs / 0.033 secs)`
```

Tried googling similar on Stack overflow example and also followed following youtube
https://www.youtube.com/watch?v=Tam0ruVGcnk

my code is exactly the same, but still formGroup value is {searchInput:''}
however expecting to get {searchInput:'Goog'}


问:
Prebid.js and Nextjs set-up
I'm trying to set-up prebid.js ( npm package ) with nextjs projec.

Following example from ( https://www.npmjs.com/package/prebid.js ) by extending webpack config in next.config.js:

```<code>let path = require("path")

module.exports = {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }) => {

    config.module.rules.push({
      test: /.js$/,
      include: new RegExp(`\\${path.sep}prebid\\.js`),
      use: [
        {
          loader: "babel-loader",
          options: require("prebid.js/.babelrc.js"),
        },
      ],
    })

    return config
  },
}

</code>```

after this while trying to import prebid.js facing this error:

```<code>import {getGlobal} from './prebidGlobal.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
</code>```

Same error accurs even without webpack set-up. SO most likely that is incorrect, anyone would know how to set-up this?

versions:
Nextjs "12.2.2"
React "^17.0.2"

fresh install, no additional libraries.

I can run prebid.js by importing external script. Or using pure react with prebidjs.
But doing that with nextjs does not work.

Title: Prebid.js and Nextjs set-up

Body:
I'm trying to set-up prebid.js ( npm package ) with nextjs projec.

Following example from ( https://www.npmjs.com/package/prebid.js ) by extending webpack config in next.config.js:

let path = require("path")

module.exports = {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }) => {

    config.module.rules.push({
      test: /.js$/,
      include: new RegExp(`\\${path.sep}prebid\\.js`),
      use: [
        {
          loader: "babel-loader",
          options: require("prebid.js/.babelrc.js"),
        },
      ],
    })

    return config
  },
}

after this while trying to import prebid.js facing this error:

import {getGlobal} from './prebidGlobal.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Same error accurs even without webpack set-up. SO most likely that is incorrect, anyone would know how to set-up this?

versions:
Nextjs "12.2.2"
React "^17.0.2"

fresh install, no additional libraries.

I can run prebid.js by importing external script. Or using pure react with prebidjs.
But doing that with nextjs does not work.


问:
OpenVswitch & Ipsec
How can I check if our OVS setup can handle ipsec feature , is there any ovs command to check that ?
from docker hub i did pull for image openvswitch/ovs , and I want to know if it support ipsec config.</p>

Title: OpenVswitch & Ipsec


问:
Converting a pandas dataframe to numpy array changes the data type to object
I have a pandas dataframe like below

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

data = {'A': ['A', 'B', 'C', 'D', 'E'], 'B': [1, 2, 3, 4, 5], 'C': [3, 4, 5, 6, 7],
'D': ['N', 'G', 'S', 'P', 'Q']}
df = pd.DataFrame(data)
print(df)

   A  B  C  D
0  A  1  3  N
1  B  2  4  G
2  C  3  5  S
3  D  4  6  P
4  E  5  7  Q

</code>```

Now when I check the data types of pandas dataframe, I see that two columns are of int data type and the other two columns are of object data type

```<code>
print(df.dtypes)

A    object
B     int64
C     int64
D    object
dtype: object

</code>```

When I convert the entire dataframe to a numpy array using the below code and then check the data type of each column it is of object data type.

```<code>X = np.array(df)

print(X.dtype)
object

print(X[:,1].dtype)
object

print(X[:,2].dtype)
object

print(X[:,3].dtype)
object

print(X[:,4].dtype)
object

</code>```

The question is, is there a way to keep the data types of NumPy arrays same as that of the original pandas data frame?

Body:
I have a pandas dataframe like below

import pandas as pd
import numpy as np

data = {'A': ['A', 'B', 'C', 'D', 'E'], 'B': [1, 2, 3, 4, 5], 'C': [3, 4, 5, 6, 7],
'D': ['N', 'G', 'S', 'P', 'Q']}
df = pd.DataFrame(data)
print(df)

   A  B  C  D
0  A  1  3  N
1  B  2  4  G
2  C  3  5  S
3  D  4  6  P
4  E  5  7  Q

Now when I check the data types of pandas dataframe, I see that two columns are of int data type and the other two columns are of object data type

print(df.dtypes)

A    object
B     int64
C     int64
D    object
dtype: object

When I convert the entire dataframe to a numpy array using the below code and then check the data type of each column it is of object data type.

X = np.array(df)

print(X.dtype)
object

print(X[:,1].dtype)
object

print(X[:,2].dtype)
object

print(X[:,3].dtype)
object

print(X[:,4].dtype)
object

The question is, is there a way to keep the data types of NumPy arrays same as that of the original pandas data frame?


问:
How to include properly main bootstrap file and rtl support file?
I am working on a project with pure html css and javascript. I am using bootstrap 5 and because I had to customize it I have download the bootstrap.scss file and then I have my main.scss file where I override the colors/ and other variables and in the end of the file I import the boostrap.scss. I am using sass to build the file and outputs a main.css
In boostrap 5 docs they mentioned that rtl support is possible by using rtlcss tool to generate a rtl file from the main file.
I am using rtlcss cli to generate the .rtl file like

```<code>rtlcss main.css main.rtl.css
</code>```

And now I have a main.css and main.rtl.css.
If I only link one of the files in html like

```<code><link rel="stylesheet" href="main.css" type="text/css"/>
</code>```

or if I had the dir="rtl" to the html tag

```<code><html dir="rtl">
</code>```

And instead of linking the main css I link the main.rtl.css

```<code> <link rel="stylesheet" href="main.rtl.css" type="text/css"/>
</code>```

The page looks but the problem is how do I know which file to link?
linking both files causes problems because both files apply at the same time.
So I used javascript to check for the dir attribute in html and if it is ltr link the main.css otherwise link the main.rtl.css.
Which is working but with a problem.
When I first open the html file in browser the content jumps.
I tried including the script both in bottom of the body or in the head, while including it in the head has slightly better results you can still see the content jumping a little.
I don't know what I should do anything else.

Here is the javascript script used for loading the css:

```<code>(function () {
  const html = document.querySelector('html')
  const head = document.querySelector('head')
  const dir = html.getAttribute('dir')
  const link = document.createElement('link')
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('type', 'text/css')
  const cssRootPath = getCssRootPath()
  if (dir === 'rtl') {
    link.setAttribute('href', cssRootPath + 'css/main.rtl.css')
  } else {
    link.setAttribute('href', cssRootPath + 'css/main.css')
  }
  head.appendChild(link)

  function getCssRootPath() {
    if (globalThis.location.origin === 'file://') return ''
    const nested = globalThis.location.pathname.split('/').length - 2
    let path = ''
    for (let i = 0; i < nested; i++) {
      path += '../'
    }
    return path
  }
})()
</code>```

Body:
I am working on a project with pure html css and javascript. I am using bootstrap 5 and because I had to customize it I have download the bootstrap.scss file and then I have my main.scss file where I override the colors/ and other variables and in the end of the file I import the boostrap.scss. I am using sass to build the file and outputs a main.css
In boostrap 5 docs they mentioned that rtl support is possible by using rtlcss tool to generate a rtl file from the main file.
I am using rtlcss cli to generate the .rtl file like

rtlcss main.css main.rtl.css

And now I have a main.css and main.rtl.css.
If I only link one of the files in html like

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

or if I had the dir="rtl" to the html tag

And instead of linking the main css I link the main.rtl.css

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

The page looks but the problem is how do I know which file to link?
linking both files causes problems because both files apply at the same time.
So I used javascript to check for the dir attribute in html and if it is ltr link the main.css otherwise link the main.rtl.css.
Which is working but with a problem.
When I first open the html file in browser the content jumps.
I tried including the script both in bottom of the body or in the head, while including it in the head has slightly better results you can still see the content jumping a little.
I don't know what I should do anything else.

Here is the javascript script used for loading the css:

(function () {
  const html = document.querySelector('html')
  const head = document.querySelector('head')
  const dir = html.getAttribute('dir')
  const link = document.createElement('link')
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('type', 'text/css')
  const cssRootPath = getCssRootPath()
  if (dir === 'rtl') {
    link.setAttribute('href', cssRootPath + 'css/main.rtl.css')
  } else {
    link.setAttribute('href', cssRootPath + 'css/main.css')
  }
  head.appendChild(link)

  function getCssRootPath() {
    if (globalThis.location.origin === 'file://') return ''
    const nested = globalThis.location.pathname.split('/').length - 2
    let path = ''
    for (let i = 0; i < nested; i++) {
      path += '../'
    }
    return path
  }
})()


问:
How to use a multi-module setup in maven?
In Parent component, I am adding child modules inside  tag.

```<code><!-- Parent pom.xml -->
<groupId>com.acc.app</groupId>
<artifactId>parent</artifactId>
<version>1.0</version>

<modules>
 <module>../child1/pom.xml</module>
 <module>../child2.pom.xml</module>
</modules>
</code>```

Where child1 and child2 are different packages outside Parent.

The purpose is that when I build parent, all children should also build automatically. In my local I am able to build Parent and all children but getting an error in Jenkins server.

Error: child1/pom.xml does not exist.
child2/pom.xml does not exist.

Body:
In Parent component, I am adding child modules inside  tag.

<groupId>com.acc.app</groupId>
<artifactId>parent</artifactId>
<version>1.0</version>

<modules>
 <module>../child1/pom.xml</module>
 <module>../child2.pom.xml</module>
</modules>

Where child1 and child2 are different packages outside Parent.

The purpose is that when I build parent, all children should also build automatically. In my local I am able to build Parent and all children but getting an error in Jenkins server.

Error: child1/pom.xml does not exist.
child2/pom.xml does not exist.


问:
How to convert png images to a HEVC(h265) video with alpha
I want to convert a sequence of png images to a HEVC video with alpha, I would like to use ffmpeg to do this work and find the following command(images name are p01.png, p02.png...):

```<code>ffmpeg -framerate 10 -i p%02d.png -c:v hevc_videotoolbox -require_sw 1 -allow_sw 1 -alpha_quality 0.5 -vtag hvc1 hevc.mov
</code>```

the print is here:

```<code>ffmpeg version 5.1.2 Copyright (c) 2000-2022 the FFmpeg developers
  built with Apple clang version 14.0.0 (clang-1400.0.29.202)
  configuration: --prefix=/opt/homebrew/Cellar/ffmpeg/5.1.2_1 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-videotoolbox --enable-neon
  libavutil      57. 28.100 / 57. 28.100
  libavcodec     59. 37.100 / 59. 37.100
  libavformat    59. 27.100 / 59. 27.100
  libavdevice    59.  7.100 / 59.  7.100
  libavfilter     8. 44.100 /  8. 44.100
  libswscale      6.  7.100 /  6.  7.100
  libswresample   4.  7.100 /  4.  7.100
  libpostproc    56.  6.100 / 56.  6.100
Input #0, image2, from 'p%02d.png':
  Duration: 00:00:09.60, start: 0.000000, bitrate: N/A
  Stream #0:0: Video: png, rgba(pc), 375x812 [SAR 3779:3779 DAR 375:812], 10 fps, 10 tbr, 10 tbn
Stream mapping:
  Stream #0:0 -> #0:0 (png (native) -> hevc (hevc_videotoolbox))
Press [q] to stop, [?] for help
[1]    16348 trace trap  ffmpeg -framerate 10 -i p%02d.png -c:v hevc_videotoolbox -require_sw 1  1  0.
</code>```

It seems like there is no error and the video has been generated but the size of video is always  0kb, I try to change the parameter for command but nothing changed, so is there something working with the command? or Is there is a simple way to create the HEVC video using png image? Thanks

My Environment:
Apple silicon(MacBook with M1 Pro clip) Mac OS 13.0
ffmpeg: 5.1.2

Body:
I want to convert a sequence of png images to a HEVC video with alpha, I would like to use ffmpeg to do this work and find the following command(images name are p01.png, p02.png...):

ffmpeg -framerate 10 -i p%02d.png -c:v hevc_videotoolbox -require_sw 1 -allow_sw 1 -alpha_quality 0.5 -vtag hvc1 hevc.mov

the print is here:

ffmpeg version 5.1.2 Copyright (c) 2000-2022 the FFmpeg developers
  built with Apple clang version 14.0.0 (clang-1400.0.29.202)
  configuration: --prefix=/opt/homebrew/Cellar/ffmpeg/5.1.2_1 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-videotoolbox --enable-neon
  libavutil      57. 28.100 / 57. 28.100
  libavcodec     59. 37.100 / 59. 37.100
  libavformat    59. 27.100 / 59. 27.100
  libavdevice    59.  7.100 / 59.  7.100
  libavfilter     8. 44.100 /  8. 44.100
  libswscale      6.  7.100 /  6.  7.100
  libswresample   4.  7.100 /  4.  7.100
  libpostproc    56.  6.100 / 56.  6.100
Input #0, image2, from 'p%02d.png':
  Duration: 00:00:09.60, start: 0.000000, bitrate: N/A
  Stream #0:0: Video: png, rgba(pc), 375x812 [SAR 3779:3779 DAR 375:812], 10 fps, 10 tbr, 10 tbn
Stream mapping:
  Stream #0:0 -> #0:0 (png (native) -> hevc (hevc_videotoolbox))
Press [q] to stop, [?] for help
[1]    16348 trace trap  ffmpeg -framerate 10 -i p%02d.png -c:v hevc_videotoolbox -require_sw 1  1  0.

It seems like there is no error and the video has been generated but the size of video is always  0kb, I try to change the parameter for command but nothing changed, so is there something working with the command? or Is there is a simple way to create the HEVC video using png image? Thanks

My Environment:
Apple silicon(MacBook with M1 Pro clip) Mac OS 13.0
ffmpeg: 5.1.2


问:
How to find client_device_id and client_wallet_account_id for adding a credit card into google pay wallet in flutter?
I want to add a credit card into Google Pay wallet in flutter.
I need these information client_device_id and client_wallet_account_id.

client_wallet_account_id is a stable identifier for a physical Android device.

client_wallet_account_id is an unique 24-byte identifier for each instance of a [Android user, Google account] pair.

How I can find these informations in flutter ?

Thank you for your reading.


问:
"Error in file(file, "rt") : invalid 'description' argument" when using paste0 in the read.table inside of the loop
I would like to read different txt file in different folders that I put them inside of my loop,
"

```<code>mainpath <- "/YAS/CV/lp21/0.1"
fold<-c("F1","F2","F3","F4","F5")

  for(result in fold){
    foldpath<- file.path(mainpath,result)
    setwd(foldpath)

      sol<-read.table(file.path(foldpath,paste0("dmu_",n,".SOL")),sep = ",",header = F)}}" but I faced this error. "
</code>```

Error in file(file, "rt") : invalid 'description' argument"
I know it is because of paste0 but I do not know how to solve it.
Thanks in advance.

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

I know this error is because of paste0 but I do not know how to solve it.

Body:
I would like to read different txt file in different folders that I put them inside of my loop,
"

mainpath <- "/YAS/CV/lp21/0.1"
fold<-c("F1","F2","F3","F4","F5")

  for(result in fold){
    foldpath<- file.path(mainpath,result)
    setwd(foldpath)

      sol<-read.table(file.path(foldpath,paste0("dmu_",n,".SOL")),sep = ",",header = F)}}" but I faced this error. "

Error in file(file, "rt") : invalid 'description' argument"
I know it is because of paste0 but I do not know how to solve it.
Thanks in advance.

I know this error is because of paste0 but I do not know how to solve it.


问:
Getting this error while deploying filebeat "Exiting: No outputs are defined. Please define one under the output section."
I am trying to deploy filebeat in one cluster and trying to send the logs into another cluster which has elastic search and kibana installed in it.
This is my yml file
`

```<code>---
apiVersion: beat.k8s.elastic.co/v1beta1
kind: Beat
metadata:
  name: es-beats
  namespace: elastic
spec:
  type: filebeat
  version: 7.12.1
  elasticsearchRef:
    name: elastic
  config:
    filebeat.inputs:
    - type: container
      paths:
      - /var/log/containers/*.log
    - output.elasticsearch:
      # Array of hosts to connect to.
      hosts: ["https://<my-other-cluster-ip>:9200"]

      # Protocol - either `http` (default) or `https`.
      protocol: "https"

      username: "elastic"
      password: "mypass"
    - setup.kibana:
      host: "https://<my-other-cluster-ip>:9200"
      username: "elastic"
      password: "mypass"
  daemonSet:
    podTemplate:
      spec:
        dnsPolicy: ClusterFirstWithHostNet
        hostNetwork: true
        securityContext:
          runAsUser: 0
        containers:
        - name: filebeat
          volumeMounts:
          - name: varlogcontainers
            mountPath: /var/log/containers
          - name: varlogpods
            mountPath: /var/log/pods
          - name: varlibdockercontainers
            mountPath: /var/lib/docker/containers
        volumes:
        - name: varlogcontainers
          hostPath:
            path: /var/log/containers
        - name: varlogpods
          hostPath:
            path: /var/log/pods
        - name: varlibdockercontainers
          hostPath:
            path: /var/lib/docker/containers
</code>```

`

beats is successfully installed and when i apply this file everything works fine but the pods don't get deployed and when I get pods the status says CrashLoopBackOff

I deployed the beats using k8 operators and want to get the logs into the other cluster I read the documentation but I am confused where do I enter the elasticsearch host and kibana host name and pass and what shall the output be.

Body:
I am trying to deploy filebeat in one cluster and trying to send the logs into another cluster which has elastic search and kibana installed in it.
This is my yml file
`

---
apiVersion: beat.k8s.elastic.co/v1beta1
kind: Beat
metadata:
  name: es-beats
  namespace: elastic
spec:
  type: filebeat
  version: 7.12.1
  elasticsearchRef:
    name: elastic
  config:
    filebeat.inputs:
    - type: container
      paths:
      - /var/log/containers/*.log
    - output.elasticsearch:
      # Array of hosts to connect to.
      hosts: ["https://<my-other-cluster-ip>:9200"]

      # Protocol - either `http` (default) or `https`.
      protocol: "https"

      username: "elastic"
      password: "mypass"
    - setup.kibana:
      host: "https://<my-other-cluster-ip>:9200"
      username: "elastic"
      password: "mypass"
  daemonSet:
    podTemplate:
      spec:
        dnsPolicy: ClusterFirstWithHostNet
        hostNetwork: true
        securityContext:
          runAsUser: 0
        containers:
        - name: filebeat
          volumeMounts:
          - name: varlogcontainers
            mountPath: /var/log/containers
          - name: varlogpods
            mountPath: /var/log/pods
          - name: varlibdockercontainers
            mountPath: /var/lib/docker/containers
        volumes:
        - name: varlogcontainers
          hostPath:
            path: /var/log/containers
        - name: varlogpods
          hostPath:
            path: /var/log/pods
        - name: varlibdockercontainers
          hostPath:
            path: /var/lib/docker/containers

`

beats is successfully installed and when i apply this file everything works fine but the pods don't get deployed and when I get pods the status says CrashLoopBackOff

I deployed the beats using k8 operators and want to get the logs into the other cluster I read the documentation but I am confused where do I enter the elasticsearch host and kibana host name and pass and what shall the output be.


问:
Connecting VScode tasks with bash.rc
So I'm developing remotely a C++ application in VSCode to a linux machine and I have a lot of environment variables defined in my bash.rc file. on the terminal in VScode everything works well but I wanted to integrate it further with the editor so I created a few tasks, for example

```<code>        {
            "label": "build",
            "type": "shell",
            "command": "cd ${workspaceFolder}/THING/build && cmake -G Ninja ${workspaceFolder}/THING/ && ninja -j 100 install"
        }

</code>```

I wouldn't wanna add source bash.rc to every task, so is there a way to configure VScode to do this automatically somehow?

Also, would VScode's debugger work in a remote session?

Title: Connecting VScode tasks with bash.rc

Body:
So I'm developing remotely a C++ application in VSCode to a linux machine and I have a lot of environment variables defined in my bash.rc file. on the terminal in VScode everything works well but I wanted to integrate it further with the editor so I created a few tasks, for example

        {
            "label": "build",
            "type": "shell",
            "command": "cd ${workspaceFolder}/THING/build && cmake -G Ninja ${workspaceFolder}/THING/ && ninja -j 100 install"
        }

I wouldn't wanna add source bash.rc to every task, so is there a way to configure VScode to do this automatically somehow?

Also, would VScode's debugger work in a remote session?


问:
AssemblyInitialize seems break unit test project in .net 6 (visual studio 2022)
I have a .net 4.8 unit test project and just migrated it to .net 6.

Although Test explorer shows all tests, when I try to run it in Visual Studio, it just doesn't run anything.
What I found is that as soon as my unit test project contains this AssemblyInitialize attribute, Visual studio just won't run any of the tests.

```<code>[TestClass]
public class SetupAssemblyInitializer
{
    [AssemblyInitialize]
    public static void AssemblyInit(TestContext context)
    {
    }
}
</code>```

This works fine as long as the project is in .net 4.8 and I didn't find any doc saying this attribute doesn't work in .net 6 any more. Is there any workaround or alternative to run some code only once in my Unit Test project?

If I decorate the method with [ClassInitialize], then the project will run without issue. However, this Attribute will not make the method run only once for all tests.

Body:
I have a .net 4.8 unit test project and just migrated it to .net 6.

Although Test explorer shows all tests, when I try to run it in Visual Studio, it just doesn't run anything.
What I found is that as soon as my unit test project contains this AssemblyInitialize attribute, Visual studio just won't run any of the tests.

[TestClass]
public class SetupAssemblyInitializer
{
    [AssemblyInitialize]
    public static void AssemblyInit(TestContext context)
    {
    }
}

This works fine as long as the project is in .net 4.8 and I didn't find any doc saying this attribute doesn't work in .net 6 any more. Is there any workaround or alternative to run some code only once in my Unit Test project?

If I decorate the method with [ClassInitialize], then the project will run without issue. However, this Attribute will not make the method run only once for all tests.


问:
How to generate javascript file, which can be loaded via script tag by a non nextjs web page
In my current project we are migrating an application to nextjs. Now I would like to inject a react component into a legacy page through including a script, which is using code from the new nextjs application. Her a simplified version of the script:

function injectCode() {
  const container = document.getElementById("container")
  const reactRoot = createRoot(container)

  reactRoot.render(<ExistingComponent />)
}

document.addEventListener('load', injectCode)

```
<p>How can I generate a js file, that can be included into a webpage not rendered by nextjs? Best would be to generate the file with <code>next build</code>, but directly running webpack would be ok as well.</p>
<p>Until now I tried to write my own webpack config and just run webpack directly. It would be ok if I run webpack once and check the generated file into git. Therefore the generated file is put into the public folder.
This is not the only webpack config I tried, but after too many iterations solving one problem and getting the next I gave up thinking there is probably an easier solution.</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  entry: './script.tsx',
  module: {
    rules: [
      {
        test: /\.(ts|tsx)?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, 'lib'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, 'components'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, 'single-header-footer'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(js)?$/,
        include: path.resolve(__dirname, 'node-modules'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'next-js-component.js',
  },
}
</code>```

I am probably missing a lot of settings which are required.

The second thing I tried was extending the webpack configuration within the next.config.js file:

...
webpack: (config, { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }) => {
  const originalEntry = config.entry

  config.entry = async () => {
    const entries = await originalEntry()
    entries['next-js-component'] = ['script.tsx']
    return entries
  }
  return config
},
...
```

This creates a chunk file .next/static/chunks/next-js-component-dc0ae8d2d7a87ec9.js. But I don't know how to use this file. Probably I need to add some other code into the page which loads the created chunk and additional chunks.

The header and footer of the legacy pages are already rendered by the next.js app and are included into the page via server side include. So I might be able to use something like the HtmlWebpackPlugin to inject the correct script tag into the header, which is then included into the legacy page.

Body:
In my current project we are migrating an application to nextjs. Now I would like to inject a react component into a legacy page through including a script, which is using code from the new nextjs application. Her a simplified version of the script:

function injectCode() {
  const container = document.getElementById("container")
  const reactRoot = createRoot(container)

  reactRoot.render(<ExistingComponent />)
}

document.addEventListener('load', injectCode)

How can I generate a js file, that can be included into a webpage not rendered by nextjs? Best would be to generate the file with next build, but directly running webpack would be ok as well.

Until now I tried to write my own webpack config and just run webpack directly. It would be ok if I run webpack once and check the generated file into git. Therefore the generated file is put into the public folder.
This is not the only webpack config I tried, but after too many iterations solving one problem and getting the next I gave up thinking there is probably an easier solution.

module.exports = {
  entry: './script.tsx',
  module: {
    rules: [
      {
        test: /\.(ts|tsx)?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, 'lib'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, 'components'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, 'single-header-footer'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(js)?$/,
        include: path.resolve(__dirname, 'node-modules'),
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'next-js-component.js',
  },
}

I am probably missing a lot of settings which are required.

The second thing I tried was extending the webpack configuration within the next.config.js file:

...
webpack: (config, { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }) => {
  const originalEntry = config.entry

  config.entry = async () => {
    const entries = await originalEntry()
    entries['next-js-component'] = ['script.tsx']
    return entries
  }
  return config
},
...

This creates a chunk file .next/static/chunks/next-js-component-dc0ae8d2d7a87ec9.js. But I don't know how to use this file. Probably I need to add some other code into the page which loads the created chunk and additional chunks.

The header and footer of the legacy pages are already rendered by the next.js app and are included into the page via server side include. So I might be able to use something like the HtmlWebpackPlugin to inject the correct script tag into the header, which is then included into the legacy page.


问:
Material dialog overlay changes
When using the Angular material dialog i want to move the scrollbar from inside the dialog to the overlay. If i inspect the overlay in HTML i see that it has the following css on it:

I want to set pointer-events to auto and add a overflow-y: auto as well but i cant seem to access the class in my css. Does anyone know if / how we can change the overlay in a dialog?

Code:

```<code>modalConfig: MatDialogConfig = {
panelClass: 'custom-dialog',
</code>```

CSS:

```<code>.custom-dialog {
  min-width: 860px;
  max-width: 860px;
  height: max-content;

  .cdk-overlay-container,
  .cdk-global-overlay-wrapper {
    pointer-events: auto !important;
    overflow-y: auto !important;
  }
}
</code>```

p.s. tried ::ng-deep but it doesn't seem to work

Title: Material dialog overlay changes

Body:
When using the Angular material dialog i want to move the scrollbar from inside the dialog to the overlay. If i inspect the overlay in HTML i see that it has the following css on it:

I want to set pointer-events to auto and add a overflow-y: auto as well but i cant seem to access the class in my css. Does anyone know if / how we can change the overlay in a dialog?

Code:

modalConfig: MatDialogConfig = {
panelClass: 'custom-dialog',

CSS:

.custom-dialog {
  min-width: 860px;
  max-width: 860px;
  height: max-content;

  .cdk-overlay-container,
  .cdk-global-overlay-wrapper {
    pointer-events: auto !important;
    overflow-y: auto !important;
  }
}

p.s. tried ::ng-deep but it doesn't seem to work


问:
System tray application would detect hotkey with PyQt5 - QSystemTrayIcon
I want to create an application with a system tray icon. This app should detect the hotkey and react to it, even if the app is not focused (icon tray).

Example: I want to show the window, then I press Alt + X. The window is showing.

I tried using some global hotkey libraries but whenever the window is showing by hotkey, it freezes. The Show option in my QMenu still working.

I'm new to programming, thanks!

Here is my code:

```<code>from PyQt5.QtCore import QSize, Qt
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QWidget, QSystemTrayIcon, QMenu
from PyQt5.QtGui import QIcon, QKeySequence

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('GTyperP5')
        self.setWindowIcon(QIcon('GTyperP5.ico'))
        self.setFixedSize(QSize(192, 64))
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, False)

        self.textInput = QLineEdit()

        self.typeButton = QPushButton('Type')
        self.typeButton.setFixedSize(QSize(50, 25))
        self.typeButton.clicked.connect(self.cut_all)

        self.textInput.returnPressed.connect(self.typeButton.click)

        self.cancelButton = QPushButton('Cancel')
        self.cancelButton.setFixedSize(QSize(50, 25))
        self.cancelButton.clicked.connect(self.hide_window)

        layout = QVBoxLayout()
        layout.addWidget(self.textInput, alignment = Qt.AlignHCenter | Qt.AlignTop)

        layout_ex = QHBoxLayout()
        layout_ex.addWidget(self.cancelButton, alignment = Qt.AlignRight)
        layout_ex.addWidget(self.typeButton, alignment = Qt.AlignLeft)

        layout.addLayout(layout_ex)

        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)

        self.trayIcon = QSystemTrayIcon(QIcon('GTyperP5.ico'), parent = app)
        self.trayIcon.setToolTip('GTyperP5')

        menu = QMenu()
        showAction = menu.addAction('Show')
        showAction.triggered.connect(self.show_window)

        exitAction = menu.addAction('Exit')
        exitAction.triggered.connect(app.quit)

        self.trayIcon.setContextMenu(menu)
        self.trayIcon.show()
        self.trayIcon.showMessage('GTyperP5 has started!', 'Thank you for using! :D', QIcon('GTyperP5.ico'), msecs = 10000)
        self.trayIcon.activated.connect(self.doubleClick)

    def closeEvent(self, event):
        self.hide_window()
        event.ignore()

    def doubleClick(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show_window()

    def cut_all(self):
        clip = QApplication.clipboard()
        clip.clear(mode = clip.Clipboard)
        clip.setText(self.textInput.text(), mode = clip.Clipboard)
        self.textInput.setText('')
        self.hide_window()

    def hide_window(self):
        self.trayIcon.show()
        self.hide()

    def show_window(self):
        self.trayIcon.hide()
        self.show()
        self.raise_()
        self.textInput.setFocus()

app = QApplication([])
window = MainWindow()
window.show()
app.exec()
</code>```

Body:
I want to create an application with a system tray icon. This app should detect the hotkey and react to it, even if the app is not focused (icon tray).

Example: I want to show the window, then I press Alt + X. The window is showing.

I tried using some global hotkey libraries but whenever the window is showing by hotkey, it freezes. The Show option in my QMenu still working.

I'm new to programming, thanks!

Here is my code:

from PyQt5.QtCore import QSize, Qt
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QWidget, QSystemTrayIcon, QMenu
from PyQt5.QtGui import QIcon, QKeySequence

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('GTyperP5')
        self.setWindowIcon(QIcon('GTyperP5.ico'))
        self.setFixedSize(QSize(192, 64))
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, False)

        self.textInput = QLineEdit()

        self.typeButton = QPushButton('Type')
        self.typeButton.setFixedSize(QSize(50, 25))
        self.typeButton.clicked.connect(self.cut_all)

        self.textInput.returnPressed.connect(self.typeButton.click)

        self.cancelButton = QPushButton('Cancel')
        self.cancelButton.setFixedSize(QSize(50, 25))
        self.cancelButton.clicked.connect(self.hide_window)

        layout = QVBoxLayout()
        layout.addWidget(self.textInput, alignment = Qt.AlignHCenter | Qt.AlignTop)

        layout_ex = QHBoxLayout()
        layout_ex.addWidget(self.cancelButton, alignment = Qt.AlignRight)
        layout_ex.addWidget(self.typeButton, alignment = Qt.AlignLeft)

        layout.addLayout(layout_ex)

        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)

        self.trayIcon = QSystemTrayIcon(QIcon('GTyperP5.ico'), parent = app)
        self.trayIcon.setToolTip('GTyperP5')

        menu = QMenu()
        showAction = menu.addAction('Show')
        showAction.triggered.connect(self.show_window)

        exitAction = menu.addAction('Exit')
        exitAction.triggered.connect(app.quit)

        self.trayIcon.setContextMenu(menu)
        self.trayIcon.show()
        self.trayIcon.showMessage('GTyperP5 has started!', 'Thank you for using! :D', QIcon('GTyperP5.ico'), msecs = 10000)
        self.trayIcon.activated.connect(self.doubleClick)

    def closeEvent(self, event):
        self.hide_window()
        event.ignore()

    def doubleClick(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show_window()

    def cut_all(self):
        clip = QApplication.clipboard()
        clip.clear(mode = clip.Clipboard)
        clip.setText(self.textInput.text(), mode = clip.Clipboard)
        self.textInput.setText('')
        self.hide_window()

    def hide_window(self):
        self.trayIcon.show()
        self.hide()

    def show_window(self):
        self.trayIcon.hide()
        self.show()
        self.raise_()
        self.textInput.setFocus()

app = QApplication([])
window = MainWindow()
window.show()
app.exec()


问:
How to trigger RedPitaya SIGNALlab 250-12 for real-time acquisition?
I'm actually working with a RedPitaya SIGNALlab 250-12 (Official page) today, and I am trying to develop a short program in Python, to acquire data, similar to oscilloscopes.

The purpose is to acquire a 1 second signal, with only a few micro-seconds of useful part, so I try to set the trigger as :

```<code>import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import csv
import time

# Initialize the connection to the RedPitaya card
rp = scpi.scpi('169.254.199.51')

# Configure the RedPitaya card for signal measurement
rp.tx_txt('ACQ:DEC 8000')
rp.tx_txt('ACQ:TRIG:EXT') # Set source 1 as trigger source
rp.tx_txt('ACQ:TRIG:EXT:LEV 0.05') # Set the trigger level to 0.05V
rp.tx_txt('ACQ:TRIG:EXT:HYST 0') # Disable hysteresis
rp.tx_txt('ACQ:TRIG:EXT:SLOP POS') # Set the trigger on rising edges
rp.tx_txt('ACQ:TRIG:EXT:DLY 1000')

# Initialize the graph
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

# Function to update the graph in real time
def update_graph(num):

    # Acquire the signal
    rp.tx_txt('ACQ:SOUR1:DATA?')
    signal = rp.rx_txt()
    signal = signal.strip('{}}.replace(" ", "").split(',')

    # Filter the signal data to keep only the valid numerical values
    signal_filtered = [x for x in signal if x.replace('.','',1).isdigit()]

    # Convert the signal data into floating point numbers
    signal_out = list(map(float, signal_filtered))
    # Update the data of the graph
    ax.clear()
    ax.plot(signal_out)

# Initialize the animation
ani = animation.FuncAnimation(fig, update_graph, interval=2000)

# Display the graph
plt.show()
</code>```

When I plot my graph, there are no differences with or without all the trigger parameters. I don't understand why. Any ideas ?

Thank you

Body:
I'm actually working with a RedPitaya SIGNALlab 250-12 (Official page) today, and I am trying to develop a short program in Python, to acquire data, similar to oscilloscopes.

The purpose is to acquire a 1 second signal, with only a few micro-seconds of useful part, so I try to set the trigger as :

import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import csv
import time

# Initialize the connection to the RedPitaya card
rp = scpi.scpi('169.254.199.51')

# Configure the RedPitaya card for signal measurement
rp.tx_txt('ACQ:DEC 8000')
rp.tx_txt('ACQ:TRIG:EXT') # Set source 1 as trigger source
rp.tx_txt('ACQ:TRIG:EXT:LEV 0.05') # Set the trigger level to 0.05V
rp.tx_txt('ACQ:TRIG:EXT:HYST 0') # Disable hysteresis
rp.tx_txt('ACQ:TRIG:EXT:SLOP POS') # Set the trigger on rising edges
rp.tx_txt('ACQ:TRIG:EXT:DLY 1000')

# Initialize the graph
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

# Function to update the graph in real time
def update_graph(num):

    # Acquire the signal
    rp.tx_txt('ACQ:SOUR1:DATA?')
    signal = rp.rx_txt()
    signal = signal.strip('{}}.replace(" ", "").split(',')

    # Filter the signal data to keep only the valid numerical values
    signal_filtered = [x for x in signal if x.replace('.','',1).isdigit()]

    # Convert the signal data into floating point numbers
    signal_out = list(map(float, signal_filtered))
    # Update the data of the graph
    ax.clear()
    ax.plot(signal_out)

# Initialize the animation
ani = animation.FuncAnimation(fig, update_graph, interval=2000)

# Display the graph
plt.show()

When I plot my graph, there are no differences with or without all the trigger parameters. I don't understand why. Any ideas ?

Thank you


问:
createTextFinder on another sheet getting wrong find
I'm using createTextFinder to search a different sheet than active and remove the row base off timeStamp. The row its deleting is the wrong row most of the time. I can't tell what the pattern is.

https://docs.google.com/spreadsheets/d/1-CgI_MigmgKBwFqA5ZhUzuTrmpLI-6emZg4FDuFwjfo/edit?usp=sharing
There's a master "Actions" list that splits off into locations sheets. When the checkbox on "E" in actions is checked the Location "G" lists should delete the row found by createTextFinder with the timeStamp in "A".

```<code> if (src.getName() != "Actions" || r.columnStart != 5 || r.rowStart == 1 || !r.isChecked()) return;
 const timeStamp = r.offset(0, -4).getDisplayValue();
 const dest = e.source.getSheetByName(r.offset(0, 2).getValue());
//  const find = dest.getRange("A3:A" + dest.getLastRow()).createTextFinder(timeStamp).findNext();
 const find = dest.createTextFinder(timeStamp).findNext();
...
 if (!find) return;
  dest.deleteRow(find.getRow());
</code>```

I also have a problem now where I can't run checkbox code if it doesn't have a location selected.

Body:
I'm using createTextFinder to search a different sheet than active and remove the row base off timeStamp. The row its deleting is the wrong row most of the time. I can't tell what the pattern is.

https://docs.google.com/spreadsheets/d/1-CgI_MigmgKBwFqA5ZhUzuTrmpLI-6emZg4FDuFwjfo/edit?usp=sharing
There's a master "Actions" list that splits off into locations sheets. When the checkbox on "E" in actions is checked the Location "G" lists should delete the row found by createTextFinder with the timeStamp in "A".

 if (src.getName() != "Actions" || r.columnStart != 5 || r.rowStart == 1 || !r.isChecked()) return;
 const timeStamp = r.offset(0, -4).getDisplayValue();
 const dest = e.source.getSheetByName(r.offset(0, 2).getValue());
//  const find = dest.getRange("A3:A" + dest.getLastRow()).createTextFinder(timeStamp).findNext();
 const find = dest.createTextFinder(timeStamp).findNext();
...
 if (!find) return;
  dest.deleteRow(find.getRow());

I also have a problem now where I can't run checkbox code if it doesn't have a location selected.


问:
Cross-Site Scripting:Persistent Fortify issue in spring boot rest controller
how to fix the cross site scripting persistent fortify security issue for the below code.
I know we are directly retrieving the output from the DB and sending it to response. which can result in security violations where attackers may inject malicious code to DB which we return it to users.

is there any way to fix the below code?

```<code>Optional<Request> request = accountRepository.findById(id)
 return ResponseEntity.status(HttpStatus.OK).body(request.get());
</code>```

Body:
how to fix the cross site scripting persistent fortify security issue for the below code.
I know we are directly retrieving the output from the DB and sending it to response. which can result in security violations where attackers may inject malicious code to DB which we return it to users.

is there any way to fix the below code?

Optional<Request> request = accountRepository.findById(id)
 return ResponseEntity.status(HttpStatus.OK).body(request.get());


问:
How to embed Linkedln posts in angular application
How to embed Linkedln posts in angular application

How to embed Linkedln posts in angular application


问:
Nuxt global middleware doesnt run before page middleware
In my nuxt project i have 2 middlewares that handle auth. The first one is
a page based validate.js, which checks if the user is authenticated, then either allows or disallows protected routes.

Second is a global reValidate.js middleware, which checks if there is a token in localstorage, but the auth state in vuex is not set. This happens during page reload. If the scenario is true, it sets the authstate with the token from localhost

The problem is that the validate middleware runs before the reValidate middleware, which causes a redirect on user pages before the other middleware can reValidate.

According to the docs, global middleware should run before page middleware https://nuxtjs.org/docs/concepts/nuxt-lifecycle/

validate.js:

```<code>export default function (context) {
  if (!context.store.getters['auth/isAuth']) {
    return context.redirect('/auth/login')
  }
}
</code>```

Use in class based dashboard component

```<code>@Component({ middleware: ['validate'] })

export default class Dashboard extends Vue {
}
</script>
</code>```

reValidate.js

```<code>export default function (context) {
  if (
    !context.store.getters['auth/isAuth'] &&
    process.client &&
    localStorage.getItem('user-token')
  ) {
    context.store.dispatch(
      'auth/setAuth',
      localStorage.getItem('user-token')
    )
  }
}
</code>```

defined  in nuxt config as

router: { middleware: ['reValidate'] },

so that it runs on every route change, which it does correctly.

Body:
In my nuxt project i have 2 middlewares that handle auth. The first one is
a page based validate.js, which checks if the user is authenticated, then either allows or disallows protected routes.

Second is a global reValidate.js middleware, which checks if there is a token in localstorage, but the auth state in vuex is not set. This happens during page reload. If the scenario is true, it sets the authstate with the token from localhost

The problem is that the validate middleware runs before the reValidate middleware, which causes a redirect on user pages before the other middleware can reValidate.

According to the docs, global middleware should run before page middleware https://nuxtjs.org/docs/concepts/nuxt-lifecycle/

validate.js:

export default function (context) {
  if (!context.store.getters['auth/isAuth']) {
    return context.redirect('/auth/login')
  }
}

Use in class based dashboard component

@Component({ middleware: ['validate'] })

export default class Dashboard extends Vue {
}
</script>

reValidate.js

export default function (context) {
  if (
    !context.store.getters['auth/isAuth'] &&
    process.client &&
    localStorage.getItem('user-token')
  ) {
    context.store.dispatch(
      'auth/setAuth',
      localStorage.getItem('user-token')
    )
  }
}

defined  in nuxt config as

router: { middleware: ['reValidate'] },

so that it runs on every route change, which it does correctly.


问:
Angular app in production slow to load with 9 second load time and huge file size
The website works efficiently and very quickly on the local, but as soon as I uploaded my application to Heroku, I was shocked at how slow the launch was for the first time, and after that it got somewhat better .. I noticed that the vendor.js file reached 3 mb and the website takes arround 10 second for the first time loading

I tried to update package.json

```<code>       "build:prod": "ng build --prod --aot --vendor-chunk --common-chunk --delete-output-path --buildOptimizer"

     "buildOptimizer": true,
</code>```

Body:
The website works efficiently and very quickly on the local, but as soon as I uploaded my application to Heroku, I was shocked at how slow the launch was for the first time, and after that it got somewhat better .. I noticed that the vendor.js file reached 3 mb and the website takes arround 10 second for the first time loading

I tried to update package.json

       "build:prod": "ng build --prod --aot --vendor-chunk --common-chunk --delete-output-path --buildOptimizer"

     "buildOptimizer": true,


问:
Flutter Web3 cannot fetch data with address type
I am using https://pub.dev/packages/flutter_web3 in order to connect my Flutter Web App with Solidity smart contract.

I could successfully connect with Metamask with my account

```<code>  Future<bool> connectProvider() async {
debugPrint("connectProvider");
if (Ethereum.isSupported) {
  final accs = await ethereum!.requestAccount();
  if (accs.isNotEmpty) {
    debugPrint("accounts not empty");
    currentAddress = accs.first;
    currentChain = await ethereum!.getChainId();
    debugPrint("current chain is $currentChain");
    debugPrint("current address $currentAddress");
  } else {
    debugPrint("accounts are empty");
  }
} else {
  debugPrint("not supported");
}
return false;
}
</code>```

I could also get data about my balance:

```<code> Future<bool> getBalance() async {
final rpcProvider = JsonRpcProvider('https://bsc-dataseed1.defibit.io/');
final lastBlock = await rpcProvider.getLastestBlock();
final balance = await rpcProvider.getBalance(address);
BigInt balanceFormatted = BigInt.from(10).pow(18);
double b = balance / balanceFormatted;
debugPrint("balance = $b");
return false;
}
</code>```

The problem appears when I am trying to fetch information from smart contract:

```<code>final contract = Contract(smartContactAddress, jsonAbi, rpcProvider);
final something = await contract.call<String>('address');
debugPrint("something = $something");
</code>```

Where method in abi file is:

```<code>   {
    "inputs": [],
    "name": "pick_address",
    "outputs": [
        {
            "internalType": "address",
            "name": "",
            "type": "address"
        }
    ],
    "stateMutability": "pure",
    "type": "function"
}
</code>```

Here's the output:

```<code>  js_util_patch.dart:80 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'apply')
at Object.callMethod$ [as callMethod] (js_util_patch.dart:80:66)
at ethers.Contract.__._call (contract.dart:193:43)
at _call.next (<anonymous>)
.....
</code>```

Which is referring to this method:

```<code>@patch
 T callMethod<T>(Object o, String method, List<Object?> args) {
 assertInteropArgs(args);
 return JS<dynamic>('Object|Null', '#[#].apply(#, #)', o, method, o, args);
 }
</code>```

Maybe anyone has a workaround for that or does know if I pass something in the wrong way.

EDIT

I have found some workaround to GET uint256 values from smart contract, but still cannot retrieve the value with type address. Post is edited. What is the equivalent type of address in flutter?

Body:
I am using https://pub.dev/packages/flutter_web3 in order to connect my Flutter Web App with Solidity smart contract.

I could successfully connect with Metamask with my account

  Future<bool> connectProvider() async {
debugPrint("connectProvider");
if (Ethereum.isSupported) {
  final accs = await ethereum!.requestAccount();
  if (accs.isNotEmpty) {
    debugPrint("accounts not empty");
    currentAddress = accs.first;
    currentChain = await ethereum!.getChainId();
    debugPrint("current chain is $currentChain");
    debugPrint("current address $currentAddress");
  } else {
    debugPrint("accounts are empty");
  }
} else {
  debugPrint("not supported");
}
return false;
}

I could also get data about my balance:

 Future<bool> getBalance() async {
final rpcProvider = JsonRpcProvider('https://bsc-dataseed1.defibit.io/');
final lastBlock = await rpcProvider.getLastestBlock();
final balance = await rpcProvider.getBalance(address);
BigInt balanceFormatted = BigInt.from(10).pow(18);
double b = balance / balanceFormatted;
debugPrint("balance = $b");
return false;
}

The problem appears when I am trying to fetch information from smart contract:

final contract = Contract(smartContactAddress, jsonAbi, rpcProvider);
final something = await contract.call<String>('address');
debugPrint("something = $something");

Where method in abi file is:

   {
    "inputs": [],
    "name": "pick_address",
    "outputs": [
        {
            "internalType": "address",
            "name": "",
            "type": "address"
        }
    ],
    "stateMutability": "pure",
    "type": "function"
}

Here's the output:

  js_util_patch.dart:80 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'apply')
at Object.callMethod$ [as callMethod] (js_util_patch.dart:80:66)
at ethers.Contract.__._call (contract.dart:193:43)
at _call.next (<anonymous>)
.....

Which is referring to this method:

@patch
 T callMethod<T>(Object o, String method, List<Object?> args) {
 assertInteropArgs(args);
 return JS<dynamic>('Object|Null', '#[#].apply(#, #)', o, method, o, args);
 }

Maybe anyone has a workaround for that or does know if I pass something in the wrong way.

EDIT

I have found some workaround to GET uint256 values from smart contract, but still cannot retrieve the value with type address. Post is edited. What is the equivalent type of address in flutter?


问:
.pdf Download unsuccessful error after downloading file from webview in android studio
`I have made a webview app through android studio where there are several download buttons that downloads .pdf, .doc, .aspx etc etc file when clicked on them.
These buttons are working fine when I download them from the website but every time I try to download it from the webview apk it shows "download unsuccessful" in the notification bar

Here is my code :

```<code>webview.setDownloadListener(new DownloadListener() {
    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition,
                               String mimeType, long contentLength) {
        MainActivity.this.websiteURL = url;
        MainActivity.this.userAgent = userAgent;
        MainActivity.this.contentDisposition = contentDisposition;
        MainActivity.this.mimeType = mimeType;

        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (ActivityCompat.checkSelfPermission(MainActivity.this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_RC);
        } else {
            downloadFile();
      }
    }
});
</code>```
```<code>private void downloadFile() {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(websiteURL));

    request.setMimeType(mimeType);
    String cookies = CookieManager.getInstance().getCookie(websiteURL);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    request.setDescription("Downloading file...");
    request.setTitle(URLUtil.guessFileName(websiteURL, contentDisposition, mimeType));
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    String fileName = URLUtil.guessFileName(websiteURL, contentDisposition, mimeType);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);

    Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == WRITE_EXTERNAL_STORAGE_RC) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            downloadFile();
        }
    }
}
</code>```

`

Body:
`I have made a webview app through android studio where there are several download buttons that downloads .pdf, .doc, .aspx etc etc file when clicked on them.
These buttons are working fine when I download them from the website but every time I try to download it from the webview apk it shows "download unsuccessful" in the notification bar

Here is my code :

webview.setDownloadListener(new DownloadListener() {
    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition,
                               String mimeType, long contentLength) {
        MainActivity.this.websiteURL = url;
        MainActivity.this.userAgent = userAgent;
        MainActivity.this.contentDisposition = contentDisposition;
        MainActivity.this.mimeType = mimeType;

        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (ActivityCompat.checkSelfPermission(MainActivity.this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_RC);
        } else {
            downloadFile();
      }
    }
});

private void downloadFile() {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(websiteURL));

    request.setMimeType(mimeType);
    String cookies = CookieManager.getInstance().getCookie(websiteURL);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    request.setDescription("Downloading file...");
    request.setTitle(URLUtil.guessFileName(websiteURL, contentDisposition, mimeType));
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    String fileName = URLUtil.guessFileName(websiteURL, contentDisposition, mimeType);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);

    Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == WRITE_EXTERNAL_STORAGE_RC) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            downloadFile();
        }
    }
}

`


问:
Is there any way to combine two custom vision project into one project?
I have two projects created in custom vision portal .Want to combine those two project into one .The project is created for object detection .

Please help out is there any tool to merge those two projects ?
Thanks


问:
How to add a index on a constrained foreign key In Laravel for PostgreSQL
I'm seeding a CSV file with about 2.000.000 entries into a PostgreSQL database, and some fields need to be dispatched in specific tables with relationship.

For the relationship, I'm using this in my migration:

$table->foreignId('foo_id')->constrained('foos');

When trying to improve the bad seeding performances with PostgreSQL, I realised there's was no index on the profession_id column, so I added one like this:

$table->foreignId('foo_id')->constrained('foos')->index();

But I don't see it in the indexes list of my main table, why ? Also, I don't get any error at migration refresh.

I don't have this problem in mysql and indexes are added but not in PostgresSql

Is it possible to add an index to a foreign key ? If yes, how ?

In migration :

$table->foreignId('foo_id')->constrained('foos')->index();


问:
php codeigniter Video Upload Not Uploaded Video file
When uploading image files, the upload is complete and successful, but when uploading the video file, it is not uploaded and it does not show where the error is

HTML Code:

```<code>           <div class="row mb-5">
                <div class="col-md-12">
                    <input type="file" name="slider_image" id="" class="form-control mb-5" onchange="homeSliderUpload(this)">
                    <div class="progress mb-5" style="--sa-progress--value: 0%">
                        <div class="progress-bar progress-bar-sa-primary" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    function homeSliderUpload(form) {
        alert("First");
        var file_data = $("input[name='slider_image']").prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajax({
            url: "<?php echo base_url(); ?>/Path/VedioUploader",
            dataType: 'text',
            method: "post",
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            success: function(data) {
                var rJson = $.parseJSON(data);
                if (rJson.status == true) {
                    $(".progress").attr("style", "--sa-progress--value: 100%");
                    $("input[name='slider_image']").val('');

                    setInterval(() => {
                        location.reload();
                    }, 1000);
                } else {
                      alert("Error");
                }
            }
        });
    }

</code>```

php Code ( Ajax Code):

```<code>public function VedioUploader()
    {
        $validateImage = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file, video/mp4, image/png, image/jpg,image/jpeg, image/gif]',
                'max_size[file, 1000000000]',
            ],
        ]);

        if ($validateImage) {
            $imageFile = $this->request->getFile('file');
            $folder = "Vedio/";
            $fileName = rand(10005, 100005) . time() . ".mp4";
            $imageFile->move($folder, $fileName);
            $data = [
                'img_name' => $imageFile->getClientName(),
                'file'  => $imageFile->getClientMimeType(),
                'type' => $imageFile->getClientExtension(),
            ];

            if ($fileName) {
                $homeSliderModel = new VedioUplaod();
                $home_slider["slider_file_url"] = $folder . "/" . $fileName;
                $home_slider["slider_show"] = 1;
                $home_slider["slider_order"] = 0;
                $homeSliderModel->insert($home_slider);

                if (!$homeSliderModel->errors()) {
                    echo json_encode([
                        "status" => true,
                        "slider_id" => $homeSliderModel->getInsertID(),
                        "file_url" => $folder . "/" . $fileName,
                        "order" => 0
                    ]);
                }
            }
        }
    }
</code>```

I tried removing the image types and retrying to upload the images, but it didn't work. It was similar to uploading the video. I thought it was because of the type, but nothing happened.

```<code>'mime_in[file, video/mp4]',
</code>```

Body:
When uploading image files, the upload is complete and successful, but when uploading the video file, it is not uploaded and it does not show where the error is

HTML Code:

                    <input type="file" name="slider_image" id="" class="form-control mb-5" onchange="homeSliderUpload(this)">


问:
Alt-based shortcuts in VS Code's intergrated terminal
My shell is configured to have Alt+n and Alt+p navigate in history (technically, using zsh's history-beginning-search-forward and history-beginning-search-backward).

I used to be able to use these shortcuts in VS Code's integrated terminal, but since I upgraded to VS Code 1.74.1, the Alt+n and Alt+p seem to be catched by VS Code before reaching my shell (the cursor changes to a cross to allow rectangular selection when I press Alt, which I guess is the cause). I do have "terminal.integrated.sendKeybindingsToShell": true and "terminal.integrated.allowMnemonics": false in my settings to avoid interference between VS Code and the Alt key, and I couldn't find another setting to change the behavior. Surprisingly, the Alt+a command is passed to the shell, so some Alt-based shortcuts are passed to the shell, but not all.

Is it possible to configure VS Code to send Alt+n and Alt+p to my shell?

As a workaround, using Alt+Shift+n and Alt+Shift+p seem to work, but that's one extra key to teach my fingers to use :-(.


问:
Spring Jpa Specification with list of long where in query
I want to run a where in query with Spring JPA Specification and criteria builder. I am having issue where I will receive a List ids from request and run specification query but could't find any way to do so.

This is what I have done so far.

```<code>     public class DistributorMasterDataSpecification implements Specification<DistributorMasterData> {
        @Override
        public Predicate toPredicate(Root<DistributorMasterData> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
           return
                codeSpec()
                .and(idSpec())
                .toPredicate(root, query, criteriaBuilder);
         }

   private Specification<DistributorMasterData> idSpec() {
        return ((root, query, criteriaBuilder) ->
                Objects.isNull(filterDto.getDistributorIds()) ?
                null : root.get(DistributorMasterData_.ID).in(filterDto.getDistributorIds())
        );
    }

}
</code>```

I am unable to figure out how to prepare where in query with specification. With current implementation I facing the error below

org.springframework.dao.InvalidDataAccessApiUsageException: literal value cannot be null; nested exception is java.lang.IllegalArgumentException: literal value cannot be null

Body:
I want to run a where in query with Spring JPA Specification and criteria builder. I am having issue where I will receive a List ids from request and run specification query but could't find any way to do so.

This is what I have done so far.

     public class DistributorMasterDataSpecification implements Specification<DistributorMasterData> {
        @Override
        public Predicate toPredicate(Root<DistributorMasterData> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
           return
                codeSpec()
                .and(idSpec())
                .toPredicate(root, query, criteriaBuilder);
         }

   private Specification<DistributorMasterData> idSpec() {
        return ((root, query, criteriaBuilder) ->
                Objects.isNull(filterDto.getDistributorIds()) ?
                null : root.get(DistributorMasterData_.ID).in(filterDto.getDistributorIds())
        );
    }

}

I am unable to figure out how to prepare where in query with specification. With current implementation I facing the error below

org.springframework.dao.InvalidDataAccessApiUsageException: literal value cannot be null; nested exception is java.lang.IllegalArgumentException: literal value cannot be null


问:
Amazon Cognito - Query For Multiple User Ids
Is there a way to query Amazon Cognito for multiple User Ids at once? If yes, are there any limitations?</p>


问:
show charecter count in content editable element
I would like to show character count for each content editable element. Each element will have separate number of allowed character limits.

Here is the code I would like to use. instead of the maxLen: 10, I would like to allow each element to limit characters. it will be easier as there are more than 1 content editable elements. Also want to display the characters like <span1></span1> in HTML.
sorry about my bad English.

Here is the code I am using to limit user from adding more than the allowed number of characters.

```<code><script>

   input = document.querySelector('#test');

    settings = {
      maxLen: 10,
    }

    keys = {
      'backspace': 8,
      'shift': 16,
      'ctrl': 17,
      'alt': 18,
      'delete': 46,
      // 'cmd':
      'leftArrow': 37,
      'upArrow': 38,
      'rightArrow': 39,
      'downArrow': 40,
    }

    utils = {
      special: {},
      navigational: {},
      isSpecial(e) {
        return typeof this.special[e.keyCode] !== 'undefined';
      },
      isNavigational(e) {
        return typeof this.navigational[e.keyCode] !== 'undefined';
      }
    }

    utils.special[keys['backspace']] = true;
    utils.special[keys['shift']] = true;
    utils.special[keys['ctrl']] = true;
    utils.special[keys['alt']] = true;
    utils.special[keys['delete']] = true;

    utils.navigational[keys['upArrow']] = true;
    utils.navigational[keys['downArrow']] = true;
    utils.navigational[keys['leftArrow']] = true;
    utils.navigational[keys['rightArrow']] = true;

    input.addEventListener('keydown', function(event) {
      let len = event.target.innerText.trim().length;
      hasSelection = false;
      selection = window.getSelection();
      isSpecial = utils.isSpecial(event);
      isNavigational = utils.isNavigational(event);

      if (selection) {
        hasSelection = !!selection.toString();
      }

      if (isSpecial || isNavigational) {
        return true;
      }

      if (len >= settings.maxLen && !hasSelection) {
        event.preventDefault();
        return false;
      }

    });

</script>

</code>```


问:
SHAP scatter plot for LightGBM classifier showing global contributions without interactions
I have a binary classification problem for which I have developed a LightGBM classifier. I would like to plot global SHAP contributions for the X most important features, as in the scatter plot documentation the code shap.plots.scatter(shap_values[:, shap_values.abs.mean(0).argsort[-1]])
produces this plot

How could I get the desired plot for some of my features?

My attempt is as follows:

```<code>clf_final = lightgbm.LGBMClassifier(**RSCV.best_estimator_.get_params())
clf_final.fit(X_train, y_train)

# compute SHAP values
explainer_LGB = shap.TreeExplainer(clf_final)
shap_values_LGB = explainer_LGB.shap_values(X_train)
shap.plots.scatter(shap_values_LGB[0:,"pet_mean_lag_t-6"])
</code>```

But it produces the error message: TypeError: list indices must be integers or slices, not tuple

Body:
I have a binary classification problem for which I have developed a LightGBM classifier. I would like to plot global SHAP contributions for the X most important features, as in the scatter plot documentation the code shap.plots.scatter(shap_values[:, shap_values.abs.mean(0).argsort[-1]])
produces this plot

How could I get the desired plot for some of my features?

My attempt is as follows:

clf_final = lightgbm.LGBMClassifier(**RSCV.best_estimator_.get_params())
clf_final.fit(X_train, y_train)

# compute SHAP values
explainer_LGB = shap.TreeExplainer(clf_final)
shap_values_LGB = explainer_LGB.shap_values(X_train)
shap.plots.scatter(shap_values_LGB[0:,"pet_mean_lag_t-6"])

But it produces the error message: TypeError: list indices must be integers or slices, not tuple


问:
Spaces are not inserted in Visual Studio before "new()"
Recently this setting of Resharper stopped working:

Code editing > C# > Formatting Style > Spaces > Before other parentheses > 'new' parentheses

So when I run Resharper "Code clenup", then it does not add space before "new()". So my code looks like this after applying "Code cleanup":

```<code>object obj = new(); // it is not okay as there is space between "new()"
</code>```

However, what we want is:

```<code>object obj = new (); // it is okay as there is space between "new ()"
</code>```

Does anybody know how to add space between  "new ()"

Body:
Recently this setting of Resharper stopped working:

Code editing > C# > Formatting Style > Spaces > Before other parentheses > 'new' parentheses

So when I run Resharper "Code clenup", then it does not add space before "new()". So my code looks like this after applying "Code cleanup":

object obj = new(); // it is not okay as there is space between "new()"

However, what we want is:

object obj = new (); // it is okay as there is space between "new ()"

Does anybody know how to add space between  "new ()"


问:
How to prevent GCC from replacing return instructions with a jump to the last one
With most optimizations disabled (-O0) GCC compiles this function to the below assembly code:

int dummy_function(int x)
{
    if (x == 1) {
        return 1;
    } else if (x == 2) {
        return 2;
    } else if (x == 3) {
        return 3;
    } else if (x == 4) {
        return 4;
    } else if (x == 5) {
        return 5;
    } else if (x == 6) {
        return 6;
    } else {
        return 10;
    }
}
```
<pre class="lang-none prettyprint-override"><code>  0:    55                      push   rbp
  1:    48 89 e5                mov    rbp,rsp
  4:    89 7d fc                mov    DWORD PTR [rbp-0x4],edi
  7:    83 7d fc 01             cmp    DWORD PTR [rbp-0x4],0x1
  b:    75 07                   jne    14 <test+0x14>
  d:    b8 01 00 00 00          mov    eax,0x1
 12:    eb 46                   jmp    5a <test+0x5a>
 14:    83 7d fc 02             cmp    DWORD PTR [rbp-0x4],0x2
 18:    75 07                   jne    21 <test+0x21>
 1a:    b8 02 00 00 00          mov    eax,0x2
 1f:    eb 39                   jmp    5a <test+0x5a>
 21:    83 7d fc 03             cmp    DWORD PTR [rbp-0x4],0x3
 25:    75 07                   jne    2e <test+0x2e>
 27:    b8 03 00 00 00          mov    eax,0x3
 2c:    eb 2c                   jmp    5a <test+0x5a>
 2e:    83 7d fc 04             cmp    DWORD PTR [rbp-0x4],0x4
 32:    75 07                   jne    3b <test+0x3b>
 34:    b8 04 00 00 00          mov    eax,0x4
 39:    eb 1f                   jmp    5a <test+0x5a>
 3b:    83 7d fc 05             cmp    DWORD PTR [rbp-0x4],0x5
 3f:    75 07                   jne    48 <test+0x48>
 41:    b8 05 00 00 00          mov    eax,0x5
 46:    eb 12                   jmp    5a <test+0x5a>
 48:    83 7d fc 06             cmp    DWORD PTR [rbp-0x4],0x6
 4c:    75 07                   jne    55 <test+0x55>
 4e:    b8 06 00 00 00          mov    eax,0x6
 53:    eb 05                   jmp    5a <test+0x5a>
 55:    b8 0a 00 00 00          mov    eax,0xa
 5a:    5d                      pop    rbp
 5b:    c3                      ret
</code>```

Return instructions are replaced with a jmp to the last one even when non merge instructions option is used.
How to prevent GCC from doing this optimization ?

Body:
With most optimizations disabled (-O0) GCC compiles this function to the below assembly code:

int dummy_function(int x)
{
    if (x == 1) {
        return 1;
    } else if (x == 2) {
        return 2;
    } else if (x == 3) {
        return 3;
    } else if (x == 4) {
        return 4;
    } else if (x == 5) {
        return 5;
    } else if (x == 6) {
        return 6;
    } else {
        return 10;
    }
}

  0:    55                      push   rbp
  1:    48 89 e5                mov    rbp,rsp
  4:    89 7d fc                mov    DWORD PTR [rbp-0x4],edi
  7:    83 7d fc 01             cmp    DWORD PTR [rbp-0x4],0x1
  b:    75 07                   jne    14 <test+0x14>
  d:    b8 01 00 00 00          mov    eax,0x1
 12:    eb 46                   jmp    5a <test+0x5a>
 14:    83 7d fc 02             cmp    DWORD PTR [rbp-0x4],0x2
 18:    75 07                   jne    21 <test+0x21>
 1a:    b8 02 00 00 00          mov    eax,0x2
 1f:    eb 39                   jmp    5a <test+0x5a>
 21:    83 7d fc 03             cmp    DWORD PTR [rbp-0x4],0x3
 25:    75 07                   jne    2e <test+0x2e>
 27:    b8 03 00 00 00          mov    eax,0x3
 2c:    eb 2c                   jmp    5a <test+0x5a>
 2e:    83 7d fc 04             cmp    DWORD PTR [rbp-0x4],0x4
 32:    75 07                   jne    3b <test+0x3b>
 34:    b8 04 00 00 00          mov    eax,0x4
 39:    eb 1f                   jmp    5a <test+0x5a>
 3b:    83 7d fc 05             cmp    DWORD PTR [rbp-0x4],0x5
 3f:    75 07                   jne    48 <test+0x48>
 41:    b8 05 00 00 00          mov    eax,0x5
 46:    eb 12                   jmp    5a <test+0x5a>
 48:    83 7d fc 06             cmp    DWORD PTR [rbp-0x4],0x6
 4c:    75 07                   jne    55 <test+0x55>
 4e:    b8 06 00 00 00          mov    eax,0x6
 53:    eb 05                   jmp    5a <test+0x5a>
 55:    b8 0a 00 00 00          mov    eax,0xa
 5a:    5d                      pop    rbp
 5b:    c3                      ret

Return instructions are replaced with a jmp to the last one even when non merge instructions option is used.
How to prevent GCC from doing this optimization ?


问:
Deeplinking in Flutter with GoRouter does not work when using PathUrlStrategy
In the GoRouter I have defined a path for deeplinking:

```<code>static const String DEEP_LINK = "deeplink/:someID/:someName";
</code>```

It is working in the browser as expeced using

```<code>http://localhost:12345/#/deeplink/1/test
</code>```

but when I use

```<code>setUrlStrategy(PathUrlStrategy());
</code>```

to remove the has and enter

```<code>http://localhost:12345/deeplink/1/test
</code>```

it does not work anymore and I get the error:

```<code>Could not navigate to initial route.
The requested route name was: "/deeplink/1/test"
There was no corresponding route in the app, and therefore the initial route specified will be ignored and "/" will be used instead.
</code>```

What am I doing wrong?

Body:
In the GoRouter I have defined a path for deeplinking:

static const String DEEP_LINK = "deeplink/:someID/:someName";

It is working in the browser as expeced using

http://localhost:12345/#/deeplink/1/test

but when I use

setUrlStrategy(PathUrlStrategy());

to remove the has and enter

http://localhost:12345/deeplink/1/test

it does not work anymore and I get the error:

Could not navigate to initial route.
The requested route name was: "/deeplink/1/test"
There was no corresponding route in the app, and therefore the initial route specified will be ignored and "/" will be used instead.

What am I doing wrong?


问:
Is it possible to include an Xhtml2pdf object in a Reportlab pdf?
I have a combination of plain text and HTML that I want to combine into 1 pdf file. The plain text I can easily write to a pdf using reportlab. Adding the HTML turns out to be more difficult.

This HTML contains images and CSS from an external source.

My initial plan was to use xhtml2pdf to convert the pieces of html into a pdf and then merge that into the reportlab object. It would like something like below.

My question is, is this possible? If yes, could you point me towards any resources because I can't find any. If no, is there any other way to achieve this?


问:
Carousel is not working when sliding right : (
I have a carousel that slides with texts and Images. I want to move Left and Right but this code moves up and down.
It only Moves Up And Down ,But I Want the Slider to move Left and Right

```<code>StreamBuilder(
    stream: offer.snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
      if (streamSnapshot.hasData) {
        QuerySnapshot<Object?>? querySnapshot = streamSnapshot.data;
        List<QueryDocumentSnapshot> documents = querySnapshot!.docs;
        List<Map> items = documents.map((e) => {
          "id": e.id,
          "Product Name": e['Product Name'],
          "Company Name": e['Company Name'],
          }).toList();
        return PageView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              Map thisitem = items[index];
              return CarouselSlider(
                items: [
SizedBox(
    height:60,
    width:80,child: Image.network("${thisitem["Image"]}")),

const SizedBox(width: 40,),
Row(
  children: [
    Text('${thisitem['Company Name']}\n '
        '${thisitem['Product Name']}'
    ),],),

</code>```

options: CarouselOptions(
scrollDirection: Axis.horizontal,
initialPage: 0,
reverse: false,
autoPlayCurve: Curves.fastOutSlowIn,
height:140.0,
enlargeCenterPage: true,
autoPlay: false,
aspectRatio: 16 / 9,
autoPlayAnimationDuration: const Duration(milliseconds: 800),
viewportFraction: 0.9,
),
);
}
);
}

Body:
I have a carousel that slides with texts and Images. I want to move Left and Right but this code moves up and down.
It only Moves Up And Down ,But I Want the Slider to move Left and Right

StreamBuilder(
    stream: offer.snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
      if (streamSnapshot.hasData) {
        QuerySnapshot<Object?>? querySnapshot = streamSnapshot.data;
        List<QueryDocumentSnapshot> documents = querySnapshot!.docs;
        List<Map> items = documents.map((e) => {
          "id": e.id,
          "Product Name": e['Product Name'],
          "Company Name": e['Company Name'],
          }).toList();
        return PageView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              Map thisitem = items[index];
              return CarouselSlider(
                items: [
SizedBox(
    height:60,
    width:80,child: Image.network("${thisitem["Image"]}")),

const SizedBox(width: 40,),
Row(
  children: [
    Text('${thisitem['Company Name']}\n '
        '${thisitem['Product Name']}'
    ),],),

options: CarouselOptions(
scrollDirection: Axis.horizontal,
initialPage: 0,
reverse: false,
autoPlayCurve: Curves.fastOutSlowIn,
height:140.0,
enlargeCenterPage: true,
autoPlay: false,
aspectRatio: 16 / 9,
autoPlayAnimationDuration: const Duration(milliseconds: 800),
viewportFraction: 0.9,
),
);
}
);
}