Title: Rayon: why do the two ways of sum give different results?

Body:
Here I use Rust rayon crate to compute the definite integral (left Riemann sum) of a function in parallel:

use rayon::prelude::*;
use rayon::ThreadPoolBuilder;
use std::f64::consts::PI;

fn integral_rayon_test<F>(segments: u32, x0: f64, xn: f64, function: F)
where
    F: Fn(f64) -> f64 + Send + Sync + Copy + 'static,
{
    let range = xn - x0;
    let d = range / segments as f64;

    let sum1 = (0..segments)
        .into_par_iter()
        .map(|x| function(x0 + x as f64 * d) * d)
        .collect::<Vec<_>>()
        .iter()
        .sum::<f64>();

    let sum2 = (0..segments)
        .into_par_iter()
        .map(|x| function(x0 + x as f64 * d) * d)
        .sum::<f64>();

    println!("{} {}", sum1, sum2);
}

fn main() {
    ThreadPoolBuilder::new()
        .num_threads(3)
        .build_global()
        .unwrap();

    for _ in 0..1000 {
        integral_rayon_test(100000, 0.0, 2.0 * PI, f64::sin);
    }
}

There are two methods I compute the integral: sum1 is to first collect the par_iter values, and then sum them up; sum2 is to directly call sum on par_iter.

Then I run the test function integral_rayon_test multiple times, it produces these outputs:

-0.00000000000000020519185459954437 0.0000000000000006661338147750939
-0.00000000000000020519185459954437 0.0000000000000006661338147750939
-0.00000000000000020519185459954437 -0.0000000000000002220446049250313
-0.00000000000000020519185459954437 -0.0000000000000002220446049250313
-0.00000000000000020519185459954437 0.0000000000000006661338147750939
-0.00000000000000020519185459954437 -0.0000000000000011102230246251565
-0.00000000000000020519185459954437 0
-0.00000000000000020519185459954437 0.0000000000000006661338147750939
-0.00000000000000020519185459954437 0
-0.00000000000000020519185459954437 -0.0000000000000002220446049250313
-0.00000000000000020519185459954437 -0.0000000000000002220446049250313
-0.00000000000000020519185459954437 0.0000000000000006661338147750939
-0.00000000000000020519185459954437 -0.0000000000000002220446049250313
-0.00000000000000020519185459954437 0.0000000000000006661338147750939
...

Then I have two questions:

First, I expect that sum1 (column 1) be equal to sum2 (column 2), but they are not.

Second, as you can see, the sum1 numbers are all the same, but each sum2 value has a slight difference. I also expect them to be the same. This looks like data racing, but I don't think that because rayon claims its data race free. I don't know what I'm missing.

When I change the thread number to 1, it outputs:

-0.00000000000000020519185459954437 0
-0.00000000000000020519185459954437 0
-0.00000000000000020519185459954437 0
-0.00000000000000020519185459954437 0
...

where sum2 values are the same, but still sum1 differs from sum2. I don't know why.

Thanks for the help!

UPDATE:
Test target is x86_64-unknown-linux-gnu

/proc/cpuinfo shows fpu and fpu_exception true

For the second question, I just ignored that IEEE-754 floating-point numbers are not commutative, and this may be the cause.

I tested on aarch64-linux-android target, with thread number 1, it outputs:

-0.0000000000000006116797606620095 -0.0000000000000002220446049250313
-0.0000000000000006116797606620095 -0.0000000000000002220446049250313
-0.0000000000000006116797606620095 -0.0000000000000002220446049250313
-0.0000000000000006116797606620095 -0.0000000000000002220446049250313
...

where all sum1 and sum2 are the same. But this result is different from the above -0.00000000000000020519185459954437 0 output.

Can this be related to hardware floating point arithmetic? Now I have some trouble compiling the test program with +soft-float target feature, and cannot do some further tests.


来源: stackexchange

问:
Understanding slash shorthand notation for XML Atom Feeds
I ran in to some documentation explaining steps to create an Atom feed that introduced a syntax I don't quite understand and I am having issues figuring out how to search for it

In the first column it displays different <entry> elements. What do the // and / indicate here when converting these to valid XML? The first row is a required Atom field ( title ) so I can deduce it would result to this. Right?

```<code><entry>
    <title />
</entry>
</code>```

However, I guess the next 3 are using a custom namespace (to allow usage of tags like ReleaseId ) since they aren't a part of the default Atom namespace? In that case I guess I would need to define the xmlns for these tags since I read that elements from other namespaces can be included pretty much anywhere here? So my attempt at the second row looks like this:

```<code><feed xmlns="http://www.w3.org/2005/Atom" xmlns:ddex="...">
...
<entry>
    <ddex:ReleaseId />
</entry>
...
</code>```

