问:
SSL connection not taking place with RabbitMQ
While working on a issue found that SSL connection are not created when interacting to RabbitMQ. There is following exception that occurs:

Starting application. . . .
RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: One or more of the parameters passed to the function was invalid
--- End of inner exception stack trace ---
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at RabbitMQ.Client.SslHelper.TcpUpgrade(Stream tcpStream, SslOption sslOption)
at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout) at RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateFrameHandler(AmqpTcpEndpoint endpoint, Func2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout)
at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList1 endpoints, String clientProvidedName) --- End of inner exception stack trace --- at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList1 endpoints, String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList`1 hostnames, String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection()

Here is the code snippet:
`

```<code>namespace ConsoleApp_Test
{
class Program
{
private static string certificatepath = @"C:\CertificatePath\4RMQClientCert.p12";
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting application. . . . ");
ConnectionFactory connectionFactory = CreateConnectionFactory();
IConnection connection = connectionFactory.CreateConnection();
Console.ReadLine();
Console.WriteLine("Connection Created successfully . . .");
}
catch (Exception ex)
{
Console.WriteLine(ex);
CreateErrorTextFile(ex.StackTrace);
}
finally
{
Console.ReadLine();
}
}

    private static ConnectionFactory CreateConnectionFactory()
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(@"TLSParameters.xml");
        XmlNodeList parameters = xml.SelectNodes("Parameters");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        foreach (XmlNode xnlNode in parameters)
        {
            XmlElement element = (XmlElement)xnlNode;
            connectionFactory.HostName = element.GetElementsByTagName("HostName")[0].ChildNodes[0].InnerText;
            connectionFactory.UserName = element.GetElementsByTagName("UserName")[0].ChildNodes[0].InnerText;
            connectionFactory.Password = element.GetElementsByTagName("Password")[0].ChildNodes[0].InnerText;
            connectionFactory.Ssl.CertPath = element.GetElementsByTagName("ClientCertPath")[0].ChildNodes[0].InnerText;
            connectionFactory.Ssl.CertPassphrase = element.GetElementsByTagName("CertificatePassword")[0].ChildNodes[0].InnerText;
            connectionFactory.Ssl.ServerName = element.GetElementsByTagName("ServerName")[0].ChildNodes[0].InnerText;
        }

        connectionFactory.Ssl.Enabled = true;
        connectionFactory.Ssl.Version = SslProtocols.Tls12; // Error in wireshark . No Client hello
        connectionFactory.Ssl.CertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
        return connectionFactory;
    }

    private static X509Certificate SelectLocalCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
    {
        Console.WriteLine("Client is selecting a local certificate.");
        if (acceptableIssuers != null &&
            acceptableIssuers.Length > 0 &&
            localCertificates != null &&
            localCertificates.Count > 0)
        {
            // Use the first certificate that is from an acceptable issuer.
            foreach (X509Certificate certificate in localCertificates)
            {
                string issuer = certificate.Issuer;
                if (Array.IndexOf(acceptableIssuers, issuer) != -1)
                    return certificate;
            }
        }
        if (localCertificates != null &&
            localCertificates.Count > 0)
            return localCertificates[0];

        return null;
    }

    private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        bool isServerVerified = false;
        if ((sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.None)
        {
            isServerVerified = true;
        }
        string sslError = sslPolicyErrors.ToString();
        CreateErrorTextFile(sslError);
        Console.WriteLine("Error:" + sslError);
        return isServerVerified;
    }

    private static void CreateErrorTextFile(string error)
    {
        string fileName = @"C:\Temp\SSLErrors.txt";
        using (FileStream fs = File.Create(fileName))
        {
            byte[] errors = new UTF8Encoding(true).GetBytes(error);
            fs.Write(errors, 0, errors.Length);
        }
    }
}
}
</code>```

`
Wireshark capture shows this:
enter image description here
As per my investigation proper wireshark capture should look like following:
enter image description here

Tried many things but none worked.
Steps taken to resolve this :

Ran IISCrypto
Certificates checked and are latest and have no problem according to me.
Verified TLS 1.2 is enabled or not, but it was enabled
Working on all other system, other than server machine.
Windows is updated to the latest.
Firewalls are also disabled.
Please let me know how can I make this hand shake successful so that application interacts successfully with RabbitMQ

Ran IISCrypto
Certificates checked and are latest and have no problem according to me.
Verified TLS 1.2 is enabled or not, but it was enabled
Working on all other system, other than server machine.
Windows is updated to the latest.
Firewalls are also disabled.
Please let me know how can I make this hand shake successful so that application interacts successfully with RabbitMQ

Body:
While working on a issue found that SSL connection are not created when interacting to RabbitMQ. There is following exception that occurs:

Starting application. . . .
RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: One or more of the parameters passed to the function was invalid
--- End of inner exception stack trace ---
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at RabbitMQ.Client.SslHelper.TcpUpgrade(Stream tcpStream, SslOption sslOption)
at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout) at RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateFrameHandler(AmqpTcpEndpoint endpoint, Func2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout)
at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList1 endpoints, String clientProvidedName) --- End of inner exception stack trace --- at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList1 endpoints, String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList`1 hostnames, String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection()

Here is the code snippet:
`

namespace ConsoleApp_Test
{
class Program
{
private static string certificatepath = @"C:\CertificatePath\4RMQClientCert.p12";
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting application. . . . ");
ConnectionFactory connectionFactory = CreateConnectionFactory();
IConnection connection = connectionFactory.CreateConnection();
Console.ReadLine();
Console.WriteLine("Connection Created successfully . . .");
}
catch (Exception ex)
{
Console.WriteLine(ex);
CreateErrorTextFile(ex.StackTrace);
}
finally
{
Console.ReadLine();
}
}

    private static ConnectionFactory CreateConnectionFactory()
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(@"TLSParameters.xml");
        XmlNodeList parameters = xml.SelectNodes("Parameters");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        foreach (XmlNode xnlNode in parameters)
        {
            XmlElement element = (XmlElement)xnlNode;
            connectionFactory.HostName = element.GetElementsByTagName("HostName")[0].ChildNodes[0].InnerText;
            connectionFactory.UserName = element.GetElementsByTagName("UserName")[0].ChildNodes[0].InnerText;
            connectionFactory.Password = element.GetElementsByTagName("Password")[0].ChildNodes[0].InnerText;
            connectionFactory.Ssl.CertPath = element.GetElementsByTagName("ClientCertPath")[0].ChildNodes[0].InnerText;
            connectionFactory.Ssl.CertPassphrase = element.GetElementsByTagName("CertificatePassword")[0].ChildNodes[0].InnerText;
            connectionFactory.Ssl.ServerName = element.GetElementsByTagName("ServerName")[0].ChildNodes[0].InnerText;
        }

        connectionFactory.Ssl.Enabled = true;
        connectionFactory.Ssl.Version = SslProtocols.Tls12; // Error in wireshark . No Client hello
        connectionFactory.Ssl.CertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
        return connectionFactory;
    }

    private static X509Certificate SelectLocalCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
    {
        Console.WriteLine("Client is selecting a local certificate.");
        if (acceptableIssuers != null &&
            acceptableIssuers.Length > 0 &&
            localCertificates != null &&
            localCertificates.Count > 0)
        {
            // Use the first certificate that is from an acceptable issuer.
            foreach (X509Certificate certificate in localCertificates)
            {
                string issuer = certificate.Issuer;
                if (Array.IndexOf(acceptableIssuers, issuer) != -1)
                    return certificate;
            }
        }
        if (localCertificates != null &&
            localCertificates.Count > 0)
            return localCertificates[0];

        return null;
    }

    private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        bool isServerVerified = false;
        if ((sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.None)
        {
            isServerVerified = true;
        }
        string sslError = sslPolicyErrors.ToString();
        CreateErrorTextFile(sslError);
        Console.WriteLine("Error:" + sslError);
        return isServerVerified;
    }

    private static void CreateErrorTextFile(string error)
    {
        string fileName = @"C:\Temp\SSLErrors.txt";
        using (FileStream fs = File.Create(fileName))
        {
            byte[] errors = new UTF8Encoding(true).GetBytes(error);
            fs.Write(errors, 0, errors.Length);
        }
    }
}
}

`
Wireshark capture shows this:
enter image description here
As per my investigation proper wireshark capture should look like following:
enter image description here

Tried many things but none worked.
Steps taken to resolve this :

