问:
Laravel (Lumen) connect to database on another server on same network
I've got a Laravel project on a server, and a Laravel Lumen 8 project on another server, they're both virtual machines and are clones of one another so have the same hardware and OS.

I have a domain, which for the purposes of this Stackoverflow we'll call foo.com, it goes through Cloudflare, both servers are ipv6 servers and when pinging each other via ssh they can see each other just fine.

The problem I have is with connecting to the MySQL (Maria DB) database from my Lumen project on the other server.

I've tried using:

The domain of the server where the DB exists

The ipv6 domain

The VM's local ipv4 address since both servers exist on the same network this is how they can see each other

I'm testing the connection using Tinker and running:

DB::connection()->getPdo();
```
<p>And I'm unable to connect for some reason, these are the combinations and errors I've encountered and would like to know what I'm missing:</p>
<h3>Attempt 1</h3>
```DB_CONNECTION=mysql
DB_HOST=local ipv4
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```
<blockquote>
<p>PDOException with message 'SQLSTATE[HY000] [2002] No route to host</p>
</blockquote>
<h3>Attempt 2</h3>
```DB_CONNECTION=mysql
DB_HOST=ipv6 address
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```
<blockquote>
<p>PDOException with message 'SQLSTATE[HY000] [2002] Invalid argument'</p>
</blockquote>
<h3>Attempt 3</h3>
```DB_CONNECTION=mysql
DB_HOST=api.foo.com
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```

PDOException with message 'SQLSTATE[HY000] [2002] Connection timed out'

How can I get my Lumen project to connect to my Laravel database on another server, I'm pretty sure I've tried every combination here.

答:
To connect MySQL Database on separate server, We have to check the followings:

Two servers can reach via ping or ssh.

MySQL can listen on IP of the dedicated VM or server.

Laravel or Lumen can access the IP address of the server.

In this answer, lets assume the network is 192.168.1.0/24. Lumen Server is Server A with 192.168.1.1. MySQL server is is Server B with 192.168.1.2.

In My configuration, I check Two servers can reach via ping using:

ping -c 4 192.168.1.2

the server must respond like.

```<code>PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.
64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.399 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.412 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.352 ms
64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.409 ms

--- 192.168.1.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3057ms
rtt min/avg/max/mdev = 0.352/0.393/0.412/0.024 ms
</code>```

For IPv6, use ping 6

ping6 -c 4 abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd

Result similar to IPv4,

```<code>PING abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd(abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd) 56 data bytes
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=1 ttl=61 time=0.421 ms
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=2 ttl=61 time=0.333 ms
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=3 ttl=61 time=0.388 ms
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=4 ttl=61 time=0.324 ms

