问:
Asp.Net core Custom ModelBinder HowTo get model from default binder
I like to create a custom Model Binder.

```<code>public async Task BindModelAsync(ModelBindingContext bindingContext)
{
    if (bindingContext.ModelType != typeof(Wrapper<SomeType>))
    {
        return;
    }

    var model = // get the model as if I would be using the default ModelBindig i.e. Complex modelbinding

    // manipulate 'model'

    return ModelBindingResult.Success(model);
}
</code>```

Any Suggestions on the get the model as If i would be using the dfault modelbinding ....

Body:
I like to create a custom Model Binder.

public async Task BindModelAsync(ModelBindingContext bindingContext)
{
    if (bindingContext.ModelType != typeof(Wrapper<SomeType>))
    {
        return;
    }

    var model = // get the model as if I would be using the default ModelBindig i.e. Complex modelbinding

    // manipulate 'model'

    return ModelBindingResult.Success(model);
}

Any Suggestions on the get the model as If i would be using the dfault modelbinding ....


来源: stackexchange

问:
Am I correct in thinking I'll get read-after-write consistency with this approach?
I am writing a system to do lock-free reservation, using a Mongo database.

The system needs to ensure that for a given concert with N available tickets, no more than N can be reserved. I want to do this without locking.

The approach I'm taking is to create a reservation document, then read back and see if it was within the first N for the concert, and if not then delete it.

I'm not a Mongo expert, and I want to make sure that I've understood correctly that these read/write concerns will ensure that when I read back I will always have the reservation I just created and all reservations that have been created in other threads up to that point - this should be sufficient to ensure the system will work correctly.

def make_reservation(concert: Document, user: Document):
    maximum_spaces = concert.maximum_spaces

    # Will wait for acknowlegement before continuing
    reservation_id = reservations.with_options(
        write_concern=WriteConcern(fsync=True)
    ).insert_one({
        "user": user.id,
        "concert": concert.id,
        "status": "UNRESERVED",
    }).inserted_id

    # Sorted list of ids ascending
    all_reservations = sorted(reservations
        .with_options(read_preference=ReadPreference.PRIMARY)
        .find({"concert": concert.id}).only("id")
    )

    # If the id we just inserted is too far down the list we missed our spot
    if all_reservations.index(reservation_id) >= maximum_spaces:
        # Oh no, we missed out
        reservations.delete_one({"id": reservation_id})
        raise Exception("Sorry, too slow")

    reservations.update_one({"id": reservation_id}, {"$set": {"status": "RESERVED"}})

    return reservation_id
```

I've tried testing this a few ways and I can't coerce it to break, but I'm still not sure if it's theoretically watertight.

ContentLicense: CC BY-SA 4.0

Body:
I am writing a system to do lock-free reservation, using a Mongo database.

The system needs to ensure that for a given concert with N available tickets, no more than N can be reserved. I want to do this without locking.

The approach I'm taking is to create a reservation document, then read back and see if it was within the first N for the concert, and if not then delete it.

I'm not a Mongo expert, and I want to make sure that I've understood correctly that these read/write concerns will ensure that when I read back I will always have the reservation I just created and all reservations that have been created in other threads up to that point - this should be sufficient to ensure the system will work correctly.

def make_reservation(concert: Document, user: Document):
    maximum_spaces = concert.maximum_spaces

    # Will wait for acknowlegement before continuing
    reservation_id = reservations.with_options(
        write_concern=WriteConcern(fsync=True)
    ).insert_one({
        "user": user.id,
        "concert": concert.id,
        "status": "UNRESERVED",
    }).inserted_id

    # Sorted list of ids ascending
    all_reservations = sorted(reservations
        .with_options(read_preference=ReadPreference.PRIMARY)
        .find({"concert": concert.id}).only("id")
    )

    # If the id we just inserted is too far down the list we missed our spot
    if all_reservations.index(reservation_id) >= maximum_spaces:
        # Oh no, we missed out
        reservations.delete_one({"id": reservation_id})
        raise Exception("Sorry, too slow")

    reservations.update_one({"id": reservation_id}, {"$set": {"status": "RESERVED"}})

    return reservation_id

I've tried testing this a few ways and I can't coerce it to break, but I'm still not sure if it's theoretically watertight.


问:
react-tippy not being positioned properly on sidebar
I am using @tippyjs/react": "^4.2.6 & the problem is that react-tippy not being positioned properly on sidebar of our dashboard, whenever there is content more than screen height and is scrollable the tippy button is placed more above than it is supposed to.

For example, when there is very little content on the right and there is no scroll bar tippy tool is positioned properly as shown in the image below:

But whenever there is more content than the screen height on the right and scroll bar appears tippy tool seems to be positioned wrong (A bit above than the button) as shown in image:

I checked multiple ways to figure / fix this but wasn't able to

The code I'm using is this for the button tippy tool is this:

```<code>import React from "react";
import Tippy from "@tippyjs/react";

const TippyReload = props => {
    return (
        <Tippy
            animation="fade"
            theme="custom"
            content="Refresh Count"
            placement="top"
            arrow={true}
            className={`custom-tippy`}>
                 {/* Wrap this component over the refresh icon, so this will be the refresh icon */}
                 {props.children}
        </Tippy>
    );
};

export default TippyReload ;

</code>```

Body:
I am using @tippyjs/react": "^4.2.6 & the problem is that react-tippy not being positioned properly on sidebar of our dashboard, whenever there is content more than screen height and is scrollable the tippy button is placed more above than it is supposed to.

For example, when there is very little content on the right and there is no scroll bar tippy tool is positioned properly as shown in the image below:

But whenever there is more content than the screen height on the right and scroll bar appears tippy tool seems to be positioned wrong (A bit above than the button) as shown in image:

I checked multiple ways to figure / fix this but wasn't able to

The code I'm using is this for the button tippy tool is this:

import React from "react";
import Tippy from "@tippyjs/react";

const TippyReload = props => {
    return (
        <Tippy
            animation="fade"
            theme="custom"
            content="Refresh Count"
            placement="top"
            arrow={true}
            className={`custom-tippy`}>
                 {/* Wrap this component over the refresh icon, so this will be the refresh icon */}
                 {props.children}
        </Tippy>
    );
};

export default TippyReload ;


问:
React Native WebView - Vimeo url not loading images
I am loading a Vimeo video using WebView in ReactNative. However, the images do not load (badge and pre-play image). I am using react-native@0.70.5 and react-native-webview@11.23.1, below is the code for my WebView, and screenshots of the video in the emulator vs. directly accessed over the browser url bar.

```<code><WebView
  allowsFullscreenVideo={true}
  source={{ uri: "https://player.vimeo.com/video/65107797" }}
  javaScriptEnabled={true}
  scrollEnabled={false}
  originWhitelist={["*"]}
  style={{ height: 300 }}
/>
</code>```

Screenshot of video in iOS emulator:

Screenshot of video in the browser:

Body:
I am loading a Vimeo video using WebView in ReactNative. However, the images do not load (badge and pre-play image). I am using react-native@0.70.5 and react-native-webview@11.23.1, below is the code for my WebView, and screenshots of the video in the emulator vs. directly accessed over the browser url bar.

<WebView
  allowsFullscreenVideo={true}
  source={{ uri: "https://player.vimeo.com/video/65107797" }}
  javaScriptEnabled={true}
  scrollEnabled={false}
  originWhitelist={["*"]}
  style={{ height: 300 }}
/>

Screenshot of video in iOS emulator:

Screenshot of video in the browser:


问:
"firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.storage is not a function". I GOT THIS WEIRD ERROR BY FIREBASE
**I am actually working on snapchat clone but i am not able to use firebase storage it shows some weird bug. I am attaching snapshots. **

I am working with React and firebase(for backend).

I got this error in console

I am attaching code snippets.

Here I import firebase storage and other

These are the rules of storage

These are the packages

I got stuck with this for 2 days now but everytime it shows this error. Please help i am new to the develpement.

I did a lot of research regarding the same problem. I watched tons of tutorials and read articles but nothing could help me.


问:
tkinter if else related issue of input and output
In my program i am using tkinter, the issue is with if else condition inside the function after clicking the submit button.

The if else statement is not giving correct output. i wanted this to be able to run multiple times with different value without rerunning the program.

```<code>    from tkinter import *
    main = Tk()

    def show_answer():
        Ans = int(num1.get())
        if Ans>5 or Ans <10:
            blank.config(text="this is between 5 and 10")
        else:
            blank.config(text="this is out of range")

    Label(main, text = "Enter Num 1:").grid(row=0)
    Label(main, text = "The Sum is:").grid(row=2)
    num1 = Entry(main)
    blank = Label(main,text="", width=25 )
    num1.grid(row=0, column=1)
    blank.grid(row=2, column=1)
    Button(main, text='Quit', command=main.destroy).grid(row=4, column=0, sticky=W, pady=4)
    Button(main, text='Show', command=show_answer).grid(row=4, column=1, sticky=W, pady=4)

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

Body:
In my program i am using tkinter, the issue is with if else condition inside the function after clicking the submit button.

The if else statement is not giving correct output. i wanted this to be able to run multiple times with different value without rerunning the program.

    from tkinter import *
    main = Tk()

    def show_answer():
        Ans = int(num1.get())
        if Ans>5 or Ans <10:
            blank.config(text="this is between 5 and 10")
        else:
            blank.config(text="this is out of range")

    Label(main, text = "Enter Num 1:").grid(row=0)
    Label(main, text = "The Sum is:").grid(row=2)
    num1 = Entry(main)
    blank = Label(main,text="", width=25 )
    num1.grid(row=0, column=1)
    blank.grid(row=2, column=1)
    Button(main, text='Quit', command=main.destroy).grid(row=4, column=0, sticky=W, pady=4)
    Button(main, text='Show', command=show_answer).grid(row=4, column=1, sticky=W, pady=4)

    main.mainloop()


问:
When using .receivedLighting on an arView.environment in RealityKit it does not show lighting
I noticed that an arView (RealityKit) has the option insert: arView.environment.sceneUnderstanding.options.insert(.receivesLighting)

with .receivesLighting description it state: The .receivesLighting option means that the virtual lights will interact with real world surfaces causing them to shine. The properties of the mesh will be set to a default material.

This would mean it is possible to relight the real world. It is also indicated in apple's talk: https://developer.apple.com/videos/play/tech-talks/609/

However, experimenting with it and having a directional light and/or spotlight added to the AR environment will have no influence on the real-world surfaces. I am using iPad Pro/iphone Pro with LIDAR.

Any idea why not?


