问:
How to handle back button in case of fragment without removing previous views?
I have one activity (MainActivity) and two fragments(FirstFragment,SecondFragment) as the lifecycle of activity is handled by the os we can press back button and go to previous activity without any hassle . But when I try to go back by pressing back button from one fragment to another fragment although it takes me back to the fragment but removes all my view. Meaning I can't see any element of that fragment . A more detailed explanation is down below with code

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val activity1Button = findViewById<Button>(R.id.activity_1_Button)

        activity1Button.setOnClickListener {

            supportFragmentManager.beginTransaction()
                .replace(R.id.mainActivity, FirstFragment()).addToBackStack(null).commit()
        }
    }
}
</code>```

The main activity has a button which can take the user to the next fragment(FirstFragment) while adding it to the BackStack

FirstFragment.kt

```<code>class FirstFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        container?.removeAllViews()

        val view = inflater.inflate(R.layout.fragment_first, container, false)

        val firstFragmentButton = view.findViewById<Button>(R.id.firstFragmentButton)

        firstFragmentButton.setOnClickListener {

            requireActivity().supportFragmentManager.beginTransaction()
                .replace(R.id.firsFragment, SecondFragment())
                .addToBackStack("tag")
                .commit()
        }

        return view
    }

}
</code>```

Now from this fragment user can go to another fragment (SecondFragment)

SecondFragment.kt

```<code>class SecondFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        container?.removeAllViews()
        return inflater.inflate(R.layout.fragment_second, container, false)
    }

}
</code>```

However I am removing all the previous container views as without doing this I  the elements of previous fragment/ activity is also visible even when I am in a new fragment. Now when once I have pressed buttons to come to SecondFragment and pressing back button to go to FirstFragment I cant see the buttons anymore in the FirstFragment but through the Layout Inspector it is confirmed that I am in the desired fragments layout. What can be done to solve this issue ?

I have tried to implement this method below but it didn't solve my problem .

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            val manager: FragmentManager = requireActivity().supportFragmentManager
            if (manager.backStackEntryCount > 0) {
                manager.popBackStack()
            }
        }
    })
}
</code>```

Thanks in advance .

Body:
I have one activity (MainActivity) and two fragments(FirstFragment,SecondFragment) as the lifecycle of activity is handled by the os we can press back button and go to previous activity without any hassle . But when I try to go back by pressing back button from one fragment to another fragment although it takes me back to the fragment but removes all my view. Meaning I can't see any element of that fragment . A more detailed explanation is down below with code

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val activity1Button = findViewById<Button>(R.id.activity_1_Button)

        activity1Button.setOnClickListener {

            supportFragmentManager.beginTransaction()
                .replace(R.id.mainActivity, FirstFragment()).addToBackStack(null).commit()
        }
    }
}

The main activity has a button which can take the user to the next fragment(FirstFragment) while adding it to the BackStack

FirstFragment.kt

class FirstFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        container?.removeAllViews()

        val view = inflater.inflate(R.layout.fragment_first, container, false)

        val firstFragmentButton = view.findViewById<Button>(R.id.firstFragmentButton)

        firstFragmentButton.setOnClickListener {

            requireActivity().supportFragmentManager.beginTransaction()
                .replace(R.id.firsFragment, SecondFragment())
                .addToBackStack("tag")
                .commit()
        }

        return view
    }

}

Now from this fragment user can go to another fragment (SecondFragment)

SecondFragment.kt

class SecondFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        container?.removeAllViews()
        return inflater.inflate(R.layout.fragment_second, container, false)
    }

}

However I am removing all the previous container views as without doing this I  the elements of previous fragment/ activity is also visible even when I am in a new fragment. Now when once I have pressed buttons to come to SecondFragment and pressing back button to go to FirstFragment I cant see the buttons anymore in the FirstFragment but through the Layout Inspector it is confirmed that I am in the desired fragments layout. What can be done to solve this issue ?

I have tried to implement this method below but it didn't solve my problem .

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            val manager: FragmentManager = requireActivity().supportFragmentManager
            if (manager.backStackEntryCount > 0) {
                manager.popBackStack()
            }
        }
    })
}

Thanks in advance .


来源: stackexchange

问:
Quectel EC21 ARM Trust Zone to secure TLS certificates
I'm exploring the possibility of using the Qualcomm Trust Zone to secure TLS certificates and sensitive data, in a Quectel EC21, which mounts a Qualcomm MDM9607

I don't know if Quectel EC21 is suitable for Trust Zone final users usages.

I’m running EC21EFAR06A05M4G_OCPU_20.002.20.002 Quectel FW Version, and typing “make kernel_menuconfig” I found “CONFIG_QTZONE” kernel configuration option.
Once enabled it, I built the kernel and flashed, I was able to found a new device in /dev (/dev/tzone).

Quectel EC21 mounts Qualcomm MDM9607 SOC.

Moreover in EC21EFAR06A05M4G_OCPU_20.002.20.002_SDK (the Quectel released SDK) is present a Trust Zone example (ql-ol-sdk/ql-ol-extsdk/example/tzone)

I built it and after tried to execute it, I got

```<code>root@mdm9607-perf:/# ./tzapp
dev tzone fd = 3
tzapp aes_gen_key key.blob
tzapp aes_import_key key.blob
tzapp aes_enc key.blob plain_file enc_file
tzapp aes_dec key.blob enc_file dec_file
tzapp rsa_gen_key key.blob
tzapp rsa_sign key.blob plain_file sign_file
tzapp rsa_verify key.blob plain_file sign_file
tzapp rsa_import_keypair key.blob
tzapp rsa_export_pubkey key.blob pubkey_file
tzapp random_gen rnd.blob
tzapp fuse_read <row_num>
</code>```

I’m not able to got how I could use it.
I really don't know how tzapp could import or export rsa keys, and general how it works.

ContentLicense: CC BY-SA 4.0

Body:
I'm exploring the possibility of using the Qualcomm Trust Zone to secure TLS certificates and sensitive data, in a Quectel EC21, which mounts a Qualcomm MDM9607

I don't know if Quectel EC21 is suitable for Trust Zone final users usages.

I’m running EC21EFAR06A05M4G_OCPU_20.002.20.002 Quectel FW Version, and typing “make kernel_menuconfig” I found “CONFIG_QTZONE” kernel configuration option.
Once enabled it, I built the kernel and flashed, I was able to found a new device in /dev (/dev/tzone).

Quectel EC21 mounts Qualcomm MDM9607 SOC.

Moreover in EC21EFAR06A05M4G_OCPU_20.002.20.002_SDK (the Quectel released SDK) is present a Trust Zone example (ql-ol-sdk/ql-ol-extsdk/example/tzone)

I built it and after tried to execute it, I got

root@mdm9607-perf:/# ./tzapp
dev tzone fd = 3
tzapp aes_gen_key key.blob
tzapp aes_import_key key.blob
tzapp aes_enc key.blob plain_file enc_file
tzapp aes_dec key.blob enc_file dec_file
tzapp rsa_gen_key key.blob
tzapp rsa_sign key.blob plain_file sign_file
tzapp rsa_verify key.blob plain_file sign_file
tzapp rsa_import_keypair key.blob
tzapp rsa_export_pubkey key.blob pubkey_file
tzapp random_gen rnd.blob
tzapp fuse_read <row_num>

I’m not able to got how I could use it.
I really don't know how tzapp could import or export rsa keys, and general how it works.


问:
Laravel 9 set custom email SMTP configuration
My system is simple. if the user clicks the test button i need to send a text email to the same email id which i used.

i have tried to set config in my controller

```<code>config(['mail.username' => $username]);
</code>```

but it gives error (Auth error)

I need a step by step approach to be done for this system.

Body:
My system is simple. if the user clicks the test button i need to send a text email to the same email id which i used.

i have tried to set config in my controller

config(['mail.username' => $username]);

but it gives error (Auth error)

I need a step by step approach to be done for this system.


问:
What is the correct way to end a Watchdog observer without a sleep loop?
I am relatively new to python and programing in general. This is my first question on Stack Overflow so thank you for any responses in advance!  My question is this. I have a Python web application that is using the django framework. A new feature of that web application requires the use of a locally installed command line tool on the server, that tool dumps an output file to a directory previously created. I want to watch that directory and when a file is created in it that ends in .json call a parsing function. Enter the Watchdog library. I have followed a number of tutorials/checked on here for how to correctly setup an observer. They all have the observer being started and then immediately going into a time.sleep(1) loop while waiting for something to happen.  However since this is a django webapp I don't want to sit and wait while the watchdog observer is looking for the file to be created. Here is an example code from Geeks for Geeks:

```<code>if __name__ == "__main__":
    # Set the format for logging info
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    # Set format for displaying path
    path = sys.argv[1] if len(sys.argv) > 1 else '.'

    # Initialize logging event handler
    event_handler = LoggingEventHandler()

    # Initialize Observer
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)

    # Start the observer
    observer.start()
    try:
        while True:
            # Set the thread sleep time
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
</code>```

Heres what I have so far.

First I am creating a class of folder monitors.

```<code>class MonitorFolder(FileSystemEventHandler):

    def on_created(self, event):
        if event.src_path.endswith(".json"):
            #call parseing function here ()
            print("stopping")
            self.observer.stop()
            self.observer.join()
</code>```
```<code>def createFileListener(curdir):
    src_path = curdir
    observer = Observer()
    event_handler=MonitorFolder(observer)
    observer.schedule(event_handler, path=src_path, recursive=True)
    print("Monitoring started")
    observer.start()

</code>```

The class of Monitor files is declared with a on_created function that eventually will call the parsing function and then stop itself. This works up until it tried to join. I assume it is because the thread is already being stopped that would run the .join(). When it attempts to run the self.observer.join() it raises a RuntimeError("cannot join current thread")

Below the class declaration is the function used to create a new instance of that class.

Any advice would be helpful!

Thank you in advance!

Body:
I am relatively new to python and programing in general. This is my first question on Stack Overflow so thank you for any responses in advance!  My question is this. I have a Python web application that is using the django framework. A new feature of that web application requires the use of a locally installed command line tool on the server, that tool dumps an output file to a directory previously created. I want to watch that directory and when a file is created in it that ends in .json call a parsing function. Enter the Watchdog library. I have followed a number of tutorials/checked on here for how to correctly setup an observer. They all have the observer being started and then immediately going into a time.sleep(1) loop while waiting for something to happen.  However since this is a django webapp I don't want to sit and wait while the watchdog observer is looking for the file to be created. Here is an example code from Geeks for Geeks:

if __name__ == "__main__":
    # Set the format for logging info
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    # Set format for displaying path
    path = sys.argv[1] if len(sys.argv) > 1 else '.'

    # Initialize logging event handler
    event_handler = LoggingEventHandler()

    # Initialize Observer
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)

    # Start the observer
    observer.start()
    try:
        while True:
            # Set the thread sleep time
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

