问:
Server returned HTTP response code: 400 received on Chinese Website that was working until July 25,2022 but has failed since
I support a ERP system that requires are China Site to update Exchange Rates at the end of the month.
A JAVA Class is ran everyday to extract those exchange rates from  http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html

After July 25 2022 the routine returns java.io.IOException: Server returned HTTP response code: 400 for URL: http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html

This code was developed by one of our Chinese Employees that is no longer with us. I am not a JAVA programmer, so I am adept at debugging the code.

Here is the code - the error is generated on the conn.getInputStream

```<code>public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            //conn.setRequestProperty("user-agent",
                //    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;

</code>```

Here is how sendPost is called:

```<code>public static void main(String[] args) throws IOException{

    String s1 = ChnExchRate.sendPost("http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html",null );

</code>```

When I paste the offending URL in my browser I reach the website. I can see the exchange rates and can manually enter them in our system.

Body:
I support a ERP system that requires are China Site to update Exchange Rates at the end of the month.
A JAVA Class is ran everyday to extract those exchange rates from  http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html

After July 25 2022 the routine returns java.io.IOException: Server returned HTTP response code: 400 for URL: http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html

This code was developed by one of our Chinese Employees that is no longer with us. I am not a JAVA programmer, so I am adept at debugging the code.

Here is the code - the error is generated on the conn.getInputStream

public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            //conn.setRequestProperty("user-agent",
                //    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;

Here is how sendPost is called:

public static void main(String[] args) throws IOException{

    String s1 = ChnExchRate.sendPost("http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html",null );

When I paste the offending URL in my browser I reach the website. I can see the exchange rates and can manually enter them in our system.


来源: stackexchange

问:
Pythonestic way: How to decide which modules to import with a flag in the constructor?
I'm trying to make a package and I'm figuring out a proper way to do it.
Basically its a cryptographic scheme that internally can operate with  64 bits arithmetic (numpy) or arbitrary precision arithmetic (mpmath).
So I made one module for the scheme (encryption, decryption, etc.) and one for all the "math" or special functions for each arithmetic (multiplication of polynomials, roots, etc.).

My approach was that in the constructor of the class scheme of the main file (scheme.py), the user can use a variable flag that if True it use one type of arithmetic and its False it use the other one.
So basically the constructor define which module imports.
I test this and it works, but when I make it like a package and import the package it stop working.
Errors like no module named arithmetic.

what I'm not seeing and how I fix it?
Which is the "Pythonestic" way to do something like this be free to tell me.
Now I'm simply making one arithmetic file, and that each function has these flag with an if....

Here is a dummy example that works:

example.py:

```<code>import scheme as sc

Arb_Arithmetic = sc.Scheme(False)
Arb_Arithmetic.sum()

Arithmetic_64= sc.Scheme(True)
Arithmetic_64.sum()
</code>```

scheme.py:

```<code>class Scheme():
    def __init__(self, flag):
        if flag:
            import arithmetic64 as ar
        else:
            import arithmetic as ar
        self.ar = ar
    def sum(self):
        self.ar.test()
</code>```

arithmetic.py:

```<code>def test():
    print("Arbitrary precision arithmetic")
</code>```

arithmetic64.py:

```<code>def test():
    print("64 bits arithmetic")
</code>```

My package structure is:

```<code>python_packace:
|---package_name:
|    |--- scheme.py
|    |--- arithmetic.py
|    |--- arithmetic64.py
|    |--- __init__.py (empty)
|--- setup.py

</code>```

setup.py (also I try several things like using pyproject.toml)

```<code>from setuptools import setup

VERSION = '1.0.0'
DESCRIPTION = 'scheme '

# Setting up
setup(
    name="package", # the name of it
    version=VERSION,
    author="mmazz",
    author_email="<asd@gmail.com>",
    description=DESCRIPTION,
    packages=find_packages(),
    install_requires=['numpy', 'mpmath'],
    classifiers=[
        "Development Status :: 1 - Planning",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
        "Operating System :: Unix",
    ]
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a package and I'm figuring out a proper way to do it.
Basically its a cryptographic scheme that internally can operate with  64 bits arithmetic (numpy) or arbitrary precision arithmetic (mpmath).
So I made one module for the scheme (encryption, decryption, etc.) and one for all the "math" or special functions for each arithmetic (multiplication of polynomials, roots, etc.).

My approach was that in the constructor of the class scheme of the main file (scheme.py), the user can use a variable flag that if True it use one type of arithmetic and its False it use the other one.
So basically the constructor define which module imports.
I test this and it works, but when I make it like a package and import the package it stop working.
Errors like no module named arithmetic.

what I'm not seeing and how I fix it?
Which is the "Pythonestic" way to do something like this be free to tell me.
Now I'm simply making one arithmetic file, and that each function has these flag with an if....

Here is a dummy example that works:

example.py:

import scheme as sc

Arb_Arithmetic = sc.Scheme(False)
Arb_Arithmetic.sum()

Arithmetic_64= sc.Scheme(True)
Arithmetic_64.sum()

scheme.py:

class Scheme():
    def __init__(self, flag):
        if flag:
            import arithmetic64 as ar
        else:
            import arithmetic as ar
        self.ar = ar
    def sum(self):
        self.ar.test()

arithmetic.py:

def test():
    print("Arbitrary precision arithmetic")

arithmetic64.py:

def test():
    print("64 bits arithmetic")

My package structure is:

python_packace:
|---package_name:
|    |--- scheme.py
|    |--- arithmetic.py
|    |--- arithmetic64.py
|    |--- __init__.py (empty)
|--- setup.py

setup.py (also I try several things like using pyproject.toml)

from setuptools import setup

VERSION = '1.0.0'
DESCRIPTION = 'scheme '

# Setting up
setup(
    name="package", # the name of it
    version=VERSION,
    author="mmazz",
    author_email="<asd@gmail.com>",
    description=DESCRIPTION,
    packages=find_packages(),
    install_requires=['numpy', 'mpmath'],
    classifiers=[
        "Development Status :: 1 - Planning",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
        "Operating System :: Unix",
    ]
)


问:
Flutter web - failures - ChromeProxyService: Failed to evaluate expression - MissingPlugin Exception
I am modifying my app to web app. The web starts but crash straightaway when degub or release.
2 failure types are occuring.

flutter_callkit - MissingPlugin Exception.

```<code>  flutter_callkit_incoming:
    dependency: "direct main"
    description:
      name: flutter_callkit_incoming
      url: "https://pub.dartlang.org"
    source: hosted
    version: "1.0.2+1"
</code>```

ChromeProxyService: Failed to evaluate expression - Authentication

I added -->  /firebase-auth.js

```<code>  </script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
    <!-- Firebase Auth SDK -->
    <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-auth.js"></script>
  <script src="main.dart.js" type="application/javascript"></script>
  <script>
    var firebaseConfig = {
      apiKey: "xx",
  authDomain: "xxx",
  databaseURL: "xxx",
  projectId: "xxx",
  storageBucket: "xx",
  messagingSenderId: "xxxx",
  appId: "xxx",
  measurementId: "xxxx"
    };
</code>```

I added the condition for web after Run App

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dotenv.load(fileName: '.env');
    if (kIsWeb) {
  await Firebase.initializeApp(
    options: const FirebaseOptions(
  apiKey: "AIzaSyDUgmLh1cCpiygA7NHlBAfAckRA1KfrTtE",
  authDomain: "tarot-card-subconex.firebaseapp.com",
  databaseURL: "https://tarot-card-subconex-default-rtdb.europe-west1.firebasedatabase.app",
  projectId: "tarot-card-subconex",
  storageBucket: "tarot-card-subconex.appspot.com",
  messagingSenderId: "504704241379",
  appId: "1:504704241379:web:f394d21c0f3daf61497fd6",
  measurementId: "G-RZT62K09QD"
      ),
  );
} else {
  await Firebase.initializeApp();}

</code>```

Body:
I am modifying my app to web app. The web starts but crash straightaway when degub or release.
2 failure types are occuring.

flutter_callkit - MissingPlugin Exception.

  flutter_callkit_incoming:
    dependency: "direct main"
    description:
      name: flutter_callkit_incoming
      url: "https://pub.dartlang.org"
    source: hosted
    version: "1.0.2+1"

ChromeProxyService: Failed to evaluate expression - Authentication

I added -->  /firebase-auth.js

  </script>


问:
Get random effect intercept value for every level in statsmodels
I'm going through a tutorial on mixed-effects models in Python.

I'm building a model where litter is the random effect.  In the tutorial, the output contains the variance across the litter intercepts.  However, in Bayesian hierarchical modeling, I'm also able to see the intercepts for every level of the random effect variable.

How would I see that here?

```<code>import pandas as pd
import statsmodels.api as sm
import scipy.stats as stats
import statsmodels.formula.api as smf

df = pd.read_csv("http://www-personal.umich.edu/~bwest/rat_pup.dat", sep = "\t")

model = smf.mixedlm("weight ~ litsize + C(treatment) + C(sex, Treatment('Male')) + C(treatment):C(sex, Treatment('Male'))",
                    df,
                    groups= "litter").fit()
model.summary()
</code>```

I would also ideally like to see the estimate of the intercept across all litters.  Then, how would I interpret that overall intercept compared to the intercept for each single litter?

If there's a better Python package for what I'm striving for, please suggest.

Body:
I'm going through a tutorial on mixed-effects models in Python.

I'm building a model where litter is the random effect.  In the tutorial, the output contains the variance across the litter intercepts.  However, in Bayesian hierarchical modeling, I'm also able to see the intercepts for every level of the random effect variable.

How would I see that here?

import pandas as pd
import statsmodels.api as sm
import scipy.stats as stats
import statsmodels.formula.api as smf

df = pd.read_csv("http://www-personal.umich.edu/~bwest/rat_pup.dat", sep = "\t")

model = smf.mixedlm("weight ~ litsize + C(treatment) + C(sex, Treatment('Male')) + C(treatment):C(sex, Treatment('Male'))",
                    df,
                    groups= "litter").fit()
model.summary()

I would also ideally like to see the estimate of the intercept across all litters.  Then, how would I interpret that overall intercept compared to the intercept for each single litter?

If there's a better Python package for what I'm striving for, please suggest.


问:
Run sql in Dockerfile starting from exisiting MySQL db image
I am trying to build a new mysql image from an existing one, and then insert some records into the database as part of the build process to create the new image (i.e. new mysql image = old mysql image + extra table records).

I am not able to add an sql file that contains my insert queries to /docker-entrypoint-initdb.d, cause that is not executing the scripts inside that directory (because the starting image already has a /var/lib/mysql dir available?).

I have tried to do something like the following instead:

```<code>FROM my.registry/starting-mysql-img:latest

ADD insert-queries.sql /tmp
RUN mysql -u root mydb < /tmp/insert-queries.sql
</code>```

But I get a

```<code>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) error.
</code>```

What am I doing wrong / is there an alternative way to achieve my I am looking for?

Body:
I am trying to build a new mysql image from an existing one, and then insert some records into the database as part of the build process to create the new image (i.e. new mysql image = old mysql image + extra table records).

I am not able to add an sql file that contains my insert queries to /docker-entrypoint-initdb.d, cause that is not executing the scripts inside that directory (because the starting image already has a /var/lib/mysql dir available?).

I have tried to do something like the following instead:

FROM my.registry/starting-mysql-img:latest

ADD insert-queries.sql /tmp
RUN mysql -u root mydb < /tmp/insert-queries.sql

But I get a

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) error.

