问:
Multi Client in server - WebSocket C#
how are you? I hope that you are good, I have a question, how can I do to the server consume multi clients? I put all my code

Server

```<code>using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Consola
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string ip = "127.0.0.1";
            int port = 8080;
            var server = new TcpListener(IPAddress.Parse(ip), port);

            server.Start();
            Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection…", ip, port);

            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("A client connected.");

            NetworkStream stream = client.GetStream();

            // enter to an infinite cycle to be able to handle every change in stream
            while (true)
            {
                while (!stream.DataAvailable) ;
                while (client.Available < 3) ; // match against "get"

                byte[] bytes = new byte[client.Available];
                stream.Read(bytes, 0, client.Available);
                string s = Encoding.UTF8.GetString(bytes);

                if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase))
                {
                    Console.WriteLine("=====Handshaking from client=====\n{0}", s);

                    // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
                    // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
                    // 3. Compute SHA-1 and Base64 hash of the new value
                    // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
                    string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                    string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                    byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                    string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                    // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
                    byte[] response = Encoding.UTF8.GetBytes(
                        "HTTP/1.1 101 Switching Protocols\r\n" +
                        "Connection: Upgrade\r\n" +
                        "Upgrade: websocket\r\n" +
                        "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");

                    stream.Write(response, 0, response.Length);
                }
                else
                {
                    bool fin = (bytes[0] & 0b10000000) != 0,
                        mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
                    int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
                        offset = 2;
                    ulong msglen = (ulong)(bytes[1] & 0b01111111);

                    if (msglen == 126)
                    {
                        // bytes are reversed because websocket will print them in Big-Endian, whereas
                        // BitConverter will want them arranged in little-endian on windows
                        msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
                        offset = 4;
                    }
                    else if (msglen == 127)
                    {
                        // To test the below code, we need to manually buffer larger messages — since the NIC's autobuffering
                        // may be too latency-friendly for this code to run (that is, we may have only some of the bytes in this
                        // websocket frame available through client.Available).
                        msglen = BitConverter.ToUInt64(new byte[] { bytes[9], bytes[8], bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2] }, 0);
                        offset = 10;
                    }

                    if (msglen == 0)
                    {
                        Console.WriteLine("msglen == 0");
                    }
                    else if (mask)
                    {
                        byte[] decoded = new byte[msglen];
                        byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
                        offset += 4;

                        for (ulong i = 0; i < msglen; ++i)
                            decoded[i] = (byte)(bytes[(ulong)offset + i] ^ masks[i % 4]);

                        string text = Encoding.UTF8.GetString(decoded);
                        Console.WriteLine("{0}", text);
                    }
                    else
                        Console.WriteLine("mask bit not set");

                    Console.WriteLine();
                }
            }
        }
    }
}
</code>```

Client

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link href="Content/bootstrap.min.css" type="text/css" rel="stylesheet" />
    <script src="Scripts/jquery-3.6.1.min.js" type="text/javascript"></script>
</head>

<body>
    <div class="card">
        <div class="card-header">
            <h2>Prueba simple de WebSocket</h2>
        </div>
        <div class="card-body">
            <p>
                <textarea cols="60" rows="6" id="cajadetexto"></textarea>
            </p>
            <p>
                <button id="boton" class="btn btn-primary">Enviar</button>
            </p>
            <p>
                <div id="salida"></div>
            </p>
        </div>
    </div>

    <style type="text/css">
        textarea {
            vertical-align: bottom;
        }

        #salida {
            overflow: auto;
        }

        #salida > p {
            overflow-wrap: break-word;
        }

        #salida span {
            color: blue;
        }

        #salida span.error {
            color: red;
        }
    </style>

    <script type="text/javascript">
        $(document).ready(function () {
            const wsUri = "ws://127.0.0.1:8080/";
            const websocket = new WebSocket(wsUri);

            $(document).on("click", "#boton", onClickButton);

            websocket.onopen = (e) => {
                writeToScreen("CONNECTED");
                doSend("WebSocket rocks");
            };

            websocket.onclose = (e) => {
                writeToScreen("DISCONNECTED");
            };

            websocket.onmessage = (e) => {
                writeToScreen(`<span>RESPONSE: ${e.data}</span>`);
            };

            websocket.onerror = (e) => {
                writeToScreen(`<span class="error">ERROR:</span> ${e.data}`);
            };

            function doSend(message) {
                writeToScreen(`SENT: ${message}`);
                websocket.send(message);
            }

            function writeToScreen(message) {
                $("#salida").append("<p>" + message + "</p>");
            }

            function onClickButton() {
                var text = $("#cajadetexto").val();

                text && doSend(text);
                $("#cajadetexto").val("");
                $("#cajadetexto").focus();
            }
        });
    </script>