Heres what I have so far.

First I am creating a class of folder monitors.

class MonitorFolder(FileSystemEventHandler):

    def on_created(self, event):
        if event.src_path.endswith(".json"):
            #call parseing function here ()
            print("stopping")
            self.observer.stop()
            self.observer.join()

def createFileListener(curdir):
    src_path = curdir
    observer = Observer()
    event_handler=MonitorFolder(observer)
    observer.schedule(event_handler, path=src_path, recursive=True)
    print("Monitoring started")
    observer.start()

The class of Monitor files is declared with a on_created function that eventually will call the parsing function and then stop itself. This works up until it tried to join. I assume it is because the thread is already being stopped that would run the .join(). When it attempts to run the self.observer.join() it raises a RuntimeError("cannot join current thread")

Below the class declaration is the function used to create a new instance of that class.

Any advice would be helpful!

Thank you in advance!


问:
AWS SDK method to list all applications(or pods) deployed in EKS cluster in AWS
I want to get list of all Applications Deployed inside an EKS cluster in AWS programatically. I am trying to find relevant SDK method to use. I checked EKS SDK JAVA. We can use
listClustersResult = eksClient.listClusters(listClustersRequest);
to list all the cluster but i did not find anything that can give me list of application deployed inside a cluster in EKS.

Can we do it in EKS or we need to use anything else?


问:
ora2pg (Unicode surrogate U+DBC0 is illegal in UTF-8)
I am extracting data using ora2pg from Oracle and get the below warning.

Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.721 (1800 recs/sec)
Unicode surrogate U+DF72 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DF72 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.721 (1802 recs/sec)
```
<p>and upon import i get this error.</p>
<blockquote>
```FATAL: ERROR: invalid byte sequence for encoding "UTF8": 0xed 0xaf 0x80
```
</blockquote>
<p>I've imported it directly using PG_DSN and not to a file but that didn't help either.</p>
<pre class="lang-none prettyprint-override"><code>[========================>] 1/1 tables (100.0%) end of scanning.
DBD::Pg::db pg_putcopyend failed: ERROR: invalid byte sequence for encoding "UTF8": 0xed 0xaf 0x80cs/sec)
CONTEXT: COPY phy_t1, line 1131 at /var/lib/pgsql/PERL_DBI_DBD/lib64/perl5/Ora2Pg.pm line 14716.
FATAL: ERROR: invalid byte sequence for encoding "UTF8": 0xed 0xaf 0x80
</code>```

When I use "iconv -f utf-16le -t UTF-8//TRANSLIT out.sql -o PHYCON_data.sql" I get "out of memory" error. I've even bumped work_mem from 4M to 200M but still get the below.

Any suggestions?

Body:
I am extracting data using ora2pg from Oracle and get the below warning.

Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.721 (1800 recs/sec)
Unicode surrogate U+DF72 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DF72 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.721 (1802 recs/sec)

and upon import i get this error.

FATAL: ERROR: invalid byte sequence for encoding "UTF8": 0xed 0xaf 0x80

I've imported it directly using PG_DSN and not to a file but that didn't help either.

[========================>] 1/1 tables (100.0%) end of scanning.
DBD::Pg::db pg_putcopyend failed: ERROR: invalid byte sequence for encoding "UTF8": 0xed 0xaf 0x80cs/sec)
CONTEXT: COPY phy_t1, line 1131 at /var/lib/pgsql/PERL_DBI_DBD/lib64/perl5/Ora2Pg.pm line 14716.
FATAL: ERROR: invalid byte sequence for encoding "UTF8": 0xed 0xaf 0x80

When I use "iconv -f utf-16le -t UTF-8//TRANSLIT out.sql -o PHYCON_data.sql" I get "out of memory" error. I've even bumped work_mem from 4M to 200M but still get the below.

Any suggestions?


问:
postscript rectangle dimensions
Drawing rectangles from postscript, it seems that the dimensions I give are taken as the middle points of the four lines; I would however like to get a rectangle with my given parameters as the outside dimensions.
For example:

```<code>newpath 4 setlinewidth 0 0 20 20 rectstroke
</code>```

seems to produce a square with sides of 24 points, rather than the 20 that I wanted.
Is my impression correct? If so, what to do about it? Of course I can declare a my_rectstroke( function, that will take the linewidth as a parameter plus the coordinates and dimensions, but perhaps there is a more elegant/less cumbersome way?

Title: postscript rectangle dimensions

Body:
Drawing rectangles from postscript, it seems that the dimensions I give are taken as the middle points of the four lines; I would however like to get a rectangle with my given parameters as the outside dimensions.
For example:

newpath 4 setlinewidth 0 0 20 20 rectstroke

seems to produce a square with sides of 24 points, rather than the 20 that I wanted.
Is my impression correct? If so, what to do about it? Of course I can declare a my_rectstroke( function, that will take the linewidth as a parameter plus the coordinates and dimensions, but perhaps there is a more elegant/less cumbersome way?


问:
NextJS Image - Remove white space around image
I'm having a problem with Next/image, I can't get my head around how the sizing works.

I'm trying to get the images without whitespace around them, but I want it to be responsive without hardcoded image sizes. I used a purple background color to make it clear what I'm trying to get rid of. For some reason the images always show up as a square.

I set the images to 100% width and height so that it takes the size of the parent Box, but it seems like the size of the Box doesn't make a difference. Can anyone explain to me how this works?

I used objectFit=contain so that it retains the correct aspect ratio. And I used layout=responsive for the variable image size.

```<code>{images.map((image, index) => (
    <Box key={index}>
        <Box sx={{ mb: 1, bgcolor: "purple" }}>
            {image.url.startsWith("http") && (
                <Image
                    src={image.url}
                    width="100%"
                    height="100%"
                    layout="responsive"
                    objectFit="contain"
                    alt="myimage"
                />
            )}
        </Box>
        {textfield and buttons}
    </Box>
))}
</code>```

Body:
I'm having a problem with Next/image, I can't get my head around how the sizing works.

I'm trying to get the images without whitespace around them, but I want it to be responsive without hardcoded image sizes. I used a purple background color to make it clear what I'm trying to get rid of. For some reason the images always show up as a square.

I set the images to 100% width and height so that it takes the size of the parent Box, but it seems like the size of the Box doesn't make a difference. Can anyone explain to me how this works?

I used objectFit=contain so that it retains the correct aspect ratio. And I used layout=responsive for the variable image size.

{images.map((image, index) => (
    <Box key={index}>
        <Box sx={{ mb: 1, bgcolor: "purple" }}>
            {image.url.startsWith("http") && (
                <Image
                    src={image.url}
                    width="100%"
                    height="100%"
                    layout="responsive"
                    objectFit="contain"
                    alt="myimage"
                />
            )}
        </Box>
        {textfield and buttons}
    </Box>
))}


问:
Laravel create a singleton instance of a class
I want to have a single instance of a Cart object in a Laravel app.
The Cart class need a Customer instance to be initialized.

class Cart {
  private Customer $customer;

  __construct(Customer $customer) {
     $this->customer = $customer;
  }
}
```
<p>I call customer's <code>cart()</code> method to get a new <code>Cart</code> instance.</p>
<pre class="lang-php prettyprint-override"><code>// Customer.php
public function cart(): Cart {
  return new Cart($this);
}
</code>```

I thought maybe with a ServiceProvider I will be able to use a singleton instance of the cart whenever I call $customer->cart() method

How can I have CartServiceProvider and every time (in app lifecycle) I call $customer->cart() it return the single instance of the customer's cart?
something like this:

// Customer.php
public function cart(): Cart {
   return CartServiceProvider::cart();
}
```

Is it possible to achieve this with a SerivceProvider?

Body:
I want to have a single instance of a Cart object in a Laravel app.
The Cart class need a Customer instance to be initialized.

class Cart {
  private Customer $customer;

  __construct(Customer $customer) {
     $this->customer = $customer;
  }
}

I call customer's cart() method to get a new Cart instance.

// Customer.php
public function cart(): Cart {
  return new Cart($this);
}

I thought maybe with a ServiceProvider I will be able to use a singleton instance of the cart whenever I call $customer->cart() method

How can I have CartServiceProvider and every time (in app lifecycle) I call $customer->cart() it return the single instance of the customer's cart?
something like this:

// Customer.php
public function cart(): Cart {
   return CartServiceProvider::cart();
}

Is it possible to achieve this with a SerivceProvider?


问:
Laravel view page not generating, its Blank Page
Does anyone, Know Laravel, one of our old project was developed in Laravel 5.5. we made a copy of the website in the new host, but the website is displaying a blank page, I checked the controller file before sending the view page data line. the data is displayed when I print it in the controller but the view is not. I checked the view under the Storage/Framework/views here its not generate anything, I think the view compiler is not running properly. please help me to resolve the problem.PHP : 7.3 , Laravel 5.5
There is no error display,
Debugging error is also not displayed.</p>


问:
Is there any way to collapse information inside extent report?
I have a huge extent report which shows results basis on a loop.

Sample code:

```<code>String[] values = {"1","2".....upto 1000};
for(int i =0; i < values.length; i++) {
log("comparison started for " + i+1);
if(s.contains("abc")) {
 log( i + "Success for " + s)
} else {
 log(i + "Fail for " + s)
}
</code>```

Now in report it shows all Pass/Fail which makes the report very heavy/ bulkier.

I want to create an expand/collapse icon next to :

log("comparison started for " + i+1);

So that, for each loop, the information remain hidden, until expanded in report.

Body:
I have a huge extent report which shows results basis on a loop.

Sample code:

String[] values = {"1","2".....upto 1000};
for(int i =0; i < values.length; i++) {
log("comparison started for " + i+1);
if(s.contains("abc")) {
 log( i + "Success for " + s)
} else {
 log(i + "Fail for " + s)
}

Now in report it shows all Pass/Fail which makes the report very heavy/ bulkier.

I want to create an expand/collapse icon next to :

log("comparison started for " + i+1);

So that, for each loop, the information remain hidden, until expanded in report.


问:
Low validation accuracy but the train have high accuracy, also the validation loss so high
i have a question, when im creating the model, why it have high accuracy and low loss, but the validation accuracy low and validation loss so high.
Any recommend way to improve this?
It took 256 samples, validate on 65 samples.
This is the code that i used to

```<code>import numpy as np
import cv2
import os
import tensorflow as tf
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
# from tensorflow.keras.models import Sequential
from keras.models import Sequential
# from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.layers import Conv2D,MaxPooling2D,Dense, Dropout, Activation, Flatten
# from tensorflow.keras.optimizers import Adam,RMSprop,SGD
from keras.optimizers import Adam , RMSprop, SGD
import pickle
from streamlit_webrtc import webrtc_streamer

################################################################
path = 'DatasetsBatik'
testRatio = 0.2
validationRatio = 0.2
imageDimension =(32,32,3)
batchSizeVal=2
epochsVal=200
stepsPerEpochVal=200

################################################################
images=[]
classNumber =[]

myList = os.listdir(path)
print("Total Number of Classes Detected" , " : " ,  len(myList))
NumberOfClasses =len(myList)

print("Importing Classes ....")
for x in range(0,NumberOfClasses):
#0 Representing Kawung,
#1 Representing Megamendung,
#2 Representing Parang,
#3 Representing Sekar Jagad,
#4 Representing Simbut,

    myPicList = os.listdir(path+"/"+str(x))

    for y in myPicList:
        currentImage = cv2.imread(path+"/"+str(x)+"/"+y)
        currentImage = cv2.resize(currentImage, (imageDimension[0],imageDimension[1]) )
        images.append(currentImage)
        classNumber.append(x)
    print(x,end = " " )
print("")
print(len(classNumber))

images = np.array(images)
classNumber = np.array(classNumber)

# print(images.shape)
# print(classNumber.shape)

### Split Data
X_train,X_test,Y_train,Y_test = train_test_split(images,classNumber,test_size = testRatio)
X_train,X_validation,Y_train,Y_validation= train_test_split(X_train,Y_train,test_size = validationRatio)

print("x_train.shape = " + str(X_train.shape))
print("x_test.shape = " +str(X_test.shape))
print("x_validation.shape = "+str(X_validation.shape))

NumberOfSamples=[]
for x in range(0,NumberOfClasses):
    # print(len(np.where(Y_train ==x)[0]))
    NumberOfSamples.append(len(np.where(Y_train==x)[0]))
print("Number Of Samples : " +str(NumberOfSamples))

plt.figure(figsize=(10,5))
plt.bar(range(0,NumberOfClasses),NumberOfSamples)
plt.title("Number of Images for each Class")
plt.xlabel("Class ID")
plt.ylabel("Number of Images")
plt.show()

# print(X_train)

def PreProcessing(img):
    img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img = cv2.equalizeHist(img)
    img = img/255
    return img

# img = X_train[30]
# img = cv2.resize(img,(300,300))
# cv2.imshow("PreProcessed",img)
# cv2.waitKey(0)

X_train=np.array(list(map(PreProcessing,X_train)))
# print(X_train)
X_test=np.array(list(map(PreProcessing,X_test)))
X_validation=np.array(list(map(PreProcessing,X_validation)))

# print(X_train.shape)

X_train = X_train.reshape(X_train.shape[0],X_train.shape[1],X_train.shape[2],1)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1],X_test.shape[2],1)
X_validation = X_validation.reshape(X_validation.shape[0],X_validation.shape[1],X_validation.shape[2],1)

# print(X_train.shape)

dataGen = ImageDataGenerator(width_shift_range=0.1,height_shift_range=0.1,zoom_range=0.2,shear_range=0.1,rotation_range=10)
dataGen.fit(X_train)

Y_train = to_categorical(Y_train,NumberOfClasses)
Y_test = to_categorical(Y_test,NumberOfClasses)
Y_validation = to_categorical(Y_validation,NumberOfClasses)

def myModel():
    NumberOfFilters1 = 128
    NumberOfFilters2 = 256
    sizeOfFilter1=(5,5)
    sizeOfFilter2=(3,3)
    sizeOfPool=(2,2)

    NumberOfNode=128

    model = Sequential()
    model.add((Conv2D(NumberOfFilters1,sizeOfFilter1,input_shape=(imageDimension[0],imageDimension[1],1),activation='relu')))
    model.add(Dropout(0.5))
    model.add(MaxPooling2D(pool_size=sizeOfPool))

    # model.add((Conv2D(NumberOfFilters1,sizeOfFilter1,activation='relu')))
    # model.add(MaxPooling2D(pool_size=sizeOfPool))
    # model.add(Dropout(0.5))

    model.add((Conv2D(NumberOfFilters2,sizeOfFilter2,activation='relu')))
    model.add(MaxPooling2D(pool_size=sizeOfPool))
    model.add(Dropout(0.5))

    # model.add((Conv2D(NumberOfFilters2,sizeOfFilter2,activation='relu')))
    # model.add(MaxPooling2D(pool_size=sizeOfPool))
    # model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(NumberOfNode,activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(NumberOfClasses,activation='softmax'))
    model.compile(Adam(lr=0.0005),loss='categorical_crossentropy',metrics=['accuracy'])
    return model

model = myModel()
print(model.summary())

history = model.fit_generator(dataGen.flow(X_train,Y_train,batch_size=batchSizeVal),steps_per_epoch=stepsPerEpochVal,epochs=epochsVal,validation_data=(X_validation,Y_validation),shuffle=1)
# history= model.fit(X_train, Y_train, batch_size=batchSizeVal,epochs=epochsVal,verbose=1,validation_data=(X_validation, Y_validation))

plt.figure(1)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['training','validation'])
plt.title('Loss')
plt.xlabel('epoch')

