问:
How to properly call local storage class?
I've just implemented some localStorage functions in a class to a song lyrics app I'm developing and I think I'm calling it wrong in some way but not sure how. Either that or something is blocking the async function from completing.

Storage Class

```<code>public class Sections
    {
        readonly string searchesFileName = "RecentSearches.txt";
        readonly string songsFileName = "RecentSongs.txt";
        readonly string playlistFileName = "Playlists.txt";
        IFolder localFolder = FileSystem.Current.LocalStorage;

        public async void VerifySectionFiles()
        {
            ExistenceCheckResult searchFileExists = await localFolder.CheckExistsAsync(searchesFileName);
            if (searchFileExists != ExistenceCheckResult.FileExists)
            {
                await localFolder.CreateFileAsync(searchesFileName, CreationCollisionOption.FailIfExists);
            }
            ExistenceCheckResult songsFileExists = await localFolder.CheckExistsAsync(songsFileName);
            if (songsFileExists != ExistenceCheckResult.FileExists)
            {
                await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.FailIfExists);
            }
            ExistenceCheckResult playlistFileExists = await localFolder.CheckExistsAsync(playlistFileName);
            if (playlistFileExists != ExistenceCheckResult.FileExists)
            {
                await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.FailIfExists);
            }
        }

        public async void AddRecentSong(string title, int id, string artist)
        {
            Song[] recentSongs = await ReadRecentSongsFromFile() ?? new Song[10];
            recentSongs[9] = null;
            for (int i = 9; i > 0; i--)
            {
                recentSongs[i] = recentSongs[i - 1];
            }
            recentSongs[0] = new Song(title, artist, id);
            IFile songFile = await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.OpenIfExists);
            string songsJsonString = JsonConvert.SerializeObject(recentSongs);
            await songFile.WriteAllTextAsync(songsJsonString);
        }

        public async Task<Song[]> ReadRecentSongsFromFile()
        {
            IFile recentSongs = await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.OpenIfExists).ConfigureAwait(false);
            string songsJsonString = await recentSongs.ReadAllTextAsync();
            Song[] songsArray = JsonConvert.DeserializeObject<Song[]>(songsJsonString);
            return songsArray;
        }

        public async void AddRecentSearch(string searchTerm)
        {
            string[] recentSearches = await ReadRecentSearchesFromFile() ?? new string[10];
            recentSearches[9] = null;
            for (int i = 9; i > 0; i--)
            {
                recentSearches[i] = recentSearches[i - 1];
            }
            recentSearches[0] = searchTerm;
            IFile songFile = await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.OpenIfExists);
            string songsJsonString = JsonConvert.SerializeObject(recentSearches);
            await songFile.WriteAllTextAsync(songsJsonString);
        }

        public async Task<string[]> ReadRecentSearchesFromFile()
        {
            IFile recentSearches = await localFolder.CreateFileAsync(searchesFileName, CreationCollisionOption.OpenIfExists);
            string searchesJsonString = await recentSearches.ReadAllTextAsync();
            string[] searchesArray = JsonConvert.DeserializeObject<string[]>(searchesJsonString);
            return searchesArray;
        }

        public async void CreatePlaylist(Playlist playlist)
        {
            List<Playlist> playlists = await ReadPlaylistsFromFile()?? new List<Playlist>();
            playlists.Add(playlist);
            IFile playlistsFile = await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.OpenIfExists);
            string playlistsJsonString = JsonConvert.SerializeObject(playlists);
            await playlistsFile.WriteAllTextAsync(playlistsJsonString);
        }

        public async void RemovePlaylist(Playlist playlist)
        {
            List<Playlist> playlists = await ReadPlaylistsFromFile() ?? new List<Playlist>();
            Playlist playlistToRemove = playlists.Find(x => x == playlist);
            playlists.Remove(playlistToRemove);
            IFile playlistsFile = await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.OpenIfExists);
            string playlistsJsonString = JsonConvert.SerializeObject(playlists);
            await playlistsFile.WriteAllTextAsync(playlistsJsonString);
        }

        public async Task<List<Playlist>> ReadPlaylistsFromFile()
        {
            IFile playlists = await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.OpenIfExists);
            string playlistsString = await playlists.ReadAllTextAsync();
            List<Playlist> playlistList = JsonConvert.DeserializeObject<List<Playlist>>(playlistsString);
            return playlistList;
        }
    }
</code>```

And when it comes to the implementation, I've used both this by instantiating the class inside the page I'm using it:

```<code>public partial class MainPortrait : ContentView
    {
        Sections sections = new Sections();

        public string[] RecentSearches = new string[10];
        public string Search { get; set; }
        public MainPortrait()
        {
            InitializeComponent();
            BindingContext= this;
            sections.VerifySectionFiles();
            RecentSearches = sections.ReadRecentSearchesFromFile().Result;
            //Do stuff with returned string[]
        }
</code>```

And this, where I added it to the App.xaml.cs

```<code>public partial class MainPortrait : ContentView
    {
        public string[] RecentSearches = new string[10];
        public string Search { get; set; }
        public MainPortrait()
        {
            InitializeComponent();
            BindingContext= this;
            ((App)App.Current).sections.VerifySectionFiles();
            RecentSearches = ((App)App.Current).sections.ReadRecentSearchesFromFile().Result;
            //Do stuff with returned string[]
</code>```

and it had the same problem both times, so I'm assuming it's a problem with the function itself. And if that's the case, there is probably a similar problem with all the functions in the Section class.

Any ideas?

Body:
I've just implemented some localStorage functions in a class to a song lyrics app I'm developing and I think I'm calling it wrong in some way but not sure how. Either that or something is blocking the async function from completing.

Storage Class

public class Sections
    {
        readonly string searchesFileName = "RecentSearches.txt";
        readonly string songsFileName = "RecentSongs.txt";
        readonly string playlistFileName = "Playlists.txt";
        IFolder localFolder = FileSystem.Current.LocalStorage;

        public async void VerifySectionFiles()
        {
            ExistenceCheckResult searchFileExists = await localFolder.CheckExistsAsync(searchesFileName);
            if (searchFileExists != ExistenceCheckResult.FileExists)
            {
                await localFolder.CreateFileAsync(searchesFileName, CreationCollisionOption.FailIfExists);
            }
            ExistenceCheckResult songsFileExists = await localFolder.CheckExistsAsync(songsFileName);
            if (songsFileExists != ExistenceCheckResult.FileExists)
            {
                await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.FailIfExists);
            }
            ExistenceCheckResult playlistFileExists = await localFolder.CheckExistsAsync(playlistFileName);
            if (playlistFileExists != ExistenceCheckResult.FileExists)
            {
                await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.FailIfExists);
            }
        }

        public async void AddRecentSong(string title, int id, string artist)
        {
            Song[] recentSongs = await ReadRecentSongsFromFile() ?? new Song[10];
            recentSongs[9] = null;
            for (int i = 9; i > 0; i--)
            {
                recentSongs[i] = recentSongs[i - 1];
            }
            recentSongs[0] = new Song(title, artist, id);
            IFile songFile = await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.OpenIfExists);
            string songsJsonString = JsonConvert.SerializeObject(recentSongs);
            await songFile.WriteAllTextAsync(songsJsonString);
        }

        public async Task<Song[]> ReadRecentSongsFromFile()
        {
            IFile recentSongs = await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.OpenIfExists).ConfigureAwait(false);
            string songsJsonString = await recentSongs.ReadAllTextAsync();
            Song[] songsArray = JsonConvert.DeserializeObject<Song[]>(songsJsonString);
            return songsArray;
        }

        public async void AddRecentSearch(string searchTerm)
        {
            string[] recentSearches = await ReadRecentSearchesFromFile() ?? new string[10];
            recentSearches[9] = null;
            for (int i = 9; i > 0; i--)
            {
                recentSearches[i] = recentSearches[i - 1];
            }
            recentSearches[0] = searchTerm;
            IFile songFile = await localFolder.CreateFileAsync(songsFileName, CreationCollisionOption.OpenIfExists);
            string songsJsonString = JsonConvert.SerializeObject(recentSearches);
            await songFile.WriteAllTextAsync(songsJsonString);
        }

        public async Task<string[]> ReadRecentSearchesFromFile()
        {
            IFile recentSearches = await localFolder.CreateFileAsync(searchesFileName, CreationCollisionOption.OpenIfExists);
            string searchesJsonString = await recentSearches.ReadAllTextAsync();
            string[] searchesArray = JsonConvert.DeserializeObject<string[]>(searchesJsonString);
            return searchesArray;
        }

        public async void CreatePlaylist(Playlist playlist)
        {
            List<Playlist> playlists = await ReadPlaylistsFromFile()?? new List<Playlist>();
            playlists.Add(playlist);
            IFile playlistsFile = await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.OpenIfExists);
            string playlistsJsonString = JsonConvert.SerializeObject(playlists);
            await playlistsFile.WriteAllTextAsync(playlistsJsonString);
        }

        public async void RemovePlaylist(Playlist playlist)
        {
            List<Playlist> playlists = await ReadPlaylistsFromFile() ?? new List<Playlist>();
            Playlist playlistToRemove = playlists.Find(x => x == playlist);
            playlists.Remove(playlistToRemove);
            IFile playlistsFile = await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.OpenIfExists);
            string playlistsJsonString = JsonConvert.SerializeObject(playlists);
            await playlistsFile.WriteAllTextAsync(playlistsJsonString);
        }

        public async Task<List<Playlist>> ReadPlaylistsFromFile()
        {
            IFile playlists = await localFolder.CreateFileAsync(playlistFileName, CreationCollisionOption.OpenIfExists);
            string playlistsString = await playlists.ReadAllTextAsync();
            List<Playlist> playlistList = JsonConvert.DeserializeObject<List<Playlist>>(playlistsString);
            return playlistList;
        }
    }

And when it comes to the implementation, I've used both this by instantiating the class inside the page I'm using it:

public partial class MainPortrait : ContentView
    {
        Sections sections = new Sections();

        public string[] RecentSearches = new string[10];
        public string Search { get; set; }
        public MainPortrait()
        {
            InitializeComponent();
            BindingContext= this;
            sections.VerifySectionFiles();
            RecentSearches = sections.ReadRecentSearchesFromFile().Result;
            //Do stuff with returned string[]
        }

And this, where I added it to the App.xaml.cs

public partial class MainPortrait : ContentView
    {
        public string[] RecentSearches = new string[10];
        public string Search { get; set; }
        public MainPortrait()
        {
            InitializeComponent();
            BindingContext= this;
            ((App)App.Current).sections.VerifySectionFiles();
            RecentSearches = ((App)App.Current).sections.ReadRecentSearchesFromFile().Result;
            //Do stuff with returned string[]

and it had the same problem both times, so I'm assuming it's a problem with the function itself. And if that's the case, there is probably a similar problem with all the functions in the Section class.

Any ideas?


来源: stackexchange

问:
Possible to generate heatmaps using tflite models?
To save server space I convert keras models (h5) to tflite format and I'd like to create heatmaps / saliency maps with the tflite models. Its easy to create a heatmap with a keras model, but tflite I have not seen any examples. Is it possible to do this?</p>

ContentLicense: CC BY-SA 4.0


问:
googleapiclient Resource object's files() method
Following Google Drive API Python sample on this section, there's a line

```<code>file = service.files().create(...)
</code>```

The service is an instance of Resource returned from googleapiclient.discovery.build().

What confused me was this files() method is not a member of Resource class and surprisingly it works (though as shown in the sample code we need to disable pylint error explicitly).

If we inspect this mysterious service.files() method:

```<code>import inspect
print(inspect.getsource(service.files))
</code>```

It points to this in the Resource class definition. This is where I get lost. Could anyone help explain how it works?

Body:
Following Google Drive API Python sample on this section, there's a line

file = service.files().create(...)

The service is an instance of Resource returned from googleapiclient.discovery.build().

What confused me was this files() method is not a member of Resource class and surprisingly it works (though as shown in the sample code we need to disable pylint error explicitly).

If we inspect this mysterious service.files() method:

import inspect
print(inspect.getsource(service.files))

It points to this in the Resource class definition. This is where I get lost. Could anyone help explain how it works?


问:
"Sorry we could not fetch the image" Pinterest error even though Image is publicly accessible
I am not sure what the real issue is but my image is publicly accessible via a url similar to

https://storage.googleapis.com/myapp.appspot.com/IMAGES/ead253addf86583ba57b7265ad9c999ba437b9ded695ac4b5bce6d78ccfe0c1b.png?GoogleAccessId=firebase-adminsdk-pgu3n%myapp.iam.gserviceaccount.com&Expires=253376550000&Signature=JgJcZK4vhn3uKThzcouTx7Pm92LrXhHEjxfPbvbiFzCXyUKH%2FuXhsH1M4Jn8KpUgi8HJcHqBMk2E7VEvHqEmmWLYmeGhBaDakZUSLQVUFEqbbxxU0e5RvsKOz66%2BymVywII9rL02xkjy10Is6ZibkfnSTG2xkNQ5XCdLoctSowZtu7dKf6OvZN48xI3cAPwcQbHLZ3n12I3%2BCsVnDiUcq4mybzKmA9e8dyKPvjYOskhmc0hO3bb%2BokxWF8wsyZ%2BGn7sjCgrvnyow%2FpxWm%2BlLVtEsbOFDZRUgmWOzgHNgcriX5MCLDNSmwRuRVl4xZtU0tcnX7dDp7XDiQqxU%2BBj6hQ%3D%3D

However whenever I submit the image url to pinterest api via the following request body:

```<code> requestBody['media_source'] = {
                source_type: 'image_url',
                url: mediaUrl
 }
</code>```

I keep getting back the following error message:

```<code>{
  "code": 1,
  "message": "Sorry we could not fetch the image."
}
</code>```

But the url is very much accessible by anyone so why is pinterest unable to get this image.

It's really weird.

Please help.

Body:
I am not sure what the real issue is but my image is publicly accessible via a url similar to

<a href="https://storage.googleapis.com/myapp.appspot.com/IMAGES/ead253addf86583ba57b7265ad9c999ba437b9ded695ac4b5bce6d78ccfe0c1b.png?GoogleAccessId=firebase-adminsdk-pgu3n%myapp.iam.gserviceaccount.com&Expires=253376550000&Signature=JgJcZK4vhn3uKThzcouTx7Pm92LrXhHEjxfPbvbiFzCXyUKH%2FuXhsH1M4Jn8KpUgi8HJcHqBMk2E7VEvHqEmmWLYmeGhBaDakZUSLQVUFEqbbxxU0e5RvsKOz66%2BymVywII9rL02xkjy10Is6ZibkfnSTG2xkNQ5XCdLoctSowZtu7dKf6OvZN48xI3cAPwcQbHLZ3n12I3%2BCsVnDiUcq4mybzKmA9e8dyKPvjYOskhmc0hO3bb%2BokxWF8wsyZ%2BGn7sjCgrvnyow%2FpxWm%2BlLVtEsbOFDZRUgmWOzgHNgcriX5MCLDNSmwRuRVl4xZtU0tcnX7dDp7XDiQqxU%2BBj6hQ%3D%3D" rel="nofollow noreferrer">https://storage.googleapis.com/myapp.appspot.com/IMAGES/ead253addf86583ba57b7265ad9c999ba437b9ded695ac4b5bce6d78ccfe0c1b.png?GoogleAccessId=firebase-adminsdk-pgu3n%myapp.iam.gserviceaccount.com&Expires=253376550000&Signature=JgJcZK4vhn3uKThzcouTx7Pm92LrXhHEjxfPbvbiFzCXyUKH%2FuXhsH1M4Jn8KpUgi8HJcHqBMk2E7VEvHqEmmWLYmeGhBaDakZUSLQVUFEqbbxxU0e5RvsKOz66%2BymVywII9rL02xkjy10Is6ZibkfnSTG2xkNQ5XCdLoctSowZtu7dKf6OvZN48xI3cAPwcQbHLZ3n12I3%2BCsVnDiUcq4mybzKmA9e8dyKPvjYOskhmc0hO3bb%2BokxWF8wsyZ%2BGn7sjCgrvnyow%2FpxWm%2BlLVtEsbOFDZRUgmWOzgHNgcriX5MCLDNSmwRuRVl4xZtU0tcnX7dDp7XDiQqxU%2BBj6hQ%3D%3D

However whenever I submit the image url to pinterest api via the following request body:

 requestBody['media_source'] = {
                source_type: 'image_url',
                url: mediaUrl
 }

I keep getting back the following error message:

{
  "code": 1,
  "message": "Sorry we could not fetch the image."
}

But the url is very much accessible by anyone so why is pinterest unable to get this image.

It's really weird.

Please help.


问:
Is there a way to set a default separatorin exporting a phpMyadmin database to csv?
I need to export several of my tables to Excel, which I can do via the export > CSV for MS Excel function. But the file created uses a semicolon ';' as the field separator...but Excel needs a comma ','.

Is there a way to change/set the default to the comma?


问:
Django - Get specific columns with get_object_or_404()
Is there a way to only get specific columns from the database using the get_object_or_404()?

This is my query for getting the thesis information from my database. But I only want to return the title , author, and published date instead of all the columns from that specific thesis.

```<code>details =  get_object_or_404(thesisDB, slug=slug, published_status='Approved')
</code>```

Body:
Is there a way to only get specific columns from the database using the get_object_or_404()?

This is my query for getting the thesis information from my database. But I only want to return the title , author, and published date instead of all the columns from that specific thesis.

details =  get_object_or_404(thesisDB, slug=slug, published_status='Approved')


问:
Password field does not migrate to db in Django
I have my user app with the following fields in its models.py file:

```<code>from django.db import models
from django import forms
# Create your models here.

class User (models.Model):
    name=models.CharField(max_length=50, verbose_name='Name')
    surname=models.CharField(max_length=50, verbose_name='Surname')
    username=models.CharField(max_length=50, unique=True, verbose_name='Username')
    password=forms.CharField(widget=forms.PasswordInput())
    email=models.EmailField(unique=True, verbose_name='Email')
</code>```

When I do the migrations with python manage.py makemigrations does not migrate the password field, am I defining it wrong with form.CharField?

Body:
I have my user app with the following fields in its models.py file:

from django.db import models
from django import forms
# Create your models here.

class User (models.Model):
    name=models.CharField(max_length=50, verbose_name='Name')
    surname=models.CharField(max_length=50, verbose_name='Surname')
    username=models.CharField(max_length=50, unique=True, verbose_name='Username')
    password=forms.CharField(widget=forms.PasswordInput())
    email=models.EmailField(unique=True, verbose_name='Email')

When I do the migrations with python manage.py makemigrations does not migrate the password field, am I defining it wrong with form.CharField?


问:
Vercel 404 page on deployment
I am trying to deploy a website to Vercel, and am having trouble with the build step and even when successfully deployed. I was getting the error "No Output Directory named "build" found after the Build completed" repeatedly, so I went in the settings and set Output Directory to '.next' and it started to deploy but now I get a 404 message at the domain. Im wondering if I have something wrong with my package.json, file structure, or idk.

Here is my package.json:

```<code>{
  "name": "portfolio-website",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "npx next dev",
    "build": "npx next build",
    "start": "npx next start"
  },
  "dependencies": {
    "@glidejs/glide": "3.5.2",
    "@next/font": "^13.0.6",
    "@types/react": "^18.0.20",
    "@types/react-dom": "^18.0.6",
    "next": "^13.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.0",
    "rollup": "^2.79.1",
    "sass": "^1.54.9"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^2.1.0",
    "vite": "^3.1.0"
  },
  "engines": {
    "node": "^18.12.1"
  }
}
</code>```

File structure:

Build log:

```<code>> portfolio-website@0.0.0 build
> npx next build
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Linting and checking validity of types...
info  - Creating an optimized production build...
info  - Compiled successfully
info  - Collecting page data...
info  - Generating static pages (0/3)
undefined
info  - Generating static pages (3/3)
info  - Finalizing page optimization...
Route (pages)                              Size     First Load JS
┌ ○ /                                      6.43 kB        79.6 kB
├   /_app                                  0 B            73.2 kB
└ ○ /404                                   181 B          73.4 kB
+ First Load JS shared by all              76.2 kB
  ├ chunks/framework-3b5a00d5d7e8d93b.js   45.4 kB
  ├ chunks/main-11be7a5831576890.js        26.7 kB
  ├ chunks/pages/_app-f8a9334f900a3d86.js  330 B
  ├ chunks/webpack-8fa1640cc84ba8fe.js     750 B
  └ css/53250905108bb3d4.css               2.98 kB
○  (Static)  automatically rendered as static HTML (uses no initial props)
Build Completed in /vercel/output [17s]
Generated build outputs:
 - Static files: 113
 - Serverless Functions: 0
 - Edge Functions: 0
Deployed outputs in 1s
Build completed. Populating build cache...
Uploading build cache [57.27 MB]...
Build cache uploaded: 1.698s
Done with "."
</code>```

and I have my Vercel settings as:

Title: Vercel 404 page on deployment

Body:
I am trying to deploy a website to Vercel, and am having trouble with the build step and even when successfully deployed. I was getting the error "No Output Directory named "build" found after the Build completed" repeatedly, so I went in the settings and set Output Directory to '.next' and it started to deploy but now I get a 404 message at the domain. Im wondering if I have something wrong with my package.json, file structure, or idk.

Here is my package.json:

{
  "name": "portfolio-website",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "npx next dev",
    "build": "npx next build",
    "start": "npx next start"
  },
  "dependencies": {
    "@glidejs/glide": "3.5.2",
    "@next/font": "^13.0.6",
    "@types/react": "^18.0.20",
    "@types/react-dom": "^18.0.6",
    "next": "^13.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.0",
    "rollup": "^2.79.1",
    "sass": "^1.54.9"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^2.1.0",
    "vite": "^3.1.0"
  },
  "engines": {
    "node": "^18.12.1"
  }
}

File structure:

Build log:

> portfolio-website@0.0.0 build
> npx next build
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Linting and checking validity of types...
info  - Creating an optimized production build...
info  - Compiled successfully
info  - Collecting page data...
info  - Generating static pages (0/3)
undefined
info  - Generating static pages (3/3)
info  - Finalizing page optimization...
Route (pages)                              Size     First Load JS
┌ ○ /                                      6.43 kB        79.6 kB
├   /_app                                  0 B            73.2 kB
└ ○ /404                                   181 B          73.4 kB
+ First Load JS shared by all              76.2 kB
  ├ chunks/framework-3b5a00d5d7e8d93b.js   45.4 kB
  ├ chunks/main-11be7a5831576890.js        26.7 kB
  ├ chunks/pages/_app-f8a9334f900a3d86.js  330 B
  ├ chunks/webpack-8fa1640cc84ba8fe.js     750 B
  └ css/53250905108bb3d4.css               2.98 kB
○  (Static)  automatically rendered as static HTML (uses no initial props)
Build Completed in /vercel/output [17s]
Generated build outputs:
 - Static files: 113
 - Serverless Functions: 0
 - Edge Functions: 0
Deployed outputs in 1s
Build completed. Populating build cache...
Uploading build cache [57.27 MB]...
Build cache uploaded: 1.698s
Done with "."

and I have my Vercel settings as:


问:
Bootstrap like training to LSTM model
I have a dataset of size 273985 x 5 that I'm training as a path prediction problem. I chose an LSTM inspired by this paper: https://ieeexplore.ieee.org/abstract/document/9225479

I have a baseline implementation as such:

```<code># lstm autoencoder recreate sequence
from numpy import array
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import RepeatVector
from keras.callbacks import EarlyStopping
from keras.layers import TimeDistributed
from keras.utils import plot_model

# define input sequence
my_sequence = np.array(sample)

# reshape input into [samples, timesteps, features]
n_in = len(my_sequence)
my_sequence = my_sequence.reshape((1, n_in, 5))

# define model
model = Sequential()
model.add(LSTM(10, activation='sigmoid', input_shape=(n_in,5)))
model.add(RepeatVector(n_in))
model.add(LSTM(10, activation='sigmoid', return_sequences=True))
model.add(TimeDistributed(Dense(5)))
model.compile(optimizer='adam', loss='mse')

# fit model
model.fit(my_sequence, my_sequence, epochs=300, verbose=0)

# structure of the model and the layers
plot_model(model, show_shapes=True, to_file=path)

# demonstrate recreation
predicted = model.predict(my_sequence, verbose=0)

print(predicted)
print(my_sequence)
</code>```

Right now, I am choosing my training sample by hand but I want to train my entire dataset much like bootstrapping where I train 1-50, predict the next 50; train 2-50, predict the next 50… until the end of the test set then compare my prediction against the actual values.

Would this be done via batching the data or k-fold validation? Also, how would one go about it or calculate the appropriate evaluation metric?

Thank you!

Title: Bootstrap like training to LSTM model

Body:
I have a dataset of size 273985 x 5 that I'm training as a path prediction problem. I chose an LSTM inspired by this paper: https://ieeexplore.ieee.org/abstract/document/9225479

I have a baseline implementation as such:

# lstm autoencoder recreate sequence
from numpy import array
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import RepeatVector
from keras.callbacks import EarlyStopping
from keras.layers import TimeDistributed
from keras.utils import plot_model

# define input sequence
my_sequence = np.array(sample)

# reshape input into [samples, timesteps, features]
n_in = len(my_sequence)
my_sequence = my_sequence.reshape((1, n_in, 5))

# define model
model = Sequential()
model.add(LSTM(10, activation='sigmoid', input_shape=(n_in,5)))
model.add(RepeatVector(n_in))
model.add(LSTM(10, activation='sigmoid', return_sequences=True))
model.add(TimeDistributed(Dense(5)))
model.compile(optimizer='adam', loss='mse')

# fit model
model.fit(my_sequence, my_sequence, epochs=300, verbose=0)

# structure of the model and the layers
plot_model(model, show_shapes=True, to_file=path)

# demonstrate recreation
predicted = model.predict(my_sequence, verbose=0)

print(predicted)
print(my_sequence)

Right now, I am choosing my training sample by hand but I want to train my entire dataset much like bootstrapping where I train 1-50, predict the next 50; train 2-50, predict the next 50… until the end of the test set then compare my prediction against the actual values.

Would this be done via batching the data or k-fold validation? Also, how would one go about it or calculate the appropriate evaluation metric?

Thank you!


问:
How to set a password to protect a directory and its contents in unix?
May I know how to set a password to protect a directory and its contents in unix? Eg. It will prompt user to type in a password to access the directory.

I tried to do it with enfs:

```<code>mkdir ~/.encrypted ~/encrypted
encfs ~/.encrypted ~/encrypted
</code>```

And but it shows "encfs: command not found".

Body:
May I know how to set a password to protect a directory and its contents in unix? Eg. It will prompt user to type in a password to access the directory.

I tried to do it with enfs:

mkdir ~/.encrypted ~/encrypted
encfs ~/.encrypted ~/encrypted

And but it shows "encfs: command not found".


问:
gitlab CI config
After I upgraded gitlab yesterday, my gitlab-ci.yml file reported an error

The error message is jobs:gitkeep:only configshould be an array of strings or regexps

My config file content is

gitkeep:
  stage: eslint
  tags:
    - chore
  only:
    - develop
    - /^feature\/((?!snapshot$|latest$|release\/).)+?$/
    - /^release\/((?!snapshot$|latest$).)+?$/
    - /^dev\/((?!snapshot$|latest$).)+?$/
  script:
    - docker build -t mdf-modify-all .
    - docker run --cpus="2.5" --rm mdf-modify-all sh -c "sh release-all.sh && git add . && git commit -m 'release all' && git push origin HEAD:$CI_COMMIT_REF_NAME"
  when: manual

```

In some online verification tools, these configurations are legal. But in CI lint, it prompts that the regularity is illegal. How can I modify this regularity?

After I delete this regular expression, the verification is passed, but I want to keep this regular expression, how can I modify it?

Title: gitlab CI config

Body:
After I upgraded gitlab yesterday, my gitlab-ci.yml file reported an error

The error message is jobs:gitkeep:only configshould be an array of strings or regexps

My config file content is

gitkeep:
  stage: eslint
  tags:
    - chore
  only:
    - develop
    - /^feature\/((?!snapshot$|latest$|release\/).)+?$/
    - /^release\/((?!snapshot$|latest$).)+?$/
    - /^dev\/((?!snapshot$|latest$).)+?$/
  script:
    - docker build -t mdf-modify-all .
    - docker run --cpus="2.5" --rm mdf-modify-all sh -c "sh release-all.sh && git add . && git commit -m 'release all' && git push origin HEAD:$CI_COMMIT_REF_NAME"
  when: manual

In some online verification tools, these configurations are legal. But in CI lint, it prompts that the regularity is illegal. How can I modify this regularity?

After I delete this regular expression, the verification is passed, but I want to keep this regular expression, how can I modify it?


问:
Typescript with Express: Received a ts(7053) error message when trying to access data from req.body
I am trying to write an express application with Typescript. The problem is that I having trouble assigning the data property from req.body to posts. When I hoover over posts of posts[id] in the if statement, I received the message ts(7053). I receive the same message for id as well. Ditto for const post:postType = posts[postId];.

Following from the 7053 error, I get a ts(2339) error message on post.comments.push({id,content}) . Where I can not access the comments property of post even through I have given it a type of postType.

```<code>import express from 'express';
import cors from 'cors';

const port = 4002;
const app = express();
app.use(express.json());
app.use(cors);

type comment = {
  id: string;
  content: string;
  postid: string;
};

type postType =
  | {
      id: string;
      title: string;
      comments: comment[];
    }
  | {};

const posts: postType = {};

app.get('/post', (req, res) => {});

app.post('/events', (req, res) => {
  const { type, data } = req.body;

  if (type === 'POSTCREATED') {
    const { id, title } = data;
    posts[id] = { id, title, comments: [] };
    // Receiving an error message: **Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}
  }
  if (type === 'COMMENTCREATED') {
    const { id, content, postId } = data;

    const post: postType = posts[postId];
    // Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}'.
    post.
    //Property 'comments' does not exist on type 'postType'. Property 'comments' does not exist on type '{}'
  }
});

app.listen(port, () => {
  console.log(`Listening on port ${port}.`);
});

</code>```

Obviously, I was expecting no errors. I tried adding an index signature and that didn't worked. But that lead to a different set of problems that made it more complicated. So I reverted the code.

Body:
I am trying to write an express application with Typescript. The problem is that I having trouble assigning the data property from req.body to posts. When I hoover over posts of posts[id] in the if statement, I received the message ts(7053). I receive the same message for id as well. Ditto for const post:postType = posts[postId];.

Following from the 7053 error, I get a ts(2339) error message on post.comments.push({id,content}) . Where I can not access the comments property of post even through I have given it a type of postType.

import express from 'express';
import cors from 'cors';

const port = 4002;
const app = express();
app.use(express.json());
app.use(cors);

type comment = {
  id: string;
  content: string;
  postid: string;
};

type postType =
  | {
      id: string;
      title: string;
      comments: comment[];
    }
  | {};

const posts: postType = {};

app.get('/post', (req, res) => {});

app.post('/events', (req, res) => {
  const { type, data } = req.body;

  if (type === 'POSTCREATED') {
    const { id, title } = data;
    posts[id] = { id, title, comments: [] };
    // Receiving an error message: **Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}
  }
  if (type === 'COMMENTCREATED') {
    const { id, content, postId } = data;

    const post: postType = posts[postId];
    // Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}'.
    post.
    //Property 'comments' does not exist on type 'postType'. Property 'comments' does not exist on type '{}'
  }
});

app.listen(port, () => {
  console.log(`Listening on port ${port}.`);
});

Obviously, I was expecting no errors. I tried adding an index signature and that didn't worked. But that lead to a different set of problems that made it more complicated. So I reverted the code.


问:
Supabase JWTs and onAuthStateChange()
I don't understand the difference between onAuthStateChange() vs usng JWTs for Supabase. My goal is to check if a user is currently logged into an app, so i don't have to present them with the login screen every time they open the app.
Which is more suited for what I want to do?</p>

Title: Supabase JWTs and onAuthStateChange()


问:
Excel Report using Python
I have one excel sheet WSR.xlxs where I Need to filter data and create a new sheet as below:

where Sprint Name should be a dropdown. And if I click on any of the sprint name element from dropdown it should give the data below the  ticket closed from WSR.xls (sprint column)

enter image description here

```<code>import xlsxwriter
import pandas as pd
from datetime import date, time
from openpyxl.workbook import Workbook
import math

#import config
"""
def ignore_nan(worksheet_obj, row, col, number, format=None):
    if math.isnan(number):
        return worksheet.write_blank(row, col, None, format)
    else:
        # Return control to the calling write() method for any other number.
        return None

"""
df = pd.read_excel('C:/Users/asing134/python_workspace/sprintReport/WSR.xlsx',sheet_name=0)
status = df['Status'].tolist()
sprint = df['Sprint'].tolist()
sprint_var = list( dict.fromkeys(sprint) )
workbook = xlsxwriter.Workbook("C:/Users/asing134/python_workspace/sprintReport/sprintClosureReport.xlsx")
cell_format = workbook.add_format()
cell_format.set_text_wrap()
worksheet_obj = workbook.add_worksheet()
#worksheet_obj.add_write_handler(float, ignore_nan)

fields = ["Year","Week Number","Sprint Name","Start Date","End Date","Tickets Closed"]
col = 0
row = 0
for field in fields:
    worksheet_obj.write(row, col, field, cell_format)
    row += 1

worksheet_obj.data_validation('B1', {'validate': 'list',
                                  'source': ['2016','2017','2018','2019','2020','2021','2022','2023','2024','2025']})

worksheet_obj.data_validation('B2', {'validate': 'list',
                                  'source': ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52']})

worksheet_obj.data_validation('B3',{'validate': 'list',
                                  'source': sprint_var[:18]})
</code>```

workbook.close()

Title: Excel Report using Python

Body:
I have one excel sheet WSR.xlxs where I Need to filter data and create a new sheet as below:

where Sprint Name should be a dropdown. And if I click on any of the sprint name element from dropdown it should give the data below the  ticket closed from WSR.xls (sprint column)

enter image description here

import xlsxwriter
import pandas as pd
from datetime import date, time
from openpyxl.workbook import Workbook
import math

#import config
"""
def ignore_nan(worksheet_obj, row, col, number, format=None):
    if math.isnan(number):
        return worksheet.write_blank(row, col, None, format)
    else:
        # Return control to the calling write() method for any other number.
        return None

"""
df = pd.read_excel('C:/Users/asing134/python_workspace/sprintReport/WSR.xlsx',sheet_name=0)
status = df['Status'].tolist()
sprint = df['Sprint'].tolist()
sprint_var = list( dict.fromkeys(sprint) )
workbook = xlsxwriter.Workbook("C:/Users/asing134/python_workspace/sprintReport/sprintClosureReport.xlsx")
cell_format = workbook.add_format()
cell_format.set_text_wrap()
worksheet_obj = workbook.add_worksheet()
#worksheet_obj.add_write_handler(float, ignore_nan)

fields = ["Year","Week Number","Sprint Name","Start Date","End Date","Tickets Closed"]
col = 0
row = 0
for field in fields:
    worksheet_obj.write(row, col, field, cell_format)
    row += 1

worksheet_obj.data_validation('B1', {'validate': 'list',
                                  'source': ['2016','2017','2018','2019','2020','2021','2022','2023','2024','2025']})

worksheet_obj.data_validation('B2', {'validate': 'list',
                                  'source': ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52']})

worksheet_obj.data_validation('B3',{'validate': 'list',
                                  'source': sprint_var[:18]})

workbook.close()


问:
Authorize based on field value in another document in AppSync GraphQL custom authentication via Lambda Resolver
I am new to Amplify Datastore & AppSync w/ GraphQL, but in Firestore, you can write an auth rule like: allow delete: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true [https://firebase.google.com/docs/firestore/security/rules-conditions#access_other_documents] -> which would grab the document at /users/{id}/ and I can access the admin field to write a security rule logic.

How do you do the same in a Lambda function resolver?

I am aware that the solution may involve a Lambda resolver (https://stackoverflow.com/a/68581796/9824103) but I cannot find any reference to reading a specific document and doing logic to authorize or deny an operation based on a field value in a document. I am only asking how to do this specific thing. Thank you!

I followed https://docs.amplify.aws/cli/graphql/authorization-rules/#custom-authorization-rule to create a custom authorization rule via adding the @rule directive: type MyModel @model @auth(rules: [{ allow: custom }]) and.. although the lambda function isn't really getting called when I try to write a listMyModel or createMyModel (any hints as to why that would be great), I am focused on writing the lambda function to read query a document and check a certain field to meet my custom auth condition.

fyi, I am using Flutter based amplify-cli.


问:
How to fix "invalid integration variable or limit(s) in Null"?
I'm trying to make a table of elements for a double numerical integraql for the function "N[CurlyPhi]0"

```<code>G1[r1_, r_, L_, \[CurlyPhi]0_] :=
 2 Sqrt[r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0]] -
  2 Sqrt[r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0] + L^2] -
  L Log[1 + (
     2 L (L - Sqrt[r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0] + L^2]))/(
     r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0])]
