问:
Share SQLAlchemy database session between objects
Currently I have a Flask-SQLAlchemy session object and also a plain Sessionmaker SQLAlchemy object in my project(legacy use case). I want to share the session between those two so that if I do flush in one session I can get the data in another session as well. For example

```<code>flask_db_session.flush()
</code>```

Then access some data in another session

```<code>session.query(<Model>).first()
</code>```

Mainly  I'm removing commits from pytest cases with flush. Everything is working great except the session that is managed with a different object. It works fine with commit because the data is changed actually in the db.

Body:
Currently I have a Flask-SQLAlchemy session object and also a plain Sessionmaker SQLAlchemy object in my project(legacy use case). I want to share the session between those two so that if I do flush in one session I can get the data in another session as well. For example

flask_db_session.flush()

Then access some data in another session

session.query(<Model>).first()

Mainly  I'm removing commits from pytest cases with flush. Everything is working great except the session that is managed with a different object. It works fine with commit because the data is changed actually in the db.


来源: stackexchange

问:
Built a very simple AVAudioEngine music player app. Resuming AVAudioEngine causing lag in the UI especially when resuming some time after pausing
Edit 2: When I don't pause the audio engine and just the player node and then resume the player node, there is no ui lag or anything at all. Smooth playback with no crackling. But I have to pause the audio engine to update the MPRemoteCommandCenter Playback controls so I am kinda stuck.

Edit: The delay is much much more apparent when using bluetooth headphones such as AirPods.

I have attached the entire code below. It is a very very basic app to reproduce the lag issue I am having in my bigger app. You could literally copy the entire code below into a SwiftUI Project and it will run.

I am unable to find the source of the lag that is being caused in the UI. Pressing the pause button is very smooth. When I pause and I wait for a couple of seconds (especially like 5 seconds or longer) and then press play, I could see that it takes some time for the player node to resume.

Furthermore, I could hear some crackling sounds when I connect more audio units such as reverb and pitch.

Could someone explain what's the cause and issue for the UI lag and the crackling issue?

I did profile the code below, and quite a number of micro hangs were registered. My bigger app registered much more longer hangs.

```<code>struct PlayerButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            configuration.label
                .font(.system(size: 35))
                .foregroundColor(.white)
                .padding(15)
                .background(configuration.isPressed ? .gray.opacity(0.3) : .clear)
                .clipShape(Circle())
                .scaleEffect(configuration.isPressed ? 0.8 : 1.0)
        }
    }

struct ContentView: View {
    @State private var isPlaying = false

    var body: some View {
        VStack(spacing: 50) {

            Button {
                withAnimation {
                    if isPlaying {
                        AudioManager.shared.pause()
                        isPlaying = false
                    } else {
                        AudioManager.shared.play()
                        isPlaying = true
                    }
                }
            } label: {
                if isPlaying {
                    Image(systemName: "pause.fill")
                } else {
                    Image(systemName: "play.fill")
                }
            }
            .buttonStyle(PlayerButtonStyle())

            Scrubber()
        }
        .padding()
    }
}

struct Scrubber: View {
    @EnvironmentObject var viewModel: ViewModel
    @State private var sliderValue = 0.0

    var body: some View {
        Slider(value: $sliderValue, in: 0...(AudioManager.shared.file?.duration ?? 0))
            .onReceive(viewModel.$sliderValue) { _ in
                sliderValue = viewModel.sliderValue
            }
    }
}

class ViewModel: ObservableObject {
    @Published var sliderValue = 0.0
}

extension AVAudioFile {
    //Duration
    var duration: TimeInterval {
        let sampleRateSong = Double(processingFormat.sampleRate)
        let lengthSongSeconds = Double(length) / sampleRateSong
        return lengthSongSeconds
    }
}

extension AVAudioPlayerNode {
    //Current Time
    var currentTime: TimeInterval {
        if let nodeTime = lastRenderTime, let playerTime = playerTime(forNodeTime: nodeTime) {
            return Double(playerTime.sampleTime) / outputFormat(forBus: 0).sampleRate
        }
        return 0
    }
}

class AudioManager {
    static let shared = AudioManager()

    var viewModel = ViewModel()

    let engine = AVAudioEngine()
    let player = AVAudioPlayerNode()
    let pitchNode = AVAudioUnitTimePitch()
    let reverb = AVAudioUnitReverb()

    var file: AVAudioFile?
    var displayLink: CADisplayLink?

    init() {
        setupSlider()
        prepareToPlay()
        enableBackgroundPlay()
        setupNowPlaying()
        setupMediaPlayerControls()
    }

    func setupSlider() {
        displayLink = CADisplayLink(target: self, selector: #selector(updateScrubber))
        displayLink?.add(to: .current, forMode: .default)
        displayLink?.preferredFrameRateRange = CAFrameRateRange(minimum: 2, maximum: 3)
        displayLink?.isPaused = true
    }

    @objc func updateScrubber() {
        viewModel.sliderValue = player.currentTime
    }

    func prepareToPlay() {
        let url = Bundle.main.url(forResource: "Stringed Disco", withExtension: "mp3")!
        do {
            file = try AVAudioFile(forReading: url)

            engine.attach(player)
            engine.connect(player, to: engine.outputNode, format: file?.processingFormat)

            if let file = file {
                player.scheduleFile(file, at: nil, completionCallbackType: .dataPlayedBack) { _ in

                }
            }

            try engine.start()
            displayLink?.isPaused = false

        } catch {
            print(error.localizedDescription)
        }
    }

    func play() {
        do {
            try engine.start()
        } catch {
            print(error.localizedDescription)
        }

        player.play()
        displayLink?.isPaused = false
    }

    func pause() {
        player.pause()
        engine.pause()
        displayLink?.isPaused = true
    }

    func enableBackgroundPlay() {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback, mode: .default)
            try session.setActive(true)
        } catch {
            print(error.localizedDescription)
        }
    }

    func setupNowPlaying() {
        // Define Now Playing Info
        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyTitle] = "Stringed Disco"
        nowPlayingInfo[MPMediaItemPropertyArtist] = "Kevin MacLeod"

        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = viewModel.sliderValue
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = file?.duration

        // Set the metadata
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }

    func setupMediaPlayerControls() {
        //Set up player controls
        let commandCentre = MPRemoteCommandCenter.shared()

        commandCentre.playCommand.addTarget { [unowned self] event in
            play()

            return .success
        }

        commandCentre.pauseCommand.addTarget { [unowned self] event in
            pause()

            return .success
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Edit 2: When I don't pause the audio engine and just the player node and then resume the player node, there is no ui lag or anything at all. Smooth playback with no crackling. But I have to pause the audio engine to update the MPRemoteCommandCenter Playback controls so I am kinda stuck.

Edit: The delay is much much more apparent when using bluetooth headphones such as AirPods.

I have attached the entire code below. It is a very very basic app to reproduce the lag issue I am having in my bigger app. You could literally copy the entire code below into a SwiftUI Project and it will run.

I am unable to find the source of the lag that is being caused in the UI. Pressing the pause button is very smooth. When I pause and I wait for a couple of seconds (especially like 5 seconds or longer) and then press play, I could see that it takes some time for the player node to resume.

Furthermore, I could hear some crackling sounds when I connect more audio units such as reverb and pitch.

Could someone explain what's the cause and issue for the UI lag and the crackling issue?

I did profile the code below, and quite a number of micro hangs were registered. My bigger app registered much more longer hangs.

struct PlayerButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            configuration.label
                .font(.system(size: 35))
                .foregroundColor(.white)
                .padding(15)
                .background(configuration.isPressed ? .gray.opacity(0.3) : .clear)
                .clipShape(Circle())
                .scaleEffect(configuration.isPressed ? 0.8 : 1.0)
        }
    }

struct ContentView: View {
    @State private var isPlaying = false

    var body: some View {
        VStack(spacing: 50) {

            Button {
                withAnimation {
                    if isPlaying {
                        AudioManager.shared.pause()
                        isPlaying = false
                    } else {
                        AudioManager.shared.play()
                        isPlaying = true
                    }
                }
            } label: {
                if isPlaying {
                    Image(systemName: "pause.fill")
                } else {
                    Image(systemName: "play.fill")
                }
            }
            .buttonStyle(PlayerButtonStyle())

            Scrubber()
        }
        .padding()
    }
}

struct Scrubber: View {
    @EnvironmentObject var viewModel: ViewModel
    @State private var sliderValue = 0.0

    var body: some View {
        Slider(value: $sliderValue, in: 0...(AudioManager.shared.file?.duration ?? 0))
            .onReceive(viewModel.$sliderValue) { _ in
                sliderValue = viewModel.sliderValue
            }
    }
}

class ViewModel: ObservableObject {
    @Published var sliderValue = 0.0
}

extension AVAudioFile {
    //Duration
    var duration: TimeInterval {
        let sampleRateSong = Double(processingFormat.sampleRate)
        let lengthSongSeconds = Double(length) / sampleRateSong
        return lengthSongSeconds
    }
}

extension AVAudioPlayerNode {
    //Current Time
    var currentTime: TimeInterval {
        if let nodeTime = lastRenderTime, let playerTime = playerTime(forNodeTime: nodeTime) {
            return Double(playerTime.sampleTime) / outputFormat(forBus: 0).sampleRate
        }
        return 0
    }
}

class AudioManager {
    static let shared = AudioManager()

    var viewModel = ViewModel()

    let engine = AVAudioEngine()
    let player = AVAudioPlayerNode()
    let pitchNode = AVAudioUnitTimePitch()
    let reverb = AVAudioUnitReverb()

    var file: AVAudioFile?
    var displayLink: CADisplayLink?

    init() {
        setupSlider()
        prepareToPlay()
        enableBackgroundPlay()
        setupNowPlaying()
        setupMediaPlayerControls()
    }

    func setupSlider() {
        displayLink = CADisplayLink(target: self, selector: #selector(updateScrubber))
        displayLink?.add(to: .current, forMode: .default)
        displayLink?.preferredFrameRateRange = CAFrameRateRange(minimum: 2, maximum: 3)
        displayLink?.isPaused = true
    }

    @objc func updateScrubber() {
        viewModel.sliderValue = player.currentTime
    }

    func prepareToPlay() {
        let url = Bundle.main.url(forResource: "Stringed Disco", withExtension: "mp3")!
        do {
            file = try AVAudioFile(forReading: url)

            engine.attach(player)
            engine.connect(player, to: engine.outputNode, format: file?.processingFormat)

            if let file = file {
                player.scheduleFile(file, at: nil, completionCallbackType: .dataPlayedBack) { _ in

                }
            }

            try engine.start()
            displayLink?.isPaused = false

        } catch {
            print(error.localizedDescription)
        }
    }

    func play() {
        do {
            try engine.start()
        } catch {
            print(error.localizedDescription)
        }

        player.play()
        displayLink?.isPaused = false
    }

    func pause() {
        player.pause()
        engine.pause()
        displayLink?.isPaused = true
    }

    func enableBackgroundPlay() {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback, mode: .default)
            try session.setActive(true)
        } catch {
            print(error.localizedDescription)
        }
    }

    func setupNowPlaying() {
        // Define Now Playing Info
        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyTitle] = "Stringed Disco"
        nowPlayingInfo[MPMediaItemPropertyArtist] = "Kevin MacLeod"

        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = viewModel.sliderValue
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = file?.duration

        // Set the metadata
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }

    func setupMediaPlayerControls() {
        //Set up player controls
        let commandCentre = MPRemoteCommandCenter.shared()

        commandCentre.playCommand.addTarget { [unowned self] event in
            play()

            return .success
        }

        commandCentre.pauseCommand.addTarget { [unowned self] event in
            pause()

            return .success
        }
    }
}


问:
Saving matplotlib figure from tkinter application without using pyplot
I am using multiple matplotlib figures to visualize data in a tkinter application and so far that has been going great by using the explicit interface, i.e. by working on the axis objects.

Now I would like to save some figures to files. For this I can only find the pyplot function plt.savefig which is using the pyplot interface. Hence, since I have multiple figures I need to run

```<code>plt.figure(somefig)
</code>```

to choose the figure I'd like to save. Unfortunately, this breaks in my usecase since I'm using FigureCanvasTkAgg to get the canvas for tkinter. As discribed in this bugreport, that call ruins the figure mangager so the call plt.figure(somefig) results in the error

```<code>ValueError: The passed figure is not managed by pyplot
</code>```

So I guess my question is: Is there a way to save a figure witout using the implicit pyplot module?

Body:
I am using multiple matplotlib figures to visualize data in a tkinter application and so far that has been going great by using the explicit interface, i.e. by working on the axis objects.

Now I would like to save some figures to files. For this I can only find the pyplot function plt.savefig which is using the pyplot interface. Hence, since I have multiple figures I need to run

plt.figure(somefig)

to choose the figure I'd like to save. Unfortunately, this breaks in my usecase since I'm using FigureCanvasTkAgg to get the canvas for tkinter. As discribed in this bugreport, that call ruins the figure mangager so the call plt.figure(somefig) results in the error

ValueError: The passed figure is not managed by pyplot

So I guess my question is: Is there a way to save a figure witout using the implicit pyplot module?


问:
Use calculated field value in other field SQL server
I whould like to use the value from one field in another field of the same query

This is a fragment of my query

```<code>SELECT
    ...
    ...
    ISNULL(
        FORMAT(reg.FechaFin,'yyyy/MM/dd'),
        ISNULL(
            DATEADD(YEAR, 1, FORMAT(reg.FechaInicio,'yyyy/MM/dd')),
            ISNULL(
                DATEADD(YEAR, 2, FORMAT(reg.FechaCreacion,'yyyy/MM/dd')),
                ''
            )
        )
    ) AS "Estimated Engagement End Date",
    ...
    ...
    IIF(EEED is null, '',
            CONCAT('FY',
                IIF(IIF(
                    FORMAT(EEED,'MM')<6,
                    FORMAT(EEED,'yy'),
                    FORMAT(EEED,'yy')+1)
                        <10,
                        '0', ''),
                IIF(FORMAT(EEED,'MM')<6,
                    FORMAT(EEED,'yy'),
                    FORMAT(EEED,'yy')+1)
        )) AS "Close Date FY",
