问:
aggregateWindow works different than expected for the current day
I accumulate data from my inverter on the daily PV production. I wanted to create a query to summarize production for each of the last 12 months. I have a problem with the current day: seems that it does not add the current day production to the current month.

The query I'm using is:

```<code>from(bucket: "home")
  |> range(start: -1y)
  |> filter(fn: (r) =>
    r._measurement == "inverter" and
    (r._field == "Power_PV_Generation_Today")
  )
  |> aggregateWindow(every: 1d, offset: -1h1m, fn: last, createEmpty: false)
  |> aggregateWindow(every: 1mo, fn: sum, createEmpty: true)
</code>```

Power_PV_Generation_Today is a value extracted from the inverter and it resets at midnight - hence I'm interested in the last value for each day (the offset there is because I messed up setting the timezone while a preparing a container collecting the data, so part of the entries was recorded with a wrong timezone).

If I comment out the last line to get daily results, the current month looks like this:

Time
Power_PV_Generation_Today

2023-01-04 23:59:00
5.12

2023-01-05 23:59:00
2.95

2023-01-06 23:59:00
4.12

2023-01-07 23:59:00
5.74

2023-01-08 23:59:00
9

2023-01-09 23:59:00
2.15

2023-01-10 23:59:00
2.70

2023-01-11 23:59:00
8.47

2023-01-12 23:59:00
12.4

2023-01-13 15:51:51
3.13

I was expecting it to be summed up to 74.33, while the actual record of the full query for the current month is:

Time
Power_PV_Generation_Today

2023-01-13 15:54:27
71.2

Looks like the last value from the first aggregateWindow is disregarded for some reason.

Is there a way to include the record for the current day in the current month sum?

I've tried rephrasing the query in the following way:

```<code>from(bucket: "home")
  |> range(start: -1y)
  |> filter(fn: (r) =>
    r._measurement == "inverter" and
    (r._field == "Power_PV_Generation_Today")
  )
  |> aggregateWindow(every: 1d, offset: -1h1m, fn: last, createEmpty: false)
  //|> aggregateWindow(every: 1mo, fn: sum, createEmpty: true)
  |> window(every: 1mo)
  |> sum()
  |> duplicate(column: "_stop", as: "_time")
  |> window(every: inf)
</code>```

but the result was identical.

Body:
I accumulate data from my inverter on the daily PV production. I wanted to create a query to summarize production for each of the last 12 months. I have a problem with the current day: seems that it does not add the current day production to the current month.

The query I'm using is:

from(bucket: "home")
  |> range(start: -1y)
  |> filter(fn: (r) =>
    r._measurement == "inverter" and
    (r._field == "Power_PV_Generation_Today")
  )
  |> aggregateWindow(every: 1d, offset: -1h1m, fn: last, createEmpty: false)
  |> aggregateWindow(every: 1mo, fn: sum, createEmpty: true)

Power_PV_Generation_Today is a value extracted from the inverter and it resets at midnight - hence I'm interested in the last value for each day (the offset there is because I messed up setting the timezone while a preparing a container collecting the data, so part of the entries was recorded with a wrong timezone).

If I comment out the last line to get daily results, the current month looks like this:

Time
Power_PV_Generation_Today

2023-01-04 23:59:00
5.12

2023-01-05 23:59:00
2.95

2023-01-06 23:59:00
4.12

2023-01-07 23:59:00
5.74

2023-01-08 23:59:00
9

2023-01-09 23:59:00
2.15

2023-01-10 23:59:00
2.70

2023-01-11 23:59:00
8.47

2023-01-12 23:59:00
12.4

2023-01-13 15:51:51
3.13

I was expecting it to be summed up to 74.33, while the actual record of the full query for the current month is:

Time
Power_PV_Generation_Today

2023-01-13 15:54:27
71.2

Looks like the last value from the first aggregateWindow is disregarded for some reason.

Is there a way to include the record for the current day in the current month sum?

I've tried rephrasing the query in the following way:

from(bucket: "home")
  |> range(start: -1y)
  |> filter(fn: (r) =>
    r._measurement == "inverter" and
    (r._field == "Power_PV_Generation_Today")
  )
  |> aggregateWindow(every: 1d, offset: -1h1m, fn: last, createEmpty: false)
  //|> aggregateWindow(every: 1mo, fn: sum, createEmpty: true)
  |> window(every: 1mo)
  |> sum()
  |> duplicate(column: "_stop", as: "_time")
  |> window(every: inf)

but the result was identical.


来源: stackexchange

问:
Converting Linear Regression Model Pipeline to Polynomial Regression
I am working on a linear and non-linear regression analysis. The following code, gives the output as shown in the figure below.

```<code>
from scipy import stats
slope, intercept = np.polyfit(x, y, deg = 1)
y_model = np.polyval([slope, intercept], x)   # modeling...
x_mean = np.mean(x)
y_mean = np.mean(y)
n = x.size                        # number of samples
m = 2                             # number of parameters
dof = n - m                       # degrees of freedom
t = stats.t.ppf(0.95, dof)       # Students statistic of interval confidence

residual = y - y_model

std_error = (np.sum(residual**2) / dof)**.5   # Standard deviation of the error

numerator = np.sum((x - x_mean)*(y - y_mean))
denominator = ( np.sum((x - x_mean)**2) * np.sum((y - y_mean)**2) )**.5
correlation_coef = numerator / denominator
r2 = correlation_coef**2

# mean squared error
MSE = 1/n * np.sum( (y - y_model)**2 )

# To plot the adjusted model
x_line = np.linspace(np.min(x), np.max(x), 100)
y_line = np.polyval([slope, intercept1, intercept2], x_line)

# confidence interval
ci = t * std_error * (1/n + (x_line - x_mean)**2 / np.sum((x - x_mean)**2))**.5
# predicting interval
pi = t * std_error * (1 + 1/n + (x_line - x_mean)**2 / np.sum((x - x_mean)**2))**.5

## Ploting
plt.rcParams.update({'font.size': 16})
fig = plt.figure(figsize = (17,7))
ax = fig.add_axes([.1, .1, .8, .8])

ax.plot(x, y, 'o', color = 'royalblue')
ax.plot(x_line, y_line, color = 'royalblue', label = 'Regression')
ax.fill_between(x_line, y_line + pi, y_line - pi, color = 'lightcyan', label = '95% prediction interval')
ax.fill_between(x_line, y_line + ci, y_line - ci, color = 'skyblue', label = '95% confidence interval')

ax.set_xlabel('x')
ax.set_ylabel('y')

# rounding and position must be changed for each case and preference
a = str(np.round(intercept))
b = str(np.round(slope,2))
r2s = str(np.round(r2,2))
MSEs = str(np.round(MSE))

ax.text(8000, 6000, 'y = ' + a + ' + ' + b + ' x')
ax.text(8000, 5000, '$r^2$ = ' + r2s)
plt.ylabel('Compresive Strenght of 6 inch Cylinders')
plt.ylabel('Compresive Strenght of 4 inch Cylinders')
plt.title('Fitted Line Plot')
plt.legend(bbox_to_anchor=(1.25, .5), fontsize=12)
plt.show();
</code>```

enter image description here

I want to convert it to polynomial regression, using degree of 2 or 3 or more and want to replicate the same output for a polynomial regression.

ContentLicense: CC BY-SA 4.0

Body:
I am working on a linear and non-linear regression analysis. The following code, gives the output as shown in the figure below.

from scipy import stats
slope, intercept = np.polyfit(x, y, deg = 1)
y_model = np.polyval([slope, intercept], x)   # modeling...
x_mean = np.mean(x)
y_mean = np.mean(y)
n = x.size                        # number of samples
m = 2                             # number of parameters
dof = n - m                       # degrees of freedom
t = stats.t.ppf(0.95, dof)       # Students statistic of interval confidence

residual = y - y_model

std_error = (np.sum(residual**2) / dof)**.5   # Standard deviation of the error

numerator = np.sum((x - x_mean)*(y - y_mean))
denominator = ( np.sum((x - x_mean)**2) * np.sum((y - y_mean)**2) )**.5
correlation_coef = numerator / denominator
r2 = correlation_coef**2

# mean squared error
MSE = 1/n * np.sum( (y - y_model)**2 )

# To plot the adjusted model
x_line = np.linspace(np.min(x), np.max(x), 100)
y_line = np.polyval([slope, intercept1, intercept2], x_line)

# confidence interval
ci = t * std_error * (1/n + (x_line - x_mean)**2 / np.sum((x - x_mean)**2))**.5
# predicting interval
pi = t * std_error * (1 + 1/n + (x_line - x_mean)**2 / np.sum((x - x_mean)**2))**.5

## Ploting
plt.rcParams.update({'font.size': 16})
fig = plt.figure(figsize = (17,7))
ax = fig.add_axes([.1, .1, .8, .8])

ax.plot(x, y, 'o', color = 'royalblue')
ax.plot(x_line, y_line, color = 'royalblue', label = 'Regression')
ax.fill_between(x_line, y_line + pi, y_line - pi, color = 'lightcyan', label = '95% prediction interval')
ax.fill_between(x_line, y_line + ci, y_line - ci, color = 'skyblue', label = '95% confidence interval')

ax.set_xlabel('x')
ax.set_ylabel('y')

# rounding and position must be changed for each case and preference
a = str(np.round(intercept))
b = str(np.round(slope,2))
r2s = str(np.round(r2,2))
MSEs = str(np.round(MSE))

ax.text(8000, 6000, 'y = ' + a + ' + ' + b + ' x')
ax.text(8000, 5000, '$r^2$ = ' + r2s)
plt.ylabel('Compresive Strenght of 6 inch Cylinders')
plt.ylabel('Compresive Strenght of 4 inch Cylinders')
plt.title('Fitted Line Plot')
plt.legend(bbox_to_anchor=(1.25, .5), fontsize=12)
plt.show();

enter image description here

I want to convert it to polynomial regression, using degree of 2 or 3 or more and want to replicate the same output for a polynomial regression.


问:
Redefine Element inside Complex Type
I am working with an xsd which I'm expanding on: "http://opcfoundation.org/UA/ModelDesign.xsd".

The relevant part I'm currently stuck on is below. I have a new ComplexType ExtendedObjectDesign in my local XSD that is equivalent to an "ObjectDesign" which in turns extends InstanceDesign and NodeDesign (all from ModuleDesign.xsd). The only difference between my ExtendedObjectDesign and the below ObjectDesign is that my "Children" can include a new type which also inherits from 'InstanceDesign' as do all the items currently in children. I am a loss as how to proceed. I have tried extending/redefining the "ListOfChildren" type but I always get format errors.

Any suggestions would be appreciated.

NodeDesign from ModuleDesign.xsd (The type ObjectDesign ultimately implements)