</code>```
```<code>G2[r1_, r_, L_] :=
  2 r r1 (-Sqrt[L^2 + (r - r1)^2] + Sqrt[(r - r1)^2] +
     L ArcTanh[L/Sqrt[L^2 + (r - r1)^2]])
</code>```

and

```<code>a3 = 8000;
b3 = 15000;
N\[CurlyPhi]0[a0_, b0_, \[CurlyPhi]0_, L_] := (
  1/(\[Pi] (\[CurlyPhi]0 (b0^2 - a0^2) L) ))
   NIntegrate[
   G2[r1, r, L] - G1[r1, r, L, \[CurlyPhi]0], {r, a0, b0}, {r1, a0, r,
     b0}, MinRecursion -> 9, MaxRecursion -> 40,
   Method -> {"GlobalAdaptive",
     "MaxErrorIncreases" ->
      100000}]

</code>```

I tried to make the table this way (I have use this same code before for another function)

```<code>N\[CurlyPhi]0vsLat\[CurlyPhi]0Dat =
 ParallelTable[{L, N\[CurlyPhi]0[a3, b3, (10 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (30 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (60 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (90 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (120 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (150 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, \[Pi], L 10^3],
   N\[CurlyPhi]0[a3, b3, (210 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (240 \[Pi])/180, L 10^3]}, {L, 1, 100, 2}]
</code>```

But I get this error message and Idk how to fix this so I can generate the table :
NIntegrate:The integrand (...) has evaluated to Overflow, Indeterminate, or Infinity for all

sampling points in the region with boundaries(...)

Body:
I'm trying to make a table of elements for a double numerical integraql for the function "N[CurlyPhi]0"

G1[r1_, r_, L_, \[CurlyPhi]0_] :=
 2 Sqrt[r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0]] -
  2 Sqrt[r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0] + L^2] -
  L Log[1 + (
     2 L (L - Sqrt[r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0] + L^2]))/(
     r^2 + r1^2 - 2 r r1 Cos[\[CurlyPhi]0])]

G2[r1_, r_, L_] :=
  2 r r1 (-Sqrt[L^2 + (r - r1)^2] + Sqrt[(r - r1)^2] +
     L ArcTanh[L/Sqrt[L^2 + (r - r1)^2]])

and

a3 = 8000;
b3 = 15000;
N\[CurlyPhi]0[a0_, b0_, \[CurlyPhi]0_, L_] := (
  1/(\[Pi] (\[CurlyPhi]0 (b0^2 - a0^2) L) ))
   NIntegrate[
   G2[r1, r, L] - G1[r1, r, L, \[CurlyPhi]0], {r, a0, b0}, {r1, a0, r,
     b0}, MinRecursion -> 9, MaxRecursion -> 40,
   Method -> {"GlobalAdaptive",
     "MaxErrorIncreases" ->
      100000}]

I tried to make the table this way (I have use this same code before for another function)

N\[CurlyPhi]0vsLat\[CurlyPhi]0Dat =
 ParallelTable[{L, N\[CurlyPhi]0[a3, b3, (10 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (30 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (60 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (90 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (120 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (150 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, \[Pi], L 10^3],
   N\[CurlyPhi]0[a3, b3, (210 \[Pi])/180, L 10^3],
   N\[CurlyPhi]0[a3, b3, (240 \[Pi])/180, L 10^3]}, {L, 1, 100, 2}]

But I get this error message and Idk how to fix this so I can generate the table :
NIntegrate:The integrand (...) has evaluated to Overflow, Indeterminate, or Infinity for all

sampling points in the region with boundaries(...)


问:
Is there a way to permanently store eststo?
My Stata code is complicated that it has many clear all commands.

Is it possible to store eststo so that it does not wiped out by clear command?

I want those stored eststo to use later.


问:
Reaflow - Panning issue
I am using reaflow to create flowcharts but I am facing some issue with panning. the library contains an attribute which enables panning but their panning is not what I thought it to be. For me , panning is something with which I can move the flowchart by clicking somewhere on the canvas and moving the cursor but I am not able to do that.

To overcome this I started using react-zoom-pan-pinch library but that is not working for me. basically It is getting out of the viewport.

Please refer my code

```<code>import React from 'react';
import { Canvas } from 'reaflow';
import { TransformWrapper, TransformComponent } from 'react-zoom-pan-pinch'

export function App(props) {
  return (
    <div className='App' style={{ height: 400, width: 700, position: 'relative', background: 'white' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
        <TransformWrapper>
          <TransformComponent>
            <Canvas
              nodes={[
                {
                  id: '1',
                  text: '1'
                },
                {
                  id: '2',
                  text: '2'
                },
                {
                  id: '3',
                  text: '3'
                },
                {
                  id: '4',
                  text: '4'
                }
              ]}
              edges={[
                {
                  id: '1-2',
                  from: '1',
                  to: '2'
                },
                {
                  id: '1-3',
                  from: '1',
                  to: '3'
                },
                {
                  id: '2-3',
                  from: '2',
                  to: '3'
                },
                {
                  id: '3-4',
                  from: '3',
                  to: '4'
                }
              ]}
            />
          </TransformComponent>
        </TransformWrapper>
      </div>
    </div>
  );
}
</code>```

Title: Reaflow - Panning issue

Body:
I am using reaflow to create flowcharts but I am facing some issue with panning. the library contains an attribute which enables panning but their panning is not what I thought it to be. For me , panning is something with which I can move the flowchart by clicking somewhere on the canvas and moving the cursor but I am not able to do that.

To overcome this I started using react-zoom-pan-pinch library but that is not working for me. basically It is getting out of the viewport.

Please refer my code

import React from 'react';
import { Canvas } from 'reaflow';
import { TransformWrapper, TransformComponent } from 'react-zoom-pan-pinch'

export function App(props) {
  return (

        <TransformWrapper>
          <TransformComponent>
            <Canvas
              nodes={[
                {
                  id: '1',
                  text: '1'
                },
                {
                  id: '2',
                  text: '2'
                },
                {
                  id: '3',
                  text: '3'
                },
                {
                  id: '4',
                  text: '4'
                }
              ]}
              edges={[
                {
                  id: '1-2',
                  from: '1',
                  to: '2'
                },
                {
                  id: '1-3',
                  from: '1',
                  to: '3'
                },
                {
                  id: '2-3',
                  from: '2',
                  to: '3'
                },
                {
                  id: '3-4',
                  from: '3',
                  to: '4'
                }
              ]}
            />
          </TransformComponent>
        </TransformWrapper>

  );
}


问:
How to update values in QTableView
I have a QTableView which gets its data from QAbstractTableModel and is a 2d array. Below the TableView I have two comboboxes. User first selects the row in the TableView. Now I want that when the user selects an option from the combobox, I want the selected option to update the display in the TableView selection.

Shown below is the UI. For example if the User Selects REF DES in the class combo box I want the selected row to update its class name to REF DES.

I am using c++ qt5. How do I achieve this with signals and slots?

enter image description here

Currently I have a slot that updates the combobox values based on my selection in tableview. I use something like this.

```<code>void GetOptionsClass::slotSelectionChange(const QItemSelection&, const QItemSelection&)
{
    int rowidx = ui->line_tableView->selectionModel()->currentIndex().row();
    data = model->index(rowidx, 2).data().toString();

    if (data == "BOARD GEOMETRY") {
        ui->lineSubclass->clear();
        ui->lineSubclass->addItems(board_geometry_opts);
        ui->lineClass->setCurrentIndex(0);
    }
</code>```

However I want to reverse this. Meaning when I change combobox I want to update the qtableview.

Title: How to update values in QTableView

Body:
I have a QTableView which gets its data from QAbstractTableModel and is a 2d array. Below the TableView I have two comboboxes. User first selects the row in the TableView. Now I want that when the user selects an option from the combobox, I want the selected option to update the display in the TableView selection.

Shown below is the UI. For example if the User Selects REF DES in the class combo box I want the selected row to update its class name to REF DES.

I am using c++ qt5. How do I achieve this with signals and slots?

enter image description here

Currently I have a slot that updates the combobox values based on my selection in tableview. I use something like this.

void GetOptionsClass::slotSelectionChange(const QItemSelection&, const QItemSelection&)
{
    int rowidx = ui->line_tableView->selectionModel()->currentIndex().row();
    data = model->index(rowidx, 2).data().toString();

    if (data == "BOARD GEOMETRY") {
        ui->lineSubclass->clear();
        ui->lineSubclass->addItems(board_geometry_opts);
        ui->lineClass->setCurrentIndex(0);
    }

However I want to reverse this. Meaning when I change combobox I want to update the qtableview.


问:
ModuleNotFoundError: No module named 'flask_sqlalchemy'
I am looking to remove this error from my project. I recently did an install of flask_sqlalchemy in my .venv file. I am using python3.11, insomnia, docker, flask, flask_smorest and flask_sqlalchemy.

After looking through documentation I see that this error usually occurs when the wrong version is installed. I am not sure how to troubleshoot this issue. Any help would be appreciated as I have removed and readded flask-sqlalchemy on my .venv which didn't fix the issue.

Here is my .venv libs

I added sql-alchemy and flask-sqlalchemy into my requirements.txt file which looks like this:
`

```<code>flask
flask-smorest
python-dotenv
sqlalchemy
flask-sqlalchemy
</code>```

`
I received this response when I installed my requirements.txt

`

```<code>pip install -r requirements.txt
Requirement already satisfied: flask in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 1)) (2.2.2)
Requirement already satisfied: flask-smorest in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 2)) (0.40.0)
Requirement already satisfied: python-dotenv in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 3)) (0.21.0)
Requirement already satisfied: sqlalchemy in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 4)) (1.4.44)
Collecting flask-sqlalchemy
  Using cached Flask_SQLAlchemy-3.0.2-py3-none-any.whl (24 kB)
Requirement already satisfied: Werkzeug>=2.2.2 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (2.2.2)
Requirement already satisfied: Jinja2>=3.0 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (3.1.2)
Requirement already satisfied: itsdangerous>=2.0 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (2.1.2)
Requirement already satisfied: click>=8.0 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (8.1.3)
Requirement already satisfied: marshmallow<4,>=3.18.0 in ./.venv/lib/python3.11/site-packages (from flask-smorest->-r requirements.txt (line 2)) (3.19.0)
Requirement already satisfied: webargs<9,>=8.0.0 in ./.venv/lib/python3.11/site-packages (from flask-smorest->-r requirements.txt (line 2)) (8.2.0)
Requirement already satisfied: apispec[marshmallow]<7,>=6.0.0 in ./.venv/lib/python3.11/site-packages (from flask-smorest->-r requirements.txt (line 2)) (6.0.2)
Requirement already satisfied: greenlet!=0.4.17 in ./.venv/lib/python3.11/site-packages (from sqlalchemy->-r requirements.txt (line 4)) (2.0.1)
Requirement already satisfied: packaging>=21.3 in ./.venv/lib/python3.11/site-packages (from apispec[marshmallow]<7,>=6.0.0->flask-smorest->-r requirements.txt (line 2)) (21.3)
Requirement already satisfied: MarkupSafe>=2.0 in ./.venv/lib/python3.11/site-packages (from Jinja2>=3.0->flask->-r requirements.txt (line 1)) (2.1.1)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in ./.venv/lib/python3.11/site-packages (from packaging>=21.3->apispec[marshmallow]<7,>=6.0.0->flask-smorest->-r requirements.txt (line 2)) (3.0.9)
Installing collected packages: flask-sqlalchemy
Successfully installed flask-sqlalchemy-3.0.2
(.venv)  valemich@Vals-iMac  ~/Desktop/code/src/courses/udemy REST APIs with FlaskPython  pip --version

pip 22.3.1 from /Users/valemich/Desktop/code/src/courses/udemy REST APIs with FlaskPython/.venv/lib/python3.11/site-packages/pip (python 3.11)
(.venv)  valemich@Vals-iMac  ~/Desktop/code/src/courses/udemy REST APIs with FlaskPython  pip uninstall flask-sqlalchemy
Found existing installation: Flask-SQLAlchemy 3.0.2
Uninstalling Flask-SQLAlchemy-3.0.2:
  Would remove:
    /Users/valemich/Desktop/code/src/courses/udemy REST APIs with FlaskPython/.venv/lib/python3.11/site-packages/Flask_SQLAlchemy-3.0.2.dist-info/*
    /Users/valemich/Desktop/code/src/courses/udemy REST APIs with FlaskPython/.venv/lib/python3.11/site-packages/flask_sqlalchemy/*
Proceed (Y/n)? y
  Successfully uninstalled Flask-SQLAlchemy-3.0.2
(.venv)  valemich@Vals-iMac  ~/Desktop/code/src/courses/udemy REST APIs with FlaskPython  pip3 install flask_sqlalchemy
Collecting flask_sqlalchemy
  Using cached Flask_SQLAlchemy-3.0.2-py3-none-any.whl (24 kB)
Requirement already satisfied: Flask>=2.2 in ./.venv/lib/python3.11/site-packages (from flask_sqlalchemy) (2.2.2)
Requirement already satisfied: SQLAlchemy>=1.4.18 in ./.venv/lib/python3.11/site-packages (from flask_sqlalchemy) (1.4.44)
Requirement already satisfied: Werkzeug>=2.2.2 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (2.2.2)
Requirement already satisfied: Jinja2>=3.0 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (3.1.2)
Requirement already satisfied: itsdangerous>=2.0 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (2.1.2)
Requirement already satisfied: click>=8.0 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (8.1.3)
Requirement already satisfied: greenlet!=0.4.17 in ./.venv/lib/python3.11/site-packages (from SQLAlchemy>=1.4.18->flask_sqlalchemy) (2.0.1)
Requirement already satisfied: MarkupSafe>=2.0 in ./.venv/lib/python3.11/site-packages (from Jinja2>=3.0->Flask>=2.2->flask_sqlalchemy) (2.1.1)
Installing collected packages: flask_sqlalchemy
Successfully installed flask_sqlalchemy-3.0.2
</code>```

`

I have docker connected to flask to auto update. Here is my docker file:

```<code>FROM python:3.11
EXPOSE 5000
WORKDIR /app
COPY ./requirements.txt requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
COPY . .
CMD ["flask", "run", "--host", "0.0.0.0"]
</code>```

I removed flask-sqlalchemy and reinstalled but received the same error.

Do I need to do something outside of my .venv to get this to work?

Any help would be greatly appreciated

Body:
I am looking to remove this error from my project. I recently did an install of flask_sqlalchemy in my .venv file. I am using python3.11, insomnia, docker, flask, flask_smorest and flask_sqlalchemy.

After looking through documentation I see that this error usually occurs when the wrong version is installed. I am not sure how to troubleshoot this issue. Any help would be appreciated as I have removed and readded flask-sqlalchemy on my .venv which didn't fix the issue.

Here is my .venv libs

I added sql-alchemy and flask-sqlalchemy into my requirements.txt file which looks like this:
`

flask
flask-smorest
python-dotenv
sqlalchemy
flask-sqlalchemy

`
I received this response when I installed my requirements.txt

`

pip install -r requirements.txt
Requirement already satisfied: flask in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 1)) (2.2.2)
Requirement already satisfied: flask-smorest in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 2)) (0.40.0)
Requirement already satisfied: python-dotenv in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 3)) (0.21.0)
Requirement already satisfied: sqlalchemy in ./.venv/lib/python3.11/site-packages (from -r requirements.txt (line 4)) (1.4.44)
Collecting flask-sqlalchemy
  Using cached Flask_SQLAlchemy-3.0.2-py3-none-any.whl (24 kB)
Requirement already satisfied: Werkzeug>=2.2.2 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (2.2.2)
Requirement already satisfied: Jinja2>=3.0 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (3.1.2)
Requirement already satisfied: itsdangerous>=2.0 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (2.1.2)
Requirement already satisfied: click>=8.0 in ./.venv/lib/python3.11/site-packages (from flask->-r requirements.txt (line 1)) (8.1.3)
Requirement already satisfied: marshmallow<4,>=3.18.0 in ./.venv/lib/python3.11/site-packages (from flask-smorest->-r requirements.txt (line 2)) (3.19.0)
Requirement already satisfied: webargs<9,>=8.0.0 in ./.venv/lib/python3.11/site-packages (from flask-smorest->-r requirements.txt (line 2)) (8.2.0)
Requirement already satisfied: apispec[marshmallow]<7,>=6.0.0 in ./.venv/lib/python3.11/site-packages (from flask-smorest->-r requirements.txt (line 2)) (6.0.2)
Requirement already satisfied: greenlet!=0.4.17 in ./.venv/lib/python3.11/site-packages (from sqlalchemy->-r requirements.txt (line 4)) (2.0.1)
Requirement already satisfied: packaging>=21.3 in ./.venv/lib/python3.11/site-packages (from apispec[marshmallow]<7,>=6.0.0->flask-smorest->-r requirements.txt (line 2)) (21.3)
Requirement already satisfied: MarkupSafe>=2.0 in ./.venv/lib/python3.11/site-packages (from Jinja2>=3.0->flask->-r requirements.txt (line 1)) (2.1.1)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in ./.venv/lib/python3.11/site-packages (from packaging>=21.3->apispec[marshmallow]<7,>=6.0.0->flask-smorest->-r requirements.txt (line 2)) (3.0.9)
Installing collected packages: flask-sqlalchemy
Successfully installed flask-sqlalchemy-3.0.2
(.venv)  valemich@Vals-iMac  ~/Desktop/code/src/courses/udemy REST APIs with FlaskPython  pip --version

pip 22.3.1 from /Users/valemich/Desktop/code/src/courses/udemy REST APIs with FlaskPython/.venv/lib/python3.11/site-packages/pip (python 3.11)
(.venv)  valemich@Vals-iMac  ~/Desktop/code/src/courses/udemy REST APIs with FlaskPython  pip uninstall flask-sqlalchemy
Found existing installation: Flask-SQLAlchemy 3.0.2
Uninstalling Flask-SQLAlchemy-3.0.2:
  Would remove:
    /Users/valemich/Desktop/code/src/courses/udemy REST APIs with FlaskPython/.venv/lib/python3.11/site-packages/Flask_SQLAlchemy-3.0.2.dist-info/*
    /Users/valemich/Desktop/code/src/courses/udemy REST APIs with FlaskPython/.venv/lib/python3.11/site-packages/flask_sqlalchemy/*
Proceed (Y/n)? y
  Successfully uninstalled Flask-SQLAlchemy-3.0.2
(.venv)  valemich@Vals-iMac  ~/Desktop/code/src/courses/udemy REST APIs with FlaskPython  pip3 install flask_sqlalchemy
Collecting flask_sqlalchemy
  Using cached Flask_SQLAlchemy-3.0.2-py3-none-any.whl (24 kB)
Requirement already satisfied: Flask>=2.2 in ./.venv/lib/python3.11/site-packages (from flask_sqlalchemy) (2.2.2)
Requirement already satisfied: SQLAlchemy>=1.4.18 in ./.venv/lib/python3.11/site-packages (from flask_sqlalchemy) (1.4.44)
Requirement already satisfied: Werkzeug>=2.2.2 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (2.2.2)
Requirement already satisfied: Jinja2>=3.0 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (3.1.2)
Requirement already satisfied: itsdangerous>=2.0 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (2.1.2)
Requirement already satisfied: click>=8.0 in ./.venv/lib/python3.11/site-packages (from Flask>=2.2->flask_sqlalchemy) (8.1.3)
Requirement already satisfied: greenlet!=0.4.17 in ./.venv/lib/python3.11/site-packages (from SQLAlchemy>=1.4.18->flask_sqlalchemy) (2.0.1)
Requirement already satisfied: MarkupSafe>=2.0 in ./.venv/lib/python3.11/site-packages (from Jinja2>=3.0->Flask>=2.2->flask_sqlalchemy) (2.1.1)
Installing collected packages: flask_sqlalchemy
Successfully installed flask_sqlalchemy-3.0.2

`

I have docker connected to flask to auto update. Here is my docker file:

FROM python:3.11
EXPOSE 5000
WORKDIR /app
COPY ./requirements.txt requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
COPY . .
CMD ["flask", "run", "--host", "0.0.0.0"]

I removed flask-sqlalchemy and reinstalled but received the same error.

Do I need to do something outside of my .venv to get this to work?

Any help would be greatly appreciated


问:
How to generate a constraint for the Maximizer Solver in Linear programming Python
I have a CSV dataset. In this CSV, I have 5 different types of animals, including: (dog, cat, mouse, rabbit, and hamster) . We have 50 from each kind of animal (dog1,dog2,dog3,...,dog50). Each animal has a different value and cost. We want to pick 10 from this 5 * 50 = 200 animals, maximizing the total value of our list. We have Four constraints and I coded up all of them except The fourth one:

```<code>! pip install ortools
from ortools.linear_solver import pywraplp
import pandas as pd
import random
df=pd.read_csv('/content/d/animals.csv')
</code>```
```<code>list1=data[data["Type"]=="Dogs"]
list2=data[data["Type"]=="Cats"]
list3=data[data["Type"]=="Mouses"]
list4=data[data["Type"]=="Rabbits"]
list5=data[data["Type"]=="Hamsters"]

typeList=[list1,list2,list3,list4,list5,list6]

</code>```
```<code>solver = pywraplp.Solver.CreateSolver('SCIP')
gList=[]
dummyL=[]
for player in data['Name']:
  gList.append(solver.IntVar(0, 1,anim))
for pos in typeList:
  xList=[]
  for anim in t['Numb']:
    xList.append(solver.BoolVar(anim+'Dummy'))
  dummyL.append(xList)
print(solver.NumVariables())
</code>```
```<code>totallist= dummyL[0]+dummyL[1]+dummyL[2]+dummyL[3]+dummyL[4]
for i, num in enumerate(gList):
  solver.Add(num-9000*jlist[i]<=0)
</code>```

1-Our budget is 6500

2-we should pick 10 animals

3-We should have less than 2 dogs

```<code>solver.Add(10>=sum(sum(type)for type in dummyL))
Price=df['Price']
solver.Add(6500>=sum(Price[i]*gList[i] for i in range(len(gList))))
solver.Add(sum(dummyList[0])<=2)
</code>```
```<code>value=df['value']
solver.Maximize(sum(costs[i]*gList[i] for i in range(len(gList))))
</code>```
```<code>status= solver.Solve()
</code>```
```<code>if status == pywraplp.Solver.OPTIMAL:
  print('Solution:')
  print('Maximum Value:'+str(solver.Objective().Value()))
  for i,varr in enumerate(gList):
    if varr.solution_value()==1:
      print('Number of '+str(gList[i])+' '+str(df['type'][i])+': '+str(gList[i].solution_value())+' Cost: '+str(df['Price'][i]))
</code>```

The fourth constraint :

```<code>#This is not code

My Question:

**Fourth constraint**=

Adding an animal of the same type reduces the next one's value by 1/3. If a dog's value is 30, the first dog chosen will have the value of 30 for us. But if we pick 2 dogs, the value of the seccond dog will be 1/3 of its value. and so on.

so if we pick 3 from the dogs:

first dog value= 60
second dog value= 30
third dog value= 9

our total value will be = 60 + 30*(1/3) + 9*(1/3*1/3)= 60+10+1=71
</code>```

The fourth constraint makes us not choose all 10 animals from the same type.

My question is How to generate The fourth constraint

I coded up all functions and constraints except The fourth constraint.

Body:
I have a CSV dataset. In this CSV, I have 5 different types of animals, including: (dog, cat, mouse, rabbit, and hamster) . We have 50 from each kind of animal (dog1,dog2,dog3,...,dog50). Each animal has a different value and cost. We want to pick 10 from this 5 * 50 = 200 animals, maximizing the total value of our list. We have Four constraints and I coded up all of them except The fourth one:

! pip install ortools
from ortools.linear_solver import pywraplp
import pandas as pd
import random
df=pd.read_csv('/content/d/animals.csv')

list1=data[data["Type"]=="Dogs"]
list2=data[data["Type"]=="Cats"]
list3=data[data["Type"]=="Mouses"]
list4=data[data["Type"]=="Rabbits"]
list5=data[data["Type"]=="Hamsters"]

typeList=[list1,list2,list3,list4,list5,list6]

solver = pywraplp.Solver.CreateSolver('SCIP')
gList=[]
dummyL=[]
for player in data['Name']:
  gList.append(solver.IntVar(0, 1,anim))
for pos in typeList:
  xList=[]
  for anim in t['Numb']:
    xList.append(solver.BoolVar(anim+'Dummy'))
  dummyL.append(xList)
print(solver.NumVariables())

totallist= dummyL[0]+dummyL[1]+dummyL[2]+dummyL[3]+dummyL[4]
for i, num in enumerate(gList):
  solver.Add(num-9000*jlist[i]<=0)

1-Our budget is 6500

2-we should pick 10 animals

3-We should have less than 2 dogs

solver.Add(10>=sum(sum(type)for type in dummyL))
Price=df['Price']
solver.Add(6500>=sum(Price[i]*gList[i] for i in range(len(gList))))
solver.Add(sum(dummyList[0])<=2)

value=df['value']
solver.Maximize(sum(costs[i]*gList[i] for i in range(len(gList))))

status= solver.Solve()

if status == pywraplp.Solver.OPTIMAL:
  print('Solution:')
  print('Maximum Value:'+str(solver.Objective().Value()))
  for i,varr in enumerate(gList):
    if varr.solution_value()==1:
      print('Number of '+str(gList[i])+' '+str(df['type'][i])+': '+str(gList[i].solution_value())+' Cost: '+str(df['Price'][i]))

The fourth constraint :

#This is not code

My Question:

**Fourth constraint**=

Adding an animal of the same type reduces the next one's value by 1/3. If a dog's value is 30, the first dog chosen will have the value of 30 for us. But if we pick 2 dogs, the value of the seccond dog will be 1/3 of its value. and so on.

so if we pick 3 from the dogs:

first dog value= 60
second dog value= 30
third dog value= 9

our total value will be = 60 + 30*(1/3) + 9*(1/3*1/3)= 60+10+1=71

The fourth constraint makes us not choose all 10 animals from the same type.

My question is How to generate The fourth constraint

I coded up all functions and constraints except The fourth constraint.


问:
Django Channels await database_to_async method not working
I'm trying to build a notification application by using Django Channels.
The problem I'm having is the following error:

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

consumers.py

```<code>class NotificationConsumer(AsyncJsonWebsocketConsumer):
    @database_sync_to_async
    def get_notifications(self, user):
        new_messages = NotificationSerializer(Notification.objects.filter(content=1, users_notified__in=[user]), many=True)

        notifs = {
            "new_messages": new_messages
        }

        return notifs

    async def connect(self):
        user = self.scope["user"]

        if user:
            self.channel_name = user.username
            self.room_group_name = 'notification_%s' % self.channel_name

            # Error happens in the following line
            notification = await self.get_notifications(self.scope["user"])
            print("Notification", notification)

            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()

        await self.disconnect(401)

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def notify(self, event):
        await self.send_json(event["content"])
</code>```

I have used the exact same approach when I developed a Django Channels chat application that saves messages to the database as well. When trying to convert my approach to the Notification system, it doesn't anymore.

As soon as I don't await the self.get_notifications method anymore, it works but I only get back a <coroutine object SyncToAsync.__call__ at ...>

Body:
I'm trying to build a notification application by using Django Channels.
The problem I'm having is the following error:

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

consumers.py

class NotificationConsumer(AsyncJsonWebsocketConsumer):
    @database_sync_to_async
    def get_notifications(self, user):
        new_messages = NotificationSerializer(Notification.objects.filter(content=1, users_notified__in=[user]), many=True)

        notifs = {
            "new_messages": new_messages
        }

        return notifs

    async def connect(self):
        user = self.scope["user"]

        if user:
            self.channel_name = user.username
            self.room_group_name = 'notification_%s' % self.channel_name

            # Error happens in the following line
            notification = await self.get_notifications(self.scope["user"])
            print("Notification", notification)

            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()

        await self.disconnect(401)

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def notify(self, event):
        await self.send_json(event["content"])

I have used the exact same approach when I developed a Django Channels chat application that saves messages to the database as well. When trying to convert my approach to the Notification system, it doesn't anymore.

As soon as I don't await the self.get_notifications method anymore, it works but I only get back a <coroutine object SyncToAsync.__call__ at ...>


问:
How to deploy Oracle forms application into web?
I am using Oracle Forms 11g to develop a screen and I want to deploy it in a application server in web? Which is the best cloud application server to deploy Forms application that already contains forms preinstalled in it
?
Also , please tell me what are the prerequisite of that server to run a small application ?(for personal use).
Does Oracle or any other cloud hosting company provide such a server for subscription ?

Thanks


问:
Strange MongoDB $setIntersection behaviour
I want to query a match between records in my db based on certain tags. The match would be calculated based on a formula and the intersection of the tags. Now, even querying the intersection doesn't work...always. Sometimes it does, sometimes it doesn't. In my example, if I change the displayName attribute to something else (add or remove one character, the query works. In its current state (for demo purposes) it doesn't as it does not deliver the one intersection match for the last doc with id 3.

https://mongoplayground.net/p/KAYPoV29RFO

That's my query:

```<code>db.collection.aggregate([
  {
    $match: {
      "_id": "1"
    }
  },
  {
    "$lookup": {
      from: "collection",
      let: {
        "criteria": "$tags"
      },
      pipeline: [
        {
          $project: {
            "match": {
              $setIntersection: [
                "$tags",
                "$$criteria"
              ]
            },

          }
        }
      ],
      as: "result"
    }
  },
  {
    $project: {
      "tags": 0
    }
  },

])
</code>```

Here is the example data (simplified):

```<code>[
  { "_id": "1", "tags": [{ "_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2}, {"_id": "c", "displayName": "c", "level": 3}]},
  {"_id": "2", "tags": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2}]},
  {"_id": "3", "tags": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "d", "displayName": "d", "level": 4}]}
]
</code>```

and the result as it is: (expected is three matches for id 1, 2 matches for id 2 and one for the last id. However, the last result has 0 elements in the intersection result. Again, when i change "displayName" to "displayNam" or "displayNames" (obviously in all docs), it give the correct result...

```<code>[{
  "_id": "1", "result": [
    {"_id": "1", "match": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2},{"_id": "c","displayName": "c","level": 3}]},
    {"_id": "2", "match": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2}]},
    {"_id": "3","match": [*here should be the match to _id: "a", but it's not (always) there*]}
  ]
}]
</code>```

Does anyone have an idea what I am missing here?

Body:
I want to query a match between records in my db based on certain tags. The match would be calculated based on a formula and the intersection of the tags. Now, even querying the intersection doesn't work...always. Sometimes it does, sometimes it doesn't. In my example, if I change the displayName attribute to something else (add or remove one character, the query works. In its current state (for demo purposes) it doesn't as it does not deliver the one intersection match for the last doc with id 3.

https://mongoplayground.net/p/KAYPoV29RFO

That's my query:

db.collection.aggregate([
  {
    $match: {
      "_id": "1"
    }
  },
  {
    "$lookup": {
      from: "collection",
      let: {
        "criteria": "$tags"
      },
      pipeline: [
        {
          $project: {
            "match": {
              $setIntersection: [
                "$tags",
                "$$criteria"
              ]
            },

          }
        }
      ],
      as: "result"
    }
  },
  {
    $project: {
      "tags": 0
    }
  },

])

Here is the example data (simplified):

[
  { "_id": "1", "tags": [{ "_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2}, {"_id": "c", "displayName": "c", "level": 3}]},
  {"_id": "2", "tags": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2}]},
  {"_id": "3", "tags": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "d", "displayName": "d", "level": 4}]}
]

and the result as it is: (expected is three matches for id 1, 2 matches for id 2 and one for the last id. However, the last result has 0 elements in the intersection result. Again, when i change "displayName" to "displayNam" or "displayNames" (obviously in all docs), it give the correct result...

[{
  "_id": "1", "result": [
    {"_id": "1", "match": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2},{"_id": "c","displayName": "c","level": 3}]},
    {"_id": "2", "match": [{"_id": "a", "displayName": "a", "level": 1}, {"_id": "b", "displayName": "b", "level": 2}]},
    {"_id": "3","match": [*here should be the match to _id: "a", but it's not (always) there*]}
  ]
}]

Does anyone have an idea what I am missing here?


问:
Unable to get pixel color from an image in SwiftUI
I want to design a draggable color selector view that will select the color of the present pixel. My strategy is, first, to choose the position of the pixel and then, second, get the pixel color. The position has been correctly changed while dragging the view. The color of the view has also been changed but don't understand its manner of changing. I think it doesn't returns the proper color of its pixel. Additionally, when x or y of the CGImage coordinate is less then 0, the getPixelColor() returns 'UIExtendedSRGBColorSpace 0 0 0 0'.

After a long search, I have not get any proper solution to get pixel color in SwiftUI.

The program is given below:

```<code>struct ColorSelectorView: View {
    @Binding var position: CGPoint
    @State private var isDragging = false
    @State private var colorPicked = UIColor.black
    var image: UIImage?
    var colorPickedCallBack : (UIColor) -> ()

    var body: some View {
        colorSelectorView()
            .onAppear {
                colorPicked = getPixelColor(image: image, point: position) ?? .clear
            }
            .gesture(DragGesture()
                .onChanged { value in
                    self.position.x += CGFloat(Int(value.location.x - value.startLocation.x))
                    self.position.y += CGFloat(Int(value.location.y - value.startLocation.y))
                    colorPicked = getPixelColor(image: image, point: position) ?? .clear
                }
                .onEnded({ value in
                    colorPickedCallBack(colorPicked)
                })
            )
            .offset(x: position.x, y: position.y)
        }
    }

    func getPixelColor(image: UIImage,  point: CGPoint) -> UIColor? {
        guard let pixelData = image.cgImage?.dataProvider?.data else { return nil }
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
        let pixelInfo: Int = Int((image.size.width * point.y + point.x) * 4.0)
        let i = Array(0 ... 3).map { CGFloat(data[pixelInfo + $0]) / CGFloat(255) }
        return UIColor(red: i[0], green: i[1], blue: i[2], alpha: 1)
    }
}
</code>```

Body:
I want to design a draggable color selector view that will select the color of the present pixel. My strategy is, first, to choose the position of the pixel and then, second, get the pixel color. The position has been correctly changed while dragging the view. The color of the view has also been changed but don't understand its manner of changing. I think it doesn't returns the proper color of its pixel. Additionally, when x or y of the CGImage coordinate is less then 0, the getPixelColor() returns 'UIExtendedSRGBColorSpace 0 0 0 0'.

After a long search, I have not get any proper solution to get pixel color in SwiftUI.

The program is given below:

struct ColorSelectorView: View {
    @Binding var position: CGPoint
    @State private var isDragging = false
    @State private var colorPicked = UIColor.black
    var image: UIImage?
    var colorPickedCallBack : (UIColor) -> ()

    var body: some View {
        colorSelectorView()
            .onAppear {
                colorPicked = getPixelColor(image: image, point: position) ?? .clear
            }
            .gesture(DragGesture()
                .onChanged { value in
                    self.position.x += CGFloat(Int(value.location.x - value.startLocation.x))
                    self.position.y += CGFloat(Int(value.location.y - value.startLocation.y))
                    colorPicked = getPixelColor(image: image, point: position) ?? .clear
                }
                .onEnded({ value in
                    colorPickedCallBack(colorPicked)
                })
            )
            .offset(x: position.x, y: position.y)
        }
    }

    func getPixelColor(image: UIImage,  point: CGPoint) -> UIColor? {
        guard let pixelData = image.cgImage?.dataProvider?.data else { return nil }
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
        let pixelInfo: Int = Int((image.size.width * point.y + point.x) * 4.0)
        let i = Array(0 ... 3).map { CGFloat(data[pixelInfo + $0]) / CGFloat(255) }
        return UIColor(red: i[0], green: i[1], blue: i[2], alpha: 1)
    }
}


问:
I need import quiniela.txt and and merge it with the functions
I need import quiniela.txt and and merge it with the functions.

quinielaGrupos=[[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "]]

file=open("quiniela.txt","r")
for a in range(0,8):
for b in range(0,4):
leer=file.readline()
quinielaGrupos[a][b]=leer
file.close()
print(quinielaGrupos)

##FUNCTIONS
`

```<code>def partido(pais, pais_rival):
    marcador = random.randint(0, 5)
    marcador_rival = random.randint(0, 5)
    print(f"Marcador -> {pais[NAME]} {marcador} - {marcador_rival} {pais_rival[NAME]}")
    if marcador > marcador_rival:
        pais[PUNTOS] += 3
    elif marcador_rival > marcador:
        pais_rival[PUNTOS] += 3
    else:
        pais[PUNTOS] += 1
        pais_rival[PUNTOS] += 1

def print_tables():
    for index, grupo in enumerate(MUNDIAL):
        print(f">>> Table of group {GROUP_NAMES[index]} <<<<<")
        for pais in grupo:
            print(f"{pais[NAME]}: {pais[PUNTOS]}")
        print("\n")

def primera_fase():
    for index, grupo in enumerate(MUNDIAL):
        print(f">>> Games of group {GROUP_NAMES[index]} <<<<<")
        for index, pais in enumerate(grupo):
            for pais_rival in grupo[index + 1:]:
                partido(pais, pais_rival)
        print("--------------------------")

def print_teams_qualified():
    for index, group in enumerate(MUNDIAL):
        print(f"\n>>> Qualified teams in group {GROUP_NAMES[index]} <<<<")
        group.sort(key = lambda x: x[1], reverse=True)
        print(group[:2])

def quiniela():
    primera_fase()
    print('\nPRIMERA FASE\n')
    print_tables()
    print_teams_qualified()

if __name__ == "__main__":
    quiniela()

</code>```

`

Body:
I need import quiniela.txt and and merge it with the functions.

quinielaGrupos=[[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "],[" "," "," "," "]]

file=open("quiniela.txt","r")
for a in range(0,8):
for b in range(0,4):
leer=file.readline()
quinielaGrupos[a][b]=leer
file.close()
print(quinielaGrupos)

##FUNCTIONS
`

def partido(pais, pais_rival):
    marcador = random.randint(0, 5)
    marcador_rival = random.randint(0, 5)
    print(f"Marcador -> {pais[NAME]} {marcador} - {marcador_rival} {pais_rival[NAME]}")
    if marcador > marcador_rival:
        pais[PUNTOS] += 3
    elif marcador_rival > marcador:
        pais_rival[PUNTOS] += 3
    else:
        pais[PUNTOS] += 1
        pais_rival[PUNTOS] += 1

def print_tables():
    for index, grupo in enumerate(MUNDIAL):
        print(f">>> Table of group {GROUP_NAMES[index]} <<<<<")
        for pais in grupo:
            print(f"{pais[NAME]}: {pais[PUNTOS]}")
        print("\n")

def primera_fase():
    for index, grupo in enumerate(MUNDIAL):
        print(f">>> Games of group {GROUP_NAMES[index]} <<<<<")
        for index, pais in enumerate(grupo):
            for pais_rival in grupo[index + 1:]:
                partido(pais, pais_rival)
        print("--------------------------")

def print_teams_qualified():
    for index, group in enumerate(MUNDIAL):
        print(f"\n>>> Qualified teams in group {GROUP_NAMES[index]} <<<<")
        group.sort(key = lambda x: x[1], reverse=True)
        print(group[:2])

def quiniela():
    primera_fase()
    print('\nPRIMERA FASE\n')
    print_tables()
    print_teams_qualified()

if __name__ == "__main__":
    quiniela()

`


问:
how do i put my print variable in an outhandle so that it prints into a txt file
this is my code, I am trying to learn about regexes and nested loops by outputting a summarization of my regex into a txt file.  In the summary I am trying to make a variable for the last three just like "student_name" and "student_seq" instead of the str(51) <- needs to find the start position of the longest chain (regex #3), str(63) <- needs to be (regex #1) and str(m.group) <- same issue as (regex #3) trying to make the print value into a variable so i can put it into the summary (regex #2)

```<code>{python polyq,eval=T,echo=T}
student_name = "Doe"
student_seq = " "
seqs = open("sequences/all_seq.tsv","r")
for l in seqs:
  fields=l.split(" ")
  a = fields[0]
  b = fields[1]
  if a == student_name:
    student_seq = b

import re
pattern = re.compile("(CAA|CAG)")
for m in re.finditer(pattern, student_seq):
      print(m.start(),m.end(),m.group(0))

pattern = re.compile("(CAA|CAG)+")
for m in re.finditer(pattern, student_seq):
      print(m.start(0))    #<-regex3
      print(len(m.group(0)))   #<-regex1
      print(m.group(0))     #<-regex2

out_handle = open("polyq.txt","w")
out_handle.write("My name is " +
            student_name +
            " and my sequence is " +
            student_seq +
            "The longest polyglutamine tract start position is " +
            str(51) +
            ". The DNA length of longest polyglutamine tract is " +
            str(63) +
            ". The sequence for longest polyglutamine tract is " +
            str(m.group(0)) + "\n")
out_handle.close()
</code>```

Ive tried making it a str value, I tried establishing it as a value (longest = print(m.group(0))) still not the answer and whatever is included in the summary right now gives me an output of NONE, This is the output into my txt file

```<code>My name is Doe and my sequence is ATGGCGACCCTGGAAAAGCTGATGAAGGCCTTCGAGTCCCTCAAGTCCTTCCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAACAGCCGCCA
The longest polyglutamine tract start position is 51. The DNA length of longest polyglutamine tract is 63. The sequence for longest polyglutamine tract is None
</code>```

Body:
this is my code, I am trying to learn about regexes and nested loops by outputting a summarization of my regex into a txt file.  In the summary I am trying to make a variable for the last three just like "student_name" and "student_seq" instead of the str(51) <- needs to find the start position of the longest chain (regex #3), str(63) <- needs to be (regex #1) and str(m.group) <- same issue as (regex #3) trying to make the print value into a variable so i can put it into the summary (regex #2)

{python polyq,eval=T,echo=T}
student_name = "Doe"
student_seq = " "
seqs = open("sequences/all_seq.tsv","r")
for l in seqs:
  fields=l.split(" ")
  a = fields[0]
  b = fields[1]
  if a == student_name:
    student_seq = b

import re
pattern = re.compile("(CAA|CAG)")
for m in re.finditer(pattern, student_seq):
      print(m.start(),m.end(),m.group(0))

pattern = re.compile("(CAA|CAG)+")
for m in re.finditer(pattern, student_seq):
      print(m.start(0))    #<-regex3
      print(len(m.group(0)))   #<-regex1
      print(m.group(0))     #<-regex2

out_handle = open("polyq.txt","w")
out_handle.write("My name is " +
            student_name +
            " and my sequence is " +
            student_seq +
            "The longest polyglutamine tract start position is " +
            str(51) +
            ". The DNA length of longest polyglutamine tract is " +
            str(63) +
            ". The sequence for longest polyglutamine tract is " +
            str(m.group(0)) + "\n")
out_handle.close()

Ive tried making it a str value, I tried establishing it as a value (longest = print(m.group(0))) still not the answer and whatever is included in the summary right now gives me an output of NONE, This is the output into my txt file

My name is Doe and my sequence is ATGGCGACCCTGGAAAAGCTGATGAAGGCCTTCGAGTCCCTCAAGTCCTTCCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAACAGCCGCCA
The longest polyglutamine tract start position is 51. The DNA length of longest polyglutamine tract is 63. The sequence for longest polyglutamine tract is None


问:
How can I write a function that verifies if a list is a non-contiguous sublist of another list, in python?
Examples:

```<code>contains([], [4, 6, 5, 0]) -> True
contains([5, 7, 5],[4, 6, 5, 0, 7, 9, 0, 5]) -> True
contains([5, 7, 5],[4, 6, 5, 0, 7, 9, 0]) -> False
contains([5, 7, 5],[4,7,5,2,5]) -> False
</code>```

I did some stuff but it clearly wasn't working, so I guess I really don't have a clue how to do it.

Body:
Examples:

contains([], [4, 6, 5, 0]) -> True
contains([5, 7, 5],[4, 6, 5, 0, 7, 9, 0, 5]) -> True
contains([5, 7, 5],[4, 6, 5, 0, 7, 9, 0]) -> False
contains([5, 7, 5],[4,7,5,2,5]) -> False

I did some stuff but it clearly wasn't working, so I guess I really don't have a clue how to do it.


问:
Flutter Navbar UI Border Radius
I am currently working on my first mobile app, and need some help with some of the code pertaining to my navbar. I have watched some videos and read some docs on using the tag BottomNavigationBar to better sort and make my navigation bar but I am struggling to make it look how I want. Right now I have the default navbar it gives you with a different background color but I added padding to give it space from the edges of the screen. I now want to round the corners but it seems wherever I try to apply a border-radius it just doesn't work. Any idea how I can go about rounding these corners to give a good-looking floating navbar look? Thanks!
Current Navbar Look</p>
```<code>  Widget build(BuildContext context) {
return Scaffold(
      // ignore: prefer_const_literals_to_create_immutables
      bottomNavigationBar: Container(
          padding: const EdgeInsets.all(8.0),
           child: Material(
            borderRadius: BorderRadius.circular(10),
            color: Colors.black,
            child: BottomNavigationBar(
              fixedColor: Colors.white,
              unselectedItemColor: Colors.white,
              backgroundColor: Color.fromARGB(255, 27, 27, 27),
              currentIndex: _selectedIndex,
          // ignore: prefer_const_literals_to_create_immutables
             items: [
               BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
               BottomNavigationBarItem(icon: Icon(Icons.add), label: 'Add Friend'),
               BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search Friends'),
          ],
         ),
        ),
      ),
    );
  }
</code>```

Title: Flutter Navbar UI Border Radius

Body:
I am currently working on my first mobile app, and need some help with some of the code pertaining to my navbar. I have watched some videos and read some docs on using the tag BottomNavigationBar to better sort and make my navigation bar but I am struggling to make it look how I want. Right now I have the default navbar it gives you with a different background color but I added padding to give it space from the edges of the screen. I now want to round the corners but it seems wherever I try to apply a border-radius it just doesn't work. Any idea how I can go about rounding these corners to give a good-looking floating navbar look? Thanks!
Current Navbar Look

  Widget build(BuildContext context) {
return Scaffold(
      // ignore: prefer_const_literals_to_create_immutables
      bottomNavigationBar: Container(
          padding: const EdgeInsets.all(8.0),
           child: Material(
            borderRadius: BorderRadius.circular(10),
            color: Colors.black,
            child: BottomNavigationBar(
              fixedColor: Colors.white,
              unselectedItemColor: Colors.white,
              backgroundColor: Color.fromARGB(255, 27, 27, 27),
              currentIndex: _selectedIndex,
          // ignore: prefer_const_literals_to_create_immutables
             items: [
               BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
               BottomNavigationBarItem(icon: Icon(Icons.add), label: 'Add Friend'),
               BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search Friends'),
          ],
         ),
        ),
      ),
    );
  }


问:
How do I add a message displaying the build type to my build.gradle?
Tried the following:

```<code>buildTypes {
    release {
        //Full debug for uploading production and beta builds.
        ndk.debugSymbolLevel "FULL"
        println 'Full debug for uploading production and beta builds.'
    }

    debug {
        //Small debug info for uploading internal testing builds.
        ndk.debugSymbolLevel "SYMBOL_TABLE"
        println 'Small debug info for uploading internal testing builds.'
    }
}
</code>```

But the both messages are printed:

```<code>Full debug for uploading production and beta builds.
Small debug info for uploading internal testing builds.

> Task :preBuild UP-TO-DATE
> Task :preDebugBuild UP-TO-DATE
> Task :mergeDebugJniLibFolders
...
</code>```

Does this mean that both release and debug are built?

Body:
Tried the following:

buildTypes {
    release {
        //Full debug for uploading production and beta builds.
        ndk.debugSymbolLevel "FULL"
        println 'Full debug for uploading production and beta builds.'
    }

    debug {
        //Small debug info for uploading internal testing builds.
        ndk.debugSymbolLevel "SYMBOL_TABLE"
        println 'Small debug info for uploading internal testing builds.'
    }
}

But the both messages are printed:

Full debug for uploading production and beta builds.
Small debug info for uploading internal testing builds.

> Task :preBuild UP-TO-DATE
> Task :preDebugBuild UP-TO-DATE
> Task :mergeDebugJniLibFolders
...

Does this mean that both release and debug are built?


问:
How to declare type for related object in django
In views.py I am creating products based on queryset and I don't know how to assign type to wz_product to get hints of appropriate variables.

```<code>product_qs: List[Product] = product.orderproduct_set.all()

for product in product_qs:
   product_serializer = ProductModelSerializer(
       data={"og_product": product.wz_product.og_product.id})
</code>```

In VSC it looks like this:

(in the question, I changed the names of the variables to make it easier to understand)

Body:
In views.py I am creating products based on queryset and I don't know how to assign type to wz_product to get hints of appropriate variables.

product_qs: List[Product] = product.orderproduct_set.all()

for product in product_qs:
   product_serializer = ProductModelSerializer(
       data={"og_product": product.wz_product.og_product.id})

In VSC it looks like this:

(in the question, I changed the names of the variables to make it easier to understand)


问:
How to get response from file_get_contents using php?
i try to show status of this page but show only blank page this my code please retify
`

```<code>$ref_no = "123";
$postdata = http_build_query(array(
    'apiToken' => '123',
    'reqid' => ''.$ref_no.''
));
$opts = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);
$context = stream_context_create($opts);
$result = file_get_contents('http://www.smslinkwallet.com/apiservice.asmx/GetRechargeStatus', false, $context);
$decoded_json = json_decode($result, false);
echo $decoded_json->status;
</code>```

this one example response page

```<code>SUPPORT:HTTP GET OR HTTP POST
    RESPONSE:
    <?xml version="1.0" encoding="utf-8"?>
    <Result xmlns="http://tempuri.org/">
    <reqid>unique id sent by the client</reqid>
    <status>SUCCESS/FAILED/PENDING/FREQUENT</status>
    <remark>recharge summary</remark>
    <balance>balance after recharge</balance>
    <mn>string</mn>
    <field1>operator transaction id</field1>
    <ec>error code</ec>
    </Result>
</code>```

`

i try to show status of this page please help me

Body:
i try to show status of this page but show only blank page this my code please retify
`

$ref_no = "123";
$postdata = http_build_query(array(
    'apiToken' => '123',
    'reqid' => ''.$ref_no.''
));
$opts = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);
$context = stream_context_create($opts);
$result = file_get_contents('http://www.smslinkwallet.com/apiservice.asmx/GetRechargeStatus', false, $context);
$decoded_json = json_decode($result, false);
echo $decoded_json->status;

this one example response page

SUPPORT:HTTP GET OR HTTP POST
    RESPONSE:
    <?xml version="1.0" encoding="utf-8"?>
    <Result xmlns="http://tempuri.org/">
    <reqid>unique id sent by the client</reqid>
    <status>SUCCESS/FAILED/PENDING/FREQUENT</status>
    <remark>recharge summary</remark>
    <balance>balance after recharge</balance>
    <mn>string</mn>
    <field1>operator transaction id</field1>
    <ec>error code</ec>
    </Result>

`

i try to show status of this page please help me


问:
what is the indented block function of 'def' in this problem?
```<code>File "C:\Users\USER\PycharmProjects\Lesson1\mad_libs.py", line 11
    animals = input("Enter a animal name: ")
    ^
Indentation Error: expected an indented block after function definition on line 8
</code>```
```<code>File "C:\Users\USER\PycharmProjects\Lesson1\mad_libs.py", line 11
    animals = input("Enter a animal name: ")
    ^
IndentationError: expected an indented block after function definition on line 8
</code>```

i need the answer to be precise
i'm trying to make a madlibs generator game

Body:
File "C:\Users\USER\PycharmProjects\Lesson1\mad_libs.py", line 11
    animals = input("Enter a animal name: ")
    ^
Indentation Error: expected an indented block after function definition on line 8

File "C:\Users\USER\PycharmProjects\Lesson1\mad_libs.py", line 11
    animals = input("Enter a animal name: ")
    ^
IndentationError: expected an indented block after function definition on line 8

i need the answer to be precise
i'm trying to make a madlibs generator game