</code>```

I want to use the value obtained in "Estimated Engagement End Date" to use it below in every place where "EEED" appears.

I don't want to copy and paste the same code every time because the query would look very messy (more than already is).

Is there a way to store temporally the value for each row in the table?

Body:
I whould like to use the value from one field in another field of the same query

This is a fragment of my query

SELECT
    ...
    ...
    ISNULL(
        FORMAT(reg.FechaFin,'yyyy/MM/dd'),
        ISNULL(
            DATEADD(YEAR, 1, FORMAT(reg.FechaInicio,'yyyy/MM/dd')),
            ISNULL(
                DATEADD(YEAR, 2, FORMAT(reg.FechaCreacion,'yyyy/MM/dd')),
                ''
            )
        )
    ) AS "Estimated Engagement End Date",
    ...
    ...
    IIF(EEED is null, '',
            CONCAT('FY',
                IIF(IIF(
                    FORMAT(EEED,'MM')<6,
                    FORMAT(EEED,'yy'),
                    FORMAT(EEED,'yy')+1)
                        <10,
                        '0', ''),
                IIF(FORMAT(EEED,'MM')<6,
                    FORMAT(EEED,'yy'),
                    FORMAT(EEED,'yy')+1)
        )) AS "Close Date FY",

I want to use the value obtained in "Estimated Engagement End Date" to use it below in every place where "EEED" appears.

I don't want to copy and paste the same code every time because the query would look very messy (more than already is).

Is there a way to store temporally the value for each row in the table?


问:
how we can click on search button present on the keyboard of android mobile using UIautomator Framework
I was automation the script to search videos and I am unable to click on search button present on keyboard

I tried
device.pressEnter() and device.pressSearch()method of uiautomator


问:
Gitlab CI - ERROR: Preparation failed: adding cache volume: set volume permissions: running permission container
I have a Gitlab-Runner (version: 15.5.1) in a VM (Ubuntu  20.04.5 lts). The docker version is 22.06.0-beta.0. I'm trying to run a pipeline which use node:latest image but The following error messages occur when I run the pipeline.

The configuration (config.toml) is :

```<code>    [[runners]]
      name = "runner-web"
      url = "my url here"
      id = 8
      token = "Q_9sEzj9y2sPPJTLnGpL"
      token_obtained_at = 2022-12-01T14:09:45Z
      token_expires_at = 0001-01-01T00:00:00Z
      executor = "docker"
      [runners.custom_build_dir]
      [runners.cache]
        [runners.cache.s3]
        [runners.cache.gcs]
        [runners.cache.azure]
      [runners.docker]
        tls_verify = false
        image = "docker:latest"
        privileged = true
        disable_entrypoint_overwrite = false
        oom_kill_disable = false
        disable_cache = false
        volumes = ["/var/run/docker.sock:/var/run/docker.sock","/cache"]
        shm_size = 0
</code>```

Could it be  disk space issues ?
This is the disk space in the VM.

Body:
I have a Gitlab-Runner (version: 15.5.1) in a VM (Ubuntu  20.04.5 lts). The docker version is 22.06.0-beta.0. I'm trying to run a pipeline which use node:latest image but The following error messages occur when I run the pipeline.

The configuration (config.toml) is :

    [[runners]]
      name = "runner-web"
      url = "my url here"
      id = 8
      token = "Q_9sEzj9y2sPPJTLnGpL"
      token_obtained_at = 2022-12-01T14:09:45Z
      token_expires_at = 0001-01-01T00:00:00Z
      executor = "docker"
      [runners.custom_build_dir]
      [runners.cache]
        [runners.cache.s3]
        [runners.cache.gcs]
        [runners.cache.azure]
      [runners.docker]
        tls_verify = false
        image = "docker:latest"
        privileged = true
        disable_entrypoint_overwrite = false
        oom_kill_disable = false
        disable_cache = false
        volumes = ["/var/run/docker.sock:/var/run/docker.sock","/cache"]
        shm_size = 0

Could it be  disk space issues ?
This is the disk space in the VM.


问:
Scalable Solution using Azure Formrecognizer
I'm trying to extract table data from pdf files and for that i'm using Azure formrecognizer service.

I created a custom model and trained it (using Neural option).

Then using that trained model now i'm able to get the desired output (write data to csv) from the pdf files.

Query:

How do i scale this process end-to-end. Currently i'm using databricks notebook and azure formrecognizer sdk package to process the pdf files. Basically calling the rest api end point of trained custom model for each source pdf files.

With the above setup i can process one file at a time, how can i run the same parallely. There are lots of pdf files that i need to process (around 1k)

How often i need to train my custom model.

Please let me know what are all scalable options available with azure formrecognizer


问:
Spring How to ignore associate entity when using @ManyToMany JPA
I am facing an issue related to fetch data with associate entity JPA.

Currently, I am using FETCH.LAZY on @ManyToMany
I want to customize query as below:

```<code>**Repo**
#1
@Transactional(readOnly = true)
@Query("from User")
List<User> fetchUsers();
#2
@Transactional(readOnly = true)
@Query("from User u join fetch .userTypes")
List<User> fetchUsersWithType();
</code>```
```<code>**Entity**
@Setter
@Getter
@Entity
Class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = UserType.class)
    private Set<UserType> userTypes;

}