Ran IISCrypto
Certificates checked and are latest and have no problem according to me.
Verified TLS 1.2 is enabled or not, but it was enabled
Working on all other system, other than server machine.
Windows is updated to the latest.
Firewalls are also disabled.
Please let me know how can I make this hand shake successful so that application interacts successfully with RabbitMQ

Ran IISCrypto
Certificates checked and are latest and have no problem according to me.
Verified TLS 1.2 is enabled or not, but it was enabled
Working on all other system, other than server machine.
Windows is updated to the latest.
Firewalls are also disabled.
Please let me know how can I make this hand shake successful so that application interacts successfully with RabbitMQ


来源: stackexchange

问:
Can I run compaction in multiple graph spaces in the NebulaGraph database?
I'm running Nebula Graph database on AWS with the Twitter dataset (3 graph spaces), and each space has a data volume of around 500GB.

I know that the compaction process is quite time-consuming. Can I run compaction for all 3 graph spaces at the same time? I don't want to get an OOM. I don't see a caution in their docs, but I still doubt it.

ContentLicense: CC BY-SA 4.0


问:
The issue with Pylance expecting an expression or "." or "(" not being closed is likely due to syntax errors in my code, but where?
Someone suggested this but it DOESN'T work either.

In the line AVCaptureDevice.requestAccess (for: .video), the parenthesis around for: .video should be removed as it is not a valid syntax in Python. Instead, you should separate the keyword argument for and its value .video with a comma.

In the line AVCaptureDevice.authorizationStatus, the dot notation is not correct. You should use the square brackets notation to access the authorizationStatus attribute of the AVCaptureDevice class.

Here is my code:

```<code>import cv2
import numpy as np
from AVFoundation import AVCaptureDevice

class Camera(object):
    def __init__(self, camera=0):
        AVCaptureDevice.requestAccess(for: .video) { granted in
            if granted:
                self.cam = cv2.VideoCapture(camera)
                self.valid = False
                try:
                    resp = self.cam.read()
                    self.shape = resp[1].shape
                    self.valid = True
                except:
                    self.shape = None
            else:
                print("Permission to access camera was denied.")
                self.valid = False
        }

    def get_frame(self):
        if self.valid:
            _, frame = self.cam.read()
        else:
            frame = np.ones((480, 640, 3), dtype=np.uint8)
            col = (0, 256, 256)
            cv2.putText(frame, "(Error: Camera not accessible)",
                        (65, 220), cv2.FONT_HERSHEY_PLAIN, 2, col)
        return frame

    def release(self):
        self.cam.release()
</code>```

Help me to resolve this "syntax error" so I can compile the code to execute a functional py2app.

Body:
Someone suggested this but it DOESN'T work either.

In the line AVCaptureDevice.requestAccess (for: .video), the parenthesis around for: .video should be removed as it is not a valid syntax in Python. Instead, you should separate the keyword argument for and its value .video with a comma.

In the line AVCaptureDevice.authorizationStatus, the dot notation is not correct. You should use the square brackets notation to access the authorizationStatus attribute of the AVCaptureDevice class.

Here is my code:

import cv2
import numpy as np
from AVFoundation import AVCaptureDevice

class Camera(object):
    def __init__(self, camera=0):
        AVCaptureDevice.requestAccess(for: .video) { granted in
            if granted:
                self.cam = cv2.VideoCapture(camera)
                self.valid = False
                try:
                    resp = self.cam.read()
                    self.shape = resp[1].shape
                    self.valid = True
                except:
                    self.shape = None
            else:
                print("Permission to access camera was denied.")
                self.valid = False
        }

    def get_frame(self):
        if self.valid:
            _, frame = self.cam.read()
        else:
            frame = np.ones((480, 640, 3), dtype=np.uint8)
            col = (0, 256, 256)
            cv2.putText(frame, "(Error: Camera not accessible)",
                        (65, 220), cv2.FONT_HERSHEY_PLAIN, 2, col)
        return frame

    def release(self):
        self.cam.release()

Help me to resolve this "syntax error" so I can compile the code to execute a functional py2app.


问:
Would it be better to organize this in multiple functions or make one that takes different arguments ? (PL/SQL)
in your opinion, what would be the best or most efficient way to do this.

I'm working with treegrid where you can edit a row, add a new one, or remove existing one.

Save button triggers creating a json file

EDIT

ADD (INSERT)

REMOVE

Now I have to write a procedure that is also triggered with save button that would actually store these changes into the database.

I have something like this for updating.

```<code>create or replace function updateDrivers (p_data varchar2)
return varchar2
IS
    p_result     varchar2(50);
    p_team_name varchar2(50);
    p_driver_name varchar2(50);
    p_driver_lastName varchar2(50);
    p_driverID varchar2(50);
Begin

SELECT JSON_value(p_data,'$.Changes.ime_tima') INTO p_team_name from dual;
SELECT JSON_value(p_data,'$.Changes.ime_vozaca') INTO p_driver_name from dual;
SELECT JSON_value(p_data,'$.Changes.prezime_vozaca') INTO p_driver_lastName from dual;
SELECT JSON_value(p_data,'$.Changes.id') INTO p_driverID from dual;

    UPDATE drivers
        SET ime_tima = p_team_name,
            ime_vozaca = p_driver_name,
            prezime_vozaca = p_driver_lastName
        where id =  p_driverID;
    p_result := '1|success!';
    return p_result;
EXCEPTION
    WHEN OTHERS THEN
        p_result := '-1|Error!';
        RETURN p_result;
END updateDrivers;
</code>```

The problem is, I have multiple tables, this one is example for drivers, but I have one for teams, races etc. Would it be better to make one procedure for every action (update/insert/delete) and for each table or should I make it one procedure which takes different arguments depending on the table and action.

Body:
in your opinion, what would be the best or most efficient way to do this.

I'm working with treegrid where you can edit a row, add a new one, or remove existing one.

Save button triggers creating a json file

EDIT

ADD (INSERT)

REMOVE

Now I have to write a procedure that is also triggered with save button that would actually store these changes into the database.

I have something like this for updating.

create or replace function updateDrivers (p_data varchar2)
return varchar2
IS
    p_result     varchar2(50);
    p_team_name varchar2(50);
    p_driver_name varchar2(50);
    p_driver_lastName varchar2(50);
    p_driverID varchar2(50);
Begin

SELECT JSON_value(p_data,'$.Changes.ime_tima') INTO p_team_name from dual;
SELECT JSON_value(p_data,'$.Changes.ime_vozaca') INTO p_driver_name from dual;
SELECT JSON_value(p_data,'$.Changes.prezime_vozaca') INTO p_driver_lastName from dual;
SELECT JSON_value(p_data,'$.Changes.id') INTO p_driverID from dual;

    UPDATE drivers
        SET ime_tima = p_team_name,
            ime_vozaca = p_driver_name,
            prezime_vozaca = p_driver_lastName
        where id =  p_driverID;
    p_result := '1|success!';
    return p_result;
EXCEPTION
    WHEN OTHERS THEN
        p_result := '-1|Error!';
        RETURN p_result;
END updateDrivers;

The problem is, I have multiple tables, this one is example for drivers, but I have one for teams, races etc. Would it be better to make one procedure for every action (update/insert/delete) and for each table or should I make it one procedure which takes different arguments depending on the table and action.


问:
Quota exceeded for quota metric saying that "status = StatusCode.RESOURCE_EXHAUSTED"
I am using Google Assistant Service in my project. After few usages, the assistant is not recording audio input and I get a message in terminal</p>
```<code>status = StatusCode.RESOURCE_EXHAUSTED
details = "Quota exceeded for quota metric 'embedded-assistant-prod/converse_requests' and limit 'ConverseRequestsPerDayPerProject' of service 'embeddedassistant.googleapis.com' for consumer 'project_number:55xxxxxxxxxx'."

debug_error_string = "UNKNOWN:Error received from peer ipv6:%5B2404:6800:4009:81D::200a%5D:443 {grpc_message:"Quota exceeded for quota metric \'embedded-assistant-prod/converse_requests\' and limit \'ConverseRequestsPerdayPerProject\' of service \'embeddedassistant.googleapis.com\' for consumer \'project_number:55xxxxxxxxxx\'."`,grpc_status:8, created_time:"2022-12-28T12:56:05.71738653+05:30"}"``