```<code><xs:complexType name="NodeDesign">
    <xs:annotation>
      <xs:documentation>
        <html:p>
          The base type of all node designs.
        </html:p>
      </xs:documentation>
    </xs:annotation>
    <xs:sequence>
       ...
       ...
       <xs:element name="Children" type="ListOfChildren" minOccurs="0">
        <xs:annotation>
          <xs:documentation>
            <html:p>
              The Children are the Properties or Components of a Node.
            </html:p>
          </xs:documentation>
        </xs:annotation>
      </xs:element>
      ...
    </xs:sequence>
     ...
  </xs:complexType>
</code>```

ListOfChildren from ModuleDesign.xsd

```<code>  <xs:complexType name="ListOfChildren">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Object" type="ObjectDesign" minOccurs="0" />
        <xs:element name="Variable" type="VariableDesign" minOccurs="0" />
        <xs:element name="Property" type="PropertyDesign" minOccurs="0" />
        <xs:element name="Method" type="MethodDesign" minOccurs="0" />
      </xs:choice>
    </xs:sequence>
  </xs:complexType>
</code>```

I want to redefine ListOfChildren (hopefully universally as I still use ListOfChildren other places to include the new item below.
ListOfChildren from ModuleDesign.xsd

```<code>  <xs:complexType name="ListOfChildren">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Object" type="ObjectDesign" minOccurs="0" />
        <xs:element name="Variable" type="VariableDesign" minOccurs="0" />
        <xs:element name="Property" type="PropertyDesign" minOccurs="0" />
        <xs:element name="Method" type="MethodDesign" minOccurs="0" />
        <xs:element name="MyType" type="MyTypeDesign" minOccurs="0" />
      </xs:choice>
    </xs:sequence>
  </xs:complexType>
</code>```

Title: Redefine Element inside Complex Type

Body:
I am working with an xsd which I'm expanding on: "http://opcfoundation.org/UA/ModelDesign.xsd".

The relevant part I'm currently stuck on is below. I have a new ComplexType ExtendedObjectDesign in my local XSD that is equivalent to an "ObjectDesign" which in turns extends InstanceDesign and NodeDesign (all from ModuleDesign.xsd). The only difference between my ExtendedObjectDesign and the below ObjectDesign is that my "Children" can include a new type which also inherits from 'InstanceDesign' as do all the items currently in children. I am a loss as how to proceed. I have tried extending/redefining the "ListOfChildren" type but I always get format errors.

Any suggestions would be appreciated.

NodeDesign from ModuleDesign.xsd (The type ObjectDesign ultimately implements)

<xs:complexType name="NodeDesign">
    <xs:annotation>
      <xs:documentation>

          The base type of all node designs.

      </xs:documentation>
    </xs:annotation>
    <xs:sequence>
       ...
       ...
       <xs:element name="Children" type="ListOfChildren" minOccurs="0">
        <xs:annotation>
          <xs:documentation>

              The Children are the Properties or Components of a Node.

          </xs:documentation>
        </xs:annotation>
      </xs:element>
      ...
    </xs:sequence>
     ...
  </xs:complexType>

ListOfChildren from ModuleDesign.xsd

  <xs:complexType name="ListOfChildren">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Object" type="ObjectDesign" minOccurs="0" />
        <xs:element name="Variable" type="VariableDesign" minOccurs="0" />
        <xs:element name="Property" type="PropertyDesign" minOccurs="0" />
        <xs:element name="Method" type="MethodDesign" minOccurs="0" />
      </xs:choice>
    </xs:sequence>
  </xs:complexType>

I want to redefine ListOfChildren (hopefully universally as I still use ListOfChildren other places to include the new item below.
ListOfChildren from ModuleDesign.xsd

  <xs:complexType name="ListOfChildren">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Object" type="ObjectDesign" minOccurs="0" />
        <xs:element name="Variable" type="VariableDesign" minOccurs="0" />
        <xs:element name="Property" type="PropertyDesign" minOccurs="0" />
        <xs:element name="Method" type="MethodDesign" minOccurs="0" />
        <xs:element name="MyType" type="MyTypeDesign" minOccurs="0" />
      </xs:choice>
    </xs:sequence>
  </xs:complexType>


问:
Freeswitch load sip_profile with mod_xml_curl
I'm trying to load from a remote server an xml file to define a sip_profile in my Freeswitch box.
I was able to load the directory using mod_xml_curl, and it is working like a charm, but i'm a little bit confuse with the "sip_profile" format.
According to the docs from mod_xml_curl i can load "directory, dialplan and configuration".

So, for example if i wanted to load a file called "profile1.xml" how can i translate this in the mod_xml_curl?.

Let's say the call from mod_curl_xml.conf is :

```<code><!-- Ask example1.com for a configuration config, if not found then revert to disk -->
<binding name="configuration">
  <param name="gateway-url" value="http://example1:80/fsapi" bindings="configuration"/>
</binding>
</code>```

So what could be the response if my "profile1.xml" is something like this?

```<code><profile name="profile1">
  <aliases>
        <alias name="profile1"/>
  </aliases>

  <domains>
    <domain name="all" alias="false" parse="true"/>
  </domains>

  <settings>
    <param name="caller-id-in-from" value="true"/>
    <param name="caller-id-type" value="none"/>
    <param name="user-agent-string" value="FS"/>
    <param name="username" value="FS"/>
    <param name="debug" value="true"/>
    <param name="sip-trace" value="no"/>
    <param name="sip-capture" value="no"/>
    <param name="rfc2833-pt" value="101"/>
    <param name="sip-port" value="5060"/>
    <param name="dialplan" value="XML"/>
    <param name="context" value="external"/>
    <param name="dtmf-type" value="rfc2833"/>
    <param name="t38-passthru" value="true"/>
    <param name="pass-rfc2833" value="true"/>
    <param name="dtmf-duration" value="2000"/>
    <param name="disable-transcoding" value="true"/>
    <param name="inbound-codec-prefs" value="PCMA,PCMU"/>
    <param name="outbound-codec-prefs" value="PCMA,PCMU"/>
    <param name="rtp-timer-name" value="none"/>
    <param name="disable-hold" value="true"/>
    <param name="manage-presence" value="false"/>
    <param name="inbound-codec-negotiation" value="generous"/>
    <param name="nonce-ttl" value="60"/>
    <param name="auth-calls" value="true"/>
    <param name="inbound-late-negotiation" value="true"/>
    <param name="inbound-zrtp-passthru" value="true"/> <!-- (also enables late negotiation) -->
    <param name="rtp-ip" value="192.0.1.43"/>
    <param name="sip-ip" value="192.0.1.43"/>
    <param name="ext-rtp-ip" value="192.0.1.43"/>
    <param name="ext-sip-ip" value="192.0.1.43"/>
    <param name="rtp-timeout-sec" value="300"/>
    <param name="rtp-hold-timeout-sec" value="1800"/>

    <param name="tls" value="disabled"/>
  </settings>
</profile>
</code>```

I'm not sure if i can do this.... or only can load sofia "gateways" from xml_curl.
Thanks!

Body:
I'm trying to load from a remote server an xml file to define a sip_profile in my Freeswitch box.
I was able to load the directory using mod_xml_curl, and it is working like a charm, but i'm a little bit confuse with the "sip_profile" format.
According to the docs from mod_xml_curl i can load "directory, dialplan and configuration".

So, for example if i wanted to load a file called "profile1.xml" how can i translate this in the mod_xml_curl?.

Let's say the call from mod_curl_xml.conf is :

<binding name="configuration">
  <param name="gateway-url" value="http://example1:80/fsapi" bindings="configuration"/>
</binding>

So what could be the response if my "profile1.xml" is something like this?

<profile name="profile1">
  <aliases>
        <alias name="profile1"/>
  </aliases>

  <domains>
    <domain name="all" alias="false" parse="true"/>
  </domains>

  <settings>
    <param name="caller-id-in-from" value="true"/>
    <param name="caller-id-type" value="none"/>
    <param name="user-agent-string" value="FS"/>
    <param name="username" value="FS"/>
    <param name="debug" value="true"/>
    <param name="sip-trace" value="no"/>
    <param name="sip-capture" value="no"/>
    <param name="rfc2833-pt" value="101"/>
    <param name="sip-port" value="5060"/>
    <param name="dialplan" value="XML"/>
    <param name="context" value="external"/>
    <param name="dtmf-type" value="rfc2833"/>
    <param name="t38-passthru" value="true"/>
    <param name="pass-rfc2833" value="true"/>
    <param name="dtmf-duration" value="2000"/>
    <param name="disable-transcoding" value="true"/>
    <param name="inbound-codec-prefs" value="PCMA,PCMU"/>
    <param name="outbound-codec-prefs" value="PCMA,PCMU"/>
    <param name="rtp-timer-name" value="none"/>
    <param name="disable-hold" value="true"/>
    <param name="manage-presence" value="false"/>
    <param name="inbound-codec-negotiation" value="generous"/>
    <param name="nonce-ttl" value="60"/>
    <param name="auth-calls" value="true"/>
    <param name="inbound-late-negotiation" value="true"/>
    <param name="inbound-zrtp-passthru" value="true"/>
    <param name="rtp-ip" value="192.0.1.43"/>
    <param name="sip-ip" value="192.0.1.43"/>
    <param name="ext-rtp-ip" value="192.0.1.43"/>
    <param name="ext-sip-ip" value="192.0.1.43"/>
    <param name="rtp-timeout-sec" value="300"/>
    <param name="rtp-hold-timeout-sec" value="1800"/>

    <param name="tls" value="disabled"/>
  </settings>
</profile>

I'm not sure if i can do this.... or only can load sofia "gateways" from xml_curl.
Thanks!


问:
How to upload a file( image, PDF or video etc ) with faker in Laravel testing
I am writing tests for laravel. I need to pass these validation rules.
Please guide how can I upload fake image and video in my test. thanks

Here is what i tried.

```<code>`'image' => ['required', 'file', 'mimes:jpg,jpeg,bmp,png'],
'video' => ['required', 'file', 'mimes:mp4'],
</code>```

Body:
I am writing tests for laravel. I need to pass these validation rules.
Please guide how can I upload fake image and video in my test. thanks

Here is what i tried.

`'image' => ['required', 'file', 'mimes:jpg,jpeg,bmp,png'],
'video' => ['required', 'file', 'mimes:mp4'],


问:
Storing encrypted password in database but decrypt it on the client side
For context, I am making a password manager where users can store different accounts of service and their passwords. The idea was to store multiple hashed/encrypted passwords in the database and decrypt them on the client side to display them to the users without any input from the user.

What is the ideal way to go around this?

I am aware this method is not recommended as the encryption key could be stolen from the client side. Regardless, I would like to hear any thoughts on this.


问:
FileChannel.tryLock works locally but hangs on remote machine, accessed via SSH
Tl;DR code with FileChannel.tryLock works on a local file but hangs indefinitely when run on a remote machine, I had SSHed into. Most of the length of this question is about showing outputs and debugging attempts, but the essential part is in the first para.

So I have a simple sample code that tries to get a file lock via FileChannel.tryLock. (scroll below for the Java version)

import java.io.RandomAccessFile
import java.util.logging.Logger

val LOGGER_FORMAT ="[%1\$tF %1\$tT] %4$-7s %5\$s %6\$s%n".also { System.setProperty("java.util.logging.SimpleFormatter.format", it) }
val logger = Logger.getGlobal()
fun main(args:Array<String>) {
    val path= if (args.isEmpty())"localFile.txt" else args[0]
    val channel=RandomAccessFile(path,"rw").channel
    logger.info("created channel $channel")
    logger.info("trying for lock on file $path")
    val lock=channel.tryLock()
    logger.info("got this lock $lock")
}
```
<p>When I execute this code on my local Ubuntu machine against <code>localFile.txt</code>, the code works just fine and gives a lock.</p>
<pre class="lang-bash prettyprint-override"><code>[2023-01-13 14:44:03] INFO    created channel sun.nio.ch.FileChannelImpl@7d4991ad
[2023-01-13 14:44:04] INFO    trying for lock on file localFile.txt
[2023-01-13 14:44:04] INFO    got this lock: sun.nio.ch.FileLockImpl[0:9223372036854775807 exclusive valid]
</code>```

I then packaged the code as an executable jar (you need not do so, just run as a .class file if you wish)  and ran it on a remote machine I had SSHed into. The file it tried to get a lock on was also a file on that remote machine, namely remoteFile.txt. There the command writes the following and hangs indefinitely.

[2023-01-13 14:40:41] INFO    created channel sun.nio.ch.FileChannelImpl@7d4991ad
[2023-01-13 14:40:41] INFO    trying for lock on file remoteFile.txt
```
<h2>Why does this happen?</h2>
<p>Especially, since <code>tryLock</code> is non-blocking.</p>
<hr />
<p><strong>My debugging attempts</strong></p>
<ol>
<li><p>As a first step to debugging I tried a java port of the code (scroll below) - but it breaks in exactly the same way.</p>
</li>
<li><p>I then checked the file permissions. Here are the <code>ls -l</code> for the files</p>
</li>
</ol>
<pre class="lang-bash prettyprint-override"><code>#localFile.txt
-rw-rw-r-- 1 giraffe giraffe 8 Jan 13 02:22 localFile.txt

#remoteFIle.txt
-rw-r--r-- 1 zebra ox 6 Jan 13 19:37 remoteFile.txt
</code>```

They are different, so I changed the permissions for the remote to be same as those for the local one, but to no avail - locking still hangs on remote.

Google returned someone facing an issue with tryLock but that's on some particular NFS deployment. I don't know how that ties into all this.

I am confused and mesmerizied by all this. Any and all help is appreciated.

Env:

local machine

#lsb_release -a
Ubuntu 20.04.5 LTS
#java -version
openjdk version "17" 2021-09-14
OpenJDK Runtime Environment (build 17+35-2724)
OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing)
#filesystem via cat /etc/fstab
ext4
```
<p>remote machine</p>
<pre class="lang-bash prettyprint-override"><code>#lsb_release -a
Fedora release 23 (Twenty Three)
#java -version
openjdk version "17" 2021-09-14
OpenJDK Runtime Environment (build 17+35-2724)
OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing)
#filesystem via cat /etc/fstab
ext4
</code>```

SSH command

ssh -X -t zebra@remoteName.website bash -l
```
<hr />
<p><strong>Java version</strong></p>
```import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Logger;

public class Test_Java {
    static {
        System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$-7s %5$s %6$s%n");
    }
    private final static Logger logger=Logger.getGlobal();

    public static void main(String[] args) throws IOException {
        var path="";
        if(args==null || args.length==0)
            path="localFile.txt";
        else
            path=args[0];

        try(var file= new RandomAccessFile(path,"rw")){
            var channel=file.getChannel();
            logger.info("created channel "+channel);
            logger.info("trying for lock on file "+path);
            var lock=channel.tryLock();
            logger.info("got this lock: "+lock);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
```
<p><em>Further data requested in comments</em></p>
<ol>
<li><code>ulimit -a</code> on remoteMachine</li>
</ol>
<pre class="lang-bash prettyprint-override"><code>core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 63929
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 63929
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
</code>```

thread dump on remoteMachine while the process was hung, using jstack pid

2023-01-14 15:39:16
Full thread dump OpenJDK 64-Bit Server VM (17+35-2724 mixed mode, sharing):

Threads class SMR info:
_java_thread_list=0x00007fddc0001ba0, length=12, elements={
0x00007fde10024840, 0x00007fde1015d100, 0x00007fde1015e5e0, 0x00007fde10163a80,
0x00007fde10164d10, 0x00007fde10166100, 0x00007fde10167ae0, 0x00007fde10169010,
0x00007fde1016a480, 0x00007fde10179aa0, 0x00007fde1017cb00, 0x00007fddc0000bd0
}

"main" #1 prio=5 os_prio=0 cpu=135.19ms elapsed=121.26s tid=0x00007fde10024840 nid=0x3fd7 runnable  [0x00007fde18b9f000]
   java.lang.Thread.State: RUNNABLE
    at sun.nio.ch.FileDispatcherImpl.lock0(java.base@17/Native Method)
    at sun.nio.ch.FileDispatcherImpl.lock(java.base@17/FileDispatcherImpl.java:96)
    at sun.nio.ch.FileChannelImpl.tryLock(java.base@17/FileChannelImpl.java:1304)
    at java.nio.channels.FileChannel.tryLock(java.base@17/FileChannel.java:1191)
    at Test_serc_2_Java.main(Test_serc_2_Java.java:23)

"Reference Handler" #2 daemon prio=10 os_prio=0 cpu=0.19ms elapsed=121.24s tid=0x00007fde1015d100 nid=0x3fde waiting on condition  [0x00007fddf0afd000]
   java.lang.Thread.State: RUNNABLE
    at java.lang.ref.Reference.waitForReferencePendingList(java.base@17/Native Method)
    at java.lang.ref.Reference.processPendingReferences(java.base@17/Reference.java:253)
    at java.lang.ref.Reference$ReferenceHandler.run(java.base@17/Reference.java:215)

"Finalizer" #3 daemon prio=8 os_prio=0 cpu=0.38ms elapsed=121.24s tid=0x00007fde1015e5e0 nid=0x3fdf in Object.wait()  [0x00007fddf09fc000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(java.base@17/Native Method)
    - waiting on <0x0000000715802f40> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(java.base@17/ReferenceQueue.java:155)
    - locked <0x0000000715802f40> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(java.base@17/ReferenceQueue.java:176)
    at java.lang.ref.Finalizer$FinalizerThread.run(java.base@17/Finalizer.java:172)

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 cpu=0.43ms elapsed=121.24s tid=0x00007fde10163a80 nid=0x3fe0 waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Service Thread" #5 daemon prio=9 os_prio=0 cpu=0.16ms elapsed=121.24s tid=0x00007fde10164d10 nid=0x3fe1 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Deflation Thread" #6 daemon prio=9 os_prio=0 cpu=1.56ms elapsed=121.24s tid=0x00007fde10166100 nid=0x3fe2 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #7 daemon prio=9 os_prio=0 cpu=33.90ms elapsed=121.24s tid=0x00007fde10167ae0 nid=0x3fe3 waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE
   No compile task

"C1 CompilerThread0" #9 daemon prio=9 os_prio=0 cpu=59.73ms elapsed=121.24s tid=0x00007fde10169010 nid=0x3fe4 waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE
   No compile task

"Sweeper thread" #10 daemon prio=9 os_prio=0 cpu=0.18ms elapsed=121.24s tid=0x00007fde1016a480 nid=0x3fe5 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Notification Thread" #11 daemon prio=9 os_prio=0 cpu=0.10ms elapsed=121.23s tid=0x00007fde10179aa0 nid=0x3fe6 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Common-Cleaner" #12 daemon prio=8 os_prio=0 cpu=0.27ms elapsed=121.23s tid=0x00007fde1017cb00 nid=0x3fe8 in Object.wait()  [0x00007fdde1ffe000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(java.base@17/Native Method)
    - waiting on <0x0000000715817018> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(java.base@17/ReferenceQueue.java:155)
    - locked <0x0000000715817018> (a java.lang.ref.ReferenceQueue$Lock)
    at jdk.internal.ref.CleanerImpl.run(java.base@17/CleanerImpl.java:140)
    at java.lang.Thread.run(java.base@17/Thread.java:833)
    at jdk.internal.misc.InnocuousThread.run(java.base@17/InnocuousThread.java:162)

"Attach Listener" #14 daemon prio=9 os_prio=0 cpu=0.57ms elapsed=72.87s tid=0x00007fddc0000bd0 nid=0x3fff waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"VM Thread" os_prio=0 cpu=2.32ms elapsed=121.25s tid=0x00007fde10159340 nid=0x3fdd runnable

"GC Thread#0" os_prio=0 cpu=0.26ms elapsed=121.26s tid=0x00007fde10072e50 nid=0x3fd8 runnable

"G1 Main Marker" os_prio=0 cpu=0.16ms elapsed=121.26s tid=0x00007fde10083e40 nid=0x3fd9 runnable

"G1 Conc#0" os_prio=0 cpu=0.09ms elapsed=121.26s tid=0x00007fde10084da0 nid=0x3fda runnable

"G1 Refine#0" os_prio=0 cpu=0.08ms elapsed=121.26s tid=0x00007fde101299d0 nid=0x3fdb runnable

"G1 Service" os_prio=0 cpu=8.82ms elapsed=121.26s tid=0x00007fde1012a8c0 nid=0x3fdc runnable

"VM Periodic Task Thread" os_prio=0 cpu=31.31ms elapsed=121.23s tid=0x00007fde1017b3e0 nid=0x3fe7 waiting on condition

JNI global refs: 8, weak refs: 0

```

Body:
Tl;DR code with FileChannel.tryLock works on a local file but hangs indefinitely when run on a remote machine, I had SSHed into. Most of the length of this question is about showing outputs and debugging attempts, but the essential part is in the first para.

So I have a simple sample code that tries to get a file lock via FileChannel.tryLock. (scroll below for the Java version)

import java.io.RandomAccessFile
import java.util.logging.Logger

val LOGGER_FORMAT ="[%1\$tF %1\$tT] %4$-7s %5\$s %6\$s%n".also { System.setProperty("java.util.logging.SimpleFormatter.format", it) }
val logger = Logger.getGlobal()
fun main(args:Array<String>) {
    val path= if (args.isEmpty())"localFile.txt" else args[0]
    val channel=RandomAccessFile(path,"rw").channel
    logger.info("created channel $channel")
    logger.info("trying for lock on file $path")
    val lock=channel.tryLock()
    logger.info("got this lock $lock")
}

When I execute this code on my local Ubuntu machine against localFile.txt, the code works just fine and gives a lock.

[2023-01-13 14:44:03] INFO    created channel sun.nio.ch.FileChannelImpl@7d4991ad
[2023-01-13 14:44:04] INFO    trying for lock on file localFile.txt
[2023-01-13 14:44:04] INFO    got this lock: sun.nio.ch.FileLockImpl[0:9223372036854775807 exclusive valid]

I then packaged the code as an executable jar (you need not do so, just run as a .class file if you wish)  and ran it on a remote machine I had SSHed into. The file it tried to get a lock on was also a file on that remote machine, namely remoteFile.txt. There the command writes the following and hangs indefinitely.

[2023-01-13 14:40:41] INFO    created channel sun.nio.ch.FileChannelImpl@7d4991ad
[2023-01-13 14:40:41] INFO    trying for lock on file remoteFile.txt

Why does this happen?

Especially, since tryLock is non-blocking.

My debugging attempts

As a first step to debugging I tried a java port of the code (scroll below) - but it breaks in exactly the same way.

I then checked the file permissions. Here are the ls -l for the files

#localFile.txt
-rw-rw-r-- 1 giraffe giraffe 8 Jan 13 02:22 localFile.txt

#remoteFIle.txt
-rw-r--r-- 1 zebra ox 6 Jan 13 19:37 remoteFile.txt

They are different, so I changed the permissions for the remote to be same as those for the local one, but to no avail - locking still hangs on remote.

Google returned someone facing an issue with tryLock but that's on some particular NFS deployment. I don't know how that ties into all this.

I am confused and mesmerizied by all this. Any and all help is appreciated.

Env:

local machine

#lsb_release -a
Ubuntu 20.04.5 LTS
#java -version
openjdk version "17" 2021-09-14
OpenJDK Runtime Environment (build 17+35-2724)
OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing)
#filesystem via cat /etc/fstab
ext4

remote machine

#lsb_release -a
Fedora release 23 (Twenty Three)
#java -version
openjdk version "17" 2021-09-14
OpenJDK Runtime Environment (build 17+35-2724)
OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing)
#filesystem via cat /etc/fstab
ext4

SSH command

ssh -X -t zebra@remoteName.website bash -l

Java version

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Logger;

public class Test_Java {
    static {
        System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$-7s %5$s %6$s%n");
    }
    private final static Logger logger=Logger.getGlobal();

    public static void main(String[] args) throws IOException {
        var path="";
        if(args==null || args.length==0)
            path="localFile.txt";
        else
            path=args[0];

        try(var file= new RandomAccessFile(path,"rw")){
            var channel=file.getChannel();
            logger.info("created channel "+channel);
            logger.info("trying for lock on file "+path);
            var lock=channel.tryLock();
            logger.info("got this lock: "+lock);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

Further data requested in comments

ulimit -a on remoteMachine

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 63929
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 63929
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

thread dump on remoteMachine while the process was hung, using jstack pid

2023-01-14 15:39:16
Full thread dump OpenJDK 64-Bit Server VM (17+35-2724 mixed mode, sharing):

Threads class SMR info:
_java_thread_list=0x00007fddc0001ba0, length=12, elements={
0x00007fde10024840, 0x00007fde1015d100, 0x00007fde1015e5e0, 0x00007fde10163a80,
0x00007fde10164d10, 0x00007fde10166100, 0x00007fde10167ae0, 0x00007fde10169010,
0x00007fde1016a480, 0x00007fde10179aa0, 0x00007fde1017cb00, 0x00007fddc0000bd0
}

"main" #1 prio=5 os_prio=0 cpu=135.19ms elapsed=121.26s tid=0x00007fde10024840 nid=0x3fd7 runnable  [0x00007fde18b9f000]
   java.lang.Thread.State: RUNNABLE
    at sun.nio.ch.FileDispatcherImpl.lock0(java.base@17/Native Method)
    at sun.nio.ch.FileDispatcherImpl.lock(java.base@17/FileDispatcherImpl.java:96)
    at sun.nio.ch.FileChannelImpl.tryLock(java.base@17/FileChannelImpl.java:1304)
    at java.nio.channels.FileChannel.tryLock(java.base@17/FileChannel.java:1191)
    at Test_serc_2_Java.main(Test_serc_2_Java.java:23)

"Reference Handler" #2 daemon prio=10 os_prio=0 cpu=0.19ms elapsed=121.24s tid=0x00007fde1015d100 nid=0x3fde waiting on condition  [0x00007fddf0afd000]
   java.lang.Thread.State: RUNNABLE
    at java.lang.ref.Reference.waitForReferencePendingList(java.base@17/Native Method)
    at java.lang.ref.Reference.processPendingReferences(java.base@17/Reference.java:253)
    at java.lang.ref.Reference$ReferenceHandler.run(java.base@17/Reference.java:215)

"Finalizer" #3 daemon prio=8 os_prio=0 cpu=0.38ms elapsed=121.24s tid=0x00007fde1015e5e0 nid=0x3fdf in Object.wait()  [0x00007fddf09fc000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(java.base@17/Native Method)
    - waiting on <0x0000000715802f40> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(java.base@17/ReferenceQueue.java:155)
    - locked <0x0000000715802f40> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(java.base@17/ReferenceQueue.java:176)
    at java.lang.ref.Finalizer$FinalizerThread.run(java.base@17/Finalizer.java:172)

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 cpu=0.43ms elapsed=121.24s tid=0x00007fde10163a80 nid=0x3fe0 waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Service Thread" #5 daemon prio=9 os_prio=0 cpu=0.16ms elapsed=121.24s tid=0x00007fde10164d10 nid=0x3fe1 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Deflation Thread" #6 daemon prio=9 os_prio=0 cpu=1.56ms elapsed=121.24s tid=0x00007fde10166100 nid=0x3fe2 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #7 daemon prio=9 os_prio=0 cpu=33.90ms elapsed=121.24s tid=0x00007fde10167ae0 nid=0x3fe3 waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE
   No compile task

"C1 CompilerThread0" #9 daemon prio=9 os_prio=0 cpu=59.73ms elapsed=121.24s tid=0x00007fde10169010 nid=0x3fe4 waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE
   No compile task

"Sweeper thread" #10 daemon prio=9 os_prio=0 cpu=0.18ms elapsed=121.24s tid=0x00007fde1016a480 nid=0x3fe5 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Notification Thread" #11 daemon prio=9 os_prio=0 cpu=0.10ms elapsed=121.23s tid=0x00007fde10179aa0 nid=0x3fe6 runnable  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Common-Cleaner" #12 daemon prio=8 os_prio=0 cpu=0.27ms elapsed=121.23s tid=0x00007fde1017cb00 nid=0x3fe8 in Object.wait()  [0x00007fdde1ffe000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(java.base@17/Native Method)
    - waiting on <0x0000000715817018> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(java.base@17/ReferenceQueue.java:155)
    - locked <0x0000000715817018> (a java.lang.ref.ReferenceQueue$Lock)
    at jdk.internal.ref.CleanerImpl.run(java.base@17/CleanerImpl.java:140)
    at java.lang.Thread.run(java.base@17/Thread.java:833)
    at jdk.internal.misc.InnocuousThread.run(java.base@17/InnocuousThread.java:162)

"Attach Listener" #14 daemon prio=9 os_prio=0 cpu=0.57ms elapsed=72.87s tid=0x00007fddc0000bd0 nid=0x3fff waiting on condition  [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"VM Thread" os_prio=0 cpu=2.32ms elapsed=121.25s tid=0x00007fde10159340 nid=0x3fdd runnable

"GC Thread#0" os_prio=0 cpu=0.26ms elapsed=121.26s tid=0x00007fde10072e50 nid=0x3fd8 runnable

"G1 Main Marker" os_prio=0 cpu=0.16ms elapsed=121.26s tid=0x00007fde10083e40 nid=0x3fd9 runnable

"G1 Conc#0" os_prio=0 cpu=0.09ms elapsed=121.26s tid=0x00007fde10084da0 nid=0x3fda runnable

"G1 Refine#0" os_prio=0 cpu=0.08ms elapsed=121.26s tid=0x00007fde101299d0 nid=0x3fdb runnable

"G1 Service" os_prio=0 cpu=8.82ms elapsed=121.26s tid=0x00007fde1012a8c0 nid=0x3fdc runnable

"VM Periodic Task Thread" os_prio=0 cpu=31.31ms elapsed=121.23s tid=0x00007fde1017b3e0 nid=0x3fe7 waiting on condition

JNI global refs: 8, weak refs: 0


问:
The type or namespace name "" cannot be found
When trying to refer to the class "Deck" in the class "Hands" i am receiving the error message that the namespace cant be found.

I also tried to just use another name of one of my classes called "Random Number" and this worked so I am not sure on my error.

public class Deck
{
    public List<Card> Cards { set; get; }//The List is the list of cards in the deck

    public Deck() //creates the pack of cards
    {
        Cards = new List<Card>();
        revealdeck();
    }

    public void revealdeck()
    {
        Cards.Clear();
        int card_number = 1;
        for (int E = 1; E < 5; E++)  // 4 different suits
        {
            for (int F = 1; F < 14; F++) // 13 different numbers in the cards 13x4 = 52
            {
                Card cardnow = new Card(); //creates the new card
                cardnow.cardnum = card_number;
                if (E == 1)
                    cardnow.cardsuit = "spades";
                if (E == 2)
                    cardnow.cardsuit = "clubs";
                if (E == 3)
                    cardnow.cardsuit = "hearts";
                if (E == 4)
                    cardnow.cardsuit = "diamonds";
                cardnow.cardvalue = F;

                Cards.Add(cardnow);
                card_number = cardnumber++;
            }
        }
    }

    public Card SearchingCards(int card_number)
    {
        foreach (Card w_card in Cards)
        {
            if (w_card.cardnum != card_number)
            {
                return null;
            }
            else
            {
                return w_card;
            }
        }
    }
}
```
<pre class="lang-cs prettyprint-override"><code>{
    public class Hand
    {
        public List<Card> Cards { set; get; }
        public int AmtOFCards { set; get; }
        public int Chips{ set; get; }
        public string Winner { set; get;}

        public Hand(int numOFcards)
        {
            AmtOFCards = numOFcards; //Cards in users hand
            Cards = new List<Card>(); // this list is to hold the cards
            Card card0 = new Card(); //Removes value
            for (int y = 0; y < numOFcards; y++)
            {
                Cards.Add(card0); // Adds card with no value to list
            }

        }

        public void Cardadd(***Deck*** thisdeck, int cards_in_a_hand) // This is where I am getting the error.
        {

        }
    }
}
</code>```

Body:
When trying to refer to the class "Deck" in the class "Hands" i am receiving the error message that the namespace cant be found.

I also tried to just use another name of one of my classes called "Random Number" and this worked so I am not sure on my error.

public class Deck
{
    public List<Card> Cards { set; get; }//The List is the list of cards in the deck

    public Deck() //creates the pack of cards
    {
        Cards = new List<Card>();
        revealdeck();
    }

    public void revealdeck()
    {
        Cards.Clear();
        int card_number = 1;
        for (int E = 1; E < 5; E++)  // 4 different suits
        {
            for (int F = 1; F < 14; F++) // 13 different numbers in the cards 13x4 = 52
            {
                Card cardnow = new Card(); //creates the new card
                cardnow.cardnum = card_number;
                if (E == 1)
                    cardnow.cardsuit = "spades";
                if (E == 2)
                    cardnow.cardsuit = "clubs";
                if (E == 3)
                    cardnow.cardsuit = "hearts";
                if (E == 4)
                    cardnow.cardsuit = "diamonds";
                cardnow.cardvalue = F;

                Cards.Add(cardnow);
                card_number = cardnumber++;
            }
        }
    }

    public Card SearchingCards(int card_number)
    {
        foreach (Card w_card in Cards)
        {
            if (w_card.cardnum != card_number)
            {
                return null;
            }
            else
            {
                return w_card;
            }
        }
    }
}

{
    public class Hand
    {
        public List<Card> Cards { set; get; }
        public int AmtOFCards { set; get; }
        public int Chips{ set; get; }
        public string Winner { set; get;}

        public Hand(int numOFcards)
        {
            AmtOFCards = numOFcards; //Cards in users hand
            Cards = new List<Card>(); // this list is to hold the cards
            Card card0 = new Card(); //Removes value
            for (int y = 0; y < numOFcards; y++)
            {
                Cards.Add(card0); // Adds card with no value to list
            }

        }

        public void Cardadd(***Deck*** thisdeck, int cards_in_a_hand) // This is where I am getting the error.
        {

        }
    }
}


问:
Cant Scroll or Click inside a Webkit2 GTK Window
I am developing a program that opens google.com website inside a borderless GTK Window on linux.

Loaded inside is webkit that displays a website. Everything works nice, but I cannot scroll or click anything

(scrolling with arrow keys and using TAB to navigate the website works). How can I fix it?

I tried googling but found no information.


问:
How to get status or details of sended mail using messageId in nodemailer?
Here is the code for sending email using nodemailer:

```<code>class SendMailWithAppPass{
    #user
    #appPassword
    #transporter
    // create reusable transporter object using the default SMTP transport
    constructor(userEmail, appPassword){
        this.#user = userEmail,
        this.#appPassword = appPassword,

        this.#transporter = nodemailer.createTransport({
            host:  'smtp.gmail.com',
            port: 465,
            secure: true, // true for 465, false for other ports
            auth: {
                user: this.#user, // generated ethereal user
                pass: this.#appPassword, // generated ethereal password
            },
            tls: {
                rejectUnauthorized: false
            },
        });
    }

    async send(from, to, sub, text, html=null){
        let info = await this.#transporter.sendMail({
            from: `"Automata" <${from}>`, // sender address
            to: to, // list of receivers
            subject: sub, // Subject line
            text: text, // plain text body
            html: html, // html body
        });

        if(info){
            console.log(info);
            return info;
        }
    }
}
</code>```

After sending email, I get messageId ('<1b796af0-d69b-f497-a91c-84d7970cd8b1@gmail.com>').
I want to use this messageId to get details of sended email to check if email is bounced or not.

Body:
Here is the code for sending email using nodemailer:

class SendMailWithAppPass{
    #user
    #appPassword
    #transporter
    // create reusable transporter object using the default SMTP transport
    constructor(userEmail, appPassword){
        this.#user = userEmail,
        this.#appPassword = appPassword,

        this.#transporter = nodemailer.createTransport({
            host:  'smtp.gmail.com',
            port: 465,
            secure: true, // true for 465, false for other ports
            auth: {
                user: this.#user, // generated ethereal user
                pass: this.#appPassword, // generated ethereal password
            },
            tls: {
                rejectUnauthorized: false
            },
        });
    }

    async send(from, to, sub, text, html=null){
        let info = await this.#transporter.sendMail({
            from: `"Automata" <${from}>`, // sender address
            to: to, // list of receivers
            subject: sub, // Subject line
            text: text, // plain text body
            html: html, // html body
        });

        if(info){
            console.log(info);
            return info;
        }
    }
}

After sending email, I get messageId ('<1b796af0-d69b-f497-a91c-84d7970cd8b1@gmail.com>').
I want to use this messageId to get details of sended email to check if email is bounced or not.


问:
How is the SceneDelegate available through @EnvironmentObject
I'm setting delegate class for UISceneConfiguration like this:

```<code>func application(_ application: UIApplication,
                 configurationForConnecting connectingSceneSession: UISceneSession,
                 options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
    sceneConfig.delegateClass = SceneDelegate.self
    return sceneConfig
}
</code>```

My body of the @main App is

```<code>var body: some Scene {
        WindowGroup {
            RootView()
        }
}
</code>```

How is the sceneDelegate object available in the RootView by?

```<code>struct RootView: View {
    @EnvironmentObject private var sceneDelegate: SceneDelegate
[...]
}
</code>```

I don't understand who and where is setting this object.

Body:
I'm setting delegate class for UISceneConfiguration like this:

func application(_ application: UIApplication,
                 configurationForConnecting connectingSceneSession: UISceneSession,
                 options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
    sceneConfig.delegateClass = SceneDelegate.self
    return sceneConfig
}

My body of the @main App is

var body: some Scene {
        WindowGroup {
            RootView()
        }
}

How is the sceneDelegate object available in the RootView by?

struct RootView: View {
    @EnvironmentObject private var sceneDelegate: SceneDelegate
[...]
}

I don't understand who and where is setting this object.


问:
Externalize the files under src/main/resources not only application.properties but also other folders present in it
I'm having a requirement that we are developing a application that requires some files like txt, json etc., currently these files are present inside the src/main/resources folder but we are distributing this app as jar file. So we need to externalize these files present inside resources folder like we used to externalize application.properties file outside the jar

Is there any way to externalize the files along with the application.properties. I had tried put these files local to the jar file but spring is not overriding the files, any help is appreciated


问:
time wont formatt correctly when using inputs

<?php

$date = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date']))))));
$date2 = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date2']))))));

?>

  <!doctype html>

    <title>date</title>

    <form action="" method="post">

      Date:
      <input type="date" class="form-control" id="date" name="date">

      Date2:
      <input type="date" class="form-control" id="date2" name="date2">

      <input id="saveForm" onclick="" class="button_text" type="submit" name="submit" value="Submit " />

    </form>

  ```