@Setter
@Getter
@Entity
Class UserType{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

</code>```

It's working for the second query
but it throw error failed to lazily initialize a collection for my #1 query.

If I set @JsonIgnore on level Enity it will ok and skip userTypes
but it's not what I want

#1 No need userType.

#2 Need userType

Please help advice me, how to achieved this!
THank you!

Body:
I am facing an issue related to fetch data with associate entity JPA.

Currently, I am using FETCH.LAZY on @ManyToMany
I want to customize query as below:

**Repo**
#1
@Transactional(readOnly = true)
@Query("from User")
List<User> fetchUsers();
#2
@Transactional(readOnly = true)
@Query("from User u join fetch .userTypes")
List<User> fetchUsersWithType();

**Entity**
@Setter
@Getter
@Entity
Class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = UserType.class)
    private Set<UserType> userTypes;

}

@Setter
@Getter
@Entity
Class UserType{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

It's working for the second query
but it throw error failed to lazily initialize a collection for my #1 query.

If I set @JsonIgnore on level Enity it will ok and skip userTypes
but it's not what I want

#1 No need userType.

#2 Need userType

Please help advice me, how to achieved this!
THank you!


问:
Stashed files reappearing in "unstaged" section of sourcetree (and in git status output)
In Sourcetree (3.4.10) if I stash my current folder, the files that were modified pops back again in my "unstaged" area.

this even though I havn't selected the flag "keep staged modifications".

git version is 2.37.0 on Windows10

Also if I

```<code>$ git status
Changes not staged for commit:
     modified: myfile.cpp
$ git stash
$ git status
Changes not staged for commit:
     modified: myfile.cpp
$
</code>```

I find the list of modified files that in my ideas should have been stashed

EDIT:

also p4merge (called from sourcetree) says:

0 diffs (Recognize line endings and whitespaces differences), tab spacing: 4, encoding: UTF8, No BOM

Body:
In Sourcetree (3.4.10) if I stash my current folder, the files that were modified pops back again in my "unstaged" area.

this even though I havn't selected the flag "keep staged modifications".

git version is 2.37.0 on Windows10

Also if I

$ git status
Changes not staged for commit:
     modified: myfile.cpp
$ git stash
$ git status
Changes not staged for commit:
     modified: myfile.cpp
$

I find the list of modified files that in my ideas should have been stashed

EDIT:

also p4merge (called from sourcetree) says:

0 diffs (Recognize line endings and whitespaces differences), tab spacing: 4, encoding: UTF8, No BOM


问:
Sending some tether to another wallet
Actually I am not really sure what am I doing! I am not really a crypto guy or something.
I want to send some tether from a blockchain wallet to another blockchain wallet. Is it possible? And if it is how can I do it with apis?</p>

Title: Sending some tether to another wallet


问:
angular few input setter, can i use one input value in anothet inpur setter
I have shareComponent which gets a few inputs:

```<code>     <share-preview
                [pageID]="pageID"
                [isAppPage]="isAppPage"
                [shareSelectedData]="shareSelectedData"
        ></share-preview>
</code>```

and in the component itself, I have a setter for input pageID which I want to use shareSelectedData value (input) inside this setter

I get the value of shareSelectedData , but is it safe?
it could be a situation in which shareSelectedData doesn't have been initialized at the point of time we set the pageID

Body:
I have shareComponent which gets a few inputs:

     <share-preview
                [pageID]="pageID"
                [isAppPage]="isAppPage"
                [shareSelectedData]="shareSelectedData"
        ></share-preview>

and in the component itself, I have a setter for input pageID which I want to use shareSelectedData value (input) inside this setter

I get the value of shareSelectedData , but is it safe?
it could be a situation in which shareSelectedData doesn't have been initialized at the point of time we set the pageID


问:
Web Essentials AspNetCore PWA - No matching service worker detected when published to IIS
I built an ASP .Net MVC web application using .Net 6 and Web Essentials AspNetCore PWA by madskristensen

Everything is normal in localhost Visual Studio or localhost IIS, but no matching service worker when accessed using IP IIS

Visual Studio Localhost: (https://i.stack.imgur.com/DtKYd.png)

IIS Localhost: (https://i.stack.imgur.com/wo4d4.png)

IIS with IP Address: (https://i.stack.imgur.com/Jlcjd.png)

I've googling so many time, but none of them are works for me

Any suggest what should i do?
Thanks before


问:
user cgroup.controllers systemd cgroup v2 after restart
enabled cgroup v2

grubby --update-kernel=ALL --args="systemd.unified_cgroup_hierarchy=1"

add /etc/systemd/system/user@.service.d/delegate.conf with

[Service]

Delegate=cpu io memory pids

after reboot node /sys/fs/cgroup/user.slice/user-2001.slice/cgroup.controllers is empty until im reload systemctl daemon-reload

after reload systemctl:

cat /sys/fs/cgroup/user.slice/user-2001.slice/cgroup.controllers

cpu io memory pids

How can I make the settings apply immediately after a restart without having to run systemctl daemon-reload every time?


问:
React JS responsive height and width
How can I make the height and width of a div grow and shrink with their aspect ratio while resizing the window?. I'm using tailwind css with next JS and I want to make my div responsive while resizing the window, and in doing that I need the height to shrink as well. how is that possible?

```<code><div className="relative flex -z-10 h-auto w-72 object-scale-down">
          <Image src={"/profile.webp"} fill objectFit="cover" />
        </div>
</code>```

I'm using an image as a content for the div.

Title: React JS responsive height and width

Body:
How can I make the height and width of a div grow and shrink with their aspect ratio while resizing the window?. I'm using tailwind css with next JS and I want to make my div responsive while resizing the window, and in doing that I need the height to shrink as well. how is that possible?

          <Image src={"/profile.webp"} fill objectFit="cover" />

I'm using an image as a content for the div.


问:
Tuple index out of range
Getting this error code. Can someone please tell me what should the correct range be here?

Built a python program for generating music based on user input. But whenever I am trying to run the script I keep getting tuples out of range. I have tried changing the values but to no avail. Some help on this will be appreciated.

```<code>1 frames
<ipython-input-6-b959e4fb411a> in create_training_data(data)
     36     data_shape = np.ravel(data['chroma_stft']).shape
     37     # Create an empty list to store training data
---> 38     X = np.zeros((data_shape[0], data_shape[1]))
     39     # Loop through the data and retrieve relevant info
     40     for i in range(len(data['energy'])):

IndexError: tuple index out of range
</code>```

Basically this is the full code:

```<code># importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import librosa

# Gathering user's input
# Gather the tempo, rhythm and tone of the song
tempo = int(input("What tempo would you like the song to have? (BPM)"))
rhythm = input("What rhythm would you like the song to have? (e.g. 4/4) ")
tone = input("What is the 'feel' or tone of the song? (e.g. cheerful, melancholy)")

# Defining some Helper Functions

# File_Retreival
# This function will retrieve our dataset with audio information
def file_retreival(file):
    # Using Librosa to import the audio file
    audio, sample_rate = librosa.load(file)

    # Defining various results from the audio source
    results = {
        "tempo": librosa.beat.tempo(audio, sample_rate),
        "energy": librosa.feature.rms(audio),
        "chroma_stft": librosa.feature.chroma_stft(audio),
        "spectral_contrast": librosa.feature.spectral_contrast(audio),
        "tonnetz": librosa.feature.tonnetz(y=librosa.effects.harmonic(audio))
    }
    return results

# Create Training Data
# This function will prepare our data for training
def create_training_data(data):
    # Retrieve the silhouette information
    data_shape = np.ravel(data['chroma_stft']).shape
    # Create an empty list to store training data
    X = np.zeros((data_shape[0], data_shape[1]))
    # Loop through the data and retrieve relevant info
    for i in range(len(data['energy'])):
        X[i][0] = data['energy'][i]
        X[i][1] = data['chroma_stft'][i]
        X[i][2] = data['spectral_contrast'][i]
        X[i][3] = data['tonnetz'][i]
        X[i][4] = data['tempo']
    return X

# Build Model
# This function will build our ML model
def build_model(X_train, y_train):
    from sklearn.ensemble import RandomForestClassifier
    # Create the model
    model = RandomForestClassifier(n_estimators=100)
    # Train the model using X_train and y_train
    model.fit(X_train, y_train)
    # Return the model
    return model

# Generate Music
# This function will generate the music using ML
def generate_music(model, X):
    # Generate predictions using X
    pred = model.predict(X)
    # Return the predictions
    return pred

# Create Music
# This function will create the music according to the tempo and user-given parameters
def create_music(pred, sample_rate, tempo, rhythm, tone):
    # Import necessary libraries
    from mido import Message, MidiFile
    from mido.midifiles import MidiTrack
    from mido.messages import note_on, note_off
    # Create a new MIDI file
    mid = MidiFile()
    # Create a track
    track = MidiTrack()
    mid.tracks.append(track)
    # Set the tempo
    track.append(Message("set_tempo", tempo=tempo))
    # Set the time signature
    track.append(Message("time_signature", numerator=rhythm))
    # Iterate through the predictions and create the notes
    for i in range(len(pred)):
        duration = pred[i][0]
        # Note on message
        track.append(Message("note_on", note=pred[i][1], velocity=127, time=0))
        # Note off message
        track.append(Message("note_off", note=pred[i][1], velocity=127, time=duration))
    # Set the tone according to the user given parameters
    track.append(Message("control_change", data=[2,tone]))
    # Save the MIDI file
    mid.save("generated_music.mid")

# Main function
# This function will execute the program and generate the music
def main():
    # Gather the file and retrieve the data
    file = "audio.mp3"
    data = file_retreival(file)
    # Create the training data
    X_train = create_training_data(data)
    # Create the labels (in this case, empty labels as we just want to generate music)
    y_train = np.zeros(X_train.shape[0])
    # Build the model
    model = build_model(X_train, y_train)
    # Generate the music predictions
    music_pred = generate_music(model, X_train)
    # Create the music
    create_music(music_pred, data['sample_rate'], tempo, rhythm, tone)

# Execute the main function
main()
</code>```

Getting TypeError: 'numpy.float64' object does not support item assignment after fixing the previous issue. ---> 41         X[i][0] = data['energy'][i] error occurs here.

Title: Tuple index out of range

Body:
Getting this error code. Can someone please tell me what should the correct range be here?

Built a python program for generating music based on user input. But whenever I am trying to run the script I keep getting tuples out of range. I have tried changing the values but to no avail. Some help on this will be appreciated.

1 frames
<ipython-input-6-b959e4fb411a> in create_training_data(data)
     36     data_shape = np.ravel(data['chroma_stft']).shape
     37     # Create an empty list to store training data
---> 38     X = np.zeros((data_shape[0], data_shape[1]))
     39     # Loop through the data and retrieve relevant info
     40     for i in range(len(data['energy'])):

IndexError: tuple index out of range

Basically this is the full code:

# importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import librosa

# Gathering user's input
# Gather the tempo, rhythm and tone of the song
tempo = int(input("What tempo would you like the song to have? (BPM)"))
rhythm = input("What rhythm would you like the song to have? (e.g. 4/4) ")
tone = input("What is the 'feel' or tone of the song? (e.g. cheerful, melancholy)")

# Defining some Helper Functions

# File_Retreival
# This function will retrieve our dataset with audio information
def file_retreival(file):
    # Using Librosa to import the audio file
    audio, sample_rate = librosa.load(file)

    # Defining various results from the audio source
    results = {
        "tempo": librosa.beat.tempo(audio, sample_rate),
        "energy": librosa.feature.rms(audio),
        "chroma_stft": librosa.feature.chroma_stft(audio),
        "spectral_contrast": librosa.feature.spectral_contrast(audio),
        "tonnetz": librosa.feature.tonnetz(y=librosa.effects.harmonic(audio))
    }
    return results

# Create Training Data
# This function will prepare our data for training
def create_training_data(data):
    # Retrieve the silhouette information
    data_shape = np.ravel(data['chroma_stft']).shape
    # Create an empty list to store training data
    X = np.zeros((data_shape[0], data_shape[1]))
    # Loop through the data and retrieve relevant info
    for i in range(len(data['energy'])):
        X[i][0] = data['energy'][i]
        X[i][1] = data['chroma_stft'][i]
        X[i][2] = data['spectral_contrast'][i]
        X[i][3] = data['tonnetz'][i]
        X[i][4] = data['tempo']
    return X

# Build Model
# This function will build our ML model
def build_model(X_train, y_train):
    from sklearn.ensemble import RandomForestClassifier
    # Create the model
    model = RandomForestClassifier(n_estimators=100)
    # Train the model using X_train and y_train
    model.fit(X_train, y_train)
    # Return the model
    return model

# Generate Music
# This function will generate the music using ML
def generate_music(model, X):
    # Generate predictions using X
    pred = model.predict(X)
    # Return the predictions
    return pred

# Create Music
# This function will create the music according to the tempo and user-given parameters
def create_music(pred, sample_rate, tempo, rhythm, tone):
    # Import necessary libraries
    from mido import Message, MidiFile
    from mido.midifiles import MidiTrack
    from mido.messages import note_on, note_off
    # Create a new MIDI file
    mid = MidiFile()
    # Create a track
    track = MidiTrack()
    mid.tracks.append(track)
    # Set the tempo
    track.append(Message("set_tempo", tempo=tempo))
    # Set the time signature
    track.append(Message("time_signature", numerator=rhythm))
    # Iterate through the predictions and create the notes
    for i in range(len(pred)):
        duration = pred[i][0]
        # Note on message
        track.append(Message("note_on", note=pred[i][1], velocity=127, time=0))
        # Note off message
        track.append(Message("note_off", note=pred[i][1], velocity=127, time=duration))
    # Set the tone according to the user given parameters
    track.append(Message("control_change", data=[2,tone]))
    # Save the MIDI file
    mid.save("generated_music.mid")

# Main function
# This function will execute the program and generate the music
def main():
    # Gather the file and retrieve the data
    file = "audio.mp3"
    data = file_retreival(file)
    # Create the training data
    X_train = create_training_data(data)
    # Create the labels (in this case, empty labels as we just want to generate music)
    y_train = np.zeros(X_train.shape[0])
    # Build the model
    model = build_model(X_train, y_train)
    # Generate the music predictions
    music_pred = generate_music(model, X_train)
    # Create the music
    create_music(music_pred, data['sample_rate'], tempo, rhythm, tone)

# Execute the main function
main()

Getting TypeError: 'numpy.float64' object does not support item assignment after fixing the previous issue. ---> 41         X[i][0] = data['energy'][i] error occurs here.


问:
Writing program output to web page and keeping server and program in different files
I'm writing web frontend for my go program that represents user input as ascii art characters. Something like this.

It makes sense for me to keep server and program that converts user input to ascii art representation in different .go files. I want to call my program from server.go, after I've taken FormValues from user. How can I accomplish this? I've already spent considerable time doing my research and cannot really find anything about it. I'm certain that this is possible.

Also how should I go about displaying my program output at webpage I've created? At the moment my program will store output inside []string and uses for loop to print out lines. It's easy for me to change output data type if that is required. Just looking for some insight to accomplish this in a smart way and not use something like fmt.Fprint() to display result.

Hope that my questions are clear and understandable. I've only been learning programming for weeks and feel like I'm missing an link from a chain at the moment.


问:
Can't receive data from recvfrom() function?
Hello I would like to try to retrieve data from a source that sends data via UDP protocol with an address and a port. So, I have taken a program in C to retrieve data via port 3000 but I am not retrieving any data as the program is stuck on the recvfrom() function.

So, I checked if the source is sending data via the resource monitor. So, it does send data (send 400B/s). I also have no error when connecting to the corresponding port.

Here is the c code below:

```<code>#include <winsock2.h> // pour les fonctions socket
#include <cstdio> // Pour les Sprintf

#pragma comment(lib,"ws2_32.lib")

WSADATA initialisation_win32;
int erreur;
int tempo;
int nombre_de_caractere;
char buffer[65535];
SOCKET id_de_la_socket;
SOCKADDR_IN information_sur_la_source;

int main (int argc, char* argv[])
    {
    printf("\nEcoute du port 3000\n");

    erreur=WSAStartup(MAKEWORD(2,2),&initialisation_win32);
    if (erreur!=0)
        printf("\nDesole, je ne peux pas initialiser Winsock du a l'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nWSAStartup  : OK");

    id_de_la_socket=socket(AF_INET,SOCK_DGRAM,0);
    if (id_de_la_socket==INVALID_SOCKET)
        printf("\nDesole, je ne peux pas creer la socket du a l'erreur : %d",WSAGetLastError());
    else
        printf("\nsocket      : OK");

    information_sur_la_source.sin_family=AF_INET;
    information_sur_la_source.sin_addr.s_addr=INADDR_ANY;
    information_sur_la_source.sin_port=htons(3000); // Ecoute sur le port 3000
    erreur=bind(id_de_la_socket,(struct sockaddr*)&information_sur_la_source,sizeof(information_sur_la_source));
    if (erreur!=0)
        printf("\nDesole, je ne peux pas ecouter ce port, code d'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nbind        : OK");

    tempo=sizeof(information_sur_la_source);
    printf("\nbefore recvfrom");
    nombre_de_caractere=recvfrom(id_de_la_socket,buffer,1024,0,(struct sockaddr*)&information_sur_la_source,&tempo);
    printf("\nafter recvfrom");
    buffer[nombre_de_caractere]=0;
    printf("\nVoici les donnees : %s",buffer);

    erreur=closesocket(id_de_la_socket);
    if (erreur!=0)
        printf("\nDesole, je ne peux pas liberer la socket du a l'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nclosesocket : OK");

    erreur=WSACleanup();
    if (erreur!=0)
        printf("\nDesole, je ne peux pas liberer winsock du a l'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nWSACleanup  : OK");
    }
</code>```

Regards,

Body:
Hello I would like to try to retrieve data from a source that sends data via UDP protocol with an address and a port. So, I have taken a program in C to retrieve data via port 3000 but I am not retrieving any data as the program is stuck on the recvfrom() function.

So, I checked if the source is sending data via the resource monitor. So, it does send data (send 400B/s). I also have no error when connecting to the corresponding port.

Here is the c code below:

#include <winsock2.h> // pour les fonctions socket
#include <cstdio> // Pour les Sprintf

#pragma comment(lib,"ws2_32.lib")

WSADATA initialisation_win32;
int erreur;
int tempo;
int nombre_de_caractere;
char buffer[65535];
SOCKET id_de_la_socket;
SOCKADDR_IN information_sur_la_source;

int main (int argc, char* argv[])
    {
    printf("\nEcoute du port 3000\n");

    erreur=WSAStartup(MAKEWORD(2,2),&initialisation_win32);
    if (erreur!=0)
        printf("\nDesole, je ne peux pas initialiser Winsock du a l'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nWSAStartup  : OK");

    id_de_la_socket=socket(AF_INET,SOCK_DGRAM,0);
    if (id_de_la_socket==INVALID_SOCKET)
        printf("\nDesole, je ne peux pas creer la socket du a l'erreur : %d",WSAGetLastError());
    else
        printf("\nsocket      : OK");

    information_sur_la_source.sin_family=AF_INET;
    information_sur_la_source.sin_addr.s_addr=INADDR_ANY;
    information_sur_la_source.sin_port=htons(3000); // Ecoute sur le port 3000
    erreur=bind(id_de_la_socket,(struct sockaddr*)&information_sur_la_source,sizeof(information_sur_la_source));
    if (erreur!=0)
        printf("\nDesole, je ne peux pas ecouter ce port, code d'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nbind        : OK");

    tempo=sizeof(information_sur_la_source);
    printf("\nbefore recvfrom");
    nombre_de_caractere=recvfrom(id_de_la_socket,buffer,1024,0,(struct sockaddr*)&information_sur_la_source,&tempo);
    printf("\nafter recvfrom");
    buffer[nombre_de_caractere]=0;
    printf("\nVoici les donnees : %s",buffer);

    erreur=closesocket(id_de_la_socket);
    if (erreur!=0)
        printf("\nDesole, je ne peux pas liberer la socket du a l'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nclosesocket : OK");

    erreur=WSACleanup();
    if (erreur!=0)
        printf("\nDesole, je ne peux pas liberer winsock du a l'erreur : %d %d",erreur,WSAGetLastError());
    else
        printf("\nWSACleanup  : OK");
    }

Regards,


问:
Image with rotatex is blank on safari and iphone until clicked
i have a filpbook that works well for me. I'm using chrome on pc. Here is the codes:

https://jsfiddle.net/b7meLj1x/

CSS:

```<code>.zone11{
   height: 700px;
    display: flex;
    align-items: center;
    justify-content: center;
    perspective: 1000px;
}
.book11{
    display: flex;
    align-items: center;
    cursor: pointer;
}
.flipbook-open .cover11{
    transform: rotateX(10deg) rotateY(-180deg);
}
.flipbook-open .page11{
    transform: rotateX(10deg) rotateY(-180deg);
    z-index: 2;
}
.cover11{
    z-index: 1;
    transition: all 3.5s;
}
.back-cover11{
    z-index: -3;
}
.cover11, .back-cover11{
   height: 400px;
    width: 320px;
    background: #3f0035;
     border-radius: 2px 20px 20px 2px;
    position: absolute;
    box-shadow: 1px 1px 10px gray;
    transform: rotateX(10deg);
    transform-origin: center left;
    backface-visibility: hidden;
}
.page11{
   height: 380px;
    width: 310px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -1;
}
.last-page11{
   height: 380px;
    width: 310px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -2;
}
.page11:nth-child(2){
    transition-duration: 3s;
}
.page11:nth-child(3){
    transition-duration: 2.6s;
}
.page11:nth-child(4){
    transition-duration: 2.2s;
}
.page11:nth-child(5){
    transition-duration: 1.8s;
}
.page11:nth-child(6){
    transition-duration: 1.4s;
}
.flipbook-open .page11:nth-child(2){
    transition-duration: 6s;
}
.flipbook-open .page11:nth-child(3){
    transition-duration: 5.6s;
}
.flipbook-open .page11:nth-child(4){
    transition-duration: 5.2s;
}
.flipbook-open .page11:nth-child(5){
    transition-duration: 4.8s;
}
.flipbook-open .page11:nth-child(6){
    transition-duration: 4.4s;
}
.last-page11 img{
    height: 360px;
    display: block;
    margin: 10px auto;
    position: relative;
    z-index: -2;
}
.cover11 img{
    height: 380px;
    display: block;
    position: relative;
    margin: 10px auto;
    z-index: -1;

}
</code>```

HTML and JAVACRIPT:

```<code><div class="zone11">
    <div class="book11">
        <div class="cover11"><img alt="" src="cover.jpg"></div>
        <div class="page11"></div>
        <div class="page11"></div>
        <div class="page11"></div>
        <div class="page11"></div>
        <div class="page11"></div>
        <div class="last-page11"><img src="page.jpg" alt=""></div>
        <div class="back-cover11"></div>
    </div>
    </div>

<script type="text/javascript">
document.querySelector('.book11').addEventListener('click', function() {
document.querySelector('.zone11').classList.toggle('flipbook-open');
});
</script>
</code>```

If i open it with safari or with iphone (even with chrome) the cover image of the flipbook is white. When i click it to open the flipbook becomes visible. When i close the book it turn white again.

I notice that the problem is for the rotatex. Removing all the rotatex i can see all the images but i lose the animation that i wanted.

Thanks if someone wants to help me.

Body:
i have a filpbook that works well for me. I'm using chrome on pc. Here is the codes:

https://jsfiddle.net/b7meLj1x/

CSS:

.zone11{
   height: 700px;
    display: flex;
    align-items: center;
    justify-content: center;
    perspective: 1000px;
}
.book11{
    display: flex;
    align-items: center;
    cursor: pointer;
}
.flipbook-open .cover11{
    transform: rotateX(10deg) rotateY(-180deg);
}
.flipbook-open .page11{
    transform: rotateX(10deg) rotateY(-180deg);
    z-index: 2;
}
.cover11{
    z-index: 1;
    transition: all 3.5s;
}
.back-cover11{
    z-index: -3;
}
.cover11, .back-cover11{
   height: 400px;
    width: 320px;
    background: #3f0035;
     border-radius: 2px 20px 20px 2px;
    position: absolute;
    box-shadow: 1px 1px 10px gray;
    transform: rotateX(10deg);
    transform-origin: center left;
    backface-visibility: hidden;
}
.page11{
   height: 380px;
    width: 310px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -1;
}
.last-page11{
   height: 380px;
    width: 310px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -2;
}
.page11:nth-child(2){
    transition-duration: 3s;
}
.page11:nth-child(3){
    transition-duration: 2.6s;
}
.page11:nth-child(4){
    transition-duration: 2.2s;
}
.page11:nth-child(5){
    transition-duration: 1.8s;
}
.page11:nth-child(6){
    transition-duration: 1.4s;
}
.flipbook-open .page11:nth-child(2){
    transition-duration: 6s;
}
.flipbook-open .page11:nth-child(3){
    transition-duration: 5.6s;
}
.flipbook-open .page11:nth-child(4){
    transition-duration: 5.2s;
}
.flipbook-open .page11:nth-child(5){
    transition-duration: 4.8s;
}
.flipbook-open .page11:nth-child(6){
    transition-duration: 4.4s;
}
.last-page11 img{
    height: 360px;
    display: block;
    margin: 10px auto;
    position: relative;
    z-index: -2;
}
.cover11 img{
    height: 380px;
    display: block;
    position: relative;
    margin: 10px auto;
    z-index: -1;

}

HTML and JAVACRIPT:

If i open it with safari or with iphone (even with chrome) the cover image of the flipbook is white. When i click it to open the flipbook becomes visible. When i close the book it turn white again.

I notice that the problem is for the rotatex. Removing all the rotatex i can see all the images but i lose the animation that i wanted.

Thanks if someone wants to help me.


问:
Telegram bot auto message
My English is a bit bad, I'll write as best I can. I am writing a telegram bot that will periodically send notifications by user_id, when you start the cycle of checking for new data in the request and sending it to the user, the whole code freezes and does not allow the user to complete more requests. I'm running a function through a thread, but I'm getting an error. Please help me to solve

```<code>bot.py

import requests
import json
import telebot
import buttonbot
import time
from telebot import types
from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher.filters import Text
import service
import threading
import bottoken

bot = Bot(token=bottoken)

notext = 'notext'

dp = Dispatcher(bot)

@dp.message_handler(commands=['help'])
async def online(message: types.Message):
    await bot.send_message(message.from_user.id, f"ваш id: {message.from_user.id}")
    user_id = message.from_user.id
    await threading.Thread(target=service.run(user_id), daemon=True, name=None).start()

</code>```
```<code>service.py

import requests
import json
import time
import threading
from data import data
from headers import headers
from aiogram import executor
import sched, time

notext = 'notext'

rt = ''

method = f"https://api.telegram.org/bot{rt}/sendMessage"

async def get_updates(file_count=0):
    url = ""
    url4 = ""
    session = requests.Session()
    session.headers.update(headers)
    response =  session.post(url, data=data)
    result = session.get(url4, data=data).json()
    return result['rows']

async def run(user_id):
    url = ""
    url2 = ""
    url3 = ""
    url4 = ""
    session = requests.Session()
    session.headers.update(headers)
    response =  session.post(url, data=data)
    update_id = get_updates()[-1]['id']
    for _ in range(5):
       messages = get_updates(update_id)
        for message in messages:
            if update_id < message['id']:
                update_id = message['id']
                card = (f"New: {message['number']}")
                r = requests.post(method, data={
                    "chat_id": user_id,
                    "text": card
                    })
                time.sleep(60)

</code>```

On startup, the console reports that the thread has started, but it will not send anything to the user

```<code>Exception in thread Thread-2:
Task exception was never retrieved
future: <Task finished name='Task-14' coro=<Dispatcher._process_polling_updates() done, defined at /usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py:407> exception=TypeError("object NoneType can't be used in 'await' expression")>
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/root/home/vtk/./botvtk.py", line 34, in online
    await threading.Thread(target=service.run(user_id), daemon=True, name=None).start()
TypeError: object NoneType can't be used in 'await' expression
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
TypeError: 'coroutine' object is not callable

</code>```

Title: Telegram bot auto message

Body:
My English is a bit bad, I'll write as best I can. I am writing a telegram bot that will periodically send notifications by user_id, when you start the cycle of checking for new data in the request and sending it to the user, the whole code freezes and does not allow the user to complete more requests. I'm running a function through a thread, but I'm getting an error. Please help me to solve

bot.py

import requests
import json
import telebot
import buttonbot
import time
from telebot import types
from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher.filters import Text
import service
import threading
import bottoken

bot = Bot(token=bottoken)

notext = 'notext'

dp = Dispatcher(bot)

@dp.message_handler(commands=['help'])
async def online(message: types.Message):
    await bot.send_message(message.from_user.id, f"ваш id: {message.from_user.id}")
    user_id = message.from_user.id
    await threading.Thread(target=service.run(user_id), daemon=True, name=None).start()

service.py

import requests
import json
import time
import threading
from data import data
from headers import headers
from aiogram import executor
import sched, time

notext = 'notext'

rt = ''

method = f"https://api.telegram.org/bot{rt}/sendMessage"

async def get_updates(file_count=0):
    url = ""
    url4 = ""
    session = requests.Session()
    session.headers.update(headers)
    response =  session.post(url, data=data)
    result = session.get(url4, data=data).json()
    return result['rows']

async def run(user_id):
    url = ""
    url2 = ""
    url3 = ""
    url4 = ""
    session = requests.Session()
    session.headers.update(headers)
    response =  session.post(url, data=data)
    update_id = get_updates()[-1]['id']
    for _ in range(5):
       messages = get_updates(update_id)
        for message in messages:
            if update_id < message['id']:
                update_id = message['id']
                card = (f"New: {message['number']}")
                r = requests.post(method, data={
                    "chat_id": user_id,
                    "text": card
                    })
                time.sleep(60)

On startup, the console reports that the thread has started, but it will not send anything to the user

Exception in thread Thread-2:
Task exception was never retrieved
future: <Task finished name='Task-14' coro=<Dispatcher._process_polling_updates() done, defined at /usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py:407> exception=TypeError("object NoneType can't be used in 'await' expression")>
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "/usr/local/lib/python3.9/dist-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/root/home/vtk/./botvtk.py", line 34, in online
    await threading.Thread(target=service.run(user_id), daemon=True, name=None).start()
TypeError: object NoneType can't be used in 'await' expression
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
TypeError: 'coroutine' object is not callable


问:
how to recognize some special sound
how to compare the mic stream data with wave file data to get if it's mixed in the stream data

I'm using pyaudio and fft to get audio frequency data frames, are there any libraries for audio recognition? I do not need speech detection, just detections of some sound saved in files?

Title: how to recognize some special sound


问:
Ugly shading in Xbim
I'm developing a software that can display 3D IFC building models. I'm using Xbim, and Helix toolkit for that.
I managed to display the geometry correctly, but there is something off with the shading as far as I can tell.

Can I alter the calculation of shading either during Xbim triangulation, or in Helix toolkit? The goal is to have sharp edges, and remove the ugly shading lines from the flat surfaces which appear on the border between 2 triangles in the mesh.

I already did some research, and what I found out, that shading calculation may be based around the vertices: If they are shared by 2 polygons, the shading will be smooth, and if you have 2 vertices in the same place, each belonging to a separate polygon, there will be a hard edge. Is this theory correct?

EDIT: I think this may be more related to Xbim, and not to helix toolkit. So The question is, how to tell Xbim, that you want sharp edges, like the ones you get in Xbim.WindowsUI?

Title: Ugly shading in Xbim


问:
Running out of RAM in Google Colab
I run the following code in Colab. my array is not too long. when I run this, after 50000 iteration, it goes out of RAM. Could you please help? the lenght of the data is limited. The RAM starts to go up and finally reach to its max limit.
`

```<code>import numpy as np

datamigrantsentiment = np.empty(len(data), dtype=int)
for i in range(0,len(data)):
  if i%1000 ==0 :
    print(i)
    !rm -rf model
    model = build_model(base_layers.PREDICT)
    model.load_weights(path+'goemotions/model_checkpoint')
  if datamigrantslistnort[i]:
    results = model.predict(x=[data[i]],verbose=0)
    #print('')
    #print('{}:'.format(text))
    labels = np.flip(np.argsort(results[0]))
    label = LABELS[labels[0]]
    label = SENTIMENT_MAP[label]
    #print('{}: {}'.format(label, results[0][labels[0]]))
    datasentiment[i]=label

</code>```

`

Whats the problem with the code?

Title: Running out of RAM in Google Colab

Body:
I run the following code in Colab. my array is not too long. when I run this, after 50000 iteration, it goes out of RAM. Could you please help? the lenght of the data is limited. The RAM starts to go up and finally reach to its max limit.
`

import numpy as np

datamigrantsentiment = np.empty(len(data), dtype=int)
for i in range(0,len(data)):
  if i%1000 ==0 :
    print(i)
    !rm -rf model
    model = build_model(base_layers.PREDICT)
    model.load_weights(path+'goemotions/model_checkpoint')
  if datamigrantslistnort[i]:
    results = model.predict(x=[data[i]],verbose=0)
    #print('')
    #print('{}:'.format(text))
    labels = np.flip(np.argsort(results[0]))
    label = LABELS[labels[0]]
    label = SENTIMENT_MAP[label]
    #print('{}: {}'.format(label, results[0][labels[0]]))
    datasentiment[i]=label

`

Whats the problem with the code?


问:
Best practice: DRY Typescript + Mongoose schema + JOI validation
I am building a web application with NodeJS/ExpressJS in the backend (as REST api) and React in the frontend.

This is more a general question than a specific one: What is the best practice to don't repeat myself when it comes to describing the properties of a model? I have them in three redundant places in the backend alone:

Typescript interface

```<code>interface ICat extends Document {
  name: string;
  age: number;
}
</code>```

Mongoose schema

```<code>type CatModel = mongoose.Model<ICat>;

const catSchema = new mongoose.Schema<ICat, CatModel>({
  name: {
    type: String,
    trim: true,
    required: true,
  },
  age: {
    type: Number,
    required: true,
  },
});

const Cat = mongoose.model<ICat, CatModel>("Cat", catSchema);
</code>```

Joi validation

```<code>const validateCat = (catData: { [key: string]: any }) => {
  const schema = Joi.object({
    name: Joi.string().required(),
    age: Joi.number().required(),
  });

  return schema.validate(catData);
};
</code>```

If I want to let the frontend know about the properties of a model and ensure proper validation before sending to the server I'd need to provide a Typescript interface and Joi validation there, too.

That example above is not DRY how I understand it. And yes, I'd like to validate data from client side before it even gets somewhere near the database.

So, what's the best practice to keep the code lean and clean?

Thanks a lot!

Body:
I am building a web application with NodeJS/ExpressJS in the backend (as REST api) and React in the frontend.

This is more a general question than a specific one: What is the best practice to don't repeat myself when it comes to describing the properties of a model? I have them in three redundant places in the backend alone:

Typescript interface

interface ICat extends Document {
  name: string;
  age: number;
}

Mongoose schema

type CatModel = mongoose.Model<ICat>;

const catSchema = new mongoose.Schema<ICat, CatModel>({
  name: {
    type: String,
    trim: true,
    required: true,
  },
  age: {
    type: Number,
    required: true,
  },
});

const Cat = mongoose.model<ICat, CatModel>("Cat", catSchema);

Joi validation

const validateCat = (catData: { [key: string]: any }) => {
  const schema = Joi.object({
    name: Joi.string().required(),
    age: Joi.number().required(),
  });

  return schema.validate(catData);
};

If I want to let the frontend know about the properties of a model and ensure proper validation before sending to the server I'd need to provide a Typescript interface and Joi validation there, too.

That example above is not DRY how I understand it. And yes, I'd like to validate data from client side before it even gets somewhere near the database.

So, what's the best practice to keep the code lean and clean?

Thanks a lot!


问:
Making a rectangle made out of a given set of rectangles sizes (get the size as closest as the given one)
I'm actually working on a ruby project and need some help.
I have these inputs :

sizeX and sizeY as an integer

rectangles, which is an array of arrays containing two integers.

I’ll take these values as example :

sizeX = 130

sizeY = 240

rectangles = [ [100,100], [100,150], [50,100], [50,50] ]

With the input i have, i need an algorithm that creates a new rectangle, made of the sizes given in rectangles, that will make a resulting size as closest as sizeX and sizeY. I’m gonna call the created rectangle size rectX and rectY.
This closest determination will be calculated like so :

abs(sizeX - rectX) + abs(sizeY - rectY)
So it returns the smallest total difference

Here are some rules of what the algorithm can and can’t do :

We can use multiple times the same rectangle

We can’t rotate a rectangle (In the case of the example, we can’t have 150x100)

We have to use the least rectangles possible

Here is an illustrated example of a result :

Here is another example if the rectangle [50,100] is not given in rectangles :

I have done some code, but it's not efficient, and is a pretty big mess :

# Returns the biggest cabinet from a given list
  def getBiggestCabinet(cabinets)
    cabinets.sort_by!{ |rect| rect.cabinetsize_w * rect.cabinetsize_h }.reverse!
    return cabinets.first
  end

  # Returns number of cabinets that fits inside a given width & height + its gap
  def getCabinetClosestMatch(width,height,cabinet)
    countX = (width / cabinet.cabinetsize_w).floor
    countY = (height / cabinet.cabinetsize_h).floor
    gapX = width - countX * cabinet.cabinetsize_w
    gapY = height - countY * cabinet.cabinetsize_h
    return countX, countY, gapX, gapY
  end

  # Only takes on cabinet at a time
  def getBestCabinetByLength(cabinets,gap,match,x_or_y)
    sorted = cabinets.sort_by!{ |cabinet|
      if x_or_y
        return cabinet.cabinetsize_w - gap
      else
        return cabinet.cabinetsize_h - gap
      end
    }

    bestLength = 0
    sorted.each do |cabinet|
      if x_or_y
        if match.modulo(cabinet.cabinetsize_h) == 0
          bestLength = cabinet.cabinetsize_h
          break;
        end
      else
        if match.modulo(cabinet.cabinetsize_w) == 0
          bestLength = cabinet.cabinetsize_w
          break;
        end
      end
    end

    return bestLength

  end

  def createCompatibleArrays(cabinets)
    # group cabinets by width or height
    cabinets_x = cabinets.group_by{ |c| c.caninetsize_w }.values
    cabinets_y = cabinets.group_by{ |c| c.caninetsize_h }.values

    return cabinets_x, cabinets_y
  end

  def getCabinetConfig(cabinets,width,height)

    biggestCabinet = getBiggestCabinet(cabinets)
    countX, countY, gapX, gapY = getCabinetClosestMatch(width,height,biggestCabinet)

    current_width = width - gapX
    current_height = height - gapY

    cabinets = cabinets.where.not(id: biggestCabinet.id)

    cabinets_gx, cabinets_gy = createCompatibleArrays(cabinets)

    cabinets_gx.each do |c|
      unless c[0].cabinetsize_h / 2 > gapY

      end
    end

  end
```


问:
check url contains pagination id
iam given with a some-url which may or may-not contains integer at last i want to check
whether integer is present and if present what is the value of it.

ex: localhost:8200/videos
localhost:8200/videos/1
localhost:8200/videos/2
localhost:8200/videos/popular-entertainment
localhost:8200/videos/popular-entertainment/1
localhost:8200/videos/popular-entertainment/2

localhost:8200/videos-funny/popular-entertainment
localhost:8200/videos-funny/popular-entertainment/1
localhost:8200/videos-funny/popular-entertainment/2
localhost:8200/videos-funny/popular-entertainment/3

i want get the pagination id at last of url if present in java

Title: check url contains pagination id


问:
How to make necessary to select at least one checkbox?
in my try where I left the codesandbox link below, I got stuck there:

I list the checkboxes with the title I sent as a prop to match the titles in the dummyArray. I send the first 2 checkboxes in Title1 selected by default and at least one of the checkboxes in Title1 must be selected. So if only one checkbox is selected in Title1, I want to disable that checkbox. But the others should remain selectable. How can I do that?

CodeSandbox Link: https://codesandbox.io/s/silly-liskov-egpq2s


问:
Keycloak OIDC Filter redirect_uri is always http
My application was developed using wicket and integrated with keycloak 10.0.2.

I have an issue with the redirect_uri, it is always in http (like https://id.dev.subok.com/auth/realms/subok/protocol/openid-connect/auth? ... &redirect_uri=http%3A%2F%2Ftest.subok.com%2F ....

To elaborate:
When I try to access my app via https://test.subok.com, I am expecting that the redirect_uri will be https%3A%2F%2Ftest.subok.com%2F but it was http%3A%2F%2Ftest.subok.com%2F. The redirect_uri is always http even if I use http or https.

The way I integrate Keycloak to my application is via servlet filter:

POM

```<code>...

<dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-servlet-filter-adapter</artifactId>
  <version>10.0.2</version>
</dependency>

<dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-authz-client</artifactId>
  <version>10.0.2</version>
</dependency>

...
</code>```

web.xml

```<code>...

<filter>
  <filter-name>keycloak</filter-name>
  <filter-class>org.keycloak.adapters.servlet.KeycloakOIDCFilter</filter-class>
  <init-param>
    <param-name>keycloak.config.skipPattern</param-name>
    <param-value>/((error-page.html)|(access-denied-page.html))</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>keycloak</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

...
</code>```

Is there a way to override the value of generated redirect_uri? Specifically to use https if the request is https and http if the request is http. Or just use https redirect_url for both http and https request?

Body:
My application was developed using wicket and integrated with keycloak 10.0.2.

I have an issue with the redirect_uri, it is always in http (like https://id.dev.subok.com/auth/realms/subok/protocol/openid-connect/auth? ... &redirect_uri=http%3A%2F%2Ftest.subok.com%2F ....

To elaborate:
When I try to access my app via https://test.subok.com, I am expecting that the redirect_uri will be https%3A%2F%2Ftest.subok.com%2F but it was http%3A%2F%2Ftest.subok.com%2F. The redirect_uri is always http even if I use http or https.

The way I integrate Keycloak to my application is via servlet filter:

POM

...

<dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-servlet-filter-adapter</artifactId>
  <version>10.0.2</version>
</dependency>

<dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-authz-client</artifactId>
  <version>10.0.2</version>
</dependency>

...

web.xml

...

<filter>
  <filter-name>keycloak</filter-name>
  <filter-class>org.keycloak.adapters.servlet.KeycloakOIDCFilter</filter-class>
  <init-param>
    <param-name>keycloak.config.skipPattern</param-name>
    <param-value>/((error-page.html)|(access-denied-page.html))</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>keycloak</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

...

Is there a way to override the value of generated redirect_uri? Specifically to use https if the request is https and http if the request is http. Or just use https redirect_url for both http and https request?


问:
How to find the uncommon rows between two Pyspark DataFrames?
I have 2 pyspark dataframes each containing 1 column. I want to find the uncommon elements between these 2 dataframes and put them in a seperate dataframe.

Kindly help.


问:
Nginx redirection based on query parameter
I want to redirect the URL to absolute URL on top of existing rule.

Suppose I have a existing rule as below

rewrite ^/xyz/(.*) /new-url redirect; this is working fine

I want a new url with a query param on top of it and that supports specific condition . I would want above URL also to work

/xyz/?infoid=color  to be redirect to www.abcde.com

I tried this by adding the rule above the existing one as per order rule but didn't work.

```<code>rewrite ^/xyz/?infoid=color$  www.abcde.com redirect;
</code>```

Is there any solution for this in nginx?

Body:
I want to redirect the URL to absolute URL on top of existing rule.

Suppose I have a existing rule as below

rewrite ^/xyz/(.*) /new-url redirect; this is working fine

I want a new url with a query param on top of it and that supports specific condition . I would want above URL also to work

/xyz/?infoid=color  to be redirect to www.abcde.com

I tried this by adding the rule above the existing one as per order rule but didn't work.

rewrite ^/xyz/?infoid=color$  www.abcde.com redirect;

Is there any solution for this in nginx?


问:
Eloquent Model Scope added on serialization
In my Model ive a Scope like so:

```<code>protected static function booted() {

        static::addGlobalScope( new AccountScope );
    }
}
</code>```

The scope itsself just checks if the Contact belongs to the Account:

```<code> public function apply(Builder $builder, Model $model)

    {

        $builder->where('account_id', auth()->user()->account->id);

    }
</code>```

If i query the model using "withoutGlobalScope" everthing works fine:

```<code>  $customer = Contact::withoutGlobalScope( AccountScope::class )
                           ->without([ 'company', 'timetracks', 'customer_page' ])
                           ->where('id', $customer)
                           ->first();
</code>```

But as soon as i try to serialize the Model with "toJson()" the scope kicks in again and it throws an error on pages that dont require an logged in user.

So how can i serilaize a Model without global scopes?

Body:
In my Model ive a Scope like so:

protected static function booted() {

        static::addGlobalScope( new AccountScope );
    }
}

The scope itsself just checks if the Contact belongs to the Account:

 public function apply(Builder $builder, Model $model)

    {

        $builder->where('account_id', auth()->user()->account->id);

    }

If i query the model using "withoutGlobalScope" everthing works fine:

  $customer = Contact::withoutGlobalScope( AccountScope::class )
                           ->without([ 'company', 'timetracks', 'customer_page' ])
                           ->where('id', $customer)
                           ->first();

But as soon as i try to serialize the Model with "toJson()" the scope kicks in again and it throws an error on pages that dont require an logged in user.

So how can i serilaize a Model without global scopes?


问:
How do I Implement Code Coverage for Unit Tests in a UWP Application?

Code coverage for UWP directly is not supported. But...

... my views and domain logic are in separate projects. So I migrated my domain logic library from UWP to dotnet standard 2.0 and referenced the Microsoft.Windows.SDK.Contracts nuget.

I created a new test project in .net core 3.1 that can consume the domain logic library, run tests, and produce code coverage results. So far, so good.

The problem is, whenever I test a unit of code that contains a control like a TextBox, I get the exception

The application called an interface that was marshalled for a different thread.

I have found many posts saying to use the active window's Dispatcher to run code on the UI thread, however I do not have a UI thread, or an active window.

Is it possible to create a UWP UI thread or instantiate a View/Window?

I'm thinking I might have to start wrapping all the UI thread classes I'm consuming so I can substitute a test dummy.


问:
write a program that calculates the number of comparisons in binary insertion sorting?
I would like to know how I can write a program to calculate the number of comparison in binary insertion sorting

I tried to code the binary insertion program below, but I would like to know how I can calculate the overall comparisons made.

```<code>#include<iostream>
using namespace std;
int binarysearch (int a[], int sel, int high, int low){
int mid=(high+low)/2;
if(high<=low){
if(sel>a[high]){
return high+1;
}
else{
    return high;
}
}
else{
if(sel==a[mid]){
return mid+1;
}
else if(sel>a[mid]){
return binarysearch( a,  sel,  high,  mid+1);
}
else{
return binarysearch( a,  sel,  mid-1,  low);
}
}}
void insertionsort(int a[], int n){
for(int i=1; i<n; i++){
int j=i-1;
int sel=a[i];
int loc=binarysearch(a,sel,j,0);
while(j>=loc){
a[j+1]=a[j];
j--;
}
a[j+1]=sel;
}
}
int main(){
int a[]= {1,6,2,5,3,4};
int n=sizeof(a)/sizeof(a[0]);
insertionsort(a,n);
 cout<<"Sorted array is :";
   for (int i = 0; i < n; i++)
      cout<<a[i]<<"\t";
   return 0;
}

</code>```

Body:
I would like to know how I can write a program to calculate the number of comparison in binary insertion sorting

I tried to code the binary insertion program below, but I would like to know how I can calculate the overall comparisons made.

#include<iostream>
using namespace std;
int binarysearch (int a[], int sel, int high, int low){
int mid=(high+low)/2;
if(high<=low){
if(sel>a[high]){
return high+1;
}
else{
    return high;
}
}
else{
if(sel==a[mid]){
return mid+1;
}
else if(sel>a[mid]){
return binarysearch( a,  sel,  high,  mid+1);
}
else{
return binarysearch( a,  sel,  mid-1,  low);
}
}}
void insertionsort(int a[], int n){
for(int i=1; i<n; i++){
int j=i-1;
int sel=a[i];
int loc=binarysearch(a,sel,j,0);
while(j>=loc){
a[j+1]=a[j];
j--;
}
a[j+1]=sel;
}
}
int main(){
int a[]= {1,6,2,5,3,4};
int n=sizeof(a)/sizeof(a[0]);
insertionsort(a,n);
 cout<<"Sorted array is :";
   for (int i = 0; i < n; i++)
      cout<<a[i]<<"\t";
   return 0;
}


问:
Sqlite db won't connect
I am trying to implement a function that adds a habit to a habit tracker app that I am building. I have created a separate database.py file and a main.py file for the interface. There is a problem connecting to my database.py file from the code below:

```<code>self.name = name
        self.description = description
        self.duration = duration
        self.database = establish_connection('main.db')
        self.streak = 0
        self.start_time = date.today().strftime("%m/%d/%Y")

    def add_habit(self):
        if habit_exists(self.database, self.name) is False:
            self.database.add(self.database, self.name, self.description, self.duration, self.start_time, self.streak)
            print(f'{self.name} has been added to the database as a {self.duration} habit starting on {self.start_time}\n')

        else:
            print(f'{self.name} already exists in the database\n')
</code>```

My database file has a function for adding the habit info into my database by using the following:

```<code>def add(db, name, description, duration, start_time, streak):
    """Adds a habit to the database

    Args:
        db (sqlite3.connect): _description_
        name (str): _description_
        description (str): _description_
        duration (str): _description_
        start_time (str): _description_
        streak (int): _description_
    """
    db = establish_connection('main.db')
    cursor = db.cursor()
    cursor.execute('''INSERT INTO habits (name, description, duration, start_time, streak) VALUES (?, ?, ?, ?, ?)''', (name, description, duration, start_time, streak))
    db.commit()

</code>```

When I run my main.py file, I get the following error:

Traceback (most recent call last):
File "/home/brandon/IU International University/Object-Oriented and Functional Programing with Python/Habit Tracker/main.py", line 89, in
interface()

File "/home/brandon/IU International University/Object-Oriented and Functional Programing with Python/Habit Tracker/main.py", line 40, in interface
habit.add_habit()

File "/home/brandon/IU International University/Object-Oriented and Functional Programing with Python/Habit Tracker/habit.py", line 39, in add_habit
self.database.add(self.database, self.name, self.description, self.duration, self.start_time, self.streak)

AttributeError: 'sqlite3.Connection' object has no attribute 'add'

Where am I going wrong?

Title: Sqlite db won't connect

Body:
I am trying to implement a function that adds a habit to a habit tracker app that I am building. I have created a separate database.py file and a main.py file for the interface. There is a problem connecting to my database.py file from the code below:

self.name = name
        self.description = description
        self.duration = duration
        self.database = establish_connection('main.db')
        self.streak = 0
        self.start_time = date.today().strftime("%m/%d/%Y")

    def add_habit(self):
        if habit_exists(self.database, self.name) is False:
            self.database.add(self.database, self.name, self.description, self.duration, self.start_time, self.streak)
            print(f'{self.name} has been added to the database as a {self.duration} habit starting on {self.start_time}\n')

        else:
            print(f'{self.name} already exists in the database\n')

My database file has a function for adding the habit info into my database by using the following:

def add(db, name, description, duration, start_time, streak):
    """Adds a habit to the database

    Args:
        db (sqlite3.connect): _description_
        name (str): _description_
        description (str): _description_
        duration (str): _description_
        start_time (str): _description_
        streak (int): _description_
    """
    db = establish_connection('main.db')
    cursor = db.cursor()
    cursor.execute('''INSERT INTO habits (name, description, duration, start_time, streak) VALUES (?, ?, ?, ?, ?)''', (name, description, duration, start_time, streak))
    db.commit()

When I run my main.py file, I get the following error:

Traceback (most recent call last):
File "/home/brandon/IU International University/Object-Oriented and Functional Programing with Python/Habit Tracker/main.py", line 89, in
interface()

File "/home/brandon/IU International University/Object-Oriented and Functional Programing with Python/Habit Tracker/main.py", line 40, in interface
habit.add_habit()

File "/home/brandon/IU International University/Object-Oriented and Functional Programing with Python/Habit Tracker/habit.py", line 39, in add_habit
self.database.add(self.database, self.name, self.description, self.duration, self.start_time, self.streak)

AttributeError: 'sqlite3.Connection' object has no attribute 'add'

Where am I going wrong?


问:
Concurrent scripts pulling jobs to do from MySQL table
I'm trying to make concurrent workers pulling jobs to do from a MySQL table with:

UPDATE jobs SET assigned_to = <my_id> WHERE assigned IS NULL LIMIT 1;
SELECT * FROM jobs WHERE assigned = <my_id> // exit if empty

Every script has its unique my_id.

Those jobs deals with external resources, very slow when compared to DB access.
Jobs are inserted in such table from external.

Goals:

process in parallel;

avoid doing the same job twice;

avoid premature terminating scripts if there are jobs to do;

avoid left job assigned to workers crashed before completing the assigned job;

I'm concerned about goal n. 3.
No luck about goal n. 4. Tried to put the queries in a transaction, committed when job is finished, but it vanishes parallelism as the first query is locked until committing transactios, so other concurrent workers cannot get new jobs to do.

For example, let's start two concurrent workers, what about the following concurrent UPDATEs?
UPDATE jobs SET assigned = 1 WHERE assigned_to IS NULL LIMIT 1;
UPDATE jobs SET assigned = 2 WHERE assigned_to IS NULL LIMIT 1;

They will always "assign" two rows? Or I can have a situation where only one row is assigned to one of two scripts? The latter will lead the other worker to premature termination?

I'm not using LIMIT a,b to just work on different part of the table because:

I don't know its length;

if I choose to start just one worker, it should do all the work, but if additional workers are started at any time later, they should get jobs left to do, concretely helping in finish all jobs faster.

I'm not using any ORDER BY RAND() because I want jobs to be done in FIFO order (insertion order)


问:
Angular PWA load old asset when reopen browser
I have an web app using angular 13 and ngsw with caching features.
The problem is when I deployed a new version to production, then I refresh the page, it's updating to a latest version, but when I close the browser than reopen it, it's loading from old assets.

I've tried change the registrationStrategy to 'registerImmediately' but I doesn't changes a thing. How to solve this issue? or should I disable caching?

"@angular/core": "~13.3.11",
"@angular/service-worker": "~13.3.11",


问:
react navigation how to open darwer on stack navigator screen?
I will open darwer on FirstScreen when press open drawer button, and remove the Home menu item in the drawer, how to do that? anybody can help me solve this problem ? thank you very much! add some content here for post this question, below is the screenshot and codes:

[![First Screen][1]][1]
[![Drawer Menu][2]][2]

package.json:

```<code>{
  "dependencies": {
    "@expo/vector-icons": "^13.0.0",
    "react-native-paper": "5.0.0-rc.10",
    "react-native-screens": "~3.15.0",
    "react-native-tab-view": "^3.3.3",
    "react-native-pager-view": "5.4.24",
    "react-native-reanimated": "~2.9.1",
    "@react-navigation/drawer": "^6.5.4",
    "@react-navigation/native": "^6.0.16",
    "react-native-gesture-handler": "~2.5.0",
    "@react-navigation/bottom-tabs": "^6.4.3",
    "@react-navigation/native-stack": "^6.9.4",
    "react-native-safe-area-context": "4.3.1",
    "@react-navigation/material-top-tabs": "^6.5.0"
  }
}
</code>```

App.tsx

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { View } from 'react-native';
import { Button, Text } from 'react-native-paper';

function FirstScreen({navigation}: {navigation:any}) {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} >
            <Text>First screen</Text>
            <Button onPress={() => navigation.openDrawer()}>
        open drawer
            </Button>
            <Button onPress={() => navigation.navigate("profile")}>go to profile screen</Button>
        </View>
    );
}