--- 2001:19f0:5:241:a315:602c:64ce:d6c1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4096ms
rtt min/avg/max/mdev = 0.324/0.368/0.421/0.035 ms
</code>```

if the result is other than this, please make sure you have connectivity or the same network. Numbers will be changed according to real result. If failed, try ssh by using:

```<code>ssh user@192.168.1.2
ssh user@[abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd]
</code>```

If your server B is not accessible both via ssh or ping, there is some problem with your server connectivity.

If these twos can ping, you can make sure your MySQL Server is listening to IP address of the server. You can check using:

#IPv4

```<code>nmap -sT -O 192.168.1.2
</code>```

#IPv6

```<code>nmap -sT -O -6 abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd
</code>```

The Result will show like:

```<code>Starting Nmap 7.92 ( https://nmap.org ) at 2022-02-11 10:04 EST
Nmap scan report for 192.168.1.2
Host is up (0.00036s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT     STATE SERVICE
3306/tcp open  mysql
MAC Address: AA:BB:CC:DD:EE:FF (Unknown)
Device type: general purpose
Running: Linux 4.X|5.X
OS CPE: cpe:/o:linux:linux_kernel:4 cpe:/o:linux:linux_kernel:5
OS details: Linux 4.15 - 5.6
Network Distance: 1 hop

OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 1.45 seconds
</code>```

Check the Session

```<code>PORT     STATE SERVICE
3306/tcp open  mysql
</code>```

if it is listen, MySQL is listening to port. Otherwise, please change the following in mysql config. Mine is /etc/mysql/my.cnf.

```<code>port          = 3306
#ipv4
bind-address  = 192.168.1.2
#ipv6
bind-address  = abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd
</code>```

CAUTION: editing Configs requires sudo or root permissions

After changing and restarting server, please check with nmap again to make sure your DB Server starts listening. PLEASE MAKE SURE FIREWALL IS OFF FOR TESTING.

To Disable Temporary, sudo service firewalld stop and try again. Please refer to your distro firewall service. Both Lumen and MySQL Servers should disable for testing reason. NOT RECOMMENDED FOR PRODUCTION SERVERS.

If Step 1 and 2 are working well. try to access the server with Laravel Tinker, or mysql client.

```<code>mysql -h 192.168.1.2 -u root -p password
</code>```

if it shows other than socks not found, like access denied, please refer to MySQL or Mariadb Manual.

If it is successful, please set your .env file inside your Laravel/Lumen Project.

```<code>#IPv4
DB_HOST=192.168.1.2
#IPv6
DB_HOST=[2001:19f0:5:241:a315:602c:64ce:d6c1]
DB_PORT=3306
</code>```

Hope this help. Worked in Mariadb.

Body:
I've got a Laravel project on a server, and a Laravel Lumen 8 project on another server, they're both virtual machines and are clones of one another so have the same hardware and OS.

I have a domain, which for the purposes of this Stackoverflow we'll call foo.com, it goes through Cloudflare, both servers are ipv6 servers and when pinging each other via ssh they can see each other just fine.

The problem I have is with connecting to the MySQL (Maria DB) database from my Lumen project on the other server.

I've tried using:

The domain of the server where the DB exists

The ipv6 domain

The VM's local ipv4 address since both servers exist on the same network this is how they can see each other

I'm testing the connection using Tinker and running:

DB::connection()->getPdo();

And I'm unable to connect for some reason, these are the combinations and errors I've encountered and would like to know what I'm missing:

Attempt 1

DB_CONNECTION=mysql
DB_HOST=local ipv4
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] No route to host

Attempt 2

DB_CONNECTION=mysql
DB_HOST=ipv6 address
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] Invalid argument'

Attempt 3

DB_CONNECTION=mysql
DB_HOST=api.foo.com
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] Connection timed out'

How can I get my Lumen project to connect to my Laravel database on another server, I'm pretty sure I've tried every combination here.

Body:
To connect MySQL Database on separate server, We have to check the followings:

Two servers can reach via ping or ssh.

MySQL can listen on IP of the dedicated VM or server.

Laravel or Lumen can access the IP address of the server.

In this answer, lets assume the network is 192.168.1.0/24. Lumen Server is Server A with 192.168.1.1. MySQL server is is Server B with 192.168.1.2.

In My configuration, I check Two servers can reach via ping using:

ping -c 4 192.168.1.2

the server must respond like.

PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.
64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.399 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.412 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.352 ms
64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.409 ms

--- 192.168.1.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3057ms
rtt min/avg/max/mdev = 0.352/0.393/0.412/0.024 ms

For IPv6, use ping 6

ping6 -c 4 abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd

Result similar to IPv4,

PING abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd(abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd) 56 data bytes
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=1 ttl=61 time=0.421 ms
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=2 ttl=61 time=0.333 ms
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=3 ttl=61 time=0.388 ms
64 bytes from abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd: icmp_seq=4 ttl=61 time=0.324 ms

--- 2001:19f0:5:241:a315:602c:64ce:d6c1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4096ms
rtt min/avg/max/mdev = 0.324/0.368/0.421/0.035 ms

if the result is other than this, please make sure you have connectivity or the same network. Numbers will be changed according to real result. If failed, try ssh by using:

ssh user@192.168.1.2
ssh user@[abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd]

If your server B is not accessible both via ssh or ping, there is some problem with your server connectivity.

If these twos can ping, you can make sure your MySQL Server is listening to IP address of the server. You can check using:

#IPv4

nmap -sT -O 192.168.1.2

#IPv6

nmap -sT -O -6 abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd

The Result will show like:

Starting Nmap 7.92 ( https://nmap.org ) at 2022-02-11 10:04 EST
Nmap scan report for 192.168.1.2
Host is up (0.00036s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT     STATE SERVICE
3306/tcp open  mysql
MAC Address: AA:BB:CC:DD:EE:FF (Unknown)
Device type: general purpose
Running: Linux 4.X|5.X
OS CPE: cpe:/o:linux:linux_kernel:4 cpe:/o:linux:linux_kernel:5
OS details: Linux 4.15 - 5.6
Network Distance: 1 hop

OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 1.45 seconds

Check the Session

PORT     STATE SERVICE
3306/tcp open  mysql

if it is listen, MySQL is listening to port. Otherwise, please change the following in mysql config. Mine is /etc/mysql/my.cnf.

port          = 3306
#ipv4
bind-address  = 192.168.1.2
#ipv6
bind-address  = abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd

CAUTION: editing Configs requires sudo or root permissions

After changing and restarting server, please check with nmap again to make sure your DB Server starts listening. PLEASE MAKE SURE FIREWALL IS OFF FOR TESTING.

To Disable Temporary, sudo service firewalld stop and try again. Please refer to your distro firewall service. Both Lumen and MySQL Servers should disable for testing reason. NOT RECOMMENDED FOR PRODUCTION SERVERS.

If Step 1 and 2 are working well. try to access the server with Laravel Tinker, or mysql client.

mysql -h 192.168.1.2 -u root -p password

if it shows other than socks not found, like access denied, please refer to MySQL or Mariadb Manual.

If it is successful, please set your .env file inside your Laravel/Lumen Project.

#IPv4
DB_HOST=192.168.1.2
#IPv6
DB_HOST=[2001:19f0:5:241:a315:602c:64ce:d6c1]
DB_PORT=3306

Hope this help. Worked in Mariadb.


来源: stackexchange

问:
Set PurchReqLine.BuyingLegalEntity default value to blank
I encountered a problem in the development, requesting a new purchase request line of a purchase with a legal person with a default value of empty

I tried a variety of methods, the default value can not be overriden.

The following is my code.

```<code>[ExtensionOf(formDataSourceStr(PurchReqTable, PurchReqLine))]
final class IWS_PurchReqTable_FDS_Extension
{

    public void initValue()
    {
        next initValue();
        //ttsbegin;
        PurchReqLine purchReqLine = this.cursor();
        purchReqLine.BuyingLegalEntity = 0;
        purchReqLine.modifiedField(fieldNum(PurchReqLine,BuyingLegalEntity));
        this.rereadReferenceDataSources(); //Refresh value
        this.reread();
        this.research(1);

        FormReferenceGroupControl BuyingLegalEntity = this.formRun().design().controlName(formControlStr(PurchReqTable, PurchReqLine_BuyingLegalEntity));
        FormStringControl BuyingLegalEntity_DataArea = this.formRun().design().controlName(formControlStr(PurchReqTable, PurchReqLine_BuyingLegalEntity_DataArea));
        BuyingLegalEntity.value(0);

        BuyingLegalEntity.resolveChanges();
        BuyingLegalEntity.referenceDataSource().research(1);
        BuyingLegalEntity.modified();
        //BuyingLegalEntity_DataArea.text('');
        //BuyingLegalEntity_DataArea.modified();

        purchReqLine.BuyingLegalEntity = 0;
        purchReqLine.modifiedField(fieldNum(PurchReqLine,BuyingLegalEntity));
        //purchReqLine.update();
        //purchReqLine.insert();
        //this.rereadReferenceDataSources();
        //this.refresh();
        //this.reread();
        //this.resetLine();
        //ttscommit;
    }
    //End

}
</code>```

答:
It is not totally clear to me what you are trying to do.

Most values are "born" zero or blank and if that is not the case for this field, something else is setting the field, maybe after your code in initValue is called. The cross reference may be of good value here to find the code that references the field.

First of, you should definitely not reference the controls, also calling modifiedField and research from here is a total no-go.

For a start try this:

```<code>public void initValue()
{
    next initValue();
    purchReqLine.BuyingLegalEntity = 0;
}
</code>```

It simply sets the field to zero. Do not worry about the field control, it will be rendered from the buffer value after the call to initValue.

If that does not solve your problem, something else is setting the field. You can set a breakpoint here, then follow to code until the field is set. Also add the value to the watch list, maybe do conditional debugging.

If another extension for this datasource exist it may override your behaviour as the execution order of extensions is arbitrary.

ContentLicense: CC BY-SA 4.0

Body:
I encountered a problem in the development, requesting a new purchase request line of a purchase with a legal person with a default value of empty

I tried a variety of methods, the default value can not be overriden.

The following is my code.

[ExtensionOf(formDataSourceStr(PurchReqTable, PurchReqLine))]
final class IWS_PurchReqTable_FDS_Extension
{

    public void initValue()
    {
        next initValue();
        //ttsbegin;
        PurchReqLine purchReqLine = this.cursor();
        purchReqLine.BuyingLegalEntity = 0;
        purchReqLine.modifiedField(fieldNum(PurchReqLine,BuyingLegalEntity));
        this.rereadReferenceDataSources(); //Refresh value
        this.reread();
        this.research(1);

        FormReferenceGroupControl BuyingLegalEntity = this.formRun().design().controlName(formControlStr(PurchReqTable, PurchReqLine_BuyingLegalEntity));
        FormStringControl BuyingLegalEntity_DataArea = this.formRun().design().controlName(formControlStr(PurchReqTable, PurchReqLine_BuyingLegalEntity_DataArea));
        BuyingLegalEntity.value(0);

        BuyingLegalEntity.resolveChanges();
        BuyingLegalEntity.referenceDataSource().research(1);
        BuyingLegalEntity.modified();
        //BuyingLegalEntity_DataArea.text('');
        //BuyingLegalEntity_DataArea.modified();

        purchReqLine.BuyingLegalEntity = 0;
        purchReqLine.modifiedField(fieldNum(PurchReqLine,BuyingLegalEntity));
        //purchReqLine.update();
        //purchReqLine.insert();
        //this.rereadReferenceDataSources();
        //this.refresh();
        //this.reread();
        //this.resetLine();
        //ttscommit;
    }
    //End

}

Body:
It is not totally clear to me what you are trying to do.

Most values are "born" zero or blank and if that is not the case for this field, something else is setting the field, maybe after your code in initValue is called. The cross reference may be of good value here to find the code that references the field.

First of, you should definitely not reference the controls, also calling modifiedField and research from here is a total no-go.

For a start try this:

public void initValue()
{
    next initValue();
    purchReqLine.BuyingLegalEntity = 0;
}

It simply sets the field to zero. Do not worry about the field control, it will be rendered from the buffer value after the call to initValue.

If that does not solve your problem, something else is setting the field. You can set a breakpoint here, then follow to code until the field is set. Also add the value to the watch list, maybe do conditional debugging.

If another extension for this datasource exist it may override your behaviour as the execution order of extensions is arbitrary.


问:
How do I set EOF on an istream without reading formatted input?
I'm doing a read in on a file character by character using istream::get(). How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace) and set the corresponding flags (EOF, bad, etc)?</p>

答:
Construct an istream::sentry on the stream. This will have a few side effects, the one we care about being:

If its skipws format flag is set, and the constructor is not passed true as second argument (noskipws), all leading whitespace characters (locale-specific) are extracted and discarded. If this operation exhausts the source of characters, the function sets both the failbit and eofbit internal state flags

OwnerDisplayName: Stuart P. Bentley

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stuart P. Bentley

ContentLicense: CC BY-SA 3.0


问:
Simple substraction on PHP (Arithmetic Operators)
I need some help with this simple substraction:

```<code>$savings = ($newprice - $newvalue);
</code>```

$newprice and $newvalue are values like 120.00 and 40.00

The problem is that the result is shown as 80 , without the .00 (dot00) at the end.

I will like to keep the values on the same format (a dot plus double cero at the end); what I need to change or include to that code ?

Thanks in advance

答:
```<code>$savings = sprintf("%0.2f", ($newprice - $newvalue));
</code>```

Body:
I need some help with this simple substraction:

$savings = ($newprice - $newvalue);

$newprice and $newvalue are values like 120.00 and 40.00

The problem is that the result is shown as 80 , without the .00 (dot00) at the end.

I will like to keep the values on the same format (a dot plus double cero at the end); what I need to change or include to that code ?

Thanks in advance


问:
PHP 7.2 Warning count(): Parameter must be an array or an object that implements Countable
i've a problem with Wordpress. This is the error message: PHP 7.2 Warning count(): Parameter must be an array or an object that implements Countable /web/htdocs/www.firenzeflowershow.com/home/wp-content/themes/wpex-elegant/functions/meta/init.php on line 750</p>
```<code>> elseif ( is_array( $meta_box['pages'] ) && count( $meta_box['pages']
> === 1  ))             $type = is_string( end( $meta_box['pages'] ) ) ? end( $meta_box['pages'] ) : false;
</code>```

答:
Please try if this works:</p>
```<code>elseif ( is_array( $meta_box['pages'] ) && count($meta_box['pages'])
>= 1  )
</code>```

Body:
i've a problem with Wordpress. This is the error message: PHP 7.2 Warning count(): Parameter must be an array or an object that implements Countable /web/htdocs/www.firenzeflowershow.com/home/wp-content/themes/wpex-elegant/functions/meta/init.php on line 750

> elseif ( is_array( $meta_box['pages'] ) && count( $meta_box['pages']
> === 1  ))             $type = is_string( end( $meta_box['pages'] ) ) ? end( $meta_box['pages'] ) : false;

Body:
Please try if this works:

elseif ( is_array( $meta_box['pages'] ) && count($meta_box['pages'])
>= 1  )


问:
How to use a viewBinding in BottomNavigation
I'm trying to implement a bottomBarNavigation as I'm practicing how to use it. I'm confused , my menu is not showing as I'm trying to initialize it to a fragment. Please how do I do it?. Im still figuring how to use viewBinding.

these are my code :

Menu

```<code><item
   android:id="@+id/nv_home"
    android:title="Home"
    android:icon="@drawable/ic_add_contact_background"/>

<item
    android:id="@+id/nv_notification"
    android:title="Notification"
    android:icon="@drawable/ic_add_contact_background"/>

<item
    android:id="@+id/nv_profile"
    android:title="Profile"
    android:icon="@drawable/ic_add_contact_background"/>
</code>```

Activity

```<code>private lateinit var binding: ActivityMain2Binding

override fun onCreate(savedInstanceState: Bundle?) {
    binding = ActivityMain2Binding.inflate(layoutInflater)
    super.onCreate(savedInstanceState)
    setContentView(binding.root)
    supportActionBar?.hide()

    val oneFragment = OneFragment()
    val twoFragment = TwoFragment()
    val threeFragment = ThreeFragment()

    setCurrentFragment(oneFragment)

    binding.bottomNavigationView.setOnItemSelectedListener {
        when(it.itemId){
            binding.nv_home-> setCurrentFragment(firstFragment)  // this is what I intended doing but the nv_home is not showing.
        }
    }
}

private fun setCurrentFragment(fragment : Fragment) = supportFragmentManager.beginTransaction().apply {
    replace(binding.frame_fragment,fragment)
    commit()
}
</code>```

答:
As per the official documentation link:

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.

The view binding is available for the layout files as its using the findviewbyId(R.id.viewid) and in the case of menu items we use the menu.findItem(R.id.menuid) so the menu id's won't available in the binding variables

for the bottomnaviagtion use the menu id like this:

```<code> binding.bottomNavigationView.setOnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.nv_home-> {
                 setCurrentFragment(firstFragment)
             }
              }
</code>```

Body:
I'm trying to implement a bottomBarNavigation as I'm practicing how to use it. I'm confused , my menu is not showing as I'm trying to initialize it to a fragment. Please how do I do it?. Im still figuring how to use viewBinding.

these are my code :

Menu

<item
   android:id="@+id/nv_home"
    android:title="Home"
    android:icon="@drawable/ic_add_contact_background"/>

<item
    android:id="@+id/nv_notification"
    android:title="Notification"
    android:icon="@drawable/ic_add_contact_background"/>

<item
    android:id="@+id/nv_profile"
    android:title="Profile"
    android:icon="@drawable/ic_add_contact_background"/>

Activity

private lateinit var binding: ActivityMain2Binding

override fun onCreate(savedInstanceState: Bundle?) {
    binding = ActivityMain2Binding.inflate(layoutInflater)
    super.onCreate(savedInstanceState)
    setContentView(binding.root)
    supportActionBar?.hide()

    val oneFragment = OneFragment()
    val twoFragment = TwoFragment()
    val threeFragment = ThreeFragment()

    setCurrentFragment(oneFragment)

    binding.bottomNavigationView.setOnItemSelectedListener {
        when(it.itemId){
            binding.nv_home-> setCurrentFragment(firstFragment)  // this is what I intended doing but the nv_home is not showing.
        }
    }
}

private fun setCurrentFragment(fragment : Fragment) = supportFragmentManager.beginTransaction().apply {
    replace(binding.frame_fragment,fragment)
    commit()
}

Body:
As per the official documentation link:

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.

The view binding is available for the layout files as its using the findviewbyId(R.id.viewid) and in the case of menu items we use the menu.findItem(R.id.menuid) so the menu id's won't available in the binding variables

for the bottomnaviagtion use the menu id like this:

 binding.bottomNavigationView.setOnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.nv_home-> {
                 setCurrentFragment(firstFragment)
             }
              }


问:
How to validate and return access and refresh tokens after user.save()
I'm verifying the user OTP to change password and after change password I'm unable to create access and refresh token using JWT ,

Normally when user get log in I use following method MyTokenObtainPairView which return both access and refresh token with all other stuff to UserSerializerWithToken.

```<code>class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)

        serializer = UserSerializerWithToken(self.user).data
        for k, v in serializer.items():
            data[k] = v

        return data

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer
</code>```

I coppied similar appraoch to return UserSerializerWithToken after set_password and user.save()

UserSerializerWithToken is

```<code>class UserSerializerWithToken(UserSerializer):
    token = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomUser
        fields = ['id',
                  'isAdmin',
                  'token']

    def get_token(self, obj):
        token = RefreshToken.for_user(obj)
        return str(token.access_token)