I think there is some quota limit for Google Assistant API. If it is so, I want help to increase this quota limit or just completely get rid off it. Please someone help me or the Google Team itself help me please...
</code>```

Body:
I am using Google Assistant Service in my project. After few usages, the assistant is not recording audio input and I get a message in terminal

status = StatusCode.RESOURCE_EXHAUSTED
details = "Quota exceeded for quota metric 'embedded-assistant-prod/converse_requests' and limit 'ConverseRequestsPerDayPerProject' of service 'embeddedassistant.googleapis.com' for consumer 'project_number:55xxxxxxxxxx'."

debug_error_string = "UNKNOWN:Error received from peer ipv6:%5B2404:6800:4009:81D::200a%5D:443 {grpc_message:"Quota exceeded for quota metric \'embedded-assistant-prod/converse_requests\' and limit \'ConverseRequestsPerdayPerProject\' of service \'embeddedassistant.googleapis.com\' for consumer \'project_number:55xxxxxxxxxx\'."`,grpc_status:8, created_time:"2022-12-28T12:56:05.71738653+05:30"}"``

I think there is some quota limit for Google Assistant API. If it is so, I want help to increase this quota limit or just completely get rid off it. Please someone help me or the Google Team itself help me please...


问:
Adobe Sign API: "access_denied: Scopes not enabled for this application" while creating OAUTH access token
I want to create an access token for the "Acrobat Sign REST API V6".
I'm logged into the echosign backend https://newsign.eu1.echosign.com/public/docs/restapi/v6#!/

Now I try to create the access token. I click on the "baseUris" section and then on the "OAUTH ACCESS-TOKEN" button.

Then I enable every of the scopes and then I click on the button "Authorize". I get the following error message:

```<code>access_denied: Scopes not enabled for this application
</code>```

Body:
I want to create an access token for the "Acrobat Sign REST API V6".
I'm logged into the echosign backend https://newsign.eu1.echosign.com/public/docs/restapi/v6#!/

Now I try to create the access token. I click on the "baseUris" section and then on the "OAUTH ACCESS-TOKEN" button.

Then I enable every of the scopes and then I click on the button "Authorize". I get the following error message:

access_denied: Scopes not enabled for this application


问:
matchMedia('print') fires twice with true and false
When I add matchMedia listener:

```<code>matchMedia('print').onchange = (m) => { console.log('print matches', m.matches)}
</code>```

And I open print dialog, I always see two logs:

```<code>print matches true
print matches false
</code>```

After firing callback with value true, there is immediately another callback with value false even when printing dialog is still open. I would expect that this woud happen only after closing dialog.

Can someone explain to me why it happens?

Body:
When I add matchMedia listener:

matchMedia('print').onchange = (m) => { console.log('print matches', m.matches)}

And I open print dialog, I always see two logs:

print matches true
print matches false

After firing callback with value true, there is immediately another callback with value false even when printing dialog is still open. I would expect that this woud happen only after closing dialog.

Can someone explain to me why it happens?


问:
GetCallback as soon as user presses recent app button for Android 12 & above
I want to get callback as soon as moves away from the app.  This should include 2 cases.

When user presses home button & the app is minimised.

When user presses recent app button, where app is visible but has lost focus.

Before Android 12, I was able to achieve it via following ways by placing this code in application class

```<code>override fun onActivityResumed(activity: Activity) {
        activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
    }

override fun onActivityPaused(activity: Activity) {
        activity.window.setFlags(
            WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE
        )
    }
</code>```

But for devices running Android 12 & above, callback is not sent to onActivityPaused for case 2. And happens only for case 1

Another way for this to work is

```<code>override fun onWindowFocusChanged(hasFocus: Boolean) {
    super.onWindowFocusChanged(hasFocus)
    if (!hasFocus) {
        Timber.d("Ujjwal: Lost focus")
    }
}
</code>```

But there are 2 issues:

I will have to put in all activities or some BaseActivity

There are cases when the flow goes to some 3rd party SDK which has their own activity launched, this workaround won't work in those scenarios.

Can anyone help here.

Main objective is whenever user moves out of the app, the app should not take screenshot & show that data in recent app screen due to security & sensitive data.

The implementation needs to be done in application class & should work for all Android versions.

Body:
I want to get callback as soon as moves away from the app.  This should include 2 cases.

When user presses home button & the app is minimised.

When user presses recent app button, where app is visible but has lost focus.

Before Android 12, I was able to achieve it via following ways by placing this code in application class

override fun onActivityResumed(activity: Activity) {
        activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
    }

override fun onActivityPaused(activity: Activity) {
        activity.window.setFlags(
            WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE
        )
    }

But for devices running Android 12 & above, callback is not sent to onActivityPaused for case 2. And happens only for case 1

Another way for this to work is

override fun onWindowFocusChanged(hasFocus: Boolean) {
    super.onWindowFocusChanged(hasFocus)
    if (!hasFocus) {
        Timber.d("Ujjwal: Lost focus")
    }
}

But there are 2 issues:

I will have to put in all activities or some BaseActivity

There are cases when the flow goes to some 3rd party SDK which has their own activity launched, this workaround won't work in those scenarios.

Can anyone help here.

Main objective is whenever user moves out of the app, the app should not take screenshot & show that data in recent app screen due to security & sensitive data.

The implementation needs to be done in application class & should work for all Android versions.


问:
Significant query performance difference when using $or
Compound Index:

```<code>{
  "A": 1,
  "C": 1,
  "D": 1,
  "E": 1,
  "F": 1,
  "G": 1,
  "H": 1,
  "I": 1,

  "B": 1
}
</code>```

Fast query:

```<code>    const result = await sandbox
      .aggregate([
        {
          $match: {
            A: { $in: [1, 2] },
            C: { $in: [1, 2] },
            D: { $in: [1, 2] },
            E: { $in: [1, 2] },
            F: { $in: [1, 2] },
            G: { $in: [1, 2] },
            H: { $in: [1, 2] },
            I: { $in: [1, 2] },

            B: { $eq: 500 },
          },
        },
      ])
</code>```

The query becomes significantly slower if it is modified to be this:

```<code>    const result = await sandbox
      .aggregate([
        {
          $match: {
            $or: [{ A: { $eq: 1 } }, { A: { $eq: 2 } }],
            $or: [{ C: { $eq: 1 } }, { C: { $eq: 2 } }],
            $or: [{ D: { $eq: 1 } }, { D: { $eq: 2 } }],
            $or: [{ E: { $eq: 1 } }, { E: { $eq: 2 } }],
            $or: [{ F: { $eq: 1 } }, { F: { $eq: 2 } }],
            $or: [{ G: { $eq: 1 } }, { G: { $eq: 2 } }],
            $or: [{ H: { $eq: 1 } }, { H: { $eq: 2 } }],
            $or: [{ I: { $eq: 1 } }, { I: { $eq: 2 } }],

            B: { $eq: 500 },
          },
        },
      ])
</code>```

What is the reason for this?

EDITED:

After using explain, it is confirmed that in the fast query, the index was scanned while in the slow query with $or statement, the collection scan was used.

Now the question becomes, why isn't MongoDB able to use the index scan with $or conditions.

Body:
Compound Index:

{
  "A": 1,
  "C": 1,
  "D": 1,
  "E": 1,
  "F": 1,
  "G": 1,
  "H": 1,
  "I": 1,

  "B": 1
}

Fast query:

    const result = await sandbox
      .aggregate([
        {
          $match: {
            A: { $in: [1, 2] },
            C: { $in: [1, 2] },
            D: { $in: [1, 2] },
            E: { $in: [1, 2] },
            F: { $in: [1, 2] },
            G: { $in: [1, 2] },
            H: { $in: [1, 2] },
            I: { $in: [1, 2] },

            B: { $eq: 500 },
          },
        },
      ])

The query becomes significantly slower if it is modified to be this:

    const result = await sandbox
      .aggregate([
        {
          $match: {
            $or: [{ A: { $eq: 1 } }, { A: { $eq: 2 } }],
            $or: [{ C: { $eq: 1 } }, { C: { $eq: 2 } }],
            $or: [{ D: { $eq: 1 } }, { D: { $eq: 2 } }],
            $or: [{ E: { $eq: 1 } }, { E: { $eq: 2 } }],
            $or: [{ F: { $eq: 1 } }, { F: { $eq: 2 } }],
            $or: [{ G: { $eq: 1 } }, { G: { $eq: 2 } }],
            $or: [{ H: { $eq: 1 } }, { H: { $eq: 2 } }],
            $or: [{ I: { $eq: 1 } }, { I: { $eq: 2 } }],

            B: { $eq: 500 },
          },
        },
      ])

What is the reason for this?

EDITED:

After using explain, it is confirmed that in the fast query, the index was scanned while in the slow query with $or statement, the collection scan was used.