function SecondScreen() {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} >
            <Text>Second screen</Text>
        </View>
    );
}

const ProfileScreen = ({navigation}: {navigation:any}) => {
    return (
        <View>
            <Text>profile screen</Text>
            <Button onPress={() => navigation.goBack()}>
        go back
            </Button>
            <Button onPress={() => navigation.openDrawer()}> open menu</Button>
        </View>
    )
}

const SettingScreen = ({navigation}: {navigation: any}) => {
    return (
        <View>
            <Text>Setting screen</Text>
            <Button onPress={() => navigation.goBack() }>go back</Button>
        </View>
    )
}

const Stak = createNativeStackNavigator();
const HomeNavigator = () => {
    return (
        <Stak.Navigator screenOptions={{ headerShown: false }} >
            <Stak.Screen name="firstScreen" component={FirstScreen}  />
            <Stak.Screen name="secondScreen" component={SecondScreen}  />
        </Stak.Navigator>
    );
}

const Tab = createBottomTabNavigator();
const TabNavigator = () => {
    return (
        <Tab.Navigator screenOptions={{headerShown: false}}>
            <Tab.Screen name="homeNavigator" component={HomeNavigator} options={{ tabBarLabel: "Home"}}/>
            <Tab.Screen name="profile" component={ProfileScreen} options={{ tabBarLabel: "Profile" }}/>
        </Tab.Navigator>
    )
}