</code>```

and the problematic function is

```<code>@api_view(['PUT'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']
    user = CustomUser.objects.get(email=email)
    serializer = UserSerializerWithToken(user, many=False)
    if CustomUser.objects.filter(email=email).exists():
        if otp_to_verify == user.otp:
            if new_password != '':
                user.set_password(new_password)
                user.save() # here password gets changed
                return Response(serializer.data) #
            else:
                message = {
                'detail': 'Password cant be empty'}
                return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
</code>```

I receive the toke but not getting access and refresh toke to use it to login next time. I'm assuming user.save() dosnt create refresh and access token here. Can anybody identify why this is happening and how to fix that

答:
user.save() does not create the tokens

token = RefreshToken.for_user(obj)
return str(token.access_token)

These lines create the token.

In my opinion, you dont need the serializer here.

```<code>@api_view(['PUT'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']
    user = CustomUser.objects.get(email=email)
    if CustomUser.objects.filter(email=email).exists():
        otp_to_verify == user.otp
        if new_password != '':
            user.set_password(new_password)
            user.save() # here password gets changed
            token = RefreshToken.for_user(user)
            response = { "refresh_token": str(token),
                         "access_token": str(token.access_token)
                       }
            return Response(response)
        else:
            message = {
                'detail': 'Password cant be empty'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
</code>```

Body:
I'm verifying the user OTP to change password and after change password I'm unable to create access and refresh token using JWT ,

Normally when user get log in I use following method MyTokenObtainPairView which return both access and refresh token with all other stuff to UserSerializerWithToken.

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)

        serializer = UserSerializerWithToken(self.user).data
        for k, v in serializer.items():
            data[k] = v

        return data

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

I coppied similar appraoch to return UserSerializerWithToken after set_password and user.save()

UserSerializerWithToken is

class UserSerializerWithToken(UserSerializer):
    token = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomUser
        fields = ['id',
                  'isAdmin',
                  'token']

    def get_token(self, obj):
        token = RefreshToken.for_user(obj)
        return str(token.access_token)

and the problematic function is

@api_view(['PUT'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']
    user = CustomUser.objects.get(email=email)
    serializer = UserSerializerWithToken(user, many=False)
    if CustomUser.objects.filter(email=email).exists():
        if otp_to_verify == user.otp:
            if new_password != '':
                user.set_password(new_password)
                user.save() # here password gets changed
                return Response(serializer.data) #
            else:
                message = {
                'detail': 'Password cant be empty'}
                return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

I receive the toke but not getting access and refresh toke to use it to login next time. I'm assuming user.save() dosnt create refresh and access token here. Can anybody identify why this is happening and how to fix that

Body:
user.save() does not create the tokens

token = RefreshToken.for_user(obj)
return str(token.access_token)

These lines create the token.

In my opinion, you dont need the serializer here.

@api_view(['PUT'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']
    user = CustomUser.objects.get(email=email)
    if CustomUser.objects.filter(email=email).exists():
        otp_to_verify == user.otp
        if new_password != '':
            user.set_password(new_password)
            user.save() # here password gets changed
            token = RefreshToken.for_user(user)
            response = { "refresh_token": str(token),
                         "access_token": str(token.access_token)
                       }
            return Response(response)
        else:
            message = {
                'detail': 'Password cant be empty'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)


问:
Calico Global Network Policy and ip table rules
I am trying to understand how do Calico Global Network Policies work "under the hood". Let's say I have lots of (namespaced) network policies. For example, the same policy deployed to lots of namespaces. Common example might be to block or allow specific traffic in all namespaces. And let's say in this example, these are specialized workloads all deployed to a single node. If I replace these large number of (namespaced) policies with a single global network policy, will it reduce the number of IP table rules configured on the node?</p>

答: I did some testing. Implementing a Calico Global network policy does result in reduced number of iptables rules on the host.</p>


问:
Unreal Engine 4 Android Armv7a Packaging Error
I am trying to package a project which contains support for Armv7a, but cannot successfully since its throwing me exceptions. I am able to package for arm64 successfully if I untick the option in package project window in Unreal Engine 4.27.2.

I have also been researching through the Internet, but simply cannot find a solution, they solutions presented were to disable exceptions all together using "-fno-exceptions" but that doesn't seem to work either.

The error is for building .so for armv7 is as follows:

```<code>`UATHelper: Packaging (Android (ETC2)):   PLATFORM_ANDROID_NDK_VERSION = 230100
UATHelper: Packaging (Android (ETC2)):   NDK toolchain: r23, NDK version: 31, GccVersion: 4.9, ClangVersion: 12.0.5
UATHelper: Packaging (Android (ETC2)):   Compiling Native 32-bit code with NDK API 'android-31'
UATHelper: Packaging (Android (ETC2)):   Compiling Native 64-bit code with NDK API 'android-31'
UATHelper: Packaging (Android (ETC2)):   Writing manifest to C:\Users\User1\Documents\Unreal Projects\Demo3AndroidCpp\Intermediate\Build\Manifest.xml
UATHelper: Packaging (Android (ETC2)):   Building Demo3AndroidCpp...
UATHelper: Packaging (Android (ETC2)):   Building 2 actions with 8 processes...
UATHelper: Packaging (Android (ETC2)):     [1/2] Demo3AndroidCpp-armv7.so
UATHelper: Packaging (Android (ETC2)):     ld.lld: error: undefined symbol: __aeabi_unwind_cpp_pr1
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager11GetInstanceEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager15DequeueAppEventEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager17ReleaseMicrophoneEb+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced 161000 more times
UATHelper: Packaging (Android (ETC2)):
UATHelper: Packaging (Android (ETC2)):     ld.lld: error: undefined symbol: __aeabi_unwind_cpp_pr0
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager4TickEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZZN16FAppEventManager4TickEvEN4Impl21ExecCheckImplInternalEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager17ExecWindowResizedEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced 369570 more times
UATHelper: Packaging (Android (ETC2)):     clang++: error: linker command failed with exit code 1 (use -v to see invocation)
PackagingResults: Error: undefined symbol: __aeabi_unwind_cpp_pr1
PackagingResults: Error: undefined symbol: __aeabi_unwind_cpp_pr0
PackagingResults: Error: linker command failed with exit code 1 (use -v to see invocation)
UATHelper: Packaging (Android (ETC2)): Took 32.2903757s to run UnrealBuildTool.exe, ExitCode=6
UATHelper: Packaging (Android (ETC2)): UnrealBuildTool failed. See log for more details. (C:\Users\User1\AppData\Roaming\Unreal Engine\AutomationTool\Logs\C+Program+Files+Epic+Games+UE_4.27\UBT-Demo3AndroidCpp-Android-Development.txt)
UATHelper: Packaging (Android (ETC2)): AutomationTool exiting with ExitCode=6 (6)
UATHelper: Packaging (Android (ETC2)): BUILD FAILED
PackagingResults: Error: Unknown Error`
</code>```

I can currently only support a limited number of devices because of arm32 package error.

答:
The correct solution to this is proper compatibility according to UE4 Documentation.

UE Engine v4.27.2 supports NDK v21.4e where I earlier tried to use v23.0.
After downloading and changing to v21.4e I was able to successfully compile for armv7a devices.

Body:
I am trying to package a project which contains support for Armv7a, but cannot successfully since its throwing me exceptions. I am able to package for arm64 successfully if I untick the option in package project window in Unreal Engine 4.27.2.

I have also been researching through the Internet, but simply cannot find a solution, they solutions presented were to disable exceptions all together using "-fno-exceptions" but that doesn't seem to work either.

The error is for building .so for armv7 is as follows:

`UATHelper: Packaging (Android (ETC2)):   PLATFORM_ANDROID_NDK_VERSION = 230100
UATHelper: Packaging (Android (ETC2)):   NDK toolchain: r23, NDK version: 31, GccVersion: 4.9, ClangVersion: 12.0.5
UATHelper: Packaging (Android (ETC2)):   Compiling Native 32-bit code with NDK API 'android-31'
UATHelper: Packaging (Android (ETC2)):   Compiling Native 64-bit code with NDK API 'android-31'
UATHelper: Packaging (Android (ETC2)):   Writing manifest to C:\Users\User1\Documents\Unreal Projects\Demo3AndroidCpp\Intermediate\Build\Manifest.xml
UATHelper: Packaging (Android (ETC2)):   Building Demo3AndroidCpp...
UATHelper: Packaging (Android (ETC2)):   Building 2 actions with 8 processes...
UATHelper: Packaging (Android (ETC2)):     [1/2] Demo3AndroidCpp-armv7.so
UATHelper: Packaging (Android (ETC2)):     ld.lld: error: undefined symbol: __aeabi_unwind_cpp_pr1
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager11GetInstanceEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager15DequeueAppEventEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager17ReleaseMicrophoneEb+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced 161000 more times
UATHelper: Packaging (Android (ETC2)):
UATHelper: Packaging (Android (ETC2)):     ld.lld: error: undefined symbol: __aeabi_unwind_cpp_pr0
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager4TickEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZZN16FAppEventManager4TickEvEN4Impl21ExecCheckImplInternalEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced by Module.Launch.cpp
UATHelper: Packaging (Android (ETC2)):     >>>               C:/Program Files/Epic Games/UE_4.27/Engine/Intermediate/Build/Android/UE4/Development/Launch/Module.Launch.cppa7.o:(.ARM.exidx.text._ZN16FAppEventManager17ExecWindowResizedEv+0x0)
UATHelper: Packaging (Android (ETC2)):     >>> referenced 369570 more times
UATHelper: Packaging (Android (ETC2)):     clang++: error: linker command failed with exit code 1 (use -v to see invocation)
PackagingResults: Error: undefined symbol: __aeabi_unwind_cpp_pr1
PackagingResults: Error: undefined symbol: __aeabi_unwind_cpp_pr0
PackagingResults: Error: linker command failed with exit code 1 (use -v to see invocation)
UATHelper: Packaging (Android (ETC2)): Took 32.2903757s to run UnrealBuildTool.exe, ExitCode=6
UATHelper: Packaging (Android (ETC2)): UnrealBuildTool failed. See log for more details. (C:\Users\User1\AppData\Roaming\Unreal Engine\AutomationTool\Logs\C+Program+Files+Epic+Games+UE_4.27\UBT-Demo3AndroidCpp-Android-Development.txt)
UATHelper: Packaging (Android (ETC2)): AutomationTool exiting with ExitCode=6 (6)
UATHelper: Packaging (Android (ETC2)): BUILD FAILED
PackagingResults: Error: Unknown Error`

I can currently only support a limited number of devices because of arm32 package error.


问:
Finding all the elements of the deepest list within a list in python without NUMPY
I am trying to code to retrieve all the list which is the "deepest" within a list. I managed to retrieve only one of the list which is the deepest and I am unable to print out all if they have the same "depth". I tried hardcoding it by it will not work if there is 2 or more values of the same depth. Can anyone share how can I modify my code to make it work?

Input: [1,2,[[3]],[[4]],[[5]], [6]]

Output: [3],[4],[5]

```<code>def get_deepest(L):
    def get_dpst(L, maxdepth):
        deepest_list = [L, maxdepth]
        for e in L:
            is_list = isinstance(e,list)
            if is_list:
                rList = get_dpst(e, maxdepth+1)
                if rList[1] > deepest_list[1]:
                    deepest_list = rList
                elif rList [1] == deepest_list[1]:
                    deepest_list[1] = rList[0]
        return deepest_list
    rList = get_dpst(L, 0)
    return rList[0]

print (get_deepest(my_list))
</code>```

答:
How about a pair of functions like this?

unnest is a recursive function that walks a tree of lists, yielding tuples of any non-list value and its depth

get_deepest_values uses unnest and keeps track of the deepest depth it has returned, gathering only those values.

```<code>def unnest(lst, depth=0):
    for atom in lst:
        if isinstance(atom, list):
            yield from unnest(atom, depth + 1)
        else:
            yield (atom, depth)

def get_deepest_values(inp):
    deepest_depth = 0
    deepest_depth_values = []
    for value, depth in unnest(inp):
        if depth > deepest_depth:
            deepest_depth = depth
            deepest_depth_values.clear()
        if depth == deepest_depth:
            deepest_depth_values.append(value)
    return (deepest_depth, deepest_depth_values)

inp = [1, 2, [[3]], [[4]], [[5, "foo"]], [6]]
deepest_depth, deepest_values = get_deepest_values(inp)
print(f"{deepest_depth=} {deepest_values=}")

</code>```

The output is

```<code>deepest_depth=2 deepest_values=[3, 4, 5, 'foo']

</code>```

Body:
I am trying to code to retrieve all the list which is the "deepest" within a list. I managed to retrieve only one of the list which is the deepest and I am unable to print out all if they have the same "depth". I tried hardcoding it by it will not work if there is 2 or more values of the same depth. Can anyone share how can I modify my code to make it work?

Input: [1,2,[[3]],[[4]],[[5]], [6]]

Output: [3],[4],[5]

def get_deepest(L):
    def get_dpst(L, maxdepth):
        deepest_list = [L, maxdepth]
        for e in L:
            is_list = isinstance(e,list)
            if is_list:
                rList = get_dpst(e, maxdepth+1)
                if rList[1] > deepest_list[1]:
                    deepest_list = rList
                elif rList [1] == deepest_list[1]:
                    deepest_list[1] = rList[0]
        return deepest_list
    rList = get_dpst(L, 0)
    return rList[0]

print (get_deepest(my_list))

Body:
How about a pair of functions like this?

unnest is a recursive function that walks a tree of lists, yielding tuples of any non-list value and its depth

get_deepest_values uses unnest and keeps track of the deepest depth it has returned, gathering only those values.

def unnest(lst, depth=0):
    for atom in lst:
        if isinstance(atom, list):
            yield from unnest(atom, depth + 1)
        else:
            yield (atom, depth)

def get_deepest_values(inp):
    deepest_depth = 0
    deepest_depth_values = []
    for value, depth in unnest(inp):
        if depth > deepest_depth:
            deepest_depth = depth
            deepest_depth_values.clear()
        if depth == deepest_depth:
            deepest_depth_values.append(value)
    return (deepest_depth, deepest_depth_values)

inp = [1, 2, [[3]], [[4]], [[5, "foo"]], [6]]
deepest_depth, deepest_values = get_deepest_values(inp)
print(f"{deepest_depth=} {deepest_values=}")

The output is

deepest_depth=2 deepest_values=[3, 4, 5, 'foo']


问:
Change Date Format in PHP HTML form results
I'm just starting to learn php and I've tried to research an answer to this but I can't find an answer that fits my situation.  Remember, I'm a noob so please explain in detail.

Webpage where results are shown: https://fireytech.com/FireytechDatabase/hello.php

I have a php select query that pulls a field from my mysql database where a date / timestamp is saved.  When I get the echo results of the query in my html form, it displays this date field in this format: 2022-01-31 00:00:00.  I would like it to show as: 01/31/2022 (no time).  Below is my form's code.  How would I change date format for my "DateReceived" and "DateLastEdited" fields?

```<code><?php

require '../../db_php/dbconnection.php';

$sql = "SELECT * FROM
            Tickets
        Left JOIN
            Clients
        ON Tickets.CustomerNumber=Clients.CustomerNumber
        JOIN Contacts
        ON Contacts.ContactID=Clients.CustomerNumber
        JOIN Equipment
        ON Equipment.ContactID=Clients.CustomerNumber

        WHERE Equipment.PRINT = '-1' AND Contacts.DispatchContact = '-1' AND TicketStatus = 'Active' AND NOT TicketSubStatus = 'CUSTOMER PICKUP' AND NOT TaskSubType = 'ON-SITE'
";
$result = $conn->query($sql);

echo"<table border='1'>";
echo "<tr><td>Ticket Type</td><td>Ticket Number</td><td>Date Received</td><td>Last Edited</td><td>Last Name</td><td>Followup By</td><td>Sub Status</td><td>Repair Type</td><tr>";
if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
    echo "<tr><td>{$row['TaskSubType']}</td><td>{$row['TicketNumber']}</td><td>{$row['DateReceived']}</td><td>{$row['DateLastEdited']}</td><td>{$row['ContactLast']}</td><td>{$row['FollowupBy']}</td><td>{$row['TicketSubStatus']}</td><td>{$row['ItemType']}</td></tr>";
}
} else {
    echo "0 records";
}

echo"</table>";

$conn->close();

?>
</code>```

Body:
I'm just starting to learn php and I've tried to research an answer to this but I can't find an answer that fits my situation.  Remember, I'm a noob so please explain in detail.

Webpage where results are shown: https://fireytech.com/FireytechDatabase/hello.php

I have a php select query that pulls a field from my mysql database where a date / timestamp is saved.  When I get the echo results of the query in my html form, it displays this date field in this format: 2022-01-31 00:00:00.  I would like it to show as: 01/31/2022 (no time).  Below is my form's code.  How would I change date format for my "DateReceived" and "DateLastEdited" fields?

<?php

require '../../db_php/dbconnection.php';

$sql = "SELECT * FROM
            Tickets
        Left JOIN
            Clients
        ON Tickets.CustomerNumber=Clients.CustomerNumber
        JOIN Contacts
        ON Contacts.ContactID=Clients.CustomerNumber
        JOIN Equipment
        ON Equipment.ContactID=Clients.CustomerNumber

        WHERE Equipment.PRINT = '-1' AND Contacts.DispatchContact = '-1' AND TicketStatus = 'Active' AND NOT TicketSubStatus = 'CUSTOMER PICKUP' AND NOT TaskSubType = 'ON-SITE'
";
$result = $conn->query($sql);

echo"
";
echo "
Ticket Type	Ticket Number	Date Received	Last Edited	Last Name	Followup By	Sub Status	Repair Type
";
if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
    echo "
{$row['TaskSubType']}	{$row['TicketNumber']}	{$row['DateReceived']}	{$row['DateLastEdited']}	{$row['ContactLast']}	{$row['FollowupBy']}	{$row['TicketSubStatus']}	{$row['ItemType']}
";
}
} else {
    echo "0 records";
}

echo"
";

$conn->close();

?>

Body: echo date_format(date_create($date),"Y-m-d");


问:
How to add an unescaped closure Swift Firebase
When I compile I get this error "The path to the document cannot be empty".

To fix this, I should add an unescaped closure.
How to add an unescaped closure to the fetchUsers () function and call the GetCorsodiLaurea () function in the closure? In such a way, the compiler will not try to execute functions asynchronously.

LoginViewModel

```<code>import SwiftUI
import Firebase
import LocalAuthentication

class LoginViewModel: ObservableObject {
@Published var email: String = ""
@Published var password: String = ""

@AppStorage("use_face_id") var useFaceID: Bool = false
@AppStorage("use_face_email") var faceIDEmail: String = ""
@AppStorage("use_face_password") var faceIDPassword: String = ""

//Log Status

@AppStorage("log_status") var logStatus: Bool = false

//MARK: Error
@Published var showError: Bool = false
@Published var errorMsg: String = ""

// MARK: Firebase Login
func loginUser(useFaceID: Bool,email: String = "",password: String = "")async throws{

    let _ = try await Auth.auth().signIn(withEmail: email != "" ? email : self.email, password: password != "" ? password : self.password)
    DispatchQueue.main.async {
        if useFaceID && self.faceIDEmail == ""{
            self.useFaceID = useFaceID
            // MARK: Storing for future face ID Login
            self.faceIDEmail = self.email
            self.faceIDPassword = self.password
        }

        self.logStatus = true

    }
    }

//MARK: FaceID Usage
func getBioMetricStatus()->Bool{

    let scanner = LAContext()

    return scanner.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: .none)

}

// MARK: FaceID Login
func autenticationUser()async throws{

    let status = try await LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "To Login Into App")

    if status{
        try await loginUser(useFaceID: useFaceID,email: self.faceIDEmail,password: self.faceIDPassword)
    }

}

}
</code>```

ProfileViewModel

```<code>import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift
import SwiftUI

class ProfileViewModel: ObservableObject {
@Published var userInfo: UserModel = .empty
@Published var userDegree: userDegreeModel = .empty
@Published var isSignedIn = false
@Published var showError: Bool = false
@Published var errorMsg: String = ""

var uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()

 init() {
// listen for auth state change and set isSignedIn property accordingly
Auth.auth().addStateDidChangeListener { auth, user in
  if let user = user {
    print("Signed in as user \(user.uid).")
    self.uid = user.uid
    self.isSignedIn = true
  }
  else {
    self.isSignedIn = false
    self.userInfo.Nomeintero = ""
  }
}

  fetchUser() { [self] in
    fetchDegrees()
}
}

func fetchUser(completion: @escaping () -> Void) {
let docRef = db.collection("users").document(uid)

docRef.getDocument { document, error in
  if let error = error as NSError? {
    self.errorMsg = "Error getting document: \(error.localizedDescription)"
  }
  else {
    if let document = document {
      do {
          self.userInfo = try document.data(as: UserModel.self)!
          completion()
      }
      catch {
        print(error)
      }
    }
  }
}
}

func fetchDegrees() {
  let docRef = db.collection("DegreeCourses").document(userInfo.Tipocorso)

docRef.getDocument { document, error in
  if let error = error as NSError? {
    self.errorMsg = "Error getting document: \(error.localizedDescription)"
  }
  else {
    if let document = document {
      do {
          self.userDegree = try document.data(as: userDegreeModel.self)!

      }
      catch {
        print(error)
      }
    }
  }
}
}

}
</code>```

UserModel

```<code>import SwiftUI
import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift

public struct UserModel: Codable{
@DocumentID var id: String?
var Nome : String
var Cognome : String
var photoURL : String
var Nomeintero : String
var Corsodilaurea : String
var Tipocorso : String
 }

extension UserModel {
static let empty = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
}
</code>```

userDegreeModel

```<code>import SwiftUI
import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift

struct userDegreeModel: Codable {
@DocumentID var id: String?
var Name : String
var TotalSubjects : Int
}

extension userDegreeModel {
static let empty = userDegreeModel(Name: "", TotalSubjects: 0)
}
</code>```

Error

答:
A couple of notes:

Firestore calls return on the main dispatch queue already about this), so you don't need to manually switch to the main queue using DispatchQueue.async { }. See my Twitter thread for more details.

Instead of mapping Firestore documents manually, you can use Codable to do so. This means less code to write, and fewer typos :-) Here is an article that goes into much more detail: Mapping Firestore Data in Swift - The Comprehensive Guide | Peter Friese

Accessing the signed in user using Auth.auth().currentUser!.uid might result in you app breaking if no user is signed in. I recommend implementing an authentication state listener instead.

Since all of Firebase's APIs are asynchronous (see my blog post about this: Calling asynchronous Firebase APIs from Swift - Callbacks, Combine, and async/await | Peter Friese), the result of fetchUser will take a short moment, so you want to make sure to only call fetchDegrees once that call has completed. One way to do this is to use a completion handler.

Lastly, I recommend following a styleguide like this one for naming your classes and attribute: Swift Style Guide

I've updated your code accordingly below.

import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift
import SwiftUI

public struct UserModel: Codable {
  @DocumentID var id: String?
  var firstName: String
  var lastName: String
  var photoUrl: String
  // ...
}

extension UserModel {
  static let empty = UserModel(firstName: "", lastName: "", photoUrl: "")
}

public struct UserDegreeModel: Codable {
  @DocumentID var id: String?
  var name: String
  var totalSubjects: Int
  // ...
}

extension UserDegreeModel {
  static let empty = UserDegreeModel(name: "", totalSubjects: 0)
}

class ProfileViewModel: ObservableObject {
  @Published var userInfo: UserModel = .empty
  @Published var userDegree: UserDegreeModel = .empty
  @Published var isSignedIn = false

  let uid = Auth.auth().currentUser!.uid
  let db = Firestore.firestore()

  init() {
    // listen for auth state change and set isSignedIn property accordingly
    Auth.auth().addStateDidChangeListener { auth, user in
      if let user = user {
        print("Signed in as user \(user.uid).")
        self.uid = user.uid
        self.isSignedIn = true
      }
      else {
        self.isSignedIn = false
        self.username = ""
      }
    }

    fetchUser() {
      fetchDegrees()
    }
  }

  func fetchUser(completion: () -> Void) {
    let docRef = db.collection("users").document(uid)

    docRef.getDocument { document, error in
      if let error = error as NSError? {
        self.errorMessage = "Error getting document: \(error.localizedDescription)"
      }
      else {
        if let document = document {
          do {
            self.user = try document.data(as: UserModel.self)
            completion()
          }
          catch {
            print(error)
          }
        }
      }
    }
  }

  func fetchDegrees() {
    let docRef = db.collection("DegreeCourses").document(userInfo.Tipocorso)

    docRef.getDocument { document, error in
      if let error = error as NSError? {
        self.errorMessage = "Error getting document: \(error.localizedDescription)"
      }
      else {
        if let document = document {
          do {
            self.userDegree = try document.data(as: UserDegreeModel.self)
          }
          catch {
            print(error)
          }
        }
      }
    }
  }

}
```

Body:
When I compile I get this error "The path to the document cannot be empty".

To fix this, I should add an unescaped closure.
How to add an unescaped closure to the fetchUsers () function and call the GetCorsodiLaurea () function in the closure? In such a way, the compiler will not try to execute functions asynchronously.

LoginViewModel

import SwiftUI
import Firebase
import LocalAuthentication

class LoginViewModel: ObservableObject {
@Published var email: String = ""
@Published var password: String = ""

@AppStorage("use_face_id") var useFaceID: Bool = false
@AppStorage("use_face_email") var faceIDEmail: String = ""
@AppStorage("use_face_password") var faceIDPassword: String = ""

//Log Status

@AppStorage("log_status") var logStatus: Bool = false

//MARK: Error
@Published var showError: Bool = false
@Published var errorMsg: String = ""

// MARK: Firebase Login
func loginUser(useFaceID: Bool,email: String = "",password: String = "")async throws{

    let _ = try await Auth.auth().signIn(withEmail: email != "" ? email : self.email, password: password != "" ? password : self.password)
    DispatchQueue.main.async {
        if useFaceID && self.faceIDEmail == ""{
            self.useFaceID = useFaceID
            // MARK: Storing for future face ID Login
            self.faceIDEmail = self.email
            self.faceIDPassword = self.password
        }

        self.logStatus = true

    }
    }

//MARK: FaceID Usage
func getBioMetricStatus()->Bool{

    let scanner = LAContext()

    return scanner.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: .none)

}

// MARK: FaceID Login
func autenticationUser()async throws{

    let status = try await LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "To Login Into App")

    if status{
        try await loginUser(useFaceID: useFaceID,email: self.faceIDEmail,password: self.faceIDPassword)
    }

}

}