What am I doing wrong / is there an alternative way to achieve my I am looking for?


问:
How to create a Clear Button in AntDesign/Blazor RangePicker
My page have two RangePicker, I want to create a button, can clear RangePicker value, but i can't find any way

code

```<code>     <RangePicker TValue="DateTime?[]"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange" />
     <RangePicker TValue="DateTime?[]"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange2" />
</code>```

I set a variable,but it doesn't work

```<code>     <RangePicker TValue="@DateTime1"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange" />
     <RangePicker TValue="@DateTime2"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange2" />
     <Button Type="@AntDesign.ButtonType.Primary" OnClick="reset">reset</Button>
</code>```
```<code>    DateTime?[] DateTime1 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }
    DateTime?[] DateTime2 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }

    public void reset()
    {
        DateTime1 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }
        DateTime2 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }
    }
</code>```

Body:
My page have two RangePicker, I want to create a button, can clear RangePicker value, but i can't find any way

code

     <RangePicker TValue="DateTime?[]"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange" />
     <RangePicker TValue="DateTime?[]"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange2" />

I set a variable,but it doesn't work

     <RangePicker TValue="@DateTime1"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange" />
     <RangePicker TValue="@DateTime2"
                         DefaultValue="new DateTime?[] {  DateTime.Now.AddDays(-7),DateTime.Now}"
                         Ranges="dayRanges"
                         Format="yyyy-MM-dd"
                         OnChange="OnSignTimeRangeChange2" />
     <Button Type="@AntDesign.ButtonType.Primary" OnClick="reset">reset</Button>

    DateTime?[] DateTime1 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }
    DateTime?[] DateTime2 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }

    public void reset()
    {
        DateTime1 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }
        DateTime2 = new DateTime?[] { DateTime.Now.AddDays(-7), DateTime.Now }
    }


问:
convert SignedXML to nodejs algorithm
I'm trying to pass a digital signature implementation in c# with nodejs, the implementation using native c# libraries is the only one that my provider supports, the current implementation is this.

```<code>XmlDocument SignXmlWithP12(XmlDocument xmlDoc, X509Certificate2 cert)
{
`
    //Obtenemos la llave privada del certificado
    var llavePrivada = cert.PrivateKey;

    //Creamos un SignedXml object que contendrá el documento.
    SignedXml xmlFirmado = new SignedXml(xmlDoc);
    //Atachamos la llave privada al SignedXml document.
    xmlFirmado.SigningKey = llavePrivada;
    //Creamos una referencia del documento a ser firmado.
    Reference reference = new Reference();
    reference.Uri = ""; //Todo el documento
                        //Agregamos un enveloped transformation a la referencia.
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true);
    reference.AddTransform(env);
    //Agregamos la referencia al SignedXml object.
    xmlFirmado.AddReference(reference);
    //Creamos un KeyInfo object.
    KeyInfo keyInfo = new KeyInfo();
    //Cargamos el certificado dentro de un KeyInfoX509Data object
    //y luego lo añadimos al KeyInfo object.
    KeyInfoX509Data clause = new KeyInfoX509Data();
    //Opcionalmente se podría agregar el Subject del certificado
    //clause.AddSubjectName(cert.Subject);
    clause.AddCertificate(cert);
    keyInfo.AddClause(clause);
    //Asignamos el KeyInfo object al SignedXml object.
    xmlFirmado.KeyInfo = keyInfo; //Procedemos acomputar la firma.
    xmlFirmado.ComputeSignature();
    //Obtenemos la representación del XML firmado y la guardamos en un XmlElement object
    XmlElement xmlFirmaDigital = xmlFirmado.GetXml();

    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlFirmaDigital, true));
    return xmlDoc;
}`
</code>```

Sample document and how I read it (if I put spaces, the provider rejects the digital signature)

XML DOC

```<code>`<?xml version="1.0" encoding="utf-8"?>
  <SemillaModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <valor>QhpoXB7wtRAeL1eL9OdHPU9JE6WJksKrmWbF5+lJlcpBasy2LlUDbIeScIMUONulTcHcRLsqZUHjLtqMIydpI3j3YQ3skDyQ3yDaiNpg7ME41bbh0e+ETBKoWvhz66Ek/mfeAqLBVw41pR9Sn9b8FQ==</valor>
    <fecha>2022-12-12T15:44:53.6251955-04:00</fecha>
  </SemillaModel>`
</code>```

Code c#