问:
How can I have my server keep sending information while listining with a timeout
I'm trying to simulate a TCP protocol while using UDP.
I want my server to be able to send chunks of the file the client requested while waiting for acks from the client.

My idea is to send chunk then recv (listen for ack) but that makes it so I can only send chunk nº2 after receiving ack nº1.
Should I just send all of them in a loop and then wait for all the acks in a loop with timeouts?
Or is there way to have recv in the background with a timeout and if it receives an ack it stops the setsockopt timeout feature, and if the timeout occurs it interrupts the current script to resend that chunk?
Edit:
My bad didn't mention it was using C.
OS is linux.

```<code>Server-Side Libraries:
packet-format.h
arpa/inet.h
limits.h
netinet/in.h
stdbool.h
stddef.h
stdio.h
stdlib.h
string.h
sys/socket.h
unistd.h

Client-Side Libraries:
packet-format.h
limits.h
netdb.h
stdbool.h
stddef.h
stdio.h
stdlib.h
string.h
unistd.h
</code>```

Body:
I'm trying to simulate a TCP protocol while using UDP.
I want my server to be able to send chunks of the file the client requested while waiting for acks from the client.

My idea is to send chunk then recv (listen for ack) but that makes it so I can only send chunk nº2 after receiving ack nº1.
Should I just send all of them in a loop and then wait for all the acks in a loop with timeouts?
Or is there way to have recv in the background with a timeout and if it receives an ack it stops the setsockopt timeout feature, and if the timeout occurs it interrupts the current script to resend that chunk?
Edit:
My bad didn't mention it was using C.
OS is linux.

Server-Side Libraries:
packet-format.h
arpa/inet.h
limits.h
netinet/in.h
stdbool.h
stddef.h
stdio.h
stdlib.h
string.h
sys/socket.h
unistd.h

Client-Side Libraries:
packet-format.h
limits.h
netdb.h
stdbool.h
stddef.h
stdio.h
stdlib.h
string.h
unistd.h


问:
Is there any way to send a tts message in discord.py
I have a simple discord.py bot, I was wondering if it is possible to send a message as TTY?

The code currently runs: await ctx.send("Hello World!")
Where ctx is the context passed to the command, it simply replies to the command with "Hello World"

I wanted to make this text to speech so it would speak the message out in the channel. A user can do this by typing "/tts" before their message, so I tried replacing the prior code with this:
ctx.send("/tts Hello World!")

However this simply replied with "/tts Hello World!" rather than running TTS.

So is there any way to mark a question as TTS?


问:
Cannot use import statement outside a module
I'm faced with a problem with my API in Heroku. I have a Node JS API, built with Typescript and hosted in Heroku. Everything looks correct when I try to execute the local script and build the script, but when I need to run the start script, things don't work.

My configurations are:

Node: v18.12.1

NPM: v8.19.2

I have some scripts to transpile .ts files to .js files with babel

```<code>"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files",
</code>```
```<code>  "dev:server": "ts-node-dev -r tsconfig-paths/register --inspect --transpile-only --ignore-watch node_modules src/shared/infra/http/server.ts",
</code>```
```<code>"start": "node dist/shared/infra/http/server.js"
</code>```

When I execute dev:server and build script, everything runs with success, but when I run the start script, I receive this error:

enter image description here

I checked some points, like my tsconfig.json and my babel.config, but everything looks correct.

```<code>module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    '@babel/preset-typescript',
  ],

  plugins: [
    [
      'module-resolver',
      {
        alias: {
          '@modules': './src/modules',
          '@config': './src/config',
          '@shared': './src/shared',
        },
      },
    ],
    'babel-plugin-transform-typescript-metadata',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    [
      'const-enum',
      {
        transform: 'removeConst',
      },
    ],
  ],
};

</code>```

Because of it, when I deploy API in Heroku, I recive this error:

enter image description here.

I don't have an idea why this occur, because about 1 month ago the API was running perfectly on Heroku production instance.

I appreciate it if anyone can help and give me some tips, about this problem.

What I tried

Check and change my npm and node versions

Check babel confgs

Add "type":"module"in my packages.json

Body:
I'm faced with a problem with my API in Heroku. I have a Node JS API, built with Typescript and hosted in Heroku. Everything looks correct when I try to execute the local script and build the script, but when I need to run the start script, things don't work.

My configurations are:

Node: v18.12.1

NPM: v8.19.2

I have some scripts to transpile .ts files to .js files with babel

"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files",

  "dev:server": "ts-node-dev -r tsconfig-paths/register --inspect --transpile-only --ignore-watch node_modules src/shared/infra/http/server.ts",

"start": "node dist/shared/infra/http/server.js"

When I execute dev:server and build script, everything runs with success, but when I run the start script, I receive this error:

enter image description here

I checked some points, like my tsconfig.json and my babel.config, but everything looks correct.

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    '@babel/preset-typescript',
  ],

  plugins: [
    [
      'module-resolver',
      {
        alias: {
          '@modules': './src/modules',
          '@config': './src/config',
          '@shared': './src/shared',
        },
      },
    ],
    'babel-plugin-transform-typescript-metadata',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    [
      'const-enum',
      {
        transform: 'removeConst',
      },
    ],
  ],
};

Because of it, when I deploy API in Heroku, I recive this error:

enter image description here.

I don't have an idea why this occur, because about 1 month ago the API was running perfectly on Heroku production instance.

I appreciate it if anyone can help and give me some tips, about this problem.

What I tried

Check and change my npm and node versions

Check babel confgs

Add "type":"module"in my packages.json


问:
gdal_calc.py Error: could not open file "a.geo"
I've had a problem with gdal_calc for a few days that I didn't have before.
Basically, I should recalculate a GEO file and I've always used (via Anaconda Prompt):

```<code>python %CONDA_PREFIX%\Scripts\gdal_calc.py -A myfile.geo --outfile mynewfile.geo --calc="-(A*5/7)" --format=ENVI --NoDataValue=-9999 --overwrite
</code>```

I've never had any problems, but since a few days, trying to convert a GEO file I get:

```<code>could not open file "file.geo"
</code>```

I tried to convert the initially converted files back without problems and:

pressing Enter, I get nothing

I get the same error

I would like to understand where the problem could be.
I state that I have not made any changes to the path of the GDAL and Anaconda files

Body:
I've had a problem with gdal_calc for a few days that I didn't have before.
Basically, I should recalculate a GEO file and I've always used (via Anaconda Prompt):

python %CONDA_PREFIX%\Scripts\gdal_calc.py -A myfile.geo --outfile mynewfile.geo --calc="-(A*5/7)" --format=ENVI --NoDataValue=-9999 --overwrite

I've never had any problems, but since a few days, trying to convert a GEO file I get:

could not open file "file.geo"

I tried to convert the initially converted files back without problems and:

pressing Enter, I get nothing

I get the same error

I would like to understand where the problem could be.
I state that I have not made any changes to the path of the GDAL and Anaconda files


问:
Download Onedrive shared file in R
I need to download an excel file shared in my company from onedrive, unfortunately I can't handle it. The link looks like this:

https://company.sharepoint.com/:x:/p/user_name/XXXXXXXXXXXXXXXXXX

After adding the parameter download=1 to the URL, the browser downloads automatically, but I can't write the R code that could download such a file.

I tried to download the file with this function

```<code>httr::GET(paste0(url), authenticate("username","password",type="any"))
</code>```

I tried to get a list of files using Microsoft365R, but after accessing from IT, list_sharepoint_sites() returns an empty list.

Title: Download Onedrive shared file in R

Body:
I need to download an excel file shared in my company from onedrive, unfortunately I can't handle it. The link looks like this:

https://company.sharepoint.com/:x:/p/user_name/XXXXXXXXXXXXXXXXXX

After adding the parameter download=1 to the URL, the browser downloads automatically, but I can't write the R code that could download such a file.

I tried to download the file with this function

httr::GET(paste0(url), authenticate("username","password",type="any"))

I tried to get a list of files using Microsoft365R, but after accessing from IT, list_sharepoint_sites() returns an empty list.


问:
PWA/Web: Remember file system access permissions on app restart
i am looking for a way to resume file uploads after session restart.

Is there a way (like in PWA API) to let the browser sth. like remember the access permissions granted to read files (and upload them), so that if the user closes the session and reopens it, the file upload can be continued?


问:
Open link after retrieving via rest in new Tab on IOS (SPA, Angular/React)
I am trying to solve a problem with opening links in a new window or tab since a few days.

UseCase: As soon as a user clicks on a button, a request is made to the backend to provide a link. Once the request is completed, the link should open in a new tab.

Although the link opens fine (in a new tab) on Android, Windows, etc., links on iOS Safari causes problems.

Already tried:

```<code>const a = document.createElement("a");
a.setAttribute('href', url);
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener ugc nofollow');
a.click();
</code>```
```<code>window.open(url, '_blank', 'noopener,ugc,nofollow');
</code>```
```<code>setTimeout(() => { <stuff above> })

</code>```

It is interesting that a normal link in the html page works. However, if the link is inserted later, there are problems. I've looked at about 1000 forum entries, tried 100 solutions, but none are currently working

Regards,
Tim

Body:
I am trying to solve a problem with opening links in a new window or tab since a few days.

UseCase: As soon as a user clicks on a button, a request is made to the backend to provide a link. Once the request is completed, the link should open in a new tab.

Although the link opens fine (in a new tab) on Android, Windows, etc., links on iOS Safari causes problems.

Already tried:

const a = document.createElement("a");
a.setAttribute('href', url);
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener ugc nofollow');
a.click();

window.open(url, '_blank', 'noopener,ugc,nofollow');

setTimeout(() => { <stuff above> })

It is interesting that a normal link in the html page works. However, if the link is inserted later, there are problems. I've looked at about 1000 forum entries, tried 100 solutions, but none are currently working

Regards,
Tim


问:
How to handle Create/Edit pages in Nextjs, should I get the product in ServerSideProps or in the component
I have a form where a user creates a product. This form uses react-hook-form to keep track of all form inputs. I'd like to reuse the form since the "Edit" page is the exact same form but with the fields filled out by data from the server.

What's the best practice is this case? Having a ProductForm component with an optional product prop? Or just copy pasting the form in two different files?

This is what I was thinking of:

pages/product/create/index.tsx

export default function Create() {
  return <ProductForm />
}
```
<p><code>pages/product/create/edit.tsx</code></p>
<pre class="lang-js prettyprint-override"><code>export default function Edit({id}: {id: number}) {
    const product = // Get the product with the id from the slug
    return <ProductForm product={product}
}

export async function getServerSideProps({ params }) {
    return {
        props: { id: params.id }
    }
}
</code>```