ProfileViewModel

import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift
import SwiftUI

class ProfileViewModel: ObservableObject {
@Published var userInfo: UserModel = .empty
@Published var userDegree: userDegreeModel = .empty
@Published var isSignedIn = false
@Published var showError: Bool = false
@Published var errorMsg: String = ""

var uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()

 init() {
// listen for auth state change and set isSignedIn property accordingly
Auth.auth().addStateDidChangeListener { auth, user in
  if let user = user {
    print("Signed in as user \(user.uid).")
    self.uid = user.uid
    self.isSignedIn = true
  }
  else {
    self.isSignedIn = false
    self.userInfo.Nomeintero = ""
  }
}

  fetchUser() { [self] in
    fetchDegrees()
}
}

func fetchUser(completion: @escaping () -> Void) {
let docRef = db.collection("users").document(uid)

docRef.getDocument { document, error in
  if let error = error as NSError? {
    self.errorMsg = "Error getting document: \(error.localizedDescription)"
  }
  else {
    if let document = document {
      do {
          self.userInfo = try document.data(as: UserModel.self)!
          completion()
      }
      catch {
        print(error)
      }
    }
  }
}
}

func fetchDegrees() {
  let docRef = db.collection("DegreeCourses").document(userInfo.Tipocorso)

docRef.getDocument { document, error in
  if let error = error as NSError? {
    self.errorMsg = "Error getting document: \(error.localizedDescription)"
  }
  else {
    if let document = document {
      do {
          self.userDegree = try document.data(as: userDegreeModel.self)!

      }
      catch {
        print(error)
      }
    }
  }
}
}

}