</div>
</div>
</p>
<p>So the bottom one works when loaded and displays correctly however when submitted or console logged looks like this 2023-01-13 and when I change it to the correct format it stops working but will then console log correctly but will still echo out wrong... What is going on here? how can I make the date auto populate when page is loaded and still console log and echo out correctly like month/day/year ?????</p>
``````
<!doctype html>
<html lang="en">
<head>
<title>date</title>
</head>
<body>
<form action="" method="post">

<label for="message" class="form-label">Date:</label>
<input type="date" class="form-control" id="date" name="date">
<br>
<label for="message" class="form-label">Date2:</label>
<input type="date" class="form-control" id="date2" name="date2">

<input id="saveForm" onclick="" class="button_text" type="submit" name="submit" value="Submit "/>

</form>

    <script>

var date = new Date();

var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = month + "-" + day + "-" + year;

document.getElementById('date').value = today;

console.log(today);

//date works but output is diffrent

var date = new Date();

var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;

document.getElementById('date2').value = today;

console.log(today);

</script>
</html>
<?php
$date = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date']))))));
$date2 = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date2']))))));
echo '<hr><br>';
echo $date;
echo '<br>';
echo $date2;
?>
```
```
<p>I assume when i change this it should output correctly but instead only makes it half work</p>
```      var today = month + "-" + day + "-" + year;
```