Lastly, the third row displays a /* which I assume means there are children nested inside the ReleaseId tag?

How do these rows all translate in to respective Atom XML? This image comes from this page for reference: https://kb.ddex.net/display/ECHO17WS/8.2+Atom+Feed

Thanks for any guidance!

ContentLicense: CC BY-SA 4.0

Body:
I ran in to some documentation explaining steps to create an Atom feed that introduced a syntax I don't quite understand and I am having issues figuring out how to search for it

In the first column it displays different <entry> elements. What do the // and / indicate here when converting these to valid XML? The first row is a required Atom field ( title ) so I can deduce it would result to this. Right?

<entry>
    <title />
</entry>

However, I guess the next 3 are using a custom namespace (to allow usage of tags like ReleaseId ) since they aren't a part of the default Atom namespace? In that case I guess I would need to define the xmlns for these tags since I read that elements from other namespaces can be included pretty much anywhere here? So my attempt at the second row looks like this:

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:ddex="...">
...
<entry>
    <ddex:ReleaseId />
</entry>
...

Lastly, the third row displays a /* which I assume means there are children nested inside the ReleaseId tag?

How do these rows all translate in to respective Atom XML? This image comes from this page for reference: https://kb.ddex.net/display/ECHO17WS/8.2+Atom+Feed

Thanks for any guidance!


问:
How to set up img size in React.js
I have trouble resizing my image in specific
I set up .img in my index.css like this

.img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain;
}
```
<p>my portfolio.jsx is</p>
```

Pair Up

          Github
          Live View

4AnimeArchive

          Github
          Live View

Console.log

          Github
          Live View

Weather Forecast

          Github
          Live View

Snake Game

          Github
          Live View

TBH

          Github
          Live View

```
<p>and I also set up .portfolio_item-image in portfolio.css like this</p>
<pre class="lang-css prettyprint-override"><code>.portfolio_item-image {
 border-radius: 1.5rem;
 -webkit-border-radius: 1.5rem;
 -moz-border-radius: 1.5rem;
 -ms-border-radius: 1.5rem;
 -o-border-radius: 1.5rem;
 overflow: hidden;
}
</code>```

and the result is the following,

I don't know why my second and 3rd image sizes are different from the others.
please help. thank you

I tried all CSS properties to resize them, but nothing changes.

Title: How to set up img size in React.js

Body:
I have trouble resizing my image in specific
I set up .img in my index.css like this

.img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain;
}

my portfolio.jsx is

Pair Up

          Github
          Live View

4AnimeArchive

          Github
          Live View

Console.log

          Github
          Live View

Weather Forecast

          Github
          Live View

Snake Game

          Github
          Live View

TBH

          Github
          Live View

and I also set up .portfolio_item-image in portfolio.css like this

.portfolio_item-image {
 border-radius: 1.5rem;
 -webkit-border-radius: 1.5rem;
 -moz-border-radius: 1.5rem;
 -ms-border-radius: 1.5rem;
 -o-border-radius: 1.5rem;
 overflow: hidden;
}

and the result is the following,

I don't know why my second and 3rd image sizes are different from the others.
please help. thank you

I tried all CSS properties to resize them, but nothing changes.


问:
xcode component to compare textual contents?
I'm wondering, is there a free (preferrably free software) component I can embed in an xcode application that when I select from two file tree views a file, it will compare them against of each other.

I'm thinking that this has been done 1000 times before, so instead of building my own, I'm looking to import a component which can when given two files, show them compared against each other in the way that eclipse does, or that meld does.

thanks

ContentLicense: CC BY-SA 3.0


问:
Downloading data from webpage that has no forms using mechanicalsoup
I'm trying to extract the data from this website -https://www.texmesonet.org/DataProducts/CustomDownloads

I have to fill the data in the text fields and select few options before downloading the data and I'm trying to do it with mechanicalsoup. The roadblock that I'm facing is that the tags corresponding to the parameters needs to download are not inside a form. Is there any way to tackle this using mechanicalsoup? I have pasted the code that I'm using to select the parameters below.

```<code>browser = mechanicalsoup.Browser()
url = 'https://www.texmesonet.org/DataProducts/CustomDownloads'
page = browser.get(url)
html_page = page.soup
#print(html_page.select('div'))
region = html_page.select('select')[0]
region.select('option')[0]["value"] = 'Station'

data_type = html_page.select('select')[1]
data_type.select('option')[2]["value"] = 'Timeseries'

        #print(html_page.select('span'))
start_date = html_page.find_all("div", {"class": "col50 field-container"})[2]
start_date.select('input')[0]["value"] = '11/28/2022'

end_date = html_page.find_all("div", {"class": "col50 field-container"})[3]
end_date.select('input')[0]["value"] = '12/05/2022'

station = html_page.find_all("div", {"class": "col50 field-container"})[4]
station.select('input')[0]["value"] = 'Headwaters Ranch'

interval = html_page.select('select')[3]
interval.select('option')[0]["value"] = 'Daily'

units = html_page.select('select')[5]
units.select('option')[0]["value"] = 'US / Customary'
</code>```

Body:
I'm trying to extract the data from this website -https://www.texmesonet.org/DataProducts/CustomDownloads

I have to fill the data in the text fields and select few options before downloading the data and I'm trying to do it with mechanicalsoup. The roadblock that I'm facing is that the tags corresponding to the parameters needs to download are not inside a form. Is there any way to tackle this using mechanicalsoup? I have pasted the code that I'm using to select the parameters below.

browser = mechanicalsoup.Browser()
url = 'https://www.texmesonet.org/DataProducts/CustomDownloads'
page = browser.get(url)
html_page = page.soup
#print(html_page.select('div'))
region = html_page.select('select')[0]
region.select('option')[0]["value"] = 'Station'

data_type = html_page.select('select')[1]
data_type.select('option')[2]["value"] = 'Timeseries'

        #print(html_page.select('span'))
start_date = html_page.find_all("div", {"class": "col50 field-container"})[2]
start_date.select('input')[0]["value"] = '11/28/2022'

end_date = html_page.find_all("div", {"class": "col50 field-container"})[3]
end_date.select('input')[0]["value"] = '12/05/2022'

station = html_page.find_all("div", {"class": "col50 field-container"})[4]
station.select('input')[0]["value"] = 'Headwaters Ranch'

interval = html_page.select('select')[3]
interval.select('option')[0]["value"] = 'Daily'

units = html_page.select('select')[5]
units.select('option')[0]["value"] = 'US / Customary'


问:
How to cross compile Linux X64 target platform using M1 Mac
I try to compile openssl and libssh2, but I'm using M1 Mac (Arm64), so I can't run a x86-64 ubuntu virtual machine.
I know clang can do cross compilation, I download llvm from: llvm, and clang -target x86_64-linux-gnu --sysroot=???, but I still need a --sysroot, where should I download the sysroot of the target platform Or is there a better way to get.

```<code>clang -target x86_64-linux-gnu -fuse-ld=lld -stdlib=libc main.c -o main
ld.lld: error: cannot open Scrt1.o: No such file or directory
ld.lld: error: cannot open crti.o: No such file or directory
ld.lld: error: cannot open crtbeginS.o: No such file or directory
ld.lld: error: unable to find library -lgcc
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: unable to find library -lc
ld.lld: error: unable to find library -lgcc
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: cannot open crtendS.o: No such file or directory
ld.lld: error: cannot open crtn.o: No such file or directory
clang-15: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```
```<code>cat main.c
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
</code>```

Body:
I try to compile openssl and libssh2, but I'm using M1 Mac (Arm64), so I can't run a x86-64 ubuntu virtual machine.
I know clang can do cross compilation, I download llvm from: llvm, and clang -target x86_64-linux-gnu --sysroot=???, but I still need a --sysroot, where should I download the sysroot of the target platform Or is there a better way to get.

clang -target x86_64-linux-gnu -fuse-ld=lld -stdlib=libc main.c -o main
ld.lld: error: cannot open Scrt1.o: No such file or directory
ld.lld: error: cannot open crti.o: No such file or directory
ld.lld: error: cannot open crtbeginS.o: No such file or directory
ld.lld: error: unable to find library -lgcc
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: unable to find library -lc
ld.lld: error: unable to find library -lgcc
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: cannot open crtendS.o: No such file or directory
ld.lld: error: cannot open crtn.o: No such file or directory
clang-15: error: linker command failed with exit code 1 (use -v to see invocation)

cat main.c
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}


问:
Google gmail api list messages by labelId error 400
I am working on a domain-wide delegation app to pull attachments from a user's email with a specific label. When trying to get their messages, I get this exception:

{
 error={
  code=400.0,
  message='raw' RFC822 payload message string or uploading message via /upload/* URL required,
  status=INVALID_ARGUMENT,
  errors=[
   {reason=invalidArgument, message='raw' RFC822 payload message string or uploading message via /upload/* URL required, domain=global}
  ]
 }
}
```
<p>The Gmail API documentation suggests to me that the labelIds property is an array of label ids.</p>
<p>From Resolve errors documentation these would cause a 400 exception.</p>
<ol>
<li>A required field or parameter hasn't been provided.</li>
<li>The value supplied or a combination of provided fields is invalid.</li>
<li>Invalid attachment.</li>
</ol>
<p>I don't think its 1, no  parameter is mandatory based on the docs.
Number 3 is out because theres no attachment.
So thats leaves 2. what field am I messing up?</p>
<p>Things I don't know: 'raw' and RFC822 from the following exception</p>
<p>Here is the exception "message='raw' RFC822 payload message string or uploading message via /upload/* URL required"</p>
```function getMessages(oAuth,userEmail,labels){
  let labels = ['Label_718766733436502667']
  if (oAuth.hasAccess()) {
    let url = 'https://gmail.googleapis.com/gmail/v1/users/' + userEmail + '/messages'

    let token = service.getAccessToken();
    let payload = JSON.stringify({labelIds:labels})

    let options = {
      headers: {
        Authorization: "Bearer " + token,
        "content-type": "application/json"
      },
      method: "GET",
      payload:payload,
      //muteHttpExceptions: true
    };

    let response = UrlFetchApp.fetch(url, options);
    //Logger.log(response.getContentText());
    let result = JSON.parse(response.getContentText());
    Logger.log(result)
    return result
    //Logger.log(JSON.stringify(result, null, 2));
  } else {
    Logger.log(service.getLastError());
  }

}
```

Body:
I am working on a domain-wide delegation app to pull attachments from a user's email with a specific label. When trying to get their messages, I get this exception:

{
 error={
  code=400.0,
  message='raw' RFC822 payload message string or uploading message via /upload/* URL required,
  status=INVALID_ARGUMENT,
  errors=[
   {reason=invalidArgument, message='raw' RFC822 payload message string or uploading message via /upload/* URL required, domain=global}
  ]
 }
}

The Gmail API documentation suggests to me that the labelIds property is an array of label ids.

From Resolve errors documentation these would cause a 400 exception.

A required field or parameter hasn't been provided.

The value supplied or a combination of provided fields is invalid.

Invalid attachment.

I don't think its 1, no  parameter is mandatory based on the docs.
Number 3 is out because theres no attachment.
So thats leaves 2. what field am I messing up?

Things I don't know: 'raw' and RFC822 from the following exception

Here is the exception "message='raw' RFC822 payload message string or uploading message via /upload/* URL required"

function getMessages(oAuth,userEmail,labels){
  let labels = ['Label_718766733436502667']
  if (oAuth.hasAccess()) {
    let url = 'https://gmail.googleapis.com/gmail/v1/users/' + userEmail + '/messages'

    let token = service.getAccessToken();
    let payload = JSON.stringify({labelIds:labels})

    let options = {
      headers: {
        Authorization: "Bearer " + token,
        "content-type": "application/json"
      },
      method: "GET",
      payload:payload,
      //muteHttpExceptions: true
    };

    let response = UrlFetchApp.fetch(url, options);
    //Logger.log(response.getContentText());
    let result = JSON.parse(response.getContentText());
    Logger.log(result)
    return result
    //Logger.log(JSON.stringify(result, null, 2));
  } else {
    Logger.log(service.getLastError());
  }

}


问:
Moviepy is stretching cell phone videos when shot in portrait
Whenever I shoot a video with my cell phone in portrait mode, the listed resolution on the file information ends up as 1920x1080, even though when you play the video on a media player, it displays as 1080x1920. When I read the video into moviepy with:  clip = VideoFileClip('filename.mp4'), it thinks it is a video with a width of 1920, a height of 1080, and a rotation of 90. clip.w == 1920 clip.h == 1080 clip.rotation == 90.

If I don't do anything at all to the clip, but try to write the clip to a new file, for example with the command clip.write_videofile("newfilename.mp4", codec="libx264", audiocodec='libmp3lame', bitrate='6000k', fps=50), it produces the same video only stretched horizontally and squashed vertically. Is there a way to prevent this from happening?


问:
Spring Boot entity not being recognized during build
I'm running into this error when I mvn clean install my Spring Boot application:

```<code>Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.fitzgerald.floorplanmanager.data.Users
</code>```

I've tried adding @EntityScan to my Application class, with and without a defined pathname, but to no avail.
I also have two other Entities aside from Users.  I'm not sure if they are being recognized or if Users was just the first entity that the compiler encountered (my gut says the latter), but I'm not seeing them in the stacktrace.
Here is what my Application class looks like:

```<code>@EntityScan
@SpringBootApplication
public class FloorplanmanagerApplication {

   public static void main(String[] args) {
      SpringApplication.run(FloorplanmanagerApplication.class, args);
   }

}
</code>```

This is my UsersRepository:

```<code>@Transactional
public interface UsersRepository extends CrudRepository<Users, Long> {

}
</code>```

UsersService:

```<code>@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;

    @Override
    public Users saveUsers(Users users) {
        return usersRepository.save(users);
    }
}
</code>```

and finally Users:

```<code>@Entity
@Data
@Table(name = "users")
@NoArgsConstructor
public class Users {

    @Id
    @Column
    private long id;
    @Column
    private String userName;
    @Column
    private String password;
}
</code>```

My file structure looks like this
Also, my data.sql file in com.fitzgerald.floorplanmanager.resources looks like this:

```<code>DROP TABLE IF EXISTS users;

CREATE TABLE users (
    id INT PRIMARY KEY,
    USER_NAME VARCHAR(250) NOT NULL,
    PASSWORD VARCHAR(250) NOT NULL
);

// two more tables are created...

</code>```

I've tried using the folder name entity instead of data, adding @EntityScan("com.fitzgerald.floorplanmanager.data") to the Application class, adding @EnableJpaRepositories, @ComponentScan, and messing with the file structure but I just can't get it to work.
Thanks!

Body:
I'm running into this error when I mvn clean install my Spring Boot application:

Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.fitzgerald.floorplanmanager.data.Users

I've tried adding @EntityScan to my Application class, with and without a defined pathname, but to no avail.
I also have two other Entities aside from Users.  I'm not sure if they are being recognized or if Users was just the first entity that the compiler encountered (my gut says the latter), but I'm not seeing them in the stacktrace.
Here is what my Application class looks like:

@EntityScan
@SpringBootApplication
public class FloorplanmanagerApplication {

   public static void main(String[] args) {
      SpringApplication.run(FloorplanmanagerApplication.class, args);
   }

}

This is my UsersRepository:

@Transactional
public interface UsersRepository extends CrudRepository<Users, Long> {

}

UsersService:

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;

    @Override
    public Users saveUsers(Users users) {
        return usersRepository.save(users);
    }
}

and finally Users:

@Entity
@Data
@Table(name = "users")
@NoArgsConstructor
public class Users {

    @Id
    @Column
    private long id;
    @Column
    private String userName;
    @Column
    private String password;
}

My file structure looks like this
Also, my data.sql file in com.fitzgerald.floorplanmanager.resources looks like this:

DROP TABLE IF EXISTS users;

CREATE TABLE users (
    id INT PRIMARY KEY,
    USER_NAME VARCHAR(250) NOT NULL,
    PASSWORD VARCHAR(250) NOT NULL
);

// two more tables are created...

I've tried using the folder name entity instead of data, adding @EntityScan("com.fitzgerald.floorplanmanager.data") to the Application class, adding @EnableJpaRepositories, @ComponentScan, and messing with the file structure but I just can't get it to work.
Thanks!


问:
BGTaskScheduler.shared.register never gets called
BGTaskScheduler.shared.register never gets called . I even downloaded a projects from github that implemented this -> ex(https://github.com/sreexamus/BackgroundTasksPOC).
Even in these projects the register function does not get called.

```<code>        BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskName, using: nil) { (task) in
        print("background task triggered")
        self.handleBGProcessingTask(task as! BGProcessingTask)
    }

    BGTaskScheduler.shared.register(forTaskWithIdentifier: appRefreshTask, using: nil) { (task) in
        print("background task triggered")
        self.handleBGAppRefreshTask(task as! BGAppRefreshTask)
    }
</code>```

"Background task triggered" never prints. I assume only after registering any BG task will be run, but my tasks are never getting registered. I setup a breakpoint after the register function and used this

```<code>e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.sree.epoc.processingTask"]
</code>```

and got this error

```<code>error: Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes
</code>```

I came across an exact same question but found no answers
BGTaskScheduler.shared.register Not Called

Body:
BGTaskScheduler.shared.register never gets called . I even downloaded a projects from github that implemented this -> ex(https://github.com/sreexamus/BackgroundTasksPOC).
Even in these projects the register function does not get called.

        BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskName, using: nil) { (task) in
        print("background task triggered")
        self.handleBGProcessingTask(task as! BGProcessingTask)
    }

    BGTaskScheduler.shared.register(forTaskWithIdentifier: appRefreshTask, using: nil) { (task) in
        print("background task triggered")
        self.handleBGAppRefreshTask(task as! BGAppRefreshTask)
    }

"Background task triggered" never prints. I assume only after registering any BG task will be run, but my tasks are never getting registered. I setup a breakpoint after the register function and used this

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.sree.epoc.processingTask"]

and got this error

error: Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes

I came across an exact same question but found no answers
BGTaskScheduler.shared.register Not Called


问:
how do I a QEvent::RequestSoftwareInputPanel event in my code
I am using an embedded platform to code using the Qt framework not Qt creator but it causes problems when I try to run my code I just set the size of my screen and it cause my player character to no longer take any inputs anymore I looked up the problem on Qt website and I found what I need to do use the QEvent::requestsoftwareinputpanel but I don't know how to implement it.

I tried to replace the original code that took inputs but it kept breaking when I tried it
here is my code

this is the main file

```<code>#include <QApplication>
#include <QGraphicsScene>
#include "Rect.h"
#include <QGraphicsView>

int main(int argc, char *argv[]){
    QApplication a(argc,argv);

    //how to make a screen
    QGraphicsScene * scene1 = new QGraphicsScene();

    // an item to put into the scene
    Rect * player = new Rect();
    player->setRect(0,0,100,100);

    // focus on item
    player->setFlag(QGraphicsItem::ItemIsFocusable);
    player->setFocus();
    //add item to the scene
    scene1->addItem(player);

    //how to actually see the scene
    QGraphicsView * view = new QGraphicsView(scene1);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // setting screensize
    scene1->setSceneRect(0,0,800,600);
    view->setBaseSize(800,600);
    view->show();

    //setting player pos
    player->setPos(view->width()/2,view->height() - player->rect().height());

    return a.exec();
}
</code>```

the header file for the movment

```<code>//
// Created by krris on 2022-12-07.
//

#ifndef GALAGA_RECT_H
#define GALAGA_RECT_H

#include <QGraphicsRectItem>
#include <QEvent>
class Rect: public QGraphicsRectItem{
    void keyPressEvent(QKeyEvent * event);
};

#endif //GALAGA_RECT_H

</code>```

the file with the code for the movment

```<code>//
// Created by krris on 2022-12-07.
//

#include "Rect.h"
#include <QKeyEvent>
#include <QGraphicsScene>
#include "Bullet.h"
#include <QEvent>

void Rect::keyPressEvent(QKeyEvent * event){
    if (event->key() == Qt::Key_Left){
        QEvent::RequestSoftwareInputPanel;
        setPos(x()-10,y());
    }
    else if (event->key() == Qt::Key_Right){
        setPos(x()+10,y());
    }
    else if (event->key() == Qt::Key_Space){
        // create a bullet
        Bullet * bullet = new Bullet();
        bullet->setPos(x(),y());
        scene()->addItem(bullet);

    }
}
</code>```

Body:
I am using an embedded platform to code using the Qt framework not Qt creator but it causes problems when I try to run my code I just set the size of my screen and it cause my player character to no longer take any inputs anymore I looked up the problem on Qt website and I found what I need to do use the QEvent::requestsoftwareinputpanel but I don't know how to implement it.

I tried to replace the original code that took inputs but it kept breaking when I tried it
here is my code

this is the main file

#include <QApplication>
#include <QGraphicsScene>
#include "Rect.h"
#include <QGraphicsView>

int main(int argc, char *argv[]){
    QApplication a(argc,argv);

    //how to make a screen
    QGraphicsScene * scene1 = new QGraphicsScene();

    // an item to put into the scene
    Rect * player = new Rect();
    player->setRect(0,0,100,100);

    // focus on item
    player->setFlag(QGraphicsItem::ItemIsFocusable);
    player->setFocus();
    //add item to the scene
    scene1->addItem(player);

    //how to actually see the scene
    QGraphicsView * view = new QGraphicsView(scene1);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // setting screensize
    scene1->setSceneRect(0,0,800,600);
    view->setBaseSize(800,600);
    view->show();

    //setting player pos
    player->setPos(view->width()/2,view->height() - player->rect().height());

    return a.exec();
}

the header file for the movment

//
// Created by krris on 2022-12-07.
//

#ifndef GALAGA_RECT_H
#define GALAGA_RECT_H

#include <QGraphicsRectItem>
#include <QEvent>
class Rect: public QGraphicsRectItem{
    void keyPressEvent(QKeyEvent * event);
};

#endif //GALAGA_RECT_H

the file with the code for the movment

//
// Created by krris on 2022-12-07.
//

#include "Rect.h"
#include <QKeyEvent>
#include <QGraphicsScene>
#include "Bullet.h"
#include <QEvent>

void Rect::keyPressEvent(QKeyEvent * event){
    if (event->key() == Qt::Key_Left){
        QEvent::RequestSoftwareInputPanel;
        setPos(x()-10,y());
    }
    else if (event->key() == Qt::Key_Right){
        setPos(x()+10,y());
    }
    else if (event->key() == Qt::Key_Space){
        // create a bullet
        Bullet * bullet = new Bullet();
        bullet->setPos(x(),y());
        scene()->addItem(bullet);

    }
}


问:
have no error info when call servicenow token api via logstash
have no error info but failed when call servicenow token api via logstash. It was working in postman.error info pic
postman pic
configuration file pic

any dalao know how to fix it please?


问:
Echo a string containing a variable, with spaces at both ends?
How would I echo a string containing a variable, that has a lot of spaces before and after the var?

Desired output is:

|                        BLAH v1.2.3                          |
```
<p>The <code>$v</code> var is fine, and contains the proper value.</p>
<p><strong>Here's what I have so far:</strong></p>
```#!/bin/bash

v=$(cat version.json)

echo '|                        BLAH v${v}                          |'
```
<p><strong>Update (see comments):</strong></p>
```#!/bin/bash

v="$(cat version.json)"

echo "|                        BLAH v${v}                          |"
```

Results in:

Notice:

how the front space shows up before the front pipe

the pipe bumps up next to the first word

the first 2 letters have vanished into the ether (lol)

and (cant tell for sure where the last spaces are there) but the last pipe ended up on the next line.

Body:
How would I echo a string containing a variable, that has a lot of spaces before and after the var?

Desired output is:

|                        BLAH v1.2.3                          |

The $v var is fine, and contains the proper value.

Here's what I have so far:

#!/bin/bash

v=$(cat version.json)

echo '|                        BLAH v${v}                          |'

Update (see comments):

#!/bin/bash

v="$(cat version.json)"

echo "|                        BLAH v${v}                          |"

Results in:

Notice:

how the front space shows up before the front pipe

the pipe bumps up next to the first word

the first 2 letters have vanished into the ether (lol)

and (cant tell for sure where the last spaces are there) but the last pipe ended up on the next line.


问:
Correct way to pass data to custom hooks in ReactJs
I have two custom hooks in ReactJs project. I like to know is it proper to have one custom hook to pass data to another custom hook

App.js

```<code>const App = () => {
  // Custom hook 1
  const { connectPin, newConnectionPin } = useRoomGenerator();

  // Custom hook 2 needs connection pin value
  const { joined } = useDevices(connectPin);
}
</code>```

I would like to know if this is okay or should we not send data from hook 1 to hook 2.

Body:
I have two custom hooks in ReactJs project. I like to know is it proper to have one custom hook to pass data to another custom hook

App.js

const App = () => {
  // Custom hook 1
  const { connectPin, newConnectionPin } = useRoomGenerator();

  // Custom hook 2 needs connection pin value
  const { joined } = useDevices(connectPin);
}

I would like to know if this is okay or should we not send data from hook 1 to hook 2.


问:
Trino unexpected partition name error =__HIVE_DEFAULT_PARTITION__ != []
The table is of parquet format and sits in Minio storage.  I create the parquet file.  After the parquet file is inserted into Minio, I run the following command to add the new partition:
call system.sync_partition_metadata('myschema', 'mytable', 'ADD', true)

However, it errors out
[Code: 65551, SQL State: ]  Query failed (#20221210_041833_00033_4iqfp): unexpected partition name: mypartitionfield=HIVE_DEFAULT_PARTITION != []

Earlier on I did insert an empty partition value.  How can I remedy this issue?  The mypartitionfield is of type date.

I tried dropping and creating the table, as well as deleting the Minio folder structure and creating it again.  None worked.


问:
Using pybind11 to call python functions in C++
my cpp file is this:

```<code>#include <pybind11/pybind11.h>
#include <iostream>

namespace py = pybind11;

int main() {
    auto math = pybind11::module::import("math");
    auto resultobj = math.attr("sqrt")(2);
    double result = resultobj.cast<double>();

    std::cout << "The square root of 2 is: " << result << "\n";
}
</code>```

when I try to compile it using this command:

```<code>g++ -Wall -std=c++11 -fPIC -I/home/qwert/miniconda3/include -I/home/qwert/miniconda3/include/python3.9 fn_call.cpp
</code>```

I get a lot of errors which I have not been able to fix

first few lines of errors:

```<code>/usr/bin/ld: /tmp/cc61RVdo.o: in function `_Py_DECREF':
fn_call.cpp:(.text+0x74): undefined reference to `_Py_Dealloc'
/usr/bin/ld: /tmp/cc61RVdo.o: in function `pybind11::type_error::set_error() const':
fn_call.cpp:(.text._ZNK8pybind1110type_error9set_errorEv[_ZNK8pybind1110type_error9set_errorEv]+0x2d): undefined reference to `PyExc_TypeError'
/usr/bin/ld: fn_call.cpp:(.text._ZNK8pybind1110type_error9set_errorEv[_ZNK8pybind1110type_error9set_errorEv]+0x3b): undefined reference to `PyErr_SetString'
/usr/bin/ld: /tmp/cc61RVdo.o: in function `pybind11::cast_error::set_error() const':
fn_call.cpp:(.text._ZNK8pybind1110cast_error9set_errorEv[_ZNK8pybind1110cast_error9set_errorEv]+0x2d): undefined reference to `PyExc_RuntimeError'
/usr/bin/ld: fn_call.cpp:(.text._ZNK8pybind1110cast_error9set_errorEv[_ZNK8pybind1110cast_error9set_errorEv]+0x3b): undefined reference to `PyErr_SetString'

</code>```

I have tried reinstalling python, pybind11, and even trying it on a different linux machine

Body:
my cpp file is this:

#include <pybind11/pybind11.h>
#include <iostream>

namespace py = pybind11;

int main() {
    auto math = pybind11::module::import("math");
    auto resultobj = math.attr("sqrt")(2);
    double result = resultobj.cast<double>();

    std::cout << "The square root of 2 is: " << result << "\n";
}

when I try to compile it using this command:

g++ -Wall -std=c++11 -fPIC -I/home/qwert/miniconda3/include -I/home/qwert/miniconda3/include/python3.9 fn_call.cpp

I get a lot of errors which I have not been able to fix

first few lines of errors:

/usr/bin/ld: /tmp/cc61RVdo.o: in function `_Py_DECREF':
fn_call.cpp:(.text+0x74): undefined reference to `_Py_Dealloc'
/usr/bin/ld: /tmp/cc61RVdo.o: in function `pybind11::type_error::set_error() const':
fn_call.cpp:(.text._ZNK8pybind1110type_error9set_errorEv[_ZNK8pybind1110type_error9set_errorEv]+0x2d): undefined reference to `PyExc_TypeError'
/usr/bin/ld: fn_call.cpp:(.text._ZNK8pybind1110type_error9set_errorEv[_ZNK8pybind1110type_error9set_errorEv]+0x3b): undefined reference to `PyErr_SetString'
/usr/bin/ld: /tmp/cc61RVdo.o: in function `pybind11::cast_error::set_error() const':
fn_call.cpp:(.text._ZNK8pybind1110cast_error9set_errorEv[_ZNK8pybind1110cast_error9set_errorEv]+0x2d): undefined reference to `PyExc_RuntimeError'
/usr/bin/ld: fn_call.cpp:(.text._ZNK8pybind1110cast_error9set_errorEv[_ZNK8pybind1110cast_error9set_errorEv]+0x3b): undefined reference to `PyErr_SetString'

I have tried reinstalling python, pybind11, and even trying it on a different linux machine


问:
Not able to access blazor website from other computers
I am trying to host a Blazor website on a local Windows machine via IIS, and it can be accessed from the same machine using IP address in the URL like https://10.0.0.123:8080/myblazor, and I also make sure port 8080 is opened on the firewall, but I am not able to access my Blazor website using the same URL from other computers. Does anyone know why? Thanks in advance!

I added another regular website (simple HTML website) and I can access from other computers. So doesn't look like it's the firewall issue or IIS issue.


问:
Border Plot Not Displaying
I am plotting a gpd map with an overlay of scatterplot and circle patches. However, when I run the code, the output only displays the scatterplot and circle patches without the border maps. There is nothing wrong with the map as I tried running it separately and it is showing the right output. Please see the image description below for how the plot looks like.

Here is the code:

```<code>def plot_dbscan(points, dbscan, title, pt_sizer=1, plot_circles=False):
    # Index noise and clusters out of the dbscan points
    noise = points[dbscan.labels_ == -1]
    clusters = points[dbscan.labels_ != -1]

    # Plot country border
    fig, ax = plt.subplots(1, figsize=(12,8))
    map_1_prj.plot(ax=ax, fc='None', ec='k', linewidth=1.5)

    # Allow relative point size adjustment with pt_sizer argument
    sns.scatterplot(x=noise[:,0], y=noise[:,1], ax=ax, alpha=1, s=2*pt_sizer, color='gray')
    sns.scatterplot(x=clusters[:,0], y=clusters[:,1], ax=ax, s=4*pt_sizer, color='red')

    # Option to plot a minimum bounding circle around each cluster
    if plot_circles:
        for label in np.unique(dbscan.labels_):
            if label != -1:
                cluster_points = points[dbscan.labels_ == label]
                # Get minimum bounding circle using pointpats.centrography.minimum_bounding_circle()
                (center_x, center_y), radius = minimum_bounding_circle(cluster_points)
                # Create matplotlib patch
                circle_patch = mpatches.Circle((center_x, center_y), radius=radius, fc='None', ec='yellow', linewidth=2)
                ax.add_patch(circle_patch)

    ax.axis('equal')

    # Limit bounds of plot to earthquake data
    ax.set_xlim(gdf_prj.total_bounds[0], gdf_prj.total_bounds[2])
    ax.set_ylim(gdf_prj.total_bounds[1], gdf_prj.total_bounds[3])

    # Manually prepare legend items
    Ph_border = mlines.Line2D([], [], color='k', linewidth=1.5, label='Philippine Border')
    noise_l = mlines.Line2D([], [], marker='.', linewidth=0, markersize=4,
                            color='gray', label='Noise')

    if plot_circles:
        # Draw yellow circle around red point for legend
        mec = 'yellow'
    else:
        mec = 'None'

    clusters_l = mlines.Line2D([], [], marker='.', linewidth=0,
                               markersize=12, color='red', markeredgecolor=mec,
                               label='DBSCAN Clusters')
    # Define legend
    plt.legend(handles=[Ph_border, noise_l, clusters_l])

    plt.title(title)

    plt.show()

</code>```

Title: Border Plot Not Displaying

Body:
I am plotting a gpd map with an overlay of scatterplot and circle patches. However, when I run the code, the output only displays the scatterplot and circle patches without the border maps. There is nothing wrong with the map as I tried running it separately and it is showing the right output. Please see the image description below for how the plot looks like.

Here is the code:

def plot_dbscan(points, dbscan, title, pt_sizer=1, plot_circles=False):
    # Index noise and clusters out of the dbscan points
    noise = points[dbscan.labels_ == -1]
    clusters = points[dbscan.labels_ != -1]

    # Plot country border
    fig, ax = plt.subplots(1, figsize=(12,8))
    map_1_prj.plot(ax=ax, fc='None', ec='k', linewidth=1.5)

    # Allow relative point size adjustment with pt_sizer argument
    sns.scatterplot(x=noise[:,0], y=noise[:,1], ax=ax, alpha=1, s=2*pt_sizer, color='gray')
    sns.scatterplot(x=clusters[:,0], y=clusters[:,1], ax=ax, s=4*pt_sizer, color='red')

    # Option to plot a minimum bounding circle around each cluster
    if plot_circles:
        for label in np.unique(dbscan.labels_):
            if label != -1:
                cluster_points = points[dbscan.labels_ == label]
                # Get minimum bounding circle using pointpats.centrography.minimum_bounding_circle()
                (center_x, center_y), radius = minimum_bounding_circle(cluster_points)
                # Create matplotlib patch
                circle_patch = mpatches.Circle((center_x, center_y), radius=radius, fc='None', ec='yellow', linewidth=2)
                ax.add_patch(circle_patch)

    ax.axis('equal')

    # Limit bounds of plot to earthquake data
    ax.set_xlim(gdf_prj.total_bounds[0], gdf_prj.total_bounds[2])
    ax.set_ylim(gdf_prj.total_bounds[1], gdf_prj.total_bounds[3])

    # Manually prepare legend items
    Ph_border = mlines.Line2D([], [], color='k', linewidth=1.5, label='Philippine Border')
    noise_l = mlines.Line2D([], [], marker='.', linewidth=0, markersize=4,
                            color='gray', label='Noise')

    if plot_circles:
        # Draw yellow circle around red point for legend
        mec = 'yellow'
    else:
        mec = 'None'

    clusters_l = mlines.Line2D([], [], marker='.', linewidth=0,
                               markersize=12, color='red', markeredgecolor=mec,
                               label='DBSCAN Clusters')
    # Define legend
    plt.legend(handles=[Ph_border, noise_l, clusters_l])

    plt.title(title)

    plt.show()


问:
Mixing RTL and LTR text in html element
I would like to Mix English and Arabic in one html element like a div that it is editable using the contenteditable="true"

```<code><div contenteditable="true" dir="rtl">
عمل Blueberry Cheesecake اللذيذة بثلاثة طرق مختلفة
</div>
</code>```

Which should display:

Now this behavior works as expected, when I edit the RTL text I get the cursor & direction correct, and when I type LTR text the cursor will support that as well.

The behavior I do not like is when I try to use the arrows keys to move left and right between the letters or highlight the text. it will jump when highlighting between RTL and LTR.

Example: try to navigate through the letters or highlight, it will start to jump based on the direction of the lang.

عمل Blueberry Cheesecake اللذيذة بثلاثة طرق مختلفة
```

Now I understand that this is the default algorithm used to control the text. I like this behavior when editing(typing) but not when I highlight or use arrows.

Title: Mixing RTL and LTR text in html element

Body:
I would like to Mix English and Arabic in one html element like a div that it is editable using the contenteditable="true"

عمل Blueberry Cheesecake اللذيذة بثلاثة طرق مختلفة

Which should display:

Now this behavior works as expected, when I edit the RTL text I get the cursor & direction correct, and when I type LTR text the cursor will support that as well.

The behavior I do not like is when I try to use the arrows keys to move left and right between the letters or highlight the text. it will jump when highlighting between RTL and LTR.

Example: try to navigate through the letters or highlight, it will start to jump based on the direction of the lang.

عمل Blueberry Cheesecake اللذيذة بثلاثة طرق مختلفة

Now I understand that this is the default algorithm used to control the text. I like this behavior when editing(typing) but not when I highlight or use arrows.


问:
how can i get the word sequence of a concatenated words by java?
I want to get the word sequence of a combining words, like a variable name - "NullPointException".

I want to get the "Null","point","Exception" by java.

So, Are there any open source libraries for java that I can use? Or what such tasks are called so I can search again.

I know that lingpipe can split a sentence, but is this a task it can accomplish?

or how can i do this by java? I know the python lib “wordninja”


问:
Error running spring boot with error : Error creating bean with name 'entityManagerFactory' defined in class path resource, Invocation of init
So i get this error when running spring boot with just add controller like this and nothing else :

@Controller
public class ConsumerController {

    @GetMapping
    public String test(){
        return "HALLO WORLD";
    }
}
```
<p>Here is my database application.properties:</p>
```spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/seasalt
spring.datasource.username=postgres
spring.datasource.password=admin
server.port=8081
```
<p>Here is my pom xml:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.6</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.seasalt.cunsomer</groupId>
   <artifactId>Seasalt-Cunsomer</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Seasalt-Cunsomer</name>
   <description>Simple Cunsomer API</description>
   <properties>
      <java.version>11</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>

</code>```

I try to run it as usual after download the spring boot file from springboot io.

Here is the screenshot of the postgres:
POSTGRES SCREENSHOT

Body:
So i get this error when running spring boot with just add controller like this and nothing else :

@Controller
public class ConsumerController {

    @GetMapping
    public String test(){
        return "HALLO WORLD";
    }
}

Here is my database application.properties:

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/seasalt
spring.datasource.username=postgres
spring.datasource.password=admin
server.port=8081

Here is my pom xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.6</version>
      <relativePath/>
   </parent>
   <groupId>com.seasalt.cunsomer</groupId>
   <artifactId>Seasalt-Cunsomer</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Seasalt-Cunsomer</name>
   <description>Simple Cunsomer API</description>
   <properties>
      <java.version>11</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>

I try to run it as usual after download the spring boot file from springboot io.

Here is the screenshot of the postgres:
POSTGRES SCREENSHOT


问:
Is there any way to scrape data if DUO authentication is required for a website?
I am trying to get the job listings from the workday portal of my university. The portal url is https://www.myworkday.com/northeastern/d/home.htmld. When this is clicked, if the cookies are correct, it only asks me for the login data and bypasses the DUO auth. But when I send a post request to this website with my data payload, it gives me an error NoSuchExecutionFlow. I am assuming it needs the duo auth and thats probably why it doesnt allow me to go further. Is there any way to make this work?

I tried using parseHub and that gives the same error as well. I tried getting the cookies through the browser and passing those in as well but it lands on the same page everytime. It's supposed to go to this website, redirect to Northeastern for authentication, then come back to workday for the portal.


问:
Easier way to display day.js in multiple locations?
I'm currently studying web development and I'm hoping one of you guys may help.

I'm currently coding the mandatory weather app that everyone and his dog has made lol.

My problem is that on the homepage I have 3 cards displaying with 3 different cities.
I want to display the current date underneath each city by using class="date".

But to do it in 3 instances on the same I've had to use date,date2 and date3. Which I'm thinking a for loop or something similar could easily fix rather than defining it 3 times.

Any help appreciated!
Thanks!

HTML

```<code><section class="row">
            <h2>  Cities</h2>
            <section class="row">
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    London
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date" class="date">date </span> <br/>
                      Temp:<span id="temp"></span>
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    Birmingham
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date2" class="date">date </span> <br/>
                      Temp:<span id="temp"></span>
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    Wolverhampton
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date3" class="date">date </span> <br/>
                      Temp:<span id="temp"></span>
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
            </section>
          </div>
          <div class="col-xs-12 col-lg-3">
            <h2>Search</h2>
            <input class="Search col-12 border-radius pb-1" placeholder="Enter City" id="search">
            <ul class="list-group mb-2 pb-2">
                <li class="list-group-item">An item</li>
                <li class="list-group-item">A second item</li>
                <li class="list-group-item">A third item</li>
                <li class="list-group-item">A fourth item</li>
                <li class="list-group-item">And a fifth one</li>
              </ul>
          </div>
          <div class="col-xs-9 col-lg-9">
            <h2 class="subtitle">Results:</h2>
            <!--search results class="results-item"-->
          </div>
        </section>
</code>```

JavaScript/JQuery

```<code>let nowDate = now.format('D / M / YY')
let date = $('#date')
let date2 = $('#date2')
let date3 = $('#date3')
date.text(nowDate);
date2.text(nowDate);
date3.text(nowDate);
</code>```

Body:
I'm currently studying web development and I'm hoping one of you guys may help.

I'm currently coding the mandatory weather app that everyone and his dog has made lol.

My problem is that on the homepage I have 3 cards displaying with 3 different cities.
I want to display the current date underneath each city by using class="date".

But to do it in 3 instances on the same I've had to use date,date2 and date3. Which I'm thinking a for loop or something similar could easily fix rather than defining it 3 times.

Any help appreciated!
Thanks!

HTML

  Cities

                    London

                      date

                      Temp:
                      Wind:
                      Humid:

                    Birmingham

                      date

                      Temp:
                      Wind:
                      Humid:

                    Wolverhampton

                      date

                      Temp:
                      Wind:
                      Humid:

Search

            <input class="Search col-12 border-radius pb-1" placeholder="Enter City" id="search">

An item

A second item

A third item

A fourth item

And a fifth one

Results:

JavaScript/JQuery

let nowDate = now.format('D / M / YY')
let date = $('#date')
let date2 = $('#date2')
let date3 = $('#date3')
date.text(nowDate);
date2.text(nowDate);
date3.text(nowDate);


问:
Is Rust hash map storing the same key twice?
I am going through the Rust language book, and was going through the hash map section.

At the end of the section there is a quiz, which asks what would be the output of the following code.

```<code>use std::collections::HashMap;
fn main() {
    let mut h: HashMap<char, Vec<usize>> = HashMap::new();
    for (i, c) in "hello!".chars().enumerate() {
        h.entry(c).or_insert(Vec::new()).push(i);
    }
    let mut sum = 0;
    for i in h.get(&'l').unwrap() {
        sum += *i;
    }
    println!("{}", sum);
}
</code>```

The answer is 5, and I confirmed by executing the same. The explanation given is following

This program stores a vector of indexes for each occurrence of a given letter into a hashmap. Then it sums all the indexes for the letter 'l', which occurs at indexes 2 and 3 in the string "hello!".

Now when I look at section adding a new key and updating value based on old one, it seems Rust only allows unique key for a hash map as per definition.

However, when I run the above program with an extra print statement in the for loop

```<code>for i in h.get(&'l').unwrap() {
    println!("{}", i);
    sum += *i;
}
</code>```

It seems there are two entries for the character l. As per my understanding, when iterating over string hello! when the first for loop encounters the second l it should update and overwrite the index value of l from 2 to 3, instead of making another entry with key l and value 3.

So the question is, is Rust allowing duplicate keys? Somehow this is not making sense.

Body:
I am going through the Rust language book, and was going through the hash map section.

At the end of the section there is a quiz, which asks what would be the output of the following code.

use std::collections::HashMap;
fn main() {
    let mut h: HashMap<char, Vec<usize>> = HashMap::new();
    for (i, c) in "hello!".chars().enumerate() {
        h.entry(c).or_insert(Vec::new()).push(i);
    }
    let mut sum = 0;
    for i in h.get(&'l').unwrap() {
        sum += *i;
    }
    println!("{}", sum);
}

The answer is 5, and I confirmed by executing the same. The explanation given is following

This program stores a vector of indexes for each occurrence of a given letter into a hashmap. Then it sums all the indexes for the letter 'l', which occurs at indexes 2 and 3 in the string "hello!".

Now when I look at section adding a new key and updating value based on old one, it seems Rust only allows unique key for a hash map as per definition.

However, when I run the above program with an extra print statement in the for loop

for i in h.get(&'l').unwrap() {
    println!("{}", i);
    sum += *i;
}

It seems there are two entries for the character l. As per my understanding, when iterating over string hello! when the first for loop encounters the second l it should update and overwrite the index value of l from 2 to 3, instead of making another entry with key l and value 3.

So the question is, is Rust allowing duplicate keys? Somehow this is not making sense.


问:
Postfix / Procmail causing email body to become modified
I have recently upgraded my Postfix installation to 3.5.13.  This was a significant upgrade, I believe that I was running 2.x before.  I have a number of real users and a number of applications that receive e-mail.  Applications receiving email have dedicated entries in my aliases file eg:
app1@mail.com: "| /usr/local/bin/app1"
Much of my email is from system auditing and results in a number of automatically generated e-mails (like logcheck).  I use some custom-written applications to parse these e-mails for potential problems (like intrusion) and manipulate the firewall rules.
This upgrade has cause automatic word wrap (in the form of extra line-breaks) to be inserted into the pipe going to the program which has caused many of the programs to no longer function correctly eg:
original (1 line):
<date> server postfix/smtpd[<pid>]: disconnect from unknown[<ip address>] ehlo=1 auth=0/1 rset=1 quit=1 commands=3/4
now becomes (2 lines):

```<code><date> server postfix/smtpd[<pid>]: disconnect from
unknown[<ip address>] ehlo=1 auth=0/1 rset=1 quit=1 commands=3/4
</code>```

Likewise, the resulting mail file delivered to ~/Mailbox/cur becomes:

```<code><date> server postfix/smtpd[<pid>]: disconnect from unknown[<ip=
address>] ehlo=3D1 auth=3D0/1 quit=3D1 commands=3D3/4
</code>```

How can I disable this formatting and allow delivery / pipe of the email body unmodified?  This is causing a severe headache.

Body:
I have recently upgraded my Postfix installation to 3.5.13.  This was a significant upgrade, I believe that I was running 2.x before.  I have a number of real users and a number of applications that receive e-mail.  Applications receiving email have dedicated entries in my aliases file eg:
app1@mail.com: "| /usr/local/bin/app1"
Much of my email is from system auditing and results in a number of automatically generated e-mails (like logcheck).  I use some custom-written applications to parse these e-mails for potential problems (like intrusion) and manipulate the firewall rules.
This upgrade has cause automatic word wrap (in the form of extra line-breaks) to be inserted into the pipe going to the program which has caused many of the programs to no longer function correctly eg:
original (1 line):
<date> server postfix/smtpd[<pid>]: disconnect from unknown[<ip address>] ehlo=1 auth=0/1 rset=1 quit=1 commands=3/4
now becomes (2 lines):

<date> server postfix/smtpd[<pid>]: disconnect from
unknown[<ip address>] ehlo=1 auth=0/1 rset=1 quit=1 commands=3/4

Likewise, the resulting mail file delivered to ~/Mailbox/cur becomes:

<date> server postfix/smtpd[<pid>]: disconnect from unknown[<ip=
address>] ehlo=3D1 auth=3D0/1 quit=3D1 commands=3D3/4

How can I disable this formatting and allow delivery / pipe of the email body unmodified?  This is causing a severe headache.


问:
how to branch cover multiple or statement in junit java
```<code>Branch branch;
date lastUpdated;
date todayUpdated

if(branch == null || branch.isEmpty() || lastUpdated == null || todayUpdate > lastUpdated)
</code>```

i have wriited test cases-

```<code>TFFFF
FTFFF
FFTFF
FFFTF
FFFFF
</code>```

but still not able to cover complete branch.

Body:
Branch branch;
date lastUpdated;
date todayUpdated

if(branch == null || branch.isEmpty() || lastUpdated == null || todayUpdate > lastUpdated)

i have wriited test cases-

TFFFF
FTFFF
FFTFF
FFFTF
FFFFF

but still not able to cover complete branch.


问:
Get openAPI.json with Swagger and Next.js
I want to generate openapi.json along with the swagger endpoint. I'm using next-swagger-doc to write swagger specifications, but want to add openapi.json file link in the swagger. The version I'm using is OpenAPI 3.0.

The link can be seen here, below the title and base url, the link to the swagger file
https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml

I tried on searching for the tag, but couldn't find it, and it's in swagger 2.0/OAS 2.0. Any idea how I could add the same in OAS 3.0?


问:
Jank in CSS transform animation
I'm getting some jank/stutter in my animation in my React App. I have a simple carousel with infinite scroll. But I'm getting the jank when I look at the site on my phone and when I try to use .scss instead of css files. You can see the jank/stutter in the attached codepen. All of the css is in index.scss. HTML and javascript are in App.js. Please let me know if you need any more info, this has been driving me crazy.

https://codesandbox.io/s/codepen-with-react-forked-zq6lly?file=/src/components/App.js

Title: Jank in CSS transform animation


问:
Why can't I update nix?
I'm using nixos on wsl.

According to this link

```<code>nix --version
</code>```

shoud return 2.11.0 . On my computer this is 2.8.1 Therefore I don't have the last nix version.

I've fast followed this procedure. I've only changed nixpkg with nixos because I'm on nixos (as the documentation say)

```<code>nix-channel --update;
nix-env -iA nixos.nix nixos.cacert;
</code>```

First  try:

```<code>nix --version
</code>```

2.8

I continue as if I had more than one user

```<code>systemctl daemon-reload;
systemctl restart nix-daemon

nix --version
</code>```

2.8

Why I don't have the right version

Title: Why can't I update nix?

Body:
I'm using nixos on wsl.

According to this link

nix --version

shoud return 2.11.0 . On my computer this is 2.8.1 Therefore I don't have the last nix version.

I've fast followed this procedure. I've only changed nixpkg with nixos because I'm on nixos (as the documentation say)

nix-channel --update;
nix-env -iA nixos.nix nixos.cacert;

First  try:

nix --version

2.8

I continue as if I had more than one user

systemctl daemon-reload;
systemctl restart nix-daemon

nix --version

2.8

Why I don't have the right version


问:
How can I run a mongo setup script in a BitBucket Pipelines service container?

Does Bitbucket Pipelines spin up service container with a build context of my source code? I ask because mongo images allow you to put setup scripts in a special folder to be automatically run

Does Bitbucket Pipelines allow any other way to copy files or run commands on a service container? If option 1 is a "no", then I want to know if I can copy my scripts over another way and run them within the service container

Are there any other options for running my mongo shell script on the BitBucket Pipelines service image other than downloading and installing mongoshell on the primary build container and running it from there?


问:
AttributeError: 'StringVar' object has no attribute 'decode'
I am making a YouTube video downloader mixed with a YouTube playlist downloader and I don't know how to fix this error. I have tried a couple other ways to write the pldownload function (this is supposed to be the playlist download function) one of them did not work at all and the other gave this same traceback.

Here is my code:

#Imports
import customtkinter
from pytube import YouTube
from tkinter import *
from pytube.cli import on_progress
from pytube import Playlist

customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

root = customtkinter.CTk()
root.geometry("500x450")
root.title("YouTube Video Downloader")

#Functions
def download():
    try:
        url = YouTube(str(link.get()))
        video = url.streams.get_by_itag(22)
        video.download("Video Output")
        label = customtkinter.CTkLabel(tabview.tab("YT Video"), text="Download Success :)", font=("Roboto", 10))
        label.pack(padx=10, pady=12)
    except:
        label = customtkinter.CTkLabel(tabview.tab("YT Video"), text="Download Failed :(", font=("Roboto", 10))
        label.pack(padx=10, pady=12)

def pldownload():
    playlist = Playlist(pllink)
    print("Total Videos: ", len(playlist.video_urls))
    for video_url in playlist.video_urls:
        yt = YouTube(video_url, on_progress_callback=on_progress)
        stream = yt.streams.get_by_itag(22)
        label = customtkinter.CTkLabel(tabview.tab("YT Playlist"), text=(yt.title))
        stream.download(filename=yt.title+".mp4")

#Window Widgets
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill='both', expand=True)

label = customtkinter.CTkLabel(master=frame, text="YouTube Video Downloader", font=("Roboto", 24))
label.pack(pady=12, padx=10)

#Tab View
tabview = customtkinter.CTkTabview(master=frame, width=150, corner_radius=0)
tabview.pack(padx=10, pady=12)
tabview.add("YT Video")
tabview.add("YT Playlist")
tabview.tab("YT Video")
tabview.tab("YT Playlist")

label_tab1 = customtkinter.CTkLabel(tabview.tab("YT Video"), text="Download YouTube Video", font=("Roboto", 16))
label_tab1.pack(padx=10, pady=12)
link = StringVar()
entry_tab1 = customtkinter.CTkEntry(tabview.tab("YT Video"), textvariable=link)
entry_tab1.pack(padx=10, pady=12)
button_tab1 = customtkinter.CTkButton(tabview.tab("YT Video"), text="Download", command=download)
button_tab1.pack(padx=10, pady=12)

label_tab2 = customtkinter.CTkLabel(tabview.tab("YT Playlist"), text="Download YouTube Playlist", font=("Roboto", 16))
label_tab2.pack(padx=10, pady=12)
pllink = StringVar()
entry_tab2 = customtkinter.CTkEntry(tabview.tab("YT Playlist"), textvariable=pllink)
entry_tab2.pack(padx=10, pady=12)
button_tab2 = customtkinter.CTkButton(tabview.tab("YT Playlist"), text="Download", command=pldownload)
button_tab2.pack(padx=10, pady=12)

#Do NOT Touch
root.mainloop()

```
<p>Here is my traceback:</p>
```Traceback (most recent call last):
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 531, in _clicked
    self._command()
  File "c:\Users\super\Code\YT Video Download\ytDownloader.py", line 29, in pldownload
    print("Total Videos: ", len(playlist.video_urls))
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\helpers.py", line 89, in __len__
    self.generate_all()
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\helpers.py", line 105, in generate_all
    next_item = next(self.gen)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 281, in url_generator
    for page in self._paginate():
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 118, in _paginate
    json.dumps(extract.initial_data(self.html))
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 58, in html
    self._html = request.get(self.playlist_url)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 48, in playlist_url
    return f"https://www.youtube.com/playlist?list={self.playlist_id}"
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 39, in playlist_id
    self._playlist_id = extract.playlist_id(self._input_url)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\extract.py", line 150, in playlist_id
    parsed = urllib.parse.urlparse(url)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 392, in urlparse
    url, scheme, _coerce_result = _coerce_args(url, scheme)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 128, in _coerce_args
    return _decode_args(args) + (_encode_result,)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 112, in _decode_args
    return tuple(x.decode(encoding, errors) if x else '' for x in args)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 112, in <genexpr>
    return tuple(x.decode(encoding, errors) if x else '' for x in args)
AttributeError: 'StringVar' object has no attribute 'decode'
```

I've tried looking around YouTube for an answer. It was not very helpful.

Body:
I am making a YouTube video downloader mixed with a YouTube playlist downloader and I don't know how to fix this error. I have tried a couple other ways to write the pldownload function (this is supposed to be the playlist download function) one of them did not work at all and the other gave this same traceback.

Here is my code:

#Imports
import customtkinter
from pytube import YouTube
from tkinter import *
from pytube.cli import on_progress
from pytube import Playlist

customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

root = customtkinter.CTk()
root.geometry("500x450")
root.title("YouTube Video Downloader")

#Functions
def download():
    try:
        url = YouTube(str(link.get()))
        video = url.streams.get_by_itag(22)
        video.download("Video Output")
        label = customtkinter.CTkLabel(tabview.tab("YT Video"), text="Download Success :)", font=("Roboto", 10))
        label.pack(padx=10, pady=12)
    except:
        label = customtkinter.CTkLabel(tabview.tab("YT Video"), text="Download Failed :(", font=("Roboto", 10))
        label.pack(padx=10, pady=12)

def pldownload():
    playlist = Playlist(pllink)
    print("Total Videos: ", len(playlist.video_urls))
    for video_url in playlist.video_urls:
        yt = YouTube(video_url, on_progress_callback=on_progress)
        stream = yt.streams.get_by_itag(22)
        label = customtkinter.CTkLabel(tabview.tab("YT Playlist"), text=(yt.title))
        stream.download(filename=yt.title+".mp4")

#Window Widgets
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill='both', expand=True)

label = customtkinter.CTkLabel(master=frame, text="YouTube Video Downloader", font=("Roboto", 24))
label.pack(pady=12, padx=10)

#Tab View
tabview = customtkinter.CTkTabview(master=frame, width=150, corner_radius=0)
tabview.pack(padx=10, pady=12)
tabview.add("YT Video")
tabview.add("YT Playlist")
tabview.tab("YT Video")
tabview.tab("YT Playlist")

label_tab1 = customtkinter.CTkLabel(tabview.tab("YT Video"), text="Download YouTube Video", font=("Roboto", 16))
label_tab1.pack(padx=10, pady=12)
link = StringVar()
entry_tab1 = customtkinter.CTkEntry(tabview.tab("YT Video"), textvariable=link)
entry_tab1.pack(padx=10, pady=12)
button_tab1 = customtkinter.CTkButton(tabview.tab("YT Video"), text="Download", command=download)
button_tab1.pack(padx=10, pady=12)

label_tab2 = customtkinter.CTkLabel(tabview.tab("YT Playlist"), text="Download YouTube Playlist", font=("Roboto", 16))
label_tab2.pack(padx=10, pady=12)
pllink = StringVar()
entry_tab2 = customtkinter.CTkEntry(tabview.tab("YT Playlist"), textvariable=pllink)
entry_tab2.pack(padx=10, pady=12)
button_tab2 = customtkinter.CTkButton(tabview.tab("YT Playlist"), text="Download", command=pldownload)
button_tab2.pack(padx=10, pady=12)

#Do NOT Touch
root.mainloop()

Here is my traceback:

Traceback (most recent call last):
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 531, in _clicked
    self._command()
  File "c:\Users\super\Code\YT Video Download\ytDownloader.py", line 29, in pldownload
    print("Total Videos: ", len(playlist.video_urls))
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\helpers.py", line 89, in __len__
    self.generate_all()
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\helpers.py", line 105, in generate_all
    next_item = next(self.gen)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 281, in url_generator
    for page in self._paginate():
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 118, in _paginate
    json.dumps(extract.initial_data(self.html))
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 58, in html
    self._html = request.get(self.playlist_url)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 48, in playlist_url
    return f"https://www.youtube.com/playlist?list={self.playlist_id}"
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\contrib\playlist.py", line 39, in playlist_id
    self._playlist_id = extract.playlist_id(self._input_url)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\extract.py", line 150, in playlist_id
    parsed = urllib.parse.urlparse(url)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 392, in urlparse
    url, scheme, _coerce_result = _coerce_args(url, scheme)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 128, in _coerce_args
    return _decode_args(args) + (_encode_result,)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 112, in _decode_args
    return tuple(x.decode(encoding, errors) if x else '' for x in args)
  File "C:\Users\super\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py", line 112, in <genexpr>
    return tuple(x.decode(encoding, errors) if x else '' for x in args)
AttributeError: 'StringVar' object has no attribute 'decode'

I've tried looking around YouTube for an answer. It was not very helpful.


问:
How to set "example" in openapi3 swagger documentation in GO
I am using

github.com/getkin/kin-openapi/openapi3

Can somebody tell me how to set the example value for the parameter field
`

```<code>swagger.Paths = openapi3.Paths{
        "/postval/subsid/{subscriberid}/updatefle": &openapi3.PathItem{
            Post: &openapi3.Operation{
                OperationID: "postvalue",
                Parameters: []*openapi3.ParameterRef{
                    {
Value: openapi3.NewPathParameter("subscriberid").WithDescription("SubscriberIdentifier").WithRequired(true).
                            WithSchema(openapi3.NewStringSchema()),
}
</code>```

`I tried setting all the parameters, but unable to find a way to set the example

Body:
I am using

github.com/getkin/kin-openapi/openapi3

Can somebody tell me how to set the example value for the parameter field
`

swagger.Paths = openapi3.Paths{
        "/postval/subsid/{subscriberid}/updatefle": &openapi3.PathItem{
            Post: &openapi3.Operation{
                OperationID: "postvalue",
                Parameters: []*openapi3.ParameterRef{
                    {
Value: openapi3.NewPathParameter("subscriberid").WithDescription("SubscriberIdentifier").WithRequired(true).
                            WithSchema(openapi3.NewStringSchema()),
}

`I tried setting all the parameters, but unable to find a way to set the example


问:
Nginx Ingress: failed health check for a load balancer in Amazon EKS
I have a Cluster in AWS EKS with two nodes (call as Node A and Node B). And I installed nginx ingress in Node A.

Then I see problem when public all pods in Node B (Node B not has nginx) and get error 504. When check detail loabancer in aws and see fail healthcheck node B. Because Node B not have service ingress shoud service not found port for health check.

I have 2 question:

One load balancer for a Cluster is best practice?

Solution for my issue?


问:
Not getting record from database using ajax call in laravel
I am new in laravel development. I am getting record of user registered from database

HTML code

```<code><meta name="_token" content="{{ csrf_token() }}">
<table id="user_table" class="table  table-row-bordered gy-5 gs-7">
  <thead>
    <tr class="fw-bold fs-6 text-gray-800">
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Action</th>
   </tr>
 </thead>
 <tbody>
   @foreach ($register_users as $value)
    <tr>
       <td>{{ $value->id }}</td>
       <td>{{ $value->name.' '.$value->lname }}</td>
       <td>{{ $value->email }}</td>
       <td style="display: inline-flex;">
       <a href="javascript:void(0)" data-id="{{ $value->id }}"  data-bs-toggle="modal" data-bs-target="#activateModal" class="viewDetailModal btn btn-warning btn-hover-rise me-5 btn-sm" style="margin: 1px">View Details</a>
       </td>
   </tr>
  @endforeach
 </tbody>
</code>```

When I clicked on view details button then ajax call for get single user data based on user id

JQUERY code

```<code>$(".viewDetailModal").click(function(e) {

     e.preventDefault();

     var customer_id = $(this).data('id');
     var _token = $("input[name='_token']").val();

     $.ajax({
        url: "{{ route('get.user.details') }}",
        type: 'POST',
        data: {_token:_token, customer_id:customer_id},
        success: function (response){
            console.log(response);

            if(response.lname)
              {
                 response.lname = response.lname;
              }
              else
              {
                 response.lname = '';
              }

           $('#user_id').text(response.id);
           $('#user_name').text(response.name+' '+response.lname);
           $('#user_email').text(response.email);
           $('#user_mobile_no').text(response.mobile_no);
           $('#user_cnic_no').text(response.cnic_no);
           $('#user_passport_no').text(response.passport_no);
           $('#user_country_id').text(response.country_id);
           $('#user_city_id').text(response.city_id);

        }
    });
  });
</code>```

I am using datatable for user table Now issue is that when I am on second page, second page mean that when we are using datatable then datatable predefined pages number bottom right side, clicked on view details then ajax call is not run for get user record from database even I searched user from search field. Only when I am on first page ajax call is working fine. I also checked console errors may be there is some mistake from me to get single user data when I am on second page but I saw no errors on it.

Datatable code

```<code>$("#user_table").DataTable({
        "order": [[ 0, "desc" ]],
         "language": {
         "lengthMenu": "Show _MENU_",
         },
         "dom":
         "<'row'" +
         "<'col-sm-6 d-flex d-none d-sm-none d-md-block align-items-center justify-content-md-start'l>" +
         "<'col-12 col-sm-6 d-flex align-items-center justify-content-md-end'f>" +
         ">" +

         "<'table-responsive'tr>" +

         "<'row'" +
         "<'col-sm-12 col-md-5 d-flex align-items-center justify-content-center justify-content-md-start'i>" +
         "<'col-sm-12 col-md-7 d-flex align-items-center justify-content-center justify-content-md-end'p>" +
         ">"
 });
</code>```

Body:
I am new in laravel development. I am getting record of user registered from database

HTML code

<meta name="_token" content="{{ csrf_token() }}">

      ID
      Name
      Email
      Action

   @foreach ($register_users as $value)

       {{ $value->id }}
       {{ $value->name.' '.$value->lname }}
       {{ $value->email }}

       id }}"  data-bs-toggle="modal" data-bs-target="#activateModal" class="viewDetailModal btn btn-warning btn-hover-rise me-5 btn-sm" style="margin: 1px">View Details

  @endforeach

When I clicked on view details button then ajax call for get single user data based on user id

JQUERY code

$(".viewDetailModal").click(function(e) {

     e.preventDefault();

     var customer_id = $(this).data('id');
     var _token = $("input[name='_token']").val();

     $.ajax({
        url: "{{ route('get.user.details') }}",
        type: 'POST',
        data: {_token:_token, customer_id:customer_id},
        success: function (response){
            console.log(response);

            if(response.lname)
              {
                 response.lname = response.lname;
              }
              else
              {
                 response.lname = '';
              }

           $('#user_id').text(response.id);
           $('#user_name').text(response.name+' '+response.lname);
           $('#user_email').text(response.email);
           $('#user_mobile_no').text(response.mobile_no);
           $('#user_cnic_no').text(response.cnic_no);
           $('#user_passport_no').text(response.passport_no);
           $('#user_country_id').text(response.country_id);
           $('#user_city_id').text(response.city_id);

        }
    });
  });

I am using datatable for user table Now issue is that when I am on second page, second page mean that when we are using datatable then datatable predefined pages number bottom right side, clicked on view details then ajax call is not run for get user record from database even I searched user from search field. Only when I am on first page ajax call is working fine. I also checked console errors may be there is some mistake from me to get single user data when I am on second page but I saw no errors on it.

Datatable code

$("#user_table").DataTable({
        "order": [[ 0, "desc" ]],
         "language": {
         "lengthMenu": "Show _MENU_",
         },
         "dom":
         "<'row'" +
         "<'col-sm-6 d-flex d-none d-sm-none d-md-block align-items-center justify-content-md-start'l>" +
         "<'col-12 col-sm-6 d-flex align-items-center justify-content-md-end'f>" +
         ">" +

         "<'table-responsive'tr>" +

         "<'row'" +
         "<'col-sm-12 col-md-5 d-flex align-items-center justify-content-center justify-content-md-start'i>" +
         "<'col-sm-12 col-md-7 d-flex align-items-center justify-content-center justify-content-md-end'p>" +
         ">"
 });


问:
Import multiple .mat files in python and create a list
I want to import some .mat files (~160 files) and store them as a list of libraries.

I am trying to import them using a loop. I have renamed the files like myfiles (1), myfiles (2) and so on.. How to import them in a loop?


问:
How to explore a specific version of the Android SDK source code?

Hi Android Community

I'm wondering if it's possible to explore a specific version of the Android SDK from Android Studio.

Currently when I open a class using ⌘ + left click, it opens directly the target version.

But I'd like to debug on on a specific version of the Android SDK.


问:
Model traing - target received an input with 12 examples - Labels
I'm trying to train the model with multiple images (14) of faces and dog photoes, But I keep getting 1 more layer than what is needed as it gives (i.e.,tensor shape [*,10]) but the target received an input with 12 examples, each with shape [2] (tensor shape [12,2]). The model shows null in the first field. I'm trying to make a CNN for image/object/face recognition. I really need help with this and it would be very gratefully appreciated.

Error:

E:\AItest\node_modules\@tensorflow\tfjs-layers\dist\tf-layers.node.js:276
        var _this = _super.call(this, message) || this;
                           ^

ValueError: target expected a batch of elements where each example has shape [10] (i.e.,tensor shape [*,10]) but the target received an input with 12 examples, each with shape [2] (tensor shape [12,2])
```
<p><strong>Code:</strong></p>
<pre class="lang-js prettyprint-override"><code>const tf = require('@tensorflow/tfjs-node-gpu');
const fs = require('fs'); // Load the Node.js filesystem module

async function main() {
const files = await fs.readdirSync('./images');

process.env.TF_FORCE_GPU_ALLOW_GROWTH = true;
process.env.TF_GPU_ALLOCATOR = 'cuda_malloc_async';

tf.setBackend('tensorflow', { device: '/gpu:0' });

// Filter the list to only include image files
const imageFiles = await files.filter((file) => file.match(/\.(jpg|jpeg|png|gif)$/i));
console.log(`Found ${imageFiles.length} image files.`);

// Load the image files as tensors and assign labels based on their filenames
const images = await imageFiles.map((file) => {
  const imageTensor = tf.node.decodeImage(fs.readFileSync(`./images/${file}`))
  const resizedImage = tf.image.resizeBilinear(imageTensor, [28, 28]);
  const label = file.startsWith('1') ? 'human' : 'dog';
  return {image: resizedImage, label: label};
});

let trainSize = Math.floor(images.length * 0.8);
let trainImages = images.slice(0, trainSize).map((e) => e.image);
let trainLabels = images.slice(0, trainSize).map((e) => e.label);
let testImages = images.slice(trainSize).map((e) => e.image);
let testLabels = images.slice(trainSize).map((e) => e.label);

console.log('Shuffled images and labels.');

console.log(`Training set: ${trainImages.length} images`);
// Create a model
const model = tf.sequential();

// Add a convolutional layer
model.add(tf.layers.conv2d({
  inputShape: [28, 28, 3],
  filters: 16,
  kernelSize: 3,
  strides: 1,
  activation: 'relu',
  kernelInitializer: 'varianceScaling'
}));

// Add a max pooling layer
model.add(tf.layers.maxPooling2d({
  poolSize: [2, 2],
  strides: [2, 2]
}));

// Flatten the output from the convolutional layer
model.add(tf.layers.flatten());

// Add a dense layer to perform classification
model.add(tf.layers.dense({
  units: 10,
  activation: 'softmax'
}));

// Compile the model
model.compile({
  optimizer: tf.train.adam(),
  loss: 'categoricalCrossentropy',
  metrics: ['accuracy']
});

console.log('Training data...');

const trainImagesTensor = tf.stack(trainImages);
const labels = ['human', 'dog'];
const trainLabelsTensor = tf.tidy(() =>
  tf.oneHot(trainLabels.map(label => labels.indexOf(label)), labels.length)
);

// Fit the model to the training data
model.fit(trainImagesTensor, trainLabelsTensor, {
  epochs: 10,
  batchSize: 2,  // <-- Decrease the batch size here
  validationData: [testImages, testLabels],
  callbacks: {
    onBatchEnd: async (batch, logs) => {
        console.log('Accuracy', logs.acc);
    },
    onEpochEnd: async (epoch, logs) => {
      console.log(`Epoch ${epoch}: loss = ${logs.loss}`);
    }
  },
  device: '/gpu:0'
});

// Save the model
model.save('file://./model/');

console.log('Model saved!');
}
main();
</code>```

The wird thing is that it also does this:

2022-12-10 16:10:35.509379: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-12-10 16:10:36.115421: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1532] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3948 MB memory:  -> device: 0, name: NVIDIA GeForce RTX 2060, pci bus id: 0000:01:00.0, compute capability: 7.5
Found 16 image files.
Shuffled images and labels.
Training set: 12 images
Training data...
Model saved!
E:\AItest\node_modules\@tensorflow\tfjs-layers\dist\tf-layers.node.js:276
        var _this = _super.call(this, message) || this;
                           ^

ValueError: target expected a batch of elements where each example has shape [10] (i.e.,tensor shape [*,10]) but the target received an input with 12 examples, each with shape [2] (tensor shape [12,2])
```

It saves it despite having the model not trained, IF you help me that would be great.

Body:
I'm trying to train the model with multiple images (14) of faces and dog photoes, But I keep getting 1 more layer than what is needed as it gives (i.e.,tensor shape [*,10]) but the target received an input with 12 examples, each with shape [2] (tensor shape [12,2]). The model shows null in the first field. I'm trying to make a CNN for image/object/face recognition. I really need help with this and it would be very gratefully appreciated.

Error:

E:\AItest\node_modules\@tensorflow\tfjs-layers\dist\tf-layers.node.js:276
        var _this = _super.call(this, message) || this;
                           ^

ValueError: target expected a batch of elements where each example has shape [10] (i.e.,tensor shape [*,10]) but the target received an input with 12 examples, each with shape [2] (tensor shape [12,2])

Code:

const tf = require('@tensorflow/tfjs-node-gpu');
const fs = require('fs'); // Load the Node.js filesystem module

async function main() {
const files = await fs.readdirSync('./images');

process.env.TF_FORCE_GPU_ALLOW_GROWTH = true;
process.env.TF_GPU_ALLOCATOR = 'cuda_malloc_async';

tf.setBackend('tensorflow', { device: '/gpu:0' });

// Filter the list to only include image files
const imageFiles = await files.filter((file) => file.match(/\.(jpg|jpeg|png|gif)$/i));
console.log(`Found ${imageFiles.length} image files.`);

// Load the image files as tensors and assign labels based on their filenames
const images = await imageFiles.map((file) => {
  const imageTensor = tf.node.decodeImage(fs.readFileSync(`./images/${file}`))
  const resizedImage = tf.image.resizeBilinear(imageTensor, [28, 28]);
  const label = file.startsWith('1') ? 'human' : 'dog';
  return {image: resizedImage, label: label};
});

let trainSize = Math.floor(images.length * 0.8);
let trainImages = images.slice(0, trainSize).map((e) => e.image);
let trainLabels = images.slice(0, trainSize).map((e) => e.label);
let testImages = images.slice(trainSize).map((e) => e.image);
let testLabels = images.slice(trainSize).map((e) => e.label);

console.log('Shuffled images and labels.');

console.log(`Training set: ${trainImages.length} images`);
// Create a model
const model = tf.sequential();

// Add a convolutional layer
model.add(tf.layers.conv2d({
  inputShape: [28, 28, 3],
  filters: 16,
  kernelSize: 3,
  strides: 1,
  activation: 'relu',
  kernelInitializer: 'varianceScaling'
}));

// Add a max pooling layer
model.add(tf.layers.maxPooling2d({
  poolSize: [2, 2],
  strides: [2, 2]
}));

// Flatten the output from the convolutional layer
model.add(tf.layers.flatten());

// Add a dense layer to perform classification
model.add(tf.layers.dense({
  units: 10,
  activation: 'softmax'
}));

// Compile the model
model.compile({
  optimizer: tf.train.adam(),
  loss: 'categoricalCrossentropy',
  metrics: ['accuracy']
});

console.log('Training data...');

const trainImagesTensor = tf.stack(trainImages);
const labels = ['human', 'dog'];
const trainLabelsTensor = tf.tidy(() =>
  tf.oneHot(trainLabels.map(label => labels.indexOf(label)), labels.length)
);

// Fit the model to the training data
model.fit(trainImagesTensor, trainLabelsTensor, {
  epochs: 10,
  batchSize: 2,  // <-- Decrease the batch size here
  validationData: [testImages, testLabels],
  callbacks: {
    onBatchEnd: async (batch, logs) => {
        console.log('Accuracy', logs.acc);
    },
    onEpochEnd: async (epoch, logs) => {
      console.log(`Epoch ${epoch}: loss = ${logs.loss}`);
    }
  },
  device: '/gpu:0'
});

// Save the model
model.save('file://./model/');

console.log('Model saved!');
}
main();

The wird thing is that it also does this:

2022-12-10 16:10:35.509379: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-12-10 16:10:36.115421: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1532] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3948 MB memory:  -> device: 0, name: NVIDIA GeForce RTX 2060, pci bus id: 0000:01:00.0, compute capability: 7.5
Found 16 image files.
Shuffled images and labels.
Training set: 12 images
Training data...
Model saved!
E:\AItest\node_modules\@tensorflow\tfjs-layers\dist\tf-layers.node.js:276
        var _this = _super.call(this, message) || this;
                           ^

ValueError: target expected a batch of elements where each example has shape [10] (i.e.,tensor shape [*,10]) but the target received an input with 12 examples, each with shape [2] (tensor shape [12,2])

It saves it despite having the model not trained, IF you help me that would be great.


问:
How to include nugget dependencies for a .dll assembly reference
I have a project which I've built (call it "projectA") that generates a .dll "projectA.dll". I add this projectA.dll as an assembly reference to another project (call it "projectB"). All is working fine however projectA has some nugget packages that it relies upon. Everything builds fine but at runtime I encounter an error when one of the nugget packages that projectA.dll relies upon is used (the exception is thrown in the source code at that particular point).

Is there any way to include these nugget dependencies within the dll file so that the .dll is purely self contained?