UserModel

import SwiftUI
import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift

public struct UserModel: Codable{
@DocumentID var id: String?
var Nome : String
var Cognome : String
var photoURL : String
var Nomeintero : String
var Corsodilaurea : String
var Tipocorso : String
 }

extension UserModel {
static let empty = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
}

userDegreeModel

import SwiftUI
import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift

struct userDegreeModel: Codable {
@DocumentID var id: String?
var Name : String
var TotalSubjects : Int
}

extension userDegreeModel {
static let empty = userDegreeModel(Name: "", TotalSubjects: 0)
}

Error


问:
How to handing Espresso idling Resources in Jetpack compose....?
I am writing ui testcases using junit and Espresso in jetpack compose. My Screen consist of Lottie animations and Some Piece of code of Kotlin Courtines.I am writing single test case to check the visibility of button in that screen but it is giving me error that compse Espresso become idle time out.Can any body show some example that how to handle Incrementation and decrementation using espresso in jetpack compose or anyother way to handle this condition....</p>

答:
So if you are initializing a composeTestRule like this for example:

```<code>@get:Rule
val composeTestRule = createEmptyComposeRule()
</code>```

Then it will suspend until idle when you have composables that are pending layouts, measuring or in some sort of infinite recomposition loop.

Since Compose 1.1, I have noticed that if I have a composable that is composed but not shown on the screen (for example, in an invisible child fragment that has been started), the test will timeout due to the compose idling resource. So my solution was to simply not define a composeTestRule in my test unless the test will be interacting with a visible composable.