const Drawer = createDrawerNavigator();
export default function App() {
    return (
        <LanguageProvider>
            <NavigationContainer>
        <Drawer.Navigator initialRouteName='Home' screenOptions={{ headerShown: false}}>
                    <Drawer.Screen name="Home" component={TabNavigator} />
                    <Drawer.Screen name="Setting" component={SettingScreen} />
                </Drawer.Navigator>
            </NavigationContainer>
        </LanguageProvider>
    );
}```

  [1]: https://i.stack.imgur.com/2Fk4E.jpg
  [2]: https://i.stack.imgur.com/Yv2gl.jpg
```

Body:
I will open darwer on FirstScreen when press open drawer button, and remove the Home menu item in the drawer, how to do that? anybody can help me solve this problem ? thank you very much! add some content here for post this question, below is the screenshot and codes:

[![First Screen][1]][1]
[![Drawer Menu][2]][2]

package.json:

{
  "dependencies": {
    "@expo/vector-icons": "^13.0.0",
    "react-native-paper": "5.0.0-rc.10",
    "react-native-screens": "~3.15.0",
    "react-native-tab-view": "^3.3.3",
    "react-native-pager-view": "5.4.24",
    "react-native-reanimated": "~2.9.1",
    "@react-navigation/drawer": "^6.5.4",
    "@react-navigation/native": "^6.0.16",
    "react-native-gesture-handler": "~2.5.0",
    "@react-navigation/bottom-tabs": "^6.4.3",
    "@react-navigation/native-stack": "^6.9.4",
    "react-native-safe-area-context": "4.3.1",
    "@react-navigation/material-top-tabs": "^6.5.0"
  }
}