plt.figure(2)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.legend(['training','validation'])
plt.title('Accuracy')
plt.xlabel('epoch')
plt.show()

score= model.evaluate(X_test,Y_test,verbose=0)
print('Test Score =',score[0])
print('Score Accuracy  = ',score[1])

print(score)
# print(model.metrics_names)

pickle_out=open("10_TestModel4","wb")
pickle.dump(model,pickle_out)
pickle_out.close()

</code>```

This is the result that i have now
Epoch 1

Finish,Epoch 200

I have tried to remove or add hidden layer, and also try some different learning rate, epoch, batch size, steps per epoch, adding drop out for the layer . Any recommend would be very helpfull, thankyou.

Body:
i have a question, when im creating the model, why it have high accuracy and low loss, but the validation accuracy low and validation loss so high.
Any recommend way to improve this?
It took 256 samples, validate on 65 samples.
This is the code that i used to

import numpy as np
import cv2
import os
import tensorflow as tf
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
# from tensorflow.keras.models import Sequential
from keras.models import Sequential
# from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.layers import Conv2D,MaxPooling2D,Dense, Dropout, Activation, Flatten
# from tensorflow.keras.optimizers import Adam,RMSprop,SGD
from keras.optimizers import Adam , RMSprop, SGD
import pickle
from streamlit_webrtc import webrtc_streamer

################################################################
path = 'DatasetsBatik'
testRatio = 0.2
validationRatio = 0.2
imageDimension =(32,32,3)
batchSizeVal=2
epochsVal=200
stepsPerEpochVal=200

################################################################
images=[]
classNumber =[]

myList = os.listdir(path)
print("Total Number of Classes Detected" , " : " ,  len(myList))
NumberOfClasses =len(myList)

print("Importing Classes ....")
for x in range(0,NumberOfClasses):
#0 Representing Kawung,
#1 Representing Megamendung,
#2 Representing Parang,
#3 Representing Sekar Jagad,
#4 Representing Simbut,

    myPicList = os.listdir(path+"/"+str(x))

    for y in myPicList:
        currentImage = cv2.imread(path+"/"+str(x)+"/"+y)
        currentImage = cv2.resize(currentImage, (imageDimension[0],imageDimension[1]) )
        images.append(currentImage)
        classNumber.append(x)
    print(x,end = " " )
print("")
print(len(classNumber))

images = np.array(images)
classNumber = np.array(classNumber)

# print(images.shape)
# print(classNumber.shape)

### Split Data
X_train,X_test,Y_train,Y_test = train_test_split(images,classNumber,test_size = testRatio)
X_train,X_validation,Y_train,Y_validation= train_test_split(X_train,Y_train,test_size = validationRatio)

print("x_train.shape = " + str(X_train.shape))
print("x_test.shape = " +str(X_test.shape))
print("x_validation.shape = "+str(X_validation.shape))

NumberOfSamples=[]
for x in range(0,NumberOfClasses):
    # print(len(np.where(Y_train ==x)[0]))
    NumberOfSamples.append(len(np.where(Y_train==x)[0]))
print("Number Of Samples : " +str(NumberOfSamples))

plt.figure(figsize=(10,5))
plt.bar(range(0,NumberOfClasses),NumberOfSamples)
plt.title("Number of Images for each Class")
plt.xlabel("Class ID")
plt.ylabel("Number of Images")
plt.show()

# print(X_train)

def PreProcessing(img):
    img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img = cv2.equalizeHist(img)
    img = img/255
    return img

# img = X_train[30]
# img = cv2.resize(img,(300,300))
# cv2.imshow("PreProcessed",img)
# cv2.waitKey(0)

X_train=np.array(list(map(PreProcessing,X_train)))
# print(X_train)
X_test=np.array(list(map(PreProcessing,X_test)))
X_validation=np.array(list(map(PreProcessing,X_validation)))

# print(X_train.shape)

X_train = X_train.reshape(X_train.shape[0],X_train.shape[1],X_train.shape[2],1)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1],X_test.shape[2],1)
X_validation = X_validation.reshape(X_validation.shape[0],X_validation.shape[1],X_validation.shape[2],1)

# print(X_train.shape)

dataGen = ImageDataGenerator(width_shift_range=0.1,height_shift_range=0.1,zoom_range=0.2,shear_range=0.1,rotation_range=10)
dataGen.fit(X_train)

Y_train = to_categorical(Y_train,NumberOfClasses)
Y_test = to_categorical(Y_test,NumberOfClasses)
Y_validation = to_categorical(Y_validation,NumberOfClasses)

def myModel():
    NumberOfFilters1 = 128
    NumberOfFilters2 = 256
    sizeOfFilter1=(5,5)
    sizeOfFilter2=(3,3)
    sizeOfPool=(2,2)

    NumberOfNode=128

    model = Sequential()
    model.add((Conv2D(NumberOfFilters1,sizeOfFilter1,input_shape=(imageDimension[0],imageDimension[1],1),activation='relu')))
    model.add(Dropout(0.5))
    model.add(MaxPooling2D(pool_size=sizeOfPool))

    # model.add((Conv2D(NumberOfFilters1,sizeOfFilter1,activation='relu')))
    # model.add(MaxPooling2D(pool_size=sizeOfPool))
    # model.add(Dropout(0.5))

    model.add((Conv2D(NumberOfFilters2,sizeOfFilter2,activation='relu')))
    model.add(MaxPooling2D(pool_size=sizeOfPool))
    model.add(Dropout(0.5))

    # model.add((Conv2D(NumberOfFilters2,sizeOfFilter2,activation='relu')))
    # model.add(MaxPooling2D(pool_size=sizeOfPool))
    # model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(NumberOfNode,activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(NumberOfClasses,activation='softmax'))
    model.compile(Adam(lr=0.0005),loss='categorical_crossentropy',metrics=['accuracy'])
    return model

model = myModel()
print(model.summary())

history = model.fit_generator(dataGen.flow(X_train,Y_train,batch_size=batchSizeVal),steps_per_epoch=stepsPerEpochVal,epochs=epochsVal,validation_data=(X_validation,Y_validation),shuffle=1)
# history= model.fit(X_train, Y_train, batch_size=batchSizeVal,epochs=epochsVal,verbose=1,validation_data=(X_validation, Y_validation))

plt.figure(1)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['training','validation'])
plt.title('Loss')
plt.xlabel('epoch')

plt.figure(2)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.legend(['training','validation'])
plt.title('Accuracy')
plt.xlabel('epoch')
plt.show()

score= model.evaluate(X_test,Y_test,verbose=0)
print('Test Score =',score[0])
print('Score Accuracy  = ',score[1])

print(score)
# print(model.metrics_names)

pickle_out=open("10_TestModel4","wb")
pickle.dump(model,pickle_out)
pickle_out.close()

This is the result that i have now
Epoch 1

Finish,Epoch 200

I have tried to remove or add hidden layer, and also try some different learning rate, epoch, batch size, steps per epoch, adding drop out for the layer . Any recommend would be very helpfull, thankyou.


问:
Python: parallelize for loop and save results in dictionary passed by reference
I would like to parallelize following function, where A and B are just some columns from my input data frame. I would like to provide the output dictionary as an input so it is filled within the function (pass by reference)

```<code>outdict = {}