</body>
</html>
</code>```

I based my code on this link:
https://github.com/mdn/content/blob/main/files/en-us/web/api/websockets_api/writing_websocket_server/index.md?plain=1

Thanks and I wait your answers.

UPGRADE 23/12/2022 12:05

Hi, finally i could implement the threads to the multi clients in the server, this is the code:

```<code>using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace Consola
{
    public class Program
    {
        private static TcpListener tcpListener = new TcpListener(
            IPAddress.Parse("127.0.0.1"),
            8080
        );
        public static void Main(string[] args)
        {
            tcpListener.Start();
            while(true)
            {
                Thread nuevoHilo = new Thread(new ThreadStart(Listeners));
                nuevoHilo.Start();
            }
        }

        private static void Listeners()
        {
            Socket client = tcpListener.AcceptSocket();
            if (client.Connected)
            {
                Console.WriteLine("Client:" + client.RemoteEndPoint + " now connected to server.");
                NetworkStream stream = new NetworkStream(client);

                while (true)
                {
                    while (!stream.DataAvailable) ;
                    while (client.Available < 3) ; // match against "get"

                    byte[] bytes = new byte[client.Available];
                    stream.Read(bytes, 0, client.Available);
                    string s = Encoding.UTF8.GetString(bytes);

                    if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase))
                    {
                        Console.WriteLine("=====Handshaking from client=====\n{0}", s);

                        // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
                        // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
                        // 3. Compute SHA-1 and Base64 hash of the new value
                        // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
                        string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                        string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                        byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                        string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                        // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
                        byte[] response = Encoding.UTF8.GetBytes(
                            "HTTP/1.1 101 Switching Protocols\r\n" +
                            "Connection: Upgrade\r\n" +
                            "Upgrade: websocket\r\n" +
                            "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");

                        stream.Write(response, 0, response.Length);
                    }
                    else
                    {
                        bool fin = (bytes
[o]& 0b10000000) != 0,
                            mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
                        int opcode = bytes
[o]& 0b00001111, // expecting 1 - text message
                            offset = 2;
                        ulong msglen = (ulong)(bytes[1] & 0b01111111);

                        if (msglen == 126)
                        {
                            // bytes are reversed because websocket will print them in Big-Endian, whereas
                            // BitConverter will want them arranged in little-endian on windows
                            msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
                            offset = 4;
                        }
                        else if (msglen == 127)
                        {
                            // To test the below code, we need to manually buffer larger messages — since the NIC's autobuffering
                            // may be too latency-friendly for this code to run (that is, we may have only some of the bytes in this
                            // websocket frame available through client.Available).
                            msglen = BitConverter.ToUInt64(new byte[] { bytes[9], bytes[8], bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2] }, 0);
                            offset = 10;
                        }

                        if (msglen == 0)
                        {
                            Console.WriteLine("msglen == 0");
                        }
                        else if (mask)
                        {
                            byte[] decoded = new byte[msglen];
                            byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
                            offset += 4;

                            for (ulong i = 0; i < msglen; ++i)
                                decoded[i] = (byte)(bytes[(ulong)offset + i] ^ masks[i % 4]);

                            string text = Encoding.UTF8.GetString(decoded);
                            Console.WriteLine("{0}", text);
                        }
                        else
                            Console.WriteLine("mask bit not set");

                        Console.WriteLine();
                    }
                }
            }

            client.Close();
        }
    }
}
</code>```

Now I need that the client view can notify the other clients messages and prevent the OutOfMemoryException when I leave the system very quiet.
This image shows my situation
enter image description here

Title: Multi Client in server - WebSocket C#

Body:
how are you? I hope that you are good, I have a question, how can I do to the server consume multi clients? I put all my code

Server

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Consola
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string ip = "127.0.0.1";
            int port = 8080;
            var server = new TcpListener(IPAddress.Parse(ip), port);

            server.Start();
            Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection…", ip, port);

            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("A client connected.");

            NetworkStream stream = client.GetStream();

            // enter to an infinite cycle to be able to handle every change in stream
            while (true)
            {
                while (!stream.DataAvailable) ;
                while (client.Available < 3) ; // match against "get"

                byte[] bytes = new byte[client.Available];
                stream.Read(bytes, 0, client.Available);
                string s = Encoding.UTF8.GetString(bytes);

                if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase))
                {
                    Console.WriteLine("=====Handshaking from client=====\n{0}", s);

                    // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
                    // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
                    // 3. Compute SHA-1 and Base64 hash of the new value
                    // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
                    string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                    string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                    byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                    string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                    // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
                    byte[] response = Encoding.UTF8.GetBytes(
                        "HTTP/1.1 101 Switching Protocols\r\n" +
                        "Connection: Upgrade\r\n" +
                        "Upgrade: websocket\r\n" +
                        "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");

                    stream.Write(response, 0, response.Length);
                }
                else
                {
                    bool fin = (bytes[0] & 0b10000000) != 0,
                        mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
                    int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
                        offset = 2;
                    ulong msglen = (ulong)(bytes[1] & 0b01111111);

                    if (msglen == 126)
                    {
                        // bytes are reversed because websocket will print them in Big-Endian, whereas
                        // BitConverter will want them arranged in little-endian on windows
                        msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
                        offset = 4;
                    }
                    else if (msglen == 127)
                    {
                        // To test the below code, we need to manually buffer larger messages — since the NIC's autobuffering
                        // may be too latency-friendly for this code to run (that is, we may have only some of the bytes in this
                        // websocket frame available through client.Available).
                        msglen = BitConverter.ToUInt64(new byte[] { bytes[9], bytes[8], bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2] }, 0);
                        offset = 10;
                    }

                    if (msglen == 0)
                    {
                        Console.WriteLine("msglen == 0");
                    }
                    else if (mask)
                    {
                        byte[] decoded = new byte[msglen];
                        byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
                        offset += 4;

                        for (ulong i = 0; i < msglen; ++i)
                            decoded[i] = (byte)(bytes[(ulong)offset + i] ^ masks[i % 4]);

                        string text = Encoding.UTF8.GetString(decoded);
                        Console.WriteLine("{0}", text);
                    }
                    else
                        Console.WriteLine("mask bit not set");

                    Console.WriteLine();
                }
            }
        }
    }
}

Client

<!DOCTYPE html>

    <link href="Content/bootstrap.min.css" type="text/css" rel="stylesheet" />

Prueba simple de WebSocket

                <textarea cols="60" rows="6" id="cajadetexto"></textarea>

                <button id="boton" class="btn btn-primary">Enviar</button>

I based my code on this link:
https://github.com/mdn/content/blob/main/files/en-us/web/api/websockets_api/writing_websocket_server/index.md?plain=1

Thanks and I wait your answers.

UPGRADE 23/12/2022 12:05

Hi, finally i could implement the threads to the multi clients in the server, this is the code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace Consola
{
    public class Program
    {
        private static TcpListener tcpListener = new TcpListener(
            IPAddress.Parse("127.0.0.1"),
            8080
        );
        public static void Main(string[] args)
        {
            tcpListener.Start();
            while(true)
            {
                Thread nuevoHilo = new Thread(new ThreadStart(Listeners));
                nuevoHilo.Start();
            }
        }

        private static void Listeners()
        {
            Socket client = tcpListener.AcceptSocket();
            if (client.Connected)
            {
                Console.WriteLine("Client:" + client.RemoteEndPoint + " now connected to server.");
                NetworkStream stream = new NetworkStream(client);

                while (true)
                {
                    while (!stream.DataAvailable) ;
                    while (client.Available < 3) ; // match against "get"

                    byte[] bytes = new byte[client.Available];
                    stream.Read(bytes, 0, client.Available);
                    string s = Encoding.UTF8.GetString(bytes);

                    if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase))
                    {
                        Console.WriteLine("=====Handshaking from client=====\n{0}", s);

                        // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
                        // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
                        // 3. Compute SHA-1 and Base64 hash of the new value
                        // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
                        string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                        string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                        byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                        string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                        // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
                        byte[] response = Encoding.UTF8.GetBytes(
                            "HTTP/1.1 101 Switching Protocols\r\n" +
                            "Connection: Upgrade\r\n" +
                            "Upgrade: websocket\r\n" +
                            "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");

                        stream.Write(response, 0, response.Length);
                    }
                    else
                    {
                        bool fin = (bytes
[o]& 0b10000000) != 0,
                            mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
                        int opcode = bytes
[o]& 0b00001111, // expecting 1 - text message
                            offset = 2;
                        ulong msglen = (ulong)(bytes[1] & 0b01111111);

                        if (msglen == 126)
                        {
                            // bytes are reversed because websocket will print them in Big-Endian, whereas
                            // BitConverter will want them arranged in little-endian on windows
                            msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
                            offset = 4;
                        }
                        else if (msglen == 127)
                        {
                            // To test the below code, we need to manually buffer larger messages — since the NIC's autobuffering
                            // may be too latency-friendly for this code to run (that is, we may have only some of the bytes in this
                            // websocket frame available through client.Available).
                            msglen = BitConverter.ToUInt64(new byte[] { bytes[9], bytes[8], bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2] }, 0);
                            offset = 10;
                        }

                        if (msglen == 0)
                        {
                            Console.WriteLine("msglen == 0");
                        }
                        else if (mask)
                        {
                            byte[] decoded = new byte[msglen];
                            byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
                            offset += 4;

                            for (ulong i = 0; i < msglen; ++i)
                                decoded[i] = (byte)(bytes[(ulong)offset + i] ^ masks[i % 4]);

                            string text = Encoding.UTF8.GetString(decoded);
                            Console.WriteLine("{0}", text);
                        }
                        else
                            Console.WriteLine("mask bit not set");

                        Console.WriteLine();
                    }
                }
            }

            client.Close();
        }
    }
}

Now I need that the client view can notify the other clients messages and prevent the OutOfMemoryException when I leave the system very quiet.
This image shows my situation
enter image description here


来源: stackexchange

问:
How to get dynamic property from object tree in TypeScript in this example?
I have this TypeScript playground, where it has this code:

```<code>export type ParentScopeType<S> = S extends ScopeType<
  unknown,
  infer PS
>
  ? PS | ParentScopeType<PS>
  : never

enum ScopeCardData {
  CodeCard = 'code-card',
  DeckCard = 'deck-card',
}

export enum Scope {
  CodeCard = 'code-card',
  DeckCard = 'deck-card',
  Form = 'form',
  Nest = 'nest',
}

export type ScopeCardDataTableType = {
  'code-card': {
    code: {
      hello: string
    }
  }
  'deck-card': {
    deck: {
      world: string
    }
  }
}

export type ScopeCardDataType<S extends ScopeCardData> = {
  card: ScopeCardDataTableType[S]
}

export type ScopeFormDataType = {
  form: {
    foo: string
    bar: number
  }
}

export type ScopeKeyListType<
  L extends Scope | unknown,
  T extends ScopeType<L>,
> = T['parent'] extends infer O
  ? O extends ScopeType<infer X>
    ? (keyof T['data'] & string) | ScopeKeyListType<X, O>
    : keyof T['data'] & string
  : never

export type ScopeNestDataType = {
  index: number
  nest: {
    one: boolean
  }
}

export type ScopeSetType<S extends ScopeType> =
  | S
  | ParentScopeType<S>

export type ScopeTableType = {
  'code-card': ScopeCardDataType<ScopeCardData.CodeCard>
  'deck-card': ScopeCardDataType<ScopeCardData.DeckCard>
  form: ScopeFormDataType
  nest: ScopeNestDataType
}

export type ScopeType<
  S extends Scope | unknown = unknown,
  P extends unknown = unknown,
> = {
  data: S extends Scope ? ScopeTableType[S] : unknown
  like: S
  parent?: P extends ScopeType<infer T extends Scope, infer Q>
    ? ScopeType<T, Q>
    : never
}

export type ScopeValueType<
  L extends Scope | unknown,
  T extends ScopeType<L>,
  K extends ScopeKeyListType<L, T>,
> = T['data'] extends { [key in K]: unknown }
  ? T['data'][K]
  : T['parent'] extends infer O
  ? O extends ScopeType<infer X>
    ? ScopeValueType<X, O, ScopeKeyListType<X, O>>
    : never
  : never

export function extendScope<
  S extends Scope,
  P extends unknown = unknown,
>(
  like: S,
  data: S extends Scope ? ScopeTableType[S] : unknown,
  parent?: P extends ScopeType<infer T extends Scope, infer Q>
    ? ScopeType<T, Q>
    : never,
): ScopeType<S, P> {
  return { data, like, parent }
}

export function getPropertyValueFromScope<
  L extends Scope,
  S extends ScopeType<L>,
  K extends ScopeKeyListType<L, S>,
>(scope: S, path: K): ScopeValueType<L, S, K> | undefined {
  let source: ScopeSetType<S> | undefined = scope

  while (source) {
    if (path in source.data) {
      break
    } else {
      source = source.parent
    }
  }

  if (!source) {
    return
  }

  return source.data[path]
}

export function setPropertyValueOnScope<
  L extends Scope,
  S extends ScopeType<L>,
  K extends ScopeKeyListType<L, S>,
>(scope: S, property: K, value: ScopeValueType<L, S, K>): void {
  if (property in scope.data) {
    scope.data[property] = value
  } else if (scope.parent) {
    setPropertyValueOnScope(scope.parent, property, value)
  } else {
    throw new Error(`Property not defined on scope`)
  }
}
</code>```

Everything works except for the getPropertyValueFromScope function, which errors on the last line, saying a complex error which I am not understanding.

```<code>Type '(L extends Scope ? ScopeTableType[L] : unknown)[K]' is not assignable to type 'ScopeValueType<L, S, K> | undefined'.
  Type '(L extends Scope ? ScopeTableType[L] : unknown)[ScopeKeyListType<L, S>]' is not assignable to type 'ScopeValueType<L, S, K> | undefined'.
    Type '(L extends Scope ? ScopeTableType[L] : unknown)[keyof S["data"] & string]' is not assignable to type 'ScopeValueType<L, S, K> | undefined'.
      Type '(L extends Scope ? ScopeTableType[L] : unknown)[string]' is not assignable to type 'ScopeValueType<L, S, K> | undefined'.ts(2322)
