问:
PHP script for front-end management of MySql tables
I'm looking for a PHP script that will allow me to easily manage 'MySql' tables. By managing I mean not their creation but the possibility of adding new records, modifying and deleting them.
It must be possible to specify for each user which tables he will have access to and with which modalities (insertion only, modification only, etc.).
For each user I will also have to specify whether he will be able to see all or some of the columns in the table and with which permissions.
Also I'll need to know who did what, a sort of global change LOG.

My idea was to have a back-end in which I specified the users and how to access the various tables/columns and a front-end for the users.
In the front-end users will be able to add/modify/delete records and data they are allowed and the ability to filter and/or sort the various records.

I know I could use some PHP frameworks or rely on CMS but I have to write a lot of code by hand and it seems hardly credible that such a product is not already available.

Does anyone know if there is something like this?

I had tried starting with PHP frameworks but implementing everything from scratch stopped me.
I expect there is already something available.

Thanks.
Davide.


来源: stackexchange

问:
multiprocessing.Pool inexplicably slow when passing around Pandas data frames
I am trying to speed up a code path that creates Pandas data frames of some 100 mega bytes.

The obvious idea is to use multiprocessing.Pool. While the actual processing is parallelized as expected, it seems as if the IPC overhead makes things way slower than not doing any multiprocessing at all.

What really puzzles me is that I can work around the problem by pickling the frames to disk and loading them back once processing is finished. I expect that passing around things in-memory should be faster than using a hard disk.

Find a script below testing the two cases and for comparison plain bytes.

Manually dumping and loading is always way faster.

Measurements

Python 3.10 on Mac OS Ventura

```<code>Pandas frame: 56.739380359998904
Bytes: 100.31256382900756
Pandas hard disk: 2.5154516759794205
</code>```

Python 3.10 on the same Mac but in a Docker container

```<code>Pandas frame: 30.639809517015237
Bytes: 17.284717564994935
Pandas hard disk: 4.386503675952554
</code>```

Test script

My POC that simply dumps the frames to disk runs in 4 seconds.

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

def creator(id_):
    # ~230 Mb in size
    return pd.DataFrame(np.ones((3000, 10000)))

def creator_bytes(id_):
    return bytearray(3000 * 10000 * 8)

def creator_pkl(id_):
    filename = f"pickled_{id_}.pkl"

    pd.DataFrame(np.ones((3000, 10000))).to_pickle(filename)

    return filename

if __name__ == "__main__":
    timestamp = time.perf_counter()

    fake_input = list(range(10))

    with multiprocessing.Pool(1) as p:
        results = p.map(creator, fake_input)

    print(f"Pandas frame: {time.perf_counter() - timestamp}")

    ###
    timestamp = time.perf_counter()

    with multiprocessing.Pool(1) as p:
        results = p.map(creator_bytes, fake_input)

    print(f"Byte array: {time.perf_counter() - timestamp}")

    ###
    timestamp = time.perf_counter()

    with multiprocessing.Pool(1) as p:
        results = p.map(creator_pkl, fake_input)

    print(f"Pandas hard disk: {time.perf_counter() - timestamp}")
</code>```

Does anyone have an explanation of the overhead?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to speed up a code path that creates Pandas data frames of some 100 mega bytes.

The obvious idea is to use multiprocessing.Pool. While the actual processing is parallelized as expected, it seems as if the IPC overhead makes things way slower than not doing any multiprocessing at all.

What really puzzles me is that I can work around the problem by pickling the frames to disk and loading them back once processing is finished. I expect that passing around things in-memory should be faster than using a hard disk.

Find a script below testing the two cases and for comparison plain bytes.

Manually dumping and loading is always way faster.

Measurements

Python 3.10 on Mac OS Ventura

Pandas frame: 56.739380359998904
Bytes: 100.31256382900756
Pandas hard disk: 2.5154516759794205

Python 3.10 on the same Mac but in a Docker container

Pandas frame: 30.639809517015237
Bytes: 17.284717564994935
Pandas hard disk: 4.386503675952554

Test script

My POC that simply dumps the frames to disk runs in 4 seconds.

import multiprocessing
import pandas as pd
import numpy as np
import time

def creator(id_):
    # ~230 Mb in size
    return pd.DataFrame(np.ones((3000, 10000)))

def creator_bytes(id_):
    return bytearray(3000 * 10000 * 8)

def creator_pkl(id_):
    filename = f"pickled_{id_}.pkl"

    pd.DataFrame(np.ones((3000, 10000))).to_pickle(filename)

    return filename

if __name__ == "__main__":
    timestamp = time.perf_counter()

    fake_input = list(range(10))

    with multiprocessing.Pool(1) as p:
        results = p.map(creator, fake_input)

    print(f"Pandas frame: {time.perf_counter() - timestamp}")

    ###
    timestamp = time.perf_counter()

    with multiprocessing.Pool(1) as p:
        results = p.map(creator_bytes, fake_input)

    print(f"Byte array: {time.perf_counter() - timestamp}")

    ###
    timestamp = time.perf_counter()

    with multiprocessing.Pool(1) as p:
        results = p.map(creator_pkl, fake_input)

    print(f"Pandas hard disk: {time.perf_counter() - timestamp}")

Does anyone have an explanation of the overhead?


问:
Rust: How to move child (commandchild) to thread to be killed on window exit
I am trying to run a streamlit server behind the scenes of a Tauri application.

The streamlit server is packaged with PyInstaller into a single binary file and works as expected when standalone.

I have a rust main.rs file that needs to run a streamlit binary using a Command (in this case its a tauri::api::process::Command using a new_sidecar).

It spawns the server, but when the app closes, my streamlit server is not disposed off.

On window exit, I want to send a kill command to kill the server instance in the child.

Here is an example of my code:

#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

use async_std::task;
use std::sync::mpsc::sync_channel;
use std::thread;
use std::time::Duration;
use tauri::api::process::{Command, CommandEvent};
use tauri::{Manager, WindowEvent};

fn main() {
    let (tx_kill, rx_kill) = sync_channel(1);
    tauri::Builder::default()
        .setup(|app| {
            println!("App Setup Start");

            let t = Command::new_sidecar("streamlit").expect("failed to create sidecar");
            let (mut rx, child) = t.spawn().expect("Failed to spawn server");

            let splashscreen_window = app.get_window("splashscreen").unwrap();
            let main_window = app.get_window("main").unwrap();

            // Listen for server port then refresh main window
            tauri::async_runtime::spawn(async move {
                while let Some(event) = rx.recv().await {
                    if let CommandEvent::Stdout(output) = event {
                        if output.contains("Network URL:") {
                            let tokens: Vec<&str> = output.split(":").collect();
                            let port = tokens.last().unwrap();
                            println!("Connect to port {}", port);
                            main_window.eval(&format!(
                                "window.location.replace('http://localhost:{}')",
                                port
                            ));
                            task::sleep(Duration::from_secs(2)).await;
                            splashscreen_window.close().unwrap();
                            main_window.show().unwrap();
                        }
                    }
                }
            });

            // Listen for kill command
            thread::spawn(move || loop {
                let event = rx_kill.recv();
                if event.unwrap() == -1 {
                    child.kill().expect("Failed to close API");
                }
            });

            Ok(())
        })
        .on_window_event(move |event| match event.event() {
            WindowEvent::Destroyed => {
                println!("Window destroyed");
                tx_kill.send(-1).expect("Failed to send close signal");
            }
            _ => {}
        })
        .run(tauri::generate_context!())
        .expect("error while running application");
}
```
<p>But I am getting an error, when I try to kill the child instance:</p>
<pre class="lang-rust prettyprint-override"><code> thread::spawn(move || loop {
                let event = rx_kill.recv();
                if event.unwrap() == -1 {
                    child.kill().expect("Failed to close API");
                }
            });
</code>```

use of moved value: `child`
move occurs because `child` has type `CommandChild`, which does not implement the `Copy` trait
```

Any ideas?

Body:
I am trying to run a streamlit server behind the scenes of a Tauri application.

The streamlit server is packaged with PyInstaller into a single binary file and works as expected when standalone.

I have a rust main.rs file that needs to run a streamlit binary using a Command (in this case its a tauri::api::process::Command using a new_sidecar).

It spawns the server, but when the app closes, my streamlit server is not disposed off.

On window exit, I want to send a kill command to kill the server instance in the child.

Here is an example of my code:

#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

use async_std::task;
use std::sync::mpsc::sync_channel;
use std::thread;
use std::time::Duration;
use tauri::api::process::{Command, CommandEvent};
use tauri::{Manager, WindowEvent};

fn main() {
    let (tx_kill, rx_kill) = sync_channel(1);
    tauri::Builder::default()
        .setup(|app| {
            println!("App Setup Start");

            let t = Command::new_sidecar("streamlit").expect("failed to create sidecar");
            let (mut rx, child) = t.spawn().expect("Failed to spawn server");

            let splashscreen_window = app.get_window("splashscreen").unwrap();
            let main_window = app.get_window("main").unwrap();

            // Listen for server port then refresh main window
            tauri::async_runtime::spawn(async move {
                while let Some(event) = rx.recv().await {
                    if let CommandEvent::Stdout(output) = event {
                        if output.contains("Network URL:") {
                            let tokens: Vec<&str> = output.split(":").collect();
                            let port = tokens.last().unwrap();
                            println!("Connect to port {}", port);
                            main_window.eval(&format!(
                                "window.location.replace('http://localhost:{}')",
                                port
                            ));
                            task::sleep(Duration::from_secs(2)).await;
                            splashscreen_window.close().unwrap();
                            main_window.show().unwrap();
                        }
                    }
                }
            });

            // Listen for kill command
            thread::spawn(move || loop {
                let event = rx_kill.recv();
                if event.unwrap() == -1 {
                    child.kill().expect("Failed to close API");
                }
            });

            Ok(())
        })
        .on_window_event(move |event| match event.event() {
            WindowEvent::Destroyed => {
                println!("Window destroyed");
                tx_kill.send(-1).expect("Failed to send close signal");
            }
            _ => {}
        })
        .run(tauri::generate_context!())
        .expect("error while running application");
}

But I am getting an error, when I try to kill the child instance:

 thread::spawn(move || loop {
                let event = rx_kill.recv();
                if event.unwrap() == -1 {
                    child.kill().expect("Failed to close API");
                }
            });