inputdict1 = {'id1': 100, 'id2': 200, 'id3': 0}
inputdict2 = {'id1': ['cat'], 'id2': ['dog', 'rabbit'], 'id3': []}
inputdf = pd.DataFrame({'A': ['cat', 'cat', 'dog', 'dog', 'dog', 'cat', 'rabbit', 'rabbit'],
                        'B': ['a', 'b', 'b', 'c', 'c', 'd', 'e', 'f']})

def processing(outdict, inputdict1, inputdict2, inputdf):
    for key, _ in tqdm(inputdict1.items()):
        outdict[key] = inputdf[inputdf.A.isin(inputdict2[key])].B.nunique()

processing(outdict, inputdict1, inputdict2, inputdf)

print(outdict)
</code>```

{'id1': 3, 'id2': 4, 'id3': 0}

After some research I have tried the following approach

```<code>from multiprocessing import Pool

def processing(outdict, inputdict1, inputdict2, inputdf):
    for key, value in tqdm(inputdict1.items()):
        outdict[key] = inputdf[inputdf.A.isin(inputdict2[key])].B.nunique()

outdict = {}

pool = Pool()
pool.starmap(processing, zip(outdict, inputdict1, inputdict2, inputdf))

print(outdict)
</code>```

{}

Body:
I would like to parallelize following function, where A and B are just some columns from my input data frame. I would like to provide the output dictionary as an input so it is filled within the function (pass by reference)

outdict = {}

inputdict1 = {'id1': 100, 'id2': 200, 'id3': 0}
inputdict2 = {'id1': ['cat'], 'id2': ['dog', 'rabbit'], 'id3': []}
inputdf = pd.DataFrame({'A': ['cat', 'cat', 'dog', 'dog', 'dog', 'cat', 'rabbit', 'rabbit'],
                        'B': ['a', 'b', 'b', 'c', 'c', 'd', 'e', 'f']})

def processing(outdict, inputdict1, inputdict2, inputdf):
    for key, _ in tqdm(inputdict1.items()):
        outdict[key] = inputdf[inputdf.A.isin(inputdict2[key])].B.nunique()

processing(outdict, inputdict1, inputdict2, inputdf)

print(outdict)

{'id1': 3, 'id2': 4, 'id3': 0}

After some research I have tried the following approach

from multiprocessing import Pool

def processing(outdict, inputdict1, inputdict2, inputdf):
    for key, value in tqdm(inputdict1.items()):
        outdict[key] = inputdf[inputdf.A.isin(inputdict2[key])].B.nunique()

outdict = {}

pool = Pool()
pool.starmap(processing, zip(outdict, inputdict1, inputdict2, inputdf))

print(outdict)

{}


问:
Python pattern matching function for nested list
I'm trying to create a pattern matching function which looks through a nested list which contains books, and each book consists of:

author

title

So I want to search through this:

```<code>books = [['author', ['elon', 'musk']],
        ['title', ['book', 'one']],

        ['author', ['elon', 'tusk']],
        ['titel', ['book', 'two']]]
</code>```

And my pattern matching function has some defining variables:

'&' means it matches with exactly one element

'--' means it can match with multiple elements

Here are some test cases:

```<code>search1 = [['author', ['elon', '&']],
           ['title', ['book', '&']]
# Explanation:
# Author: elon SOMETHING     -->     match with both books
# Title: book SOMETHING      -->     match with both books, return both

search2 = ['--',
          ['title', ['book', 'one']]]
# Explanation:
# Author: -- means ALL authors
# Title: book one     --> should match with book one

#-- Run cases
match(search1, books)
match(search2, books)
</code>```

Here is my current code which I'm having trouble connecting to the book searching algorithm:

```<code>def match(seq, pattern):
if not pattern:
    return not seq
elif pattern[0] == '--':
    if match(seq, pattern[1:]):
        return True
    elif not seq:
        return False
    else:
        return match(seq[1:], pattern)
elif not seq:
    return False
elif pattern[0] == '&':
    return match(seq[1:], pattern[1:])
elif seq[0] == pattern[0]:
    return match(seq[1:], pattern[1:])
elif type(seq[0]) == list and type(seq[0]) == list:
    if not match(seq, pattern):
        return False
else:
    return False
</code>```

My question is, how can I implement something that can return the correct book or multiple books if that is the case? This function works for generic pattern matching but I'm having trouble making it work for this list of books and searching for author or a title. What can I add to make it work?

Body:
I'm trying to create a pattern matching function which looks through a nested list which contains books, and each book consists of:

author

title

So I want to search through this:

books = [['author', ['elon', 'musk']],
        ['title', ['book', 'one']],

        ['author', ['elon', 'tusk']],
        ['titel', ['book', 'two']]]

And my pattern matching function has some defining variables:

'&' means it matches with exactly one element

'--' means it can match with multiple elements

Here are some test cases:

search1 = [['author', ['elon', '&']],
           ['title', ['book', '&']]
# Explanation:
# Author: elon SOMETHING     -->     match with both books
# Title: book SOMETHING      -->     match with both books, return both

search2 = ['--',
          ['title', ['book', 'one']]]
# Explanation:
# Author: -- means ALL authors
# Title: book one     --> should match with book one

#-- Run cases
match(search1, books)
match(search2, books)

Here is my current code which I'm having trouble connecting to the book searching algorithm:

def match(seq, pattern):
if not pattern:
    return not seq
elif pattern[0] == '--':
    if match(seq, pattern[1:]):
        return True
    elif not seq:
        return False
    else:
        return match(seq[1:], pattern)
elif not seq:
    return False
elif pattern[0] == '&':
    return match(seq[1:], pattern[1:])
elif seq[0] == pattern[0]:
    return match(seq[1:], pattern[1:])
elif type(seq[0]) == list and type(seq[0]) == list:
    if not match(seq, pattern):
        return False
else:
    return False

My question is, how can I implement something that can return the correct book or multiple books if that is the case? This function works for generic pattern matching but I'm having trouble making it work for this list of books and searching for author or a title. What can I add to make it work?


问:
ATT popup is not showing iOS 16
ATT popup isn't showing in iOS 16

I tried many ways but I failed.
(This project doesn't have AppDelegate and SceneDelegate so I couldn't try the way)

in init()

I also changed delay for 10 sec but it wasn't work.

@main
struct lockAppApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }

    init() {
        GADMobileAds.sharedInstance().start(completionHandler: nil)

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            if #available(iOS 14, *) {
                ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                })
            }
        }
    }
}

```
<ol start="2">
<li>in <code>View</code>
It just printed "Not Determined"</li>
</ol>
<pre class="lang-swift prettyprint-override"><code>struct ContentView: View {
    var body: some View {
        ZStack(alignment: .top) {
            GifImage("help")
                .frame(width: UIScreen.main.bounds.width - (UIScreen.main.bounds.width * 0.3))
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                switch status {
                case .authorized:
                    print("Authorized")
                case .denied:
                    print("Denied")
                case .notDetermined:
                    ATTrackingManager.requestTrackingAuthorization(completionHandler: {_ in})
                    print("Not Determined")
                case .restricted:
                    print("Restricted")
                @unknown default:
                    print("Unknown")
                }

            })
        }
    }
}
</code>```

Title: ATT popup is not showing iOS 16

Body:
ATT popup isn't showing in iOS 16

I tried many ways but I failed.
(This project doesn't have AppDelegate and SceneDelegate so I couldn't try the way)

in init()

I also changed delay for 10 sec but it wasn't work.

@main
struct lockAppApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }

    init() {
        GADMobileAds.sharedInstance().start(completionHandler: nil)

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            if #available(iOS 14, *) {
                ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                })
            }
        }
    }
}

in View
It just printed "Not Determined"

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .top) {
            GifImage("help")
                .frame(width: UIScreen.main.bounds.width - (UIScreen.main.bounds.width * 0.3))
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                switch status {
                case .authorized:
                    print("Authorized")
                case .denied:
                    print("Denied")
                case .notDetermined:
                    ATTrackingManager.requestTrackingAuthorization(completionHandler: {_ in})
                    print("Not Determined")
                case .restricted:
                    print("Restricted")
                @unknown default:
                    print("Unknown")
                }

            })
        }
    }
}


问:
Add entities in Maltego through an api
Im working with Maltego and I would like to add entities to a graph from a server through an api.

Is that possible?

I would say that it is not possible but in a project are asking me to do that and I don't know how to do it. I've been looking for information for a few days and I can't find anything.

Thanks in advance.

I have not tested anything because reading the documentation I do not see it possible.

Title: Add entities in Maltego through an api


问:
trait is_same for arbitrary many types
The type_traits library offers the possibility to check if two type are the same with is_same.

How can one generalize to an arbitrary long list of types? Something declared as

```<code>template <class... U>
struct is_same_many;
</code>```

with a field value such that value = true if all Us are the same, and false otherwise.

Title: trait is_same for arbitrary many types

Body:
The type_traits library offers the possibility to check if two type are the same with is_same.

How can one generalize to an arbitrary long list of types? Something declared as

template <class... U>
struct is_same_many;

with a field value such that value = true if all Us are the same, and false otherwise.


问:
Debugging BLE in React Native without constantly building the application
I'm developing a React Native application that uses BLE. Expo doesn't support bluetooth debugging, neither on an emulator nor on a real device.

To check if the application works, I need to build it first with eas build, which takes about 6 minutes.

Result of time command:

```<code>eas build -p android --profile preview  3,61s user 0,66s system 1% cpu 6:12,42 total
</code>```

Is there a better way to debug a React Native application with bluetooth, without constantly building it and uploading it to the device?

Body:
I'm developing a React Native application that uses BLE. Expo doesn't support bluetooth debugging, neither on an emulator nor on a real device.

To check if the application works, I need to build it first with eas build, which takes about 6 minutes.

Result of time command:

eas build -p android --profile preview  3,61s user 0,66s system 1% cpu 6:12,42 total

Is there a better way to debug a React Native application with bluetooth, without constantly building it and uploading it to the device?


问:
how do i show a money formatted variable if exists otherwise show blank
I am using the blade directive to format money

```<code>    \Blade::directive('money', function ($money) {
        return "<?php echo '$' . number_format($money, 2); ?>";
    });