Now the question becomes, why isn't MongoDB able to use the index scan with $or conditions.


问:
SSAS "The Subscription identifier is invalid"
We switched from a SQL server 2017 to a newer SQL server 2019. We deployed all our SSIS-packages in the same way to the newer server. Since then we have often the same error on processing-tasks like cube-processing or dimension-processing on the newer server:

Error: Trace: The Subscription identifier is invalid; it must be unique when subscribing and the identifier of a registerd subscription when unsubscribing.

So our jobs are failing. Some jobs are scheduled every ten minutes. They don't fail always, but sometimes within a day.

I changed our SSIS-package with SSAS-tasks from a projecttype of sql server 2017 to the projecttype of sql server 2019, but this didn't solve this problem. I have no clue what is wrong.


问:
how to check is printer out of paper, Win32_Printer, PrinterState, PrinterStatus, DetectedErrorState not working
```<code>bool IsOffline = false;

            ManagementObjectSearcher searcher = new
            ManagementObjectSearcher("SELECT * FROM Win32_Printer where Name='" + printer_name + "'");
            foreach (ManagementObject printer in searcher.Get())
            {

                ReadyCheck(printer);
                IsOffline = (bool)printer["WorkOffline"];
                var ans =printer["PrinterState"];
                var sdgs = Int32.Parse(printer["PrinterStatus"].ToString());
                switch (Int32.Parse(printer["DetectedErrorState"].ToString()))
                {
                    case 1: Console.WriteLine("Other"); break;
                    case 2: Console.WriteLine("Unknown"); break;
                    case 3: Console.WriteLine("Idle"); break;
                    case 4: Console.WriteLine("Printing"); break;
                    case 5: Console.WriteLine("Warmup"); break;
                    case 6: Console.WriteLine("Stopped printing"); break;
                    case 7: Console.WriteLine("Offline"); break;
                    default: Console.WriteLine("sfaasf"); break;
                }
            }

            if (!IsOffline)
            {
               // ReadyCheck(printer);
            }
</code>```

//PrinterStatus this gives always 3 and Idle its not supported by my Xprinter XP -80c

I expected any changes in answers but always got false in out of paper

Body:
bool IsOffline = false;

            ManagementObjectSearcher searcher = new
            ManagementObjectSearcher("SELECT * FROM Win32_Printer where Name='" + printer_name + "'");
            foreach (ManagementObject printer in searcher.Get())
            {

                ReadyCheck(printer);
                IsOffline = (bool)printer["WorkOffline"];
                var ans =printer["PrinterState"];
                var sdgs = Int32.Parse(printer["PrinterStatus"].ToString());
                switch (Int32.Parse(printer["DetectedErrorState"].ToString()))
                {
                    case 1: Console.WriteLine("Other"); break;
                    case 2: Console.WriteLine("Unknown"); break;
                    case 3: Console.WriteLine("Idle"); break;
                    case 4: Console.WriteLine("Printing"); break;
                    case 5: Console.WriteLine("Warmup"); break;
                    case 6: Console.WriteLine("Stopped printing"); break;
                    case 7: Console.WriteLine("Offline"); break;
                    default: Console.WriteLine("sfaasf"); break;
                }
            }

            if (!IsOffline)
            {
               // ReadyCheck(printer);
            }

//PrinterStatus this gives always 3 and Idle its not supported by my Xprinter XP -80c

I expected any changes in answers but always got false in out of paper


问:
Hello friend, how can I view the code debugger in devtools (Edge)?
I wrote a function to compute the square of a number as follows:

Above this code are 43 commented lines.

I want to visualize the step-by-step execution of the function and see the values of the variables. Yes, it can be visualized in VS Code too but I need to see it working in the browser console (just like it works for everyone)

Also I have tried Run & debug in VSCode along with configuring the launch.json file. It works but the breakpoint doesn't bind. So I am currently not thinking about connecting the browser and vscode. I am only concerned about the debugger in the browser devtools.

Please note that I have seen several YouTube videos stating about breakpoints and writing debugger keyword inside the function but the debugger just doesn't come up (neither in Edge nor Chrome). I am intrigued why is it the case.

These are the videos I have seen (Hindi):

https://www.youtube.com/watch?v=ek2hhFZNul8&t=459s

https://www.youtube.com/watch?v=Z95IGBWyK1I&t=152s

I am expecting the debugger in my browser to show up just like it works for them because I have done what they have told me to do.


Title: ValueError: cannot reindex on an axis with duplicate labels when adding EMAs via group_by

Body:
Sorry for the noob question.

I have a bunch of minute data like so:

                     timestamp    open  high     low   close  volume  trade_count      vwap symbol  volume_10_day
0       2021-06-28 11:15:00+00:00  1.8899  1.89  1.8899  1.8900    1200            2  1.889942   AADI       102027.6
1       2021-06-28 13:15:00+00:00  1.8200  1.82  1.8100  1.8100     710            8  1.818282   AADI       102027.6
2       2021-06-28 13:30:00+00:00  1.8600  1.87  1.8500  1.8600   13845           52  1.858409   AADI       102027.6
3       2021-06-28 13:35:00+00:00  1.8659  1.87  1.8626  1.8700     860            5  1.867670   AADI       102027.6
4       2021-06-28 13:40:00+00:00  1.8700  1.87  1.8477  1.8477    7386           33  1.859019   AADI       102027.6
...                           ...     ...   ...     ...     ...     ...          ...       ...    ...            ...
423069  2021-01-13 00:35:00+00:00  1.2600  1.27  1.2500  1.2600  242391          140  1.260218    ZOM       122065.8
423070  2021-01-13 00:40:00+00:00  1.2600  1.26  1.2500  1.2600  129074          108  1.256255    ZOM       122065.8
423071  2021-01-13 00:45:00+00:00  1.2500  1.26  1.2500  1.2500  297198          151  1.253695    ZOM       122065.8
423072  2021-01-13 00:50:00+00:00  1.2600  1.26  1.2500  1.2600  223822          121  1.256325    ZOM       122065.8
423073  2021-01-13 00:55:00+00:00  1.2600  1.26  1.2500  1.2600  378248          222  1.255110    ZOM       122065.8

[423074 rows x 10 columns]

timestamp   open    high    low close   volume  trade_count vwap    symbol  volume_10_day
2021-07-26 13:00:00+00:00   2.7799  2.78    2.68    2.7 182448  285 2.712106    SOS 6552.7
2021-07-26 13:05:00+00:00   2.7 2.71    2.68    2.69    46906   154 2.692083    SOS 6552.7

I am then grouping them by their symbols, and adding EMAs to them:

ema72 = lambda x: ta.ema(df.loc[x.index, "close"], 72)
ema89 = lambda x: ta.ema(df.loc[x.index, "close"], 89)
ema216 = lambda x: ta.ema(df.loc[x.index, "close"], 216)
ema267 = lambda x: ta.ema(df.loc[x.index, "close"], 267)
ema200 = lambda x: ta.ema(df.loc[x.index, "close"], 200)

df["EMA72"] = df.groupby(['symbol']).apply(ema72).reset_index(0,drop=True)
df["EMA89"] = df.groupby(['symbol']).apply(ema89).reset_index(0,drop=True)
df["EMA216"] = df.groupby(['symbol']).apply(ema216).reset_index(0,drop=True)
df["EMA267"] = df.groupby(['symbol']).apply(ema267).reset_index(0,drop=True)
df["EMA200"] = df.groupby(['symbol']).apply(ema200).reset_index(0,drop=True)

Which gives the error:

    raise ValueError("cannot reindex on an axis with duplicate labels")
ValueError: cannot reindex on an axis with duplicate labels

What am I doing wrong here?

UPDATE

I can add the 72 and 89 ema fine by doing:

df["EMA72"] = df.groupby(['symbol']).apply(ema72).reset_index(0,drop=True)
df = df[~df.index.duplicated()]
df["EMA89"] = df.groupby(['symbol']).apply(ema89).reset_index(0,drop=True)
df = df[~df.index.duplicated()]

Will result in:

                       timestamp    open    high   low  close  volume  trade_count      vwap symbol  volume_10_day     EMA72     EMA89