App.tsx

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { View } from 'react-native';
import { Button, Text } from 'react-native-paper';

function FirstScreen({navigation}: {navigation:any}) {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} >
            <Text>First screen</Text>
            <Button onPress={() => navigation.openDrawer()}>
        open drawer
            </Button>
            <Button onPress={() => navigation.navigate("profile")}>go to profile screen</Button>
        </View>
    );
}

function SecondScreen() {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} >
            <Text>Second screen</Text>
        </View>
    );
}

const ProfileScreen = ({navigation}: {navigation:any}) => {
    return (
        <View>
            <Text>profile screen</Text>
            <Button onPress={() => navigation.goBack()}>
        go back
            </Button>
            <Button onPress={() => navigation.openDrawer()}> open menu</Button>
        </View>
    )
}

const SettingScreen = ({navigation}: {navigation: any}) => {
    return (
        <View>
            <Text>Setting screen</Text>
            <Button onPress={() => navigation.goBack() }>go back</Button>
        </View>
    )
}

const Stak = createNativeStackNavigator();
const HomeNavigator = () => {
    return (
        <Stak.Navigator screenOptions={{ headerShown: false }} >
            <Stak.Screen name="firstScreen" component={FirstScreen}  />
            <Stak.Screen name="secondScreen" component={SecondScreen}  />
        </Stak.Navigator>
    );
}