```<code>`try
{
    X509Certificate2 cert = new X509Certificate2(@"x", "y", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
    XmlDocument docx = new XmlDocument();
    docx.Load("response_1670874293557.xml");

    XmlDocument doc2 = SignXmlWithP12(docx, cert);
    XmlTextWriter xmltw = new XmlTextWriter("response_1670874293557_sign_spaces_7.0.xml", new UTF8Encoding(false));
    doc2.WriteTo(xmltw);
    xmltw.Close();
    //  doc2.Save(Console.Out);
    Console.WriteLine("XML file signed.");

}
catch (System.IO.FileNotFoundException)
{

}`
</code>```

This works fine and my provider accepts the signatures I put in this way , however I need to pass this to nodejs .
I currently have an implementation that for some reason gives me a different digestValue

```<code>`const signed=()=>{

    var sig = new SignedXml()
    sig.digestAlgorithm ="http://www.w3.org/2001/04/xmlenc#sha256";
    sig.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
    sig.keyInfoProvider = new keyProvider(public_key)
    sig.canonicalizationAlgorithm = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"

    sig.addReference(`//*[local-name(.)='SemillaModel']`, ["http://www.w3.org/2000/09/xmldsig#enveloped-signature"], "http://www.w3.org/2001/04/xmlenc#sha256", "", "", "", true)

    sig.signingKey =signingKey;
    console.log(sig.getSignatureXml());
    sig.computeSignature(xml)
    fs.writeFileSync(xml_sign, sig.getSignedXml())

}`
</code>```

**
C#**

```<code>`string sha256(string text)
{
    byte[] bytes = Encoding.Unicode.GetBytes(text);
    using (var generator = new SHA256Managed())
    {
        byte[] hash = generator.ComputeHash(bytes);
        return  Convert.ToBase64String(hash);
    }
}`
</code>```
```<code>`const getHash = function (xml) {

  console.log(xml.split('').map(char => char.charCodeAt(0)).join(' '), "end");
  var shasum = crypto.createHash('sha256');
  shasum.update(xml,'ucs2')
  var res = shasum.digest('base64')
  return res
}
`
</code>```

Changing the encoding from utf-8 to ucs2 , the manual implementations without using SignedXml , are the same, but they vary with respect to if I use standard SignedXml, which I don't understand why it could be.

In node I already remove leading whitespaces, clean, also the CRLF , and nothing, to make sure of this, copy the file from c# stdin before using the signature and use the same in node , currently not sure How to proceed, I'm looking to do some kind of reverse ing to the compiled C# libraries, but I see it as quite complicated, anyone with similar experience? .

PS: I found some similar problems when they tried to switch from c# to java, however, just changing the coding was solved... something that doesn't happen in node..

I hope you can help me solve this problem that has me standing...

```<code></code>```

Title: convert SignedXML to nodejs algorithm

Body:
I'm trying to pass a digital signature implementation in c# with nodejs, the implementation using native c# libraries is the only one that my provider supports, the current implementation is this.

XmlDocument SignXmlWithP12(XmlDocument xmlDoc, X509Certificate2 cert)
{
`
    //Obtenemos la llave privada del certificado
    var llavePrivada = cert.PrivateKey;

    //Creamos un SignedXml object que contendrá el documento.
    SignedXml xmlFirmado = new SignedXml(xmlDoc);
    //Atachamos la llave privada al SignedXml document.
    xmlFirmado.SigningKey = llavePrivada;
    //Creamos una referencia del documento a ser firmado.
    Reference reference = new Reference();
    reference.Uri = ""; //Todo el documento
                        //Agregamos un enveloped transformation a la referencia.
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true);
    reference.AddTransform(env);
    //Agregamos la referencia al SignedXml object.
    xmlFirmado.AddReference(reference);
    //Creamos un KeyInfo object.
    KeyInfo keyInfo = new KeyInfo();
    //Cargamos el certificado dentro de un KeyInfoX509Data object
    //y luego lo añadimos al KeyInfo object.
    KeyInfoX509Data clause = new KeyInfoX509Data();
    //Opcionalmente se podría agregar el Subject del certificado
    //clause.AddSubjectName(cert.Subject);
    clause.AddCertificate(cert);
    keyInfo.AddClause(clause);
    //Asignamos el KeyInfo object al SignedXml object.
    xmlFirmado.KeyInfo = keyInfo; //Procedemos acomputar la firma.
    xmlFirmado.ComputeSignature();
    //Obtenemos la representación del XML firmado y la guardamos en un XmlElement object
    XmlElement xmlFirmaDigital = xmlFirmado.GetXml();

    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlFirmaDigital, true));
    return xmlDoc;
}`

Sample document and how I read it (if I put spaces, the provider rejects the digital signature)

XML DOC

`<?xml version="1.0" encoding="utf-8"?>
  <SemillaModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <valor>QhpoXB7wtRAeL1eL9OdHPU9JE6WJksKrmWbF5+lJlcpBasy2LlUDbIeScIMUONulTcHcRLsqZUHjLtqMIydpI3j3YQ3skDyQ3yDaiNpg7ME41bbh0e+ETBKoWvhz66Ek/mfeAqLBVw41pR9Sn9b8FQ==</valor>
    <fecha>2022-12-12T15:44:53.6251955-04:00</fecha>
  </SemillaModel>`

Code c#

`try
{
    X509Certificate2 cert = new X509Certificate2(@"x", "y", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
    XmlDocument docx = new XmlDocument();
    docx.Load("response_1670874293557.xml");

    XmlDocument doc2 = SignXmlWithP12(docx, cert);
    XmlTextWriter xmltw = new XmlTextWriter("response_1670874293557_sign_spaces_7.0.xml", new UTF8Encoding(false));
    doc2.WriteTo(xmltw);
    xmltw.Close();
    //  doc2.Save(Console.Out);
    Console.WriteLine("XML file signed.");

}
catch (System.IO.FileNotFoundException)
{

}`

This works fine and my provider accepts the signatures I put in this way , however I need to pass this to nodejs .
I currently have an implementation that for some reason gives me a different digestValue

`const signed=()=>{

    var sig = new SignedXml()
    sig.digestAlgorithm ="http://www.w3.org/2001/04/xmlenc#sha256";
    sig.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
    sig.keyInfoProvider = new keyProvider(public_key)
    sig.canonicalizationAlgorithm = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"

    sig.addReference(`//*[local-name(.)='SemillaModel']`, ["http://www.w3.org/2000/09/xmldsig#enveloped-signature"], "http://www.w3.org/2001/04/xmlenc#sha256", "", "", "", true)

    sig.signingKey =signingKey;
    console.log(sig.getSignatureXml());
    sig.computeSignature(xml)
    fs.writeFileSync(xml_sign, sig.getSignedXml())

}`

**
C#**

`string sha256(string text)
{
    byte[] bytes = Encoding.Unicode.GetBytes(text);
    using (var generator = new SHA256Managed())
    {
        byte[] hash = generator.ComputeHash(bytes);
        return  Convert.ToBase64String(hash);
    }
}`

`const getHash = function (xml) {

  console.log(xml.split('').map(char => char.charCodeAt(0)).join(' '), "end");
  var shasum = crypto.createHash('sha256');
  shasum.update(xml,'ucs2')
  var res = shasum.digest('base64')
  return res
}
`

Changing the encoding from utf-8 to ucs2 , the manual implementations without using SignedXml , are the same, but they vary with respect to if I use standard SignedXml, which I don't understand why it could be.

In node I already remove leading whitespaces, clean, also the CRLF , and nothing, to make sure of this, copy the file from c# stdin before using the signature and use the same in node , currently not sure How to proceed, I'm looking to do some kind of reverse ing to the compiled C# libraries, but I see it as quite complicated, anyone with similar experience? .

PS: I found some similar problems when they tried to switch from c# to java, however, just changing the coding was solved... something that doesn't happen in node..

I hope you can help me solve this problem that has me standing...


问:
How to get html content of a page after navigating to it in Playwright ? Python
I am visiting a website and navigating to a new page from there. I want html of that page but I am getting the html of old page with page. content().
Can anyone help me out.</p>
```<code> with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()
        page.goto("https://www.espncricinfo.com/", timeout=0)
        page.locator("div[role=\"tooltip\"] >> text=Rankings").click()
        page.wait_for_url("https://www.espncricinfo.com/rankings/content/page/211271.html")
        html = page.content()
        context.close()

        browser.close()
</code>```

Body:
I am visiting a website and navigating to a new page from there. I want html of that page but I am getting the html of old page with page. content().
Can anyone help me out.

 with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()
        page.goto("https://www.espncricinfo.com/", timeout=0)
        page.locator("div[role=\"tooltip\"] >> text=Rankings").click()
        page.wait_for_url("https://www.espncricinfo.com/rankings/content/page/211271.html")
        html = page.content()
        context.close()

        browser.close()


问:
Live-Updating Graph
So I have the following code:

```<code>class GooglePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Google (GOOG)", font=LARGEFONT)
        label.pack(pady=10,padx=10)
        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()
        f = Figure(figsize=(5,5), dpi=100)
        a = f.add_subplot(111)
        a.plot(x, y)
        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
</code>```

So later on in the script, I define x and y to be lists that get 1 more element per second. However, a  does not update. I need to know how to get a to update with x and y.

The first thing I tried was to use a while True loop inside the init function. It didn't run anything after the class declaration of GooglePage, including more class declarations and important stuff. I also tried to update a outside the class declaration, when I updated the lists. However, a, GooglePage.a , and GooglePage.__init__.a all throw errors.

Title: Live-Updating Graph

Body:
So I have the following code:

class GooglePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Google (GOOG)", font=LARGEFONT)
        label.pack(pady=10,padx=10)
        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()
        f = Figure(figsize=(5,5), dpi=100)
        a = f.add_subplot(111)
        a.plot(x, y)
        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

So later on in the script, I define x and y to be lists that get 1 more element per second. However, a  does not update. I need to know how to get a to update with x and y.

The first thing I tried was to use a while True loop inside the init function. It didn't run anything after the class declaration of GooglePage, including more class declarations and important stuff. I also tried to update a outside the class declaration, when I updated the lists. However, a, GooglePage.a , and GooglePage.__init__.a all throw errors.


问:
I Can't Run a Java Module on Android Studio
So I am very much a newcomer to the android studio, so I might've missed a few settings here and there, but
when I try to run a code with created java module, it doesn't recognize any of my code.

I attached the screenshot of what the ide returned to me.

I tried to reinstall the newest version of the android studio with the newest version of SDK (I attached another image file.) several times, but it doesn't seem to go anywhere.

For the SDK tools, I have the followings:

Android SDK Build-Tools

Android Emulator

Android SDK Platform-Tools

Also, I did try Build>Cealn Project.

Does anyone know how to fix this problem?

P.S. Here is my build gradle for the java module.


问:
Works in Unity Remote 5 but not on Phone
```<code> public float shakeThreshold= 1;

 public void Update()
 {
   if(Input.acceleration.magnitude >= shakeThreshold)
    {
      Invoke("Throw", 0.7f);
    }
 }
</code>```

I have a basic code that when I shake my phone invoke the throw method.

It works perfectly fine in unity remote 5 but when I build the game and play on my phone it doesn't work. I checked Player Settings and there are nothing about "Accelerometer" in the settings.

what is the issue here: the code, unity remote, android sdk or my phone?

Body:
 public float shakeThreshold= 1;

 public void Update()
 {
   if(Input.acceleration.magnitude >= shakeThreshold)
    {
      Invoke("Throw", 0.7f);
    }
 }

I have a basic code that when I shake my phone invoke the throw method.

It works perfectly fine in unity remote 5 but when I build the game and play on my phone it doesn't work. I checked Player Settings and there are nothing about "Accelerometer" in the settings.

what is the issue here: the code, unity remote, android sdk or my phone?


问:
Issues with Matplotlib Presentation
I am using Matplotlib to plot a 2x3 grid as follows.

fig, axs = plt.subplots(2, 3, figsize=(12, 6))

Producing each subplot is not an issue but when I run the code cell (I am working in a Jupyter Notebook) I get the following being printed:

```<code>[<matplotlib.lines.Line2D at 0x7f95f8627dd8>]
Out[37]:
Text(0.5, 0, 'log(Temperature)')
Out[37]:
Text(0, 0.5, 'log(Path Length)')
</code>```

How can I make it so that this will not occur when producing graphs and/or subplots.

Title: Issues with Matplotlib Presentation

Body:
I am using Matplotlib to plot a 2x3 grid as follows.

fig, axs = plt.subplots(2, 3, figsize=(12, 6))

Producing each subplot is not an issue but when I run the code cell (I am working in a Jupyter Notebook) I get the following being printed:

[<matplotlib.lines.Line2D at 0x7f95f8627dd8>]
Out[37]:
Text(0.5, 0, 'log(Temperature)')
Out[37]:
Text(0, 0.5, 'log(Path Length)')

How can I make it so that this will not occur when producing graphs and/or subplots.


问:
C# PrincipalServerDownException not execute the handler that I implemented
I've implemented the PrincipalServerDownException handler, but it seems like the program does not execute the handler.

```<code>public void GetData(String domain) {
    try
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain);
        UserPrincipal user = UserPrincipal.Current;
        this.name = user.DisplayName;
        this.nik = user.EmployeeId;
    }
    catch (PrincipalServerDownException)
    {
        Console.WriteLine("Failed to Connect");
        using (StreamReader r = new StreamReader("EmployeeData.json"))
        {

            string json = r.ReadToEnd();
            var semiParsedJson = JArray.Parse(json);

            String locname = Environment.UserName;

            List<EmpData> employeeData = JsonConvert.DeserializeObject<List<EmpData>>(json);

            foreach (var item in employeeData)
            {
                if (item.username == locname)
                {
                    this.name = item.display_name;
                    this.nik = item.nik;
                    break;
                }
            }
        }
    }
}
</code>```

And here the debug error message

```<code>1. Use a debug build configuration or disable the debug option 'Enable Just My Code'.

