问:
Efficient Net Image Classification
I am trying to classify custom data with Keras Efficient net.evening and morning
I was following here for classification custom data evening morning.
https://keras.io/examples/vision/image_classification_efficientnet_fine_tuning/  I could not do the data upload and tpu part.
I'm trying to test with gpu. (FIRST QUESTION)
tfds.load(dataset_name, data_dir="gs://example-bucket/datapath") how can i change this part for myself ?
SECOND QUESTION
https://github.com/AarohiSingla/Image-Classification-Using-EfficientNets/blob/main/2-efficientnetB0_Custom_dataset.ipynb
I have a question about this place
I'm trying to add the reporting part to this code, but I couldn't.</p>
```<code>from sklearn.metrics import classification_report
predIdxs = model.predict(train_x, verbose  = 1)
predictions= np.argmax(predIdxs, axis=1)
print(classification_report(labels,predictions,target_names=dataset_path))
ERROR-------------------
Traceback (most recent call last):
File "C:\Users\A\PycharmProjects\pythonProject8\test.py", line 142, in <module>
print(classification_report(labels,predictions,target_names=dataset_path))
File "C:\Users\A\Anacondainstallb\envs\tfow\lib\site-packages\sklearn\metrics\_classification.py", line 2310, in classification_report
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
File "C:\Users\A\Anacondainstallb\envs\tfow\lib\site-packages\sklearn\metrics\_classification.py", line 86, in _check_targets
check_consistent_length(y_true, y_pred)
File "C:\Users\A\Anacondainstallb\envs\tfow\lib\site-packages\sklearn\utils\validation.py", line 397, in check_consistent_length
raise ValueError(
ValueError: Found input variables with inconsistent numbers of samples: [106, 100]
</code>```
```<code>import numpy as np
import pandas as pd
import tensorflow as tf

import os

from sklearn.metrics import classification_report

dataset_path = os.listdir('C:\\Users\\A\\Desktop\\day\\dataset')

print (dataset_path)  #what kinds of classes are in this dataset

print("Types of classes labels found: ", len(dataset_path))

class_labels = []

for item in dataset_path:
 # Get all the file names
 all_classes = os.listdir('C:\\Users\\A\\Desktop\\day\\dataset' + '/' +item)
 #print(all_classes)

 # Add them to the list
 for room in all_classes:
    class_labels.append((item, str('dataset_path' + '/' +item) + '/' + room))

df = pd.DataFrame(data=class_labels, columns=['Labels', 'image'])
print(df.head())
print(df.tail())

print("Total number of images in the dataset: ", len(df))

label_count = df['Labels'].value_counts()
print(label_count)

import cv2

path = 'C:\\Users\\A\\Desktop\\day\\dataset\\'
dataset_path = os.listdir('C:\\Users\\A\\Desktop\\day\\dataset\\')

im_size = 224

images = []
labels = []

for i in dataset_path:
    data_path = path + str(i)
    filenames = [i for i in os.listdir(data_path)]

    for f in filenames:
        img = cv2.imread(data_path + '/' + f)
        img = cv2.resize(img, (im_size, im_size))
        images.append(img)
        labels.append(i)

images = np.array(images)
images = images.astype('float32') / 255.0
images.shape

from sklearn.preprocessing import LabelEncoder , OneHotEncoder
y=df['Labels'].values
print(y)

y_labelencoder = LabelEncoder ()
y = y_labelencoder.fit_transform (y)
print (y)

y=y.reshape(-1,1)

from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([('my_ohe', OneHotEncoder(), [0])], remainder='passthrough')
Y = ct.fit_transform(y) #.toarray()
print(Y[:5])
print(Y[35:])

from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split

images, Y = shuffle(images, Y, random_state=1)

train_x, test_x, train_y, test_y = train_test_split(images, Y, test_size=0.05, random_state=415)

#inpect the shape of the training and testing.
print(train_x.shape)#(100, 224, 224, 3)
print(train_y.shape)#(100, 2)
print(test_x.shape)#(6, 224, 224, 3)
print(test_y.shape)#(6, 2)

from tensorflow.keras import layers
from tensorflow.keras.applications import EfficientNetB0

NUM_CLASSES = 2
IMG_SIZE = 224
size = (IMG_SIZE, IMG_SIZE)

inputs = layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))

# Using model without transfer learning

outputs = EfficientNetB0(include_top=True, weights=None, classes=NUM_CLASSES)(inputs)

model = tf.keras.Model(inputs, outputs)

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

model.summary()

hist = model.fit(train_x, train_y, epochs=1, verbose=2)

import matplotlib.pyplot as plt

def plot_hist(hist):
        plt.plot(hist.history["accuracy"])
        # plt.plot(hist.history["val_accuracy"])
        plt.title("model accuracy")
        plt.ylabel("accuracy")
        plt.xlabel("epoch")
        plt.legend(["train", "validation"], loc="upper left")
        plt.show()

plot_hist(hist)

from sklearn.metrics import classification_report
predIdxs = model.predict(train_x, verbose  = 1)
predictions= np.argmax(predIdxs, axis=1)
print(classification_report(labels,predictions,target_names=dataset_path))
</code>```

Title: Efficient Net Image Classification

Body:
I am trying to classify custom data with Keras Efficient net.evening and morning
I was following here for classification custom data evening morning.
https://keras.io/examples/vision/image_classification_efficientnet_fine_tuning/  I could not do the data upload and tpu part.
I'm trying to test with gpu. (FIRST QUESTION)
tfds.load(dataset_name, data_dir="gs://example-bucket/datapath") how can i change this part for myself ?
SECOND QUESTION
https://github.com/AarohiSingla/Image-Classification-Using-EfficientNets/blob/main/2-efficientnetB0_Custom_dataset.ipynb
I have a question about this place
I'm trying to add the reporting part to this code, but I couldn't.

from sklearn.metrics import classification_report
predIdxs = model.predict(train_x, verbose  = 1)
predictions= np.argmax(predIdxs, axis=1)
print(classification_report(labels,predictions,target_names=dataset_path))
ERROR-------------------
Traceback (most recent call last):
File "C:\Users\A\PycharmProjects\pythonProject8\test.py", line 142, in <module>
print(classification_report(labels,predictions,target_names=dataset_path))
File "C:\Users\A\Anacondainstallb\envs\tfow\lib\site-packages\sklearn\metrics\_classification.py", line 2310, in classification_report
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
File "C:\Users\A\Anacondainstallb\envs\tfow\lib\site-packages\sklearn\metrics\_classification.py", line 86, in _check_targets
check_consistent_length(y_true, y_pred)
File "C:\Users\A\Anacondainstallb\envs\tfow\lib\site-packages\sklearn\utils\validation.py", line 397, in check_consistent_length
raise ValueError(
ValueError: Found input variables with inconsistent numbers of samples: [106, 100]

import numpy as np
import pandas as pd
import tensorflow as tf

import os

from sklearn.metrics import classification_report

dataset_path = os.listdir('C:\\Users\\A\\Desktop\\day\\dataset')

print (dataset_path)  #what kinds of classes are in this dataset

print("Types of classes labels found: ", len(dataset_path))

class_labels = []

for item in dataset_path:
 # Get all the file names
 all_classes = os.listdir('C:\\Users\\A\\Desktop\\day\\dataset' + '/' +item)
 #print(all_classes)

 # Add them to the list
 for room in all_classes:
    class_labels.append((item, str('dataset_path' + '/' +item) + '/' + room))

df = pd.DataFrame(data=class_labels, columns=['Labels', 'image'])
print(df.head())
print(df.tail())

print("Total number of images in the dataset: ", len(df))

label_count = df['Labels'].value_counts()
print(label_count)

import cv2

path = 'C:\\Users\\A\\Desktop\\day\\dataset\\'
dataset_path = os.listdir('C:\\Users\\A\\Desktop\\day\\dataset\\')

im_size = 224

images = []
labels = []

for i in dataset_path:
    data_path = path + str(i)
    filenames = [i for i in os.listdir(data_path)]

    for f in filenames:
        img = cv2.imread(data_path + '/' + f)
        img = cv2.resize(img, (im_size, im_size))
        images.append(img)
        labels.append(i)

images = np.array(images)
images = images.astype('float32') / 255.0
images.shape

from sklearn.preprocessing import LabelEncoder , OneHotEncoder
y=df['Labels'].values
print(y)

y_labelencoder = LabelEncoder ()
y = y_labelencoder.fit_transform (y)
print (y)

y=y.reshape(-1,1)

from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([('my_ohe', OneHotEncoder(), [0])], remainder='passthrough')
Y = ct.fit_transform(y) #.toarray()
print(Y[:5])
print(Y[35:])

from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split

images, Y = shuffle(images, Y, random_state=1)

train_x, test_x, train_y, test_y = train_test_split(images, Y, test_size=0.05, random_state=415)

#inpect the shape of the training and testing.
print(train_x.shape)#(100, 224, 224, 3)
print(train_y.shape)#(100, 2)
print(test_x.shape)#(6, 224, 224, 3)
print(test_y.shape)#(6, 2)

from tensorflow.keras import layers
from tensorflow.keras.applications import EfficientNetB0

NUM_CLASSES = 2
IMG_SIZE = 224
size = (IMG_SIZE, IMG_SIZE)

inputs = layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))

# Using model without transfer learning

outputs = EfficientNetB0(include_top=True, weights=None, classes=NUM_CLASSES)(inputs)

model = tf.keras.Model(inputs, outputs)

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

model.summary()

hist = model.fit(train_x, train_y, epochs=1, verbose=2)

import matplotlib.pyplot as plt

def plot_hist(hist):
        plt.plot(hist.history["accuracy"])
        # plt.plot(hist.history["val_accuracy"])
        plt.title("model accuracy")
        plt.ylabel("accuracy")
        plt.xlabel("epoch")
        plt.legend(["train", "validation"], loc="upper left")
        plt.show()

plot_hist(hist)

from sklearn.metrics import classification_report
predIdxs = model.predict(train_x, verbose  = 1)
predictions= np.argmax(predIdxs, axis=1)
print(classification_report(labels,predictions,target_names=dataset_path))