const Tab = createBottomTabNavigator();
const TabNavigator = () => {
    return (
        <Tab.Navigator screenOptions={{headerShown: false}}>
            <Tab.Screen name="homeNavigator" component={HomeNavigator} options={{ tabBarLabel: "Home"}}/>
            <Tab.Screen name="profile" component={ProfileScreen} options={{ tabBarLabel: "Profile" }}/>
        </Tab.Navigator>
    )
}

const Drawer = createDrawerNavigator();
export default function App() {
    return (
        <LanguageProvider>
            <NavigationContainer>
        <Drawer.Navigator initialRouteName='Home' screenOptions={{ headerShown: false}}>
                    <Drawer.Screen name="Home" component={TabNavigator} />
                    <Drawer.Screen name="Setting" component={SettingScreen} />
                </Drawer.Navigator>
            </NavigationContainer>
        </LanguageProvider>
    );
}```

  [1]: https://i.stack.imgur.com/2Fk4E.jpg
  [2]: https://i.stack.imgur.com/Yv2gl.jpg


问:
NextJS - unable to resolve public folder images from sub route
I am using Next JS (ver 12.3) with the following folder structure:

in next.config.js :

```<code>basePath = 'my-app'
</code>```

While trying to load any image, say image1.svg from sub-route route-1:

With the following img tag

```<code><img src={ 'image1.svg' }  alt='my-image'/>
</code>```

It tries to load the image from http://localhost:3000/my-app/route-1/image1.svg

And with

```<code><img src={ '/image1.svg' }  alt='my-image'/>
</code>```

it tries to load the image from http://localhost:3000/route-1/image1.svg

How is it possible to load any image while in route-1 from http://localhost:3000/my-app/image1.svg ?

Thanks in advance

Body:
I am using Next JS (ver 12.3) with the following folder structure:

in next.config.js :

basePath = 'my-app'

While trying to load any image, say image1.svg from sub-route route-1:

With the following img tag

It tries to load the image from http://localhost:3000/my-app/route-1/image1.svg

And with

it tries to load the image from http://localhost:3000/route-1/image1.svg

How is it possible to load any image while in route-1 from http://localhost:3000/my-app/image1.svg ?

Thanks in advance


问:
Python Pandas value_counts returns more than 2 counts for boolean columns
I have a data frame that is purely boolean. I have two columns IsInTime and IsGoodKine.

```<code>      IsInTime      IsGoodKine
0         True            True
1         True            True
2         True            True
3         True           False
4         True           False
5         True            True
6         True            True
7         True            True
8         True            True
9         True            True
...
</code>```

When I called df.dtypes I get "bool" for every column. However, when I call df[IsInTime].value_counts() I get a series back that does not have two entries: I get this,

```<code>True     3846372
False     172188
True           6
</code>```

Why is Pandas splitting in this instance True into two separate value counts? How can I stop this.

I have inspected the data types of the data frame and event tried casting the column as boolean. It still doesn't fix the issue. I.e.,

df["IsInTime"].astype("bool").value_counts() # Doesn't work

Edit: The below also doesn't work for a similar reason,

```<code>df.groupby(['IsGoodKine', 'IsInTime']).size()