0       2021-07-06 13:30:00+00:00  1.7200  1.7300  1.71  1.730   23342           54  1.723628   AADI       102027.6       NaN       NaN
1       2021-07-06 13:35:00+00:00  1.7300  1.7300  1.72  1.720   13225           26  1.729698   AADI       102027.6       NaN       NaN
2       2021-07-06 13:40:00+00:00  1.7199  1.7199  1.71  1.715    1740           12  1.712175   AADI       102027.6       NaN       NaN
3       2021-07-06 13:45:00+00:00  1.7150  1.7177  1.71  1.710    1223            9  1.714411   AADI       102027.6       NaN       NaN
4       2021-07-06 13:50:00+00:00  1.7100  1.7100  1.71  1.710     900            1  1.710000   AADI       102027.6       NaN       NaN
...                           ...     ...     ...   ...    ...     ...          ...       ...    ...            ...       ...       ...
247074  2021-01-13 00:35:00+00:00  1.2600  1.2700  1.25  1.260  242391          140  1.260218    ZOM       122065.8  1.264493  1.258082
247075  2021-01-13 00:40:00+00:00  1.2600  1.2600  1.25  1.260  129074          108  1.256255    ZOM       122065.8  1.264370  1.258125
247076  2021-01-13 00:45:00+00:00  1.2500  1.2600  1.25  1.250  297198          151  1.253695    ZOM       122065.8  1.263976  1.257944
247077  2021-01-13 00:50:00+00:00  1.2600  1.2600  1.25  1.260  223822          121  1.256325    ZOM       122065.8  1.263867  1.257990
247078  2021-01-13 00:55:00+00:00  1.2600  1.2600  1.25  1.260  378248          222  1.255110    ZOM       122065.8  1.263761  1.258035

[247079 rows x 12 columns]

But doing this:

df["EMA72"] = df.groupby(['symbol']).apply(ema72).reset_index(0,drop=True)
df = df[~df.index.duplicated()]
df["EMA89"] = df.groupby(['symbol']).apply(ema89).reset_index(0,drop=True)
df = df[~df.index.duplicated()]
df["EMA216"] = df.groupby(['symbol']).apply(ema216).reset_index(0,drop=True)
df = df[~df.index.duplicated()]
df["EMA267"] = df.groupby(['symbol']).apply(ema267).reset_index(0,drop=True)
df = df[~df.index.duplicated()]
df["EMA200"] = df.groupby(['symbol']).apply(ema200).reset_index(0,drop=True)
df = df[~df.index.duplicated()]

Gives the error:

    raise ValueError("cannot reindex on an axis with duplicate labels")
ValueError: cannot reindex on an axis with duplicate labels

I have tried removing the duplicated timestamps for each symbol:

df = df.groupby(['symbol', 'timestamp'])
df = df.last().sort_index().reset_index()

247079 // before
233228 // after

But it still gives the same error

I thought it may be something to do with the functions but when I do this:

df["EMA200"] = df.groupby('symbol')['close'].rolling(200).mean()

The error persists


问:
Is there a way to import python package correctly from external folder?
I have a python package folder, I am using regularly. As part of my work, I have multiple versions of this package folder.

The folder look something like this,

Main folder

scripts.ipynb

other stuff

package folder

init.py

all submodules folders

The init.py file consists of 'import package_name.submodule_name' lines. I have many main folders, like this one, for all the different versions. If I run the scripts.ipynb notebook, then it works correctly with the wanted package version.

But if I run the notebook, outside of the main_folder, it seems I can not import the package correctly. I want to have the ability to run single scripts notebook, where I can toggle and switch between the different main folders/packages.

Giving unique name for every package is very tedious work, because the name of the package is repeated numerous time along the files. I tried to append the python path to the system, or set the PYTHONPATH to look at the correct folder, but it doesn't help.

In the case of appending the python path to sys, the import routine goes to the correct init.py file, but inside the file it fails to import the submodules. When setting the PYTHONPATH to the folder, no error is given, but the functionality is incorrect (error at first call).


问:
I'm getting USBD_BUSY when i try to transmit sensor readings from sensor to my computer via virtual com port
I'm trying to transmit MPU6050 sensor readings to my computer via virtual comport.I'm using STM32 Nucleo F446RE. As far as i can see in debug mode there is no issue in sensor and sensor readings. Problem is I can't transmit them using USB. Are there anyone who have experienced this issue before?

In the tutorial I watched the guy can transmit sensor reading with USB port and can see them with a serial port reader program. I'm sure that there is no issue in sensor the card sees sensor. I don't know why it keeps returning USBD_BUSY.

Transmit Code I'm using


问:
Google Maps Streetview working on web and emulator. But not working real device black screen
Street view that works on web and Android Emulator does not work on real device. I also tested Android 12, Android 9 and Android 13.

Google Maps version on emulator:
11.28.7

Google Maps version on device:
11.60.0703

The result is the same.

```<code>For example: 40.036716,42.171997
</code>```

http://maps.google.com/maps?q=&layer=c&cbll=40.036716,42.171997

```<code>String destinationCoord = "40.036716,42.171997";
Uri uri = Uri.parse("google.streetview:cbll=" + destinationCoord);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
mapIntent.setPackage("com.google.android.apps.maps");
mContext.startActivity(mapIntent);
</code>```

Body:
Street view that works on web and Android Emulator does not work on real device. I also tested Android 12, Android 9 and Android 13.

Google Maps version on emulator:
11.28.7

Google Maps version on device:
11.60.0703

The result is the same.

For example: 40.036716,42.171997

http://maps.google.com/maps?q=&layer=c&cbll=40.036716,42.171997

String destinationCoord = "40.036716,42.171997";
Uri uri = Uri.parse("google.streetview:cbll=" + destinationCoord);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
mapIntent.setPackage("com.google.android.apps.maps");
mContext.startActivity(mapIntent);


问:
How to use a simple JS database in another js file that is used on the front end - without using webserver
I have an index.html file that displays names:

```<code><div id="names">
  <div>John</div>
  <div>Henry</div>
  <div>Jason</div>
</div>
</code>```

I also have a Javascript file that gets the names from somewhere (internet/database/wherever):

```<code>class NamesDatabase  {
  getNames()  {
    let names = [];

    // fill the names list

    return names;
  }
}
</code>```

I'd like to use the NamesDatabase.js in a index.js file, in this way:

```<code>document.addEventListener("DOMContentLoaded", function(){
  let database = new NamesDatabase();
  let names = database.getNames();

  let namesDiv = document.getElementById("names");
  names.forEach((name) =>  {
    // add a new child to namesDiv
  });
}
</code>```

I tried using

```<code><script type="module" src="NamesDatabase.js"></script>
</code>```

to import it inside index.html, however I got the access blocked cors error.

What is the preferred way of going about this problem, without using a webserver such as Express?

Body:
I have an index.html file that displays names:

John

Henry

Jason

I also have a Javascript file that gets the names from somewhere (internet/database/wherever):

class NamesDatabase  {
  getNames()  {
    let names = [];

    // fill the names list

    return names;
  }
}

I'd like to use the NamesDatabase.js in a index.js file, in this way:

document.addEventListener("DOMContentLoaded", function(){
  let database = new NamesDatabase();
  let names = database.getNames();

  let namesDiv = document.getElementById("names");
  names.forEach((name) =>  {
    // add a new child to namesDiv
  });
}

I tried using

to import it inside index.html, however I got the access blocked cors error.

What is the preferred way of going about this problem, without using a webserver such as Express?


问:
Django fails to migrate | ValueError: Cannot serialize: <Price: 0.99 €>
I am trying to migrate some changes on a Model but it doesn't apply the migration because of this Model:

```<code>class Price(models.Model):
    price = models.FloatField(default=0.00)
    type = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return f'{self.price} €'
</code>```

Error:

```<code>ValueError: Cannot serialize: <Price: 0.99 €>
There are some values Django cannot serialize into migration files.
</code>```

Migration file:

```<code>Migrations for 'core':
  core/migrations/0001_initial.py
    - Create model Album
    - Create model Genre
    - Create model Language
    - Create model Price
    - Create model Services
    - Create model Track
    - Create model Songwriter
    - Create model Artist
    - Add field artist to album
    - Add field language to album
    - Add field price to album
    - Add field primary_genre to album
    - Add field secondary_genre to album
    - Add field services to album
    - Add field user to album
    - Create model Account
</code>```

Body:
I am trying to migrate some changes on a Model but it doesn't apply the migration because of this Model:

class Price(models.Model):
    price = models.FloatField(default=0.00)
    type = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return f'{self.price} €'

Error:

ValueError: Cannot serialize: <Price: 0.99 €>
There are some values Django cannot serialize into migration files.

Migration file:

Migrations for 'core':
  core/migrations/0001_initial.py
    - Create model Album
    - Create model Genre
    - Create model Language
    - Create model Price
    - Create model Services
    - Create model Track
    - Create model Songwriter
    - Create model Artist
    - Add field artist to album
    - Add field language to album
    - Add field price to album
    - Add field primary_genre to album
    - Add field secondary_genre to album
    - Add field services to album
    - Add field user to album
    - Create model Account


问:
Install snap() on wsl2 for flutter
I have just started working on flutter SDK. In its installation(for linux) I found the following command

```<code>sudo snap install flutter --classic
</code>```

But it needed snapd to be installed on my computer(wsl). I have windows operating system but I work on WSL (version 2) for my development related activities so I was going through linux installation method. I am unable to find any resources to download snap on my wsl (and do not even know what snap actually is). Can anyone suggest any commands or methods so that I can following along further with this or anyother wy by which i can install flutter in wsl.

Also I tried downloading it manually but that downloads the flutter file over to windows and I also don't know if I could change the file location to wsl from windows. If it could be done this way then please tell.
If any further information is needed, then please tell :)