Body:
<?php

$date = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date']))))));
$date2 = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date2']))))));

?>

  <!doctype html>

    <title>date</title>

    <form action="" method="post">

      Date:
      <input type="date" class="form-control" id="date" name="date">

      Date2:
      <input type="date" class="form-control" id="date2" name="date2">

      <input id="saveForm" onclick="" class="button_text" type="submit" name="submit" value="Submit " />

    </form>

So the bottom one works when loaded and displays correctly however when submitted or console logged looks like this 2023-01-13 and when I change it to the correct format it stops working but will then console log correctly but will still echo out wrong... What is going on here? how can I make the date auto populate when page is loaded and still console log and echo out correctly like month/day/year ?????

```
<!doctype html>
<html lang="en">
<head>
<title>date</title>
</head>
<body>
<form action="" method="post">

<label for="message" class="form-label">Date:</label>
<input type="date" class="form-control" id="date" name="date">
<br>
<label for="message" class="form-label">Date2:</label>
<input type="date" class="form-control" id="date2" name="date2">

<input id="saveForm" onclick="" class="button_text" type="submit" name="submit" value="Submit "/>

</form>

    <script>

var date = new Date();

var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = month + "-" + day + "-" + year;

document.getElementById('date').value = today;

console.log(today);

//date works but output is diffrent

var date = new Date();

var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;

document.getElementById('date2').value = today;

console.log(today);

</script>
</html>
<?php
$date = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date']))))));
$date2 = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date2']))))));
echo '<hr><br>';
echo $date;
echo '<br>';
echo $date2;
?>
```