来源: stackexchange

问:
Creating/Generating Swagger UI from apiDefinition.swagger.json file/Creationg Swagger UI without using SwashBuckle
I wanted to add swagger UI to one of our Asp.Net Web API projects. Tried installing SwashBuckle but it is not working because of some restrictions. So, checking for other ways. I have created apiDefinition.swagger.json file from postman collection. How can I create swagger UI from this? Also, please suggest other ways to create swagger UI.

what I have tried: Tried installing SwashBuckle but it is not creating swaggerconfig.cs file. When i checked the project dependencies, i saw that our controller is derived from a common controller that is in another project. This common controller is derived from ApiController. All the Controllers of the projects in the solution are derived from this common controller. So, we thought this approach might not work. So, checking for other ways. I could generate apiDefinition.swagger.json file using postman collection of our API's. Now, I want to know how I can use it for creating swagger UI.

ContentLicense: CC BY-SA 4.0


问:
How to wrap nvidia-smi calls to NVML?
I am trying to intercept the calls that nvidia-smi CLI makes to NVML in order to add some custom code (like for instance printing "I am here" every time nvidia-smi is called).

I am using ubuntu 20.04, with:

NVIDIA-SMI 515.65.01

Driver Version: 515.65.01

CUDA Version: 11.7

I have tried to override Nvidia NVML function calls using dlsym and LD_PRELOAD i.e.

```<code>nvmlReturn_t nvmlDeviceGetMemoryInfo_v2(nvmlDevice_t device, nvmlMemory_v2_t *memory){
    void* handle = dlopen("libnvidia-ml.so", RTLD_LOCAL | RTLD_LAZY);
    nvmlReturn_t (*fn) (nvmlDevice_t, nvmlMemory_v2_t *) = (nvmlReturn_t (*) (nvmlDevice_t, nvmlMemory_v2_t *))dlsym(handle, "nvmlDeviceGetMemoryInfo_v2");
    nvmlReturn_t current_return = fn(device, memory);
    printf("i am here");
    return current_return;
}
</code>```

I have compiled the code above with gcc as follows:

gcc -I/usr/local/cuda/include -shared -fPIC -o mylib.so mylib.c -ldl -L/usr/lib/x86_64-linux-gnu/ -lnvidia-ml
```
<p>Finally, I have tried to execute the nvidia-smi command with LD_PRELOAD in order to load my code:</p>
<pre class="lang-bash prettyprint-override"><code>LD_PRELOAD=./mylib.so nvidia-smi
</code>```

Nevertheless, I was unable to intercept any nvidia-smi calls of NVML, since the output "I am here" is never printed to screen.

I also have tried to wrap other functions but it seems that my code is never executed when invoking nvidia-smi. However, I have tried to #include <nvml.h> in a small project and I saw that in this case using LD_PRELOAD the functions calls are intercepted successfully.

Why does nvidia-smi seem not to be affected by the preload?
Am I wrapping the wrong functions or my library is not built/loaded correctly? Is there any other way to achieve this?

Title: How to wrap nvidia-smi calls to NVML?

Body:
I am trying to intercept the calls that nvidia-smi CLI makes to NVML in order to add some custom code (like for instance printing "I am here" every time nvidia-smi is called).

I am using ubuntu 20.04, with:

NVIDIA-SMI 515.65.01

Driver Version: 515.65.01

CUDA Version: 11.7

I have tried to override Nvidia NVML function calls using dlsym and LD_PRELOAD i.e.

nvmlReturn_t nvmlDeviceGetMemoryInfo_v2(nvmlDevice_t device, nvmlMemory_v2_t *memory){
    void* handle = dlopen("libnvidia-ml.so", RTLD_LOCAL | RTLD_LAZY);
    nvmlReturn_t (*fn) (nvmlDevice_t, nvmlMemory_v2_t *) = (nvmlReturn_t (*) (nvmlDevice_t, nvmlMemory_v2_t *))dlsym(handle, "nvmlDeviceGetMemoryInfo_v2");
    nvmlReturn_t current_return = fn(device, memory);
    printf("i am here");
    return current_return;
}

I have compiled the code above with gcc as follows:

gcc -I/usr/local/cuda/include -shared -fPIC -o mylib.so mylib.c -ldl -L/usr/lib/x86_64-linux-gnu/ -lnvidia-ml

Finally, I have tried to execute the nvidia-smi command with LD_PRELOAD in order to load my code:

LD_PRELOAD=./mylib.so nvidia-smi

Nevertheless, I was unable to intercept any nvidia-smi calls of NVML, since the output "I am here" is never printed to screen.

I also have tried to wrap other functions but it seems that my code is never executed when invoking nvidia-smi. However, I have tried to #include <nvml.h> in a small project and I saw that in this case using LD_PRELOAD the functions calls are intercepted successfully.

Why does nvidia-smi seem not to be affected by the preload?
Am I wrapping the wrong functions or my library is not built/loaded correctly? Is there any other way to achieve this?


问:
SwiftUI Picker with style = navigationLink causes 100% CPU usage
I have a NavigationStack that contains some View, which itself contains a Picker with .pickerStyle(.navigationLink).

When clicking on the Picker in the emulator, the cpu usage spikes to 100% and becomes unresponsive.

It does not happen when not using .pickerStyle(.navigationLink)

```<code>//
//  ContentView.swift
//  test
//
//  Created by Anon on 1/4/23.
//

import SwiftUI

struct Contact : Hashable, Identifiable {
    var id: String = ""
    var name: String = ""
    static var preview : [Contact] = [
        Contact(id: UUID().uuidString, name: "John"),
        Contact(id: UUID().uuidString, name: "Mary")
    ]
}

struct ContentView: View {
    let types : [String] = ["work","home"]
    var body: some View {
        NavigationStack(){
            List(Contact.preview){
                contact in
                NavigationLink(contact.name, value: contact)
            }
            .navigationDestination(for: Contact.self){
                contact in
                Form{
                    Picker(selection: .constant("work"), label: Text("Type")){
                        ForEach(types, id: \.self) { item in
                            Text(item)
                        }
                    }
                    .pickerStyle(.navigationLink)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

</code>```

Body:
I have a NavigationStack that contains some View, which itself contains a Picker with .pickerStyle(.navigationLink).

When clicking on the Picker in the emulator, the cpu usage spikes to 100% and becomes unresponsive.

It does not happen when not using .pickerStyle(.navigationLink)

//
//  ContentView.swift
//  test
//
//  Created by Anon on 1/4/23.
//

import SwiftUI

struct Contact : Hashable, Identifiable {
    var id: String = ""
    var name: String = ""
    static var preview : [Contact] = [
        Contact(id: UUID().uuidString, name: "John"),
        Contact(id: UUID().uuidString, name: "Mary")
    ]
}