The second part of my question is what the best practice is for an Edit page to get the product from the server, getServerSideProps or getStaticProps. Should I be getting the product with the id from the slug inside one of those functions? So the edit would look something like this instead

pages/product/create/edit.tsx

export default function Edit({product}: {product: Product}) {
    return <ProductForm product={product}
}

export async function getServerSideProps({ params }) {
    const product = // get product from slug id
    return {
        props: { product: product }
    }
}
```

New to Nextjs so any thoughts on this are appreciated

Body:
I have a form where a user creates a product. This form uses react-hook-form to keep track of all form inputs. I'd like to reuse the form since the "Edit" page is the exact same form but with the fields filled out by data from the server.

What's the best practice is this case? Having a ProductForm component with an optional product prop? Or just copy pasting the form in two different files?

This is what I was thinking of:

pages/product/create/index.tsx

export default function Create() {
  return <ProductForm />
}

pages/product/create/edit.tsx

export default function Edit({id}: {id: number}) {
    const product = // Get the product with the id from the slug
    return <ProductForm product={product}
}

export async function getServerSideProps({ params }) {
    return {
        props: { id: params.id }
    }
}

The second part of my question is what the best practice is for an Edit page to get the product from the server, getServerSideProps or getStaticProps. Should I be getting the product with the id from the slug inside one of those functions? So the edit would look something like this instead

pages/product/create/edit.tsx

export default function Edit({product}: {product: Product}) {
    return <ProductForm product={product}
}

export async function getServerSideProps({ params }) {
    const product = // get product from slug id
    return {
        props: { product: product }
    }
}

New to Nextjs so any thoughts on this are appreciated


问:
The files are grayed out in UIDocumentPicker
I’m unable to select the document documents they are greyed out

I have tried with

UIDocumentPickerViewController - each file that was picked once is then grayed out

```<code>

import UIKit
import MobileCoreServices
import UniformTypeIdentifiers

class ViewController: UIViewController, UINavigationControllerDelegate, UIDocumentPickerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    @IBAction func ShowPicker(_ sender: Any) {
        let pickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf], asCopy: true)
        pickerViewController.delegate = self
        pickerViewController.allowsMultipleSelection = false
        pickerViewController.shouldShowFileExtensions = true
        present(pickerViewController, animated: true, completion: nil)

    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("Cancelled")
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print("didPickDocuments at \(urls)")
    }
}
</code>```

Body:
I’m unable to select the document documents they are greyed out

I have tried with

UIDocumentPickerViewController - each file that was picked once is then grayed out

import UIKit
import MobileCoreServices
import UniformTypeIdentifiers

class ViewController: UIViewController, UINavigationControllerDelegate, UIDocumentPickerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    @IBAction func ShowPicker(_ sender: Any) {
        let pickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf], asCopy: true)
        pickerViewController.delegate = self
        pickerViewController.allowsMultipleSelection = false
        pickerViewController.shouldShowFileExtensions = true
        present(pickerViewController, animated: true, completion: nil)

    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("Cancelled")
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print("didPickDocuments at \(urls)")
    }
}


问:
Delay "back" commandButton on JSF until DOM update
I have a page that displays orders, each order has a status of "Read/Unread". When you click the order id, you are redirected to a new page to visualize the PDF order. From the PDF file, you have a back button that takes you back to the page with the table of orders, and there the status of the order you just visualized has to be changed from "Unread" to "Read".

The issue: if you click the "back" button immediately after reaching the PDF visualization, the status of the order is not updated because the DOM is not updated so fast. Only after you refresh manually the page you can see the changed status.

I was thinking to add a delay on the back button until DOM is updated. (tried to reload the page automatically but doesn't look good).

The only problem is that I can't delay the button. I tried using the setTimeout directly in the onComplete, also tried to define a function in  and call it with setTimeout..not sure why is not working.

Here is my code:

```<code>    <g:documentViewer value="#{cc.attrs.value.viewer}" rendered="#{cc.attrs.value.viewer!=null}">
                    <f:facet name="actions">
                        <p:commandButton id="backbtn"
                                         value="#{'back'}"
                                         immediate="false"
                                         process="@this"
                                         update="@(.docPnl)"
                                         styleClass="#{'btn btn-primary'}"
                                         oncomplete="setTimeout(9000000); updateColumns(true); resetOrderBy();">

                            <f:setPropertyActionListener target="#{cc.attrs.value.viewer}" value="#{null}"/>
                        </p:commandButton>
 </g:documentViewer>
</code>```

Body:
I have a page that displays orders, each order has a status of "Read/Unread". When you click the order id, you are redirected to a new page to visualize the PDF order. From the PDF file, you have a back button that takes you back to the page with the table of orders, and there the status of the order you just visualized has to be changed from "Unread" to "Read".

The issue: if you click the "back" button immediately after reaching the PDF visualization, the status of the order is not updated because the DOM is not updated so fast. Only after you refresh manually the page you can see the changed status.

I was thinking to add a delay on the back button until DOM is updated. (tried to reload the page automatically but doesn't look good).

The only problem is that I can't delay the button. I tried using the setTimeout directly in the onComplete, also tried to define a function in  and call it with setTimeout..not sure why is not working.

Here is my code:

    <g:documentViewer value="#{cc.attrs.value.viewer}" rendered="#{cc.attrs.value.viewer!=null}">
                    <f:facet name="actions">

                            <f:setPropertyActionListener target="#{cc.attrs.value.viewer}" value="#{null}"/>

 </g:documentViewer>


问:
Ingress (Kubernetes) working only with path "/"
This is my ingress.yaml file:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
    nginx.ingress.kubernetes.io/cors-allow-headers: "Content-Type"
    nginx.ingress.kubernetes.io/rewrite-target: "/"
spec:
  rules:
    - host: my-project.app.loc
      http:
        paths:
          - path: /
            pathType: ImplementationSpecific
            backend:
              service:
                name: user-service
                port:
                  number: 8080
</code>```

This is my UserController.java file:

```<code>@RestController
public class UserController {

    @GetMapping("/hello1")
    public String sayHello1() {
        return "Hello World 1!";
    }

    @GetMapping("/hello2")
    public String sayHello2() {
        return "Hello World 2!";
    }

}
</code>```

This setup works. For example, if I call:
curl my-project.app.loc/hello1
I get Hello World 1!

However, my goal is to call:
curl my-project.app.loc/users/hello1
and get Hello World 1!

I found two working solutions:

Add @RequestMapping("/users") annotation in my UserController class.

Or

Add server.servlet.context-path=/users in application.properties file.

All this, with "/" path in Ingress file.

But I saw many example on Internet in which people use path: /users in ingress.yaml file, without using @RequestMapping annotation or editing application.properties.

I would like to know why this setup doesn't work for me and what could I do to make it work. As you can see, I've also used the rewrite-target annotation.

Thank you all in advance.

Solution:
I solved using this configuration for ingress.yaml file:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - host: my-project.app.loc
      http:
        paths:
          - path: /users/(.*)
            pathType: ImplementationSpecific
            backend:
              service:
                name: user-service
                port:
                  number: 8080
</code>```

Body:
This is my ingress.yaml file:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
    nginx.ingress.kubernetes.io/cors-allow-headers: "Content-Type"
    nginx.ingress.kubernetes.io/rewrite-target: "/"
spec:
  rules:
    - host: my-project.app.loc
      http:
        paths:
          - path: /
            pathType: ImplementationSpecific
            backend:
              service:
                name: user-service
                port:
                  number: 8080

This is my UserController.java file:

@RestController
public class UserController {

    @GetMapping("/hello1")
    public String sayHello1() {
        return "Hello World 1!";
    }

    @GetMapping("/hello2")
    public String sayHello2() {
        return "Hello World 2!";
    }

}

This setup works. For example, if I call:
curl my-project.app.loc/hello1
I get Hello World 1!

However, my goal is to call:
curl my-project.app.loc/users/hello1
and get Hello World 1!

I found two working solutions:

Add @RequestMapping("/users") annotation in my UserController class.

Or

Add server.servlet.context-path=/users in application.properties file.

All this, with "/" path in Ingress file.

But I saw many example on Internet in which people use path: /users in ingress.yaml file, without using @RequestMapping annotation or editing application.properties.

I would like to know why this setup doesn't work for me and what could I do to make it work. As you can see, I've also used the rewrite-target annotation.

Thank you all in advance.

Solution:
I solved using this configuration for ingress.yaml file:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - host: my-project.app.loc
      http:
        paths:
          - path: /users/(.*)
            pathType: ImplementationSpecific
            backend:
              service:
                name: user-service
                port:
                  number: 8080


问:
Opentelemtry trace not emitted - no error in console
I have this ruby code to test opentelemtry

```<code>require 'uri'
require 'net/http'
require 'opentelemetry/sdk'
require 'opentelemetry/instrumentation/all'
require 'opentelemetry/exporter/otlp'
require "opentelemetry-api"

OpenTelemetry::SDK.configure do |c|
  c.service_name = 'test'
  c.use_all
end