use of moved value: `child`
move occurs because `child` has type `CommandChild`, which does not implement the `Copy` trait

Any ideas?


问:
Notification sound playing on loop in iOS 16 and above
I have added the support to play a custom notification sound in my application whenever a notification of a certain type is received. The notification sound being used in this case is 9 seconds long.
Till iOS version 15 (including all the incremental release), it is being played just once, i.e. for 9 seconds if it is not intercepted by the user or by another notification (silent/normal) but for iOS 16 and above the sound it being played on loop for 30 seconds if there is no interception.

Any suggestions or ideas as to why this is happening and how can this be solved.
TIA.

It should ideally be played once only for 9 seconds if there is no interception.


问:
SOLVED: Remote mercurial server fails in changegroup.notify with an exception
Pushing changes to a remote mercurial repo is reporting an error in my changegroup.notify hook.  It worked with an old 2.7 release of mercurial, but is broken now.

My server has

```<code>Python 3.9, hg --version is
Mercurial Distributed SCM (version 6.3.1)
</code>```

The relevant repo's hgrc has

```<code>changegroup.notify = python:hgext.notify.hook
</code>```

The hook reports an exception:

```<code>>: hg --traceback push
pushing to https://[redacted]
searching for changes
remote: adding changesets
remote: adding manifests
remote: adding file changes
remote: added 1 changesets with 1 changes to 1 files
remote: error: changegroup.notify hook raised an exception: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
remote: (run with --traceback for stack trace)
</code>```

Why the exception, when I am using what is supposed to just work
out of the box?

Update: Re-ran the test pushing from an account on the same machine as the server (thanks @LazyBadger), got the following traceback:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/mercurial/hook.py", line 116, in pythonhook
    r = obj(ui=ui, repo=repo, hooktype=htype, **pycompat.strkwargs(args))
  File "/usr/local/lib/python3.9/dist-packages/hgext/notify.py", line 589, in hook
    n = notifier(ui, repo, hooktype)
  File "/usr/local/lib/python3.9/dist-packages/hgext/notify.py", line 326, in __init__
    self.stripcount = int(self.ui.config(b'notify', b'strip'))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
</code>```

Solution:
Turns out this is the error you get if you haven't updated your hgrc in years.  Used to be that adding the hook to your [.]hgrc was all that was required.  Now you have to enable notify as well, so, e.g.

```<code>[extensions]
notify=

[hooks]
changegroup.notify = python:hgext.notify.hook
</code>```

You also need some things to allow the email notication to work, for example if you have personal email support on the same server:

```<code>[reposubs]
* = [my email on the server]

[email]
from = Mercurial Notification <noreply@mydomain>

[smtp]
host = localhost
</code>```

Body:
Pushing changes to a remote mercurial repo is reporting an error in my changegroup.notify hook.  It worked with an old 2.7 release of mercurial, but is broken now.

My server has

Python 3.9, hg --version is
Mercurial Distributed SCM (version 6.3.1)

The relevant repo's hgrc has

changegroup.notify = python:hgext.notify.hook

The hook reports an exception:

>: hg --traceback push
pushing to https://[redacted]
searching for changes
remote: adding changesets
remote: adding manifests
remote: adding file changes
remote: added 1 changesets with 1 changes to 1 files
remote: error: changegroup.notify hook raised an exception: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
remote: (run with --traceback for stack trace)

Why the exception, when I am using what is supposed to just work
out of the box?

Update: Re-ran the test pushing from an account on the same machine as the server (thanks @LazyBadger), got the following traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/mercurial/hook.py", line 116, in pythonhook
    r = obj(ui=ui, repo=repo, hooktype=htype, **pycompat.strkwargs(args))
  File "/usr/local/lib/python3.9/dist-packages/hgext/notify.py", line 589, in hook
    n = notifier(ui, repo, hooktype)
  File "/usr/local/lib/python3.9/dist-packages/hgext/notify.py", line 326, in __init__
    self.stripcount = int(self.ui.config(b'notify', b'strip'))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Solution:
Turns out this is the error you get if you haven't updated your hgrc in years.  Used to be that adding the hook to your [.]hgrc was all that was required.  Now you have to enable notify as well, so, e.g.

[extensions]
notify=

[hooks]
changegroup.notify = python:hgext.notify.hook

You also need some things to allow the email notication to work, for example if you have personal email support on the same server:

[reposubs]
* = [my email on the server]

[email]
from = Mercurial Notification <noreply@mydomain>

[smtp]
host = localhost


问:
Argument of type '(data: MyContact[]) => void' is not assignable to parameter of type '(value: MyContact)
```<code>ngOnInit(): void {
    this.loading = true;
    this.cantService.getAllContacts().subscribe(
      (data: MyContact[]) => {
        this.contacts = data;
        this.loading = false;
      },
      (error) => {
        this.errorMessage = error;
        this.loading = false;
      }
    );
</code>```

Where am I going wrong?

Body:
ngOnInit(): void {
    this.loading = true;
    this.cantService.getAllContacts().subscribe(
      (data: MyContact[]) => {
        this.contacts = data;
        this.loading = false;
      },
      (error) => {
        this.errorMessage = error;
        this.loading = false;
      }
    );

Where am I going wrong?


问:
Is there a way to pack/unpack binary data from memory in R without going through a `rawConnection`?
I'm currently using this handmade thing (which should of course be adjusted for different data types):

```<code>
read_blob <- function(blob) {
  blob_con <- rawConnection(blob)
  data <- readBin(blob_con, "numeric", n = length(blob) / 4)
  close(blob_con)
  return(data)
}

write_blob <- function(data) {
  stopifnot(is.numeric(data))
  blob_con <- rawConnection(raw(0), "r+")
  writeBin(data, blob_con)
  blob <- rawConnectionValue(blob_con)
  close(blob_con)
  return(blob)
}

input_data <- c(123.45,234.56,345.67)

data_to_raw <- write_blob(input_data)
print(data_to_raw)

raw_to_data <- read_blob(data_to_raw)
print(raw_to_data)
stopifnot(all(input_data == raw_to_data))

</code>```

I consider this somewhat of a workaround, having to open a rawConnection for reading and writing. Is there really no better way of doing this?

I know of

rawToChar but no other data types,

the package pack which should work with structure descriptors in the style of unpack('d*', data). I guess it was never finished because in my case only returns the first value regardless of what I put in the pattern, and last updated in 2008.

the package blob which doesn't seem to be doing this on its own.

Body:
I'm currently using this handmade thing (which should of course be adjusted for different data types):

read_blob <- function(blob) {
  blob_con <- rawConnection(blob)
  data <- readBin(blob_con, "numeric", n = length(blob) / 4)
  close(blob_con)
  return(data)
}

write_blob <- function(data) {
  stopifnot(is.numeric(data))
  blob_con <- rawConnection(raw(0), "r+")
  writeBin(data, blob_con)
  blob <- rawConnectionValue(blob_con)
  close(blob_con)
  return(blob)
}

input_data <- c(123.45,234.56,345.67)

data_to_raw <- write_blob(input_data)
print(data_to_raw)

raw_to_data <- read_blob(data_to_raw)
print(raw_to_data)
stopifnot(all(input_data == raw_to_data))

I consider this somewhat of a workaround, having to open a rawConnection for reading and writing. Is there really no better way of doing this?

I know of

rawToChar but no other data types,

the package pack which should work with structure descriptors in the style of unpack('d*', data). I guess it was never finished because in my case only returns the first value regardless of what I put in the pattern, and last updated in 2008.

the package blob which doesn't seem to be doing this on its own.


问:
Generate clients for apis with @Hidden annotations via openapi-generator
I'm using swaggerCodegen to generate Apis clients for a Spring based application using org.openapitools.openapi-generator-cli. I marked some operations with @io.swagger.v3.oas.annotations.Hidden. Swagger codegen is not generating client stubs for these. Is there a config to hide them in the Swagger documentation, but still generate client code?


问:
I installed nodejs on WSL2, but cant call it from windows
I have installed Node 18 on Ubuntu on WSL2 in Windows 11.  (plus eslint, which is the main end goal)  When I'm in the Ubuntu terminal, everything works fine.  I can even eslint my code on the windows file system via /mnt/c/somefolder/... - cool!

When I try to call it from the Windows command prompt, I get "command not found"

```<code>C:\Windows>wsl node --version
/bin/bash: line 1: node: command not found
</code>```

Other standard linux commands work fine, e.g. wsl ls or wsl nano foo.txt work as intended (though the current directory differs)

I'm guessing it's something about a PATH to node, but my Google-fu has failed me for a solution.

EDIT, FIXED (sort of): This seems to be NVM related.  When I do a basic install of a single version of node in /usr/bin using Ubuntu apt-get (doing the tricks to get the more recent v18.2 LTS) it all works o.k.  I don't need NVM for now...

EDIT 2
I can't get the VSCode (running under windows, with the ESLint extension) to connect to the node and eslint code under WSL.  Which might just be impossible.  Is it?

Body:
I have installed Node 18 on Ubuntu on WSL2 in Windows 11.  (plus eslint, which is the main end goal)  When I'm in the Ubuntu terminal, everything works fine.  I can even eslint my code on the windows file system via /mnt/c/somefolder/... - cool!

When I try to call it from the Windows command prompt, I get "command not found"

C:\Windows>wsl node --version
/bin/bash: line 1: node: command not found

Other standard linux commands work fine, e.g. wsl ls or wsl nano foo.txt work as intended (though the current directory differs)

I'm guessing it's something about a PATH to node, but my Google-fu has failed me for a solution.

EDIT, FIXED (sort of): This seems to be NVM related.  When I do a basic install of a single version of node in /usr/bin using Ubuntu apt-get (doing the tricks to get the more recent v18.2 LTS) it all works o.k.  I don't need NVM for now...

EDIT 2
I can't get the VSCode (running under windows, with the ESLint extension) to connect to the node and eslint code under WSL.  Which might just be impossible.  Is it?


问:
I want to show a different view on a page to the user according to different notifications in a swiftui
I want to show a different view on a page to the user according to different notifications. : [Like this][1]
[1]: https://i.stack.imgur.com/vWNgP.png

I can't create function to show different views.
My model and sample data are as follows:

```<code>    enum NotificationType {
        case DuelReceived, TogetherReceived, InfoReceived, FollowReceived
    }
    let username : String
    let msg : String
    var time : Int
    var photo:String
    let type : NotificationType
}