2. Check the 'Symbols' settings under debugging options.'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices.AccountManagement\v4.0_4.0.0.0__b77a5c561934e089\System.DirectoryServices.AccountManagement.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'Microsoft.Extensions.Hosting.Abstractions'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.DirectoryServices.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices.Protocols\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.DirectoryServices.Protocols.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

An unhandled exception of type 'System.DirectoryServices.AccountManagement.PrincipalServerDownException' occurred in System.DirectoryServices.AccountManagement.dll

The server could not be contacted.
</code>```

My question is what happen? and how should I handle this Exception?

I expecting when the progrann cant connect to Active Directory server it will get the data from the json file that syncronized every day when user connected to AD server

Body:
I've implemented the PrincipalServerDownException handler, but it seems like the program does not execute the handler.

public void GetData(String domain) {
    try
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain);
        UserPrincipal user = UserPrincipal.Current;
        this.name = user.DisplayName;
        this.nik = user.EmployeeId;
    }
    catch (PrincipalServerDownException)
    {
        Console.WriteLine("Failed to Connect");
        using (StreamReader r = new StreamReader("EmployeeData.json"))
        {

            string json = r.ReadToEnd();
            var semiParsedJson = JArray.Parse(json);

            String locname = Environment.UserName;

            List<EmpData> employeeData = JsonConvert.DeserializeObject<List<EmpData>>(json);

            foreach (var item in employeeData)
            {
                if (item.username == locname)
                {
                    this.name = item.display_name;
                    this.nik = item.nik;
                    break;
                }
            }
        }
    }
}

And here the debug error message

1. Use a debug build configuration or disable the debug option 'Enable Just My Code'.

2. Check the 'Symbols' settings under debugging options.'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices.AccountManagement\v4.0_4.0.0.0__b77a5c561934e089\System.DirectoryServices.AccountManagement.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'Microsoft.Extensions.Hosting.Abstractions'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.DirectoryServices.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices.Protocols\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.DirectoryServices.Protocols.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

'EmployeeInterestAgreement.exe' (CLR v4.0.30319: EmployeeInterestAgreement.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

An unhandled exception of type 'System.DirectoryServices.AccountManagement.PrincipalServerDownException' occurred in System.DirectoryServices.AccountManagement.dll

The server could not be contacted.

My question is what happen? and how should I handle this Exception?

I expecting when the progrann cant connect to Active Directory server it will get the data from the json file that syncronized every day when user connected to AD server


问:
Unity Multiplayer Position Interpolation results in coordinites being infinity
I am working on a multiplayer FPS using Tom Weiland's Riptide networking solution. I followed his three part tutorial on setting up basic networking and movement, but ran into an error after implementing interpolation (This video).

When only one player is connected to the server it works fine, but when two players are connected the following error occurs (client side):

```<code>
transform.position assign attempt for 'Player 2 (editor)' is not valid. Input position is { Infinity, Infinity, -Infinity }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
Interpolator:InterpolatePosition (single) (at Assets/Scripts/Interpolator.cs:56)
Interpolator:Update () (at Assets/Scripts/Interpolator.cs:43)

</code>```

The Update and InterpolatePosition functions in which the error occurs are:

```<code>private void Update()
    {
        for (int i = 0; i < futureTransformUpdates.Count; i++)
        {
            if (NetworkManager.Singleton.ServerTick >= futureTransformUpdates[i].Tick)
            {
                previous = to;
                to = futureTransformUpdates[i];
                from = new TransformUpdate(NetworkManager.Singleton.InterpolationTick, transform.position);

                futureTransformUpdates.RemoveAt(i);
                i--;
                timeElapsed = 0f;
                timeToReachTarget = (to.Tick - from.Tick) * Time.fixedDeltaTime;
            }
        }

        timeElapsed += Time.deltaTime;
        InterpolatePosition(timeElapsed / timeToReachTarget);    // Line 43
    }

    private void InterpolatePosition(float lerpAmount)
    {
        if ((to.Position - previous.Position).sqrMagnitude < squareMovementThreshold)
        {
            if (to.Position != from.Position)
                transform.position = Vector3.Lerp(from.Position, to.Position, lerpAmount);

            return;
        }

        transform.position = Vector3.LerpUnclamped(from.Position, to.Position, lerpAmount);    // Line 56
    }

</code>```

I have double checked and this is how it appears in the tutorial. I haven't used Lerp or LerpUnclamped before, and don't really know how to diagnose the issue. The error results in very choppy movement, often with several seconds between position updates, and no smoothing between them, making the game unplayable.

I am running the server and one client in the Unity editor, and the other client as a build, all on one computer. It doesn't matter which order I connect the clients in, both experience the issue when both are connected.

Body:
I am working on a multiplayer FPS using Tom Weiland's Riptide networking solution. I followed his three part tutorial on setting up basic networking and movement, but ran into an error after implementing interpolation (This video).

When only one player is connected to the server it works fine, but when two players are connected the following error occurs (client side):

transform.position assign attempt for 'Player 2 (editor)' is not valid. Input position is { Infinity, Infinity, -Infinity }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
Interpolator:InterpolatePosition (single) (at Assets/Scripts/Interpolator.cs:56)
Interpolator:Update () (at Assets/Scripts/Interpolator.cs:43)

The Update and InterpolatePosition functions in which the error occurs are:

private void Update()
    {
        for (int i = 0; i < futureTransformUpdates.Count; i++)
        {
            if (NetworkManager.Singleton.ServerTick >= futureTransformUpdates[i].Tick)
            {
                previous = to;
                to = futureTransformUpdates[i];
                from = new TransformUpdate(NetworkManager.Singleton.InterpolationTick, transform.position);

                futureTransformUpdates.RemoveAt(i);
                i--;
                timeElapsed = 0f;
                timeToReachTarget = (to.Tick - from.Tick) * Time.fixedDeltaTime;
            }
        }

        timeElapsed += Time.deltaTime;
        InterpolatePosition(timeElapsed / timeToReachTarget);    // Line 43
    }

    private void InterpolatePosition(float lerpAmount)
    {
        if ((to.Position - previous.Position).sqrMagnitude < squareMovementThreshold)
        {
            if (to.Position != from.Position)
                transform.position = Vector3.Lerp(from.Position, to.Position, lerpAmount);

            return;
        }

        transform.position = Vector3.LerpUnclamped(from.Position, to.Position, lerpAmount);    // Line 56
    }

I have double checked and this is how it appears in the tutorial. I haven't used Lerp or LerpUnclamped before, and don't really know how to diagnose the issue. The error results in very choppy movement, often with several seconds between position updates, and no smoothing between them, making the game unplayable.

I am running the server and one client in the Unity editor, and the other client as a build, all on one computer. It doesn't matter which order I connect the clients in, both experience the issue when both are connected.


问:
Can I apply torch.isin() to each row in 2D tensor without loop?
I have two tensors.

```<code>tensor_1 = tensor([[10,  8,  7],
                   [ 4,  5,  9]])

target_tensor = tensor([[ 8,  8,  6, 11,  0],
                        [ 7,  2, 10,  4,  5]])
</code>```

and torch.isin(tensor_1, target_tensor) returns

```<code>tensor([[ True,  True,  True],
        [ True,  True, False]])
</code>```

I want to apply isin to each row and get result like below

```<code>tensor([[False,  True, False],
        [ True,  True, False]])
</code>```

I can do this using for loop, but I don't want to use loop.

```<code>tmp_result = torch.zeros_like(tensor_1, dtype=torch.bool)

for i in range(tensor_1.size(0)):
    tmp_result[i] = torch.isin(tensor_1[i], target_tensor[i])