</code>```

I have tinkered with this for hours, and I change one thing and fix this issue, but another thing breaks. For example, if I remove the last line keyof T['data'] & string and replace with never in the definition of ScopeKeyListType, then that error goes away but then call to getPropertyValueFromScope (inside generateUnhandledNestCaseBaseError at the bottom) breaks, and gives this error:

```<code>Type '"card"' does not satisfy the constraint '"nest" | "index"'.
'card' is declared but its value is never read.
</code>```

So something is off, but I haven't been able to figure out what it is. Any ideas how to get this compiling in one way or another?

The ScopeType object is basically a tree of objects, where it has 3 properties:

like (type as string)

data (object of properties, the actual scope data)

parent (an optional parent scope of a different type)

ContentLicense: CC BY-SA 4.0


问:
Flutter Web App Hosted in NodeJS shows only white screen
I have built a flutter web application (flutter stable@3.3.9) where I have set the url strategy to PathUrlStrategy().

Of course, locally this application builds fine and runs fine. I am hosting this application in a NodeJS application as follows:

```<code>import express, {Express, Request, Response} from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import https from "https";
import {ClientRequest, IncomingMessage} from "http";
import path from "path";

const app: Express = express();
const port = process.env.PORT;

app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "flutter")));

app.get("/api/page/:id", async (req, res) => {
  getPageSessionHandler(req, res);
});

app.post("/api/payment", async (req, res) => {
  console.log("handling payment request");
  postPaymentHandler(req, res);
});

app.get("*", (_, res) => {
  res.sendFile(path.resolve(__dirname, "flutter/index.html"));
});

app.listen(port, () => {
  console.log(
    `⚡[server (nodejs)]: Server is running at http://localhost:${port}`,
  );
});

var postPaymentHandler = (authToken: String, req: any, res: any) => {
  //implementation removed
};

var getPageSessionHandler = (authToken: String, req: any, res: any) => {
  //implementation removed
};
</code>```

Of course, this runs fine locally as follows:

flutter build web --release --web-render=html

Then move the build/web* output to the proper folder in my nodejs server.

I can even locally containerize this application and run it from my docker desktop (windows 11) using the following dockerfile:

```<code>FROM debian:latest AS build-env
# Install flutter dependencies and nodejs dependencies
RUN apt-get update
RUN apt-get install -y curl git wget unzip gettext-base libgconf-2-4 gdb libstdc++6 libglu1-mesa fonts-droid-fallback lib32stdc++6 python3
RUN apt-get clean

RUN curl -fsSL https://deb.nodesource.com/setup_12.x | bash -
RUN apt-get -y install nodejs
RUN npm install

WORKDIR /app

COPY . .
RUN npm install
RUN npm run build

RUN git clone https://github.com/flutter/flutter.git /usr/local/flutter
ENV PATH="/usr/local/flutter/bin:/usr/local/flutter/bin/cache/dart-sdk/bin:${PATH}"

WORKDIR /app/flutter_src/payment

# Build the app
RUN touch .env
RUN flutter clean && flutter pub get
RUN flutter build web --release --web-renderer=html

# Build the final image
WORKDIR /app

RUN cp -R flutter_src/payment/build/web dist/flutter

CMD ["/bin/sh",  "-c", "exec node dist/index.ts"]
</code>```

Again, this works fine in both my windows node server environment, and also in my docker desktop container. When I deploy this via my CI/CD pipeline to AWS ECR, I am unable to load the application. I can hit the associated API endpoints in the node's index.ts file above. My kubernetes pod is healthy... but I am not able to load routes with a second slash... i.e.:

https:///welcome <--- loads fine
https:///user/fun_username  <-- does not load.

After a ton of debugging, I'm finding another oddity in how this behaves in environment. See the Network log from a request to my application's deep-linked route in Chrome (and also Edge):

when requesting /page/{page-id-here}, the browser is requesting the main.dart.js at the subroute.

What's even more perplexing is that if I request the same deep route in Firefox, not only does my application load as intended and work as expected, the browser seems to literally be requesting my main.dart.js at the root (what it should be) of my node server, as it's serving the flutter directory statically... See this screenshot from firefox:

here, the main.dart.js file is requested from the root of the node server as I'd expect.

I have tried all sorts of routing tricks in the node server, but that just feels wrong, especially since it seems to be specific to my environment. If I revert the path strategy back to client-only routing (/#/path/here), this works fine, but does not meet my requirements on this project.

Thank you all for your help. This is weeks of struggling I'm deferring on at this point.

Body:
I have built a flutter web application (flutter stable@3.3.9) where I have set the url strategy to PathUrlStrategy().

Of course, locally this application builds fine and runs fine. I am hosting this application in a NodeJS application as follows:

import express, {Express, Request, Response} from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import https from "https";
import {ClientRequest, IncomingMessage} from "http";
import path from "path";

const app: Express = express();
const port = process.env.PORT;

app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "flutter")));

app.get("/api/page/:id", async (req, res) => {
  getPageSessionHandler(req, res);
});

app.post("/api/payment", async (req, res) => {
  console.log("handling payment request");
  postPaymentHandler(req, res);
});

app.get("*", (_, res) => {
  res.sendFile(path.resolve(__dirname, "flutter/index.html"));
});

app.listen(port, () => {
  console.log(
    `⚡[server (nodejs)]: Server is running at http://localhost:${port}`,
  );
});

var postPaymentHandler = (authToken: String, req: any, res: any) => {
  //implementation removed
};

var getPageSessionHandler = (authToken: String, req: any, res: any) => {
  //implementation removed
};

Of course, this runs fine locally as follows:

flutter build web --release --web-render=html

Then move the build/web* output to the proper folder in my nodejs server.

I can even locally containerize this application and run it from my docker desktop (windows 11) using the following dockerfile:

FROM debian:latest AS build-env
# Install flutter dependencies and nodejs dependencies
RUN apt-get update
RUN apt-get install -y curl git wget unzip gettext-base libgconf-2-4 gdb libstdc++6 libglu1-mesa fonts-droid-fallback lib32stdc++6 python3
RUN apt-get clean

RUN curl -fsSL https://deb.nodesource.com/setup_12.x | bash -
RUN apt-get -y install nodejs
RUN npm install

WORKDIR /app

COPY . .
RUN npm install
RUN npm run build

RUN git clone https://github.com/flutter/flutter.git /usr/local/flutter
ENV PATH="/usr/local/flutter/bin:/usr/local/flutter/bin/cache/dart-sdk/bin:${PATH}"

WORKDIR /app/flutter_src/payment

# Build the app
RUN touch .env
RUN flutter clean && flutter pub get
RUN flutter build web --release --web-renderer=html

# Build the final image
WORKDIR /app

RUN cp -R flutter_src/payment/build/web dist/flutter

CMD ["/bin/sh",  "-c", "exec node dist/index.ts"]

Again, this works fine in both my windows node server environment, and also in my docker desktop container. When I deploy this via my CI/CD pipeline to AWS ECR, I am unable to load the application. I can hit the associated API endpoints in the node's index.ts file above. My kubernetes pod is healthy... but I am not able to load routes with a second slash... i.e.:

https:///welcome <--- loads fine
https:///user/fun_username  <-- does not load.

After a ton of debugging, I'm finding another oddity in how this behaves in environment. See the Network log from a request to my application's deep-linked route in Chrome (and also Edge):

when requesting /page/{page-id-here}, the browser is requesting the main.dart.js at the subroute.

What's even more perplexing is that if I request the same deep route in Firefox, not only does my application load as intended and work as expected, the browser seems to literally be requesting my main.dart.js at the root (what it should be) of my node server, as it's serving the flutter directory statically... See this screenshot from firefox:

here, the main.dart.js file is requested from the root of the node server as I'd expect.