uri = URI('https://google.ch')
res = Net::HTTP.get_response(uri)
puts res.body
</code>```

Which outputs:

```<code>I, [2022-12-15T15:57:44.881172 #5506]  INFO -- : Instrumentation: OpenTelemetry::Instrumentation::Net::HTTP was successfully installed with the following options {:untraced_hosts=>[]}
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.ch/">here</A>.
</BODY></HTML>
</code>```

But there are not traces visible in Jaeger.

ENV ist set:

```<code>export OTEL_EXPORTER_OTLP_ENDPOINT=http://0.0.0.0:4318
</code>```

Jaeger running with

```<code>docker run --name jaeger \
-e COLLECTOR_OTLP_ENABLED=true \
-p 16686:16686 \
-p 4317:4317 \
-p 4318:4318 \
--platform=linux/amd64 \
jaegertracing/all-in-one:1.6
</code>```

What I'm doing wrong?

Body:
I have this ruby code to test opentelemtry

require 'uri'
require 'net/http'
require 'opentelemetry/sdk'
require 'opentelemetry/instrumentation/all'
require 'opentelemetry/exporter/otlp'
require "opentelemetry-api"

OpenTelemetry::SDK.configure do |c|
  c.service_name = 'test'
  c.use_all
end

uri = URI('https://google.ch')
res = Net::HTTP.get_response(uri)
puts res.body

Which outputs:

I, [2022-12-15T15:57:44.881172 #5506]  INFO -- : Instrumentation: OpenTelemetry::Instrumentation::Net::HTTP was successfully installed with the following options {:untraced_hosts=>[]}
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE>

301 Moved

The document has moved
here.

But there are not traces visible in Jaeger.

ENV ist set:

export OTEL_EXPORTER_OTLP_ENDPOINT=http://0.0.0.0:4318

Jaeger running with

docker run --name jaeger \
-e COLLECTOR_OTLP_ENABLED=true \
-p 16686:16686 \
-p 4317:4317 \
-p 4318:4318 \
--platform=linux/amd64 \
jaegertracing/all-in-one:1.6

What I'm doing wrong?


问:
HttpURLConnection throws NoSuchElementException
I'm performing an endpoint check but somehow I got a NoSuchElementException:

```<code>HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(HttpMethod.HEAD.name());
conn.setUseCaches(false);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
final HttpStatus rc = HttpStatus.valueOf(conn.getResponseCode());
</code>```

According to the logs, it failing on the

```<code>final HttpStatus rc = HttpStatus.valueOf(conn.getResponseCode());
</code>```

What I'm not sure is why is this happening, I've checked Java documentation regarding HttpURLConnection and HttpStatus and none of them will throw a this kind of exception.

I've go through the documentation and also tried to insert values that may trigger that exception so I can understand a little bit why this is happening but I've no luck

Body:
I'm performing an endpoint check but somehow I got a NoSuchElementException:

HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(HttpMethod.HEAD.name());
conn.setUseCaches(false);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
final HttpStatus rc = HttpStatus.valueOf(conn.getResponseCode());

According to the logs, it failing on the

final HttpStatus rc = HttpStatus.valueOf(conn.getResponseCode());

What I'm not sure is why is this happening, I've checked Java documentation regarding HttpURLConnection and HttpStatus and none of them will throw a this kind of exception.

I've go through the documentation and also tried to insert values that may trigger that exception so I can understand a little bit why this is happening but I've no luck


问:
CNN trained on MNIST data set always show same output for all inputs
I am using a Keras CNN for handwritten digit recognition. I downloaded dataset from Kaggle.The preprocessing is :

```<code>    train = pd.read_csv("./input/train.csv")
    test = pd.read_csv("./input/test.csv")
    Y_train = train["label"]
    X_train = train.drop(labels = ["label"],axis = 1)

    X_train = X_train / 255.0
    test = test / 255.0
    X_train = X_train.values.reshape(-1,28,28,1)
    test = test.values.reshape(-1,28,28,1)

    Y_train = to_categorical(Y_train, num_classes = 10)

    random_seed = 2

   X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1,       random_state=random_seed)
</code>```

My model looks like:

```<code>    model = Sequential()
    model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
                 activation ='relu', input_shape = (28,28,1)))
    model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
                 activation ='relu'))
    model.add(MaxPool2D(pool_size=(2,2)))
    model.add(Dropout(0.25))
    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
                 activation ='relu'))
    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
                 activation ='relu'))
    model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(256, activation = "relu"))
    model.add(Dropout(0.5))
    model.add(Dense(10, activation = "softmax"))
</code>```
```<code>
  optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

    model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"])

    learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss',
                                            patience=3,
                                            verbose=1,
                                            factor=0.5,
                                            min_lr=0.00001)
    epochs = 1
    batch_size = 86
    datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)
        zoom_range = 0.1, # Randomly zoom image
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=False,  # randomly flip images
        vertical_flip=False)  # randomly flip images
    datagen.fit(X_train)
    history = model.fit(datagen.flow(X_train,Y_train, batch_size=batch_size),
                              epochs = epochs,
                              validation_data = (X_val,Y_val),
                              verbose = 2,
                              steps_per_epoch=X_train.shape[0] // batch_size,
                              callbacks=[learning_rate_reduction])