struct ContentView: View {
    let types : [String] = ["work","home"]
    var body: some View {
        NavigationStack(){
            List(Contact.preview){
                contact in
                NavigationLink(contact.name, value: contact)
            }
            .navigationDestination(for: Contact.self){
                contact in
                Form{
                    Picker(selection: .constant("work"), label: Text("Type")){
                        ForEach(types, id: \.self) { item in
                            Text(item)
                        }
                    }
                    .pickerStyle(.navigationLink)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
DSLR image capture 1 per second and video capture
I'm trying to learn to use gphoto2 to control a DSLR camera for image and video capture. I want the camera to take a photo every second, or minimum at a fixed rate but I can't work out how to do it.

I have found that in the command line one can use the command

```<code>gphoto2 - -I 2 -F 5 --capture-image and download
</code>```

to capture an image every 2 seconds for 5 images for example but I don't know how to implement that in Python code and I don't know how many frames will be recorded. I would just like to capture the image, save to the camera SD card and 1 second later capture the next image.

Using

```<code>triggerCommand = ["--trigger-capture"]
</code>```

appears to take images much quicker than

```<code>triggerCommand = ["--capture-image"]
</code>```

but I cannot control the timings, both options also take longer than a second between frame captures.

My current code is below:

```<code>#!/usr/bin/env python3
import subprocess
import time
from datetime import datetime
from sh import gphoto2 as gp
import signal, os, subprocess

#kill gphoto2 process that occurs whenever connect camera
def killgphoto2():
    p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
    out,err = p.communicate()
    for line in out.splitlines():
        if b'gvfsd-gphoto2' in line:
            #kill process
            pid = int(line.split(None, 1)[0])
            os.kill(pid, signal.SIGKILL)

triggerCommand = ["--trigger-capture"]

killgphoto2()
start_time = time.time()
for i in range(5):
    gp(triggerCommand)
end_time = time.time()
print(end_time - start_time)
</code>```

If anyone could help, I'd really appreciate it.

Also can one use gphoto2 or something else with the raspberry pi to record the video using the camera SD card, so that the camera native resolution and frame rate can be used?

I currently use opencv on the pi which records the video screen but has difficulty maintaining a stable frame rate.

Thanks

Body:
I'm trying to learn to use gphoto2 to control a DSLR camera for image and video capture. I want the camera to take a photo every second, or minimum at a fixed rate but I can't work out how to do it.

I have found that in the command line one can use the command

gphoto2 - -I 2 -F 5 --capture-image and download

to capture an image every 2 seconds for 5 images for example but I don't know how to implement that in Python code and I don't know how many frames will be recorded. I would just like to capture the image, save to the camera SD card and 1 second later capture the next image.

Using

triggerCommand = ["--trigger-capture"]

appears to take images much quicker than

triggerCommand = ["--capture-image"]

but I cannot control the timings, both options also take longer than a second between frame captures.

My current code is below:

#!/usr/bin/env python3
import subprocess
import time
from datetime import datetime
from sh import gphoto2 as gp
import signal, os, subprocess

#kill gphoto2 process that occurs whenever connect camera
def killgphoto2():
    p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
    out,err = p.communicate()
    for line in out.splitlines():
        if b'gvfsd-gphoto2' in line:
            #kill process
            pid = int(line.split(None, 1)[0])
            os.kill(pid, signal.SIGKILL)

triggerCommand = ["--trigger-capture"]

killgphoto2()
start_time = time.time()
for i in range(5):
    gp(triggerCommand)
end_time = time.time()
print(end_time - start_time)

If anyone could help, I'd really appreciate it.

Also can one use gphoto2 or something else with the raspberry pi to record the video using the camera SD card, so that the camera native resolution and frame rate can be used?

I currently use opencv on the pi which records the video screen but has difficulty maintaining a stable frame rate.

Thanks


问:
Unit test fail with No EntityManager available
I have a unit test that covers a @transactional method, however, I'm getting No EntityManager when I try to run it. As I've seen in many places, I put the @Transactional annotation before the test method, I tried also before the whole class, but still had the same issue.

@Transactional
@RunWith(KronosSpringTestRunner.class)
@ClassesToTest(classes = {

}, bindAllMocks = true
)
public class ShiftAuditJPADataReadUsingIndexServiceTest {

    @Inject
    private ShiftAuditJPADataReadUsingIndexService underTest;

    @Before
    public void setup() {

        when(entityManager.unwrap(Session.class)).thenReturn(sessionMock);
    }

    @Test
    public void test_findByEmployee() {

        List<ShiftAudit> expected = Collections.singletonList(new ShiftAudit());

        when(properties.getProperty(QUERY_BATCH_SIZE, DEFAULT_QUERY_BATCH_SIZE)).thenReturn(DEFAULT_QUERY_BATCH_SIZE);

        when(sessionMock.createSQLQuery(anyString())).thenReturn(sqlQuery);
        when(sqlQuery.setResultTransformer(any(ResultTransformer.class))).thenReturn(queryMock);
        when(jpaDataReadServiceHelper.queryList(sqlQuery, employeeIds, scheduleStartDate, scheduleEndDate, false)).thenReturn(expected);

        Collection<ShiftAudit> actual = underTest.findByEmployee(employeeId, scheduleStartDate, scheduleEndDate, false);

        assertEquals(expected, actual);
        verify(sessionMock).createSQLQuery(anyString());
    }

```


问:
Why I can't install packages du to this OSError?
I am trying to install packages via a requirements.txt file I have two types, local ones (I created - they are fine) and general ones e.g., fsspec or et-xmlfile, surprisingly it is these that are returning me the following error message which seems to be an OSError:

ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/96/c2/3dd434b0108730014f1b96fd286040dc3bcb70066346f7e01ec2ac95865f/et_xmlfile-1
.1.0-py3-none-any.whl (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))

in the requirements.txt they are labelled as follows with their version e.g., fsspec==2022.2.0 ; et-xmlfile==1.1.0

I had a look online to see if people had a similar issue, could not find any solution.
I tried to see which ones are the problematical ones and it turned out to be fsspec and et-xmlfile, for instance, another I am installing is cramjam and I don't have any issue with it.
I tried to see if newer versions existed and if it would be a version issue but for these two, I have the latest versions in the requirements.txt file

How can I get rid of this OSError?


问:
Substituting variables in a Camelot equation
I am using Camelot to parse tables that are not exactly identical across pages.  I have used the "lattice" function to get the table regions for each page and want to substitute those into the function used by Camelot.  The equation is:

tables = camelot.read_pdf('file.pdf', pages=’1’, flavor = 'stream', table_regions = [‘0,800,800,0’])

where within the brackets are the X1,Y1 and X2,Y2 coordinates for the table regions that I want to change as I loop through each page.

I had set each X and Y coordinate as a value that I would loop through and change, but I don't seem to be getting the syntax right.  I tried substituting [X1, Y1, X2, Y2] but end up with an Attribute Error: 'float' object has no attribute 'split'.  I've tried a variety of permutations to no avail.


问:
How to disable "This operation has been cancelled due to restrictions in effect on this computer" message from showing?
I Develop a medical device that runs Windows 10 Ent. 1809. since this is a medical device, must Windows Explorer and other Windows settings need to be restricted from the user that operates this device.
So I Had to turn change most of the Registry values in

```<code>Computer\HKEY_USERS\Medical\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
</code>```

The problem that I am facing is this annoying "This operation has been canceled due to restrictions in effect on this computer" message, which I DO NOT want my user to see.

How do I prevent this message from showing?

I basically searched all over the internet for a solution. But I couldn't find any information on the matter, except on chat from Microsoft forum which, surprise.. surprise..., was not helpful.

Body:
I Develop a medical device that runs Windows 10 Ent. 1809. since this is a medical device, must Windows Explorer and other Windows settings need to be restricted from the user that operates this device.
So I Had to turn change most of the Registry values in

Computer\HKEY_USERS\Medical\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

The problem that I am facing is this annoying "This operation has been canceled due to restrictions in effect on this computer" message, which I DO NOT want my user to see.

How do I prevent this message from showing?

I basically searched all over the internet for a solution. But I couldn't find any information on the matter, except on chat from Microsoft forum which, surprise.. surprise..., was not helpful.


问:
Accessing the TypeORM Entity (MYSQL Table) in TypeScript
index.ts

```<code>import express, { Express } from 'express';
import dotenv from 'dotenv';
import { DataSource } from 'typeorm';
import cors from 'cors';
import bodyParser from 'body-parser';
import { Task } from './src/tasks/tasks.entity';
import { tasksRouter } from './src/tasks/tasks.router';
// Instantiate express app
const app: Express = express();
dotenv.config();

//Parsing incoming request
app.use(bodyParser.json());

//Use CORS install types as well
app.use(cors());

// Create Databse Connection
export const AppDataSource = new DataSource({
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DB,
  entities: [Task],
  synchronize: true,
  logging: true,
});

//Define Server Port
const port = process.env.PORT;

AppDataSource.initialize()
  .then(() => {
    // Start listening Request on defined port
    app.listen(port);
    console.log('Data Source has been initialized');
  })
  .catch((err) => console.log(err));

//create a Route
app.use('/', tasksRouter);
</code>```

tasks.router.ts

```<code>import { Request, Response, Router } from 'express';
import { validationResult } from 'express-validator';
import { tasksController } from './tasks.controller';
import { createValidator } from './tasks.validator';

export const tasksRouter: Router = Router();

tasksRouter.get('/tasks', tasksController.getAll);

tasksRouter.post(
  '/tasks',
  createValidator,
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res
        .json({
          errors: errors.array(),
        })
        .status(400);
    }
  },
);
</code>```

tasks.controller.ts

```<code>import { AppDataSource } from '../../index';
import { Task } from './tasks.entity';
import { instanceToPlain } from 'class-transformer';
import { Request, Response } from 'express';

class TasksController {
  constructor(private taskRepository = AppDataSource.getRepository(Task)) {}

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  public async getAll(req: Request, res: Response): Promise<Response> {
    let allTasks: Task[];

    try {
      allTasks = await this.taskRepository.find({
        order: {
          date: 'ASC',
        },
      });
      allTasks = instanceToPlain(allTasks) as Task[];

      res.json(allTasks).status(200);
    } catch (_errors) {
      return res.json({ error: 'Internal Server Error' }).status(500);
    }
  }
}

export const tasksController = new TasksController();
</code>```

While accessing the Task Entity, I get an error in the tasks.controller.ts file and

TypeError: Cannot read properties of undefined (reading
'getRepository')

What difference goes it make if I instantiate the class in tasks.controller.ts file instead of the tasks.router.ts file?

It is working if I instantiate the TasksController class inside the route.

Body:
index.ts

import express, { Express } from 'express';
import dotenv from 'dotenv';
import { DataSource } from 'typeorm';
import cors from 'cors';
import bodyParser from 'body-parser';
import { Task } from './src/tasks/tasks.entity';
import { tasksRouter } from './src/tasks/tasks.router';
// Instantiate express app
const app: Express = express();
dotenv.config();

//Parsing incoming request
app.use(bodyParser.json());

//Use CORS install types as well
app.use(cors());

// Create Databse Connection
export const AppDataSource = new DataSource({
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DB,
  entities: [Task],
  synchronize: true,
  logging: true,
});

//Define Server Port
const port = process.env.PORT;

AppDataSource.initialize()
  .then(() => {
    // Start listening Request on defined port
    app.listen(port);
    console.log('Data Source has been initialized');
  })
  .catch((err) => console.log(err));

//create a Route
app.use('/', tasksRouter);

tasks.router.ts

import { Request, Response, Router } from 'express';
import { validationResult } from 'express-validator';
import { tasksController } from './tasks.controller';
import { createValidator } from './tasks.validator';

export const tasksRouter: Router = Router();

tasksRouter.get('/tasks', tasksController.getAll);

tasksRouter.post(
  '/tasks',
  createValidator,
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res
        .json({
          errors: errors.array(),
        })
        .status(400);
    }
  },
);

tasks.controller.ts

import { AppDataSource } from '../../index';
import { Task } from './tasks.entity';
import { instanceToPlain } from 'class-transformer';
import { Request, Response } from 'express';

class TasksController {
  constructor(private taskRepository = AppDataSource.getRepository(Task)) {}

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  public async getAll(req: Request, res: Response): Promise<Response> {
    let allTasks: Task[];

    try {
      allTasks = await this.taskRepository.find({
        order: {
          date: 'ASC',
        },
      });
      allTasks = instanceToPlain(allTasks) as Task[];

      res.json(allTasks).status(200);
    } catch (_errors) {
      return res.json({ error: 'Internal Server Error' }).status(500);
    }
  }
}

export const tasksController = new TasksController();

While accessing the Task Entity, I get an error in the tasks.controller.ts file and

TypeError: Cannot read properties of undefined (reading
'getRepository')

What difference goes it make if I instantiate the class in tasks.controller.ts file instead of the tasks.router.ts file?

It is working if I instantiate the TasksController class inside the route.


问:
Start up script not executing recursively, how to fix?
I'm on archlinux using bspwm and this is my .config/bspwm/bspwmrc file:

```<code>#!/bin/sh

pgrep -x sxhkd > /dev/null || sxhkd &

bspc monitor HDMI-1 -d I II III IV V VI VII
bspc monitor HDMI-2 -d VIII IX X

bspc config border_width         2
bspc config window_gap           12
#bspc config top_padding 0
#bspc config bottom_padding 0

bspc config split_ratio          0.5
bspc config border_width         2
bspc config borderless_monocle   true
bspc config gapless_monocle      true
bspc config focus_follows_pointer true
#bspc config auto_alternate true #
#bspc config auto_cancel true #
bspc config focused_border_color \#7a5014
bspc config active_border_color \#4d4b48
bspc config normal_border_color \#4d4b48
bspc config presel_border_color "#9a875f"
bspc config urgent_border_color "#504339"
bspc config focused_locked_border_color "#8c644c"
#bspc config normal_frame_opacity 0.0
#bspc config focused_frame_opacity 0.1

bspc rule -a Gimp desktop='^8' state=floating follow=on
bspc rule -a mplayer2 state=floating
bspc rule -a Kupfer.py focus=on
bspc rule -a Screenkey manage=off
bspc rule -a discord desktop='^10' state=floating rectangle=1230x724+1943+148
#bspc rule -a Pcmanfm state=floating
bspc rule -a mpv state=fullscreen
bspc rule -a feh state=floating rectangle=1600x900+100+100
bspc rule -a vlc state=floating
bspc rule -a heroic state=floating
bspc rule -a Lutris state=floating
bspc rule -a Steam state=floating
bspc rule -a zsnes state=fullscreen
bspc rule -a lxappearance desktop='^8'
bspc rule -a Lxappearance desktop='^8'
#bspc rule -a terminator -o desktop='^10' state=floating rectangle 100x100+0+0 sticky=on

~/.fehbg &
/usr/bin/numlockx on &
xinput --set-prop 13 286 -1 &
~/.config/polybar/launch.sh &
picom &
bash ~/.config/extra_config_files/bspwm_extra_exec &
</code>```

on the last line I tell it to execute this bspwm_extra_exec file:

```<code>sleep 0.5
alacritty --hold -e mocp|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=759x505+1145+559 &
sleep 0.5
alacritty --hold -e cava|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=759x184+1145+359 &
sleep 0.5
alacritty --hold -e peaclock|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=759x305+1145+38 &
sleep 0.5
alacritty|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=1117x200+12+864 &
sleep 0.5
alacritty|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=1117x810+12+38 &
sleep 1
alttab &
</code>```

so far so good, but when alacritty is openning it does not open correctly, sometimes it reads the 4th line first, then the 6th, then the 2nd and so on...

I can't get it to execute recursively, step by step. I have to re-execute for it to work properly.

Body:
I'm on archlinux using bspwm and this is my .config/bspwm/bspwmrc file:

#!/bin/sh

pgrep -x sxhkd > /dev/null || sxhkd &

bspc monitor HDMI-1 -d I II III IV V VI VII
bspc monitor HDMI-2 -d VIII IX X

bspc config border_width         2
bspc config window_gap           12
#bspc config top_padding 0
#bspc config bottom_padding 0

bspc config split_ratio          0.5
bspc config border_width         2
bspc config borderless_monocle   true
bspc config gapless_monocle      true
bspc config focus_follows_pointer true
#bspc config auto_alternate true #
#bspc config auto_cancel true #
bspc config focused_border_color \#7a5014
bspc config active_border_color \#4d4b48
bspc config normal_border_color \#4d4b48
bspc config presel_border_color "#9a875f"
bspc config urgent_border_color "#504339"
bspc config focused_locked_border_color "#8c644c"
#bspc config normal_frame_opacity 0.0
#bspc config focused_frame_opacity 0.1

bspc rule -a Gimp desktop='^8' state=floating follow=on
bspc rule -a mplayer2 state=floating
bspc rule -a Kupfer.py focus=on
bspc rule -a Screenkey manage=off
bspc rule -a discord desktop='^10' state=floating rectangle=1230x724+1943+148
#bspc rule -a Pcmanfm state=floating
bspc rule -a mpv state=fullscreen
bspc rule -a feh state=floating rectangle=1600x900+100+100
bspc rule -a vlc state=floating
bspc rule -a heroic state=floating
bspc rule -a Lutris state=floating
bspc rule -a Steam state=floating
bspc rule -a zsnes state=fullscreen
bspc rule -a lxappearance desktop='^8'
bspc rule -a Lxappearance desktop='^8'
#bspc rule -a terminator -o desktop='^10' state=floating rectangle 100x100+0+0 sticky=on

~/.fehbg &
/usr/bin/numlockx on &
xinput --set-prop 13 286 -1 &
~/.config/polybar/launch.sh &
picom &
bash ~/.config/extra_config_files/bspwm_extra_exec &

on the last line I tell it to execute this bspwm_extra_exec file:

sleep 0.5
alacritty --hold -e mocp|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=759x505+1145+559 &
sleep 0.5
alacritty --hold -e cava|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=759x184+1145+359 &
sleep 0.5
alacritty --hold -e peaclock|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=759x305+1145+38 &
sleep 0.5
alacritty|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=1117x200+12+864 &
sleep 0.5
alacritty|bspc rule -a Alacritty -o desktop='^3' state=floating rectangle=1117x810+12+38 &
sleep 1
alttab &

so far so good, but when alacritty is openning it does not open correctly, sometimes it reads the 4th line first, then the 6th, then the 2nd and so on...

I can't get it to execute recursively, step by step. I have to re-execute for it to work properly.


问:
Verify Http Status Code for ~90K URLs with PHP
I have a list of 90K URLs and I need to verify the Http status code for each of them; and make an entry next to each URL in the database. Here's my attempt so far; but it's super slow. I'd appreciate any suggestions, feedback on making this run faster.

```<code>public function handle()
    {

        DB::table('internal_links')->whereNull('status')->orderBy('id')->chunk(5, function($links) {

           foreach($links as $link) {
                stream_context_get_default([
                    'http' => ['method' => 'HEAD']
                ]);
                $status_code = @get_headers($link->href)[0];
                if(!$status_code) {
                    $status_code = 404;
                } else {
                    $status_code = substr($status_code, 9,3);
                }
                DB::table('internal_links')->where('href', $link->href)->update(['status' => $status_code]);
           }
        });
        return Command::SUCCESS;
    }
</code>```

In my test, this takes about ~6-7 hours to complete. I'd be happy if this can be done faster with concurrent requests. I'm currently exploring a way to build the concurrent requests with Laravel's Http client; but can't figure it out.

Update
I'm attempting to use Laravel Http concurrent requests; but not able to figure this out -

```<code>public function handle()
    {
        DB::table('internal_links')->distinct('href')->orderBy('id')->chunk(50, function($urls) {
            // How do I write the following block to have my "$urls as $url) go into the $pool->head($url) ?
            $responses = Http::pool(fn (Pool $pool) => [
                $pool->head('http://url1'),
                $pool->head('http://url2')
            ]);
        });
        return Command::SUCCESS;
    }
</code>```

Body:
I have a list of 90K URLs and I need to verify the Http status code for each of them; and make an entry next to each URL in the database. Here's my attempt so far; but it's super slow. I'd appreciate any suggestions, feedback on making this run faster.

public function handle()
    {

        DB::table('internal_links')->whereNull('status')->orderBy('id')->chunk(5, function($links) {

           foreach($links as $link) {
                stream_context_get_default([
                    'http' => ['method' => 'HEAD']
                ]);
                $status_code = @get_headers($link->href)[0];
                if(!$status_code) {
                    $status_code = 404;
                } else {
                    $status_code = substr($status_code, 9,3);
                }
                DB::table('internal_links')->where('href', $link->href)->update(['status' => $status_code]);
           }
        });
        return Command::SUCCESS;
    }

In my test, this takes about ~6-7 hours to complete. I'd be happy if this can be done faster with concurrent requests. I'm currently exploring a way to build the concurrent requests with Laravel's Http client; but can't figure it out.

Update
I'm attempting to use Laravel Http concurrent requests; but not able to figure this out -

public function handle()
    {
        DB::table('internal_links')->distinct('href')->orderBy('id')->chunk(50, function($urls) {
            // How do I write the following block to have my "$urls as $url) go into the $pool->head($url) ?
            $responses = Http::pool(fn (Pool $pool) => [
                $pool->head('http://url1'),
                $pool->head('http://url2')
            ]);
        });
        return Command::SUCCESS;
    }


问:
Flutter - Cannot upload image to Firebase and add field to Field Firestore collection
I am building a flutter app and currently I am working on the user profile page. I have two issues. Firstly I am trying to upload the image to Firebase storage (after it has been cropped) but it's not uploading anything. Secondly I had made a user collection in my login page but now I want to add the Url of my image as an additional field to my user collection.

Here are screenshots to show what's currently happening

After image has been uploaded from the gallery and cropped out, I then need to upload it to FirebaseStorage as well as the image Url to FirebaseStore

```<code>import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:fluttertoast/fluttertoast.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  String name = '';
  String email = '';
  String? image = '';
  File? imageFile;
  String? imageUrl;
  String? userNameInput = '';

  //Get image from camera
  void _getFromCamera(BuildContext context) async {
    XFile? pickedFile =
        await ImagePicker().pickImage(source: ImageSource.camera);
    _cropImage(pickedFile!.path);
    _uploadImageToFirebase();
    Navigator.pop(context);
  }

  //get image from gallery
  void _getFromGallery(BuildContext context) async {
    XFile? pickedFile =
        await ImagePicker().pickImage(source: ImageSource.gallery);
    _cropImage(pickedFile!.path);
    _uploadImageToFirebase();
    Navigator.pop(context);
  }

  //crop the image
  void _cropImage(filePath) async {
    CroppedFile? croppedImage = await ImageCropper()
        .cropImage(sourcePath: filePath, maxHeight: 1080, maxWidth: 1080);

    if (croppedImage != null) {
      setState(() {
        imageFile = File(croppedImage.path);
      });
    }
  }

  //Upload image to Firebase
  Future _uploadImageToFirebase() async {
    if (imageFile == null) {
      Fluttertoast.showToast(msg: 'Please upload an image');
      return;
    }
    try {
      final ref = FirebaseStorage.instance
          .ref()
          .child('userImages')
          .child(DateTime.now().toString() + '.jpg');
      await ref.putFile(imageFile!);
      imageUrl = await ref.getDownloadURL();

      FirebaseFirestore.instance
          .collection('users')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .set({'userImage': imageUrl});
    } catch (error) {
      Fluttertoast.showToast(msg: error.toString());
    }
  }

  void _showImageDialogue(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('Choose an option'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                InkWell(
                  onTap: () {
                    _getFromCamera(context);
                  },
                  child: Row(
                    children: const [
                      Padding(
                        padding: EdgeInsets.all(4.0),
                        child: Icon(Icons.camera),
                      ),
                      Text('Camera')
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {
                    _getFromGallery(context);
                  },
                  child: Row(
                    children: const [
                      Padding(
                        padding: EdgeInsets.all(4.0),
                        child: Icon(Icons.image),
                      ),
                      Text('Gallery')
                    ],
                  ),
                ),
              ],
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Builder(builder: (context) {
          return SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: GestureDetector(
                        onTap: () {
                          _showImageDialogue(context);
                        },
                        child: CircleAvatar(
                          minRadius: 60.0,
                          backgroundColor: Colors.white,
                          child: CircleAvatar(
                            radius: 50.0,
                            backgroundImage: imageFile == null
                                ? const AssetImage('assets/images/avatar.png')
                                : Image.file(imageFile!).image,
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 60.0),
                      child: IconButton(
                        icon: const Icon(Icons.camera_alt),
                        onPressed: (() {
                          //_showIageDialogue();
                        }),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 20.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: Container(
                        child: Column(
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(name,
                                  style: const TextStyle(
                                      fontSize: 20.0, color: Colors.black)),
                            ),
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                email,
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20.0,
                                    color: Colors.black),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: Container(
                        child: const Icon(Icons.edit),
                      ),
                    )
                  ],
                ),
              ],
            ),
          );
        }),
      ),
    );
  }
}
</code>```

Body:
I am building a flutter app and currently I am working on the user profile page. I have two issues. Firstly I am trying to upload the image to Firebase storage (after it has been cropped) but it's not uploading anything. Secondly I had made a user collection in my login page but now I want to add the Url of my image as an additional field to my user collection.

Here are screenshots to show what's currently happening

After image has been uploaded from the gallery and cropped out, I then need to upload it to FirebaseStorage as well as the image Url to FirebaseStore

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:fluttertoast/fluttertoast.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  String name = '';
  String email = '';
  String? image = '';
  File? imageFile;
  String? imageUrl;
  String? userNameInput = '';

  //Get image from camera
  void _getFromCamera(BuildContext context) async {
    XFile? pickedFile =
        await ImagePicker().pickImage(source: ImageSource.camera);
    _cropImage(pickedFile!.path);
    _uploadImageToFirebase();
    Navigator.pop(context);
  }

  //get image from gallery
  void _getFromGallery(BuildContext context) async {
    XFile? pickedFile =
        await ImagePicker().pickImage(source: ImageSource.gallery);
    _cropImage(pickedFile!.path);
    _uploadImageToFirebase();
    Navigator.pop(context);
  }

  //crop the image
  void _cropImage(filePath) async {
    CroppedFile? croppedImage = await ImageCropper()
        .cropImage(sourcePath: filePath, maxHeight: 1080, maxWidth: 1080);

    if (croppedImage != null) {
      setState(() {
        imageFile = File(croppedImage.path);
      });
    }
  }

  //Upload image to Firebase
  Future _uploadImageToFirebase() async {
    if (imageFile == null) {
      Fluttertoast.showToast(msg: 'Please upload an image');
      return;
    }
    try {
      final ref = FirebaseStorage.instance
          .ref()
          .child('userImages')
          .child(DateTime.now().toString() + '.jpg');
      await ref.putFile(imageFile!);
      imageUrl = await ref.getDownloadURL();

      FirebaseFirestore.instance
          .collection('users')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .set({'userImage': imageUrl});
    } catch (error) {
      Fluttertoast.showToast(msg: error.toString());
    }
  }

  void _showImageDialogue(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('Choose an option'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                InkWell(
                  onTap: () {
                    _getFromCamera(context);
                  },
                  child: Row(
                    children: const [
                      Padding(
                        padding: EdgeInsets.all(4.0),
                        child: Icon(Icons.camera),
                      ),
                      Text('Camera')
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {
                    _getFromGallery(context);
                  },
                  child: Row(
                    children: const [
                      Padding(
                        padding: EdgeInsets.all(4.0),
                        child: Icon(Icons.image),
                      ),
                      Text('Gallery')
                    ],
                  ),
                ),
              ],
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Builder(builder: (context) {
          return SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: GestureDetector(
                        onTap: () {
                          _showImageDialogue(context);
                        },
                        child: CircleAvatar(
                          minRadius: 60.0,
                          backgroundColor: Colors.white,
                          child: CircleAvatar(
                            radius: 50.0,
                            backgroundImage: imageFile == null
                                ? const AssetImage('assets/images/avatar.png')
                                : Image.file(imageFile!).image,
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 60.0),
                      child: IconButton(
                        icon: const Icon(Icons.camera_alt),
                        onPressed: (() {
                          //_showIageDialogue();
                        }),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 20.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: Container(
                        child: Column(
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(name,
                                  style: const TextStyle(
                                      fontSize: 20.0, color: Colors.black)),
                            ),
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                email,
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20.0,
                                    color: Colors.black),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: Container(
                        child: const Icon(Icons.edit),
                      ),
                    )
                  ],
                ),
              ],
            ),
          );
        }),
      ),
    );
  }
}


问:
docker network - assign multiple ip-range by itables
I need add to my docker network which I using for squid, outgoing ip range from xx.ip to yy.ip.
At the moment I adding single ip using bellow command:

```<code>iptables -t nat -A POSTROUTING -s 172.18.0.0/16 ! -o bridge-coi -j SNAT --to-source 1xx.xxx.xxx.xx4
</code>```

How I can add range ip?

When I put several many above command, not working.

Body:
I need add to my docker network which I using for squid, outgoing ip range from xx.ip to yy.ip.
At the moment I adding single ip using bellow command:

iptables -t nat -A POSTROUTING -s 172.18.0.0/16 ! -o bridge-coi -j SNAT --to-source 1xx.xxx.xxx.xx4

How I can add range ip?

When I put several many above command, not working.


问:
Matlab Acoustic Modem with QAM modulation
I am trying to make an acoustic modem with matlab. It records sound an stores it in an array, modulates it using 64-QAM and adds then demodulates it. But the demodulated sound and recorded sound are not the same.
Here is the code:

```<code>clear;
clc;
M = 64;      % Modulation order (alphabet size or number of points in signal constellation)
k = log2(M);
Fs=44100;
Nbits=8;
nChannels=1;
SNR=250;