I have tried all sorts of routing tricks in the node server, but that just feels wrong, especially since it seems to be specific to my environment. If I revert the path strategy back to client-only routing (/#/path/here), this works fine, but does not meet my requirements on this project.

Thank you all for your help. This is weeks of struggling I'm deferring on at this point.


问:
Runtime template arguments?
I am writing an SI unit class that uses integer template arguments for the dimensions of the type. I am trying to write a power function, but I am running into the issue that the exponent is not necessarily known until runtime and therefore the template arguments are not either.

Some code is omitted in the examples

template <int m = 0, int s = 0, int kg = 0, int A = 0, int K = 0, int mol = 0, int cd = 0>
struct Dimension{
  template <typename D, Ratio R> friend class Unit;
  public:
    real value;

    template <int m2, int s2, int kg2, int A2, int K2, int mol2, int cd2>
    constexpr Dimension<m+m2, s+s2, kg+kg2, A+A2, K+K2, mol+mol2, cd+cd2> operator*(Dimension<m2, s2, kg2, A2, K2, mol2, cd2> const & rhs) const {return value*rhs.value;}

   //Power function here
};
```
<p>The multiplication operator works because the result type depends on only template parameters.</p>
<p>None of the following work for the power operator because they all have the template argument depend on a runtime parameter.</p>
```constexpr auto operator^(int n) const {return Dimension<m*n, s*n, kg*n, A*n, K*n, mol*n, cd*n>{std::pow(value, n)};}

template <int N>
constexpr Dimension<m*N, s*N, kg*N, A*N, K*N, mol*N, cd*N> pow() const {return std::pow(value, N);}

constexpr auto operator^(int n) const {
  if constexpr (n == 0) return Dimension<0, 0, 0, 0, 0, 0, 0>{std::pow(value, N)};
  else if constexpr (n == 1) return Dimension<m*N, s*N, kg*N, A*N, K*N, mol*N, cd*N>{std::pow(value, N)};
  else if constexpr (n == 2) return Dimension<m*2, s*2, kg*2, A*2, K*2, mol*2, cd*2>{std::pow(value, N)};
//...
// I can reasonably expect a range smaller than [-10, 10], but theoretically I should be able to have any n
}
```

Sorry if there are minor code mistakes, I have written them directly.

Are there any solutions that don't resort to macros that would let me solve this?

Title: Runtime template arguments?

Body:
I am writing an SI unit class that uses integer template arguments for the dimensions of the type. I am trying to write a power function, but I am running into the issue that the exponent is not necessarily known until runtime and therefore the template arguments are not either.

Some code is omitted in the examples

template <int m = 0, int s = 0, int kg = 0, int A = 0, int K = 0, int mol = 0, int cd = 0>
struct Dimension{
  template <typename D, Ratio R> friend class Unit;
  public:
    real value;

    template <int m2, int s2, int kg2, int A2, int K2, int mol2, int cd2>
    constexpr Dimension<m+m2, s+s2, kg+kg2, A+A2, K+K2, mol+mol2, cd+cd2> operator*(Dimension<m2, s2, kg2, A2, K2, mol2, cd2> const & rhs) const {return value*rhs.value;}

   //Power function here
};

The multiplication operator works because the result type depends on only template parameters.

None of the following work for the power operator because they all have the template argument depend on a runtime parameter.

constexpr auto operator^(int n) const {return Dimension<m*n, s*n, kg*n, A*n, K*n, mol*n, cd*n>{std::pow(value, n)};}

template <int N>
constexpr Dimension<m*N, s*N, kg*N, A*N, K*N, mol*N, cd*N> pow() const {return std::pow(value, N);}

constexpr auto operator^(int n) const {
  if constexpr (n == 0) return Dimension<0, 0, 0, 0, 0, 0, 0>{std::pow(value, N)};
  else if constexpr (n == 1) return Dimension<m*N, s*N, kg*N, A*N, K*N, mol*N, cd*N>{std::pow(value, N)};
  else if constexpr (n == 2) return Dimension<m*2, s*2, kg*2, A*2, K*2, mol*2, cd*2>{std::pow(value, N)};
//...
// I can reasonably expect a range smaller than [-10, 10], but theoretically I should be able to have any n
}

Sorry if there are minor code mistakes, I have written them directly.

Are there any solutions that don't resort to macros that would let me solve this?


问:
Getting Value of a Join Field in Siebel without refreshing
I created a join in BC1 having table T1. Join was with T2 which is a DB View Table. When i created a new record in UI, the value of join field needs a refresh to populate it's values.

How can i get values from join without refreshing the applet?


问:
Exec a complex stored procedure in MS SQL using Pyodbc
I'm trying to create a program that upload an excel table to SQL server and run a procedure of that takes the table as an input. The procedure is pretty complex with declare statement using injected variable, and dynamic variable (e.g. derived from injected variable, or select the latest table in the database). I tried several things but the proc were not executed.

```<code>Server='IP address'
Database='database name'
Driver='ODBC Driver 17 for SQL Server'

date = '20221220'
MONTH = '202211'

db = pyodbc.connect(driver=Driver, server=Server, Trusted_Connection='yes')
dbc = db.cursor()

stored_proc = f"exec db..proc @date = '{date}',@Month='{MONTH}'"
dbc.execute(stored_proc)

#I also tried this, but it did not worked either
#dbc.execute(f"db..proc {date}, {MONTH}")
#dbc.execute("db..proc ?,?", [date,MONTH])
</code>```

I expected that the procedure was successfully executed and data are updated. However, no error were shown in python terminal, but data in the needed SQL table were not updated either. I suspect that pyodbc can run select, insert into, update, ... statements, but not the declare statement.

Can any one help me with this?
Many thanks

Body:
I'm trying to create a program that upload an excel table to SQL server and run a procedure of that takes the table as an input. The procedure is pretty complex with declare statement using injected variable, and dynamic variable (e.g. derived from injected variable, or select the latest table in the database). I tried several things but the proc were not executed.

Server='IP address'
Database='database name'
Driver='ODBC Driver 17 for SQL Server'

date = '20221220'
MONTH = '202211'

db = pyodbc.connect(driver=Driver, server=Server, Trusted_Connection='yes')
dbc = db.cursor()

stored_proc = f"exec db..proc @date = '{date}',@Month='{MONTH}'"
dbc.execute(stored_proc)

#I also tried this, but it did not worked either
#dbc.execute(f"db..proc {date}, {MONTH}")
#dbc.execute("db..proc ?,?", [date,MONTH])

I expected that the procedure was successfully executed and data are updated. However, no error were shown in python terminal, but data in the needed SQL table were not updated either. I suspect that pyodbc can run select, insert into, update, ... statements, but not the declare statement.

Can any one help me with this?
Many thanks


问:
Interpolate variable in multiline vanilla javascipt
Recently, I wanted to develop a plugin for javascipt for visual studio code. It's essence is to generate 3 files with template text in them. I stored the template text as a multiline string in a variable, but I never managed to insert the variable interpolation into the multiline string.

Code sample below:

```<code>const blocName = await vscode.window.showInputBox({
            placeHolder: "Bloc name",
            prompt: "Enter the BLoC name",
          });

const blocNameLower = blocName.toLowerCase();

const bloc = 'import \'dart:async\';\n\
import \'package:${blocNameLower}_bloc/bloc.dart\'\;\n\
import \'package:meta/meta.dart\';\n\
\n\
part \'${blocNameLower}_event.dart\';\n\
part \'${blocNameLower}_state.dart\';\n\
\n\
class ${blockName}Bloc extends Bloc<${blockName}Event, ${blockName}State> {\n\
        ${blockName}Bloc() : super(${blockName}Initial()) {\n\
        on<${blockName}Event>((event, emit) {\n\
        // TODO: implement event handler\n\
        });\n\
    }\n\
}';

</code>```

Let's assume input is Test:

Actual behavior:

```<code>import 'dart:async';
import 'package:${blocNameLower}_bloc/bloc.dart';
import 'package:meta/meta.dart';

part '**${blocNameLower}**_event.dart';
part '${blocNameLower}_state.dart';

class ${blockName}Bloc extends Bloc<${blockName}Event, ${blockName}State> {
    ${blockName}Bloc() : super(${blockName}Initial()) {
    on<${blockName}Event>((event, emit) {
        // TODO: implement event handler
    });
    }
}
</code>```

Expected behavior:

```<code>import 'dart:async';
import 'package:test_bloc/bloc.dart';
import 'package:meta/meta.dart';

part '**test**_event.dart';
part 'test_state.dart';

class TestBloc extends Bloc<TestEvent, TestState> {
    TestBloc() : super(TestInitial()) {
    on<TestEvent>((event, emit) {
        // TODO: implement event handler
    });
    }
}
</code>```

Is there any chance to interpolate variable in multiline line..(as with 'part test_event.dart';) ?

Body:
Recently, I wanted to develop a plugin for javascipt for visual studio code. It's essence is to generate 3 files with template text in them. I stored the template text as a multiline string in a variable, but I never managed to insert the variable interpolation into the multiline string.

Code sample below:

const blocName = await vscode.window.showInputBox({
            placeHolder: "Bloc name",
            prompt: "Enter the BLoC name",
          });

const blocNameLower = blocName.toLowerCase();

const bloc = 'import \'dart:async\';\n\
import \'package:${blocNameLower}_bloc/bloc.dart\'\;\n\
import \'package:meta/meta.dart\';\n\
\n\
part \'${blocNameLower}_event.dart\';\n\
part \'${blocNameLower}_state.dart\';\n\
\n\
class ${blockName}Bloc extends Bloc<${blockName}Event, ${blockName}State> {\n\
        ${blockName}Bloc() : super(${blockName}Initial()) {\n\
        on<${blockName}Event>((event, emit) {\n\
        // TODO: implement event handler\n\
        });\n\
    }\n\
}';

Let's assume input is Test:

Actual behavior:

import 'dart:async';
import 'package:${blocNameLower}_bloc/bloc.dart';
import 'package:meta/meta.dart';

part '**${blocNameLower}**_event.dart';
part '${blocNameLower}_state.dart';

class ${blockName}Bloc extends Bloc<${blockName}Event, ${blockName}State> {
    ${blockName}Bloc() : super(${blockName}Initial()) {
    on<${blockName}Event>((event, emit) {
        // TODO: implement event handler
    });
    }
}

Expected behavior:

import 'dart:async';
import 'package:test_bloc/bloc.dart';
import 'package:meta/meta.dart';

part '**test**_event.dart';
part 'test_state.dart';

class TestBloc extends Bloc<TestEvent, TestState> {
    TestBloc() : super(TestInitial()) {
    on<TestEvent>((event, emit) {
        // TODO: implement event handler
    });
    }
}

Is there any chance to interpolate variable in multiline line..(as with 'part test_event.dart';) ?


问:
Can't change settings in VSCode Jupyter editor because vertical scrollbar active area is only a pixel or two wide
I tried to change some settings in VSCode.  As a start, the vertical scrollbar active area is only a pixel or two wide.  It typically takes me 3-4 tries before I successfully grab/drag it.  No problems, I'll change the Vertical Scrollbar Size.  I did -- and nothing changed.  I exited and restarted, nothing changed.  I tried changing another setting (Scrollbar: Scroll By Page) and nothing changed.

@modified shows all the settings I've changed.  They just don't work.  (Edit:  I kept experimenting, and I found some settings DO work, e.g. Cursor Style and Auto Closing Quote.)

What's the secret to get the changes to work ??

Version 1.74.2, 1 day ago.  Running on Windows 10 Pro.

====================

So, the settings work in the normal editor but not in the Jupyter editor, which is where I actually work 95% of the time.  I can't find a scrollbar-width setting for the Notebook class.  Does anyone know if the scrollbars can be adjusted in Jupyter notebooks?


问:
Create a list of Reference for FocusRequester in Jetpack compose
I have something like

```<code>            promotions.forEachIndexed { index, item ->
                key(item.hashCode()) {
                    PromotionItem(
                        promotionItem = item,
                        onRemove = { onRemove(index) }
                    )
                }
            }
</code>```

I want to focus to one of them. I know I can create focusrequester like

```<code>val (item1, item2, item3, item4) = remember { FocusRequester.createRefs() }
</code>```

How can I create the list of reference for the list in the code above. Or is there other way to handle the list?

Thanks in advance

Body:
I have something like

            promotions.forEachIndexed { index, item ->
                key(item.hashCode()) {
                    PromotionItem(
                        promotionItem = item,
                        onRemove = { onRemove(index) }
                    )
                }
            }

I want to focus to one of them. I know I can create focusrequester like

val (item1, item2, item3, item4) = remember { FocusRequester.createRefs() }

How can I create the list of reference for the list in the code above. Or is there other way to handle the list?

Thanks in advance


问:
Is it possible to insert a link into a richtextbox targetting filepath to computer?
I have multiple .txt files in a folder.
I have a form where I type a keyword into a textbox that search among those .txt files when I click the button called "search".
For every match the entire line surrounding the keyword is then written into the richtextbox preceded  by the fullpath of the related txt file.

I would like to know if there's a way to make that fullpath a link that could be simply clicked, to reach the related .txt file.


问:
Dynamically Enable/Disable Form Fields in Streamlit
I have a form in Streamlit that looks something like this,

```<code>with st.form("my_form"):
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"])

   submitted = st.form_submit_button("Submit")
   if submitted:
       submission_state = st.text('Form Submitted!')
</code>```

Now, I want my second dropdown field, i.e. drop_down_2 to appear only if a certain value in drop_down_1 is selected, say Option 1.

How can I achieve this?

I tried something like this, but it did not work.

```<code>with st.form("my_form"):
   is_drop_down_2_disabled = True
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   if drop_down_1 == 'Option 1':
       is_drop_down_2_disabled = False

   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"], disabled=is_drop_down_2_disabled)

   submitted = st.form_submit_button("Submit")
   if submitted:
       submission_state = st.text('Form Submitted!')
</code>```

I assume that this is because the variables within the form are not assigned any values until the Submit button is clicked.

Body:
I have a form in Streamlit that looks something like this,

with st.form("my_form"):
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"])

   submitted = st.form_submit_button("Submit")
   if submitted:
       submission_state = st.text('Form Submitted!')

Now, I want my second dropdown field, i.e. drop_down_2 to appear only if a certain value in drop_down_1 is selected, say Option 1.

How can I achieve this?

I tried something like this, but it did not work.

with st.form("my_form"):
   is_drop_down_2_disabled = True
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   if drop_down_1 == 'Option 1':
       is_drop_down_2_disabled = False

   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"], disabled=is_drop_down_2_disabled)

   submitted = st.form_submit_button("Submit")
   if submitted:
       submission_state = st.text('Form Submitted!')

I assume that this is because the variables within the form are not assigned any values until the Submit button is clicked.


问:
Application rejected Unsafe Encryption androidx.transition.u.P
I have submitted my application on play store and It is rejected with following errors:

Your app contains unsafe cryptographic encryption patterns. Please see this Google Help Center article for details.

androidx.transition.u.P

I have search on google but nothing find appropriate. My application is basically a dialer application not sms which has functionality like: call block, dial call.

From this solution "Your app contains unsafe cryptographic encryption patterns" - How I can get rid of this warning?

I am using encryption as below:

```<code>SecretKeySpec skeySpec = new SecretKeySpec(getRaw(BuildConfig.PLAIN_TEXT_NAME, BuildConfig.AESSALT_NAME), "AES");
    Cipher cipher = Cipher.getInstance(cypherInstance);
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(initializationVector.getBytes()));
    byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes());
    return Base64.encodeToString(encrypted, Base64.DEFAULT);

 private static byte[] getRaw(String plainText, String salt) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(secretKeyInstance);
        KeySpec spec = new PBEKeySpec(plainText.toCharArray(), salt.getBytes(), pswdIterations, keySize);
        return factory.generateSecret(spec).getEncoded();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return new byte[0];
}
</code>```

I have taken all values in static variable. Is it issue of that?

Body:
I have submitted my application on play store and It is rejected with following errors:

Your app contains unsafe cryptographic encryption patterns. Please see this Google Help Center article for details.

androidx.transition.u.P

I have search on google but nothing find appropriate. My application is basically a dialer application not sms which has functionality like: call block, dial call.

From this solution "Your app contains unsafe cryptographic encryption patterns" - How I can get rid of this warning?

I am using encryption as below:

SecretKeySpec skeySpec = new SecretKeySpec(getRaw(BuildConfig.PLAIN_TEXT_NAME, BuildConfig.AESSALT_NAME), "AES");
    Cipher cipher = Cipher.getInstance(cypherInstance);
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(initializationVector.getBytes()));
    byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes());
    return Base64.encodeToString(encrypted, Base64.DEFAULT);

 private static byte[] getRaw(String plainText, String salt) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(secretKeyInstance);
        KeySpec spec = new PBEKeySpec(plainText.toCharArray(), salt.getBytes(), pswdIterations, keySize);
        return factory.generateSecret(spec).getEncoded();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return new byte[0];
}

I have taken all values in static variable. Is it issue of that?


问:
On mac visual studio 2022 how to publish to GitHub, add GitHub username and password
Hi,
I was trying to upload into GitHub, I created a GitHub repository. On VS 2022 for mac I only have the Git tab and when I publish I get the no remote target set, second image. I don't know how to set the remote and change the username and password for Github on the VS 2022 for mac.


问:
JSON Parsing Error for Schema.org Structured Data
I'm an SEO just getting into manual structured data building, so apologies if I come off as a newb here.

Working on this JSON code an**I keep getting parsing errors.

The error seems to be at line 125, but I think the object's brackets are closed and commas in the right place.

Lines 124-133

```<code>
</code>```
```<code>     "@type": "HowToStep",
          "position": "2",
          "itemListElement": [
            {
              "@type": "HowToDirection",
              "position": "1",
              "text": "Research the business you want an appointment with"
            },
</code>```
```<code>
</code>```

I've tried ensuring all the brackets were closed and that commas were placed on all key:value pairs except for the last key:value pair of an object or array - using parsing tools like validator.schema.org/ , json-ld.org/playground/ ,  and search.google.com/test/rich-results keep telling me there's a missing "," "}" or "]" but the key:value pairs, objects, and arrays all look right to me.

I can provide the whole code if needed for more context.

Thanks for the help everyone.

Body:
I'm an SEO just getting into manual structured data building, so apologies if I come off as a newb here.

Working on this JSON code an**I keep getting parsing errors.

The error seems to be at line 125, but I think the object's brackets are closed and commas in the right place.

Lines 124-133

     "@type": "HowToStep",
          "position": "2",
          "itemListElement": [
            {
              "@type": "HowToDirection",
              "position": "1",
              "text": "Research the business you want an appointment with"
            },

I've tried ensuring all the brackets were closed and that commas were placed on all key:value pairs except for the last key:value pair of an object or array - using parsing tools like validator.schema.org/ , json-ld.org/playground/ ,  and search.google.com/test/rich-results keep telling me there's a missing "," "}" or "]" but the key:value pairs, objects, and arrays all look right to me.

I can provide the whole code if needed for more context.

Thanks for the help everyone.


问:
How to change pull to refresh icon of tableview in swift?
I am trying to change the pull to refresh icon of tableview

I have succeeded in removing the icon as shown below, but the progress does not go any further.

How can I change the pull to refresh icon?

thank you

```<code>let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(pullToRefresh(refresh:)), for: .valueChanged)
refreshControl.backgroundColor = UIColor.clear
refreshControl.tintColor = UIColor.clear
tableview.refreshControl = refreshControl
</code>```

Body:
I am trying to change the pull to refresh icon of tableview

I have succeeded in removing the icon as shown below, but the progress does not go any further.

How can I change the pull to refresh icon?

thank you

let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(pullToRefresh(refresh:)), for: .valueChanged)
refreshControl.backgroundColor = UIColor.clear
refreshControl.tintColor = UIColor.clear
tableview.refreshControl = refreshControl


问:
Firebase to Google Analytics 4 no working and some error using Javascript
I have an old application using GoogleAnalytics3(GA3) and wants to version up to GoogleAnalytics4(GA4) using Firebase.

Now, I implemented watching tutorials and sample records, but shows console error and logs no show on GA4.
I researched and no articles I want to know, I want to resolve those errors...

The application uses Node.js 14.19 and builds up with coffeescript(1.12.7) and webpack.

Error Type 1:
TypeError: Cannot read properties of undefined (reading 'id')
Codes:

```<code>var firebase = require('firebase/app');
var Analytics = require('firebase/analytics');

// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const ga4 = Analytics.getAnalytics(firebaseApp);

module.exports = {
    initialize: function() {
        Analytics.logEvent(ga4, 'init', {
            userId: Env.loginUser.id,
            dimension1: Env.organizationId
        });
        _initialized = true;
    },

    trackPageView: function(page) {
        if (!_initialized) { this.initialize(); }

    Analytics.logEvent(ga4, 'page', page);
    }
}
</code>```

Caller:

```<code>AccessTracker.trackPageView('suggest-single');
</code>```

Error Type 2:
o is not a function

Codes:

```<code>var firebase = require('firebase/app');
var logEvent = require('firebase/analytics'), getAnalytics = require('firebase/analytics');

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const ga4 = getAnalytics(firebaseApp);

module.exports = {
    initialize: function() {
        logEvent(ga4, 'init', {
            userId: Env.loginUser.id,
            dimension1: Env.organizationId
        });
        _initialized = true;
    },

    trackPageView: function(page) {
        if (!_initialized) { this.initialize(); }
        logEvent(ga4, 'page', page);
    },
}
</code>```

Caller:

```<code>AccessTracker.trackPageView('suggest-single');
</code>```

Body:
I have an old application using GoogleAnalytics3(GA3) and wants to version up to GoogleAnalytics4(GA4) using Firebase.

Now, I implemented watching tutorials and sample records, but shows console error and logs no show on GA4.
I researched and no articles I want to know, I want to resolve those errors...

The application uses Node.js 14.19 and builds up with coffeescript(1.12.7) and webpack.

Error Type 1:
TypeError: Cannot read properties of undefined (reading 'id')
Codes:

var firebase = require('firebase/app');
var Analytics = require('firebase/analytics');

// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const ga4 = Analytics.getAnalytics(firebaseApp);

module.exports = {
    initialize: function() {
        Analytics.logEvent(ga4, 'init', {
            userId: Env.loginUser.id,
            dimension1: Env.organizationId
        });
        _initialized = true;
    },

    trackPageView: function(page) {
        if (!_initialized) { this.initialize(); }

    Analytics.logEvent(ga4, 'page', page);
    }
}

Caller:

AccessTracker.trackPageView('suggest-single');

Error Type 2:
o is not a function

Codes:

var firebase = require('firebase/app');
var logEvent = require('firebase/analytics'), getAnalytics = require('firebase/analytics');

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const ga4 = getAnalytics(firebaseApp);

module.exports = {
    initialize: function() {
        logEvent(ga4, 'init', {
            userId: Env.loginUser.id,
            dimension1: Env.organizationId
        });
        _initialized = true;
    },

    trackPageView: function(page) {
        if (!_initialized) { this.initialize(); }
        logEvent(ga4, 'page', page);
    },
}

Caller:

AccessTracker.trackPageView('suggest-single');


问:
Add a new columns returning columns header meeting all conditions
```<code>DF