</code>```

Predicting my input:

```<code>def predict(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.resize(image, (28, 28))
    image = image.astype('float32')
    image = image.reshape(1, 28, 28, 1)
    image /= 255
    model = load_model('./model.h5')
    pred = model.predict(image, batch_size=1)
    print("Predicted Number: ", pred.argmax())

predict(cv2.imread('./testImages/1.png'))
</code>```

What am I doing wrong?

Desired result is the digit that is provided as an input image, instead I get the same output (i.e. digit 8) for every input.

Body:
I am using a Keras CNN for handwritten digit recognition. I downloaded dataset from Kaggle.The preprocessing is :

    train = pd.read_csv("./input/train.csv")
    test = pd.read_csv("./input/test.csv")
    Y_train = train["label"]
    X_train = train.drop(labels = ["label"],axis = 1)

    X_train = X_train / 255.0
    test = test / 255.0
    X_train = X_train.values.reshape(-1,28,28,1)
    test = test.values.reshape(-1,28,28,1)

    Y_train = to_categorical(Y_train, num_classes = 10)

    random_seed = 2

   X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1,       random_state=random_seed)

My model looks like:

    model = Sequential()
    model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
                 activation ='relu', input_shape = (28,28,1)))
    model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
                 activation ='relu'))
    model.add(MaxPool2D(pool_size=(2,2)))
    model.add(Dropout(0.25))
    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
                 activation ='relu'))
    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
                 activation ='relu'))
    model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(256, activation = "relu"))
    model.add(Dropout(0.5))
    model.add(Dense(10, activation = "softmax"))

  optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

    model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"])

    learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss',
                                            patience=3,
                                            verbose=1,
                                            factor=0.5,
                                            min_lr=0.00001)
    epochs = 1
    batch_size = 86
    datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)
        zoom_range = 0.1, # Randomly zoom image
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=False,  # randomly flip images
        vertical_flip=False)  # randomly flip images
    datagen.fit(X_train)
    history = model.fit(datagen.flow(X_train,Y_train, batch_size=batch_size),
                              epochs = epochs,
                              validation_data = (X_val,Y_val),
                              verbose = 2,
                              steps_per_epoch=X_train.shape[0] // batch_size,
                              callbacks=[learning_rate_reduction])

Predicting my input:

def predict(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.resize(image, (28, 28))
    image = image.astype('float32')
    image = image.reshape(1, 28, 28, 1)
    image /= 255
    model = load_model('./model.h5')
    pred = model.predict(image, batch_size=1)
    print("Predicted Number: ", pred.argmax())

predict(cv2.imread('./testImages/1.png'))

What am I doing wrong?

Desired result is the digit that is provided as an input image, instead I get the same output (i.e. digit 8) for every input.


问:
How to impute individual values in a data frame with multiple measurements in R?
I have a question regarding the imputation of missing values:

For each individual my dataset has more than one row.
After the beginning of data selection, we introduced a new variable. Therefore, some individuals have missing values at the beginning of the observation. Now I have the task to replace all missing values by the first non-missing value for each individual.

For example:

```<code>set.seed(123)
d <- data.frame(
  id = rep(1:3, each = 10),
  year = rep(seq(2000,2002),10))

#Introduce NA values in first rows
d[,2][1:3] <- NA
d[,2][11:14] <- NA
d[,2][20:27] <- NA
</code>```

For each individual we have more than one observation. Individual 1 has 3 missing values, the 4th value is equal to 2000. Therfore, all missing values from individual 1 have to be relacped by 2000.
For individual 2 all missing values have to be replaced by the 5th observation (2002) and so on.

Of cause our dataset is very large with about 10,000 observations and 2000 individuals. I can't do it by hand.
Any smart solutions for this problem?

Thank you! :)

Body:
I have a question regarding the imputation of missing values:

For each individual my dataset has more than one row.
After the beginning of data selection, we introduced a new variable. Therefore, some individuals have missing values at the beginning of the observation. Now I have the task to replace all missing values by the first non-missing value for each individual.

For example:

set.seed(123)
d <- data.frame(
  id = rep(1:3, each = 10),
  year = rep(seq(2000,2002),10))

#Introduce NA values in first rows
d[,2][1:3] <- NA
d[,2][11:14] <- NA
d[,2][20:27] <- NA

For each individual we have more than one observation. Individual 1 has 3 missing values, the 4th value is equal to 2000. Therfore, all missing values from individual 1 have to be relacped by 2000.
For individual 2 all missing values have to be replaced by the 5th observation (2002) and so on.

Of cause our dataset is very large with about 10,000 observations and 2000 individuals. I can't do it by hand.
Any smart solutions for this problem?

Thank you! :)


问:
How to deploy GPT-like model to Triton inference server?
The tutorials on deployment GPT-like models inference to Triton looks like:

Preprocess our data as input_ids = tokenizer(text)["input_ids"]

Feed input to Triton inference server and get outputs_ids = model(input_ids)

Postprocess outputs like

```<code>outputs = outputs_ids.logits.argmax(axis=2)
outputs = tokenizer.decode(outputs)
</code>```

I use finetuned GPT2 model and this method gives incorrect result. The correct result will be obtained by model.decode(input_ids) method.

There is the way to deploy finetuned GPT-like huggingface model to Triton with inference model.decode(input_ids) not model(input_ids)?

Body:
The tutorials on deployment GPT-like models inference to Triton looks like:

Preprocess our data as input_ids = tokenizer(text)["input_ids"]

Feed input to Triton inference server and get outputs_ids = model(input_ids)

Postprocess outputs like

outputs = outputs_ids.logits.argmax(axis=2)
outputs = tokenizer.decode(outputs)

I use finetuned GPT2 model and this method gives incorrect result. The correct result will be obtained by model.decode(input_ids) method.

There is the way to deploy finetuned GPT-like huggingface model to Triton with inference model.decode(input_ids) not model(input_ids)?


问:
Plots (ggplot2) in my R markdown slides (xaringan) error when i share in R pubs or just html file
I'm trying to share mi homework in r markdown slides (with xaringan) through r pubs o just sharing the html file but i realized that the plots looks like: error that doesn't exist in my local machine.

i'm not sure why, but renderized just the r markdown has html works fine.... i guess that there could be something in the script. Also, i leave here the configuration of r chunks that deploy the plots (ggplot)

Thanks in advance


问:
openCV - Generating disparity map from stereo images
I calibrated my cameras and took a picture with each. Have rectified the images, and saved them. these are the images:

despite my best efforts, I cannot produce a decent depthmap out of these.

this is the best I got so far:

The code I use to try different values is this, where Left_Nice and Right_Nice are the images posted here:

```<code>import cv2
import numpy as np

cv2.namedWindow('disp', cv2.WINDOW_NORMAL)
cv2.resizeWindow('disp', 800, 1200)

cv2.createTrackbar('numDisparities', 'disp', 1, 50, nothing)
cv2.createTrackbar('blockSize', 'disp', 5, 50, nothing)
cv2.createTrackbar('preFilterType', 'disp', 1, 1, nothing)
cv2.createTrackbar('preFilterSize', 'disp', 2, 25, nothing)
cv2.createTrackbar('preFilterCap', 'disp', 5, 62, nothing)
cv2.createTrackbar('textureThreshold', 'disp', 10, 100, nothing)
cv2.createTrackbar('uniquenessRatio', 'disp', 15, 100, nothing)
cv2.createTrackbar('speckleRange', 'disp', 0, 100, nothing)
cv2.createTrackbar('speckleWindowSize', 'disp', 3, 25, nothing)
cv2.createTrackbar('disp12MaxDiff', 'disp', 0, 100, nothing)
cv2.createTrackbar('minDisparity', 'disp', 0, 25, nothing)

stereo = cv2.StereoBM_create()

Left_nice = cv2.imread('c:/calimages/nice_cam_left_.jpg')
Right_nice = cv2.imread('c:/calimages/nice_cam_right_.jpg')
Left_nice = cv2.cvtColor(Left_nice, cv2.COLOR_BGR2GRAY)
Right_nice = cv2.cvtColor(Right_nice, cv2.COLOR_BGR2GRAY)

while True:
    # Updating the parameters based on the trackbar positions
    numDisparities = cv2.getTrackbarPos('numDisparities', 'disp') * 16
    blockSize = cv2.getTrackbarPos('blockSize', 'disp') * 2 + 5
    preFilterType = cv2.getTrackbarPos('preFilterType', 'disp')
    preFilterSize = cv2.getTrackbarPos('preFilterSize', 'disp') * 2 + 5
    preFilterCap = cv2.getTrackbarPos('preFilterCap', 'disp')
    textureThreshold = cv2.getTrackbarPos('textureThreshold', 'disp')
    uniquenessRatio = cv2.getTrackbarPos('uniquenessRatio', 'disp')
    speckleRange = cv2.getTrackbarPos('speckleRange', 'disp')
    speckleWindowSize = cv2.getTrackbarPos('speckleWindowSize', 'disp') * 2
    disp12MaxDiff = cv2.getTrackbarPos('disp12MaxDiff', 'disp')
    minDisparity = cv2.getTrackbarPos('minDisparity', 'disp')

    # Setting the updated parameters before computing disparity map
    stereo.setNumDisparities(numDisparities)
    stereo.setBlockSize(blockSize)
    stereo.setPreFilterType(preFilterType)
    stereo.setPreFilterSize(preFilterSize)
    stereo.setPreFilterCap(preFilterCap)
    stereo.setTextureThreshold(textureThreshold)
    stereo.setUniquenessRatio(uniquenessRatio)
    stereo.setSpeckleRange(speckleRange)
    stereo.setSpeckleWindowSize(speckleWindowSize)
    stereo.setDisp12MaxDiff(disp12MaxDiff)
    stereo.setMinDisparity(minDisparity)

    # Calculating disparity using the StereoBM algorithm
    disparity = stereo.compute(Left_nice, Right_nice)
    # NOTE: Code returns a 16bit signed single channel image,
    # CV_16S containing a disparity map scaled by 16. Hence it
    # is essential to convert it to CV_32F and scale it down 16 times.

    # Converting to float32
    disparity = disparity.astype(np.float32)

    # Scaling down the disparity values and normalizing them
    disparity = (disparity / 16.0 - minDisparity) / numDisparities

    # Displaying the disparity map
    cv2.imshow("disp", disparity)
    # Close window using esc key
    if cv2.waitKey(1) == 27:
        break
</code>```

taken from this sample code:
https://learnopencv.com/depth-perception-using-stereo-camera-python-c/

any idea on what I am dong wrong?

Body:
I calibrated my cameras and took a picture with each. Have rectified the images, and saved them. these are the images:

despite my best efforts, I cannot produce a decent depthmap out of these.

this is the best I got so far:

The code I use to try different values is this, where Left_Nice and Right_Nice are the images posted here:

import cv2
import numpy as np

cv2.namedWindow('disp', cv2.WINDOW_NORMAL)
cv2.resizeWindow('disp', 800, 1200)

cv2.createTrackbar('numDisparities', 'disp', 1, 50, nothing)
cv2.createTrackbar('blockSize', 'disp', 5, 50, nothing)
cv2.createTrackbar('preFilterType', 'disp', 1, 1, nothing)
cv2.createTrackbar('preFilterSize', 'disp', 2, 25, nothing)
cv2.createTrackbar('preFilterCap', 'disp', 5, 62, nothing)
cv2.createTrackbar('textureThreshold', 'disp', 10, 100, nothing)
cv2.createTrackbar('uniquenessRatio', 'disp', 15, 100, nothing)
cv2.createTrackbar('speckleRange', 'disp', 0, 100, nothing)
cv2.createTrackbar('speckleWindowSize', 'disp', 3, 25, nothing)
cv2.createTrackbar('disp12MaxDiff', 'disp', 0, 100, nothing)
cv2.createTrackbar('minDisparity', 'disp', 0, 25, nothing)

stereo = cv2.StereoBM_create()

Left_nice = cv2.imread('c:/calimages/nice_cam_left_.jpg')
Right_nice = cv2.imread('c:/calimages/nice_cam_right_.jpg')
Left_nice = cv2.cvtColor(Left_nice, cv2.COLOR_BGR2GRAY)
Right_nice = cv2.cvtColor(Right_nice, cv2.COLOR_BGR2GRAY)

while True:
    # Updating the parameters based on the trackbar positions
    numDisparities = cv2.getTrackbarPos('numDisparities', 'disp') * 16
    blockSize = cv2.getTrackbarPos('blockSize', 'disp') * 2 + 5
    preFilterType = cv2.getTrackbarPos('preFilterType', 'disp')
    preFilterSize = cv2.getTrackbarPos('preFilterSize', 'disp') * 2 + 5
    preFilterCap = cv2.getTrackbarPos('preFilterCap', 'disp')
    textureThreshold = cv2.getTrackbarPos('textureThreshold', 'disp')
    uniquenessRatio = cv2.getTrackbarPos('uniquenessRatio', 'disp')
    speckleRange = cv2.getTrackbarPos('speckleRange', 'disp')
    speckleWindowSize = cv2.getTrackbarPos('speckleWindowSize', 'disp') * 2
    disp12MaxDiff = cv2.getTrackbarPos('disp12MaxDiff', 'disp')
    minDisparity = cv2.getTrackbarPos('minDisparity', 'disp')

    # Setting the updated parameters before computing disparity map
    stereo.setNumDisparities(numDisparities)
    stereo.setBlockSize(blockSize)
    stereo.setPreFilterType(preFilterType)
    stereo.setPreFilterSize(preFilterSize)
    stereo.setPreFilterCap(preFilterCap)
    stereo.setTextureThreshold(textureThreshold)
    stereo.setUniquenessRatio(uniquenessRatio)
    stereo.setSpeckleRange(speckleRange)
    stereo.setSpeckleWindowSize(speckleWindowSize)
    stereo.setDisp12MaxDiff(disp12MaxDiff)
    stereo.setMinDisparity(minDisparity)

    # Calculating disparity using the StereoBM algorithm
    disparity = stereo.compute(Left_nice, Right_nice)
    # NOTE: Code returns a 16bit signed single channel image,
    # CV_16S containing a disparity map scaled by 16. Hence it
    # is essential to convert it to CV_32F and scale it down 16 times.

    # Converting to float32
    disparity = disparity.astype(np.float32)

    # Scaling down the disparity values and normalizing them
    disparity = (disparity / 16.0 - minDisparity) / numDisparities

    # Displaying the disparity map
    cv2.imshow("disp", disparity)
    # Close window using esc key
    if cv2.waitKey(1) == 27:
        break

taken from this sample code:
https://learnopencv.com/depth-perception-using-stereo-camera-python-c/

any idea on what I am dong wrong?


问:
Scale changes after d3js zoom are not reflected in the circle elements on the graph
I changed the domain of the scale when zooming and repositioned the circles displayed on the graph, but they are not properly reflected.

I used the following document reference for d3js zoom.

https://observablehq.com/@d3/pan-zoom-axes

I wrote the following code according to this document.

$(document).ready(function(){
  var dataset = [
      {x: 5, y: 20, name: "one", color: "blue"},
      {x: 100, y: 50, name: "two", color: "red"},
      {x: 250, y: 80, name: "three", color: "green"},
      {x: 480, y: 90, name: "four", color: "black"},
    ];

  var a = 1;
  const width = 400;
  const height = 300;
  const margin = { "top": 30, "bottom": 60, "right": 30, "left": 60 };
  const svgWidth = width + margin.left + margin.right;
  const svgHeight = height + margin.top + margin.bottom;
  var radius = 5;
  var tooltipFlag = false;
  var originalDomainX = [0, d3.max(dataset, function(d) { return d.x; }) + 10];
  var originalDomainY = [0, d3.max(dataset, function(d) { return d.y; }) + 10];
  const zoomAmount = 1.0

  var svg = d3.select("#graph-area").append("svg")
      .attr("width", svgWidth)
      .attr("height", svgHeight)
      .style("border-radius", "20px 20px 20px 20px")
      .append("g")
      .attr("transform", `translate(${margin.left}, ${margin.top})`);

  var tooltip = d3.select("#graph-area")
        .append("div")
        .attr("id", "dc-tooltip")
        .attr("class", "chart-tooltip");

  var xScale = d3.scaleLinear()
    .domain(originalDomainX)
    .range([0, width]);

  var yScale = d3.scaleLinear()
    .domain(originalDomainY)
    .range([height, 0]);

  var axisx = d3.axisBottom().scale(xScale).ticks(5);
  var axisy = d3.axisLeft().scale(yScale).ticks(5);

  var gx = svg.append("g")
    .attr("transform", "translate(" + 0 + "," + height + ")")
    .call(axisx)
    .attr("class", "axisx")

   gx.append("text")
        .attr("x", (width - margin.left - margin.right) / 2 + margin.left)
        .attr("y", 35)
        .attr("text-anchor", "middle")
        .attr("font-size", "10pt")
        .attr("font-weight", "bold")
        .text("X Label")
        .attr("class", "x_axis")

  var gy = svg.append("g")
    .call(axisy)
    .attr("class", "axisy")

  gy.append("text")
    .attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
    .attr("y", -35)
    .attr("transform", "rotate(-90)")
    .attr("text-anchor", "middle")
    .attr("font-weight", "bold")
    .attr("font-size", "10pt")
    .text("Y Label")
    .attr("class", "y_axis")

  var clip = svg.append("defs").append("svg:clipPath")
            .attr("id", "clip")
            .append("svg:rect")
            .attr("width", width )
            .attr("height", height )
            .attr("x", 0)
            .attr("y", 0);

  var zoom = d3.zoom().on("zoom", zoomed)
              .scaleExtent([1, 10])

  function zoomed({transform}){

    gx.call(axisx.scale(transform.rescaleX(xScale)));
    gy.call(axisy.scale(transform.rescaleY(yScale)));

    circles.attr("cx", function(d){return d.x = xScale(d.rx)}).attr("cy", function(d){return d.y = yScale(d.ry)});

  }

  var zoomArea = svg.append("g")
         .attr("class", "zoomArea")
         .style("cursor","move")
         .attr("clip-path", "url(#clip)");
  var zoomRect = zoomArea.append("rect")
       .attr("x", margin.x)
       .attr("y", 0)
       .attr("width", width)
       .attr("height", height)
       .attr("fill", "rgba(0, 0, 0, 0)")
       .style("pointer-events", "all")
       .style("cursor","move")
       .call(zoom);

  var circleg = svg.append("g")
        .attr("id", "scatterplot")
        .attr("clip-path", "url(#clip)");

  var circles;
  createCircles();

  function createCircles(){
    circles = circleg.selectAll("circle")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
      d.ox = d.x;
      d.rx = d.x;
      return d.x = xScale(d.x);
    })
    .attr("cy", function(d) {
      d.oy = d.y;
      d.ry = d.y;
      return d.y = yScale(d.y);
    })
    .attr("fill", function(d){return d.color})
    .attr("r", radius)
    .attr("opacity", 0.3)

  }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>D3 Scatter Plot</title>
  <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>

<body>
  <div id="graph-area"></div>

</body>

</html></code>```

However, the redrawn circle remains in the same place in the svg drawing area as before the change. I thought this was because the xScale used was not updated, so I fixed function zoomed as follows.
view.js

  function zoomed({transform}){

    xScale.domain(transform.rescaleX(xScale).domain());
    yScale.domain(transform.rescaleY(yScale).domain());
    axisx.scale(xScale);
    axisy.scale(yScale);
    gx.call(axisx);
    gy.call(axisy);

    circles.attr("cx", function(d){return d.x = xScale(d.rx)})
           .attr("cy", function(d){return d.y = yScale(d.ry)});

  }```

However, when I run this code, the scaling by zooming does not work correctly. The following two appear to perform the same function, but what is the actual difference?

Body:
I changed the domain of the scale when zooming and repositioned the circles displayed on the graph, but they are not properly reflected.

I used the following document reference for d3js zoom.

https://observablehq.com/@d3/pan-zoom-axes

I wrote the following code according to this document.

$(document).ready(function(){
  var dataset = [
      {x: 5, y: 20, name: "one", color: "blue"},
      {x: 100, y: 50, name: "two", color: "red"},
      {x: 250, y: 80, name: "three", color: "green"},
      {x: 480, y: 90, name: "four", color: "black"},
    ];

  var a = 1;
  const width = 400;
  const height = 300;
  const margin = { "top": 30, "bottom": 60, "right": 30, "left": 60 };
  const svgWidth = width + margin.left + margin.right;
  const svgHeight = height + margin.top + margin.bottom;
  var radius = 5;
  var tooltipFlag = false;
  var originalDomainX = [0, d3.max(dataset, function(d) { return d.x; }) + 10];
  var originalDomainY = [0, d3.max(dataset, function(d) { return d.y; }) + 10];
  const zoomAmount = 1.0

  var svg = d3.select("#graph-area").append("svg")
      .attr("width", svgWidth)
      .attr("height", svgHeight)
      .style("border-radius", "20px 20px 20px 20px")
      .append("g")
      .attr("transform", `translate(${margin.left}, ${margin.top})`);

  var tooltip = d3.select("#graph-area")
        .append("div")
        .attr("id", "dc-tooltip")
        .attr("class", "chart-tooltip");

  var xScale = d3.scaleLinear()
    .domain(originalDomainX)
    .range([0, width]);

  var yScale = d3.scaleLinear()
    .domain(originalDomainY)
    .range([height, 0]);

  var axisx = d3.axisBottom().scale(xScale).ticks(5);
  var axisy = d3.axisLeft().scale(yScale).ticks(5);

  var gx = svg.append("g")
    .attr("transform", "translate(" + 0 + "," + height + ")")
    .call(axisx)
    .attr("class", "axisx")

   gx.append("text")
        .attr("x", (width - margin.left - margin.right) / 2 + margin.left)
        .attr("y", 35)
        .attr("text-anchor", "middle")
        .attr("font-size", "10pt")
        .attr("font-weight", "bold")
        .text("X Label")
        .attr("class", "x_axis")

  var gy = svg.append("g")
    .call(axisy)
    .attr("class", "axisy")

  gy.append("text")
    .attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
    .attr("y", -35)
    .attr("transform", "rotate(-90)")
    .attr("text-anchor", "middle")
    .attr("font-weight", "bold")
    .attr("font-size", "10pt")
    .text("Y Label")
    .attr("class", "y_axis")

  var clip = svg.append("defs").append("svg:clipPath")
            .attr("id", "clip")
            .append("svg:rect")
            .attr("width", width )
            .attr("height", height )
            .attr("x", 0)
            .attr("y", 0);

  var zoom = d3.zoom().on("zoom", zoomed)
              .scaleExtent([1, 10])

  function zoomed({transform}){

    gx.call(axisx.scale(transform.rescaleX(xScale)));
    gy.call(axisy.scale(transform.rescaleY(yScale)));

    circles.attr("cx", function(d){return d.x = xScale(d.rx)}).attr("cy", function(d){return d.y = yScale(d.ry)});

  }

  var zoomArea = svg.append("g")
         .attr("class", "zoomArea")
         .style("cursor","move")
         .attr("clip-path", "url(#clip)");
  var zoomRect = zoomArea.append("rect")
       .attr("x", margin.x)
       .attr("y", 0)
       .attr("width", width)
       .attr("height", height)
       .attr("fill", "rgba(0, 0, 0, 0)")
       .style("pointer-events", "all")
       .style("cursor","move")
       .call(zoom);

  var circleg = svg.append("g")
        .attr("id", "scatterplot")
        .attr("clip-path", "url(#clip)");

  var circles;
  createCircles();

  function createCircles(){
    circles = circleg.selectAll("circle")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
      d.ox = d.x;
      d.rx = d.x;
      return d.x = xScale(d.x);
    })
    .attr("cy", function(d) {
      d.oy = d.y;
      d.ry = d.y;
      return d.y = yScale(d.y);
    })
    .attr("fill", function(d){return d.color})
    .attr("r", radius)
    .attr("opacity", 0.3)

  }

})

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>D3 Scatter Plot</title>

However, the redrawn circle remains in the same place in the svg drawing area as before the change. I thought this was because the xScale used was not updated, so I fixed function zoomed as follows.
view.js

  function zoomed({transform}){

    xScale.domain(transform.rescaleX(xScale).domain());
    yScale.domain(transform.rescaleY(yScale).domain());
    axisx.scale(xScale);
    axisy.scale(yScale);
    gx.call(axisx);
    gy.call(axisy);

    circles.attr("cx", function(d){return d.x = xScale(d.rx)})
           .attr("cy", function(d){return d.y = yScale(d.ry)});

  }

However, when I run this code, the scaling by zooming does not work correctly. The following two appear to perform the same function, but what is the actual difference?


问:
React Native - Task :app:processReleaseMainManifest FAILED, error (aab) after changing to compileSdkVersion and targetSdkVersion to 31
After switching to compileSdkVersion = 31 due to GooglePlay changes (The target API level for your application is 30. To ensure the required performance and security, the target API level must be at least 31. Change the target API level for the application so that it becomes at least 31). Not going to bundle. My actions:

changed in build.gradle file
"compileSdkVersion=31 targetSdkVersion=31"

./gradlew bundleRelease

I get an error:

Task :app:processReleaseMainManifest FAILED
[:@react-native-firebase_config] /Users/butinproject/it-department/stable-android/kapibara_mobile_app/node_modules/@react-native-firebase/remote-config/android/build/intermediates/merged_manifest/release/AndroidManifest.xml Warning:
Package name 'io.invertase.firebase.config' used in: :@react-native-firebase_config, :react-native-firebase_remote-config.
[:@react-native-firebase_analytics] /Users/butinproject/it-department/stable-android/kapibara_mobile_app/node_modules/@react-native-firebase/analytics/android/build/intermediates/merged_manifest/release/AndroidManifest.xml Warning:
Package name 'io.invertase.firebase.analytics' used in: :@react-native-firebase_analytics, :react-native-firebase_analytics.
[:@react-native-firebase_perf] /Users/butinproject/it-department/stable-android/kapibara_mobile_app/node_modules/@react-native-firebase/perf/android/build/intermediates/merged_manifest/release/AndroidManifest.xml Warning:
Package name 'io.invertase.firebase.perf' used in: :@react-native-firebase_perf, :react-native-firebase_perf.
/Users/butinproject/it-department/stable-android/kapibara_mobile_app/android/app/src/main/AndroidManifest.xml Error:
Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

See http://g.co/androidstudio/manifest-merger for more information about the manifest merger.

Perhaps something else is needed to switch to Android 12?

try

changed in build.gradle file
"compileSdkVersion=31 targetSdkVersion=31"

./gradlew bundleRelease

Wanted to get:
build success

got instead: error

Task :app:processReleaseMainManifest FAILED


问:
Autoencoder is being trained through only one iteration per epoch
I am training an encoder with a custom dataset in google colab directory (train folder/test folder) using the code below (based on 1):

```<code>    my_data_train_dir = train_path
    labels_train = os.listdir(my_data_train_dir)
    data_train = tf.keras.utils.image_dataset_from_directory(train_path, batch_size=1, image_size=(224, 224))
    data_train_iterator = data_train.as_numpy_iterator()
    batch_train = data_train_iterator.next()

    my_data_test_dir = test_path
    labels_test = os.listdir(my_data_test_dir)
    data_test = tf.keras.utils.image_dataset_from_directory(test_path, batch_size=1, image_size=(224, 224))
    data_test_iterator = data_test.as_numpy_iterator()
    batch_test = data_test_iterator.next()

# Found 10903 files belonging to 67 classes.
# Found 1619 files belonging to 67 classes

    encoder = keras.models.Sequential([
        keras.layers.Flatten(input_shape=[224, 224, 3]),
        keras.layers.Dense(400, activation="relu"),
        keras.layers.Dense(200, activation="relu"),
        keras.layers.Dense(100, activation="relu"),
        keras.layers.Dense(50, activation="relu"),
        keras.layers.Dense(25, activation="relu"),
    ])

    decoder = keras.models.Sequential([
        keras.layers.Dense(50, activation="relu", input_shape=[25]),
        keras.layers.Dense(100, activation="relu"),
        keras.layers.Dense(200, activation="relu"),
        keras.layers.Dense(400, activation="relu"),
        keras.layers.Dense(224 * 224 * 3, activation="sigmoid"),
        keras.layers.Reshape([224, 224, 3])
    ])

    stacked_autoencoder = keras.models.Sequential([encoder, decoder])

    stacked_autoencoder.compile(loss="binary_crossentropy",
                       optimizer='adam', metrics=['accuracy'])

    x_train = batch_train[0] / 255
    x_test = batch_test[0] / 255
    history = stacked_autoencoder.fit(x_train, x_train, epochs=10,
                                      validation_data=[x_test, x_test])
Epoch 1/10
1/1 [==============================] - 0s 77ms/step - loss: 0.5549 - accuracy: 0.9994 - val_loss: 0.7653 - val_accuracy: 0.5443
Epoch 2/10
1/1 [==============================] - 0s 51ms/step - loss: 0.5549 - accuracy: 0.9992 - val_loss: 0.7669 - val_accuracy: 0.5444
Epoch 3/10
1/1 [==============================] - 0s 51ms/step - loss: 0.5549 - accuracy: 0.9994 - val_loss: 0.7646 - val_accuracy: 0.5443
</code>```

As you can see, the training at each epoch is done through 1 iteration only knowing that we have 10903 training images in total (10903/1 = 10903 iterations). How can I solve this problem ?

Thank in advance !

Body:
I am training an encoder with a custom dataset in google colab directory (train folder/test folder) using the code below (based on 1):

    my_data_train_dir = train_path
    labels_train = os.listdir(my_data_train_dir)
    data_train = tf.keras.utils.image_dataset_from_directory(train_path, batch_size=1, image_size=(224, 224))
    data_train_iterator = data_train.as_numpy_iterator()
    batch_train = data_train_iterator.next()

    my_data_test_dir = test_path
    labels_test = os.listdir(my_data_test_dir)
    data_test = tf.keras.utils.image_dataset_from_directory(test_path, batch_size=1, image_size=(224, 224))
    data_test_iterator = data_test.as_numpy_iterator()
    batch_test = data_test_iterator.next()

# Found 10903 files belonging to 67 classes.
# Found 1619 files belonging to 67 classes

    encoder = keras.models.Sequential([
        keras.layers.Flatten(input_shape=[224, 224, 3]),
        keras.layers.Dense(400, activation="relu"),
        keras.layers.Dense(200, activation="relu"),
        keras.layers.Dense(100, activation="relu"),
        keras.layers.Dense(50, activation="relu"),
        keras.layers.Dense(25, activation="relu"),
    ])

    decoder = keras.models.Sequential([
        keras.layers.Dense(50, activation="relu", input_shape=[25]),
        keras.layers.Dense(100, activation="relu"),
        keras.layers.Dense(200, activation="relu"),
        keras.layers.Dense(400, activation="relu"),
        keras.layers.Dense(224 * 224 * 3, activation="sigmoid"),
        keras.layers.Reshape([224, 224, 3])
    ])

    stacked_autoencoder = keras.models.Sequential([encoder, decoder])

    stacked_autoencoder.compile(loss="binary_crossentropy",
                       optimizer='adam', metrics=['accuracy'])

    x_train = batch_train[0] / 255
    x_test = batch_test[0] / 255
    history = stacked_autoencoder.fit(x_train, x_train, epochs=10,
                                      validation_data=[x_test, x_test])
Epoch 1/10
1/1 [==============================] - 0s 77ms/step - loss: 0.5549 - accuracy: 0.9994 - val_loss: 0.7653 - val_accuracy: 0.5443
Epoch 2/10
1/1 [==============================] - 0s 51ms/step - loss: 0.5549 - accuracy: 0.9992 - val_loss: 0.7669 - val_accuracy: 0.5444
Epoch 3/10
1/1 [==============================] - 0s 51ms/step - loss: 0.5549 - accuracy: 0.9994 - val_loss: 0.7646 - val_accuracy: 0.5443

As you can see, the training at each epoch is done through 1 iteration only knowing that we have 10903 training images in total (10903/1 = 10903 iterations). How can I solve this problem ?

Thank in advance !


问:
How to unzip to a specific folder name using the decompress package with Node.js
I write a simple Node.js app, that downloads zip file from internet and unzip in specific folder.

I use decompress npm package to do it.

zip file name is rclone-current-windows-amd64.zip

and I want to unzip it in C:\rclone in Windows OS but it decompresses with create new folder rclone-current-windows-amd64 path.

So the result is like this C:\rclone\rclone-v1.60.1-windows-amd64 with my code.

It seems that I can do it with just decompress under C:\ path and decompress it and rename the folder but, I want to know there are other options to do this.

```<code>const https = require("https"); // Use the https module to download the file
const fs = require("fs"); // Use the fs module to read and write files
const decompress = require("decompress"); // Use the decompress package to decompress the downloaded file

const fileUrl = "https://downloads.rclone.org/rclone-current-windows-amd64.zip"; // URL of the zip file to download
const filePath = "C:/rclone/test/file.zip"; // Local path where the zip file will be downloaded
const unzipPath = "C:/rclone"; // Local path where the zip file will be decompressed

https.get(fileUrl, (response) => {
  // Pipe the downloaded file to the local file path
  response.pipe(fs.createWriteStream(filePath)).on("close", () => {
    // When the download is complete, decompress the file
    decompress(filePath, unzipPath, {
      map: (file) => {
        console.log(file);
        file.path = `unicorn-${file.path}`;
        // return file;
      },
    })
      .then(() => {
        // When the file is decompressed, delete the zip file
        fs.unlinkSync(filePath);
        console.log("Done!");
      })
      .catch((err) => {
        console.error(err);
      });
  });
});

</code>```

Body:
I write a simple Node.js app, that downloads zip file from internet and unzip in specific folder.

I use decompress npm package to do it.

zip file name is rclone-current-windows-amd64.zip

and I want to unzip it in C:\rclone in Windows OS but it decompresses with create new folder rclone-current-windows-amd64 path.

So the result is like this C:\rclone\rclone-v1.60.1-windows-amd64 with my code.

It seems that I can do it with just decompress under C:\ path and decompress it and rename the folder but, I want to know there are other options to do this.

const https = require("https"); // Use the https module to download the file
const fs = require("fs"); // Use the fs module to read and write files
const decompress = require("decompress"); // Use the decompress package to decompress the downloaded file

const fileUrl = "https://downloads.rclone.org/rclone-current-windows-amd64.zip"; // URL of the zip file to download
const filePath = "C:/rclone/test/file.zip"; // Local path where the zip file will be downloaded
const unzipPath = "C:/rclone"; // Local path where the zip file will be decompressed

https.get(fileUrl, (response) => {
  // Pipe the downloaded file to the local file path
  response.pipe(fs.createWriteStream(filePath)).on("close", () => {
    // When the download is complete, decompress the file
    decompress(filePath, unzipPath, {
      map: (file) => {
        console.log(file);
        file.path = `unicorn-${file.path}`;
        // return file;
      },
    })
      .then(() => {
        // When the file is decompressed, delete the zip file
        fs.unlinkSync(filePath);
        console.log("Done!");
      })
      .catch((err) => {
        console.error(err);
      });
  });
});


问:
Adobe acrobat fails to detect some footers on my PDFs
i'm trying to covert PDFs into HTMLs and process text within them to preserve layout using Adobe Acrobat Pro and i'm finding it hard to remove some footers from the PDFs as they are categorized as paragraphs itself. Do i need to do some post processing before opening it in adobe? has anybody faced this issue? please help.

PDF sample: PDF Drive Link

page 4: 1 IBA/215/2020
2 Ordinance 9 of 2020 (the “Ordinance”)
3 IA 395 of 2020

page 12: 4 1957 SCR 605
5 “Whereas with a view to putting a check on the growing tendency of landholders to eject or dispossess tenants from their holdings, and in the wider national interest of increasing the production of foodgrains, it is expedient to make provisions for the protection of tenants in Rajasthan from ejectment or dispossession from their holdings.”
**
page 15:** 6. G.P. Singh, Principles of Statutory Interpretation (1st edn., Lexis Nexis 2015)

page 16: 7 (2019) 4 SCC 17

These are all footers and i have PDFs ranging from years 2000 to 2022. This particular PDF is from 2020 and i need help removing these footers. shall i do some post processing on the PDFs? please help.


问:
How to upload all files from local folder to FTP server using batch script?
I need help to upload all files stored into a local folder to the FTP server.

I have created a batch script that can upload the latest file from the local folder to FTP, but I neeed someone who can edit this script and it should upload all files from the local directory.

echo off
REM - FTP Parameters
set Username=ABC
set Password=123
set Upload_DIR=%Local_DIR%
set Upload_FILES="C:\\New folder"
set Filename_wildcard=\*practice\*
echo 1
echo %Upload_DIR%
del %Upload_DIR%
copy /y nul %Upload_DIR%
echo 2
echo option batch abort \> %Upload_DIR%
echo option confirm off \>\> %Upload_DIR%
echo open %Username%:%Password%@hostname/ \>\> %Upload_DIR%
echo %Upload_FILES%\\%Filename_wildcard%
for /f "tokens=\*" %%a in ('dir %Upload_FILES%\\%Filename_wildcard% /b /od /a-d') do set latest=%%a
echo Latest File: %latest%
echo 3
echo cd Outbox \>\> %Upload_DIR%
echo put %Upload_FILES%\\%latest% -nopreservetime -nopermissions \>\> %Upload_DIR%
echo close \>\> %Upload_DIR%
echo exit \>\> %Upload_DIR%
```


问:
What is the best possible object/format (parquet/pickle/csv/txt/...) to store a scipy.sparse.csr.csr_matrix into S3 bucket?
I used a scipy.sparse.csr.csr_matrix of size - (281333, 2550842) train a XGBoost model. Now I am in the process of deploying this model using SageMaker pipeline but facing a challenge to store this vector into S3 bucket. Appreciate your help. Thanks

I stored the rows of matrix into a csv but pandas.read_csv is giving me a string of

```<code>"[<1x2550842 sparse matrix of type '<class 'numpy.int64'>'\n\twith 220 stored elements in Compressed Sparse Row format>]"
</code>```

Body:
I used a scipy.sparse.csr.csr_matrix of size - (281333, 2550842) train a XGBoost model. Now I am in the process of deploying this model using SageMaker pipeline but facing a challenge to store this vector into S3 bucket. Appreciate your help. Thanks

I stored the rows of matrix into a csv but pandas.read_csv is giving me a string of

"[<1x2550842 sparse matrix of type '<class 'numpy.int64'>'\n\twith 220 stored elements in Compressed Sparse Row format>]"


问:
Can't get OAuth 2 Scope. It is not set. Quickbook
I have successfully integrated Quickbook accounting APIs with the Development Keys and Credentials. Moreover, when I put Production Keys and Secret, I got an error with status code (403), and later I got to know that is because of scopes.
I noticed there is a function called "getScope()" to check the token scopes. I went to try that and get the following error:

Can't get OAuth 2 Scope. It is not set.

I even tried using access and refresh tokens from the API playground. Still, the error is there.
Here is my code snippet:

```<code>$dataService = DataService::Configure(array(
        'auth_mode' => 'oauth2',
        'ClientID' => $quickBookData->client_id,
        'ClientSecret' => $quickBookData->client_secret,
        'accessTokenKey' => $quickBookData->access_token,
        'refreshTokenKey' => $quickBookData->refresh_token,
        'QBORealmID' => $quickBookData->realm_id,
        'baseUrl' => "production",
    ));
    $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
    $scopes = $OAuth2LoginHelper->getScope();
</code>```

Body:
I have successfully integrated Quickbook accounting APIs with the Development Keys and Credentials. Moreover, when I put Production Keys and Secret, I got an error with status code (403), and later I got to know that is because of scopes.
I noticed there is a function called "getScope()" to check the token scopes. I went to try that and get the following error:

Can't get OAuth 2 Scope. It is not set.

I even tried using access and refresh tokens from the API playground. Still, the error is there.
Here is my code snippet:

$dataService = DataService::Configure(array(
        'auth_mode' => 'oauth2',
        'ClientID' => $quickBookData->client_id,
        'ClientSecret' => $quickBookData->client_secret,
        'accessTokenKey' => $quickBookData->access_token,
        'refreshTokenKey' => $quickBookData->refresh_token,
        'QBORealmID' => $quickBookData->realm_id,
        'baseUrl' => "production",
    ));
    $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
    $scopes = $OAuth2LoginHelper->getScope();


问:
Emulate a focused page programmatically with a Chrome extension in JS
I made a Chrome extension and I want it to make a specific tab think it's focused, even if it's not.

I know I can do it manually by opening Chrome DevTools panel and enabling "Emulate a focused page" but I really want my extension to do it programmatically.

Do you think it is possible ? Thx


问:
URL in iframe results in "Site not found" error even though site is valid
The details of this issue are quite complex and confusing, but I will try to explain as clearly as I can.

I have written an app using NWJS which uses an iframe within which I am loading the web page generated by similar devices (surveillance cameras) on my local network, using ip addresses (192.168.1.252 and 192.168.1.245).  One device is newer than the other.

I am able to access the older camera just fine using the url http:/192.168.1.252/ in the src attribute of the iframe.

However, I am unable to access the newer camera this way (http:192.168.1.245/), and get a "Page not found" error.  BUT, I can access either camera just fine in Firefox using the ip address.  HOWEVER, in Chrome, I can only access the older camera; the newer one gives me a "connection not private ... NET::ERR_CERT_AUTHORITY_INVALID" error.

I found this question on SO that is related, which talked about things getting screwed up due to redirection: HTTPS iframe inside a HTTPS page not working .  In Firefox (where I can access both devices) I observe that in both cases, the url redirects to an https url.  Based on the advice given in the SO question, for both urls, I have tried using various combinations in the src attribute of the iframe:

http://192.168.1.xxx

http://192.168.1.xxx/

https://192.168.1.xxx

https://192.168.1.xxx/

(What is really interesting to me, only http://... in src attribute the will work for the older device; if I use https://... (the protocol it gets redirected to when it works in the browser) I get "page not found".  I don't know if this bit on information is helpful or more of a diversion.)

There is nothing that indicates this is a cross-origin issue, and there shouldn't be as I am using the nwfaketop nwdisable attributes as talked about on this page: Avoid iframe-busting with nwdisable and nwfaketop? .

The HTML in the NWJS app is as follows:

```<code><!doctype HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>ReolinkNWJS_TEST</title>
</head>

<body>
  <iframe id="reolink_page" src="http://192.168.1.245/" nwfaketop nwdisable>
  </iframe>
</body>
</html>
</code>```

package.json:

```<code>{
  "name": "ReolinkNWJS_TEST",
  "description": "TEST",
  "version": "0.0.1",
  "icon": "icons/app.icns",
  "main": "html/main.html",
  "chromium-args": "--enable-logging=stderr --enable-spell-checking",
  "window": {
    "toolbar": false,
    "width": 800,
    "height": 500,
    "position": "center"
  },
  "nodejs": true,
  "node-remote": "*://*",
  "scripts": {
    "prod": "nwbuild --platforms win64 --buildDir dist/ ./"
  },
  "devDependencies": {
    "nw": "^0.12.0",
    "nw-builder": "^3.7.0"
  }
}
</code>```

I'll update with any other code if needed.

Body:
The details of this issue are quite complex and confusing, but I will try to explain as clearly as I can.

I have written an app using NWJS which uses an iframe within which I am loading the web page generated by similar devices (surveillance cameras) on my local network, using ip addresses (192.168.1.252 and 192.168.1.245).  One device is newer than the other.

I am able to access the older camera just fine using the url http:/192.168.1.252/ in the src attribute of the iframe.

However, I am unable to access the newer camera this way (http:192.168.1.245/), and get a "Page not found" error.  BUT, I can access either camera just fine in Firefox using the ip address.  HOWEVER, in Chrome, I can only access the older camera; the newer one gives me a "connection not private ... NET::ERR_CERT_AUTHORITY_INVALID" error.

I found this question on SO that is related, which talked about things getting screwed up due to redirection: HTTPS iframe inside a HTTPS page not working .  In Firefox (where I can access both devices) I observe that in both cases, the url redirects to an https url.  Based on the advice given in the SO question, for both urls, I have tried using various combinations in the src attribute of the iframe:

http://192.168.1.xxx

http://192.168.1.xxx/

https://192.168.1.xxx

https://192.168.1.xxx/

(What is really interesting to me, only http://... in src attribute the will work for the older device; if I use https://... (the protocol it gets redirected to when it works in the browser) I get "page not found".  I don't know if this bit on information is helpful or more of a diversion.)

There is nothing that indicates this is a cross-origin issue, and there shouldn't be as I am using the nwfaketop nwdisable attributes as talked about on this page: Avoid iframe-busting with nwdisable and nwfaketop? .

The HTML in the NWJS app is as follows:

<!doctype HTML>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>ReolinkNWJS_TEST</title>

package.json:

{
  "name": "ReolinkNWJS_TEST",
  "description": "TEST",
  "version": "0.0.1",
  "icon": "icons/app.icns",
  "main": "html/main.html",
  "chromium-args": "--enable-logging=stderr --enable-spell-checking",
  "window": {
    "toolbar": false,
    "width": 800,
    "height": 500,
    "position": "center"
  },
  "nodejs": true,
  "node-remote": "*://*",
  "scripts": {
    "prod": "nwbuild --platforms win64 --buildDir dist/ ./"
  },
  "devDependencies": {
    "nw": "^0.12.0",
    "nw-builder": "^3.7.0"
  }
}

I'll update with any other code if needed.


问:
AG-grid Set filter can have separate values to api other then what it is showing in set filter
we came in scenario where we have set filter and to display value to user is something descriptive e.g like a country name, and while applying a filter have to send some code e.g country code to backend application. we tried couple of ways but didn't get luck in that. i tried  any expert help?</p>


问:
Problem with InstallForge and CustomTkinter
I am currently working on a gui with the custom tkinter lib.

I created the .exe file by adding the CustomTkinter with auto-py-to-exe

Then I use the InstallForge software because I want to share my file.

After that I got my setup file, it works on my computer but not on my friends one.

Do you guys now why ?

I try to use other software like Inno Setup compiler but the problem is still the same, the application cant be launched.

I run is as admin : result : the application cant be launched.

Here is the files that I add in the software Install Forge

Thank you.


问:
What is the difference between `jtwDecode` and `jwt_decode`
I'm working on a typescript code in an angular project and am seeing that both ways of using jwt-decode seems to work the same way:

```<code>import jwt_decode from 'jwt-decode';
</code>```

and

```<code>import jwtDecode from 'jwt-decode';
</code>```

Is there any difference between the two? Is there a preferred option between the two?

Body:
I'm working on a typescript code in an angular project and am seeing that both ways of using jwt-decode seems to work the same way:

import jwt_decode from 'jwt-decode';

and

import jwtDecode from 'jwt-decode';

Is there any difference between the two? Is there a preferred option between the two?


问:
Percent of map and reduce continuously changing
I am running a job on production with below config and for some reason the percentage of map and percentage of reduce is decreasing instead of increasing. I want to know why such kind of behavior.

Percentage Completed

It can be seen in above image that the percent of reduce has decreased from 97% to 93%. Even map percent is changing in between to 95-99%

HQL configs:

```<code>set mapreduce.jobtracker.split.metainfo.maxsize=-1;
set mapred.job.queue.name=root.mciaae;
set hive.exec.max.dynamic.partitions=50000;
set hive.exec.max.dynamic.partitions.pernode=10000000;
set hive.exec.max.created.files=10000000;
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.optimize.sort.dynamic.partition=true;
set hive.stats.autogather=false;
set hive.merge.size.per.task=268435456;
set hive.merge.smallfiles.avgsize=268435456;
set mapred.output.compress=true;
set hive.exec.compress.output=true;
set mapreduce.reduce.shuffle.memory.limit.percent=0.15;
</code>```

I checked the number of reducers and mappers on the tracking URL and the remain same only.

Body:
I am running a job on production with below config and for some reason the percentage of map and percentage of reduce is decreasing instead of increasing. I want to know why such kind of behavior.

Percentage Completed

It can be seen in above image that the percent of reduce has decreased from 97% to 93%. Even map percent is changing in between to 95-99%

HQL configs:

set mapreduce.jobtracker.split.metainfo.maxsize=-1;
set mapred.job.queue.name=root.mciaae;
set hive.exec.max.dynamic.partitions=50000;
set hive.exec.max.dynamic.partitions.pernode=10000000;
set hive.exec.max.created.files=10000000;
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.optimize.sort.dynamic.partition=true;
set hive.stats.autogather=false;
set hive.merge.size.per.task=268435456;
set hive.merge.smallfiles.avgsize=268435456;
set mapred.output.compress=true;
set hive.exec.compress.output=true;
set mapreduce.reduce.shuffle.memory.limit.percent=0.15;

I checked the number of reducers and mappers on the tracking URL and the remain same only.