I assume when i change this it should output correctly but instead only makes it half work

      var today = month + "-" + day + "-" + year;


问:
Java ThreadPoolExecutor for timed tasks
I'd like to know if there exists a class that runs tasks for a timed duration, if that duration exceeds then it errors out or gives a return status of fail. If there isn't, how simple would this be to implement in Java using ThreadPoolExecutor class.

After some looking around, there are some examples working with ThreadPoolExecutor class.

Title: Java ThreadPoolExecutor for timed tasks


问:
RabbitMQ Cluster Deployment error on K8 - Readiness probe failed
K8 Tools version I am using: kubelet=1.19.16-00 kubeadm=1.19.16-00 kubectl=1.19.16-00

RabbitMQ cluster operator is running successfully but the cluster is not able to setup due to some network related issues (my guess..)

cluster operator is running successfully

When I describe the pods for debugging I get to see error for all nodes Readiness probe failed: dial tcp :5672: connect: connection refused It goes in race condition and eventually throws crashbackloop error.
Readiness probe failed

I am new to RMQ, K8 and have tried few more work arounds available on web but always get stuck at this stage.

My K8 is installed on AWS EC2 instance and
I have installed operator there using kubectl apply -f https://github.com/rabbitmq/cluster-operator/releases/latest/download/cluster-operator.yml

Below is the yaml file I am trying to deploy as a cluster.