</code>```

How can I apply torch.isin() to each row in 2D tensor using GPU without loop?

Body:
I have two tensors.

tensor_1 = tensor([[10,  8,  7],
                   [ 4,  5,  9]])

target_tensor = tensor([[ 8,  8,  6, 11,  0],
                        [ 7,  2, 10,  4,  5]])

and torch.isin(tensor_1, target_tensor) returns

tensor([[ True,  True,  True],
        [ True,  True, False]])

I want to apply isin to each row and get result like below

tensor([[False,  True, False],
        [ True,  True, False]])

I can do this using for loop, but I don't want to use loop.

tmp_result = torch.zeros_like(tensor_1, dtype=torch.bool)

for i in range(tensor_1.size(0)):
    tmp_result[i] = torch.isin(tensor_1[i], target_tensor[i])

How can I apply torch.isin() to each row in 2D tensor using GPU without loop?


问:
new klaviyo node SDK
I'm trying to use Klaviyo for the first time, and the natural starting point seems to be their new Node SDK. Unfortunately, their documentation seems to be an odd combination of extremely detailed, and laking any details.

I've set up my account and gotten my API key, but am failing to get a simple registration to succeed.

I thought I could do this:

```<code>import { ConfigWrapper, Profiles } from 'klaviyo-api';
import logger from '../utils/logger';
import requireEnvVariable from '../utils/requireEnvVariable';

export async function subscribe(profile) {
    const apiKey = requireEnvVariable('KLAVIYO_PK');
    ConfigWrapper(apiKey);

    const user = Profiles.createProfile(profile)
    .then(data => logger.debug({data}, 'Got profile data'))
    .catch(error => {
        logger.warn(error, 'Klaviyo error');
        return error;
    });

    return true;
}
</code>```

For profile, I'm passing in

```<code>{
    "email": "me@example.com",
    "phone_number": "",
    "first_name": "Bob",
    "last_name": "Smith"
}
</code>```

but it responds with an error:

```<code>WARN: Klaviyo error
    env: "development"
    err: {
      "type": "Error",
      "message": "Bad Request",
      "status": 400,
      "response": {
        "req": {
          "method": "POST",
          "url": "https://a.klaviyo.com/api/profiles/",
          "data": {
            "email": "me@example.com",
            "phone_number": "",
            "first_name": "Bob",
            "last_name": "Smith"
          },
          "headers": {
            "authorization": "Klaviyo-API-Key <my private key>",
            "revision": "2022-10-17",
            "user-agent": "klaviyo-api-node/1.0.2",
            "content-type": "application/json",
            "accept": "application/json"
          }
        },
        "header": {
          "date": "Wed, 28 Dec 2022 23:34:14 GMT",
          "content-type": "application/vnd.api+json",
          "content-length": "211",
          "connection": "close",
          "cf-ray": "780e1b056c3728f5-ORD",
          "allow": "GET, POST, HEAD, OPTIONS",
          "vary": "Cookie, Accept-Encoding",
          "cf-cache-status": "DYNAMIC",
          "cid": "UDiE82",
          "ratelimit-limit": "700, 75;w=1, 700;w=60",
          "ratelimit-remaining": "699",
          "ratelimit-reset": "44",
          "x-robots-tag": "noindex, nofollow",
          "server": "cloudflare"
        },
        "status": 400,
        "text": "{\"errors\":[{\"id\":\"5648779b-3e1a-4ccf-80c4-dc19b8b32a2c\",\"status\":400,\"code\":\"invalid\",\"title\":\"Invalid input.\",\"detail\":\"The payload provided in the request is invalid.\",\"source\":{\"pointer\":\"/data\"},\"meta\":{}}]}"
      }
    }