extension Notification {
    static let sampleChat = [
        Notification(username: "steveab", msg: "he offered you a walk together", time: 20000, photo: "mangaa", type: .TogetherReceived),
        Notification(username: "benjamin", msg: "challenged you", time: 49999, photo: "mangaa", type: .DuelReceived),
        Notification(username: "robertt", msg: "started following you", time: 60000, photo: "mangaa", type: .FollowReceived),
        Notification(username: "mases", msg: "accepted the offer to walk together", time: 59999, photo: "mangaa", type: .InfoReceived)
    ]
}```

This way i prepared code for 3 different views:

 ```struct Notification {
    enum NotificationType {
        case DuelReceived, TogetherReceived, InfoReceived, FollowReceived
    }
    let username : String
    let msg : String
    var time : Int
    var photo:String
    let type : NotificationType
}

extension Notification {
    static let sampleChat = [
        Notification(username: "steveab", msg: "he offered you a walk together", time: 20000, photo: "mangaa", type: .TogetherReceived),
        Notification(username: "benjamin", msg: "challenged you", time: 49999, photo: "mangaa", type: .DuelReceived),
        Notification(username: "robertt", msg: "started following you", time: 60000, photo: "mangaa", type: .FollowReceived),
        Notification(username: "mases", msg: "accepted the offer to walk together", time: 59999, photo: "mangaa", type: .InfoReceived)
    ]
}```

I made two more views infoNotification and newFollower.
Then created a function like this but it didn't work. How can i show different views for different data. These notifications can be multiple.

 ```func getNotification() -> some View {
    let notification : [Notification] = Notification.sampleChat
    ForEach(notification){ section in
        if section.type == .TogetherReceived {
            inviteNotification(photo: section.photo, username: section.username, msg: section.msg, time:section.time)
        }
        else if section.type == .InfoReceived {
            infoNotification(photo: section.photo, username : section.username,
                             msg: section.msg , time : section.time)
        } else if  section.type == .FollowReceived {
            newFollower(photo: section.photo, username : section.username,
                        msg: section.msg , time : section.time)
        }
    }
} ```
```

Body:
I want to show a different view on a page to the user according to different notifications. : [Like this][1]
[1]: https://i.stack.imgur.com/vWNgP.png

I can't create function to show different views.
My model and sample data are as follows:

    enum NotificationType {
        case DuelReceived, TogetherReceived, InfoReceived, FollowReceived
    }
    let username : String
    let msg : String
    var time : Int
    var photo:String
    let type : NotificationType
}

extension Notification {
    static let sampleChat = [
        Notification(username: "steveab", msg: "he offered you a walk together", time: 20000, photo: "mangaa", type: .TogetherReceived),
        Notification(username: "benjamin", msg: "challenged you", time: 49999, photo: "mangaa", type: .DuelReceived),
        Notification(username: "robertt", msg: "started following you", time: 60000, photo: "mangaa", type: .FollowReceived),
        Notification(username: "mases", msg: "accepted the offer to walk together", time: 59999, photo: "mangaa", type: .InfoReceived)
    ]
}```

This way i prepared code for 3 different views:

 ```struct Notification {
    enum NotificationType {
        case DuelReceived, TogetherReceived, InfoReceived, FollowReceived
    }
    let username : String
    let msg : String
    var time : Int
    var photo:String
    let type : NotificationType
}

extension Notification {
    static let sampleChat = [
        Notification(username: "steveab", msg: "he offered you a walk together", time: 20000, photo: "mangaa", type: .TogetherReceived),
        Notification(username: "benjamin", msg: "challenged you", time: 49999, photo: "mangaa", type: .DuelReceived),
        Notification(username: "robertt", msg: "started following you", time: 60000, photo: "mangaa", type: .FollowReceived),
        Notification(username: "mases", msg: "accepted the offer to walk together", time: 59999, photo: "mangaa", type: .InfoReceived)
    ]
}```

I made two more views infoNotification and newFollower.
Then created a function like this but it didn't work. How can i show different views for different data. These notifications can be multiple.

 ```func getNotification() -> some View {
    let notification : [Notification] = Notification.sampleChat
    ForEach(notification){ section in
        if section.type == .TogetherReceived {
            inviteNotification(photo: section.photo, username: section.username, msg: section.msg, time:section.time)
        }
        else if section.type == .InfoReceived {
            infoNotification(photo: section.photo, username : section.username,
                             msg: section.msg , time : section.time)
        } else if  section.type == .FollowReceived {
            newFollower(photo: section.photo, username : section.username,
                        msg: section.msg , time : section.time)
        }
    }
} ```


问:
webinarium/DataTablesBundle search by individual column
i want to make and search by column on my datatable for moment i have this

```<code> $('#data-table-sse thead th').each(function () {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        });

        // DataTable
        var table = $('#data-table-sse').DataTable({
            serverSide: true,
            ajax: '{{ path('datatable_project') }}',
            initComplete: function () {
                // Apply the search
                this.api()
                    .columns()
                    .every(function () {
                        var that = this;

                        $('input', this.footer()).on('keyup change clear', function () {
                            if (that.search() !== this.value) {
                                that.search(this.value).draw();
                            }
                        });
                    });
            },
        });