ID  Mon Tue Wed Thur    Count_Y

1   Yes No  No  No  1

2   No  No  Yes No  1

3   No  No  No  No  0

4   No  Yes No  Yes 2

5   Yes Yes No  Yes 3

6   Yes Yes Yes Yes 4

7   No  No  Yes Yes 2
</code>```

my script is

```<code>    DF1 <- DF %>%
     mutate ('New_Column' = case_when(`Mon` == "YES" ~ 'Mon',
                                `Tue`=="YES" ~ 'Tue',
                                `Wed` =="YES" ~ 'Wed',`Thur`=="YES" ~ 'Thur'
                                ,TRUE ~ 'OFF'))
</code>```

The final output is as seen below

```<code>ID  Mon Tue Wed Thur    Count_Y New_column
1   Yes No  No  No  1   Mon
2   No  No  Yes No  1   Wed
3   No  No  No  No  0   OFF
4   No  Yes No  Yes 2   Tue
4   No  Yes No  Yes 2   Thur
5   Yes Yes No  Yes 3   Mon
5   Yes Yes No  Yes 3   Tue
5   Yes Yes No  Yes 3   Thur
6   Yes Yes Yes Yes 4   Mon
6   Yes Yes Yes Yes 4   Tue
6   Yes Yes Yes Yes 4   Wed
6   Yes Yes Yes Yes 4   Thur
7   No  No  Yes Yes 2   Wed
7   No  No  Yes Yes 2   Thur
</code>```

Body:
DF

ID  Mon Tue Wed Thur    Count_Y

1   Yes No  No  No  1

2   No  No  Yes No  1

3   No  No  No  No  0

4   No  Yes No  Yes 2

5   Yes Yes No  Yes 3

6   Yes Yes Yes Yes 4

7   No  No  Yes Yes 2

my script is

    DF1 <- DF %>%
     mutate ('New_Column' = case_when(`Mon` == "YES" ~ 'Mon',
                                `Tue`=="YES" ~ 'Tue',
                                `Wed` =="YES" ~ 'Wed',`Thur`=="YES" ~ 'Thur'
                                ,TRUE ~ 'OFF'))

The final output is as seen below

ID  Mon Tue Wed Thur    Count_Y New_column
1   Yes No  No  No  1   Mon
2   No  No  Yes No  1   Wed
3   No  No  No  No  0   OFF
4   No  Yes No  Yes 2   Tue
4   No  Yes No  Yes 2   Thur
5   Yes Yes No  Yes 3   Mon
5   Yes Yes No  Yes 3   Tue
5   Yes Yes No  Yes 3   Thur
6   Yes Yes Yes Yes 4   Mon
6   Yes Yes Yes Yes 4   Tue
6   Yes Yes Yes Yes 4   Wed
6   Yes Yes Yes Yes 4   Thur
7   No  No  Yes Yes 2   Wed
7   No  No  Yes Yes 2   Thur


问:
Exception: Gradle task assembleDebug failed with exit code 1
Hey guys I just started building flutter app for the first time and I am having this error, I have installed all requirements and configurations but I still, have this error when I click on run.

```<code>Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
[Fatal Error] jvnet-parent-5.pom:2:1: Content is not allowed in prolog.
[Fatal Error] kotlin-stdlib-common-1.3.72.pom:2:1: Content is not allowed in prolog.

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\watchdog\Documents\coding\Android\flutter_1\android\app\build.gradle' line: 26

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not resolve all files for configuration 'classpath'.
   > Could not resolve org.glassfish.jaxb:jaxb-runtime:2.3.1.
     Required by:
         unspecified:unspecified:unspecified > com.android.tools.build:gradle:4.1.0 > androidx.databinding:databinding-compiler-common:4.1.0
         unspecified:unspecified:unspecified > com.android.tools.build:gradle:4.1.0 > com.android.tools.build:builder:4.1.0 > com.android.tools:sdklib:27.1.0 > com.android.tools:repository:27.1.0
      > Could not resolve org.glassfish.jaxb:jaxb-runtime:2.3.1.
         > Could not parse POM https://repo.maven.apache.org/maven2/org/glassfish/jaxb/jaxb-runtime/2.3.1/jaxb-runtime-2.3.1.pom
            > Could not resolve com.sun.xml.bind.mvn:jaxb-runtime-parent:2.3.1.
               > Could not resolve com.sun.xml.bind.mvn:jaxb-runtime-parent:2.3.1.
                  > Could not parse POM https://repo.maven.apache.org/maven2/com/sun/xml/bind/mvn/jaxb-runtime-parent/2.3.1/jaxb-runtime-parent-2.3.1.pom
                     > Could not resolve com.sun.xml.bind.mvn:jaxb-parent:2.3.1.
                        > Could not resolve com.sun.xml.bind.mvn:jaxb-parent:2.3.1.
                           > Could not parse POM https://repo.maven.apache.org/maven2/com/sun/xml/bind/mvn/jaxb-parent/2.3.1/jaxb-parent-2.3.1.pom
                              > Could not resolve com.sun.xml.bind:jaxb-bom-ext:2.3.1.
                                 > Could not resolve com.sun.xml.bind:jaxb-bom-ext:2.3.1.
                                    > Could not parse POM https://repo.maven.apache.org/maven2/com/sun/xml/bind/jaxb-bom-ext/2.3.1/jaxb-bom-ext-2.3.1.pom
                                       > Could not resolve org.glassfish.jaxb:jaxb-bom:2.3.1.
                                          > Could not resolve org.glassfish.jaxb:jaxb-bom:2.3.1.
                                             > Could not parse POM https://repo.maven.apache.org/maven2/org/glassfish/jaxb/jaxb-bom/2.3.1/jaxb-bom-2.3.1.pom
                                                > Could not resolve net.java:jvnet-parent:5.
                                                   > Could not resolve net.java:jvnet-parent:5.
                                                      > Could not parse POM https://repo.maven.apache.org/maven2/net/java/jvnet-parent/5/jvnet-parent-5.pom
                                                         > Content is not allowed in prolog.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72.
     Required by:
         unspecified:unspecified:unspecified > com.android.tools.build:gradle:4.1.0 > org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72 > org.jetbrains.kotlin:kotlin-stdlib:1.3.72
      > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72.
         > Could not parse POM https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-stdlib-common/1.3.72/kotlin-stdlib-common-1.3.72.pom
            > Content is not allowed in prolog.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s
Exception: Gradle task assembleDebug failed with exit code 1