</code>```

it returns,

```<code>        IsGoodKine         IsInTime
False        False             7633
             True            164555
True         True                 6
             False           133369
             True           3713003
dtype: int64
</code>```

Note: I cannot simply "add" the two values together because what I actually want to do is get the number of entires across the two columns with each logical combination (true, true), (true, false), (false, true) and (false, false). But when I call size() or value_counts() I am getting more than 4 logical combinations! Which can't be correct.

Body:
I have a data frame that is purely boolean. I have two columns IsInTime and IsGoodKine.

      IsInTime      IsGoodKine
0         True            True
1         True            True
2         True            True
3         True           False
4         True           False
5         True            True
6         True            True
7         True            True
8         True            True
9         True            True
...

When I called df.dtypes I get "bool" for every column. However, when I call df[IsInTime].value_counts() I get a series back that does not have two entries: I get this,

True     3846372
False     172188
True           6

Why is Pandas splitting in this instance True into two separate value counts? How can I stop this.

I have inspected the data types of the data frame and event tried casting the column as boolean. It still doesn't fix the issue. I.e.,

df["IsInTime"].astype("bool").value_counts() # Doesn't work

Edit: The below also doesn't work for a similar reason,

df.groupby(['IsGoodKine', 'IsInTime']).size()

it returns,

        IsGoodKine         IsInTime
False        False             7633
             True            164555
True         True                 6
             False           133369
             True           3713003
dtype: int64

Note: I cannot simply "add" the two values together because what I actually want to do is get the number of entires across the two columns with each logical combination (true, true), (true, false), (false, true) and (false, false). But when I call size() or value_counts() I am getting more than 4 logical combinations! Which can't be correct.


问:
pthread_mutex, PTHREAD_MUTEX_RECURSIVE and memory-barrier
In https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12 it is said that recursive mutexes need not to synchronize memory.

In my understanding, they therefore do not need to establish a memory-barrier. Should I then use a memory-barrier explicitly? Say: use asm volatile ("" ::: "memory"); ?


问:
Unable to set Cookie in php
I am facing some issue to retrive cookie after shifted the hosting, currently I am using following syntax:</p>
```<code>setcookie("CatID", $CatID, time() + 3600, "/");
</code>```
```<code>$_COOKIE["CatID"];
</code>```

Title: Unable to set Cookie in php

Body:
I am facing some issue to retrive cookie after shifted the hosting, currently I am using following syntax:

setcookie("CatID", $CatID, time() + 3600, "/");

$_COOKIE["CatID"];