If you are interacting directly with the composable, then you can try the following:

```<code>composeTestRule.mainClock.autoAdvance = true
</code>```

Also, perhaps your Lottie animation is causing some sort of infinite recomposition. Try the test without the Lottie animating. You can also try using this to disable animations in your apps build.gradle file:

```<code>testOptions {
    ...
    animationsDisabled = true
    ...
}
</code>```

If all this still fails, try putting a log in your composable to check if it is recomposing non stop when it shouldn't be, then figure out why it is happening.

Edit: One more thing, you can register your own idling resource for compose (and figure out how that works) using composeTestRule.registerIdlingResource(idlingResource -> compose specific idling resource.)

Body:
So if you are initializing a composeTestRule like this for example:

@get:Rule
val composeTestRule = createEmptyComposeRule()

Then it will suspend until idle when you have composables that are pending layouts, measuring or in some sort of infinite recomposition loop.

Since Compose 1.1, I have noticed that if I have a composable that is composed but not shown on the screen (for example, in an invisible child fragment that has been started), the test will timeout due to the compose idling resource. So my solution was to simply not define a composeTestRule in my test unless the test will be interacting with a visible composable.

If you are interacting directly with the composable, then you can try the following:

composeTestRule.mainClock.autoAdvance = true

Also, perhaps your Lottie animation is causing some sort of infinite recomposition. Try the test without the Lottie animating. You can also try using this to disable animations in your apps build.gradle file:

testOptions {
    ...
    animationsDisabled = true
    ...
}

If all this still fails, try putting a log in your composable to check if it is recomposing non stop when it shouldn't be, then figure out why it is happening.

Edit: One more thing, you can register your own idling resource for compose (and figure out how that works) using composeTestRule.registerIdlingResource(idlingResource -> compose specific idling resource.)


问:
Resolve overfitting in a convolutional network
I've written a snippet to classify Omniglot images. I calculate the training and validation losses in each epoch, where the latter is computed using images that were not seen by the network before. The two plots are as below:

Since the training loss decreases while the validation loss increases, I have concluded that my model overfits. I've tried several suggestions (e.g. here) to overcome this, including:

Increasing the size of the training set.

shuffling the data.

Adding dropout layers (up to p=0.9).

Using smaller model.

Altering the architecture.

Changing the learning rate.

Reducing the batch size.

Adding weight decay.

However, the validation loss still increases. I wonder if there are any other suggestions to improve this behavior or if this is not overfitting, but the problem is something else. Below is the snippet used in this question.

```<code>import torch
import torchvision
import torchvision.transforms as transforms

from torch import nn, optim
from torch.utils.data import DataLoader

class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()

        dim_out = 964

        # -- embedding params
        self.cn1 = nn.Conv2d(1, 16, 7)
        self.cn2 = nn.Conv2d(16, 32, 4)
        self.cn3 = nn.Conv2d(32, 64, 3)
        self.pool = nn.MaxPool2d(2)

        self.bn1 = nn.BatchNorm2d(16)
        self.bn2 = nn.BatchNorm2d(32)
        self.bn3 = nn.BatchNorm2d(64)

        # -- prediction params
        self.fc1 = nn.Linear(256, 170)
        self.fc2 = nn.Linear(170, 50)
        self.fc3 = nn.Linear(50, dim_out)

        # -- non-linearity
        self.relu = nn.ReLU()
        self.Beta = 10
        self.sopl = nn.Softplus(beta=self.Beta)

    def forward(self, x):

        y1 = self.pool(self.bn1(self.relu(self.cn1(x))))
        y2 = self.pool(self.bn2(self.relu(self.cn2(y1))))
        y3 = self.relu(self.bn3(self.cn3(y2)))

        y3 = y3.view(y3.size(0), -1)

        y5 = self.sopl(self.fc1(y3))
        y6 = self.sopl(self.fc2(y5))

        return self.fc3(y6)

class Train:
    def __init__(self):

        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

        # -- data
        dim = 28
        batch_size = 400
        my_transforms = transforms.Compose([transforms.Resize((dim, dim)), transforms.ToTensor()])
        trainset = torchvision.datasets.Omniglot(root="./data/omniglot_train/", download=False, transform=my_transforms)
        validset = torchvision.datasets.Omniglot(root="./data/omniglot_train/", background=False, download=False,
                                                     transform=my_transforms)
        self.TrainDataset = DataLoader(dataset=trainset, batch_size=batch_size, shuffle=True)
        self.ValidDataset = DataLoader(dataset=validset, batch_size=len(validset), shuffle=False)
        self.N_train = len(trainset)
        self.N_valid = len(validset)

        # -- model
        self.model = MyModel().to(self.device)

        # -- train
        self.epochs = 3000
        self.loss = nn.CrossEntropyLoss()
        self.optimizer = optim.Adam(self.model.parameters(), lr=1e-3)

    def train_epoch(self):

        self.model.train()
        train_loss = 0
        for batch_idx, data_batch in enumerate(self.TrainDataset):
            # -- predict
            predict = self.model(data_batch[0].to(self.device))

            # -- loss
            loss = self.loss(predict, data_batch[1].to(self.device))

            # -- optimize
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()
            train_loss += loss.item()

        return train_loss/(batch_idx+1)

    def valid_epoch(self):

        with torch.no_grad():
            self.model.eval()
            for data_batch in self.ValidDataset:
                # -- predict
                predict = self.model(data_batch[0].to(self.device))

                # -- loss
                loss = self.loss(predict, data_batch[1].to(self.device))

        return loss.item()

    def __call__(self):

        for epoch in range(self.epochs):
            train_loss = self.train_epoch()
            valid_loss = self.valid_epoch()

            print('Epoch {}: Training loss = {:.5f}, Validation loss = {:.5f}.'.format(epoch, train_loss, valid_loss))

        torch.save(self.model.state_dict(), './model_stat.pth')

if __name__ == '__main__':
    my_train = Train()
    my_train()
</code>```

答:
If your train accuracy is good but testing (data not used in training) accuracy is bad then you have an overfitting problem. I had the same problem with a CNN model. You can use two methods to overcome overfitting. First is early stopping for your train and second is regularization. Check the below example:

```<code># L2 regularizers for layers
model = keras.Sequential([
    keras.layers.InputLayer(input_shape=(32, 32)),
    keras.layers.Reshape(target_shape=(32, 32, 1)),
    keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu,  use_bias=True , kernel_regularizer =tf.keras.regularizers.l2( l=0.01)),
    keras.layers.MaxPooling2D(pool_size=(2, 2)),
    keras.layers.Flatten(),
    keras.layers.Dense(10, activation = 'softmax', use_bias=True)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(),
              metrics=['accuracy'])
#Early Stopping
history = model.fit(X_train, Y_train,
                            validation_data=(X_dev, Y_dev),
                            epochs=4000,
                            callbacks=EarlyStopping(monitor='val_loss'))
</code>```

Do not forget to import for early stopping.

```<code>from tensorflow.keras.callbacks import EarlyStopping
</code>```