</code>```

Please any help on fixing this?

Body:
Hey guys I just started building flutter app for the first time and I am having this error, I have installed all requirements and configurations but I still, have this error when I click on run.

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
[Fatal Error] jvnet-parent-5.pom:2:1: Content is not allowed in prolog.
[Fatal Error] kotlin-stdlib-common-1.3.72.pom:2:1: Content is not allowed in prolog.

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\watchdog\Documents\coding\Android\flutter_1\android\app\build.gradle' line: 26

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not resolve all files for configuration 'classpath'.
   > Could not resolve org.glassfish.jaxb:jaxb-runtime:2.3.1.
     Required by:
         unspecified:unspecified:unspecified > com.android.tools.build:gradle:4.1.0 > androidx.databinding:databinding-compiler-common:4.1.0
         unspecified:unspecified:unspecified > com.android.tools.build:gradle:4.1.0 > com.android.tools.build:builder:4.1.0 > com.android.tools:sdklib:27.1.0 > com.android.tools:repository:27.1.0
      > Could not resolve org.glassfish.jaxb:jaxb-runtime:2.3.1.
         > Could not parse POM https://repo.maven.apache.org/maven2/org/glassfish/jaxb/jaxb-runtime/2.3.1/jaxb-runtime-2.3.1.pom
            > Could not resolve com.sun.xml.bind.mvn:jaxb-runtime-parent:2.3.1.
               > Could not resolve com.sun.xml.bind.mvn:jaxb-runtime-parent:2.3.1.
                  > Could not parse POM https://repo.maven.apache.org/maven2/com/sun/xml/bind/mvn/jaxb-runtime-parent/2.3.1/jaxb-runtime-parent-2.3.1.pom
                     > Could not resolve com.sun.xml.bind.mvn:jaxb-parent:2.3.1.
                        > Could not resolve com.sun.xml.bind.mvn:jaxb-parent:2.3.1.
                           > Could not parse POM https://repo.maven.apache.org/maven2/com/sun/xml/bind/mvn/jaxb-parent/2.3.1/jaxb-parent-2.3.1.pom
                              > Could not resolve com.sun.xml.bind:jaxb-bom-ext:2.3.1.
                                 > Could not resolve com.sun.xml.bind:jaxb-bom-ext:2.3.1.
                                    > Could not parse POM https://repo.maven.apache.org/maven2/com/sun/xml/bind/jaxb-bom-ext/2.3.1/jaxb-bom-ext-2.3.1.pom
                                       > Could not resolve org.glassfish.jaxb:jaxb-bom:2.3.1.
                                          > Could not resolve org.glassfish.jaxb:jaxb-bom:2.3.1.
                                             > Could not parse POM https://repo.maven.apache.org/maven2/org/glassfish/jaxb/jaxb-bom/2.3.1/jaxb-bom-2.3.1.pom
                                                > Could not resolve net.java:jvnet-parent:5.
                                                   > Could not resolve net.java:jvnet-parent:5.
                                                      > Could not parse POM https://repo.maven.apache.org/maven2/net/java/jvnet-parent/5/jvnet-parent-5.pom
                                                         > Content is not allowed in prolog.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72.
     Required by:
         unspecified:unspecified:unspecified > com.android.tools.build:gradle:4.1.0 > org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72 > org.jetbrains.kotlin:kotlin-stdlib:1.3.72
      > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72.
         > Could not parse POM https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-stdlib-common/1.3.72/kotlin-stdlib-common-1.3.72.pom
            > Content is not allowed in prolog.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s
Exception: Gradle task assembleDebug failed with exit code 1

Please any help on fixing this?


问:
Any one can find the timeout issue in my New Year Chaos solution(even I used index)?
My design is to pop or delete the max value in the list and then add up the difference between the max value index and the length of the list (moves)
I thought it is a pretty cool method and it uses index so should be fast, however, the solution passed the first 3 test cases only and then timed out on the extremely long list. Here is my code:

def minimumBribes(q):
    # Write your code here
    total_moves = 0
    max_value = max(q)
    max_value_index = q.index(max_value)
    while max_value_index != len(q)-1 or len(q)>1:
        if len(q) - 1 - max_value_index >= 3:
            print ("Too chaotic")
            return

        total_moves += (len(q)-1-max_value_index)
        q.pop(max_value_index)
        max_value = max(q)
        max_value_index = q.index(max_value)

    print(total_moves)
    return

```

Anybody gives me a lesson on why this is not fast enough?

Body:
My design is to pop or delete the max value in the list and then add up the difference between the max value index and the length of the list (moves)
I thought it is a pretty cool method and it uses index so should be fast, however, the solution passed the first 3 test cases only and then timed out on the extremely long list. Here is my code:

def minimumBribes(q):
    # Write your code here
    total_moves = 0
    max_value = max(q)
    max_value_index = q.index(max_value)
    while max_value_index != len(q)-1 or len(q)>1:
        if len(q) - 1 - max_value_index >= 3:
            print ("Too chaotic")
            return

        total_moves += (len(q)-1-max_value_index)
        q.pop(max_value_index)
        max_value = max(q)
        max_value_index = q.index(max_value)

    print(total_moves)
    return

Anybody gives me a lesson on why this is not fast enough?


问:
How would I set up a docker container that runs an OS version of chrome and puppeteer?
I am creating a node.js QR code reader. From experience, I have found that the most reliable and efficient reader is the built-in Chrome barcode detector API. Thus, I decided to build this application with a Puppeteer instance running Chrome. I successfully made the app pass in an image with a QR code to a Puppeteer browser instance, scan the QR code, and then return the result. It works as intended on my Mac. I packaged this functionality in an express app to make a scanning API. Currently, I am trying to deploy it on the web using a service that requires a docker container. However, I am struggling to make a Docker file that can runs the application.

I have tried installing Chrome in these three ways: 1, 2, 3. All of them have failed. Upon further searching, I discovered that Chrome supports the Barcode Detection API only on OS devices. Therefore, I need a way to ensure the docker container runs an OS version of Chrome.

If it is helpful, here is the function I am running with Puppeteer that works locally:

```<code>const puppeteer = require('puppeteer');

function scanQR = async (src) => {
  try {
    const browser = await puppeteer.launch({
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });
    const page = await browser.newPage();
    await page.setJavaScriptEnabled(true);
    await page.setCacheEnabled(true);
    await page.goto('https://nimiq.github.io/qr-scanner/demo/');
    const barcodeDetectorPromise = page.evaluate(
      async (src) =>
        new Promise(async (resolve, reject) => {
          const image = new Image();

          image.src = src;

          // eslint-disable-next-line no-undef
          const barcodeReader = new BarcodeDetector({ formats: ['qr_code'] });

          await new Promise((resolve, reject) => (image.onload = resolve));

          resolve(await barcodeReader.detect(image));
        }),
      src
    );

    const timeoutPromise = new Promise((resolve, reject) => {
      setTimeout(() => resolve([]), 2000);
    });

    const result = await Promise.race([barcodeDetectorPromise, timeoutPromise]);

    await browser.close();

    return result;
  } catch {
    return [];
  }
};

</code>```

The src is a link to an image with a QR code such as a base64URL whose image data includes a QR.

Body:
I am creating a node.js QR code reader. From experience, I have found that the most reliable and efficient reader is the built-in Chrome barcode detector API. Thus, I decided to build this application with a Puppeteer instance running Chrome. I successfully made the app pass in an image with a QR code to a Puppeteer browser instance, scan the QR code, and then return the result. It works as intended on my Mac. I packaged this functionality in an express app to make a scanning API. Currently, I am trying to deploy it on the web using a service that requires a docker container. However, I am struggling to make a Docker file that can runs the application.

I have tried installing Chrome in these three ways: 1, 2, 3. All of them have failed. Upon further searching, I discovered that Chrome supports the Barcode Detection API only on OS devices. Therefore, I need a way to ensure the docker container runs an OS version of Chrome.

If it is helpful, here is the function I am running with Puppeteer that works locally:

const puppeteer = require('puppeteer');

function scanQR = async (src) => {
  try {
    const browser = await puppeteer.launch({
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });
    const page = await browser.newPage();
    await page.setJavaScriptEnabled(true);
    await page.setCacheEnabled(true);
    await page.goto('https://nimiq.github.io/qr-scanner/demo/');
    const barcodeDetectorPromise = page.evaluate(
      async (src) =>
        new Promise(async (resolve, reject) => {
          const image = new Image();

          image.src = src;

          // eslint-disable-next-line no-undef
          const barcodeReader = new BarcodeDetector({ formats: ['qr_code'] });

          await new Promise((resolve, reject) => (image.onload = resolve));

          resolve(await barcodeReader.detect(image));
        }),
      src
    );

    const timeoutPromise = new Promise((resolve, reject) => {
      setTimeout(() => resolve([]), 2000);
    });

    const result = await Promise.race([barcodeDetectorPromise, timeoutPromise]);

    await browser.close();

    return result;
  } catch {
    return [];
  }
};

The src is a link to an image with a QR code such as a base64URL whose image data includes a QR.


问:
SQL Server Conditional Select Into Issue
I am working on a task where i had to enhance the performance of the stored procedure. However, i had stucked in an issue is that i am unable to use SELECT INTO in a conditional statement.

I had gone through some links like
INSERT INTO vs SELECT INTO and
sql server conditional select into temp table.

The query is as below:

```<code>IF(@abc = 7)
 BEGIN
  SELECT MemberID INTO #TempMember from dbo.Member WHERE ....
 END
ELSE
 BEGIN
  SELECT MemberID INTO #TempMember from dbo.Member WHERE ....
 END
</code>```