</code>```

I have a form value that I want prepopulated if variable exists.

```<code> <input type='text' value="@money($money)">
</code>```

The variable may not always exist so if it were a standard variable I would do:

```<code><input type='text' value="{{$money ?? 'notset'">
</code>```

In laymans terms I am trying to write:

```<code><input type='text' value="{{@(money) ?? 'notset'}}">
</code>```

How would i do that correctly?

Body:
I am using the blade directive to format money

    \Blade::directive('money', function ($money) {
        return "<?php echo '$' . number_format($money, 2); ?>";
    });

I have a form value that I want prepopulated if variable exists.

 <input type='text' value="@money($money)">

The variable may not always exist so if it were a standard variable I would do:

<input type='text' value="{{$money ?? 'notset'">

In laymans terms I am trying to write:

<input type='text' value="{{@(money) ?? 'notset'}}">

How would i do that correctly?


问:
Adding Text Makes The Whole Application Blurry
hello i was working on a project with pyglet. The problem i encountered is that when i add a Label class to my app, all the other sprites become blurry.

Here is a screenshot of what i mean:

as you can see the text is corrupted and is weird

Text Code

```<code>self.label.text = "Index: " + str(self.h_floor + (self.v_floor * self.map.h_cells))
</code>```

so it looks like the other half is the one that gets corrupted and when i print it, it's just some integers

here's the code:

Main Application Code

```<code>def draw(self):
    pyglet.gl.glTexParameteri(pyglet.gl.GL_TEXTURE_2D, pyglet.gl.GL_TEXTURE_MAG_FILTER,pyglet.gl.GL_NEAREST)

    self.window.clear()
    self.batch.draw()
    self.window.flip()
</code>```

I have two classes in Application:

Label Class

Sprite Class

Even if i explicitly say in draw function to use GL_NEAREST
it appears that label overrides that.
When i remove Label Class everything goes back to normal

the Label seems to get some corrupted characters as well, but that diseappears when i remove the Sprite Class as well.

how do i prevent Label Class from changing the texture filtering ?

I Tried to remove the blurring from the sprites but the Label Class always overrides anything i write.

Body:
hello i was working on a project with pyglet. The problem i encountered is that when i add a Label class to my app, all the other sprites become blurry.

Here is a screenshot of what i mean:

as you can see the text is corrupted and is weird

Text Code

self.label.text = "Index: " + str(self.h_floor + (self.v_floor * self.map.h_cells))

so it looks like the other half is the one that gets corrupted and when i print it, it's just some integers

here's the code:

Main Application Code

def draw(self):
    pyglet.gl.glTexParameteri(pyglet.gl.GL_TEXTURE_2D, pyglet.gl.GL_TEXTURE_MAG_FILTER,pyglet.gl.GL_NEAREST)

    self.window.clear()
    self.batch.draw()
    self.window.flip()

I have two classes in Application:

Label Class

Sprite Class

Even if i explicitly say in draw function to use GL_NEAREST
it appears that label overrides that.
When i remove Label Class everything goes back to normal

the Label seems to get some corrupted characters as well, but that diseappears when i remove the Sprite Class as well.

how do i prevent Label Class from changing the texture filtering ?

I Tried to remove the blurring from the sprites but the Label Class always overrides anything i write.


问:
How to configure maven fail-never in pom file?
I want to configure the tests to not stop execution even in case of error and try to re-run the test in case of any issue.

I use maven 3.6 to run the tests by typing

```<code>mvn clean verify -fn -Dfailsafe.rerunFailingTestsCount=2
</code>```

Where fn is a shortcut for --fail-never

How can i do the same by creating a profile in the pom.xml file?

According to https://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html
I've tried to use

```<code><configuration>
<argLine>
-Dfailsafe.rerunFailingTestsCount=2
</argLine>
</configuration>
</code>```

in profile part.
However, I have an issue with -fn part - when I try to add it to argLine, it complains that it is not recognized.

Body:
I want to configure the tests to not stop execution even in case of error and try to re-run the test in case of any issue.

I use maven 3.6 to run the tests by typing

mvn clean verify -fn -Dfailsafe.rerunFailingTestsCount=2

Where fn is a shortcut for --fail-never

How can i do the same by creating a profile in the pom.xml file?

According to https://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html
I've tried to use

<configuration>
<argLine>
-Dfailsafe.rerunFailingTestsCount=2
</argLine>
</configuration>

in profile part.
However, I have an issue with -fn part - when I try to add it to argLine, it complains that it is not recognized.


问:
How to convert ASP MSAccess SQL CDbl and LEFT in a select statement to MySQL
I have this SQL statement in an ASP page querying the database and I need to convert it to MySQL.

```<code>SELECT DISTINCT trelMapSU.Site, trelMapSU.MapNum, tlkpSUTyp.SUTyp,
        tblSU.SUNum, tlkpSUDesc.SUDesc,
        CDbl(IIf(IsNumeric( [tblSU]![SUNum]),[tblSU]![SUNum],
          Left([tblSU]![SUNum],
             InStr(1,[tblSU]![SUNum],'-')-1)
            )
        )
FROM tlkpSUTyp
</code>```

I am new to this and found that CDbl means to convert a value to a double which still make very little sense to me even with the examples I have found.  It also seems that the Left command returns a specified number of characters from the left side of a string.  A Little more clear but I am still not sure what this is trying to accomplish.  Can someone explain how to convert this to MySQL?

UPDATE

Could someone translate what this means:

```<code>CDbl(IIf(IsNumeric( [tblSU]![SUNum]),[tblSU]![SUNum],
 Left([tblSU]![SUNum],
  InStr(1,[tblSU]![SUNum],'-')-1)
 )
)
</code>```

I think if I knew that I could get somewhere.

Body:
I have this SQL statement in an ASP page querying the database and I need to convert it to MySQL.

SELECT DISTINCT trelMapSU.Site, trelMapSU.MapNum, tlkpSUTyp.SUTyp,
        tblSU.SUNum, tlkpSUDesc.SUDesc,
        CDbl(IIf(IsNumeric( [tblSU]![SUNum]),[tblSU]![SUNum],
          Left([tblSU]![SUNum],
             InStr(1,[tblSU]![SUNum],'-')-1)
            )
        )
FROM tlkpSUTyp

I am new to this and found that CDbl means to convert a value to a double which still make very little sense to me even with the examples I have found.  It also seems that the Left command returns a specified number of characters from the left side of a string.  A Little more clear but I am still not sure what this is trying to accomplish.  Can someone explain how to convert this to MySQL?

UPDATE

Could someone translate what this means:

CDbl(IIf(IsNumeric( [tblSU]![SUNum]),[tblSU]![SUNum],
 Left([tblSU]![SUNum],
  InStr(1,[tblSU]![SUNum],'-')-1)
 )
)

I think if I knew that I could get somewhere.


问:
Make vertical scrollbar always visible in the Xcode source editor
I want to make the vertical scrollbar (and the red lines representing errors) always visible, not just when scrolling.

I know that there is a system-wide setting in macOS to make all scrollbars always visible, but I'd rather keep the current system setting on (automatically detected).


问:
pywin.dialogs.list.ListDialog: Unexpected focus when called after global hot key pressed
Sorry for the weird title.  I don't know how else to phrase it.  Please feel free to re-write/improve the title with edits.

Using Python 3 on Win 10, this code works well to pop-up a small MFC dialog with a selection box:

```<code>import pywin.dialogs.list

if __name__ == "__main__":
    pywin.dialogs.list.ListDialog("Window Title", ["abc", "def"]).DoModal()
</code>```

When I run this code, the dialog takes focus and is the activated window.

Next, I would like to trigger this dialog from a global hot key: Ctrl+Alt+Shift+P

```<code>import ctypes.wintypes
from ctypes import windll

import pywin.dialogs.list
import win32con

if __name__ == "__main__":
    hot_key_index = 0
    if not ctypes.windll.user32.RegisterHotKey(None, hot_key_index, win32con.MOD_ALT + win32con.MOD_CONTROL + win32con.MOD_SHIFT, ord('P')):
        raise Exception("Failed: user32.RegisterHotKey()")
    try:
        msg = ctypes.wintypes.MSG()
        while windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
            if msg.message == win32con.WM_HOTKEY:
                if hot_key_index == msg.wParam:
                    pywin.dialogs.list.ListDialog("Window Title", ["abc", "def"]).DoModal()

            windll.user32.TranslateMessage(ctypes.byref(msg))
            windll.user32.DispatchMessageA(ctypes.byref(msg))
    finally:
        windll.user32.UnregisterHotKey(None, hot_key_index)
</code>```

Run the code, then strike: Ctrl+Alt+Shift+P.  The global hot key dialog will pop-up... or rather pop-under.  I always need to do Alt+Tab to find the dialog.  It does not take focus and is not the activated window.

I tried to find different ways set focus.  However, I cannot find a working solution.  Example that does not work:

```<code>hWnd = dlg._obj_.GetSafeHwnd()
win32gui.SetFocus(hWnd)
</code>```

By luck, I discovered if I display a dummy message box before starting the message loop, the global hot key pop-up dialog takes focus correctly.

This works, but why?  (It feels like a strange MFC init issue, but this is beyond my area of expertise.)

```<code>if __name__ == "__main__":
    win32api.MessageBox(None, "message", "title", win32con.MB_OK)
    hot_key_index = 0
    ...