%audio recording
recObj=audiorecorder(Fs,Nbits,nChannels);
recDuration=3;
disp("Begin speaking.")s
recordblocking(recObj,recDuration);
disp("2 sec pause")
pause(2)
disp("End of recording")
y=getaudiodata(recObj);
plot(y);
% playObj=audioplayer(y,Fs);
% play(playObj);
Ts=-(1/Fs)/2:1:(1/Fs)/2;
figure
subplot(1,2,1);
plottf(y,Ts,'t');
subplot(1,2,2);
plottf(y,Ts,'f');

%MODULATION QAM
y_int = abs(round(y*1000/16));
constdiag = comm.ConstellationDiagram('XLimits',[-sqrt(M) sqrt(M)],'YLimits',[-sqrt(M) sqrt(M)]);
qamData = qammod(y_int,M);
constdiag(qamData)

%DEMODULATION QAM
demodData = qamdemod(noisySound,M);
demodData = demodData*16/1000;
isequal(y_int,demodData);
playObjn=audioplayer(demodData,Fs);
play(playObjn);

%LOWPASS FILTER
Fn = Fs/2;                                              % Nyquist Frequency (Hz)
Wp = 1000/Fn;                                           % Passband Frequency (Normalised)
Ws = 1010/Fn;                                           % Stopband Frequency (Normalised)
Rp =   1;                                               % Passband Ripple (dB)
Rs = 150;                                               % Stopband Ripple (dB)
[n,Ws] = cheb2ord(Wp,Ws,Rp,Rs);                         % Filter Order
[z,p,k] = cheby2(n,Rs,Ws,'low');                        % Filter Design
[soslp,glp] = zp2sos(z,p,k);                            % Convert To Second-Order-Section For Stability
figure(3)
freqz(soslp, 2^16, Fs)                                  % Filter Bode Plot
filtered_sound = filtfilt(soslp, glp, demodData);
%sound(filtered_sound, 44100)
</code>```

where am i doing wrong?

I tried 16QAM and 32QAM but result is the same.

Body:
I am trying to make an acoustic modem with matlab. It records sound an stores it in an array, modulates it using 64-QAM and adds then demodulates it. But the demodulated sound and recorded sound are not the same.
Here is the code:

clear;
clc;
M = 64;      % Modulation order (alphabet size or number of points in signal constellation)
k = log2(M);
Fs=44100;
Nbits=8;
nChannels=1;
SNR=250;

%audio recording
recObj=audiorecorder(Fs,Nbits,nChannels);
recDuration=3;
disp("Begin speaking.")s
recordblocking(recObj,recDuration);
disp("2 sec pause")
pause(2)
disp("End of recording")
y=getaudiodata(recObj);
plot(y);
% playObj=audioplayer(y,Fs);
% play(playObj);
Ts=-(1/Fs)/2:1:(1/Fs)/2;
figure
subplot(1,2,1);
plottf(y,Ts,'t');
subplot(1,2,2);
plottf(y,Ts,'f');

%MODULATION QAM
y_int = abs(round(y*1000/16));
constdiag = comm.ConstellationDiagram('XLimits',[-sqrt(M) sqrt(M)],'YLimits',[-sqrt(M) sqrt(M)]);
qamData = qammod(y_int,M);
constdiag(qamData)

%DEMODULATION QAM
demodData = qamdemod(noisySound,M);
demodData = demodData*16/1000;
isequal(y_int,demodData);
playObjn=audioplayer(demodData,Fs);
play(playObjn);

%LOWPASS FILTER
Fn = Fs/2;                                              % Nyquist Frequency (Hz)
Wp = 1000/Fn;                                           % Passband Frequency (Normalised)
Ws = 1010/Fn;                                           % Stopband Frequency (Normalised)
Rp =   1;                                               % Passband Ripple (dB)
Rs = 150;                                               % Stopband Ripple (dB)
[n,Ws] = cheb2ord(Wp,Ws,Rp,Rs);                         % Filter Order
[z,p,k] = cheby2(n,Rs,Ws,'low');                        % Filter Design
[soslp,glp] = zp2sos(z,p,k);                            % Convert To Second-Order-Section For Stability
figure(3)
freqz(soslp, 2^16, Fs)                                  % Filter Bode Plot
filtered_sound = filtfilt(soslp, glp, demodData);
%sound(filtered_sound, 44100)

where am i doing wrong?

I tried 16QAM and 32QAM but result is the same.


问:
Javafx - Add action to button click on table row
I have a problem with the below code. On click the last row button, i want to get the current row data and execute a delete to SQL database bun I don't know how to get the row data.

I create the table and column in the fxml file and populate it with data and button on MainController and HomeController but I spent many hours looking for a solution to get the row data on witch the button is located.

HomeController.java

```<code>
public class HomeController implements Initializable{
    ObservableList<Book> recordsBook = FXCollections.observableArrayList();
    ObservableList<BorrowedBook> recordsBorrowedBooks = FXCollections.observableArrayList();
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

    }
    public ObservableList<Book> getBooks(){
        DatabaseConnection connectionNew = new DatabaseConnection();
        Connection connectDB = connectionNew.getConnection();

        String books = "SELECT * FROM books";
        try{
            Statement statement = connectDB.createStatement();
            ResultSet rs = statement.executeQuery(books);

            while(rs.next()){
                Book book = new Book(rs.getInt("Id"),rs.getString("Title"),rs.getString("PublicatedOn"),rs.getString("PublishingHouse"),rs.getString("Cover"),rs.getString("Summary"),rs.getInt("Price"));
                recordsBook.add(book);
            }
        }catch (Exception e) {
            throw new RuntimeException("unhandled", e);
        }

        return recordsBook;
    }

    public ObservableList<BorrowedBook> getBorrowedBooks(int userId){
        DatabaseConnection connectionNew = new DatabaseConnection();
        Connection connectDB = connectionNew.getConnection();

        String books = "SELECT b.Title,a.borrowDate,a.returnDate,a.id FROM borrowed_books a INNER JOIN books b on a.bookId = b.Id INNER JOIN users c on a.userId = c.Id WHERE a.userId = " + userId;
        try{
            Statement statement = connectDB.createStatement();
            ResultSet rs = statement.executeQuery(books);
            while(rs.next()){
                int remainingDays = getDaysDiff(rs.getString("ReturnDate"));

                Button returnOnClick = new Button("Inapoiaza");
                returnOnClick.setOnAction((ActionEvent event) -> {
                    System.out.println(event);
                });

                BorrowedBook borrowedBook = new BorrowedBook(rs.getString("Title"), rs.getString("BorrowDate"), rs.getString("ReturnDate"), remainingDays, returnOnClick);

                recordsBorrowedBooks.add(borrowedBook);
            }
        }catch (Exception e) {
            throw new RuntimeException("unhandled", e);
        }

        return recordsBorrowedBooks;
    }

    public boolean borrowBook(Integer bookId, Integer userId) throws SQLException {
        DatabaseConnection connectionNew = new DatabaseConnection();
        Connection connectDB = connectionNew.getConnection();
        LocalDate date = LocalDate.now();

        String checkBookExist = "SELECT count(1) FROM borrowed_books WHERE bookId= ? AND userId =? AND `returnDate` > CURRENT_DATE()";
        PreparedStatement prepareStatementSelect=connectDB.prepareStatement(checkBookExist);
        prepareStatementSelect.setInt(1, bookId);
        prepareStatementSelect.setInt(2, userId);

        try{
            ResultSet rs = prepareStatementSelect.executeQuery();

            while(rs.next()){

                if(rs.getInt(1) == 0){
                    String borrowString = "INSERT INTO borrowed_books (bookId, userId, borrowDate, returnDate) VALUES (?, ?, ?, ?);";
                    PreparedStatement prepareStatementInsert=connectDB.prepareStatement(borrowString);
                    prepareStatementInsert.setInt(1, bookId);
                    prepareStatementInsert.setInt(2, userId);
                    prepareStatementInsert.setString(3, date.toString());
                    prepareStatementInsert.setString(4, String.valueOf(date.plusMonths(1)));
                    try{
                        prepareStatementInsert.executeUpdate();
                        return true;
                    }catch (Exception e) {
                        throw new RuntimeException("unhandled", e);
                    }
                }else{
                    return false;
                }
            }
        }catch (Exception e) {
            throw new RuntimeException("unhandled", e);
        }
        return false;
    }
    public int getDaysDiff(String dateStop) throws ParseException {
        LocalDate dt1 = LocalDate.now();
        LocalDate dt2 = LocalDate.parse(dateStop);

        long diffDays = ChronoUnit.DAYS.between(dt1, dt2);

        return (int)diffDays;
    }
}