Body:
I've written a snippet to classify Omniglot images. I calculate the training and validation losses in each epoch, where the latter is computed using images that were not seen by the network before. The two plots are as below:

Since the training loss decreases while the validation loss increases, I have concluded that my model overfits. I've tried several suggestions (e.g. here) to overcome this, including:

Increasing the size of the training set.

shuffling the data.

Adding dropout layers (up to p=0.9).

Using smaller model.

Altering the architecture.

Changing the learning rate.

Reducing the batch size.

Adding weight decay.

However, the validation loss still increases. I wonder if there are any other suggestions to improve this behavior or if this is not overfitting, but the problem is something else. Below is the snippet used in this question.

import torch
import torchvision
import torchvision.transforms as transforms

from torch import nn, optim
from torch.utils.data import DataLoader

class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()

        dim_out = 964

        # -- embedding params
        self.cn1 = nn.Conv2d(1, 16, 7)
        self.cn2 = nn.Conv2d(16, 32, 4)
        self.cn3 = nn.Conv2d(32, 64, 3)
        self.pool = nn.MaxPool2d(2)

        self.bn1 = nn.BatchNorm2d(16)
        self.bn2 = nn.BatchNorm2d(32)
        self.bn3 = nn.BatchNorm2d(64)

        # -- prediction params
        self.fc1 = nn.Linear(256, 170)
        self.fc2 = nn.Linear(170, 50)
        self.fc3 = nn.Linear(50, dim_out)

        # -- non-linearity
        self.relu = nn.ReLU()
        self.Beta = 10
        self.sopl = nn.Softplus(beta=self.Beta)

    def forward(self, x):

        y1 = self.pool(self.bn1(self.relu(self.cn1(x))))
        y2 = self.pool(self.bn2(self.relu(self.cn2(y1))))
        y3 = self.relu(self.bn3(self.cn3(y2)))

        y3 = y3.view(y3.size(0), -1)

        y5 = self.sopl(self.fc1(y3))
        y6 = self.sopl(self.fc2(y5))

        return self.fc3(y6)

class Train:
    def __init__(self):

        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

        # -- data
        dim = 28
        batch_size = 400
        my_transforms = transforms.Compose([transforms.Resize((dim, dim)), transforms.ToTensor()])
        trainset = torchvision.datasets.Omniglot(root="./data/omniglot_train/", download=False, transform=my_transforms)
        validset = torchvision.datasets.Omniglot(root="./data/omniglot_train/", background=False, download=False,
                                                     transform=my_transforms)
        self.TrainDataset = DataLoader(dataset=trainset, batch_size=batch_size, shuffle=True)
        self.ValidDataset = DataLoader(dataset=validset, batch_size=len(validset), shuffle=False)
        self.N_train = len(trainset)
        self.N_valid = len(validset)

        # -- model
        self.model = MyModel().to(self.device)

        # -- train
        self.epochs = 3000
        self.loss = nn.CrossEntropyLoss()
        self.optimizer = optim.Adam(self.model.parameters(), lr=1e-3)

    def train_epoch(self):

        self.model.train()
        train_loss = 0
        for batch_idx, data_batch in enumerate(self.TrainDataset):
            # -- predict
            predict = self.model(data_batch[0].to(self.device))

            # -- loss
            loss = self.loss(predict, data_batch[1].to(self.device))

            # -- optimize
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()
            train_loss += loss.item()

        return train_loss/(batch_idx+1)

    def valid_epoch(self):

        with torch.no_grad():
            self.model.eval()
            for data_batch in self.ValidDataset:
                # -- predict
                predict = self.model(data_batch[0].to(self.device))

                # -- loss
                loss = self.loss(predict, data_batch[1].to(self.device))

        return loss.item()

    def __call__(self):

        for epoch in range(self.epochs):
            train_loss = self.train_epoch()
            valid_loss = self.valid_epoch()

            print('Epoch {}: Training loss = {:.5f}, Validation loss = {:.5f}.'.format(epoch, train_loss, valid_loss))

        torch.save(self.model.state_dict(), './model_stat.pth')

if __name__ == '__main__':
    my_train = Train()
    my_train()

Body:
If your train accuracy is good but testing (data not used in training) accuracy is bad then you have an overfitting problem. I had the same problem with a CNN model. You can use two methods to overcome overfitting. First is early stopping for your train and second is regularization. Check the below example:

# L2 regularizers for layers
model = keras.Sequential([
    keras.layers.InputLayer(input_shape=(32, 32)),
    keras.layers.Reshape(target_shape=(32, 32, 1)),
    keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu,  use_bias=True , kernel_regularizer =tf.keras.regularizers.l2( l=0.01)),
    keras.layers.MaxPooling2D(pool_size=(2, 2)),
    keras.layers.Flatten(),
    keras.layers.Dense(10, activation = 'softmax', use_bias=True)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(),
              metrics=['accuracy'])
#Early Stopping
history = model.fit(X_train, Y_train,
                            validation_data=(X_dev, Y_dev),
                            epochs=4000,
                            callbacks=EarlyStopping(monitor='val_loss'))

Do not forget to import for early stopping.

from tensorflow.keras.callbacks import EarlyStopping


问:
How to run a pulled images - docker
I'm trying to run a pulled image without any success.
I pulled an image from AWS using the Image URI.

when I run docker images I can see my pulled image:

```<code>REPOSITORY                                           TAG             IMAGE ID            CREATED             SIZE
alpine                                               3.9             055936d39205        3 weeks ago         5.53MB
24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools    dab-1.1.0slim   f994713b61cb        3 weeks ago         110MB
ubuntu                                               16.04           a3551444fc85        5 weeks ago         119MB
anapsix/alpine-java                                  8               745575fbfe52        3 months ago        126MB
</code>```

I'm new at dockers, but from what I understand after pulling no need to build it, just run it but when I tried to run it like so: docker run 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools I get the below message:

```<code>Unable to find image '24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools:latest' locally
docker: Error response from daemon: pull access denied for 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools, repository does not exist or may require 'docker login'.
</code>```

So I tried to build it like so: docker build -t 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools
and got the message:

```<code>"docker build" requires exactly 1 argument.
See 'docker build --help'.
</code>```

What is the problem?
How can I run a pulled image from AWS?

答:
You can use simple command</p>
```<code>docker run -d -p [PORT_ON_YOUR_BROWSER]:[PORT_ON_CONTAINER] <Image ID>

docker run -d -p 8080:80 <Image ID>

</code>```

Title: How to run a pulled images - docker

Body:
I'm trying to run a pulled image without any success.
I pulled an image from AWS using the Image URI.

when I run docker images I can see my pulled image:

REPOSITORY                                           TAG             IMAGE ID            CREATED             SIZE
alpine                                               3.9             055936d39205        3 weeks ago         5.53MB
24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools    dab-1.1.0slim   f994713b61cb        3 weeks ago         110MB
ubuntu                                               16.04           a3551444fc85        5 weeks ago         119MB
anapsix/alpine-java                                  8               745575fbfe52        3 months ago        126MB

I'm new at dockers, but from what I understand after pulling no need to build it, just run it but when I tried to run it like so: docker run 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools I get the below message:

Unable to find image '24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools:latest' locally
docker: Error response from daemon: pull access denied for 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools, repository does not exist or may require 'docker login'.

So I tried to build it like so: docker build -t 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools
and got the message:

"docker build" requires exactly 1 argument.
See 'docker build --help'.

What is the problem?
How can I run a pulled image from AWS?

Body:
You can use simple command

docker run -d -p [PORT_ON_YOUR_BROWSER]:[PORT_ON_CONTAINER] <Image ID>

docker run -d -p 8080:80 <Image ID>


问:
SQL Server LocalDB login/user cannot access .MDF file (when created with a different windows account)
Our application has been live for several years. It's an installed WPF desktop application used by our customers. So, there's only so much we can control about the administration of the computers it runs on.

The application has an underlying SQL Server LocalDB .MDF database that it uses. The application has just been using basic Windows Authentication to access this database. However, we've been running into issues where the application will crash because it randomly looses permission to access the database during runtime. Also occasionally, a customer's IT will [incorrectly] merge domains and hose Windows user account access to the .MDF files.

To address this, I'm trying to add an explicit database user that the application will connect with. The idea is that this would be Windows user account independent and would add a layer of protection against customer IT departments doing unexpected things.

Anyway, I implemented this and it all works fine. It's in Internal Testing now. However, a couple of our project engineers running the new Test version have sent me their .MDF databases for me to investigate unrelated issues, and our application crashes immediately when I run it with their database:

```<code>Cannot open database "C:\MURRAY\CONTROLPRO\DATA\DATABASE.MDF" requested by the login. The login failed.
Login failed for user 'murray'.
</code>```

Using Visual Studio to connect to the .MDF directly, I get this error:

If I connect to the default 'master' database using the 'murray' user, I can connect just fine; and I can query the 'master' database normally. So, the 'murrray' user allows me to access the database instance. But when then I try to access the .MDF database, I see this:

Now this is where it gets strange... If I log out and log back in using Windows Authentication, I can access the .MDF just fine. I can query the server and database principals and see the 'murray' user there.

In order to get our application to access the .MDF again, I have to kill the 'SQL Server Windows NT - 64 Bit' task in the Task Manager, drop the 'murray' user and recreate it using the original SQL. After that, everything works again.

```<code>DROP USER murray;
DROP LOGIN murray;

CREATE LOGIN murray WITH PASSWORD = '12345'; -- It's what idiots have on their luggage...
CREATE USER murray FOR LOGIN murray;
EXEC sp_addrolemember 'db_owner', 'murray';
</code>```

But this moots the entire point of having an explicit database user in the first place. If customer IT hoses the user's Windows user account, we're back to square one. And it makes customer support considerably harder.

Any thoughts on why an explicit database user will only work when using it with the same Windows user account that created it? Thanks!

答:
That's a automatic user-specific instance of LocalDb.  The current Windows user owns the LocalDb instance, should always connect using Windows Auth, and needs Windows NTFS access to the .MDF file.