</code>```

Body:
Sorry for the weird title.  I don't know how else to phrase it.  Please feel free to re-write/improve the title with edits.

Using Python 3 on Win 10, this code works well to pop-up a small MFC dialog with a selection box:

import pywin.dialogs.list

if __name__ == "__main__":
    pywin.dialogs.list.ListDialog("Window Title", ["abc", "def"]).DoModal()

When I run this code, the dialog takes focus and is the activated window.

Next, I would like to trigger this dialog from a global hot key: Ctrl+Alt+Shift+P

import ctypes.wintypes
from ctypes import windll

import pywin.dialogs.list
import win32con

if __name__ == "__main__":
    hot_key_index = 0
    if not ctypes.windll.user32.RegisterHotKey(None, hot_key_index, win32con.MOD_ALT + win32con.MOD_CONTROL + win32con.MOD_SHIFT, ord('P')):
        raise Exception("Failed: user32.RegisterHotKey()")
    try:
        msg = ctypes.wintypes.MSG()
        while windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
            if msg.message == win32con.WM_HOTKEY:
                if hot_key_index == msg.wParam:
                    pywin.dialogs.list.ListDialog("Window Title", ["abc", "def"]).DoModal()

            windll.user32.TranslateMessage(ctypes.byref(msg))
            windll.user32.DispatchMessageA(ctypes.byref(msg))
    finally:
        windll.user32.UnregisterHotKey(None, hot_key_index)

Run the code, then strike: Ctrl+Alt+Shift+P.  The global hot key dialog will pop-up... or rather pop-under.  I always need to do Alt+Tab to find the dialog.  It does not take focus and is not the activated window.

I tried to find different ways set focus.  However, I cannot find a working solution.  Example that does not work:

hWnd = dlg._obj_.GetSafeHwnd()
win32gui.SetFocus(hWnd)

By luck, I discovered if I display a dummy message box before starting the message loop, the global hot key pop-up dialog takes focus correctly.

This works, but why?  (It feels like a strange MFC init issue, but this is beyond my area of expertise.)

if __name__ == "__main__":
    win32api.MessageBox(None, "message", "title", win32con.MB_OK)
    hot_key_index = 0
    ...


问:
Do I need to check both ref and *ref in C#?
I have a data structure with references to something like pLimit.TopPoint, where TopPoint has information including x and y location, so its structured.

Certainly before access, it makes sense to verify that pLimit is not null.

Running a linter suggests I should also check *pLimit before accessing pLimit.TopPoint.  Why is that?  Is the linter wrong?


问:
letsencrypt/certbot doesnt find certificate
I have expired certificates I want to renew but when i type

```<code>certbot certificates
</code>```

I get

```<code>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
No certificates found.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
</code>```

I have checked my /etc/letsencrypt/live/ and I do have <mydomain.org> folder.

Certbot is running in a docker container that was stopped and relaunched.

How can I tell my certbot where to find the certificates so it can renew it properly with certbot renew?

I have checked the documentation @ https://eff-certbot.readthedocs.io/en/stable/using.html#re-creating-and-updating-existing-certificates but didnt find anything useful

Thank you

Body:
I have expired certificates I want to renew but when i type

certbot certificates

I get

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
No certificates found.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

I have checked my /etc/letsencrypt/live/ and I do have <mydomain.org> folder.

Certbot is running in a docker container that was stopped and relaunched.

How can I tell my certbot where to find the certificates so it can renew it properly with certbot renew?

I have checked the documentation @ https://eff-certbot.readthedocs.io/en/stable/using.html#re-creating-and-updating-existing-certificates but didnt find anything useful

Thank you


问:
Django Model form is showing invalid with initialized values and file
I have a model like this:

```<code>class Cohortpdfs(models.Model):
    id = models.AutoField(primary_key=True,editable=True)
    title= models.CharField(max_length=200,validators=[MaxLengthValidator(100)])
    content=models.FileField()
    cohort_id=models.ForeignKey(Cohort,on_delete=models.CASCADE,default=0,db_constraint=False)
</code>```

I want to initialize and save data from views.

views.py:

```<code>    if requests.method == 'POST':
        initialvalue={
            'cohort_id':id,
            'title':requests.POST.get('title'),
            'content':requests.FILES['content'],
        }

        if contentform.is_valid():
            print("form valid")
        else:
            print("FORM ERROR")
</code>```

Forms.py

```<code>class CohortpdfsForm(forms.ModelForm):

    class Meta:
        model = Cohortpdfs

        fields = [
            "title","content","cohort_id",
        ]

        widgets={
            'title' : forms.TextInput(attrs={'class': 'form-control','max_length':20}),
            'content': forms.FileInput(attrs={'class': 'form-control'}),
            'cohort_id': forms.TextInput(attrs={'type': 'hidden'}),
        }
</code>```

This is showing my form is not valid. How can I initialize the form with the uploaded file(PDF) and save it into the model database?

Body:
I have a model like this:

class Cohortpdfs(models.Model):
    id = models.AutoField(primary_key=True,editable=True)
    title= models.CharField(max_length=200,validators=[MaxLengthValidator(100)])
    content=models.FileField()
    cohort_id=models.ForeignKey(Cohort,on_delete=models.CASCADE,default=0,db_constraint=False)

I want to initialize and save data from views.

views.py:

    if requests.method == 'POST':
        initialvalue={
            'cohort_id':id,
            'title':requests.POST.get('title'),
            'content':requests.FILES['content'],
        }

        if contentform.is_valid():
            print("form valid")
        else:
            print("FORM ERROR")

Forms.py

class CohortpdfsForm(forms.ModelForm):

    class Meta:
        model = Cohortpdfs

        fields = [
            "title","content","cohort_id",
        ]

        widgets={
            'title' : forms.TextInput(attrs={'class': 'form-control','max_length':20}),
            'content': forms.FileInput(attrs={'class': 'form-control'}),
            'cohort_id': forms.TextInput(attrs={'type': 'hidden'}),
        }

This is showing my form is not valid. How can I initialize the form with the uploaded file(PDF) and save it into the model database?


问:
Woocommerce Analytics: Total Sale or Gross Sale per category
I am trying to get the total sale per category. Not Net sale, but total sale or Gross sale. Meaning product price times number of sales including tax and shipping. I can get total sale for the whole store and net sale per category. But not total sale or gross sale per category.

If this is not possible in analytics then a simple code might be a solution, just to print it out because I only need this info one time.

Thanks for any help, Fredrik.


问:
Error npm run prod on sass file (SassError: Undefined variable: "$gradient-colors".)
i edit a ready make laravel VUE 2 project when i npm run prod it show this error:

`

```<code>ERROR in ./resources/src/assets/styles/sass/globals/_globals.scss
Module build failed (from ./node_modules/laravel-mix/node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable: "$gradient-colors".
        on line 1 of resources/src/assets/styles/sass/globals/_palette.scss
        from line 5 of C:\xampp\htdocs\sas\resources\src\assets\styles\sass\globals\_globals.scss
>> @each $gcolor_name, $gcolor in $gradient-colors {
</code>```

`

My _palette.scss file i got error on it:
`

```<code>@each $gcolor_name, $gcolor in $gradient-colors {
  $start-color: map-get($gcolor, start-color);
  $end-color: map-get($gcolor, end-color);

  .sidebar-#{$gcolor_name} {
    .sidebar-left {
      @include directional-gradient(-154deg, $start-color, $end-color);
    }
  }
  .#{$gcolor_name} {
    @include directional-gradient(-154deg, $start-color, $end-color);
  }
  .btn.#{$gcolor_name} {
    &:active,
    &.active {
      @include directional-gradient(-90deg, $start-color, $end-color);
    }
  }
}
</code>```

`

How can i fix this???

i got this problem when i want run npm rum prod on laravel vue js 2 project

Body:
i edit a ready make laravel VUE 2 project when i npm run prod it show this error:

`

ERROR in ./resources/src/assets/styles/sass/globals/_globals.scss
Module build failed (from ./node_modules/laravel-mix/node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable: "$gradient-colors".
        on line 1 of resources/src/assets/styles/sass/globals/_palette.scss
        from line 5 of C:\xampp\htdocs\sas\resources\src\assets\styles\sass\globals\_globals.scss
>> @each $gcolor_name, $gcolor in $gradient-colors {

`

My _palette.scss file i got error on it:
`

@each $gcolor_name, $gcolor in $gradient-colors {
  $start-color: map-get($gcolor, start-color);
  $end-color: map-get($gcolor, end-color);

  .sidebar-#{$gcolor_name} {
    .sidebar-left {
      @include directional-gradient(-154deg, $start-color, $end-color);
    }
  }
  .#{$gcolor_name} {
    @include directional-gradient(-154deg, $start-color, $end-color);
  }
  .btn.#{$gcolor_name} {
    &:active,
    &.active {
      @include directional-gradient(-90deg, $start-color, $end-color);
    }
  }
}

`

How can i fix this???

i got this problem when i want run npm rum prod on laravel vue js 2 project


问:
APA style latex - Ubuntu
I am trying to use apastyle via

\bibliographystyle{apa}

for my reference list. Unfortunately, I get the error message:
"I found no style file" when using Bibtex.

Can someone maybe explain to me how to fix this error? I am using (TexLive2019 Debian) on
Ubuntu20.

Thanks for any suggestions.

Title: APA style latex - Ubuntu


问:
std::cout isn't printing after using std::wcout
After I'm using std::wcout, std::cout isn't printing

int main() {
  std::wcout << "Hello " << std::endl;
  std::cout << "World" << std::endl;
}
```
<p>Output:</p>
```Hello
```
<hr>
<pre class="lang-cpp prettyprint-override"><code>int main() {
  std::cout << "Hello " << std::endl;
  std::wcout << "World" << std::endl;
}
</code>```

Output:

```<code>Hello
World
</code>```

Body:
After I'm using std::wcout, std::cout isn't printing

int main() {
  std::wcout << "Hello " << std::endl;
  std::cout << "World" << std::endl;
}

Output:

Hello

int main() {
  std::cout << "Hello " << std::endl;
  std::wcout << "World" << std::endl;
}

Output:

Hello
World


问:
.NET MAUI: Customize Shell ContentPage Header
Is there an opportunity to customize the header bar of a content page?

I want to add some controls after the title:

How can i achieve this?

Here the example code of the page:

```<code><ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="FluxMobile.Pages.Arrival"
         Title="Arrival">
<VerticalStackLayout>
    <Label
        Text="Welcome to .NET MAUI!"
        VerticalOptions="Center"
        HorizontalOptions="Center" />
</VerticalStackLayout>
</code>```

The execution of this page is a shell content:

<ShellContent Title="{x:Static res:AppRes.Arrival}" Icon="arrival.png" ContentTemplate="{DataTemplate pages:Arrival}" Route="Arrival"  />

Thank you!

Body:
Is there an opportunity to customize the header bar of a content page?

I want to add some controls after the title:

How can i achieve this?

Here the example code of the page:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="FluxMobile.Pages.Arrival"
         Title="Arrival">
<VerticalStackLayout>

</VerticalStackLayout>

The execution of this page is a shell content:

<ShellContent Title="{x:Static res:AppRes.Arrival}" Icon="arrival.png" ContentTemplate="{DataTemplate pages:Arrival}" Route="Arrival"  />

Thank you!


问:
How to make index 0 without whitespace and the next index approve whitespace in dart?
For username

I have case when i want to approve in the text field if index 0 the text not approve whitespace, and the next index will approve whitespace with regex, how to do that?

trim white space on index 0 and approve in the next step also use regex symbol


问:
Git add a tracked folder
I have 2 folders inside a parent folder.

I initialized git inside server folder (i need it for deployment ) and I would like to create a new github repo containing both server and client folder . But, the server folder is always empty in this repo.

I tried to push the folder "QUIZERO" top github but server folder is empty

Title: Git add a tracked folder


问:
Extract rows with almost matching column values (pandas)
I have a dataframe with multiple columns, and I want to extract rows for which the column names are almost matching (basically, the entry in one column should be part of the entry of another column).

Suppose the whole dataframe is df, and the columns in question are Rubriken-Gruppe and User Gruppe. This is how I achieved what I want, but I wonder whether there is a more elegant/faster way to do this:

```<code>only_groups = df[['Rubriken-Gruppe', 'User Gruppe']]
same_flag = []
for index, row in only_groups.iterrows():
    same_flag.append(True if row['Rubriken-Gruppe'] in row['User Gruppe'].split(' ') else False)