</code>```

The various examples under Optional Parameters made me think that the above would Just Work; however, the docs also say, "For example values / data types, as well as whether parameters are required/optional, please reference the corresponding API Reference link," and "This SDK is a thin wrapper around our API. See our API Reference for full documentation on API behavior."

So looking at the Create Profile API Reference, I tried both

```<code>const user = Profiles.createProfile({attributes: profile})
</code>```

and

```<code>const user = Profiles.createProfile({type: 'profile', attributes: profile})
</code>```

but they both end up with the same error (except the reported data is updated appropriately, e.g.,

```<code>"status": 400,
      "response": {
        "req": {
          "method": "POST",
          "url": "https://a.klaviyo.com/api/profiles/",
          "data": {
            "type": "profile",
            "attributes": {
              "email": "me@example.com",
              "phone_number": "",
              "first_name": "Bob",
              "last_name": "Smith"
            }
          },
</code>```

What's the right way to use the new SDK? Or should I ignore this, and go back to creating manual fetch calls against their API?

Title: new klaviyo node SDK

Body:
I'm trying to use Klaviyo for the first time, and the natural starting point seems to be their new Node SDK. Unfortunately, their documentation seems to be an odd combination of extremely detailed, and laking any details.

I've set up my account and gotten my API key, but am failing to get a simple registration to succeed.

I thought I could do this:

import { ConfigWrapper, Profiles } from 'klaviyo-api';
import logger from '../utils/logger';
import requireEnvVariable from '../utils/requireEnvVariable';

export async function subscribe(profile) {
    const apiKey = requireEnvVariable('KLAVIYO_PK');
    ConfigWrapper(apiKey);

    const user = Profiles.createProfile(profile)
    .then(data => logger.debug({data}, 'Got profile data'))
    .catch(error => {
        logger.warn(error, 'Klaviyo error');
        return error;
    });

    return true;
}

For profile, I'm passing in

{
    "email": "me@example.com",
    "phone_number": "",
    "first_name": "Bob",
    "last_name": "Smith"
}

but it responds with an error:

WARN: Klaviyo error
    env: "development"
    err: {
      "type": "Error",
      "message": "Bad Request",
      "status": 400,
      "response": {
        "req": {
          "method": "POST",
          "url": "https://a.klaviyo.com/api/profiles/",
          "data": {
            "email": "me@example.com",
            "phone_number": "",
            "first_name": "Bob",
            "last_name": "Smith"
          },
          "headers": {
            "authorization": "Klaviyo-API-Key <my private key>",
            "revision": "2022-10-17",
            "user-agent": "klaviyo-api-node/1.0.2",
            "content-type": "application/json",
            "accept": "application/json"
          }
        },
        "header": {
          "date": "Wed, 28 Dec 2022 23:34:14 GMT",
          "content-type": "application/vnd.api+json",
          "content-length": "211",
          "connection": "close",
          "cf-ray": "780e1b056c3728f5-ORD",
          "allow": "GET, POST, HEAD, OPTIONS",
          "vary": "Cookie, Accept-Encoding",
          "cf-cache-status": "DYNAMIC",
          "cid": "UDiE82",
          "ratelimit-limit": "700, 75;w=1, 700;w=60",
          "ratelimit-remaining": "699",
          "ratelimit-reset": "44",
          "x-robots-tag": "noindex, nofollow",
          "server": "cloudflare"
        },
        "status": 400,
        "text": "{\"errors\":[{\"id\":\"5648779b-3e1a-4ccf-80c4-dc19b8b32a2c\",\"status\":400,\"code\":\"invalid\",\"title\":\"Invalid input.\",\"detail\":\"The payload provided in the request is invalid.\",\"source\":{\"pointer\":\"/data\"},\"meta\":{}}]}"
      }
    }

The various examples under Optional Parameters made me think that the above would Just Work; however, the docs also say, "For example values / data types, as well as whether parameters are required/optional, please reference the corresponding API Reference link," and "This SDK is a thin wrapper around our API. See our API Reference for full documentation on API behavior."

So looking at the Create Profile API Reference, I tried both

const user = Profiles.createProfile({attributes: profile})

and

const user = Profiles.createProfile({type: 'profile', attributes: profile})

but they both end up with the same error (except the reported data is updated appropriately, e.g.,

"status": 400,
      "response": {
        "req": {
          "method": "POST",
          "url": "https://a.klaviyo.com/api/profiles/",
          "data": {
            "type": "profile",
            "attributes": {
              "email": "me@example.com",
              "phone_number": "",
              "first_name": "Bob",
              "last_name": "Smith"
            }
          },

What's the right way to use the new SDK? Or should I ignore this, and go back to creating manual fetch calls against their API?


问:
The difference in the spread of red and white wine quality
I used R with simulation to test if there is a difference in the spread (as measured by the standard deviation) between the quality of red and white wines.

I was able to write and run the code but I was not able to confirm if there is diffrence or not.

Am I making somthing wrong?

Check the used data

The code I used as follows:

```<code># Load the necessary libraries
    library(tidyverse)
# Read in the wine dataset
    wine <- read.csv("WINE.csv", sep=";", header=TRUE)
# Split the dataset into red and white wine subgroups
    red_wine <- wine %>% filter(colour == "red")
    white_wine <- wine %>% filter(colour == "white")
# Perform the two-sample t-test
    t_test <- t.test(red_wine$quality, white_wine$quality, var.equal = TRUE)
# Print the results of the test
    print(t_test)
# Set the number of simulations
    n <- 500
# Set the critical value of the t-distribution
    critical_value <- qt(0.975, df = t_test$parameter)
# Perform the simulation
    simulated_t_stats <- replicate(n, {
  # Sample from the red and white wine data
    red_sample <- sample(red_wine$quality, size = length(red_wine$quality))
    white_sample <- sample(white_wine$quality, size = length(white_wine$quality))

  # Calculate the t-statistic for the simulated samples
    t.test(red_sample, white_sample, var.equal = TRUE)$statistic
})
# Calculate the proportion of simulated t-statistics that are within the critical region
    p_value <- mean(abs(simulated_t_stats) > critical_value)
# Print the p-value
    print(p_value)

</code>```

I am seeking a guide to take me to the right path.

Body:
I used R with simulation to test if there is a difference in the spread (as measured by the standard deviation) between the quality of red and white wines.

I was able to write and run the code but I was not able to confirm if there is diffrence or not.

Am I making somthing wrong?

Check the used data

The code I used as follows:

# Load the necessary libraries
    library(tidyverse)
# Read in the wine dataset
    wine <- read.csv("WINE.csv", sep=";", header=TRUE)
# Split the dataset into red and white wine subgroups
    red_wine <- wine %>% filter(colour == "red")
    white_wine <- wine %>% filter(colour == "white")
# Perform the two-sample t-test
    t_test <- t.test(red_wine$quality, white_wine$quality, var.equal = TRUE)
# Print the results of the test
    print(t_test)
# Set the number of simulations
    n <- 500
# Set the critical value of the t-distribution
    critical_value <- qt(0.975, df = t_test$parameter)
# Perform the simulation
    simulated_t_stats <- replicate(n, {
  # Sample from the red and white wine data
    red_sample <- sample(red_wine$quality, size = length(red_wine$quality))
    white_sample <- sample(white_wine$quality, size = length(white_wine$quality))

  # Calculate the t-statistic for the simulated samples
    t.test(red_sample, white_sample, var.equal = TRUE)$statistic
})
# Calculate the proportion of simulated t-statistics that are within the critical region
    p_value <- mean(abs(simulated_t_stats) > critical_value)
# Print the p-value
    print(p_value)

I am seeking a guide to take me to the right path.


问:
per level math operation in multilevel pandas dataframe?
I have a dataframe with index of (a, b, c),columns: D to H. I have sorted the dataframe by [a, E] Now I want to normalize the dataframe like this:

```<code>for va in df.index.get_level_values('a').unique():
    df[df['a']==va] = df[df['a']==va]/(df[df['a']==va].iloc[0])
</code>```

I wonder is there a more efficient way or even a builtin method for this kind of operation?

maybe something like reversed groupby('xxxx').apply(). Because the groupby is just aggregate. I probably need something reversed.

Body:
I have a dataframe with index of (a, b, c),columns: D to H. I have sorted the dataframe by [a, E] Now I want to normalize the dataframe like this:

for va in df.index.get_level_values('a').unique():
    df[df['a']==va] = df[df['a']==va]/(df[df['a']==va].iloc[0])

I wonder is there a more efficient way or even a builtin method for this kind of operation?

maybe something like reversed groupby('xxxx').apply(). Because the groupby is just aggregate. I probably need something reversed.


问:
How to control music playback on the phone from WearOS watch
I want remote control phone music playback  from WearOS watch just for play/pause/next/previous as system app does.

I have google a lot, building a media browser client in WearOS app looks right to implement this.

        val comp = ComponentName("com.android.bluetooth",
           "com.android.bluetooth.avrcpcontroller.BluetoothMediaBrowserService")

        mMediaBrowser = MediaBrowserCompat(context,comp,mConnectionCallbacks,null)
        mMediaBrowser?.connect()
```
<p>but connection always failed</p>
``` Unable to start service Intent { act=android.media.browse.MediaBrowserService cmp=com.android.bluetooth/.a2dpsink.mbs.A2dpMediaBrowserService } U=0: not found

```
<p>I also tried  <strong>avrcpcontroller.BluetoothMediaBrowserService</strong></p>
```Unable to start service Intent { act=android.media.browse.MediaBrowserService cmp=com.android.bluetooth/.avrcpcontroller.BluetoothMediaBrowserService } U=0: not found
```

It seems there is no way to connect the mediabrowser from WearOS watch.

Body:
I want remote control phone music playback  from WearOS watch just for play/pause/next/previous as system app does.

I have google a lot, building a media browser client in WearOS app looks right to implement this.

        val comp = ComponentName("com.android.bluetooth",
           "com.android.bluetooth.avrcpcontroller.BluetoothMediaBrowserService")

        mMediaBrowser = MediaBrowserCompat(context,comp,mConnectionCallbacks,null)
        mMediaBrowser?.connect()

but connection always failed

 Unable to start service Intent { act=android.media.browse.MediaBrowserService cmp=com.android.bluetooth/.a2dpsink.mbs.A2dpMediaBrowserService } U=0: not found

I also tried  avrcpcontroller.BluetoothMediaBrowserService

Unable to start service Intent { act=android.media.browse.MediaBrowserService cmp=com.android.bluetooth/.avrcpcontroller.BluetoothMediaBrowserService } U=0: not found

It seems there is no way to connect the mediabrowser from WearOS watch.


问:
HTTPS Request Not Working in Google App Engine (Python Requests lib) / Cloud Shell
I have been trying to do some html scraping for one of my projects, wherein the it is working from my local computer, but it is now working in google app engine. It is getting timed out.

I have tried using dig from google cloud shell, which is resolving the correct IP but still curl / trace is failing. Billing is enabled, haven't touched any DNS setting in GAE.

The target site is apparently using chunked reply.

```<code>from flask import Flask, render_template, request, send_file, redirect, url_for, Response, send_from_directory
import flask
import requests
import bs4
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import logging
import os

s = requests.Session()
r = s.get("https://kdseodb.smportkolkata.in/ccuPomsPosWeb/index.jsp")
id1 = r.cookies['JSESSIONID']
r2 = s.get("https://kdseodb.smportkolkata.in/ccuPomsPosWeb/apps/dos/PosCTS.xhtml")
id2 = r2.cookies['oam.Flash.RENDERMAP.TOKEN']
headers = {'Accept': 'application/xml, text/xml, */*; q=0.01', 'Accept-Language': 'en-US,en;q=0.9', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Faces-Request': 'partial/ajax', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest', 'Cookie': 'JSESSIONID='+id1+'; oam.Flash.RENDERMAP.TOKEN=-'+id2+''}

payload = 'javax.faces.partial.ajax=true&javax.faces.source=form1%3AbtnSearch&javax.faces.partial.execute=form1&javax.faces.partial.render=form1&form1%3AbtnSearch=form1%3AbtnSearch&form1%3AcomMloCd_focus=&form1%3AcomMloCd_input=NONE&form1%3AtxtCntNo=ABCD1234567&form1%3AtblData_scrollState=0%2C0&form1_SUBMIT=1&javax.faces.ViewState=PCsvYkkMUQAmP0zfu2tj7G5AqM%2BXrDH8%2BaG%2FROvEtWIHJyXX'

r3 = s.post("https://kdseodb.smportkolkata.in/ccuPomsPosWeb/apps/dos/PosCTS.xhtml", cookies=r.cookies, headers=headers, data=payload)
soup = bs4.BeautifulSoup(r3.text)
</code>```

dig output from google cloud shell, NXDOMAIN is coming up when used on the IPs

```<code>dig kdseodb.smportkolkata.in

; <<>> DiG 9.16.33-Debian <<>> kdseodb.smportkolkata.in
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 414
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;kdseodb.smportkolkata.in.      IN      A

;; ANSWER SECTION:
kdseodb.smportkolkata.in. 3600  IN      A       117.242.152.158
kdseodb.smportkolkata.in. 3600  IN      A       203.153.37.38

;; Query time: 6 msec
;; SERVER: 169.254.169.254#53(169.254.169.254)
;; WHEN: Thu Dec 29 01:44:36 UTC 2022
;; MSG SIZE  rcvd: 85

dig 117.242.152.158

; <<>> DiG 9.16.33-Debian <<>> 117.242.152.158
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 29831
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;117.242.152.158.               IN      A

;; AUTHORITY SECTION:
.                       86400   IN      SOA     a.root-servers.net. nstld.verisign-grs.com. 2022122801 1800 900 604800 86400

;; Query time: 5 msec
;; SERVER: 169.254.169.254#53(169.254.169.254)
;; WHEN: Thu Dec 29 01:45:39 UTC 2022
;; MSG SIZE  rcvd: 119

dig 203.153.37.38

; <<>> DiG 9.16.33-Debian <<>> 203.153.37.38
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 32307
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;203.153.37.38.                 IN      A

;; AUTHORITY SECTION:
.                       86400   IN      SOA     a.root-servers.net. nstld.verisign-grs.com. 2022122801 1800 900 604800 86400

;; Query time: 7 msec
;; SERVER: 169.254.169.254#53(169.254.169.254)
;; WHEN: Thu Dec 29 01:46:13 UTC 2022
;; MSG SIZE  rcvd: 117

</code>```

Body:
I have been trying to do some html scraping for one of my projects, wherein the it is working from my local computer, but it is now working in google app engine. It is getting timed out.

I have tried using dig from google cloud shell, which is resolving the correct IP but still curl / trace is failing. Billing is enabled, haven't touched any DNS setting in GAE.

The target site is apparently using chunked reply.

from flask import Flask, render_template, request, send_file, redirect, url_for, Response, send_from_directory
import flask
import requests
import bs4
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import logging
import os

s = requests.Session()
r = s.get("https://kdseodb.smportkolkata.in/ccuPomsPosWeb/index.jsp")
id1 = r.cookies['JSESSIONID']
r2 = s.get("https://kdseodb.smportkolkata.in/ccuPomsPosWeb/apps/dos/PosCTS.xhtml")
id2 = r2.cookies['oam.Flash.RENDERMAP.TOKEN']
headers = {'Accept': 'application/xml, text/xml, */*; q=0.01', 'Accept-Language': 'en-US,en;q=0.9', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Faces-Request': 'partial/ajax', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest', 'Cookie': 'JSESSIONID='+id1+'; oam.Flash.RENDERMAP.TOKEN=-'+id2+''}

payload = 'javax.faces.partial.ajax=true&javax.faces.source=form1%3AbtnSearch&javax.faces.partial.execute=form1&javax.faces.partial.render=form1&form1%3AbtnSearch=form1%3AbtnSearch&form1%3AcomMloCd_focus=&form1%3AcomMloCd_input=NONE&form1%3AtxtCntNo=ABCD1234567&form1%3AtblData_scrollState=0%2C0&form1_SUBMIT=1&javax.faces.ViewState=PCsvYkkMUQAmP0zfu2tj7G5AqM%2BXrDH8%2BaG%2FROvEtWIHJyXX'

r3 = s.post("https://kdseodb.smportkolkata.in/ccuPomsPosWeb/apps/dos/PosCTS.xhtml", cookies=r.cookies, headers=headers, data=payload)
soup = bs4.BeautifulSoup(r3.text)

dig output from google cloud shell, NXDOMAIN is coming up when used on the IPs

dig kdseodb.smportkolkata.in

; <<>> DiG 9.16.33-Debian <<>> kdseodb.smportkolkata.in
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 414
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;kdseodb.smportkolkata.in.      IN      A

;; ANSWER SECTION:
kdseodb.smportkolkata.in. 3600  IN      A       117.242.152.158
kdseodb.smportkolkata.in. 3600  IN      A       203.153.37.38

;; Query time: 6 msec
;; SERVER: 169.254.169.254#53(169.254.169.254)
;; WHEN: Thu Dec 29 01:44:36 UTC 2022
;; MSG SIZE  rcvd: 85

dig 117.242.152.158

; <<>> DiG 9.16.33-Debian <<>> 117.242.152.158
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 29831
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;117.242.152.158.               IN      A

;; AUTHORITY SECTION:
.                       86400   IN      SOA     a.root-servers.net. nstld.verisign-grs.com. 2022122801 1800 900 604800 86400

;; Query time: 5 msec
;; SERVER: 169.254.169.254#53(169.254.169.254)
;; WHEN: Thu Dec 29 01:45:39 UTC 2022
;; MSG SIZE  rcvd: 119

dig 203.153.37.38

; <<>> DiG 9.16.33-Debian <<>> 203.153.37.38
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 32307
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;203.153.37.38.                 IN      A

;; AUTHORITY SECTION:
.                       86400   IN      SOA     a.root-servers.net. nstld.verisign-grs.com. 2022122801 1800 900 604800 86400

;; Query time: 7 msec
;; SERVER: 169.254.169.254#53(169.254.169.254)
;; WHEN: Thu Dec 29 01:46:13 UTC 2022
;; MSG SIZE  rcvd: 117


问:
micronaut runs with the DB on dev/test but not with the build image
I'm trying to use postgres on a micronaut project. When running locally, or by executing the tests, everything works correctly. But when I try to generate a docker image and run it I got the following error:

```<code>Caused by: org.hibernate.HibernateException: HR000048: Could not determine Dialect from JDBC driver metadata (specify a connection URI with scheme 'postgresql:', 'mysql:', 'cockroachdb', or 'db2:')

</code>```

According to the official documentation:

When you move to production, you will need to configure the properties
injected by Test Resources to point at your real production database.
This can be done via environment variables like so:

I should set some application items described onthe JDBC section of the guide

So here is my application.yaml:

micronaut:
  application:
    name: micronaut-guide
netty:
  default:
    allocator:
      max-order: 3
#tag::jpa[]
jpa:
  default:
    entity-scan:
      packages:
        - 'example.micronaut.domain'
    properties:
      hibernate:
        show-sql: true
        hbm2ddl:
          auto: update
        connection:
          db-type: postgres
    reactive: true
#end::jpa[]
datasources:
  default:
    driverClassName: org.postgresql.Driver
    db-type: postgresql
    schema-generate: CREATE_DROP
    dialect: POSTGRES
jpa.default.properties.hibernate.hbm2ddl.auto: update

```
<p>Plus, I've tried to pass some environment variable when running it:</p>
```docker run micronaut-postgres -p 8080:8080 --rm -e DATASOURCES_DEFAULT_URL=$DATASOURCES_DEFAULT_URL -e DATASOURCES_DEFAULT_USERNAME=$DATASOURCES_DEFAULT_USERNAME -e DATASOURCES_DEFAULT_PASSWORD=$DATASOURCES_DEFAULT_PASSWORD

◼ ~/Code/Personal/micronaut-postgres $ echo $DATASOURCES_DEFAULT_URL                                                             130
jdbc:postgresql://localhost:3306/db
```
<p>to be sure there are all the pieces here is my <code>build.gradle</code>:</p>
```plugins {
    id("org.jetbrains.kotlin.jvm") version "1.6.21"
    id("org.jetbrains.kotlin.kapt") version "1.6.21"
    id("org.jetbrains.kotlin.plugin.allopen") version "1.6.21"
    id("org.jetbrains.kotlin.plugin.jpa") version "1.6.21"
    id("com.github.johnrengelman.shadow") version "7.1.2"
    id("io.micronaut.application") version "3.6.7"
    id("io.micronaut.test-resources") version "3.6.7"
}

version = "0.1"
group = "example.micronaut"

repositories {
    mavenCentral()
}

dependencies {
    kapt("io.micronaut.data:micronaut-data-processor")
    kapt("io.micronaut:micronaut-http-validation")
    kapt("io.micronaut.serde:micronaut-serde-processor")
    implementation("io.micronaut:micronaut-http-client")
    implementation("io.micronaut.data:micronaut-data-hibernate-reactive")
    implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
    implementation("io.micronaut.reactor:micronaut-reactor")
    implementation("io.micronaut.reactor:micronaut-reactor-http-client")
    implementation("com.ongres.scram:client:2.1")

    implementation("io.micronaut.serde:micronaut-serde-jackson")
//    implementation("io.vertx:vertx-mysql-client")
    implementation("io.vertx:vertx-pg-client")
    implementation("io.micronaut.sql:micronaut-vertx-pg-client")

    implementation("jakarta.annotation:jakarta.annotation-api")
    implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
    runtimeOnly("ch.qos.logback:logback-classic")

//    testResourcesService("mysql:mysql-connector-java")
    testResourcesService("org.postgresql:postgresql")

    compileOnly("org.graalvm.nativeimage:svm")

    implementation("io.micronaut.sql:micronaut-vertx-pg-client")
    implementation("io.micronaut:micronaut-validation")

    runtimeOnly("com.fasterxml.jackson.module:jackson-module-kotlin")
}

application {
    mainClass.set("example.micronaut.ApplicationKt")
}
java {
    sourceCompatibility = JavaVersion.toVersion("11")
}

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
}
graalvmNative.toolchainDetection = false
micronaut {
    runtime("netty")
    testRuntime("junit5")
    processing {
        incremental(true)
        annotations("example.micronaut.*")
    }
    testResources {
        additionalModules.add("hibernate-reactive-postgresql")
    }
}

tasks.named("dockerfile") {
    baseImage = "eclipse-temurin:17.0.5_8-jre-jammy"
}
```
<hr />
<h2>Another more standard way to replicate the problem</h2>
<p>I got into the same problem with the official example on the micronaut website available here.</p>
<p>I can generate the docker image, run it and the same problem arises:</p>
```Step 8/8 : ENTRYPOINT ["java", "-jar", "/home/app/application.jar"]
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
 ---> Running in b4ac7195ad12
Removing intermediate container b4ac7195ad12
 ---> 98936716be8c
Successfully built 98936716be8c
Successfully tagged micronautguide:latest
Created image with ID '98936716be8c'.

...
# just checking the env var is there
 $ echo $JDBC_URL
jdbc:mysql://production-server:3306/micronaut

 $  docker run --rm -e DATASOURCES_DEFAULT_URL=$JDBC_URL -e DATASOURCES_DEFAULT_USERNAME=$JDBC_USER -e DATASOURCES_DEFAULT_PASSWORD=$JDBC_PASSWORD -it -p 8080:8080 98936716be8c 125
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested

...

Caused by: org.hibernate.HibernateException: HR000048: Could not determine Dialect from JDBC driver metadata (specify a connection URI with scheme 'postgresql:', 'mysql:', 'cockroachdb', or 'db2:')

```

Body:
I'm trying to use postgres on a micronaut project. When running locally, or by executing the tests, everything works correctly. But when I try to generate a docker image and run it I got the following error:

Caused by: org.hibernate.HibernateException: HR000048: Could not determine Dialect from JDBC driver metadata (specify a connection URI with scheme 'postgresql:', 'mysql:', 'cockroachdb', or 'db2:')

According to the official documentation:

When you move to production, you will need to configure the properties
injected by Test Resources to point at your real production database.
This can be done via environment variables like so:

I should set some application items described onthe JDBC section of the guide

So here is my application.yaml:

micronaut:
  application:
    name: micronaut-guide
netty:
  default:
    allocator:
      max-order: 3
#tag::jpa[]
jpa:
  default:
    entity-scan:
      packages:
        - 'example.micronaut.domain'
    properties:
      hibernate:
        show-sql: true
        hbm2ddl:
          auto: update
        connection:
          db-type: postgres
    reactive: true
#end::jpa[]
datasources:
  default:
    driverClassName: org.postgresql.Driver
    db-type: postgresql
    schema-generate: CREATE_DROP
    dialect: POSTGRES
jpa.default.properties.hibernate.hbm2ddl.auto: update

Plus, I've tried to pass some environment variable when running it:

docker run micronaut-postgres -p 8080:8080 --rm -e DATASOURCES_DEFAULT_URL=$DATASOURCES_DEFAULT_URL -e DATASOURCES_DEFAULT_USERNAME=$DATASOURCES_DEFAULT_USERNAME -e DATASOURCES_DEFAULT_PASSWORD=$DATASOURCES_DEFAULT_PASSWORD

◼ ~/Code/Personal/micronaut-postgres $ echo $DATASOURCES_DEFAULT_URL                                                             130
jdbc:postgresql://localhost:3306/db

to be sure there are all the pieces here is my build.gradle:

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.6.21"
    id("org.jetbrains.kotlin.kapt") version "1.6.21"
    id("org.jetbrains.kotlin.plugin.allopen") version "1.6.21"
    id("org.jetbrains.kotlin.plugin.jpa") version "1.6.21"
    id("com.github.johnrengelman.shadow") version "7.1.2"
    id("io.micronaut.application") version "3.6.7"
    id("io.micronaut.test-resources") version "3.6.7"
}

version = "0.1"
group = "example.micronaut"

repositories {
    mavenCentral()
}

dependencies {
    kapt("io.micronaut.data:micronaut-data-processor")
    kapt("io.micronaut:micronaut-http-validation")
    kapt("io.micronaut.serde:micronaut-serde-processor")
    implementation("io.micronaut:micronaut-http-client")
    implementation("io.micronaut.data:micronaut-data-hibernate-reactive")
    implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
    implementation("io.micronaut.reactor:micronaut-reactor")
    implementation("io.micronaut.reactor:micronaut-reactor-http-client")
    implementation("com.ongres.scram:client:2.1")

    implementation("io.micronaut.serde:micronaut-serde-jackson")
//    implementation("io.vertx:vertx-mysql-client")
    implementation("io.vertx:vertx-pg-client")
    implementation("io.micronaut.sql:micronaut-vertx-pg-client")

    implementation("jakarta.annotation:jakarta.annotation-api")
    implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
    runtimeOnly("ch.qos.logback:logback-classic")

//    testResourcesService("mysql:mysql-connector-java")
    testResourcesService("org.postgresql:postgresql")

    compileOnly("org.graalvm.nativeimage:svm")

    implementation("io.micronaut.sql:micronaut-vertx-pg-client")
    implementation("io.micronaut:micronaut-validation")

    runtimeOnly("com.fasterxml.jackson.module:jackson-module-kotlin")
}

application {
    mainClass.set("example.micronaut.ApplicationKt")
}
java {
    sourceCompatibility = JavaVersion.toVersion("11")
}

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
}
graalvmNative.toolchainDetection = false
micronaut {
    runtime("netty")
    testRuntime("junit5")
    processing {
        incremental(true)
        annotations("example.micronaut.*")
    }
    testResources {
        additionalModules.add("hibernate-reactive-postgresql")
    }
}

tasks.named("dockerfile") {
    baseImage = "eclipse-temurin:17.0.5_8-jre-jammy"
}

Another more standard way to replicate the problem

I got into the same problem with the official example on the micronaut website available here.

I can generate the docker image, run it and the same problem arises:

Step 8/8 : ENTRYPOINT ["java", "-jar", "/home/app/application.jar"]
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
 ---> Running in b4ac7195ad12
Removing intermediate container b4ac7195ad12
 ---> 98936716be8c
Successfully built 98936716be8c
Successfully tagged micronautguide:latest
Created image with ID '98936716be8c'.

...
# just checking the env var is there
 $ echo $JDBC_URL
jdbc:mysql://production-server:3306/micronaut

 $  docker run --rm -e DATASOURCES_DEFAULT_URL=$JDBC_URL -e DATASOURCES_DEFAULT_USERNAME=$JDBC_USER -e DATASOURCES_DEFAULT_PASSWORD=$JDBC_PASSWORD -it -p 8080:8080 98936716be8c 125
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested

...

Caused by: org.hibernate.HibernateException: HR000048: Could not determine Dialect from JDBC driver metadata (specify a connection URI with scheme 'postgresql:', 'mysql:', 'cockroachdb', or 'db2:')


问:
Cannot compare the values of two columns correctly using tidyverse
I have a dataset with several columns and about 22,000 rows. My goal is to determine if each row equals the maximum value of that row. I do so by creating a dummy variable column.

Here is an example of the data.

Here is the code I have. testdf is the dataframe and test2 is the output.

Please excuse the fact that the third and fourth rows do the same thing as the fifth row's command. I had tried it manually to keep my own sanity.

```<code>test2 = testdf %>%
  ungroup() %>%
  mutate(New_Column_1 = max(Column_C)) %>%
  mutate(New_Column_2 = if_else(Column_C == New_Column_1, "Yes", "No")) %>% # the previous and this line execute the next line manually
  mutate(`Final?` = case_when( # this method still doesn't work
    Column_C == max(Column_C) ~ "Y",
    TRUE ~ "N"
  ))
</code>```

Here is the output.

Since all the numbers in Column_C are the same, I expected for all rows to return a "Y" or "Yes". However, only the seventh and twelfth rows returned a "Y" or "Yes" in columns "Final?" and "New_Column_2."

Even more weirdly, when I tried to create a reproducible example using dput and ran the same code, the results were correct. Here is the result after running the same code on the dataframe created using dput.

I'm not sure why the reproducible example doesn't behave incorrectly and if the reproducible dataframe will be useful, but here it is below anyway.

```<code>testdf_dput = structure(list(Column_A = 1:12, Column_B = c(458, 458, 458, 458,
438, 407, 382, 355, 345, 338, 322, 307), Column_C = c(458, 458,
458, 458, 458, 458, 458, 458, 458, 458, 458, 458), Column_D = c(531,
531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531), Column_E = c(181833.517467249,
181833.517467249, 181833.517467249, 181833.517467249, 188243.751141552,
193750.334152334, 198517.429319372, 201049.918309859, 203428.110144927,
205612.289940828, 205185.167701863, 206427.749185668), Column_F = c("Melissa",
"Dominique", "Ronald", "Jedediah", "Samantha", "Justin", "Jeanmarc",
"Tiffany", "Jacob", "David", "Schyanne", "Vincent"), Column_G = c("2019",
"2019", "2019", "2019", "2019", "2019", "2019", "2019", "2019",
"2019", "2019", "2019")), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))