Title: Install snap() on wsl2 for flutter

Body:
I have just started working on flutter SDK. In its installation(for linux) I found the following command

sudo snap install flutter --classic

But it needed snapd to be installed on my computer(wsl). I have windows operating system but I work on WSL (version 2) for my development related activities so I was going through linux installation method. I am unable to find any resources to download snap on my wsl (and do not even know what snap actually is). Can anyone suggest any commands or methods so that I can following along further with this or anyother wy by which i can install flutter in wsl.

Also I tried downloading it manually but that downloads the flutter file over to windows and I also don't know if I could change the file location to wsl from windows. If it could be done this way then please tell.
If any further information is needed, then please tell :)


问:
Is there a way to configure git revert -n (or --no-commit) as a default in Visual Studio 2022 Git client?
In most cases when I use git revert, I usually want to revert only a couple of files. Is there a way to do so via Visual Studio Git GUI? For now, it doesn't seem to be one, even though there were some related feature requests.

For now in this cases, using git revert -n (or --no-commit) and git reset HEAD  through console is a better option  .


问:
Unity game google in app review not popping up
Unity Version: 2021.3.14f1
Google play core version: 1.8.0

It was working fine and now suddenly it says certificate mismatch. I thought the package name was not matched but no. I released the app in internal testing with all certificates matched. Now even for the internal testers, the In App review window is not showing. Here is the Android Log Preview:
LogCat

I have enabled 'Releases signed by Google Play' so there is not problem with package name since app is released in internal testing.

I tried changing the google play core, play common, and review library. I thought even for internal testers, there may be quota, so i installed the game in an account which have never installed my game before, but no luck.


问:
i18next/next locales without region 404
After installing next-i18next package I noticed that localization won't work (404) with locale only without the region e.g localhost/en/somepage. localhost/en-uk/somepage does work as expected. Here's the config

```<code>    i18n: {
        locales: ['en', 'lt'],
        defaultLocale: 'en',
    },
</code>```

Is it possible to fix this or should I simply rewrite the url?

Title: i18next/next locales without region 404

Body:
After installing next-i18next package I noticed that localization won't work (404) with locale only without the region e.g localhost/en/somepage. localhost/en-uk/somepage does work as expected. Here's the config

    i18n: {
        locales: ['en', 'lt'],
        defaultLocale: 'en',
    },

Is it possible to fix this or should I simply rewrite the url?


问:
invalid_grant error in Bubble.io (Exchange code for token - Discord oAuth)
I am completely stuck here.. the authorization works fine, but keep getting the following error when i initialize my POST request to exchange an oAuth code for a token. This is using Bubble.io and Discord's API.


问:
Flutter: "flutter pub get" gets stuck
I'm trying to get packages, when I run flutter pub get nothing happens or it get stuck

```<code>PS C:\Users\user\Desktop\clone\my_app> flutter pub get
Running "flutter pub get" in my_app...          /
</code>```

Tried upgrading flutter.
Tried running it on multiple networks.

when I used flutter pug get --verbose this was the output:

```<code>    cloud_firestore","homepage":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","repository":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","version":"3.1.0","environment":{"sdk":">=2.16.0
<3.0.0","flutter":">=1.20.0"},"dependencies":{"_flutterfire_internals":"^1.0.9","cloud_firestore_platform_interface":"^5.9.0","collection":"^1.0.0","firebase_core":"^2.3.0","firebase_core_web":"^2.0.1","flutter":{"sdk":"flutter"},"flutter_web_plugins":{"sdk":"flutter"},"js":"^0.6.3"},"dev_dependencies":{"firebase_core_platform_interface":"^4.5.2","flutter_test":{"sdk":"flutter"},"mockito":"^5.0.0"},"flutter":{"plugin":{"platforms":{"web":{"pluginClass":"FirebaseFirestoreWeb","fileName":"cloud_firestore_web.dart"}}}}},"archive_url":"https://pub.dartlang.org/packages/cloud_firestore_web/versions/3.1.0.tar.gz","archive_sha256":"3c9a77380e6a053129c2cb6dbe8ef1b708f4350ce0dad220d2c05cd68a2d467f","published":"2022-11-17T14:00:52.599889Z"},{"version":"3.1.1","pubspec":{"name":"cloud_firestore_web","description":"The web implementation of
cloud_firestore","homepage":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","repository":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","version":"3.1.1","environment":{"sdk":">=2.16.0
<3.0.0","flutter":">=1.20.0"},"dependencies":{"_flutterfire_internals":"^1.0.10","cloud_firestore_platform_interface":"^5.9.1","collection":"^1.0.0","firebase_core":"^2.4.0","firebase_core_web":"^2.0.2","flutter":{"sdk":"flutter"},"flutter_web_plugins":{"sdk":"flutter"},"js":"^0.6.3"},"dev_dependencies":{"firebase_core_platform_interface":"^4.5.2","flutter_test":{"sdk":"flutter"},"mockito":"^5.0.0"},"flutter":{"plugin":{"platforms":{"web":{"pluginClass":"FirebaseFirestoreWeb","fileName":"cloud_firestore_web.dart"}}}}},"archive_url":"https://pub.dartlang.org/packages/cloud_firestore_web/versions/3.1.1.tar.gz","archive_sha256":"b6a5712dc5d74473249b0777b93e6adf0ae68aeabae2699238d4647f3d5e1624","published":"2022-12-08T14:07:35.355432Z"},{"version":"3.2.0","pubspec":{"name":"cloud_firestore_web","description":"The web implementation of
cloud_firestore","homepage":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","repository":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","version":"3.2.0","environment":{"sdk":">=2.16.0
<3.0.0","flutter":">=1.20.0"},"dependencies":{"_flutterfire_internals":"^1.0.11","cloud_firestore_platform_interface":"^5.10.0","collection":"^1.0.0","firebase_core":"^2.4.0","firebase_core_web":"^2.0.2","flutter":{"sdk":"flutter"},"flutter_web_plugins":{"sdk":"flutter"},"js":"^0.6.3"},"dev_dependencies":{"firebase_core_platform_interface":"^4.5.2","flutter_test":{"sdk":"flutter"},"mockito":"^5.0.0"},"flutter":{"plugin":{"platforms":{"web":{"pluginClass":"FirebaseFirestoreWeb","fileName":"cloud_firestore_web.dart"}}}}},"archive_url":"https://pub.dartlang.org/packages/cloud_firestore_web/versions/3.2.0.tar.gz","archive_sha256":"2d7339bf3f79adcdb123a88e908474478b060317332189bdd5dcb2d498952127","published":"2022-12-22T12:35:55.126423Z"}],"_fetchedAt":"2022-12-28T11:16:24.333312"}
</code>```

This is the last 6 lines I get

any kind of help will be appreciated.

Title: Flutter: "flutter pub get" gets stuck

Body:
I'm trying to get packages, when I run flutter pub get nothing happens or it get stuck

PS C:\Users\user\Desktop\clone\my_app> flutter pub get
Running "flutter pub get" in my_app...          /

Tried upgrading flutter.
Tried running it on multiple networks.

when I used flutter pug get --verbose this was the output:

    cloud_firestore","homepage":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","repository":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","version":"3.1.0","environment":{"sdk":">=2.16.0