</code>```

MainController.java

```<code>package com.example.library;
import javafx.beans.binding.Bindings;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;

public class MainController implements Initializable {

    private static String paneName;
    private static String defaultImagePath = "C:\\Users\\costi\\Desktop\\LibraryImages\\";
    private static String defaultImageName = "default.png";
    public TableView<Book> tableViewSearch, tableViewHome;
    public TableView<BorrowedBook> tableViewBorrowed;
    public TableColumn<Book,String> colActions, colSearchTitle, colHomeTitle, colSearchPublicatedOn, colHomePublicatedOn, colSearchPublishingHouse, colHomePublishingHouse, colSearchSummary, colHomeSummary, colBorrowedTitle, colBorrowedDateStart, colBorrowedDateEnd;
    public TableColumn<Book,Integer> colSearchPrice, colHomePrice, colSearchId, colHomeId, colBorrowedRemainingDays;
    @FXML
    private Button cancelButton, menuHomeButton, menuSearchButton, borrowBookButton, menuBorrowButton;
    @FXML
    private Pane paneHome, paneSearch, paneBookDetails, paneBorrowed;
    @FXML
    private TextField searchField, titleField, publishingHouseField, priceField, bookIdField;
    @FXML
    private DatePicker publishedOnField;
    @FXML
    private TextArea summaryTextArea;
    @FXML
    private FlowPane flowPaneCoverImage;
    @FXML
    private Label statusLabel;