same_groups = df[same_flag]
</code>```

The dataframe same_groups contains the desired result.

Body:
I have a dataframe with multiple columns, and I want to extract rows for which the column names are almost matching (basically, the entry in one column should be part of the entry of another column).

Suppose the whole dataframe is df, and the columns in question are Rubriken-Gruppe and User Gruppe. This is how I achieved what I want, but I wonder whether there is a more elegant/faster way to do this:

only_groups = df[['Rubriken-Gruppe', 'User Gruppe']]
same_flag = []
for index, row in only_groups.iterrows():
    same_flag.append(True if row['Rubriken-Gruppe'] in row['User Gruppe'].split(' ') else False)

same_groups = df[same_flag]

The dataframe same_groups contains the desired result.


问:
How to get OverlayFlags and OverlayCommit of Unified Write Filter with WMI-to-CSP Bridge?
OS is Windows 10 IoT Enterprise 21H2 with all necessary updates.

Accorting this article i can get values of OverlayFlags and OverlayCommit from CSP. Scheme of CSP is here.

According this capter i can use WMI-to-CSP Bridge to cponfigure settings with CSPs.

As shown in this example i try to get parameters OverlayFlags and OverlayCommit.

I tried to run command shell with admin rights "powershell" and "PsExec.exe -i -s powershell". In both cases I have the same result.
With below commands i can get list of classes but i can't see the "UnifiedWriteFilter" as shown here

```<code>$Namespace = "root\standardcimv2\embedded"
Get-CimClass -Namespace $Namespace
</code>```

Then i tried to find OverlayFlags and OverlayCommit in classes there are exists with below commands, but i can't find they are.

```<code>Get-CimInstance -Namespace $Namespace -ClassName 'UWF_Filter'
Get-CimInstance -Namespace $Namespace -ClassName 'UWF_Overlay'
Get-CimInstance -Namespace $Namespace -ClassName 'UWF_OverlayConfig'
</code>```

How can i use path './Vendor/MSFT' to find parameters of 'UnifiedWriteFilter' as shown here?

OK, i can get OverlayFlags from registry.
Mainly question - how can i get OverlayCommit value from somewhere as value for script?

Body:
OS is Windows 10 IoT Enterprise 21H2 with all necessary updates.

Accorting this article i can get values of OverlayFlags and OverlayCommit from CSP. Scheme of CSP is here.

According this capter i can use WMI-to-CSP Bridge to cponfigure settings with CSPs.

As shown in this example i try to get parameters OverlayFlags and OverlayCommit.

I tried to run command shell with admin rights "powershell" and "PsExec.exe -i -s powershell". In both cases I have the same result.
With below commands i can get list of classes but i can't see the "UnifiedWriteFilter" as shown here

$Namespace = "root\standardcimv2\embedded"
Get-CimClass -Namespace $Namespace

Then i tried to find OverlayFlags and OverlayCommit in classes there are exists with below commands, but i can't find they are.

Get-CimInstance -Namespace $Namespace -ClassName 'UWF_Filter'
Get-CimInstance -Namespace $Namespace -ClassName 'UWF_Overlay'
Get-CimInstance -Namespace $Namespace -ClassName 'UWF_OverlayConfig'

How can i use path './Vendor/MSFT' to find parameters of 'UnifiedWriteFilter' as shown here?

OK, i can get OverlayFlags from registry.
Mainly question - how can i get OverlayCommit value from somewhere as value for script?


问:
How to automate selection of column for VBA (macro)
I am currently writing my first vba code (macro - excel) for work.
I have been checking online and could not quite find an answer that solves my problem.

I have written the below code so far:

```<code>Sub UpdateRdata()
'
' UpdateRdata Macro
' change formula to use new data from CSV file
'

   ** Range("R3").Formula = "=C3-E27"**
    Range("R3").AutoFill Range("R3:R9")

    If Range("R3") > 0 Then
       Range("S3").Value = "NOK"
    End If
    If Range("R3") = 0 Then
       Range("S3").Value = "OK"
    End If
    Range("S3").AutoFill Range("S3:S9")

End Sub
</code>```

Now the issue is that everytime I add a new data in the column to the right Id like the macro to recognize and adapt the formuula. (i have hilighted it in bold, so the E27 is static but C3 should change to E3, F3, G3, etc. everytime i create a new reporting for each month).

Hope it makes sense. Is it possible to combine it with autofill? I have only referenced one cell but added autofill in order for the output/value of the formula to drag down in column R, R3 to R9

If possible please let me know which is the best approach. I tried with offset and activecell but always receive error messages

Body:
I am currently writing my first vba code (macro - excel) for work.
I have been checking online and could not quite find an answer that solves my problem.

I have written the below code so far:

Sub UpdateRdata()
'
' UpdateRdata Macro
' change formula to use new data from CSV file
'

   ** Range("R3").Formula = "=C3-E27"**
    Range("R3").AutoFill Range("R3:R9")

    If Range("R3") > 0 Then
       Range("S3").Value = "NOK"
    End If
    If Range("R3") = 0 Then
       Range("S3").Value = "OK"
    End If
    Range("S3").AutoFill Range("S3:S9")

End Sub

Now the issue is that everytime I add a new data in the column to the right Id like the macro to recognize and adapt the formuula. (i have hilighted it in bold, so the E27 is static but C3 should change to E3, F3, G3, etc. everytime i create a new reporting for each month).

Hope it makes sense. Is it possible to combine it with autofill? I have only referenced one cell but added autofill in order for the output/value of the formula to drag down in column R, R3 to R9

If possible please let me know which is the best approach. I tried with offset and activecell but always receive error messages


问:
NetLogo: How to change shape of a turtle if condition is true?
I want to make 2 turtles(a male and a female) get married. I have 2 different shapes for males and females in my simulation.

If a female meets a male on the same patch, they get married. When they do, I want to bundle them as one unit (i.e. I want to delete one of the turtles, and change the other to a third shape indicating a married couple).

How can I do this. I am already lost at the "meeting" stage.

What I have:

```<code>if any? other turtle-here with [?????]
</code>```

Pseudocode:
if female on_same_patch_as_male:

change her marital-status to married

Remove [one of the two turtles]

change the shape of the remaining turtle to "married-couple-icon"

Any help is appreciated

Body:
I want to make 2 turtles(a male and a female) get married. I have 2 different shapes for males and females in my simulation.

If a female meets a male on the same patch, they get married. When they do, I want to bundle them as one unit (i.e. I want to delete one of the turtles, and change the other to a third shape indicating a married couple).

How can I do this. I am already lost at the "meeting" stage.

What I have:

if any? other turtle-here with [?????]

Pseudocode:
if female on_same_patch_as_male:

change her marital-status to married

Remove [one of the two turtles]

change the shape of the remaining turtle to "married-couple-icon"

Any help is appreciated


问:
React | Dynamically build a form with react-hook-forms
I am trying to dynamically render a form based on a series of questions which are provided from an API. The form should render the questions individually (one by one) and should not add the next question if it has already been triggered.

I have managed to do the above, quite easily but then when it comes to the logic surrounding a "multiple choice" I am starting to have great difficulty, whereby I am currently unable to determine the logic which could help the above scenario.

The API returns a resource such as the following to render a form:

[
  {
    id: 1,
    title: 'What is your name?',
    type: 'free-text'
  },
  {
    id: 2,
    title: 'What is your age?',
    type: 'number'
  },
  {
    id: 3,
    title: 'What is your occupations?',
    type: 'choice',
    allowMultiple: true,
    choices: [
      { value: 'Developer', goTo: 1 },
      { value: 'Engineer' }
    ]
  },
  {
    id: 4,
    title: 'Any comments?',
    type: 'free-text'
  }
]
```

From the above example, goTo simulates what question that answer should go to. In this above example, after the use select "Developer" they will be greeted with "What is your name?" question again.

I have currently tried the following (React):

When the form is rendered it renders in the following format {questionId}-{index}. This is due to the same question being able to render on the screen at a given time, therefore "questionId" wouldn't be sufficient and would cause duplications.

Please find the link to codesandbox here:

https://codesandbox.io/s/unruffled-flower-pwyfbd

You will see that it works correctly for inputs, but then when using the choice the logic is messed up.

What should happen is the following:

When "What is your name?" has a value -> load "What is your age?"

When "What is your age" has a value -> load "What is your
occupations?"

When "Developer" option is checked -> load "What is your name" (due to the branching).

Loop to the start.

When "Engineer" option is checked -> load "Any comments?"

If "Developer" is unchecked, it removed all inputs / checkboxes that were generated from that checkbox.

If "Engineer" option is unchecked, it removes all inputs / checkboxes that were generated from that checkbox.

** please note, I could be going in the completely wrong direction with this and I am happy for suggestions on how to improve the code / a alternative method to go down **

Body:
I am trying to dynamically render a form based on a series of questions which are provided from an API. The form should render the questions individually (one by one) and should not add the next question if it has already been triggered.

I have managed to do the above, quite easily but then when it comes to the logic surrounding a "multiple choice" I am starting to have great difficulty, whereby I am currently unable to determine the logic which could help the above scenario.

The API returns a resource such as the following to render a form:

[
  {
    id: 1,
    title: 'What is your name?',
    type: 'free-text'
  },
  {
    id: 2,
    title: 'What is your age?',
    type: 'number'
  },
  {
    id: 3,
    title: 'What is your occupations?',
    type: 'choice',
    allowMultiple: true,
    choices: [
      { value: 'Developer', goTo: 1 },
      { value: 'Engineer' }
    ]
  },
  {
    id: 4,
    title: 'Any comments?',
    type: 'free-text'
  }
]

From the above example, goTo simulates what question that answer should go to. In this above example, after the use select "Developer" they will be greeted with "What is your name?" question again.

I have currently tried the following (React):

When the form is rendered it renders in the following format {questionId}-{index}. This is due to the same question being able to render on the screen at a given time, therefore "questionId" wouldn't be sufficient and would cause duplications.