</code>```

And this on handle

```<code> foreach ($request->columns as $column) {
            if ($column->search->value) {
                $value = strtolower($column->search->value);
                // "Login" column
                if ($column->data == 2) {
                    $query->andWhere('p.serial_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
                if ($column->data == 3) {
                    $query->andWhere('p.order_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
            }
        }
</code>```

But when he have only and column define on handle is working, but when i put an second column, the handle don't made the difference between column data == 2 & data == 3 and launch two $query->andWhere()

Do you have and exemple of JS Code to Column Search or any information about this issue thx

For example i add dump('HIT') and dump('HIT x2') on every handle column

```<code>foreach ($request->columns as $column) {
            if ($column->search->value) {
                $value = strtolower($column->search->value);
                // "Login" column
                if ($column->data == 2) {
                    dump('HIT');
                    $query->andWhere('p.serial_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
                if ($column->data == 3) {
                    dump('HIT x2');
                    $query->andWhere('p.order_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
            }
        }
</code>```

When i put an search on just one column the two dump is hit

How to identity the column search only and process the $query->andWhere only when the correct column is hit

Body:
i want to make and search by column on my datatable for moment i have this

 $('#data-table-sse thead th').each(function () {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        });

        // DataTable
        var table = $('#data-table-sse').DataTable({
            serverSide: true,
            ajax: '{{ path('datatable_project') }}',
            initComplete: function () {
                // Apply the search
                this.api()
                    .columns()
                    .every(function () {
                        var that = this;

                        $('input', this.footer()).on('keyup change clear', function () {
                            if (that.search() !== this.value) {
                                that.search(this.value).draw();
                            }
                        });
                    });
            },
        });

And this on handle

 foreach ($request->columns as $column) {
            if ($column->search->value) {
                $value = strtolower($column->search->value);
                // "Login" column
                if ($column->data == 2) {
                    $query->andWhere('p.serial_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
                if ($column->data == 3) {
                    $query->andWhere('p.order_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
            }
        }

But when he have only and column define on handle is working, but when i put an second column, the handle don't made the difference between column data == 2 & data == 3 and launch two $query->andWhere()

Do you have and exemple of JS Code to Column Search or any information about this issue thx

For example i add dump('HIT') and dump('HIT x2') on every handle column

foreach ($request->columns as $column) {
            if ($column->search->value) {
                $value = strtolower($column->search->value);
                // "Login" column
                if ($column->data == 2) {
                    dump('HIT');
                    $query->andWhere('p.serial_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
                if ($column->data == 3) {
                    dump('HIT x2');
                    $query->andWhere('p.order_number LIKE :search');
                    $query->setParameter('search', "%{$value}%");
                }
            }
        }

When i put an search on just one column the two dump is hit

How to identity the column search only and process the $query->andWhere only when the correct column is hit


问:
How to configure swagger with java api using dropwizard? Need to get past SwaggerUIConfiguration undefined
Struggling getting Swagger implemented with a Java api using dropwizard (I come from .net world, and still learning the java architecture). Followed the swagger docs and samples. When I hit my /swagger endpoint, I get the console error Uncaught ReferenceError: SwaggerUIBundle is not defined. So, it seems that my servlet for the swagger endpoint is working, it's just that my configuration isn't delivering the swagger data to the index.html file? Seems like I am a small change away from getting this...

EDIT ADD: Also, hitting /swagger/openapi.json does not deliver the json, rather is a 404.

I've built and compiled the app, and the swagger has been added to the resources/swagger/assess of the repo

pom.xml

```<code>        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-jaxrs2</artifactId>
            <scope>compile</scope>
            <version>2.2.7</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-assets</artifactId>
        </dependency>
</code>```

root/conf/swagger.yml

```<code>defaultName: My Api
server:
  rootPath: /swagger/
logging:
  level: ERROR
  appenders:
    - type: console
      threshold: ALL
      timeZone: UTC
      target: stdout
</code>```

I've recreated the above in the application.conf file as well with no changes... This seems like part of my problem, where to properly apply swagger configuration?

resources/app/index.html (Script only)

```<code>  window.onload = function() {
    var url = window.location.search.match(/url=([^&]+)/);
    if (url && url.length > 1) {
      url = decodeURIComponent(url[1]);
    } else {
      url = '/swagger/openapi.json';
    }

    // Build a system
    const ui = SwaggerUIBundle({ // SwaggerUIBundle is never resolved
      url: url,
      dom_id: '#swagger-ui',
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIStandalonePreset
      ],
      plugins: [
        SwaggerUIBundle.plugins.DownloadUrl
      ],
      layout: "StandaloneLayout"
    })

    window.ui = ui
  }
</script>
</code>```

configuration file

```<code>public class MyConfig extends TypesafeConfiguration implements ... { //TyepsafeConfguration extends Configuration as in the Sample setup

    @NotEmpty
    @JsonProperty
    private String defaultName = "My Api";

    public String getDefaultName() { // greyed out as unused?
        return defaultName;
    }

}
</code>```

service file

```<code>public class MyService extends Application<MyConfiguration> {
    @Override
    public String getName() {
        return "My Service";
    }

    @Override
    public void initialize(final Bootstrap<MyConfiguration> bootstrap) {

        // Swagger
        bootstrap.addBundle(new AssetsBundle("/app", "/swagger", "index.html"));

    }

    @Override
    public void run(final MyConfiguration configuration,
                    final Environment environment) {

        OpenAPI oas = new OpenAPI();
        Info info = new Info()
                .title("My Title")
                .description("My Description")
                .termsOfService("https://myurl.com/tos")
                .license(new License()
                        .name("Public Domain")
                        .url("https://myurl.com/LICENSE.md"));

        oas.info(info);
        List<Server> servers = new ArrayList<>();
        servers.add(new Server().url("/api"));
        oas.servers(servers);
        SwaggerConfiguration oasConfig = new SwaggerConfiguration()
                .openAPI(oas)
                .prettyPrint(true)
                .resourcePackages(Stream.of("path.to.resources").collect(Collectors.toSet()));

        environment.jersey().register(FooResource.class);
        environment.jersey().register(BarResource.class);
        environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // eg.
        environment.jersey().register(new OpenApiResource().openApiConfiguration(oasConfig));
}
</code>```

FooResource.java

```<code>public MyResource() {

    @Override
    @GET
    @Path("/metadata")
    @Public
    @ApiOperation(value = "Get some metadata", notes = "returns metadata", response = CapabilityStatement.class)
    @ApiResponses(@ApiResponse(code = 200, message = "Successful operation", examples = @Example(@ExampleProperty(value = ""))))
    public CapabilityStatement metadata() {
        return Capabilities.getCapabilities(baseURL);
    }

}
</code>```

Body:
Struggling getting Swagger implemented with a Java api using dropwizard (I come from .net world, and still learning the java architecture). Followed the swagger docs and samples. When I hit my /swagger endpoint, I get the console error Uncaught ReferenceError: SwaggerUIBundle is not defined. So, it seems that my servlet for the swagger endpoint is working, it's just that my configuration isn't delivering the swagger data to the index.html file? Seems like I am a small change away from getting this...

EDIT ADD: Also, hitting /swagger/openapi.json does not deliver the json, rather is a 404.

I've built and compiled the app, and the swagger has been added to the resources/swagger/assess of the repo

pom.xml

        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-jaxrs2</artifactId>
            <scope>compile</scope>
            <version>2.2.7</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-assets</artifactId>
        </dependency>

root/conf/swagger.yml

defaultName: My Api
server:
  rootPath: /swagger/
logging:
  level: ERROR
  appenders:
    - type: console
      threshold: ALL
      timeZone: UTC
      target: stdout

I've recreated the above in the application.conf file as well with no changes... This seems like part of my problem, where to properly apply swagger configuration?

resources/app/index.html (Script only)

  window.onload = function() {
    var url = window.location.search.match(/url=([^&]+)/);
    if (url && url.length > 1) {
      url = decodeURIComponent(url[1]);
    } else {
      url = '/swagger/openapi.json';
    }

    // Build a system
    const ui = SwaggerUIBundle({ // SwaggerUIBundle is never resolved
      url: url,
      dom_id: '#swagger-ui',
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIStandalonePreset
      ],
      plugins: [
        SwaggerUIBundle.plugins.DownloadUrl
      ],
      layout: "StandaloneLayout"
    })

    window.ui = ui
  }
</script>

configuration file

public class MyConfig extends TypesafeConfiguration implements ... { //TyepsafeConfguration extends Configuration as in the Sample setup

    @NotEmpty
    @JsonProperty
    private String defaultName = "My Api";

    public String getDefaultName() { // greyed out as unused?
        return defaultName;
    }

}

service file

public class MyService extends Application<MyConfiguration> {
    @Override
    public String getName() {
        return "My Service";
    }

    @Override
    public void initialize(final Bootstrap<MyConfiguration> bootstrap) {

        // Swagger
        bootstrap.addBundle(new AssetsBundle("/app", "/swagger", "index.html"));

    }

    @Override
    public void run(final MyConfiguration configuration,
                    final Environment environment) {

        OpenAPI oas = new OpenAPI();
        Info info = new Info()
                .title("My Title")
                .description("My Description")
                .termsOfService("https://myurl.com/tos")
                .license(new License()
                        .name("Public Domain")
                        .url("https://myurl.com/LICENSE.md"));

        oas.info(info);
        List<Server> servers = new ArrayList<>();
        servers.add(new Server().url("/api"));
        oas.servers(servers);
        SwaggerConfiguration oasConfig = new SwaggerConfiguration()
                .openAPI(oas)
                .prettyPrint(true)
                .resourcePackages(Stream.of("path.to.resources").collect(Collectors.toSet()));

        environment.jersey().register(FooResource.class);
        environment.jersey().register(BarResource.class);
        environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // eg.
        environment.jersey().register(new OpenApiResource().openApiConfiguration(oasConfig));
}

FooResource.java

public MyResource() {

    @Override
    @GET
    @Path("/metadata")
    @Public
    @ApiOperation(value = "Get some metadata", notes = "returns metadata", response = CapabilityStatement.class)
    @ApiResponses(@ApiResponse(code = 200, message = "Successful operation", examples = @Example(@ExampleProperty(value = ""))))
    public CapabilityStatement metadata() {
        return Capabilities.getCapabilities(baseURL);
    }

}


问:
How to increase the efficiency of a for loop used to run Stepwise Regressions iteratively
All of the code in this question can be found in my GitHub Repository for this research project on Estimated Exhaustive Regression. Specifically, in the "Both BE & FS script" and "LASSO code" Rscripts, and you may use the significantly truncated file folder of datasets "sample_obs(20)" rather than "spencer" because the former only contains 20 csvs while the latter contains 58.5k!

I am running both a Backward Elimination and a Forward Selection Stepwise Regression on each of N different csv file formatted datasets within a file folder using the following code (once the N datasets have already been loaded):

```<code>set.seed(11)      # for reproducibility
full_models <- vector("list", length = length(datasets))
BE_fits <- vector("list", length = length(datasets))
head(BE_fits, n = 3)   # returns a list with 18 elements, all of which are NULL

set.seed(11)      # for reproducibility
for(i in seq_along(datasets)) {
  full_models[[i]] <- lm(formula = Y ~ ., data = datasets[[i]])
  BE_fits[[i]] <- step(object = full_models[[i]],
                        scope = formula(full_models[[i]]),
                        direction = 'backward',
                        trace = 0) }
</code>```

And to get the final results I want, I use the following:

```<code>BE_Coeffs <- lapply(seq_along(BE_fits), function(i) coef(BE_fits[[i]]))

Models_Selected_by_BE <- lapply(seq_along(BE_fits),
                              \(i) names(coef(BE_fits[[i]])))
</code>```

And for FS Stepwise, I used:

```<code>set.seed(11)      # for reproducibility
FS_fits <- vector("list", length = length(datasets))
head(FS_fits, n = 3)   # returns a list with 15 elements, all of which are NULL

set.seed(11)      # for reproducibility
for(j in seq_along(datasets)) { null_models[[j]] = lm(formula = Y ~ 1,
                                                     data = datasets[[j]])
                                FS_fits[[j]] = step(object = null_models[[j]],
                                                    direction = 'forward',
                       scope = formula(full_models[[j]]), trace = 0) }
</code>```

Much of the syntax of this code I got from previous questions I asked here several months ago, but now I am rerunning all of my models on a new file folder filled with new randomly generated synthetic datasets, and I don't want to re-run this using this code because last time, it took WELL OVER 12 or 14 hours for both the BE and the FS stepwise procedures to finish running.

p.s.
I already was able to avoid using a loop when I did the same thing instead for LASSO Regression as my 1st Benchmark Variable Selection Procedure using the following code which employed a function from R's useful apply family (this only takes 2-3 hours):

```<code>set.seed(11)     # to ensure replicability
LASSO_fits <- lapply(datasets, function(i)
               enet(x = as.matrix(select(i, starts_with("X"))),
                    y = i$Y, lambda = 0, normalize = FALSE))
</code>```

However, I could not figure out how to replicate something similar for either basic version of Stepwise because of the all important initialization step beforehand.

Body:
All of the code in this question can be found in my GitHub Repository for this research project on Estimated Exhaustive Regression. Specifically, in the "Both BE & FS script" and "LASSO code" Rscripts, and you may use the significantly truncated file folder of datasets "sample_obs(20)" rather than "spencer" because the former only contains 20 csvs while the latter contains 58.5k!

I am running both a Backward Elimination and a Forward Selection Stepwise Regression on each of N different csv file formatted datasets within a file folder using the following code (once the N datasets have already been loaded):

set.seed(11)      # for reproducibility
full_models <- vector("list", length = length(datasets))
BE_fits <- vector("list", length = length(datasets))
head(BE_fits, n = 3)   # returns a list with 18 elements, all of which are NULL

set.seed(11)      # for reproducibility
for(i in seq_along(datasets)) {
  full_models[[i]] <- lm(formula = Y ~ ., data = datasets[[i]])
  BE_fits[[i]] <- step(object = full_models[[i]],
                        scope = formula(full_models[[i]]),
                        direction = 'backward',
                        trace = 0) }

And to get the final results I want, I use the following:

BE_Coeffs <- lapply(seq_along(BE_fits), function(i) coef(BE_fits[[i]]))

Models_Selected_by_BE <- lapply(seq_along(BE_fits),
                              \(i) names(coef(BE_fits[[i]])))

And for FS Stepwise, I used:

set.seed(11)      # for reproducibility
FS_fits <- vector("list", length = length(datasets))
head(FS_fits, n = 3)   # returns a list with 15 elements, all of which are NULL

set.seed(11)      # for reproducibility
for(j in seq_along(datasets)) { null_models[[j]] = lm(formula = Y ~ 1,
                                                     data = datasets[[j]])
                                FS_fits[[j]] = step(object = null_models[[j]],
                                                    direction = 'forward',
                       scope = formula(full_models[[j]]), trace = 0) }

Much of the syntax of this code I got from previous questions I asked here several months ago, but now I am rerunning all of my models on a new file folder filled with new randomly generated synthetic datasets, and I don't want to re-run this using this code because last time, it took WELL OVER 12 or 14 hours for both the BE and the FS stepwise procedures to finish running.

p.s.
I already was able to avoid using a loop when I did the same thing instead for LASSO Regression as my 1st Benchmark Variable Selection Procedure using the following code which employed a function from R's useful apply family (this only takes 2-3 hours):

set.seed(11)     # to ensure replicability
LASSO_fits <- lapply(datasets, function(i)
               enet(x = as.matrix(select(i, starts_with("X"))),
                    y = i$Y, lambda = 0, normalize = FALSE))

However, I could not figure out how to replicate something similar for either basic version of Stepwise because of the all important initialization step beforehand.


问:
I want to implement a function to display a status active when the expiration date is not hit, and a status inactive when it's hit
My greetings to everybody, actually I want to write a function or a condition to display status active when the expiration date is not hit, and a status inactive when it's hit.

```<code>         Ref No
     Beneficiaire
     Date expiration
     Status
     Actions

@foreach($contrats as $contrat)

      {{$contrat->reference}}
      {{$contrat->beneficiare}}
          {{$contrat->date_exp}}

    Inactive
    Confirmé

           <a href="#">
        <i>Voir</i>
           </a>

  @endforeach
</code>```

`

Body:
My greetings to everybody, actually I want to write a function or a condition to display status active when the expiration date is not hit, and a status inactive when it's hit.

         Ref No
     Beneficiaire
     Date expiration
     Status
     Actions

@foreach($contrats as $contrat)

      {{$contrat->reference}}
      {{$contrat->beneficiare}}
          {{$contrat->date_exp}}

    Inactive
    Confirmé

        Voir

  @endforeach

`


问:
How do I make my FlatList scrollable while sibling Modal is visible?
My FlatList is not scrollable while my Modal is visible. I've tried a bunch of things but none seem to do the job. I'm building for Android. You can find the Expo snack here https://snack.expo.dev/@ordis45/modal_flatlist?platform=android. Code is as follows:

Any pointers in the right direction would be appreciated!

```<code>const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  modal: {
    position: 'relative',
    bottom: 0,
    height: 20,
  },
  modalContent: {
    backgroundColor: 'white',
    padding: 22,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: 'rgba(0, 0, 0, 0.1)',
  },
  openButton: {
    backgroundColor: '#F194FF',
    borderRadius: 20,
    padding: 10,
    elevation: 2,
    position: 'absolute',
    bottom: 20,
    right: 20,
  },
});

const myComp = () => {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container} overflow='scroll'>
      <Modal
        visible={modalVisible}
        style={styles.modal}
        transparent={true}
      >
        <View style={styles.modalContent}>
          <Text>This is a modal</Text>
          <TouchableOpacity onPress={() => setModalVisible(false)}>
            <Text>Close</Text>
          </TouchableOpacity>
        </View>
      </Modal>
      <FlatList
        style={{height: 300, position: 'relative', elevation: 1}}
        data={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
        renderItem={({ item }) => <Text style={{padding: 50}}>{item}</Text>}
      />
      <TouchableOpacity onPress={() => setModalVisible(true)} style={styles.openButton}>
        <Text>Open</Text>
      </TouchableOpacity>
    </View>
  );

};
</code>```

I tried things like changing the elevation and z-indices of the View component and the FlatList and Modal components- to no avail. I also tried setting supportedOrientations={['landscape']} but that didn't work either.

Body:
My FlatList is not scrollable while my Modal is visible. I've tried a bunch of things but none seem to do the job. I'm building for Android. You can find the Expo snack here https://snack.expo.dev/@ordis45/modal_flatlist?platform=android. Code is as follows:

Any pointers in the right direction would be appreciated!

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  modal: {
    position: 'relative',
    bottom: 0,
    height: 20,
  },
  modalContent: {
    backgroundColor: 'white',
    padding: 22,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: 'rgba(0, 0, 0, 0.1)',
  },
  openButton: {
    backgroundColor: '#F194FF',
    borderRadius: 20,
    padding: 10,
    elevation: 2,
    position: 'absolute',
    bottom: 20,
    right: 20,
  },
});

const myComp = () => {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container} overflow='scroll'>
      <Modal
        visible={modalVisible}
        style={styles.modal}
        transparent={true}
      >
        <View style={styles.modalContent}>
          <Text>This is a modal</Text>
          <TouchableOpacity onPress={() => setModalVisible(false)}>
            <Text>Close</Text>
          </TouchableOpacity>
        </View>
      </Modal>
      <FlatList
        style={{height: 300, position: 'relative', elevation: 1}}
        data={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
        renderItem={({ item }) => <Text style={{padding: 50}}>{item}</Text>}
      />
      <TouchableOpacity onPress={() => setModalVisible(true)} style={styles.openButton}>
        <Text>Open</Text>
      </TouchableOpacity>
    </View>
  );

};

I tried things like changing the elevation and z-indices of the View component and the FlatList and Modal components- to no avail. I also tried setting supportedOrientations={['landscape']} but that didn't work either.


问:
Create flip cart animation between two NSViews
Hi I want to create flip card animation between two full screen NSViews

but my animation didn't work as expected like in iOS

here is example of iOS working code

```<code>UIView.transition(from:self.upperView, to:self.lowerView,duration:1,options:[.transitionFlipFromRight])
</code>```

On mac OS app i am trying add two NSViews stack on top of each other.

```<code>private lazy var lowerView:NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.red.cgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var upperView:NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.green.cgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
</code>```

Thank I add 2 views to parent view of the viewcontroller with constraints.

```<code>private func addUpperView() {
        self.view.addSubview(upperView)
        NSLayoutConstraint.activate([
            upperView.topAnchor.constraint(equalTo: self.view.topAnchor),
            upperView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            upperView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            upperView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),

        ])
    }

    private func addLowerView () {
        self.view.addSubview(lowerView)
        NSLayoutConstraint.activate([
            lowerView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            lowerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            lowerView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
            lowerView.heightAnchor.constraint(equalTo: self.view.heightAnchor)        ])

    }
</code>```

All of this i am executing in on viewDidAppear

```<code>override func viewDidAppear() {
addLowerView()
addUpperView()

 DispatchQueue.main.asyncAfter(deadline: .now()+2) {
            FlipTransition().flip(from: self.upperView, to: self.lowerView)
        }

}
</code>```

And this is my helper class for executing the animation.

```<code>import Cocoa

public final class FlipTransition: NSObject {

    private var srcView, dstView: NSView?

    private var duration: TimeInterval = 2

    public func flip(
        from srcView: NSView,
        to dstView: NSView,
        duration: TimeInterval = 2
    ) {

        self.duration = duration
        self.srcView = srcView
        self.dstView = dstView
        srcView.isHidden = false
        dstView.isHidden = true

        guard let superLayer = srcView.layer else {
            return
        }

        var transform3D = CATransform3DIdentity
        transform3D.m34 = 1 / -1000

        let translation = CATransform3DMakeTranslation(
            superLayer.bounds.midX,
            superLayer.bounds.midY,
            .zero
        )

        superLayer.sublayerTransform = CATransform3DConcat(
            transform3D,
            translation
        )

        animate(
            srcView,
            from: CATransform3DIdentity,
            to: CATransform3DMakeRotation(CGFloat.pi / -2, 0, 1, 0)
        ) { f in
            self.startSecondStep()
        }
    }

    private func startSecondStep() {

        guard let srcView = srcView, let dstView = dstView else {
            return
        }

        srcView.isHidden = true
        dstView.isHidden = false
        animate(
            dstView,
            from: CATransform3DMakeRotation(CGFloat.pi / 2, 0, 1, 0),
            to: CATransform3DIdentity
        ) { f in
            self.finish()
        }
    }

    private func finish() {

        guard let srcView = srcView, let dstView = dstView else {
            return
        }

        srcView.layer?.removeAllAnimations()
        dstView.layer?.removeAllAnimations()

        [srcView, dstView]
            .compactMap(\.layer)
            .forEach { layer in
                layer.anchorPoint = .zero
            }

        srcView.superview?.layer?.sublayerTransform = CATransform3DIdentity
    }

    private class AnimationDelegate: NSObject, CAAnimationDelegate {

        private let completion: (Bool) -> Void

        init(completion: @escaping (Bool) -> Void) {
            self.completion = completion
        }

        func animationDidStart(_ anim: CAAnimation) { }

        func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
            completion(flag)
        }

    }

    private func animate(
        _ view: NSView,
        from: CATransform3D,
        to: CATransform3D,
        completion: @escaping (Bool) -> Void
    ) {

        let dstRotation = CABasicAnimation(keyPath: "transform")
        dstRotation.fromValue = from
        dstRotation.toValue = to
        dstRotation.duration = duration / 2
        dstRotation.fillMode = .forwards
        dstRotation.isRemovedOnCompletion = false
        dstRotation.delegate = AnimationDelegate(completion: completion)

        view.layer?.add(dstRotation, forKey: "flip")
    }

}
</code>```

Can some one help me pls how to achieve the same animation like in iOS using UIView.transition

Body:
Hi I want to create flip card animation between two full screen NSViews

but my animation didn't work as expected like in iOS

here is example of iOS working code

UIView.transition(from:self.upperView, to:self.lowerView,duration:1,options:[.transitionFlipFromRight])

On mac OS app i am trying add two NSViews stack on top of each other.

private lazy var lowerView:NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.red.cgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var upperView:NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.green.cgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

Thank I add 2 views to parent view of the viewcontroller with constraints.

private func addUpperView() {
        self.view.addSubview(upperView)
        NSLayoutConstraint.activate([
            upperView.topAnchor.constraint(equalTo: self.view.topAnchor),
            upperView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            upperView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            upperView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),

        ])
    }

    private func addLowerView () {
        self.view.addSubview(lowerView)
        NSLayoutConstraint.activate([
            lowerView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            lowerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            lowerView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
            lowerView.heightAnchor.constraint(equalTo: self.view.heightAnchor)        ])

    }

All of this i am executing in on viewDidAppear

override func viewDidAppear() {
addLowerView()
addUpperView()

 DispatchQueue.main.asyncAfter(deadline: .now()+2) {
            FlipTransition().flip(from: self.upperView, to: self.lowerView)
        }

}

And this is my helper class for executing the animation.

import Cocoa

public final class FlipTransition: NSObject {

    private var srcView, dstView: NSView?

    private var duration: TimeInterval = 2

    public func flip(
        from srcView: NSView,
        to dstView: NSView,
        duration: TimeInterval = 2
    ) {

        self.duration = duration
        self.srcView = srcView
        self.dstView = dstView
        srcView.isHidden = false
        dstView.isHidden = true

        guard let superLayer = srcView.layer else {
            return
        }

        var transform3D = CATransform3DIdentity
        transform3D.m34 = 1 / -1000

        let translation = CATransform3DMakeTranslation(
            superLayer.bounds.midX,
            superLayer.bounds.midY,
            .zero
        )

        superLayer.sublayerTransform = CATransform3DConcat(
            transform3D,
            translation
        )

        animate(
            srcView,
            from: CATransform3DIdentity,
            to: CATransform3DMakeRotation(CGFloat.pi / -2, 0, 1, 0)
        ) { f in
            self.startSecondStep()
        }
    }

    private func startSecondStep() {

        guard let srcView = srcView, let dstView = dstView else {
            return
        }

        srcView.isHidden = true
        dstView.isHidden = false
        animate(
            dstView,
            from: CATransform3DMakeRotation(CGFloat.pi / 2, 0, 1, 0),
            to: CATransform3DIdentity
        ) { f in
            self.finish()
        }
    }

    private func finish() {

        guard let srcView = srcView, let dstView = dstView else {
            return
        }

        srcView.layer?.removeAllAnimations()
        dstView.layer?.removeAllAnimations()

        [srcView, dstView]
            .compactMap(\.layer)
            .forEach { layer in
                layer.anchorPoint = .zero
            }

        srcView.superview?.layer?.sublayerTransform = CATransform3DIdentity
    }

    private class AnimationDelegate: NSObject, CAAnimationDelegate {

        private let completion: (Bool) -> Void

        init(completion: @escaping (Bool) -> Void) {
            self.completion = completion
        }

        func animationDidStart(_ anim: CAAnimation) { }

        func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
            completion(flag)
        }

    }

    private func animate(
        _ view: NSView,
        from: CATransform3D,
        to: CATransform3D,
        completion: @escaping (Bool) -> Void
    ) {

        let dstRotation = CABasicAnimation(keyPath: "transform")
        dstRotation.fromValue = from
        dstRotation.toValue = to
        dstRotation.duration = duration / 2
        dstRotation.fillMode = .forwards
        dstRotation.isRemovedOnCompletion = false
        dstRotation.delegate = AnimationDelegate(completion: completion)

        view.layer?.add(dstRotation, forKey: "flip")
    }

}

Can some one help me pls how to achieve the same animation like in iOS using UIView.transition


问:
How to specify postgres DB parameters during Github Action Python build for Azure?
I have a Django web application I'm trying to deploy to Azure. I'm following this tutorial on how to set up the project. During the build I'm trying to run migrations on the DB, with the following command:

```<code>env:
  WEBSITE_HOSTNAME: 'something'
  DBHOST: ${{ secrets.DBHOST }}
  DBNAME: ${{ secrets.DBNAME }}
  DBPASSWORD: ${{ secrets.DBPASSWORD }}
  DBUSER: ${{ secrets.DBUSER }}
  DBPASS: ${{ secrets.DBPASS }}
  DBPORT: ${{ secrets.DBPORT }}

jobs:
  build:
    runs-on: ubuntu-latest

steps:
  - uses: actions/checkout@v2

  - name: Set up Python version
    uses: actions/setup-python@v1
    with:
      python-version: '3.10'

  - name: Create and start virtual environment
    run: |
      python -m venv venv
      source venv/bin/activate

  - name: Install dependencies
    run: pip install -r requirements.txt

  - name: Make migrations and run migrations
    run: python ./appname/manage.py migrate
</code>```

However, this step fails with the following error:

```<code> django.db.utils.OperationalError: could not translate host name "***.***.database.azure.com" to address: Name or service not known
</code>```

I'm referring to these values in the settings.py like this:

```<code>hostname = os.environ['DBHOST']
DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': os.environ['DBNAME'],
        'USER': os.environ['DBUSER'],
        'PASSWORD': os.environ['DBPASS'],
        'PORT':  os.environ['DBPORT'],
        'HOST': hostname + ".postgres.database.azure.com" if 'WEBSITE_HOSTNAME' in os.environ else os.environ['DBHOST']
    }
}
</code>```

I have inserted the DBNAME, DBHOST, etc. values shown on the screenshot as app secrets into github, so I'm really not sure why its failing. Can anyone point out please what am I missing here?

Body:
I have a Django web application I'm trying to deploy to Azure. I'm following this tutorial on how to set up the project. During the build I'm trying to run migrations on the DB, with the following command:

env:
  WEBSITE_HOSTNAME: 'something'
  DBHOST: ${{ secrets.DBHOST }}
  DBNAME: ${{ secrets.DBNAME }}
  DBPASSWORD: ${{ secrets.DBPASSWORD }}
  DBUSER: ${{ secrets.DBUSER }}
  DBPASS: ${{ secrets.DBPASS }}
  DBPORT: ${{ secrets.DBPORT }}

jobs:
  build:
    runs-on: ubuntu-latest

steps:
  - uses: actions/checkout@v2

  - name: Set up Python version
    uses: actions/setup-python@v1
    with:
      python-version: '3.10'

  - name: Create and start virtual environment
    run: |
      python -m venv venv
      source venv/bin/activate

  - name: Install dependencies
    run: pip install -r requirements.txt

  - name: Make migrations and run migrations
    run: python ./appname/manage.py migrate

However, this step fails with the following error:

 django.db.utils.OperationalError: could not translate host name "***.***.database.azure.com" to address: Name or service not known

I'm referring to these values in the settings.py like this:

hostname = os.environ['DBHOST']
DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': os.environ['DBNAME'],
        'USER': os.environ['DBUSER'],
        'PASSWORD': os.environ['DBPASS'],
        'PORT':  os.environ['DBPORT'],
        'HOST': hostname + ".postgres.database.azure.com" if 'WEBSITE_HOSTNAME' in os.environ else os.environ['DBHOST']
    }
}

I have inserted the DBNAME, DBHOST, etc. values shown on the screenshot as app secrets into github, so I'm really not sure why its failing. Can anyone point out please what am I missing here?


问:
Redirect the socket traffic on an application already executed
I am trying to understand how to change the IP/port of a socket used by an application, to get it to send its packets to me instead of the original recipient.

I saw that Frida API can help me to do that, but I want to understand how its done. Could someone explain to me how Frida is able to do that? It kind of blows my mind that it is able to slip so deeply into a program.


问:
Python function not writing or overwriting when threading
I have a script that takes a a group of images on the local machine, sends it to removeBG using threading.  If it is successful, it gets the resultant file and uploads to s3 and grabs the s3 URL.  Now we pass this URL to BannerBear to generate a composite which returns another URL that we print to the screen and then get the file so we can write it locally.

But while all the text of each process is being printed to the screen properly, somewhere along the way the writing of the final image locally gets skipped or overwritten by the other file that is being processed.  If I go one at a time it works.

Code:

```<code># Check the result of the RemoveBG API request if ok write the file locally and upload to s3
if response.status_code == requests.codes.ok:
    with open(
        os.path.join(OUTPUT_DIR, os.path.splitext(file)[0] + ".png"), "wb"
    ) as out:
        out.write(response.content)

        # Open a file-like object using io.BytesIO
        image_data = io.BytesIO(response.content)

        # Upload the image data to S3
        s3.upload_fileobj(image_data, bucket_name, object_key)

        # Get the URL for the uploaded image
        image_url = f"https://{bucket_name}.s3.amazonaws.com/{object_key}"
        print(f"Image uploaded to S3: {image_url}")

        # pass the s3 url to BannerBear
        bannerbear(image_url)

# start BannerBear Func
def bannerbear(photo_url):

    # Send a POST request to the endpoint URL
    responseBB = requests.post(endpoint_url, headers=headers, json=data)
    if responseBB.status_code == 200:
        # Print the URL of the generated image
        print(responseBB.json()["image_url_jpg"])
        # Write the image data to a file
        filedata = requests.get(responseBB.json()["image_url_jpg"])
        with open(
            os.path.join(OUTPUT_DIR, "bb", os.path.splitext(file)[0] + ".jpg"), "wb"
        ) as f:
            f.write(filedata.content)
        print("BannerBear File Written")
    else:
        # Something went wrong
        print(f"An error occurred: {responseBB.status_code}")
        print(response.json()["message"])

# Create a thread pool with a maximum of 4 threads
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
    # Iterate through all the files in the image directory
    for file in os.listdir(IMAGE_DIR):
        # Check if the file is an image
        if file.endswith(".jpg") or file.endswith(".png"):
            # Submit the task to the thread pool
            executor.submit(process_image, file)

</code>```

This is what I see in the console:
So it's going through all the steps.

Body:
I have a script that takes a a group of images on the local machine, sends it to removeBG using threading.  If it is successful, it gets the resultant file and uploads to s3 and grabs the s3 URL.  Now we pass this URL to BannerBear to generate a composite which returns another URL that we print to the screen and then get the file so we can write it locally.

But while all the text of each process is being printed to the screen properly, somewhere along the way the writing of the final image locally gets skipped or overwritten by the other file that is being processed.  If I go one at a time it works.

Code:

# Check the result of the RemoveBG API request if ok write the file locally and upload to s3
if response.status_code == requests.codes.ok:
    with open(
        os.path.join(OUTPUT_DIR, os.path.splitext(file)[0] + ".png"), "wb"
    ) as out:
        out.write(response.content)

        # Open a file-like object using io.BytesIO
        image_data = io.BytesIO(response.content)

        # Upload the image data to S3
        s3.upload_fileobj(image_data, bucket_name, object_key)

        # Get the URL for the uploaded image
        image_url = f"https://{bucket_name}.s3.amazonaws.com/{object_key}"
        print(f"Image uploaded to S3: {image_url}")

        # pass the s3 url to BannerBear
        bannerbear(image_url)

# start BannerBear Func
def bannerbear(photo_url):

    # Send a POST request to the endpoint URL
    responseBB = requests.post(endpoint_url, headers=headers, json=data)
    if responseBB.status_code == 200:
        # Print the URL of the generated image
        print(responseBB.json()["image_url_jpg"])
        # Write the image data to a file
        filedata = requests.get(responseBB.json()["image_url_jpg"])
        with open(
            os.path.join(OUTPUT_DIR, "bb", os.path.splitext(file)[0] + ".jpg"), "wb"
        ) as f:
            f.write(filedata.content)
        print("BannerBear File Written")
    else:
        # Something went wrong
        print(f"An error occurred: {responseBB.status_code}")
        print(response.json()["message"])

# Create a thread pool with a maximum of 4 threads
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
    # Iterate through all the files in the image directory
    for file in os.listdir(IMAGE_DIR):
        # Check if the file is an image
        if file.endswith(".jpg") or file.endswith(".png"):
            # Submit the task to the thread pool
            executor.submit(process_image, file)

This is what I see in the console:
So it's going through all the steps.


问:
jinja2 block assigment as reusable template inside another block
I'm trying to create a reusable template with block assignment, as shown in Reuse a block of code in several places in jinja2. I got it to work as a stand-alone block:

```<code>import jinja2

template = jinja2.Template("""
{% set reply | wordwrap %}
    You wrote:
    {{ message }}
{% endset %}
{{reply}}
""")

print(template.render(message="Hello!"))
</code>```

That produces:

    You wrote:
    Hello!
```
<p>However, if I use the same block nested inside a for loop, the variable isn't rendered:</p>
```import jinja2

template = jinja2.Template("""
{% set reply | wordwrap %}
    You wrote:
    {{ message }}
{% endset %}
{% for message in ["Foo", "Bar"] %}
{{reply}}
{% endfor %}
""")

print(template.render())
```
<p>I'm getting:</p>
<pre class="lang-bash prettyprint-override"><code>    You wrote:

    You wrote:

</code>```

I expected:

    You wrote:
    Foo

    You wrote:
    Bar

```
<p>Of course, if I use a template like so:</p>
<pre class="lang-py prettyprint-override"><code>import jinja2

template = jinja2.Template("""
{% set reply | wordwrap %}
    You wrote:
    {{ message }}
{% endset %}
{% for message in ["Foo", "Bar"] %}
{{message}}
{% endfor %}
""")

print(template.render())
</code>```

I got the expected result:

Foo

Bar
```

So there's nothing wrong with the loop block.

How can I get message to be replaced by the loop variable? Many thanks!

Body:
I'm trying to create a reusable template with block assignment, as shown in Reuse a block of code in several places in jinja2. I got it to work as a stand-alone block:

import jinja2

template = jinja2.Template("""
{% set reply | wordwrap %}
    You wrote:
    {{ message }}
{% endset %}
{{reply}}
""")

print(template.render(message="Hello!"))

That produces:

    You wrote:
    Hello!

However, if I use the same block nested inside a for loop, the variable isn't rendered:

import jinja2

template = jinja2.Template("""
{% set reply | wordwrap %}
    You wrote:
    {{ message }}
{% endset %}
{% for message in ["Foo", "Bar"] %}
{{reply}}
{% endfor %}
""")

print(template.render())

I'm getting:

    You wrote:

    You wrote:

I expected:

    You wrote:
    Foo

    You wrote:
    Bar

Of course, if I use a template like so:

import jinja2

template = jinja2.Template("""
{% set reply | wordwrap %}
    You wrote:
    {{ message }}
{% endset %}
{% for message in ["Foo", "Bar"] %}
{{message}}
{% endfor %}
""")

print(template.render())

I got the expected result:

Foo

Bar

So there's nothing wrong with the loop block.

How can I get message to be replaced by the loop variable? Many thanks!


问:
How to handover a .pdf or .png object using R in Foundry Code Workbook?
I have created formatted tables using R and the package gt in Code Workbook. I would like to save them as .png or .pdf files so they can be used in other Foundry applications. Currently, I can only save them as .html files.

An example of what my current code looks like:

```<code>table <- function(metrics_national) {

    library(tidyverse)
    library(webshot)
    library(gt)

    table <- metrics_national %>%
    gt()  %>%
    tab_header(title = "My table")

    output <- new.output()
    output_fs <- output$fileSystem()
    table %>% gtsave(filename = output_fs$get_path("table.html",'w'))
    return(table)
}
</code>```

This runs and saves the .html file as expected but when I change the filename extension to .png or .pdf instead of .html it stops working.

Body:
I have created formatted tables using R and the package gt in Code Workbook. I would like to save them as .png or .pdf files so they can be used in other Foundry applications. Currently, I can only save them as .html files.

An example of what my current code looks like:

table <- function(metrics_national) {

    library(tidyverse)
    library(webshot)
    library(gt)

    table <- metrics_national %>%
    gt()  %>%
    tab_header(title = "My table")

    output <- new.output()
    output_fs <- output$fileSystem()
    table %>% gtsave(filename = output_fs$get_path("table.html",'w'))
    return(table)
}

This runs and saves the .html file as expected but when I change the filename extension to .png or .pdf instead of .html it stops working.


问:
Phase context status code: YAML_FILE_ERROR Message: Unknown runtime version named '14' of nodejs. This build image has the following versions: 10, 12
I have updated node version from 12 to 14 for a github project where I have to update the node version from 12 to 14 and then deploy it to aws, but it is giving this error: Phase context status code: YAML_FILE_ERROR Message: Unknown runtime version named '14' of nodejs. This build image has the following versions: 10, 12. I am not understanding why I am getting this error.

in the aws codebuild-details
image:  aws/codebuild/amazonlinux2-x86_64-standard:2.0
enviorment: LInux

Thanks in advance

I wanted to try image for nodejs 14 which is aws/codebuild/standard:5.0, but this change will get us around the issue in CodeBuild, but I think there might be some unintended side effects. It looks like lambda is run on Amazon Linux, so I don't think it makes sense to package the apollo-server lambda on a ubuntu image.

Thanks


问:
Logging SES RECEIVE failures with email sender
I recently encountered a failure with an SES recipient rule set to forward the email to S3 due to a permissions issue. When trying to determine what emails bounced back and from who, I found myself blind.

Is there a way to guarantee logs when an email is sent (despite a failure in the rule)?

Cloudwatch offers a metric on failures, but it does not include any additional information (e.g email sender)


问:
Is passing additional data to save() the right way to store the results of logic triggered by a POST?
I've got a django rest framework view that passes data from a POST to another function that returns a result.

I want to store that result in the database so that you can GET a previous result or results.

Currently, I've got the "nornir_result" defined in my serializer and model.

The serializer field is set to required=False (because the result isn't known when the payload is passed in).

Then, to populate/save this information for later GETs, save(nornir_result=nornir_result) gets called during the POST.

Is my approach correct? Passing additional data to save() to store the results of logic triggered by a POST so it can be viewed later?

```<code># views.py

class F5AuditList(APIView):

    def get(self, request, format=None):
        audits = F5Audit.objects.all()
        serializer = F5AuditSerializer(audits, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = F5AuditSerializer(data=request.data)
        if serializer.is_valid():
            nornir_result = audit.django_result(request.data)
            serializer.save(
                audit_id=create_unique_number(), nornir_result=nornir_result
            )
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# serializers.py

class F5AuditSerializer(serializers.Serializer):

    audit_id = serializers.IntegerField(required=False)
    created = serializers.DateTimeField(required=False)
    devices = serializers.DictField()
    audit_type = serializers.CharField(
        max_length=None, style={"base_template": "textarea.html"}, required=False
    )
    nornir_result = serializers.CharField(
        max_length=None, style={"base_template": "textarea.html"}, required=False
    )

# models.py

class F5Audit(Document):

    audit_id = fields.IntField(primary_key=True)
    created = fields.DateTimeField(default=datetime.datetime.utcnow)
    audit_type = fields.StringField(max_length=100, default="type of f5 audit")
    devices = fields.DictField()
    nornir_result = fields.StringField(max_length=1000)
</code>```

Body:
I've got a django rest framework view that passes data from a POST to another function that returns a result.

I want to store that result in the database so that you can GET a previous result or results.

Currently, I've got the "nornir_result" defined in my serializer and model.

The serializer field is set to required=False (because the result isn't known when the payload is passed in).

Then, to populate/save this information for later GETs, save(nornir_result=nornir_result) gets called during the POST.

Is my approach correct? Passing additional data to save() to store the results of logic triggered by a POST so it can be viewed later?

# views.py

class F5AuditList(APIView):

    def get(self, request, format=None):
        audits = F5Audit.objects.all()
        serializer = F5AuditSerializer(audits, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = F5AuditSerializer(data=request.data)
        if serializer.is_valid():
            nornir_result = audit.django_result(request.data)
            serializer.save(
                audit_id=create_unique_number(), nornir_result=nornir_result
            )
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# serializers.py

class F5AuditSerializer(serializers.Serializer):

    audit_id = serializers.IntegerField(required=False)
    created = serializers.DateTimeField(required=False)
    devices = serializers.DictField()
    audit_type = serializers.CharField(
        max_length=None, style={"base_template": "textarea.html"}, required=False
    )
    nornir_result = serializers.CharField(
        max_length=None, style={"base_template": "textarea.html"}, required=False
    )

# models.py

class F5Audit(Document):

    audit_id = fields.IntField(primary_key=True)
    created = fields.DateTimeField(default=datetime.datetime.utcnow)
    audit_type = fields.StringField(max_length=100, default="type of f5 audit")
    devices = fields.DictField()
    nornir_result = fields.StringField(max_length=1000)


问:
Redux Toolkit: Update state of localstorage after removing item from cart
I am making this Food delivery app, with redux-toolkit, rtk query,NextJS and TS.
So, adding the cart functionality is working fine. But the problem arises, when I remove an item from the cart.

Problem

If I remove an item from the cart, it gets removed and the UI updates accordingly. But in the food menu page, it is not updated properly. So, If I add an item to the cart, the previously removed item also gets added. I checked the localstorage in browser application by opening two tabs. It gets updated properly.

What I have done

So, here is my addToCart and removecart functionality:

```<code>addToCart: (state, action) => {
      const itemIndex = state.items.findIndex(
        (item) => item.id === action.payload.id
      );

      if (itemIndex >= 0) {
        if (state.items[itemIndex].quantity_available === 0) {
          return state;
        }
        state.items[itemIndex].quantity += 1;
        state.items[itemIndex].quantity_available -= 1;
        state.items[itemIndex].total_price =
          (state.items[itemIndex].price + state.items[itemIndex].vat) *
          state.items[itemIndex].quantity;
      } else {
        state.items.push({
          ...action.payload,
          quantity: 1,
          quantity_available: action.payload.quantity_available - 1,
          total_price: action.payload.price + action.payload.vat,
        });
      }
    },
 removeCart: (state, action) => {
      console.log(action);
      return {
        ...state,
        items: state.items.filter((elem) => elem.id !== action.payload),
      };
    },

</code>```

Here is how I added the store to the localstorage(using redux persist library):

```<code>import { configureStore } from "@reduxjs/toolkit";
import { foodcartSlice } from "../features/slice";

import { api } from "../services/products";

//import redux persist
import {
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";

import useFoodCartReducer from "../features/slice";

const persistConfig = {
  key: "cart",
  version: 1,
  storage,
};

const persistedReducer = persistReducer(persistConfig, useFoodCartReducer);

export const store = configureStore({
  reducer: {
    [api.reducerPath]: api.reducer,
    cart: persistedReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(api.middleware),
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

</code>```

Possible solution

What I have done in the cart page is that using a window.location.reload inside useEffect, which is every time I visit another tab and then go back to the cart page, it gets reloaded. Yes, If I do the same on the food menu page, the whole thing is solved. But then, no one wants reloads on every page visit. What I have done in the cart page is below:

```<code>  useEffect(() => {
    function handleVisibilityChange() {
      if (document.visibilityState === "visible") {
        window.location.reload();
      }
    }
    document.addEventListener(
      "visibilitychange",
      handleVisibilityChange,
      false
    );
    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  });
</code>```

I was thinking, if I can do something in the reducer method, to get the items from localstorage after every removal or addition of items, it could work. So, I added the following method:

```<code> reloadCart: (state, action) => {
      console.log("state", state, action);
      return {
        ...state,
        ...JSON.parse(localStorage.getItem("persist:cart")!), // yes I used redux persist for saving in localstorage
      };
    },
</code>```

Problem of the reloadCart method:

So, first of all without the null assertion, I get the error type null is not assignable to type string. If I add null assertion, I get loads of error in the cart and other components because my data in localstorage gets messed up big time.
So, apart from the page reloading part, anyone got any solution on how to do this in RTK and NextJS?

Body:
I am making this Food delivery app, with redux-toolkit, rtk query,NextJS and TS.
So, adding the cart functionality is working fine. But the problem arises, when I remove an item from the cart.

Problem

If I remove an item from the cart, it gets removed and the UI updates accordingly. But in the food menu page, it is not updated properly. So, If I add an item to the cart, the previously removed item also gets added. I checked the localstorage in browser application by opening two tabs. It gets updated properly.

What I have done

So, here is my addToCart and removecart functionality:

addToCart: (state, action) => {
      const itemIndex = state.items.findIndex(
        (item) => item.id === action.payload.id
      );

      if (itemIndex >= 0) {
        if (state.items[itemIndex].quantity_available === 0) {
          return state;
        }
        state.items[itemIndex].quantity += 1;
        state.items[itemIndex].quantity_available -= 1;
        state.items[itemIndex].total_price =
          (state.items[itemIndex].price + state.items[itemIndex].vat) *
          state.items[itemIndex].quantity;
      } else {
        state.items.push({
          ...action.payload,
          quantity: 1,
          quantity_available: action.payload.quantity_available - 1,
          total_price: action.payload.price + action.payload.vat,
        });
      }
    },
 removeCart: (state, action) => {
      console.log(action);
      return {
        ...state,
        items: state.items.filter((elem) => elem.id !== action.payload),
      };
    },

Here is how I added the store to the localstorage(using redux persist library):

import { configureStore } from "@reduxjs/toolkit";
import { foodcartSlice } from "../features/slice";

import { api } from "../services/products";

//import redux persist
import {
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";

import useFoodCartReducer from "../features/slice";

const persistConfig = {
  key: "cart",
  version: 1,
  storage,
};

const persistedReducer = persistReducer(persistConfig, useFoodCartReducer);

export const store = configureStore({
  reducer: {
    [api.reducerPath]: api.reducer,
    cart: persistedReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(api.middleware),
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

Possible solution

What I have done in the cart page is that using a window.location.reload inside useEffect, which is every time I visit another tab and then go back to the cart page, it gets reloaded. Yes, If I do the same on the food menu page, the whole thing is solved. But then, no one wants reloads on every page visit. What I have done in the cart page is below:

  useEffect(() => {
    function handleVisibilityChange() {
      if (document.visibilityState === "visible") {
        window.location.reload();
      }
    }
    document.addEventListener(
      "visibilitychange",
      handleVisibilityChange,
      false
    );
    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  });

I was thinking, if I can do something in the reducer method, to get the items from localstorage after every removal or addition of items, it could work. So, I added the following method:

 reloadCart: (state, action) => {
      console.log("state", state, action);
      return {
        ...state,
        ...JSON.parse(localStorage.getItem("persist:cart")!), // yes I used redux persist for saving in localstorage
      };
    },

Problem of the reloadCart method:

So, first of all without the null assertion, I get the error type null is not assignable to type string. If I add null assertion, I get loads of error in the cart and other components because my data in localstorage gets messed up big time.
So, apart from the page reloading part, anyone got any solution on how to do this in RTK and NextJS?


问:
Spark - nondeterministic expressions not allowed using Delete FROM and exists
The goal of this query is to delete the records that have the same keys of the new dataframe.

This is the query that I'm executing:

```<code>val op=spark.sql(s"""
DELETE
FROM TABLE1 AS t
WHERE EXISTS (
    SELECT 1
    FROM TABLE2 AS s
    WHERE t.DAY=s.DAY
    AND t.DATA_STREAM=s.DATA_STREAM
)""")
</code>```

The error that I'm getting is:

```<code>AnalysisException: nondeterministic expressions are only allowed in
Project, Filter, Aggregate, Window, or Generate, but found:
 exists(t.DAY, t.DATA_STREAM)
in operator DeleteCommandEdge com.databricks.sql.transaction.tahoe.DeltaLog@49e1c8fd, exists#107963 [DAY#108138 && DATA_STREAM#108193]
               ;
DeleteCommandEdge com.databricks.sql.transaction.tahoe.DeltaLog@49e1c8fd, exists#107963 [DAY#108138 && DATA_STREAM#108193]```
```

As far as I know exists is deterministic. Is there another way to achieve the same result with another query?

The query is running on a Databricks cluster with Spark 3.2.1

Body:
The goal of this query is to delete the records that have the same keys of the new dataframe.

This is the query that I'm executing:

val op=spark.sql(s"""
DELETE
FROM TABLE1 AS t
WHERE EXISTS (
    SELECT 1
    FROM TABLE2 AS s
    WHERE t.DAY=s.DAY
    AND t.DATA_STREAM=s.DATA_STREAM
)""")

The error that I'm getting is:

AnalysisException: nondeterministic expressions are only allowed in
Project, Filter, Aggregate, Window, or Generate, but found:
 exists(t.DAY, t.DATA_STREAM)
in operator DeleteCommandEdge com.databricks.sql.transaction.tahoe.DeltaLog@49e1c8fd, exists#107963 [DAY#108138 && DATA_STREAM#108193]
               ;
DeleteCommandEdge com.databricks.sql.transaction.tahoe.DeltaLog@49e1c8fd, exists#107963 [DAY#108138 && DATA_STREAM#108193]```

As far as I know exists is deterministic. Is there another way to achieve the same result with another query?

The query is running on a Databricks cluster with Spark 3.2.1


问:
Ext Js - how to add html attribute to created iframe
How do I add an attribute to an iframe created in Ext Js 7.5.1? I have an iframe component and would like to add the attribute allow="geolocation *" to the iframe element.

Using the autoEl configuration mentioned here adds the attribute to the wrapping
 not the  itself, which doesn't provide the desired behavior. Adding it after render also mentioned here does not appear to provide the desired behavior. I'm not exactly sure why, my guess is because it is added after the component is rendered, not "in" the component as it is being rendered, although I may be wrong on this.


问:
The process cannot access file 'C:/.......' because it is being used by another process
In my application that I wrote in C#, I have the files merged and one of the files I merged is deleted. When I try to merge merged files Process cannot access file '5-1325106-2020004.tif' because it is being used by another process. I get an error</p>
```<code>  GdPictureUtil.MergeFiles(sourceFiles, targetFileName);

                foreach (var item in sourceFiles)
                {

                    if (item != targetFileName)
                    {
                        File.Delete(item); //  it goes wrong here
                    }

                }
</code>```

Body:
In my application that I wrote in C#, I have the files merged and one of the files I merged is deleted. When I try to merge merged files Process cannot access file '5-1325106-2020004.tif' because it is being used by another process. I get an error

  GdPictureUtil.MergeFiles(sourceFiles, targetFileName);

                foreach (var item in sourceFiles)
                {

                    if (item != targetFileName)
                    {
                        File.Delete(item); //  it goes wrong here
                    }

                }


问:
how to stop VLookup bringing back blank cells
The code I am using for a vlookup is working to an extent, but for one of the variables its leaving it blank. even though the relevant information is 100% there.

```<code>Range("B7").Formula = "=IFERROR(VLOOKUP(C7,[" & sourceFile.Name & "]CompanyStructure!$A$2:$B$" & sourceFileRowsCount & ",2,False), """")"
</code>```

It only relates to one piece of data from the sourcefile.

I've tried amending the parameters of the vlookup and the cells its bringing back with no success,

Body:
The code I am using for a vlookup is working to an extent, but for one of the variables its leaving it blank. even though the relevant information is 100% there.

Range("B7").Formula = "=IFERROR(VLOOKUP(C7,[" & sourceFile.Name & "]CompanyStructure!$A$2:$B$" & sourceFileRowsCount & ",2,False), """")"

It only relates to one piece of data from the sourcefile.

I've tried amending the parameters of the vlookup and the cells its bringing back with no success,