    public void initialize(URL url, ResourceBundle resourceBundle) {
        paneHome.toFront();
        setPaneName("paneHome");
        setMainData();
    }
    public void setMainData(){
        colHomeId.setCellValueFactory(new PropertyValueFactory<>("Id"));
        colHomeTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
        colHomePublicatedOn.setCellValueFactory(new PropertyValueFactory<>("PublicatedOn"));
        colHomePublishingHouse.setCellValueFactory(new PropertyValueFactory<>("PublishingHouse"));
        colHomeSummary.setCellValueFactory(new PropertyValueFactory<>("Summary"));
        colHomePrice.setCellValueFactory(new PropertyValueFactory<>("Price"));
        HomeController homeController = new HomeController();
        tableViewHome.setRowFactory( tv -> {
            TableRow<Book> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
                    paneBookDetails.toFront();
                    Book rowData = row.getItem();

                    String date = rowData.getPublicatedOn();
                    var dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
                    var dateTime = LocalDate.parse(date, dateTimeFormatter);

                    bookIdField.setText(Integer.toString(rowData.getId()));
                    titleField.setText(rowData.getTitle());
                    publishingHouseField.setText(rowData.getPublishingHouse());
                    priceField.setText(Integer.toString(rowData.getPrice()));
                    publishedOnField.setValue(dateTime);
                    summaryTextArea.setText(rowData.getSummary());

                    InputStream stream = null;
                    try {
                        stream = new FileInputStream(defaultImagePath + rowData.getCover());
                    } catch (FileNotFoundException e) {
                        try {
                            stream = new FileInputStream(defaultImagePath + defaultImageName);
                        } catch (FileNotFoundException ex) {
                        }
                    }

                    Image image = new Image(stream);
                    ImageView imageView = new ImageView(image);
                    imageView.setFitHeight(flowPaneCoverImage.getHeight());
                    imageView.setFitWidth(flowPaneCoverImage.getWidth());
                    flowPaneCoverImage.getChildren().clear();
                    flowPaneCoverImage.getChildren().add(imageView);
                }
            });
            return row ;
        });

        tableViewHome.setItems(homeController.getBooks());
    }

    public void searchButtonOnAction(ActionEvent event) {
        colSearchId.setCellValueFactory(new PropertyValueFactory<>("Id"));
        colSearchTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
        colSearchPublicatedOn.setCellValueFactory(new PropertyValueFactory<>("PublicatedOn"));
        colSearchPublishingHouse.setCellValueFactory(new PropertyValueFactory<>("PublishingHouse"));
        colSearchSummary.setCellValueFactory(new PropertyValueFactory<>("Summary"));
        colSearchPrice.setCellValueFactory(new PropertyValueFactory<>("Price"));
        tableViewSearch.setRowFactory( tv -> {
            TableRow<Book> row = new TableRow<>();
            row.setOnMouseClicked(ev -> {
                if (ev.getClickCount() == 2 && (! row.isEmpty()) ) {
                    paneBookDetails.toFront();
                    Book rowData = row.getItem();

                    String date = rowData.getPublicatedOn();
                    var dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
                    var dateTime = LocalDate.parse(date, dateTimeFormatter);

                    bookIdField.setText(Integer.toString(rowData.getId()));
                    titleField.setText(rowData.getTitle());
                    publishingHouseField.setText(rowData.getPublishingHouse());
                    priceField.setText(Integer.toString(rowData.getPrice()));
                    publishedOnField.setValue(dateTime);
                    summaryTextArea.setText(rowData.getSummary());

                    InputStream stream = null;
                    try {
                        stream = new FileInputStream(defaultImagePath + rowData.getCover());
                    } catch (FileNotFoundException e) {
                        try {
                            stream = new FileInputStream(defaultImagePath + defaultImageName);
                        } catch (FileNotFoundException ex) {
                        }
                    }

                    Image image = new Image(stream);
                    ImageView imageView = new ImageView(image);
                    imageView.setFitHeight(flowPaneCoverImage.getHeight());
                    imageView.setFitWidth(flowPaneCoverImage.getWidth());
                    flowPaneCoverImage.getChildren().clear();
                    flowPaneCoverImage.getChildren().add(imageView);
                }
            });
            return row ;
        });
        SearchController searchController = new SearchController();
        tableViewSearch.setItems(searchController.getBooks(searchField.getText()));
    }

    public void setBorrowedData(){
        colBorrowedTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
        colBorrowedDateStart.setCellValueFactory(new PropertyValueFactory<>("DateStart"));
        colBorrowedDateEnd.setCellValueFactory(new PropertyValueFactory<>("DateEnd"));
        colBorrowedRemainingDays.setCellValueFactory(new PropertyValueFactory<>("RemainingDays"));
        colActions.setCellValueFactory(new PropertyValueFactory<>("button"));
        HomeController homeController = new HomeController();
        tableViewBorrowed.setRowFactory( tv -> {
            TableRow<BorrowedBook> row = new TableRow<>(){
                @Override
                public void updateItem(BorrowedBook item, boolean empty) {
                    super.updateItem(item, empty) ;
                    if (item == null) {
                        setStyle("");
                    } else if (item.getRemainingDays() < 0) {
                        setStyle("-fx-background-color: #ff5d5d;");
                    } else {
                        setStyle("");
                    }
                }
            };
            return row ;
        });

        tableViewBorrowed.setItems(homeController.getBorrowedBooks(Global.getUserId()));
    }

    public void cancelButtonOnAction(ActionEvent event){
        Stage stage = (Stage) cancelButton.getScene().getWindow();
        stage.close();
    }

    public void menuButtonOnAction(ActionEvent event){
        statusLabel.setText("");
        if(event.getSource() == menuHomeButton){
            setPaneName("paneHome");
            paneHome.toFront();
            setMainData();
        }else if(event.getSource() == menuSearchButton){
            setPaneName("paneSearch");
            paneSearch.toFront();
        }else if(event.getSource() == menuBorrowButton){
            setPaneName("paneBorrowed");
            paneBorrowed.toFront();
            setBorrowedData();
        }
    }

    public void backButtonOnAction(ActionEvent event){
        var lastPannelName = getPaneName();
        statusLabel.setText("");
        if(lastPannelName == "paneHome"){
            paneHome.toFront();
        }else if(lastPannelName == "paneSearch"){
            paneSearch.toFront();
        }
    }

    public void borrowBookOnAction(ActionEvent event){
        HomeController homeController = new HomeController();
        int currentUserId = Global.getUserId();
        var currentBookId = Integer.valueOf(bookIdField.getText());
        try {
            boolean inserted = homeController.borrowBook(currentBookId, currentUserId);
            if(inserted){
                statusLabel.setText("Cartea a fost imprumutata pentru 1 luna.");
            }else{
                statusLabel.setText("Ai imprumutat deja aceasta carte.");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getPaneName() {
        return paneName;
    }

    public static void setPaneName(String paneName) {
        MainController.paneName = paneName;
    }

}

</code>```

Body:
I have a problem with the below code. On click the last row button, i want to get the current row data and execute a delete to SQL database bun I don't know how to get the row data.

I create the table and column in the fxml file and populate it with data and button on MainController and HomeController but I spent many hours looking for a solution to get the row data on witch the button is located.

HomeController.java

public class HomeController implements Initializable{
    ObservableList<Book> recordsBook = FXCollections.observableArrayList();
    ObservableList<BorrowedBook> recordsBorrowedBooks = FXCollections.observableArrayList();
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

    }
    public ObservableList<Book> getBooks(){
        DatabaseConnection connectionNew = new DatabaseConnection();
        Connection connectDB = connectionNew.getConnection();

        String books = "SELECT * FROM books";
        try{
            Statement statement = connectDB.createStatement();
            ResultSet rs = statement.executeQuery(books);

            while(rs.next()){
                Book book = new Book(rs.getInt("Id"),rs.getString("Title"),rs.getString("PublicatedOn"),rs.getString("PublishingHouse"),rs.getString("Cover"),rs.getString("Summary"),rs.getInt("Price"));
                recordsBook.add(book);
            }
        }catch (Exception e) {
            throw new RuntimeException("unhandled", e);
        }

        return recordsBook;
    }

    public ObservableList<BorrowedBook> getBorrowedBooks(int userId){
        DatabaseConnection connectionNew = new DatabaseConnection();
        Connection connectDB = connectionNew.getConnection();

        String books = "SELECT b.Title,a.borrowDate,a.returnDate,a.id FROM borrowed_books a INNER JOIN books b on a.bookId = b.Id INNER JOIN users c on a.userId = c.Id WHERE a.userId = " + userId;
        try{
            Statement statement = connectDB.createStatement();
            ResultSet rs = statement.executeQuery(books);
            while(rs.next()){
                int remainingDays = getDaysDiff(rs.getString("ReturnDate"));

                Button returnOnClick = new Button("Inapoiaza");
                returnOnClick.setOnAction((ActionEvent event) -> {
                    System.out.println(event);
                });

                BorrowedBook borrowedBook = new BorrowedBook(rs.getString("Title"), rs.getString("BorrowDate"), rs.getString("ReturnDate"), remainingDays, returnOnClick);

                recordsBorrowedBooks.add(borrowedBook);
            }
        }catch (Exception e) {
            throw new RuntimeException("unhandled", e);
        }

        return recordsBorrowedBooks;
    }

    public boolean borrowBook(Integer bookId, Integer userId) throws SQLException {
        DatabaseConnection connectionNew = new DatabaseConnection();
        Connection connectDB = connectionNew.getConnection();
        LocalDate date = LocalDate.now();

        String checkBookExist = "SELECT count(1) FROM borrowed_books WHERE bookId= ? AND userId =? AND `returnDate` > CURRENT_DATE()";
        PreparedStatement prepareStatementSelect=connectDB.prepareStatement(checkBookExist);
        prepareStatementSelect.setInt(1, bookId);
        prepareStatementSelect.setInt(2, userId);

        try{
            ResultSet rs = prepareStatementSelect.executeQuery();

            while(rs.next()){

                if(rs.getInt(1) == 0){
                    String borrowString = "INSERT INTO borrowed_books (bookId, userId, borrowDate, returnDate) VALUES (?, ?, ?, ?);";
                    PreparedStatement prepareStatementInsert=connectDB.prepareStatement(borrowString);
                    prepareStatementInsert.setInt(1, bookId);
                    prepareStatementInsert.setInt(2, userId);
                    prepareStatementInsert.setString(3, date.toString());
                    prepareStatementInsert.setString(4, String.valueOf(date.plusMonths(1)));
                    try{
                        prepareStatementInsert.executeUpdate();
                        return true;
                    }catch (Exception e) {
                        throw new RuntimeException("unhandled", e);
                    }
                }else{
                    return false;
                }
            }
        }catch (Exception e) {
            throw new RuntimeException("unhandled", e);
        }
        return false;
    }
    public int getDaysDiff(String dateStop) throws ParseException {
        LocalDate dt1 = LocalDate.now();
        LocalDate dt2 = LocalDate.parse(dateStop);

        long diffDays = ChronoUnit.DAYS.between(dt1, dt2);

        return (int)diffDays;
    }
}

MainController.java

package com.example.library;
import javafx.beans.binding.Bindings;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;

public class MainController implements Initializable {

    private static String paneName;
    private static String defaultImagePath = "C:\\Users\\costi\\Desktop\\LibraryImages\\";
    private static String defaultImageName = "default.png";
    public TableView<Book> tableViewSearch, tableViewHome;
    public TableView<BorrowedBook> tableViewBorrowed;
    public TableColumn<Book,String> colActions, colSearchTitle, colHomeTitle, colSearchPublicatedOn, colHomePublicatedOn, colSearchPublishingHouse, colHomePublishingHouse, colSearchSummary, colHomeSummary, colBorrowedTitle, colBorrowedDateStart, colBorrowedDateEnd;
    public TableColumn<Book,Integer> colSearchPrice, colHomePrice, colSearchId, colHomeId, colBorrowedRemainingDays;
    @FXML
    private Button cancelButton, menuHomeButton, menuSearchButton, borrowBookButton, menuBorrowButton;
    @FXML
    private Pane paneHome, paneSearch, paneBookDetails, paneBorrowed;
    @FXML
    private TextField searchField, titleField, publishingHouseField, priceField, bookIdField;
    @FXML
    private DatePicker publishedOnField;
    @FXML
    private TextArea summaryTextArea;
    @FXML
    private FlowPane flowPaneCoverImage;
    @FXML
    private Label statusLabel;

    public void initialize(URL url, ResourceBundle resourceBundle) {
        paneHome.toFront();
        setPaneName("paneHome");
        setMainData();
    }
    public void setMainData(){
        colHomeId.setCellValueFactory(new PropertyValueFactory<>("Id"));
        colHomeTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
        colHomePublicatedOn.setCellValueFactory(new PropertyValueFactory<>("PublicatedOn"));
        colHomePublishingHouse.setCellValueFactory(new PropertyValueFactory<>("PublishingHouse"));
        colHomeSummary.setCellValueFactory(new PropertyValueFactory<>("Summary"));
        colHomePrice.setCellValueFactory(new PropertyValueFactory<>("Price"));
        HomeController homeController = new HomeController();
        tableViewHome.setRowFactory( tv -> {
            TableRow<Book> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
                    paneBookDetails.toFront();
                    Book rowData = row.getItem();

                    String date = rowData.getPublicatedOn();
                    var dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
                    var dateTime = LocalDate.parse(date, dateTimeFormatter);

                    bookIdField.setText(Integer.toString(rowData.getId()));
                    titleField.setText(rowData.getTitle());
                    publishingHouseField.setText(rowData.getPublishingHouse());
                    priceField.setText(Integer.toString(rowData.getPrice()));
                    publishedOnField.setValue(dateTime);
                    summaryTextArea.setText(rowData.getSummary());

                    InputStream stream = null;
                    try {
                        stream = new FileInputStream(defaultImagePath + rowData.getCover());
                    } catch (FileNotFoundException e) {
                        try {
                            stream = new FileInputStream(defaultImagePath + defaultImageName);
                        } catch (FileNotFoundException ex) {
                        }
                    }

                    Image image = new Image(stream);
                    ImageView imageView = new ImageView(image);
                    imageView.setFitHeight(flowPaneCoverImage.getHeight());
                    imageView.setFitWidth(flowPaneCoverImage.getWidth());
                    flowPaneCoverImage.getChildren().clear();
                    flowPaneCoverImage.getChildren().add(imageView);
                }
            });
            return row ;
        });

        tableViewHome.setItems(homeController.getBooks());
    }

    public void searchButtonOnAction(ActionEvent event) {
        colSearchId.setCellValueFactory(new PropertyValueFactory<>("Id"));
        colSearchTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
        colSearchPublicatedOn.setCellValueFactory(new PropertyValueFactory<>("PublicatedOn"));
        colSearchPublishingHouse.setCellValueFactory(new PropertyValueFactory<>("PublishingHouse"));
        colSearchSummary.setCellValueFactory(new PropertyValueFactory<>("Summary"));
        colSearchPrice.setCellValueFactory(new PropertyValueFactory<>("Price"));
        tableViewSearch.setRowFactory( tv -> {
            TableRow<Book> row = new TableRow<>();
            row.setOnMouseClicked(ev -> {
                if (ev.getClickCount() == 2 && (! row.isEmpty()) ) {
                    paneBookDetails.toFront();
                    Book rowData = row.getItem();

                    String date = rowData.getPublicatedOn();
                    var dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
                    var dateTime = LocalDate.parse(date, dateTimeFormatter);

                    bookIdField.setText(Integer.toString(rowData.getId()));
                    titleField.setText(rowData.getTitle());
                    publishingHouseField.setText(rowData.getPublishingHouse());
                    priceField.setText(Integer.toString(rowData.getPrice()));
                    publishedOnField.setValue(dateTime);
                    summaryTextArea.setText(rowData.getSummary());

                    InputStream stream = null;
                    try {
                        stream = new FileInputStream(defaultImagePath + rowData.getCover());
                    } catch (FileNotFoundException e) {
                        try {
                            stream = new FileInputStream(defaultImagePath + defaultImageName);
                        } catch (FileNotFoundException ex) {
                        }
                    }

                    Image image = new Image(stream);
                    ImageView imageView = new ImageView(image);
                    imageView.setFitHeight(flowPaneCoverImage.getHeight());
                    imageView.setFitWidth(flowPaneCoverImage.getWidth());
                    flowPaneCoverImage.getChildren().clear();
                    flowPaneCoverImage.getChildren().add(imageView);
                }
            });
            return row ;
        });
        SearchController searchController = new SearchController();
        tableViewSearch.setItems(searchController.getBooks(searchField.getText()));
    }

    public void setBorrowedData(){
        colBorrowedTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
        colBorrowedDateStart.setCellValueFactory(new PropertyValueFactory<>("DateStart"));
        colBorrowedDateEnd.setCellValueFactory(new PropertyValueFactory<>("DateEnd"));
        colBorrowedRemainingDays.setCellValueFactory(new PropertyValueFactory<>("RemainingDays"));
        colActions.setCellValueFactory(new PropertyValueFactory<>("button"));
        HomeController homeController = new HomeController();
        tableViewBorrowed.setRowFactory( tv -> {
            TableRow<BorrowedBook> row = new TableRow<>(){
                @Override
                public void updateItem(BorrowedBook item, boolean empty) {
                    super.updateItem(item, empty) ;
                    if (item == null) {
                        setStyle("");
                    } else if (item.getRemainingDays() < 0) {
                        setStyle("-fx-background-color: #ff5d5d;");
                    } else {
                        setStyle("");
                    }
                }
            };
            return row ;
        });

        tableViewBorrowed.setItems(homeController.getBorrowedBooks(Global.getUserId()));
    }

    public void cancelButtonOnAction(ActionEvent event){
        Stage stage = (Stage) cancelButton.getScene().getWindow();
        stage.close();
    }

    public void menuButtonOnAction(ActionEvent event){
        statusLabel.setText("");
        if(event.getSource() == menuHomeButton){
            setPaneName("paneHome");
            paneHome.toFront();
            setMainData();
        }else if(event.getSource() == menuSearchButton){
            setPaneName("paneSearch");
            paneSearch.toFront();
        }else if(event.getSource() == menuBorrowButton){
            setPaneName("paneBorrowed");
            paneBorrowed.toFront();
            setBorrowedData();
        }
    }

    public void backButtonOnAction(ActionEvent event){
        var lastPannelName = getPaneName();
        statusLabel.setText("");
        if(lastPannelName == "paneHome"){
            paneHome.toFront();
        }else if(lastPannelName == "paneSearch"){
            paneSearch.toFront();
        }
    }

    public void borrowBookOnAction(ActionEvent event){
        HomeController homeController = new HomeController();
        int currentUserId = Global.getUserId();
        var currentBookId = Integer.valueOf(bookIdField.getText());
        try {
            boolean inserted = homeController.borrowBook(currentBookId, currentUserId);
            if(inserted){
                statusLabel.setText("Cartea a fost imprumutata pentru 1 luna.");
            }else{
                statusLabel.setText("Ai imprumutat deja aceasta carte.");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getPaneName() {
        return paneName;
    }

    public static void setPaneName(String paneName) {
        MainController.paneName = paneName;
    }

}


问:
Android Bluetooth onCharacteristicChanged just one time, right after i call writeCharacteristic
The function onCharacteristicChanged is called just one time every time i call a writecharacteristic. What i expect to happen is onCharacteristicChanged to be called everytime something actually change. For exemple the device I'm using have a characteristic that gets the time of the system, so this characteristic change every second but onCharacteristicChanged doesn't notify me that this change is happening if I don't call the writecharacteristic method</p>
```<code>        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            with(characteristic) {
                addGlog("\uD83D\uDCE2 BluetoothGattCallback: Characteristic $uuid changed | value: ${value.toHexString()}")
            }
        }

    @SuppressLint("MissingPermission")
    fun writeDescriptor(descriptor: BluetoothGattDescriptor, payload: ByteArray) {
        actual_gatt?.let { gatt ->
            descriptor.value = payload
            gatt.writeDescriptor(descriptor)

        } ?: addGlog("Not connected to a BLE device!")

    }

@SuppressLint("MissingPermission")
    fun enableNotifications(characteristic: BluetoothGattCharacteristic) { //nuova versione il meno invasiva possibile

        var cccdUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") //valore temporaneo
        addGlog("BluetoothGattDescriptor for ${characteristic.uuid.toString()}")
        for (descriptor in characteristic.descriptors) {
            addGlog("> " + descriptor.uuid.toString())
            cccdUuid = descriptor.uuid
        }

        val payload = when {
            characteristic.isIndicatable() -> BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
            characteristic.isNotifiable() -> BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
            else -> {
                addGlog("ConnectionManager: ${characteristic.uuid} doesn't support notifications/indications")
                return
            }
        }

        characteristic.getDescriptor(cccdUuid)?.let { cccDescriptor ->
            if (actual_gatt?.setCharacteristicNotification(characteristic, true) == false) {
                addGlog("ConnectionManager: setCharacteristicNotification failed for ${characteristic.uuid}")
                return
            }

            writeDescriptor(cccDescriptor, payload)
            addGlog("\uD83D\uDD14 enableNotification with cccDescriptor: ${cccDescriptor.toString()} and cccdUuid ${cccdUuid.toString()} completed")

        } ?: addGlog("ConnectionManager: ${characteristic.uuid} doesn't contain the CCC descriptor!")
    }
</code>```

Body:
The function onCharacteristicChanged is called just one time every time i call a writecharacteristic. What i expect to happen is onCharacteristicChanged to be called everytime something actually change. For exemple the device I'm using have a characteristic that gets the time of the system, so this characteristic change every second but onCharacteristicChanged doesn't notify me that this change is happening if I don't call the writecharacteristic method

        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            with(characteristic) {
                addGlog("\uD83D\uDCE2 BluetoothGattCallback: Characteristic $uuid changed | value: ${value.toHexString()}")
            }
        }

    @SuppressLint("MissingPermission")
    fun writeDescriptor(descriptor: BluetoothGattDescriptor, payload: ByteArray) {
        actual_gatt?.let { gatt ->
            descriptor.value = payload
            gatt.writeDescriptor(descriptor)

        } ?: addGlog("Not connected to a BLE device!")

    }

@SuppressLint("MissingPermission")
    fun enableNotifications(characteristic: BluetoothGattCharacteristic) { //nuova versione il meno invasiva possibile

        var cccdUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") //valore temporaneo
        addGlog("BluetoothGattDescriptor for ${characteristic.uuid.toString()}")
        for (descriptor in characteristic.descriptors) {
            addGlog("> " + descriptor.uuid.toString())
            cccdUuid = descriptor.uuid
        }

        val payload = when {
            characteristic.isIndicatable() -> BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
            characteristic.isNotifiable() -> BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
            else -> {
                addGlog("ConnectionManager: ${characteristic.uuid} doesn't support notifications/indications")
                return
            }
        }

        characteristic.getDescriptor(cccdUuid)?.let { cccDescriptor ->
            if (actual_gatt?.setCharacteristicNotification(characteristic, true) == false) {
                addGlog("ConnectionManager: setCharacteristicNotification failed for ${characteristic.uuid}")
                return
            }

            writeDescriptor(cccDescriptor, payload)
            addGlog("\uD83D\uDD14 enableNotification with cccDescriptor: ${cccDescriptor.toString()} and cccdUuid ${cccdUuid.toString()} completed")

        } ?: addGlog("ConnectionManager: ${characteristic.uuid} doesn't contain the CCC descriptor!")
    }