<3.0.0","flutter":">=1.20.0"},"dependencies":{"_flutterfire_internals":"^1.0.9","cloud_firestore_platform_interface":"^5.9.0","collection":"^1.0.0","firebase_core":"^2.3.0","firebase_core_web":"^2.0.1","flutter":{"sdk":"flutter"},"flutter_web_plugins":{"sdk":"flutter"},"js":"^0.6.3"},"dev_dependencies":{"firebase_core_platform_interface":"^4.5.2","flutter_test":{"sdk":"flutter"},"mockito":"^5.0.0"},"flutter":{"plugin":{"platforms":{"web":{"pluginClass":"FirebaseFirestoreWeb","fileName":"cloud_firestore_web.dart"}}}}},"archive_url":"https://pub.dartlang.org/packages/cloud_firestore_web/versions/3.1.0.tar.gz","archive_sha256":"3c9a77380e6a053129c2cb6dbe8ef1b708f4350ce0dad220d2c05cd68a2d467f","published":"2022-11-17T14:00:52.599889Z"},{"version":"3.1.1","pubspec":{"name":"cloud_firestore_web","description":"The web implementation of
cloud_firestore","homepage":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","repository":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","version":"3.1.1","environment":{"sdk":">=2.16.0
<3.0.0","flutter":">=1.20.0"},"dependencies":{"_flutterfire_internals":"^1.0.10","cloud_firestore_platform_interface":"^5.9.1","collection":"^1.0.0","firebase_core":"^2.4.0","firebase_core_web":"^2.0.2","flutter":{"sdk":"flutter"},"flutter_web_plugins":{"sdk":"flutter"},"js":"^0.6.3"},"dev_dependencies":{"firebase_core_platform_interface":"^4.5.2","flutter_test":{"sdk":"flutter"},"mockito":"^5.0.0"},"flutter":{"plugin":{"platforms":{"web":{"pluginClass":"FirebaseFirestoreWeb","fileName":"cloud_firestore_web.dart"}}}}},"archive_url":"https://pub.dartlang.org/packages/cloud_firestore_web/versions/3.1.1.tar.gz","archive_sha256":"b6a5712dc5d74473249b0777b93e6adf0ae68aeabae2699238d4647f3d5e1624","published":"2022-12-08T14:07:35.355432Z"},{"version":"3.2.0","pubspec":{"name":"cloud_firestore_web","description":"The web implementation of
cloud_firestore","homepage":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","repository":"https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore/cloud_firestore_web","version":"3.2.0","environment":{"sdk":">=2.16.0
<3.0.0","flutter":">=1.20.0"},"dependencies":{"_flutterfire_internals":"^1.0.11","cloud_firestore_platform_interface":"^5.10.0","collection":"^1.0.0","firebase_core":"^2.4.0","firebase_core_web":"^2.0.2","flutter":{"sdk":"flutter"},"flutter_web_plugins":{"sdk":"flutter"},"js":"^0.6.3"},"dev_dependencies":{"firebase_core_platform_interface":"^4.5.2","flutter_test":{"sdk":"flutter"},"mockito":"^5.0.0"},"flutter":{"plugin":{"platforms":{"web":{"pluginClass":"FirebaseFirestoreWeb","fileName":"cloud_firestore_web.dart"}}}}},"archive_url":"https://pub.dartlang.org/packages/cloud_firestore_web/versions/3.2.0.tar.gz","archive_sha256":"2d7339bf3f79adcdb123a88e908474478b060317332189bdd5dcb2d498952127","published":"2022-12-22T12:35:55.126423Z"}],"_fetchedAt":"2022-12-28T11:16:24.333312"}

This is the last 6 lines I get

any kind of help will be appreciated.


问:
Issues with pytorch tensors iteration
I keep getting the error: TypeError: iteration over a 0-d tensor in the code bellow:

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import pandas as pd
import base64
from torch import tensor
import itertools
import random
# Define the neural network model
class ModelClass(nn.Module):
        def __init__(self, input_size, hidden_size, num_layers, output_size, device):
                super(ModelClass, self).__init__()
                self.device = device
                self.hidden_size = hidden_size
                self.num_layers = num_layers
                self.rnn = nn.GRU(input_size, hidden_size, num_layers)
                self.fc = nn.Linear(hidden_size, output_size)

        def forward(self, input, hidden):
                output, hidden = self.rnn(input, hidden)
                output = self.fc(output)
                return output, hidden

        def init_hidden(self):
                return torch.zeros(self.num_layers, 1, self.hidden_size, device=self.device)

        def reward(self,r:int):
                for p in self.model.parameters():
                        p.data += r * p.grad
padding_char = '\0'

def get_data():
        file = open('./payloads/all.txt','r',errors='ignore')
        training_data = file.readlines()
        final = []
        for t in training_data:
                final.append(t.strip())
        training_data = final
        longest = len(max(training_data, key=len))
        shortest = len(min(training_data, key=len))
        char_to_int = {c: i for i, c in enumerate(sorted(set(''.join(training_data))))}
        training_data = [[char_to_int[c] for c in string] for string in training_data]

        return {'data': training_data, 'length': len(char_to_int), 'original': file.readlines(), 'long': longest, 'short': shortest}
def initialize():
        data = get_data()
        original_data = data['original']
        input_size = data['length']
        hidden_size = 256
        num_layers = 8
        minimum = data['short']
        maximum = data['long']
        output_size = random.randint(minimum,maximum)
        device = 'cuda' if torch.cuda.is_available() else 'cpu'

        model = ModelClass(input_size, hidden_size, num_layers, output_size, device)
        optimizer = optim.Adam(model.parameters())
        loss_fn = nn.CrossEntropyLoss()

        return model, optimizer, loss_fn

def int_train_model():
        data = get_data()
        original_data = data['original']
        max_length = data['long']
        shortest = data['short']
        data['data'] = list(data['data'])
        fin = []
        for lis in data['data']:
                for li in lis:
                        fin.append(li)
        data['data'] = fin

        data['data'] = torch.tensor(data['data'], dtype=torch.long)
        print(data['data'])
        model, optimizer, loss_fn = initialize()
        num_epochs = 50
        batch_size = 32

        model.train()
        for epoch in range(num_epochs):
                hidden = model.init_hidden()
                for input, label in data['data']:
                        optimizer.zero_grad()
                        input = input.view(-1, 1).to(device)
                        label = label.view(-1, 1).to(device)
                        output, hidden = model(input, hidden)
                        loss = loss_fn(output, label)
                        loss.backward()
                        optimizer.step()
                print(f'Epoch {epoch+1}/{num_epochs}: Loss {loss.item():.4f}')

if __name__ == '__main__':
        int_train_model()
```

I have the model try and craft it's own SQLi payloads using a wordlist called all.txt. Thank you in advance and I have very little experience with pytorch, numpy, and pandas. So if it would be possible to explain why the error happens and what the fix does that would be great!

Title: Issues with pytorch tensors iteration

Body:
I keep getting the error: TypeError: iteration over a 0-d tensor in the code bellow:

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import pandas as pd
import base64
from torch import tensor
import itertools
import random
# Define the neural network model
class ModelClass(nn.Module):
        def __init__(self, input_size, hidden_size, num_layers, output_size, device):
                super(ModelClass, self).__init__()
                self.device = device
                self.hidden_size = hidden_size
                self.num_layers = num_layers
                self.rnn = nn.GRU(input_size, hidden_size, num_layers)
                self.fc = nn.Linear(hidden_size, output_size)

        def forward(self, input, hidden):
                output, hidden = self.rnn(input, hidden)
                output = self.fc(output)
                return output, hidden

        def init_hidden(self):
                return torch.zeros(self.num_layers, 1, self.hidden_size, device=self.device)

        def reward(self,r:int):
                for p in self.model.parameters():
                        p.data += r * p.grad
padding_char = '\0'

def get_data():
        file = open('./payloads/all.txt','r',errors='ignore')
        training_data = file.readlines()
        final = []
        for t in training_data:
                final.append(t.strip())
        training_data = final
        longest = len(max(training_data, key=len))
        shortest = len(min(training_data, key=len))
        char_to_int = {c: i for i, c in enumerate(sorted(set(''.join(training_data))))}
        training_data = [[char_to_int[c] for c in string] for string in training_data]

        return {'data': training_data, 'length': len(char_to_int), 'original': file.readlines(), 'long': longest, 'short': shortest}
def initialize():
        data = get_data()
        original_data = data['original']
        input_size = data['length']
        hidden_size = 256
        num_layers = 8
        minimum = data['short']
        maximum = data['long']
        output_size = random.randint(minimum,maximum)
        device = 'cuda' if torch.cuda.is_available() else 'cpu'

        model = ModelClass(input_size, hidden_size, num_layers, output_size, device)
        optimizer = optim.Adam(model.parameters())
        loss_fn = nn.CrossEntropyLoss()

        return model, optimizer, loss_fn

def int_train_model():
        data = get_data()
        original_data = data['original']
        max_length = data['long']
        shortest = data['short']
        data['data'] = list(data['data'])
        fin = []
        for lis in data['data']:
                for li in lis:
                        fin.append(li)
        data['data'] = fin

        data['data'] = torch.tensor(data['data'], dtype=torch.long)
        print(data['data'])
        model, optimizer, loss_fn = initialize()
        num_epochs = 50
        batch_size = 32

        model.train()
        for epoch in range(num_epochs):
                hidden = model.init_hidden()
                for input, label in data['data']:
                        optimizer.zero_grad()
                        input = input.view(-1, 1).to(device)
                        label = label.view(-1, 1).to(device)
                        output, hidden = model(input, hidden)
                        loss = loss_fn(output, label)
                        loss.backward()
                        optimizer.step()
                print(f'Epoch {epoch+1}/{num_epochs}: Loss {loss.item():.4f}')

if __name__ == '__main__':
        int_train_model()

I have the model try and craft it's own SQLi payloads using a wordlist called all.txt. Thank you in advance and I have very little experience with pytorch, numpy, and pandas. So if it would be possible to explain why the error happens and what the fix does that would be great!


问:
Is it possible to enter two parameters to the render in <f:ajax render/> on JSF?
I need to get back the difference of the values entered from two date fields on JSF as day, month and year. I have to do this with ajax. Is there a use for render="@param1 @param2"? Or can you suggest a better solution? Java scripts will not be used.

I don't have any information on how to do this.

Isn't there a solution other than prime faces to solve this? I am a beginner level student.


问:
Java Twitter Connector to extract ad filter tweets: 403
Did anyone already implement a Twitter client?
I'm trying to connect to Twitter and extract some tweets filtered by words.
I get back the error 403.

```[hosebird-client-io-thread-0] INFO com.twitter.hbc.httpclient.ClientBase - Hosebird-Client-01 Establishing a connection
[hosebird-client-io-thread-0] WARN com.twitter.hbc.httpclient.ClientBase - Hosebird-Client-01 Error connecting w/ status code - 403, reason - Forbidden```

I've created my Twitter app, and got the consumer/secret keys and the access/secret tokens.

It seems there are some misalignments between this client and the new Tweet API but after googling around I still cannot find the right Twitter client.

Has anyone got one working? Below is a snippet of the code

```
public Client createTwitterClient(BlockingQueue msgQueue){

        /** Declare the host you want to connect to, the endpoint, and authentication (basic auth or oauth) */
        Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
        StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint();
        hosebirdEndpoint.trackTerms(terms);

        // These secrets should be read from a config file
        Authentication hosebirdAuth = new OAuth1(consumerKey, consumerSecret, token, secret);

        ClientBuilder builder = new ClientBuilder()
                .name("Hosebird-Client-01")     // optional: mainly for the logs
                .hosts(hosebirdHosts)
                .authentication(hosebirdAuth)
                .endpoint(hosebirdEndpoint)
                .processor(new StringDelimitedProcessor(msgQueue));

        Client hosebirdClient = builder.build();
        return hosebirdClient;
```

Any help would really appreciate!

Body:
Did anyone already implement a Twitter client?
I'm trying to connect to Twitter and extract some tweets filtered by words.
I get back the error 403.

[hosebird-client-io-thread-0] INFO com.twitter.hbc.httpclient.ClientBase - Hosebird-Client-01 Establishing a connection
[hosebird-client-io-thread-0] WARN com.twitter.hbc.httpclient.ClientBase - Hosebird-Client-01 Error connecting w/ status code - 403, reason - Forbidden

I've created my Twitter app, and got the consumer/secret keys and the access/secret tokens.

It seems there are some misalignments between this client and the new Tweet API but after googling around I still cannot find the right Twitter client.

Has anyone got one working? Below is a snippet of the code

public Client createTwitterClient(BlockingQueue msgQueue){

        /** Declare the host you want to connect to, the endpoint, and authentication (basic auth or oauth) */
        Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
        StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint();
        hosebirdEndpoint.trackTerms(terms);

        // These secrets should be read from a config file
        Authentication hosebirdAuth = new OAuth1(consumerKey, consumerSecret, token, secret);

        ClientBuilder builder = new ClientBuilder()
                .name("Hosebird-Client-01")     // optional: mainly for the logs
                .hosts(hosebirdHosts)
                .authentication(hosebirdAuth)
                .endpoint(hosebirdEndpoint)
                .processor(new StringDelimitedProcessor(msgQueue));

        Client hosebirdClient = builder.build();
        return hosebirdClient;

Any help would really appreciate!


问:
How to get source maps to work with tsc and tsc-alias in TypeScript with Node.js?
My source maps are being generated but they are not accurate. They say what file and function/method they are in, but the line number and column are off. Any idea if it's tsc-alias causing this, and if so, how to fix?

My build command is:

```<code>tsc && tsc-alias
</code>```

My watch command is:

```<code>concurrently --kill-others "tsc -w" "tsc-alias -w"
</code>```

My project is fairly large so hard to isolate to a small example.

My aliases are defined in tsconfig.json like:

```<code>{
  "compilerOptions": {
    "module": "ES6",
    "target": "ES6",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "moduleResolution": "node",
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": "./make",
    "paths": {
      "~": ["."]
    },
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "noImplicitAny": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}
</code>```

And I use it in a circular fashion like:

```<code>import { api } from '~'
</code>```

But the line numbers are off.

Body:
My source maps are being generated but they are not accurate. They say what file and function/method they are in, but the line number and column are off. Any idea if it's tsc-alias causing this, and if so, how to fix?

My build command is:

tsc && tsc-alias

My watch command is:

concurrently --kill-others "tsc -w" "tsc-alias -w"

My project is fairly large so hard to isolate to a small example.

My aliases are defined in tsconfig.json like:

{
  "compilerOptions": {
    "module": "ES6",
    "target": "ES6",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "moduleResolution": "node",
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": "./make",
    "paths": {
      "~": ["."]
    },
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "noImplicitAny": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}

And I use it in a circular fashion like:

import { api } from '~'

But the line numbers are off.


问:
Firebase: Uploading an image through html input and storing it as a property of an object
For learning purposes I decided to make a simple closet imitation website where I could basically add new clothes as objects and store them into firebase database. Where am I currently: I successfully managed to make a registration and login option for the website. When registering, an object of a person, with properties email, full name, encrypted password and username is stored into Realtime Database. After that I managed to make a simple "Add Item" form, where you can fill in name of the item, choose a category from a select input and also upload your own image of an item. After every added item, the item gets stored into Realtime Database into the current's username that is logged in. The current username now gets an extra property "Items" which now stores all the added objects/items. The last thing I managed was to display the items on the screen by using "get", looping through "Items" and dynamically creating a new div with p for name, p for category, and an img for image. So basically I create a new div for every item in database and then I append it to my website.

Now at the time I realized that for uploading images you actually need to use Firebase Storage, so I decided that instead of uploading an image, I will select image through input, get it's URL (URL.createObjectURL) and store that URL as a property inside of the item/object. Now reading the data and displaying the image works fine when adding new items and displaying them, but after closing the browser and opening it again, items display without an image. In the Firefox console I get the following error: Security Error: Content at http://127.0.0.1:5500/home.html may not load data from blob:http://127.0.0.1:5500/e324b58c-97ab-4ba4-b5e9-357dc9b06d92.

Now I realized that this option is not going to work for me due to safety reasons. I decided to store images locally, because I only wanted to learn working with objects and saving them into database. I would really like to understand how can I store an item/object with name, category and image as a properties, into a Firebase database and then retrieve data and display them. My only problem currently is for images, so how can I upload images of different items/objects, store them into database and then retrieve them as object properties.

I would like to say that I'm currently learning so I may use some wrong word terminology regarding programming. Thank you in advance.

Currently I am stuck, so I'm thinking about instead of uploading the images I will just use the images from the web.


问:
pass object by request or asynchronous local storage
i have to store the info about the user and the db connection and pass it to my service/model.

at the moment i pass the request.user object direct to my service/model.

request.user = decodedJwt;
request.user.db = getTenantConnetion(decodedJwt.tenantid);

routes -> controller -> service -> model

it seems i doing something wrong with the  "@fastify/request-context"  but i cant acces the fastify instance in my service or model so i have to pass info
controller (by "fastify.requestContext.get('user')"  )  -> service -> model

How i can access the request context from my service/model or is it better to pass the user object to each function?