The query above ends up showing "there is already an object named '#TempMember' in the database" at the ELSE statement. Worth pointing that i had not create a temp table for #TempMember and the if statement is not in a loop as well.

But just why does the output shows the #TempMember exist but we know that only one SELECT statement will be performed in the query above as it is a conditional?

The reason for me to use SELECT INTO because there will be 500,000 datas to be dealt with in this statement. And INSERT INTO will make the performance bad. I am unable to convert it to dynamic SQL as well because of the practice of my company.

Is there any way that I can do to use both SELECT INTO in the conditional or any better practice to insert data into the #TempTable for performance wise?

Body:
I am working on a task where i had to enhance the performance of the stored procedure. However, i had stucked in an issue is that i am unable to use SELECT INTO in a conditional statement.

I had gone through some links like
INSERT INTO vs SELECT INTO and
sql server conditional select into temp table.

The query is as below:

IF(@abc = 7)
 BEGIN
  SELECT MemberID INTO #TempMember from dbo.Member WHERE ....
 END
ELSE
 BEGIN
  SELECT MemberID INTO #TempMember from dbo.Member WHERE ....
 END

The query above ends up showing "there is already an object named '#TempMember' in the database" at the ELSE statement. Worth pointing that i had not create a temp table for #TempMember and the if statement is not in a loop as well.

But just why does the output shows the #TempMember exist but we know that only one SELECT statement will be performed in the query above as it is a conditional?

The reason for me to use SELECT INTO because there will be 500,000 datas to be dealt with in this statement. And INSERT INTO will make the performance bad. I am unable to convert it to dynamic SQL as well because of the practice of my company.

Is there any way that I can do to use both SELECT INTO in the conditional or any better practice to insert data into the #TempTable for performance wise?


问:
How to set up tez ui with remote timeline server url in config.js?
Currently i am trying to configure tez-ui. I have put the tez ui web server on tomcat and running it as a service. When i am editing the timeline url with ip:8188 instead of localhost in /opt/tomcat/webapps/tez-ui/config/config.js file, it is throwing error  Adapter operation failed » Timeline server (ATS) is out of reach. Either it's down, or CORS is not enabled.

I have notice one thing tez ui is requesting the url http://localhost:8188/ws/v1/timeline/TEZ_DAG_ID instead after editing timeline url in config.js it should point http://ip:8188/ws/v1/timeline/TEZ_DAG_ID. Can anyone guide on why it is happening ?


问:
View "last accessed" project info using gcloud CLI
I am looking for a way to view last accessed or the date of the latest activity log, commit, modify, etc. on a project using the CLI so I can get a rough idea of what projects are(n't) in use for an account cleanup.

Would anyone have a recommendation of how to do this programmatically, or how I can find similar data.


问:
For Android 13 the VMOS app not working is there any solution to it
For Android 13 the VMOS app not working is there any solution

For Android 13 the VMOS app not working is there any solution


问:
gsoap C SOAP server hijacks memory even after using soap_end() call
For a project, I have implemented a gsoap(v2.8.83) FastCGI server with a C application. It is hosted as FastCGI on lighttpd webserver. It serves SOAP request and populates SOAP response with items available on the device. The number of items are varying with time. The functionality works fine but the FastCGI process seems to hijack some memory.

I expected the gsoap generated code to handle the release of all memory used to serve the request once I call soap_destroy() and soap_end(). But that does not happen.

For same number of items in the SOAP response, the memory held by the process is same (more than the memory held before serving the request) over multiple requests. However, as the number of items increases in the SOAP response, the memory held by the process also increases and this is an issue for the project as it runs on an embedded device.

I have enabled DEBUG option provided by gsoap and verified from the logs that all allocated memory is freed.
I have also tried compiling my FastCIG with few optimization options provided by gsoap and running it as an independent server (isolated from lighttpd) but there is no improvement. I am not able to use the WITH_LEAN compilation flag as I need data-time serialization.
gsoap memory leak C applications posts a similar issue but I have tried using the auto-generated functions as suggested in the answers for allocating the elements with no luck.

From the source code, I feel that the server is retaining some attribute data even after calls to soap_end() but not quite able to nail down as the debug logs does not give any clue on this.

Anyone understands what could be happening?
Any help is much appreciated.

Regards,


问:
Using React-pdf in Node JS to render pdf content to string
I am using the npm @react-pdf/renderer to convert a pdf content to a string in node js (using the renderToString method from the npm) so i can attach the pdf to an email. The issue is everything i try leads to an error when attempting this.

Try 1: I've tried is creating the pdf on the front end and sending the data to my node server:

pdf.js (front-end)

```<code>  const MyDoc = () => (
    <Document>
      <Page>
        <Text>React-pdf</Text>
      </Page>
    </Document>
  )

//using firebase to call https callable node functions
functions.httpsCallable('pdfRenderToString')({ htmlElement: <MyDoc />  })
</code>```

index.js (node)

```<code>//call renderToString from react-pdf

exports.pdfRenderToString = functions.https.onCall((data, context) => {
  return renderToString(data.htmlElement)
    .then(pdf => {
      return pdf
    })
    .catch((err) => console.log(err)) //always hits this error, says 'cannot convert Symbol to string'
})
</code>```

Try 2: i thought maybe the pdf html must be created on node so i tried that

index.js (node)

```<code>const MyDoc = () => (
    <Document>
      <Page>
        <Text>React-pdf</Text>
      </Page>
    </Document>
  )

renderToString(<MyDoc />)
    .then()...
    .catch...
</code>```

This method forces me to import React (which i find weird but do it anyways)...
This time the firebase functions don't even deploy and show error "Failed to load function definition from source: Failed to generate manifest from function source: SyntaxError: Unexpected token '<'"

I've tried everything the react-pdf docs say and i haven't had the least bit of success.

Anyone know what i'm doing wrong or missing?

Body:
I am using the npm @react-pdf/renderer to convert a pdf content to a string in node js (using the renderToString method from the npm) so i can attach the pdf to an email. The issue is everything i try leads to an error when attempting this.

Try 1: I've tried is creating the pdf on the front end and sending the data to my node server:

pdf.js (front-end)

  const MyDoc = () => (
    <Document>
      <Page>
        <Text>React-pdf</Text>
      </Page>
    </Document>
  )

//using firebase to call https callable node functions
functions.httpsCallable('pdfRenderToString')({ htmlElement: <MyDoc />  })

index.js (node)

//call renderToString from react-pdf

exports.pdfRenderToString = functions.https.onCall((data, context) => {
  return renderToString(data.htmlElement)
    .then(pdf => {
      return pdf
    })
    .catch((err) => console.log(err)) //always hits this error, says 'cannot convert Symbol to string'
})

Try 2: i thought maybe the pdf html must be created on node so i tried that

index.js (node)

const MyDoc = () => (
    <Document>
      <Page>
        <Text>React-pdf</Text>
      </Page>
    </Document>
  )

renderToString(<MyDoc />)
    .then()...
    .catch...

This method forces me to import React (which i find weird but do it anyways)...
This time the firebase functions don't even deploy and show error "Failed to load function definition from source: Failed to generate manifest from function source: SyntaxError: Unexpected token '<'"

I've tried everything the react-pdf docs say and i haven't had the least bit of success.

Anyone know what i'm doing wrong or missing?


问:
How can a SectionList / FlatList renderItem and renderSectionItem layout event be used to memoize getItemLayout?
One of the optimizations for FlatList/SectionList is to use the getItemLayout but with varying content this becomes difficult to compute a priori.  However, I was wondering can we at least capture the onLayout event when the item is rendered and put it in a useRef<{length:number, offset:number, index:number}[]>

I think FlatList won't be as hard, but SectionList would be difficulty knowing what section is presently being rendered.

So if I look at FlatList I was thinking about something like this for FlatList

```<code>const layouts = useRef<{length:number, offset:number, index:number}[]>([]);
const onLayoutFor = useCallback((index:number)=>{

return ({nativeEvent}) => {
  layouts[index] = { index, offset: y, length: height }
};

},[data]);

const renderItem = useCallback(({item, data, index}) => (
  <View onLayout={onLayoutFor(index)}>...</View>
));

const getItemLayout = useCallback((data, index) => layout[index], [data]);

return
  <FlatList data={data}
  renderItem={renderItem}
  getItemLayout={getItemLayout }
  />

</code>```

For section list I am not quite sure anymore.

Body:
One of the optimizations for FlatList/SectionList is to use the getItemLayout but with varying content this becomes difficult to compute a priori.  However, I was wondering can we at least capture the onLayout event when the item is rendered and put it in a useRef<{length:number, offset:number, index:number}[]>

I think FlatList won't be as hard, but SectionList would be difficulty knowing what section is presently being rendered.

So if I look at FlatList I was thinking about something like this for FlatList

const layouts = useRef<{length:number, offset:number, index:number}[]>([]);
const onLayoutFor = useCallback((index:number)=>{

return ({nativeEvent}) => {
  layouts[index] = { index, offset: y, length: height }
};

},[data]);

const renderItem = useCallback(({item, data, index}) => (
  <View onLayout={onLayoutFor(index)}>...</View>
));

const getItemLayout = useCallback((data, index) => layout[index], [data]);

return
  <FlatList data={data}
  renderItem={renderItem}
  getItemLayout={getItemLayout }
  />

For section list I am not quite sure anymore.