Please find the link to codesandbox here:

https://codesandbox.io/s/unruffled-flower-pwyfbd

You will see that it works correctly for inputs, but then when using the choice the logic is messed up.

What should happen is the following:

When "What is your name?" has a value -> load "What is your age?"

When "What is your age" has a value -> load "What is your
occupations?"

When "Developer" option is checked -> load "What is your name" (due to the branching).

Loop to the start.

When "Engineer" option is checked -> load "Any comments?"

If "Developer" is unchecked, it removed all inputs / checkboxes that were generated from that checkbox.

If "Engineer" option is unchecked, it removes all inputs / checkboxes that were generated from that checkbox.

** please note, I could be going in the completely wrong direction with this and I am happy for suggestions on how to improve the code / a alternative method to go down **


问:
Calculating mAP, F1 score for MaskRCNN
To detect Litchi, I applied the original code of MaskRCNN from its github repository "https://github.com/matterport/Mask RCNN" to my dataset. The detection accuracy is quite high. However, I was unable to locate code to evaluate other evaluation matrices such as mAP, F1 scource, and so on. Can anyone assist me in this matter?

Thank you

Title: Calculating mAP, F1 score for MaskRCNN


问:
when switch is "ON", code check specific condition continuously until the user make switch "OFF" (in flutter)
When the user make switch "ON" , some specific condition will be checking under the while loop. But the user make switch "OFF" before hitting condition then the switch should be "OFF".

But the problem is that code is unable to make switch "OFF" when the user make switch "OFF" i.e. it means code is unable to exit from while loop when the user clicked on switch to make it "OFF".

I am expecting from the code:

When the user clicked on switch to make Switch "ON" then the code will go under the "While loop" to check some specific condition until the hitting condition.

Before hitting condition if the user clicked again on switch to make Switch "OFF" then the code "break" the "while" loop and make Switch "OFF"

enter image description here


问:
PowerShell Script Stop-Restart Service on Windows Server 2022 via Intranet App - Not Working
I've got an aspx intranet app written in VB, that calls a PowerShell script to stop and restart a service. It is run using an ID in the local admin group and works fine on all servers but is not working on Windows 2022 Server. It'll return errors such as the following: Cannot be stopped due to the following error: Cannot open 'myService' service on computer 'Win2022 Server'.

The script lives locally on the servers root, and has permissions granted to all local admins. The PS versions are all v5+. The app and script function properly on all other servers except Windows 2022 Server. I've been struggling with this if anyone can provide some guidance or help whatsoever.
thanks

When the PS script is run locally on the server right from PwerShell ISE, not invoked from intranet application, it runs fine. When run remotely either from Intranet app in Edge, or from File Explorer, the PS's Stop-Service fails with the error above.
This is the PowerShell script:

```<code>$running = "Running"
$stopPending = "StopPending"
$stopped = "Stopped"
$serviceDNm = "Video Service"
$serviceSrvcNm = "VideoService"
$srvrname = "Win2022Server"

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

$s = (Get-Service -Name $serviceSrvcNm -Computername $srvrname)

Get-Service -Name $serviceSrvcNm -ComputerName $srvrname | Set-Service -Status stopped

s.Stop()

Start-Sleep -Seconds 10

$s = (Get-Service -Computername $srvrname -Name $serviceSrvcNm)
if($s.status -eq "Stopped")
        {
           $s.Start() #start-service -name $s.Name -PassThru
        }
</code>```

Body:
I've got an aspx intranet app written in VB, that calls a PowerShell script to stop and restart a service. It is run using an ID in the local admin group and works fine on all servers but is not working on Windows 2022 Server. It'll return errors such as the following: Cannot be stopped due to the following error: Cannot open 'myService' service on computer 'Win2022 Server'.

The script lives locally on the servers root, and has permissions granted to all local admins. The PS versions are all v5+. The app and script function properly on all other servers except Windows 2022 Server. I've been struggling with this if anyone can provide some guidance or help whatsoever.
thanks

When the PS script is run locally on the server right from PwerShell ISE, not invoked from intranet application, it runs fine. When run remotely either from Intranet app in Edge, or from File Explorer, the PS's Stop-Service fails with the error above.
This is the PowerShell script:

$running = "Running"
$stopPending = "StopPending"
$stopped = "Stopped"
$serviceDNm = "Video Service"
$serviceSrvcNm = "VideoService"
$srvrname = "Win2022Server"

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

$s = (Get-Service -Name $serviceSrvcNm -Computername $srvrname)

Get-Service -Name $serviceSrvcNm -ComputerName $srvrname | Set-Service -Status stopped

s.Stop()

Start-Sleep -Seconds 10

$s = (Get-Service -Computername $srvrname -Name $serviceSrvcNm)
if($s.status -eq "Stopped")
        {
           $s.Start() #start-service -name $s.Name -PassThru
        }


问:
Ruby 'Go To Definition' not working in VS Code for methods defined inside a block

Issue

For support of Ruby, I'm using the VS Code extension listed below. I'm having trouble with the 'Go To Definition' command for methods defined within a block

```<code>module Abc
  module DefExtensions
    extend ActiveSupport::Concern
    included do
      def foo1() end # this gets ignored
    end

    User.new {
      def foo2() end
    }
    end

    def foo3
      def obj.bar() end # this gets ignored
    end
  end
end
</code>```

Extension

```<code>Name: Ruby
Id: rebornix.ruby
Description: Ruby language support and debugging for Visual Studio Code
Version: 0.28.1
Publisher: Peng Lv
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=rebornix.Ruby
</code>```

Facing the same issue with Solargraph too

```<code>Name: Ruby Solargraph
Id: castwide.solargraph
Description: A Ruby language server featuring code completion, intellisense, and inline documentation
Version: 0.24.0
Publisher: Castwide
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=castwide.solargraph
</code>```

I've reported an issue to ruby-method-locate which is used by the extension to support 'Go To Definition'

Is there a fix or solution for the aforementioned issue?

Body:
Issue

For support of Ruby, I'm using the VS Code extension listed below. I'm having trouble with the 'Go To Definition' command for methods defined within a block

module Abc
  module DefExtensions
    extend ActiveSupport::Concern
    included do
      def foo1() end # this gets ignored
    end

    User.new {
      def foo2() end
    }
    end

    def foo3
      def obj.bar() end # this gets ignored
    end
  end
end

Extension

Name: Ruby
Id: rebornix.ruby
Description: Ruby language support and debugging for Visual Studio Code
Version: 0.28.1
Publisher: Peng Lv
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=rebornix.Ruby

Facing the same issue with Solargraph too

Name: Ruby Solargraph
Id: castwide.solargraph
Description: A Ruby language server featuring code completion, intellisense, and inline documentation
Version: 0.24.0
Publisher: Castwide
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=castwide.solargraph

I've reported an issue to ruby-method-locate which is used by the extension to support 'Go To Definition'

Is there a fix or solution for the aforementioned issue?


问:
Getting value error often while trying to implement a GAN
This is the code I have where I have tried to implement a basic GAN:

```<code>import tensorflow as tf
import numpy as np

#Set the seed for reproducibility
np.random.seed(42)

#load the required image files, convert them to array
data_path = r"C:/Users/jayanth.kumar/Desktop/pou_new/"
#Import as tf.Dataset
data = tf.keras.preprocessing.image_dataset_from_directory(data_path, label_mode = None, image_size = (28, 28))
a = np.stack(data)

#Build the generator model
generator = tf.keras.Sequential()
generator.add(tf.keras.layers.Dense(128450*3, input_dim=100))
generator.add(tf.keras.layers.LeakyReLU())
generator.add(tf.keras.layers.BatchNormalization())
generator.add(tf.keras.layers.Reshape((9, 28, 28, 3)))

#Build the discriminator model
discriminator = tf.keras.Sequential()
discriminator.add(tf.keras.layers.Flatten(input_shape=(9, 28, 28, 3)))
discriminator.add(tf.keras.layers.Dense(128))
discriminator.add(tf.keras.layers.LeakyReLU())
discriminator.add(tf.keras.layers.Dense(1, activation='sigmoid'))

#Build the combined model
gan = tf.keras.models.Sequential()
gan.add(generator)
gan.add(discriminator)

#Compile the model
gan.compile(loss='binary_crossentropy', optimizer='adam')

#Train the model
gan.fit(a, epochs=100)
</code>```

When I run the model, I have been getting these different value error(s). Like for example:

```<code>ValueError: Exception encountered when calling layer "reshape_14" (type Reshape).

total size of new array must be unchanged, input_shape = [3596600], output_shape = [9, 28, 28, 3]

Call arguments received by layer "reshape_14" (type Reshape):
  • inputs=tf.Tensor(shape=(None, 3596600), dtype=float32)

</code>```

I have tried reshaping the array, changing the input dimensions such that it matches the input shape but every time when I do that and run the model, the error occurs for other layers i.e. for example reshape_15, reshape 18.

Body:
This is the code I have where I have tried to implement a basic GAN:

import tensorflow as tf
import numpy as np

#Set the seed for reproducibility
np.random.seed(42)

#load the required image files, convert them to array
data_path = r"C:/Users/jayanth.kumar/Desktop/pou_new/"
#Import as tf.Dataset
data = tf.keras.preprocessing.image_dataset_from_directory(data_path, label_mode = None, image_size = (28, 28))
a = np.stack(data)

#Build the generator model
generator = tf.keras.Sequential()
generator.add(tf.keras.layers.Dense(128450*3, input_dim=100))
generator.add(tf.keras.layers.LeakyReLU())
generator.add(tf.keras.layers.BatchNormalization())
generator.add(tf.keras.layers.Reshape((9, 28, 28, 3)))

#Build the discriminator model
discriminator = tf.keras.Sequential()
discriminator.add(tf.keras.layers.Flatten(input_shape=(9, 28, 28, 3)))
discriminator.add(tf.keras.layers.Dense(128))
discriminator.add(tf.keras.layers.LeakyReLU())
discriminator.add(tf.keras.layers.Dense(1, activation='sigmoid'))

#Build the combined model
gan = tf.keras.models.Sequential()
gan.add(generator)
gan.add(discriminator)

#Compile the model
gan.compile(loss='binary_crossentropy', optimizer='adam')

#Train the model
gan.fit(a, epochs=100)

When I run the model, I have been getting these different value error(s). Like for example:

ValueError: Exception encountered when calling layer "reshape_14" (type Reshape).

total size of new array must be unchanged, input_shape = [3596600], output_shape = [9, 28, 28, 3]

Call arguments received by layer "reshape_14" (type Reshape):
  • inputs=tf.Tensor(shape=(None, 3596600), dtype=float32)

I have tried reshaping the array, changing the input dimensions such that it matches the input shape but every time when I do that and run the model, the error occurs for other layers i.e. for example reshape_15, reshape 18.