Connect to the automatic instance
The easiest way to use LocalDB is to
connect to the automatic instance owned by the current user by using
the connection string Server=(localdb)\MSSQLLocalDB;Integrated
Security=true. To connect to a specific database by using the file
name, connect using a connection string similar to
Server=(LocalDB)\MSSQLLocalDB;Integrated
Security=true;AttachDbFileName=D:\Data\MyDB1.mdf.

LocalDb

If you want SQL Server to "own" the database and grant users access to it, use a "shared" LocalDb instance or a SQL Server Express Service install.

Body:
Our application has been live for several years. It's an installed WPF desktop application used by our customers. So, there's only so much we can control about the administration of the computers it runs on.

The application has an underlying SQL Server LocalDB .MDF database that it uses. The application has just been using basic Windows Authentication to access this database. However, we've been running into issues where the application will crash because it randomly looses permission to access the database during runtime. Also occasionally, a customer's IT will [incorrectly] merge domains and hose Windows user account access to the .MDF files.

To address this, I'm trying to add an explicit database user that the application will connect with. The idea is that this would be Windows user account independent and would add a layer of protection against customer IT departments doing unexpected things.

Anyway, I implemented this and it all works fine. It's in Internal Testing now. However, a couple of our project engineers running the new Test version have sent me their .MDF databases for me to investigate unrelated issues, and our application crashes immediately when I run it with their database:

Cannot open database "C:\MURRAY\CONTROLPRO\DATA\DATABASE.MDF" requested by the login. The login failed.
Login failed for user 'murray'.

Using Visual Studio to connect to the .MDF directly, I get this error:

If I connect to the default 'master' database using the 'murray' user, I can connect just fine; and I can query the 'master' database normally. So, the 'murrray' user allows me to access the database instance. But when then I try to access the .MDF database, I see this:

Now this is where it gets strange... If I log out and log back in using Windows Authentication, I can access the .MDF just fine. I can query the server and database principals and see the 'murray' user there.

In order to get our application to access the .MDF again, I have to kill the 'SQL Server Windows NT - 64 Bit' task in the Task Manager, drop the 'murray' user and recreate it using the original SQL. After that, everything works again.

DROP USER murray;
DROP LOGIN murray;

CREATE LOGIN murray WITH PASSWORD = '12345'; -- It's what idiots have on their luggage...
CREATE USER murray FOR LOGIN murray;
EXEC sp_addrolemember 'db_owner', 'murray';

But this moots the entire point of having an explicit database user in the first place. If customer IT hoses the user's Windows user account, we're back to square one. And it makes customer support considerably harder.

Any thoughts on why an explicit database user will only work when using it with the same Windows user account that created it? Thanks!


问:
How do OpenCV's selectROI coordinates work?
I need to use the selectROI function for my project. However, I just can't seem to wrap my head around the format of the coordinates. According to this link, the coordinate array should be in this form: [Top_X, Top_Y, Bottom_X, Bottom_Y]. Assuming that the top left corner starts at (0,0) for (x,y), why are my coordinates so off when I draw 3 different bounding boxes using the selectROI function?

This is what I used to create my bounding boxes and output the coordinates:

```<code>import cv2

image = cv2.imread("path")

# Select ROI
r = cv2.selectROI("select the area", image, fromCenter=False)

print('Selected bounding boxes: {}'.format(r))

</code>```

The following were outputted (see the image for reference of the boxes):

box 1: (42, 18, 212, 303)
box 2: (463, 314, 108, 226)
box 3: (1215, 801, 79, 161)
image

Why do the x-values increase from 42 -> 212 -> 464 -> back to 108 -> 1125 -> back to 79... shouldn't the coordinates for the x's be increasing? And same goes for the y.

答: The explanation on geeksforgeeks is wrong or at least easy to misunderstand: the last two values are not coordinates for the bottom-right corner, they are width and height of the rectangle. Notice that e.g. for the third rectangle, the height (161) is roughly twice the width (79), which matches the appearance of the rectangle.</p>

Body:
I need to use the selectROI function for my project. However, I just can't seem to wrap my head around the format of the coordinates. According to this link, the coordinate array should be in this form: [Top_X, Top_Y, Bottom_X, Bottom_Y]. Assuming that the top left corner starts at (0,0) for (x,y), why are my coordinates so off when I draw 3 different bounding boxes using the selectROI function?

This is what I used to create my bounding boxes and output the coordinates:

import cv2

image = cv2.imread("path")

# Select ROI
r = cv2.selectROI("select the area", image, fromCenter=False)

print('Selected bounding boxes: {}'.format(r))

The following were outputted (see the image for reference of the boxes):

box 1: (42, 18, 212, 303)
box 2: (463, 314, 108, 226)
box 3: (1215, 801, 79, 161)
image

Why do the x-values increase from 42 -> 212 -> 464 -> back to 108 -> 1125 -> back to 79... shouldn't the coordinates for the x's be increasing? And same goes for the y.


问:
Display text with linebreaks when output from database
So i have set up a news page on my website, the user can add posts to the website through a text area in a dashboard. The problem i am having is when the news post is added it does not displaying any line breaks.

So for example it should read like -

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip."

But instead it reads

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip"

The link breaks in my database(mongodb) are stored as \r\n' + but i cant get it to display with the line breaks.

I am using EJS to dispay it in my page.

答:
When you display text in an HTML element like
, line breaks are treated like spaces and the
 element finds its own line breaks. To achieve what you want, you can split the text that comes from database at the line breaks:

var listOfParagraphs = textFromDatabase.split("\r\n");
```

and generate one
 element per entry in the listOfParagraphs array.

Body:
When you display text in an HTML element like <p>, line breaks are treated like spaces and the <p> element finds its own line breaks. To achieve what you want, you can split the text that comes from database at the line breaks:

var listOfParagraphs = textFromDatabase.split("\r\n");

and generate one <p> element per entry in the listOfParagraphs array.


问:
Fully custom validation error message with Rails
Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:

```<code>validates_presence_of :song_rep_xyz, :message => "can't be empty"
</code>```

... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.

I don't want to hack around rails' validation process and I feel there should be a way of fixing that.

答:
Rails3 Code with fully localized messages:

In the model user.rb define the validation

```<code>validates :email, :presence => true
</code>```

In config/locales/en.yml

```<code>en:
  activerecord:
    models:
      user: "Customer"
    attributes:
      user:
        email: "Email address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "cannot be empty"
</code>```

Body:
Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:

validates_presence_of :song_rep_xyz, :message => "can't be empty"

... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.

I don't want to hack around rails' validation process and I feel there should be a way of fixing that.

Body:
Rails3 Code with fully localized messages:

In the model user.rb define the validation

validates :email, :presence => true

In config/locales/en.yml

en:
  activerecord:
    models:
      user: "Customer"
    attributes:
      user:
        email: "Email address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "cannot be empty"


问:
Retrieving splayed tables in q kdb
I tried the following code to retrieve the splayed table, but in vain. After loading sym, the table still leaves its symbol columns as bare enumerations.

```<code>\l dir/file
load `:dir/file/sym
get `:/dir/file/
</code>```

Here is the file structure

```<code>file
-sym
-col1
-col2
-col3
-.d
</code>```

Please help

答:
check if you are enumerating the file for any missed symbols. when you are writing the data to the splayed table.

.Q.en[`dir/file]

Title: Retrieving splayed tables in q kdb

Body:
I tried the following code to retrieve the splayed table, but in vain. After loading sym, the table still leaves its symbol columns as bare enumerations.

\l dir/file
load `:dir/file/sym
get `:/dir/file/

Here is the file structure

file
-sym
-col1
-col2
-col3
-.d

Please help


问:
How to make the column header sticky in scroll if my application uses AgGrid and React class based component
I want to make my column header sticky while scrolling. I am using class based component and AG Grid. I have checked numerous examples but mostly found everyone using function based component. Is there a way to use class based?</p>

答: there is nothing different between class based or functional components while using ag-grid and it always has sticky headers under normal usage. just dont forget set the width and height of the grid and it handles the rest of the work.</p>


问:
how to return only the value contained in the field without the key with mongoose
friends i have the following query in mongoose:

```<code>return this.connection
      .find({ texts: { $in: textIds }})
      .select('texts -_id');
</code>```

and this returns me

```<code>[{text: 'aaa'}, {text: 'bbb'}]
</code>```

is there any way for this query to return the data to me without the key as follows:

```<code>['aaa','bbb']
</code>```

I didn't find anything that could help me here on the stack, maybe I've searched the wrong way, but could you help me?

答:
use aggregation and $push</p>
```<code>this.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "values": {
        "$push": {
          "$cond": [
            {
              "$in": [
                "$texts",
                textIds
              ]
            },
            "$text",
            "$$REMOVE"
          ]
        }
      }
    }
  }
])
</code>```

Body:
friends i have the following query in mongoose:

return this.connection
      .find({ texts: { $in: textIds }})
      .select('texts -_id');

and this returns me

[{text: 'aaa'}, {text: 'bbb'}]

is there any way for this query to return the data to me without the key as follows:

['aaa','bbb']

I didn't find anything that could help me here on the stack, maybe I've searched the wrong way, but could you help me?

Body:
use aggregation and $push

this.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "values": {
        "$push": {
          "$cond": [
            {
              "$in": [
                "$texts",
                textIds
              ]
            },
            "$text",
            "$$REMOVE"
          ]
        }
      }
    }
  }
])


问:
How to add +9 hours on my jQuery script?
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

```<code>$end = mktime(16, 54, 0, 8, 18, 2011);
</code>```

and the copy it below

Countdown Script

```<code><script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);

$(document).ready(function() {
    $("#time").countdown({
        date: end_date,
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>
</code>```

答:
```<code>var end_date = new Date((<?php echo $end; ?>+32400)*1000);
</code>```

Body:
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

$end = mktime(16, 54, 0, 8, 18, 2011);

and the copy it below

Countdown Script