library(tidyverse)

test3 = testdf_dput %>%
  mutate(New_Column_1 = max(Column_C)) %>%
  mutate(New_Column_2 = if_else(Column_C == New_Column_1, "Yes", "No")) %>% # the previous and this line execute the next line manually
  mutate(`Final?` = case_when( # this method still doesn't work
    Column_C == max(Column_C) ~ "Y",
    TRUE ~ "N"
  ))
</code>```

Please let me know if you've experienced something like this. I have no idea what is going on.

Thanks in advance.

Body:
I have a dataset with several columns and about 22,000 rows. My goal is to determine if each row equals the maximum value of that row. I do so by creating a dummy variable column.

Here is an example of the data.

Here is the code I have. testdf is the dataframe and test2 is the output.

Please excuse the fact that the third and fourth rows do the same thing as the fifth row's command. I had tried it manually to keep my own sanity.

test2 = testdf %>%
  ungroup() %>%
  mutate(New_Column_1 = max(Column_C)) %>%
  mutate(New_Column_2 = if_else(Column_C == New_Column_1, "Yes", "No")) %>% # the previous and this line execute the next line manually
  mutate(`Final?` = case_when( # this method still doesn't work
    Column_C == max(Column_C) ~ "Y",
    TRUE ~ "N"
  ))

Here is the output.

Since all the numbers in Column_C are the same, I expected for all rows to return a "Y" or "Yes". However, only the seventh and twelfth rows returned a "Y" or "Yes" in columns "Final?" and "New_Column_2."

Even more weirdly, when I tried to create a reproducible example using dput and ran the same code, the results were correct. Here is the result after running the same code on the dataframe created using dput.

I'm not sure why the reproducible example doesn't behave incorrectly and if the reproducible dataframe will be useful, but here it is below anyway.

testdf_dput = structure(list(Column_A = 1:12, Column_B = c(458, 458, 458, 458,
438, 407, 382, 355, 345, 338, 322, 307), Column_C = c(458, 458,
458, 458, 458, 458, 458, 458, 458, 458, 458, 458), Column_D = c(531,
531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531), Column_E = c(181833.517467249,
181833.517467249, 181833.517467249, 181833.517467249, 188243.751141552,
193750.334152334, 198517.429319372, 201049.918309859, 203428.110144927,
205612.289940828, 205185.167701863, 206427.749185668), Column_F = c("Melissa",
"Dominique", "Ronald", "Jedediah", "Samantha", "Justin", "Jeanmarc",
"Tiffany", "Jacob", "David", "Schyanne", "Vincent"), Column_G = c("2019",
"2019", "2019", "2019", "2019", "2019", "2019", "2019", "2019",
"2019", "2019", "2019")), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))

library(tidyverse)

test3 = testdf_dput %>%
  mutate(New_Column_1 = max(Column_C)) %>%
  mutate(New_Column_2 = if_else(Column_C == New_Column_1, "Yes", "No")) %>% # the previous and this line execute the next line manually
  mutate(`Final?` = case_when( # this method still doesn't work
    Column_C == max(Column_C) ~ "Y",
    TRUE ~ "N"
  ))

Please let me know if you've experienced something like this. I have no idea what is going on.

Thanks in advance.