```<code>apiVersion: rabbitmq.com/v1beta1
kind: RabbitmqCluster
metadata:
 name: rabbitmq-cluster
 namespace: rabbitmq-system
spec:
 replicas: 3
 resources:
   requests:
     cpu: 250m
     memory: 500Mi
   limits:
     cpu: 1
     memory: 1Gi
 rabbitmq:
         additionalPlugins:
            -   rabbitmq_mqtt
 service:
   type: ClusterIP
</code>```

Any help or suggestion what I am missing here would be appreciated. Thanks in Advance!

Body:
K8 Tools version I am using: kubelet=1.19.16-00 kubeadm=1.19.16-00 kubectl=1.19.16-00

RabbitMQ cluster operator is running successfully but the cluster is not able to setup due to some network related issues (my guess..)

cluster operator is running successfully

When I describe the pods for debugging I get to see error for all nodes Readiness probe failed: dial tcp :5672: connect: connection refused It goes in race condition and eventually throws crashbackloop error.
Readiness probe failed

I am new to RMQ, K8 and have tried few more work arounds available on web but always get stuck at this stage.

My K8 is installed on AWS EC2 instance and
I have installed operator there using kubectl apply -f https://github.com/rabbitmq/cluster-operator/releases/latest/download/cluster-operator.yml

Below is the yaml file I am trying to deploy as a cluster.

apiVersion: rabbitmq.com/v1beta1
kind: RabbitmqCluster
metadata:
 name: rabbitmq-cluster
 namespace: rabbitmq-system
spec:
 replicas: 3
 resources:
   requests:
     cpu: 250m
     memory: 500Mi
   limits:
     cpu: 1
     memory: 1Gi
 rabbitmq:
         additionalPlugins:
            -   rabbitmq_mqtt
 service:
   type: ClusterIP

Any help or suggestion what I am missing here would be appreciated. Thanks in Advance!


问:
Load assembly from folder and specific version
In a VB.net solution I need to load some dll from a specific folder. I have read
Could not load an assembly from specific folder and many others but in my case no luck. I have tried to add in app.config lines to reference to the file I need :

```<code><dependentAssembly>
  <assemblyIdentity name="Eplan.EplApi.Starteru" publicKeyToken="57aaa27e22f7b107" />
  <publisherPolicy apply="yes" />
  <codeBase version="1.0.0.0" href="C:\Program Files\EPLAN\Platform\2023.0.3\Bin\Eplan.EplApi.Starteru.dll"/>
</dependentAssembly>
</code>```

But when I try to start my solution I have a System.InvalidOperationException without any other message. I have also tried this solution https://social.technet.microsoft.com/wiki/contents/articles/53408.vb-net-dynamically-load-assemblies.aspx without luck.Any idea for solving?

Body:
In a VB.net solution I need to load some dll from a specific folder. I have read
Could not load an assembly from specific folder and many others but in my case no luck. I have tried to add in app.config lines to reference to the file I need :

<dependentAssembly>
  <assemblyIdentity name="Eplan.EplApi.Starteru" publicKeyToken="57aaa27e22f7b107" />
  <publisherPolicy apply="yes" />
  <codeBase version="1.0.0.0" href="C:\Program Files\EPLAN\Platform\2023.0.3\Bin\Eplan.EplApi.Starteru.dll"/>
</dependentAssembly>

But when I try to start my solution I have a System.InvalidOperationException without any other message. I have also tried this solution https://social.technet.microsoft.com/wiki/contents/articles/53408.vb-net-dynamically-load-assemblies.aspx without luck.Any idea for solving?


问:
Calling a stored function using postgres dblink
I am trying to execute a function dev.dev_support_process in a different database of same instance using the dblink</p>
```<code>select
 *
from
   dblink('port=5432 dbname=dev host=postgres.database.azure.com user=dev@pgsql-dev-db password=dev123' ,
'SELECT * FROM dev.dev_support_process ( ''support'' )');

Also tried the same command with dblink_exec.

Getting the same error from the functions exceptional part. Can anyone help me on this.

Postgres version 11.4

I tried but getting below error.

ERROR: function dev_support_log_message(character varying, unknown) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. CONTEXT: while executing command on unnamed dblink connection PL/pgSQL function dev.dev_support_process(text) line 26 at PERFORM

dev_support_log_message is the function called inside the dev_support_process as a exception part.

I verified the user is having access to execute the function and can execute manually. I am getting the error only when I am trying from this dblink.

Thanks in advance.
</code>```

Body:
I am trying to execute a function dev.dev_support_process in a different database of same instance using the dblink

select
 *
from
   dblink('port=5432 dbname=dev host=postgres.database.azure.com user=dev@pgsql-dev-db password=dev123' ,
'SELECT * FROM dev.dev_support_process ( ''support'' )');

Also tried the same command with dblink_exec.

Getting the same error from the functions exceptional part. Can anyone help me on this.

Postgres version 11.4

I tried but getting below error.

ERROR: function dev_support_log_message(character varying, unknown) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. CONTEXT: while executing command on unnamed dblink connection PL/pgSQL function dev.dev_support_process(text) line 26 at PERFORM

dev_support_log_message is the function called inside the dev_support_process as a exception part.

I verified the user is having access to execute the function and can execute manually. I am getting the error only when I am trying from this dblink.

Thanks in advance.


问:
CORS preflight did not succeed with Spring Boot and Kotlin
I have a Spring Boot application using version 2.7.6 and Kotlin.
I have a frontend built with Angular and I'm trying to send requests to my backend.
I use Spring Security in my project.
I am having trouble setting a CORS configuration to allow my Angular frontend to send requests to the backend while developping both.

From my research online, it seems like I need a CORS configuration to allow the two to communicate while in development mode.

This is the CORS configuration I have added to my project:

@Configuration
@EnableWebMvc
class CorsConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
    }
}
```
<p>This is how I set up the CORS configuration in my <code>WebSecurityConfig</code>:</p>
<pre class="lang-kotlin prettyprint-override"><code>@EnableWebSecurity
@Configuration
class SecurityConfig @Autowired constructor(
    val authTokenFilter: AuthTokenFilter
){

    @Bean
    @Throws(Exception::class)
    fun filterChain(http: HttpSecurity): SecurityFilterChain? {
        http
            .httpBasic().disable()
            .csrf().disable()
            .cors()
                .and()
            .authorizeRequests()
                .anyRequest().permitAll()
                .and()
            .httpBasic()

        http
            .addFilterBefore(authTokenFilter, WebAsyncManagerIntegrationFilter::class.java)
        return http.build()
    }
}
</code>```

I have tried using the @CrossOrigin annotation on the controller level like specified here but it doesn't seem to work either.

I have found this similar issue and the proposed solutions doesn't work either.

I have also tried both solutions provided by this answer to a similar issue but it still doesn't work.

My Spring Boot application doesn't log any error.
The only thing I can see is in my developer tools on my navigator like so:

The request passes through via Postman and it seems like I need to allow OPTIONS preflight. I have tried adding them to my SecurityConfig doing http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll() but it doesn't work either.

Does anyone know what I'm doing wrong or how I should configure the CORS to be disabled throughout my application?

Body:
I have a Spring Boot application using version 2.7.6 and Kotlin.
I have a frontend built with Angular and I'm trying to send requests to my backend.
I use Spring Security in my project.
I am having trouble setting a CORS configuration to allow my Angular frontend to send requests to the backend while developping both.

From my research online, it seems like I need a CORS configuration to allow the two to communicate while in development mode.

This is the CORS configuration I have added to my project:

@Configuration
@EnableWebMvc
class CorsConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
    }
}

This is how I set up the CORS configuration in my WebSecurityConfig:

@EnableWebSecurity
@Configuration
class SecurityConfig @Autowired constructor(
    val authTokenFilter: AuthTokenFilter
){

    @Bean
    @Throws(Exception::class)
    fun filterChain(http: HttpSecurity): SecurityFilterChain? {
        http
            .httpBasic().disable()
            .csrf().disable()
            .cors()
                .and()
            .authorizeRequests()
                .anyRequest().permitAll()
                .and()
            .httpBasic()

        http
            .addFilterBefore(authTokenFilter, WebAsyncManagerIntegrationFilter::class.java)
        return http.build()
    }
}

I have tried using the @CrossOrigin annotation on the controller level like specified here but it doesn't seem to work either.

I have found this similar issue and the proposed solutions doesn't work either.

I have also tried both solutions provided by this answer to a similar issue but it still doesn't work.

My Spring Boot application doesn't log any error.
The only thing I can see is in my developer tools on my navigator like so:

The request passes through via Postman and it seems like I need to allow OPTIONS preflight. I have tried adding them to my SecurityConfig doing http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll() but it doesn't work either.

Does anyone know what I'm doing wrong or how I should configure the CORS to be disabled throughout my application?


问:
How to get string, wich is after a certain string in a text
Am looking to get a certain part of a textfile, wich changes with each file, the very part infront of it doesnt however, and it only occurs once in the whole file (in this case it's a HTML file and im writing a simple automation program, wich gets that text (and some other variables) and stores them into a .csv).

Was searching all day for an Answer, sadly didn't find anything useful. Thanks in Advance!


问:
String to Enum Graphql

hey I have the attribute fields as seen in the picture, I need to switch the type of status from string to enum for GraphQL. Unfortunately I have no clue how I can implement it.

Tried just to replace string with enum.

Title: String to Enum Graphql


问:
Find returning nothing because of how I define a range
I am new to vba, so sometimes I don't know fully how the programming language works.

I am having trouble with a code which is suposed to get me the address of a cell based on a condition. When I apply .find() whith a generic and non dynamic range it works but when I try to use SpecialCells(xlCellTypeLastCell) and insert the last row as the end of my range in the .find(), it my variable returns nothing.

if I run the code like this:

```<code>Sub teste1()
Dim aux As Long
Dim aux2 As Range
Dim LR As Long

'LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row

aux = ThisWorkbook.Worksheets("namedsheet").Range("A1").Value
With ThisWorkbook.Worksheets("Namedsheet").Range("A2:A1000") ' & LR)
    Set aux2 = .Find(What:=aux)
    If Not aux2 Is Nothing Then
        Cell_Split_R = Split(aux2.Address(ReferenceStyle:=xlR1C1), "R")
        Cell_Split_C = Split(Cell_Split_R(1), "C")
        SCol = CLng(Cell_Split_C(0))
        SRow = CLng(Cell_Split_C(1))
    End If
End With

ThisWorkbook.Worksheets("namedsheet2").Cells(1, 1).Value = _
    ThisWorkbook.Worksheets("namedsheet").Cells(SCol, SRow).Value
MsgBox "terminou"
End Sub
</code>```

it works.

but it I try to make a little more dynamic, with the SpecialCells, it does not work:

```<code>Sub teste1()
Dim aux As Long
Dim aux2 As Range
Dim LR As Long

LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row

aux = ThisWorkbook.Worksheets("namedsheet").Range("A1").Value
With ThisWorkbook.Worksheets("namedsheet").Range("A2:A" & LR)
    Set aux2 = .Find(What:=aux)
    If Not aux2 Is Nothing Then
        Cell_Split_R = Split(aux2.Address(ReferenceStyle:=xlR1C1), "R")
        Cell_Split_C = Split(Cell_Split_R(1), "C")
        SCol = CLng(Cell_Split_C(0))
        SRow = CLng(Cell_Split_C(1))
    End If
End With

ThisWorkbook.Worksheets("namedsheet2").Cells(1, 1).Value = _
    ThisWorkbook.Worksheets("namedsheet").Cells(SCol, SRow).Value
MsgBox "terminou"
End Sub
</code>```

I am expecting the range to go to the last cell with non blank values, and make it the range to apply the find method.
Right now when I do the second way the aux2 returns nothing, because the range is defined incorrectly.

Body:
I am new to vba, so sometimes I don't know fully how the programming language works.

I am having trouble with a code which is suposed to get me the address of a cell based on a condition. When I apply .find() whith a generic and non dynamic range it works but when I try to use SpecialCells(xlCellTypeLastCell) and insert the last row as the end of my range in the .find(), it my variable returns nothing.

if I run the code like this:

Sub teste1()
Dim aux As Long
Dim aux2 As Range
Dim LR As Long

'LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row

aux = ThisWorkbook.Worksheets("namedsheet").Range("A1").Value
With ThisWorkbook.Worksheets("Namedsheet").Range("A2:A1000") ' & LR)
    Set aux2 = .Find(What:=aux)
    If Not aux2 Is Nothing Then
        Cell_Split_R = Split(aux2.Address(ReferenceStyle:=xlR1C1), "R")
        Cell_Split_C = Split(Cell_Split_R(1), "C")
        SCol = CLng(Cell_Split_C(0))
        SRow = CLng(Cell_Split_C(1))
    End If
End With

ThisWorkbook.Worksheets("namedsheet2").Cells(1, 1).Value = _
    ThisWorkbook.Worksheets("namedsheet").Cells(SCol, SRow).Value
MsgBox "terminou"
End Sub

it works.

but it I try to make a little more dynamic, with the SpecialCells, it does not work:

Sub teste1()
Dim aux As Long
Dim aux2 As Range
Dim LR As Long

LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row

aux = ThisWorkbook.Worksheets("namedsheet").Range("A1").Value
With ThisWorkbook.Worksheets("namedsheet").Range("A2:A" & LR)
    Set aux2 = .Find(What:=aux)
    If Not aux2 Is Nothing Then
        Cell_Split_R = Split(aux2.Address(ReferenceStyle:=xlR1C1), "R")
        Cell_Split_C = Split(Cell_Split_R(1), "C")
        SCol = CLng(Cell_Split_C(0))
        SRow = CLng(Cell_Split_C(1))
    End If
End With

ThisWorkbook.Worksheets("namedsheet2").Cells(1, 1).Value = _
    ThisWorkbook.Worksheets("namedsheet").Cells(SCol, SRow).Value
MsgBox "terminou"
End Sub

I am expecting the range to go to the last cell with non blank values, and make it the range to apply the find method.
Right now when I do the second way the aux2 returns nothing, because the range is defined incorrectly.


问:
django model override save m2m field
I want to update m2m field on save() method

I have the following model:

```<code>class Tag(models.Model):
    label = models.CharField(max_length=50)
    parents_direct = models.ManyToManyField("Tag", related_name="children", blank=True)
    created = models.DateTimeField(auto_now_add=True)
    description = models.TextField(null=True, blank=True)
    administrators = models.ManyToManyField(
        to=KittyUser, related_name="administrated_tags", blank=True)
    moderators = models.ManyToManyField(
        to=KittyUser, related_name="moderated_tags", blank=True)
    allowed_users = models.ManyToManyField(
        to=KittyUser, related_name="allowed_tags", blank=True)
    visible = models.BooleanField(default=True, verbose_name="visible to anyone")
    POSTABILITY_CHOICES = (
        ('0', 'any allowed user can post'),
        ('1', 'only moderators\\admins can post')
    )
    postability_type = models.CharField(default='0',
                                        max_length=1,
                                        choices=POSTABILITY_CHOICES)

    parents_tree = models.ManyToManyField("Tag", related_name="parents_tree_in_for", blank=True)
    related_tags = models.ManyToManyField("Tag", related_name="related_tags_in_for", blank=True)

    def save(self, *args, **kwargs):
        self.label="overriden label"
        super(Tag, self).save(*args, **kwargs)
        self.parents_tree.add(*self.parents_direct.all())
        breakpoint()
        super(Tag, self).save(*args, **kwargs)

</code>```

Through django-admin the tags get created, the label substitution works, though parents_tree don't get updated.

If I create it from the shell, it is swearing at the second super().save:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "posts_tag_pkey"

If you take away the first super.save(), you get the following:
 "<Tag: overriden label>" needs to have a value for field "id" before this many-to-many relationship can be used.
in both shell and admin.

The question is, how to update my m2m field on save?

Another question is why does it work differently in admin panel and shell?

As a temporary solution I managed to listen to the signal of updating parents_direct field, but what if I wanted to depend on non-m2m fields?

```<code>from django.db.models.signals import m2m_changed

def tag_set_parents_tree(sender, **kwargs):
    if kwargs['action'] == 'post_add' or 'post_remove':
        parents_direct = kwargs['instance'].parents_direct.all()
        if parents_direct:
            kwargs['instance'].parents_tree.set(parents_direct)
            for tag in parents_direct:
                kwargs['instance'].parents_tree.add(*tag.parents_tree.all())
        else:
            kwargs['instance'].parents_tree.clear()

m2m_changed.connect(tag_set_parents_tree, sender=Tag.parents_direct.through)
</code>```

Title: django model override save m2m field

Body:
I want to update m2m field on save() method

I have the following model:

class Tag(models.Model):
    label = models.CharField(max_length=50)
    parents_direct = models.ManyToManyField("Tag", related_name="children", blank=True)
    created = models.DateTimeField(auto_now_add=True)
    description = models.TextField(null=True, blank=True)
    administrators = models.ManyToManyField(
        to=KittyUser, related_name="administrated_tags", blank=True)
    moderators = models.ManyToManyField(
        to=KittyUser, related_name="moderated_tags", blank=True)
    allowed_users = models.ManyToManyField(
        to=KittyUser, related_name="allowed_tags", blank=True)
    visible = models.BooleanField(default=True, verbose_name="visible to anyone")
    POSTABILITY_CHOICES = (
        ('0', 'any allowed user can post'),
        ('1', 'only moderators\\admins can post')
    )
    postability_type = models.CharField(default='0',
                                        max_length=1,
                                        choices=POSTABILITY_CHOICES)

    parents_tree = models.ManyToManyField("Tag", related_name="parents_tree_in_for", blank=True)
    related_tags = models.ManyToManyField("Tag", related_name="related_tags_in_for", blank=True)

    def save(self, *args, **kwargs):
        self.label="overriden label"
        super(Tag, self).save(*args, **kwargs)
        self.parents_tree.add(*self.parents_direct.all())
        breakpoint()
        super(Tag, self).save(*args, **kwargs)

Through django-admin the tags get created, the label substitution works, though parents_tree don't get updated.

If I create it from the shell, it is swearing at the second super().save:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "posts_tag_pkey"

If you take away the first super.save(), you get the following:
 "<Tag: overriden label>" needs to have a value for field "id" before this many-to-many relationship can be used.
in both shell and admin.

The question is, how to update my m2m field on save?

Another question is why does it work differently in admin panel and shell?

As a temporary solution I managed to listen to the signal of updating parents_direct field, but what if I wanted to depend on non-m2m fields?

from django.db.models.signals import m2m_changed

def tag_set_parents_tree(sender, **kwargs):
    if kwargs['action'] == 'post_add' or 'post_remove':
        parents_direct = kwargs['instance'].parents_direct.all()
        if parents_direct:
            kwargs['instance'].parents_tree.set(parents_direct)
            for tag in parents_direct:
                kwargs['instance'].parents_tree.add(*tag.parents_tree.all())
        else:
            kwargs['instance'].parents_tree.clear()

m2m_changed.connect(tag_set_parents_tree, sender=Tag.parents_direct.through)


问:
How to eliminate no-neighbour data when doing spatial clustering
Hello wonderful people!

I'm trying to run a cluster analysis on some data that I've mapped on a choropleth map. It's the % participation rates per constituency.

I'm trying to run a Moran_result test, but am unable to get the data in list format. I keep getting the error: "Error in nb2listw(nb) : Empty neighbour sets found".

I assume this is because some constituencies (like the Isle of White) have no neighbours. I can't find online what constituencies are islands or have no neighbours, and wondered if there is a speedier way to by-pass solve this issue in R, rather than googling all 573 England and Wales constituencies.

Can you help?

Ideas: I thought that maybe I could create "fake" polygons to surround all constituencies with no value so at the very least they could be listed. Or maybe there is a way of searching which have no neighbours and then removing them? Both of these I'm unsure how to do.

My goal: I wan't to get a few spatial clusters where the participation rates are similar and then extract that data so I can compare it to a regression model I have. If you know of another way to do this, other than above, please let me know.

I've tried: new_dataframe <- filter(election_merged_sf, !is.na(nb), but this doesn't actually remove any objects. I assume this is because it is testing whether there are numeric neighbours, when it needs to be done spatially.


问:
Abaqus Python: Access the scalar value of the first element in tuple
In the Abaqus Viewer scripting console, I am struggling to retrieve the scalar from the first element of the tuple in the results odb file.

```<code>(tmpField_MISESONLY, tmpIndex_MISESONLY) = maxEnvelope([s0f1_MISESONLY])
>>>

type(tmpField_MISESONLY)
>>>SCALAR

tmpField_MISESONLY
>>>maxEnvelope( session.openOdb(r'path').steps['Step-4'].frames[1].fieldOutputs['MISESONLY'], )[0]
</code>```

Not sure where the error is. Have I missed something?

Body:
In the Abaqus Viewer scripting console, I am struggling to retrieve the scalar from the first element of the tuple in the results odb file.

(tmpField_MISESONLY, tmpIndex_MISESONLY) = maxEnvelope([s0f1_MISESONLY])
>>>

type(tmpField_MISESONLY)
>>>SCALAR

tmpField_MISESONLY
>>>maxEnvelope( session.openOdb(r'path').steps['Step-4'].frames[1].fieldOutputs['MISESONLY'], )[0]

Not sure where the error is. Have I missed something?


问:
compare a audio file (edited) to a video file (not edited) and remove the difference in python
I am very new to python programming
I am suck at this problem kindly help

I have so much data from recorded audios and videos

audios and videos are recorded in the same environment at the same time.

someone only edited the audio files and removed all the mistakes from them. but video files are not edited I want this this code to remove the difference (mistakes present in video file) between them and its not working.
code:

```<code>import numpy as np
import soundfile as sf
import moviepy.editor as mp

def remove_difference(audio_file, video_file):
    # read audio file
    data1, rate1 = sf.read(audio_file, dtype='int16')

    # get audio data from video file
    video = mp.VideoFileClip(video_file)
    audio = video.audio
    data2, rate2 = sf.read(audio.fps==rate1)

    # ensure audio files have same sample rate and same length
    if rate1 != rate2:
        raise ValueError("Sample rates of audio files do not match")
    if data1.shape[0] != data2.shape[0]:
        min_length = min(data1.shape[0], data2.shape[0])
        data1 = data1[:min_length]
        data2 = data2[:min_length]
    # calculate difference between audio files
    difference = data1 - data2

    # remove difference from audio1
    data1 = data1 - difference

    # create a new video clip with the modified audio
    new_audio = mp.AudioClip(data1, fps=rate1)
    final_video = mp.VideoClip(lambda t: video.get_frame(t), audio=new_audio)

    # save new video file
    final_video.write_videofile("output.mp4", fps=video.fps)

# example usage
remove_difference("audio1.wav", "video2.mp4")
</code>```

Body:
I am very new to python programming
I am suck at this problem kindly help

I have so much data from recorded audios and videos

audios and videos are recorded in the same environment at the same time.

someone only edited the audio files and removed all the mistakes from them. but video files are not edited I want this this code to remove the difference (mistakes present in video file) between them and its not working.
code:

import numpy as np
import soundfile as sf
import moviepy.editor as mp

def remove_difference(audio_file, video_file):
    # read audio file
    data1, rate1 = sf.read(audio_file, dtype='int16')

    # get audio data from video file
    video = mp.VideoFileClip(video_file)
    audio = video.audio
    data2, rate2 = sf.read(audio.fps==rate1)

    # ensure audio files have same sample rate and same length
    if rate1 != rate2:
        raise ValueError("Sample rates of audio files do not match")
    if data1.shape[0] != data2.shape[0]:
        min_length = min(data1.shape[0], data2.shape[0])
        data1 = data1[:min_length]
        data2 = data2[:min_length]
    # calculate difference between audio files
    difference = data1 - data2

    # remove difference from audio1
    data1 = data1 - difference

    # create a new video clip with the modified audio
    new_audio = mp.AudioClip(data1, fps=rate1)
    final_video = mp.VideoClip(lambda t: video.get_frame(t), audio=new_audio)

    # save new video file
    final_video.write_videofile("output.mp4", fps=video.fps)

# example usage
remove_difference("audio1.wav", "video2.mp4")


问:
Odoo 13 : How to display selection field in kanban view based on Qweb and color transformation?
This is the first time I am using Qweb for Odoo XML. My code is not working as intendent due to lack of experience I guess. Thank you very much in advance.

I have a selection field :

```<code>priority = fields.Selection([('critical', 'Critical'), ('urgent', 'Urgent'), ('low', 'Low')], tracking=True, help="You can give your tas a priority")
</code>```

So every selection has a different color in my form view :

```<code> <field name="priority" decoration-danger="priority =='critical'" decoration-success="priority =='low'" decoration-warning="priority=='urgent'" class="o_project_name oe_inline"/>
</code>```

I want to display the colored priority in my kanban view, but its not working as intendent :

```<code> <record id="todo_kanban" model="ir.ui.view">
    <field name="name">todo.kanban</field>
    <field name="model">todo</field>
    <field name="arch" type="xml">
        <kanban default_group_by ="stage_id" class="o_kanban_small_column o_kanban_project_tasks" on_create="quick_create" >
            <field name="todo_id"/>
            <field name="user_id"/>
            <field name="priority"/>
            <templates>
                <t t-name="kanban-box">
                    <div class="oe_kanban_details">
                        <strong class="o_kanban_record_title"><field name="todo_id"/></strong>
                        <div class="o_kanban_tags_section"/>
                        <ul>
                            <li>User : <field name="user_id"/></li>
                            <li>Priority : <field name="priority"/>
                                    <t t-if="priority == 'critial'">
                                        <t t-set="style" t-value="'color:red'" />
                                    </t>
                                    <t t-if="priority == 'urgent'">
                                        <t t-set="style" t-value="'color:orange'" />
                                    </t>
                                    <t t-if="priority == 'low'">
                                        <t t-set="style" t-value="'color:green'" />
                                    </t>
                            </li>
                        </ul>
                    </div>
                </t>
            </templates>
        </kanban>
    </field>
</record>
</code>```

Body:
This is the first time I am using Qweb for Odoo XML. My code is not working as intendent due to lack of experience I guess. Thank you very much in advance.

I have a selection field :

priority = fields.Selection([('critical', 'Critical'), ('urgent', 'Urgent'), ('low', 'Low')], tracking=True, help="You can give your tas a priority")

So every selection has a different color in my form view :

 <field name="priority" decoration-danger="priority =='critical'" decoration-success="priority =='low'" decoration-warning="priority=='urgent'" class="o_project_name oe_inline"/>

I want to display the colored priority in my kanban view, but its not working as intendent :

 <record id="todo_kanban" model="ir.ui.view">
    <field name="name">todo.kanban</field>
    <field name="model">todo</field>
    <field name="arch" type="xml">
        <kanban default_group_by ="stage_id" class="o_kanban_small_column o_kanban_project_tasks" on_create="quick_create" >
            <field name="todo_id"/>
            <field name="user_id"/>
            <field name="priority"/>
            <templates>
                <t t-name="kanban-box">

                        <field name="todo_id"/>

User : <field name="user_id"/>

Priority : <field name="priority"/>
                                    <t t-if="priority == 'critial'">
                                        <t t-set="style" t-value="'color:red'" />
                                    </t>
                                    <t t-if="priority == 'urgent'">
                                        <t t-set="style" t-value="'color:orange'" />
                                    </t>
                                    <t t-if="priority == 'low'">
                                        <t t-set="style" t-value="'color:green'" />
                                    </t>

                </t>
            </templates>
        </kanban>
    </field>
</record>


问:
How to get cpu, memory used by a process launched via the Java process API?
Hi I need to start a Linux process from the Java API (ProcessBuilder.start()). Is there some way I can monitor this child process for memory, cpu usage etc? I will be starting more than one process at any one time.</p>


问:
One quadrant multiplier and Four quadrant multip
I am studying Advance electronics subject and i came across topics one quadrant multiplier and four quadrant multiplier. What i can't understand is that how one quadrant multiplier can operate on only when both inputs are positive (eg: +2 and +1 ) but cannot operate when input voltages are both negative and opposite polarity (+-, -+, --) and four quadrant multiplier can operate on all four possible input values (++, -+ ,+-, --). I will be very happy for your explanation. Thank you.
[Four quadrant multiplierone quadrant multiplier](https://i.stack.imgur.com/Bkg2H.jpg)

I just don't understand how one quadrant multiplier cannot operate when inputs are +-, -+ or --. I just want explanation how it cannot operate on these values and also how four quadrant multiplier can operate on those values.


问:
Modify how specific numbers are displayed using print in numpy
I would like to modify the appearance of numpy arrays, so that specific numbers are displayed in a different way. In my specific case, I would like each number 0 in an array to be displayed as character e, and each -math.inf to be seen as the Greek character epsilon (ε or, in unicode, \u03B5).

For instance, when I run the following code

```<code>A = np.array([[10,1,541],[0,5000,-math.inf]])
print(A)
</code>```

I would like to obtain

```<code>[[10    1 541]
 [ e 5000   ε]]
</code>```

I've already tried to play around a bit with numpy.set_printoptions and the best I could do is:

```<code># create a function that returns 'ε' if x is -inf, 'e' if x is 0, 'x' otherwise
my_format_function = lambda x: '\u03B5' if x==-math.inf else ('e' if x==0 else str(x))

# set the function as formatter for numpy's printing options
numpy.set_printoptions(formatter={'all':my_format_function})

# test
A = np.array([[10,1,541],[0,5000,-math.inf]])
print(A)
</code>```

but this scrambles the nice default format offered by numpy (e.g., indentation); I get:

```<code>[[10.0 1.0 541.0]
 [e 5000.0 ε]]
</code>```

which is not particularly pleasant.

Body:
I would like to modify the appearance of numpy arrays, so that specific numbers are displayed in a different way. In my specific case, I would like each number 0 in an array to be displayed as character e, and each -math.inf to be seen as the Greek character epsilon (ε or, in unicode, \u03B5).

For instance, when I run the following code

A = np.array([[10,1,541],[0,5000,-math.inf]])
print(A)

I would like to obtain

[[10    1 541]
 [ e 5000   ε]]

I've already tried to play around a bit with numpy.set_printoptions and the best I could do is:

# create a function that returns 'ε' if x is -inf, 'e' if x is 0, 'x' otherwise
my_format_function = lambda x: '\u03B5' if x==-math.inf else ('e' if x==0 else str(x))

# set the function as formatter for numpy's printing options
numpy.set_printoptions(formatter={'all':my_format_function})

# test
A = np.array([[10,1,541],[0,5000,-math.inf]])
print(A)

but this scrambles the nice default format offered by numpy (e.g., indentation); I get:

[[10.0 1.0 541.0]
 [e 5000.0 ε]]

which is not particularly pleasant.


问:
how to work reusable state in class components?
do class components support Reusable State in React 18? I wrote an example

  componentDidMount() {
    console.log("componentDidMount");
    if (!this.mounted) {
      this.fetchData();
      this.mounted = true;
    }
  }

  fetchData() {
    fetch().then((data) => {
      this.setState((statePrev) => {
        console.log("prev data", statePrev); // always null after editing the file of this component and triggering Fast Refresh, how to work reusable state in class components?
        return {
          data: [
            ...(Array.isArray(statePrev?.data) ? statePrev?.data : []),
            ...data
          ]
        };
      });
    });
  }
```

I expected that when I edit and save the component file and React Refresh is triggered then statePrev will contain the previous state but it is always null

second problem is when React Refresh is triggered, the this.mounted property also does not work to determine that the mounting has occurred and you do not need to run fetch again

Body:
do class components support Reusable State in React 18? I wrote an example

  componentDidMount() {
    console.log("componentDidMount");
    if (!this.mounted) {
      this.fetchData();
      this.mounted = true;
    }
  }

  fetchData() {
    fetch().then((data) => {
      this.setState((statePrev) => {
        console.log("prev data", statePrev); // always null after editing the file of this component and triggering Fast Refresh, how to work reusable state in class components?
        return {
          data: [
            ...(Array.isArray(statePrev?.data) ? statePrev?.data : []),
            ...data
          ]
        };
      });
    });
  }

I expected that when I edit and save the component file and React Refresh is triggered then statePrev will contain the previous state but it is always null

second problem is when React Refresh is triggered, the this.mounted property also does not work to determine that the mounting has occurred and you do not need to run fetch again