问:
Import library could not be resolved Pylance Visual Studio Code
I am trying to do a monte carlo simulation with different code but my program doesn't run because the different libraries like time, and random, and the apis are not recognizable for visual studio Code.
I have watched different videos for solution but I haven't find the solution to run my program.
--------------------------EDIT-------------------
I change the interpreter to the 3.10.7 version in my computer and apparently run all other libraries except these ones. What do I do?

```<code>import dash
import dash_core_components as dcc
import dash_html_components as html
import *dash_bootstrap_components* as dbc
from dash.dependencies import Input, Output
import plotly.express as px
import simulategames
from *IPython.display* import clear_output
</code>```

*dash_bootstrap_ components and *IPython.display are the ones highlighted in visual studio code.
Also, the others that are not highlighted, they are still not recognized even if I did the pip install library

I expected for it to run after doing a virtual environment, but It didn't work

Body:
I am trying to do a monte carlo simulation with different code but my program doesn't run because the different libraries like time, and random, and the apis are not recognizable for visual studio Code.
I have watched different videos for solution but I haven't find the solution to run my program.
--------------------------EDIT-------------------
I change the interpreter to the 3.10.7 version in my computer and apparently run all other libraries except these ones. What do I do?

import dash
import dash_core_components as dcc
import dash_html_components as html
import *dash_bootstrap_components* as dbc
from dash.dependencies import Input, Output
import plotly.express as px
import simulategames
from *IPython.display* import clear_output

*dash_bootstrap_ components and *IPython.display are the ones highlighted in visual studio code.
Also, the others that are not highlighted, they are still not recognized even if I did the pip install library

I expected for it to run after doing a virtual environment, but It didn't work


来源: stackexchange

问:
engine initialization failed for the first time in flutter
I am using flutter file view package to view document files but for the first it shows engine initialization failed and after restart app it work fine can someone help plzdart

```<code>          FileView(controller: widget.controller),
</code>```

widdget.controller is the path of file

ContentLicense: CC BY-SA 4.0

Body:
I am using flutter file view package to view document files but for the first it shows engine initialization failed and after restart app it work fine can someone help plzdart

          FileView(controller: widget.controller),

widdget.controller is the path of file


问:
Node.js - creating a module that supports multiple module system
I get that each module systems require separate entry points set on package.json like:

CJS package:

{
  "exports": {
    ".": {
      "require": "./dist/index.js",
      "import": "./dist/index.mjs"
    }
  }
}
```
<p><strong>ESM package:</strong></p>
<pre class="lang-json prettyprint-override"><code>{
  "type": "module"
  "exports": {
    ".": {
      "require": "./dist/index.cjs",
      "import": "./dist/index.js"
    }
  }
}
</code>```

The question is if there are sub modules(?) which are only imported to entry point, index.js, do I have to write them in separate formats as well?

Body:
I get that each module systems require separate entry points set on package.json like:

CJS package:

{
  "exports": {
    ".": {
      "require": "./dist/index.js",
      "import": "./dist/index.mjs"
    }
  }
}

ESM package:

{
  "type": "module"
  "exports": {
    ".": {
      "require": "./dist/index.cjs",
      "import": "./dist/index.js"
    }
  }
}

The question is if there are sub modules(?) which are only imported to entry point, index.js, do I have to write them in separate formats as well?


问:
Popping noise when piping audio into a vitual mic debian
I have a pipe module with the command pactl load-module module-pipe-source source_name=VirtualMic file=/tmp/virtualmic format=wav rate=44100 channels=2

I want to use SoX to play a sound file into it. I am doing this with sox "example.wav" -t wav - > /tmp/virtualmic

I have tried piping the audio using ffmpeg, to the same result, and to confirm that it is not my computer speakers or the file, playing the file in audio programs such as vlc does not include a popping sound.

The number of channels and the sample rate are both identical, and other then the pop the audio plays normally


问:
How to Control Numato Ethernet Relay Module
I have winforms application in c# and 8 channel numato ethernet relay module, I am able to connect using telnet using this library https://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library with this defualt credential ip : 169.254.1.1
port: 23
un : admin
pw : admin
the problem is that when I send the command nothing happens.

here is the full code of the telnet lib.

```<code>// minimalistic telnet implementation
// conceived by Tom Janssens on 2007/06/06  for codeproject
//
// http://www.corebvba.be

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;

namespace MinimalisticTelnet
{
    enum Verbs {
        WILL = 251,
        WONT = 252,
        DO = 253,
        DONT = 254,
        IAC = 255
    }

    enum Options
    {
        SGA = 3
    }

    class TelnetConnection
    {
        TcpClient tcpSocket;

        int TimeOutMs = 100;

        public TelnetConnection(string Hostname, int Port)
        {
            tcpSocket = new TcpClient(Hostname, Port);

        }

        public string Login(string Username,string Password,int LoginTimeOutMs)
        {
            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;
            string s = Read();
            if (!s.TrimEnd().EndsWith(":"))
               throw new Exception("Failed to connect : no login prompt");
            WriteLine(Username);

            s += Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no password prompt");
            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;

            return s;
        }

        public void WriteLine(string cmd)
        {
            Write(cmd + "\n");

        }

        public void Write(string cmd)
        {
            if (!tcpSocket.Connected) return;
            byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF","\0xFF\0xFF"));
            tcpSocket.GetStream().Write(buf, 0, buf.Length);
        }

        public string Read()
        {
            if (!tcpSocket.Connected) return null;
            StringBuilder sb=new StringBuilder();
            do
            {
                ParseTelnet(sb);
                System.Threading.Thread.Sleep(TimeOutMs);
            } while (tcpSocket.Available > 0);
            return sb.ToString();
        }

        public bool IsConnected
        {
            get { return tcpSocket.Connected; }
        }

        void ParseTelnet(StringBuilder sb)
        {
            while (tcpSocket.Available > 0)
            {
                int input = tcpSocket.GetStream().ReadByte();
                switch (input)
                {
                    case -1 :
                        break;
                    case (int)Verbs.IAC:
                        // interpret as command
                        int inputverb = tcpSocket.GetStream().ReadByte();
                        if (inputverb == -1) break;
                        switch (inputverb)
                        {
                            case (int)Verbs.IAC:
                                //literal IAC = 255 escaped, so append char 255 to string
                                sb.Append(inputverb);
                                break;
                            case (int)Verbs.DO:
                            case (int)Verbs.DONT:
                            case (int)Verbs.WILL:
                            case (int)Verbs.WONT:
                                // reply to all commands with "WONT", unless it is SGA (suppres go ahead)
                                int inputoption = tcpSocket.GetStream().ReadByte();
                                if (inputoption == -1) break;
                                tcpSocket.GetStream().WriteByte((byte)Verbs.IAC);
                                if (inputoption == (int)Options.SGA )
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL:(byte)Verbs.DO);
                                else
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT);
                                tcpSocket.GetStream().WriteByte((byte)inputoption);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        sb.Append( (char)input );
                        break;
                }
            }
        }
    }
}

</code>```

my form load code to connect to the device

```<code>using System;
using System.Net.Sockets;
using System.Windows.Forms;
using MinimalisticTelnet;

TelnetConnection tc;
private void Form1_Load(object sender, EventArgs e)
        {

            tc = new TelnetConnection("169.254.1.1", 23);
            string s = tc.Login("admin", "admin", 100);
            textBox1.Text = s;
        }
</code>```

button code to send command

```<code>  private void button1_Click(object sender, EventArgs e)
        {
            if (tc.IsConnected)
            {
                tc.WriteLine("relay on 0");
                textBox2.Text = tc.Read();
            }
        }
</code>```

Body:
I have winforms application in c# and 8 channel numato ethernet relay module, I am able to connect using telnet using this library https://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library with this defualt credential ip : 169.254.1.1
port: 23
un : admin
pw : admin
the problem is that when I send the command nothing happens.

here is the full code of the telnet lib.

// minimalistic telnet implementation
// conceived by Tom Janssens on 2007/06/06  for codeproject
//
// http://www.corebvba.be

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;

namespace MinimalisticTelnet
{
    enum Verbs {
        WILL = 251,
        WONT = 252,
        DO = 253,
        DONT = 254,
        IAC = 255
    }

    enum Options
    {
        SGA = 3
    }

    class TelnetConnection
    {
        TcpClient tcpSocket;

        int TimeOutMs = 100;

        public TelnetConnection(string Hostname, int Port)
        {
            tcpSocket = new TcpClient(Hostname, Port);

        }

        public string Login(string Username,string Password,int LoginTimeOutMs)
        {
            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;
            string s = Read();
            if (!s.TrimEnd().EndsWith(":"))
               throw new Exception("Failed to connect : no login prompt");
            WriteLine(Username);

            s += Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no password prompt");
            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;

            return s;
        }

        public void WriteLine(string cmd)
        {
            Write(cmd + "\n");

        }

        public void Write(string cmd)
        {
            if (!tcpSocket.Connected) return;
            byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF","\0xFF\0xFF"));
            tcpSocket.GetStream().Write(buf, 0, buf.Length);
        }

        public string Read()
        {
            if (!tcpSocket.Connected) return null;
            StringBuilder sb=new StringBuilder();
            do
            {
                ParseTelnet(sb);
                System.Threading.Thread.Sleep(TimeOutMs);
            } while (tcpSocket.Available > 0);
            return sb.ToString();
        }

        public bool IsConnected
        {
            get { return tcpSocket.Connected; }
        }

        void ParseTelnet(StringBuilder sb)
        {
            while (tcpSocket.Available > 0)
            {
                int input = tcpSocket.GetStream().ReadByte();
                switch (input)
                {
                    case -1 :
                        break;
                    case (int)Verbs.IAC:
                        // interpret as command
                        int inputverb = tcpSocket.GetStream().ReadByte();
                        if (inputverb == -1) break;
                        switch (inputverb)
                        {
                            case (int)Verbs.IAC:
                                //literal IAC = 255 escaped, so append char 255 to string
                                sb.Append(inputverb);
                                break;
                            case (int)Verbs.DO:
                            case (int)Verbs.DONT:
                            case (int)Verbs.WILL:
                            case (int)Verbs.WONT:
                                // reply to all commands with "WONT", unless it is SGA (suppres go ahead)
                                int inputoption = tcpSocket.GetStream().ReadByte();
                                if (inputoption == -1) break;
                                tcpSocket.GetStream().WriteByte((byte)Verbs.IAC);
                                if (inputoption == (int)Options.SGA )
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL:(byte)Verbs.DO);
                                else
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT);
                                tcpSocket.GetStream().WriteByte((byte)inputoption);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        sb.Append( (char)input );
                        break;
                }
            }
        }
    }
}

my form load code to connect to the device

using System;
using System.Net.Sockets;
using System.Windows.Forms;
using MinimalisticTelnet;

TelnetConnection tc;
private void Form1_Load(object sender, EventArgs e)
        {

            tc = new TelnetConnection("169.254.1.1", 23);
            string s = tc.Login("admin", "admin", 100);
            textBox1.Text = s;
        }

button code to send command

  private void button1_Click(object sender, EventArgs e)
        {
            if (tc.IsConnected)
            {
                tc.WriteLine("relay on 0");
                textBox2.Text = tc.Read();
            }
        }


问:
problem with QueueRecieving value in FreeRTOS
I'm implement task handler for GUI task by using LVGL and FreeRTOS in ESP32

Whenever I get queue message, I read message as 0 in handler.

When I send message, It is fine.

LOG:

```<code>I (105690) wifi_app: WIFI_APP_MSG_STA_DISCONNECTED: USER REQUESTED DISCONNECTION
I (105700) LVGL: SEND MESSAGE
I (105700) LVGL: SENDING msgID 4 // when send
I (105710) LVGL: RECEVING msgID: 0 // read message in handler
I (105710) LVGL: Get NTU from sensor
I (105720) http_server: HTTP_MSG_WIFI_USER_DISCONNECT
</code>```

Handler: Parsing message Id by using switch statement

```<code>static void cmd_parsing(void *arg)
{
    lvgl_queue_message_t lvglMsg;

    for (;;)
    {

        if (xQueueReceive(lvgl_queue_handle, &lvglMsg, portMAX_DELAY))
        {

            ESP_LOGI(TAG, "Recieving msgID: %d", lvglMsg.msgID);
            switch (lvglMsg.msgID)
            {
                case LVGL_MSG_SEND_NTU:
                        ESP_LOGI(TAG, "Get NTU from sensor");
                        //                    lv_label_set_text(label_ntu, evt.string1);
                        lv_label_set_text_fmt(label_ntu, "%0.3f NTU", lvglMsg.valueFloat);
                        break;
                case LVGL_MSG_WIFI_CONNECT_INIT:
                        ESP_LOGI(TAG, "Create spinner for connecting Wi-Fi");

                        create_spinner();

                        xSemaphoreGive(xGuiSemaphore);
                    break;
                case LVGL_MSG_WIFI_USER_DISCONNECT:

                        ESP_LOGI(TAG, "WIFI_USER_DISCONNECT");

                        lv_obj_clean(settings_tab);
                        create_list_settings();
                    break;
                default:
                    break;
            }
        }
    }
</code>```

Send: Sending message Id in WIFI task

```<code>BaseType_t lvgl_send_message(lvgl_message_e msgID)
{
    ESP_LOGI(TAG, "SEND MESSAGE");
    ESP_LOGI(TAG, "Sending msgID %d", msgID);
    lvgl_queue_message_t lvglMsg;
    lvglMsg.msgID = msgID;
    return xQueueSend(lvgl_queue_handle, &lvglMsg, portMAX_DELAY);
}
</code>```

Body:
I'm implement task handler for GUI task by using LVGL and FreeRTOS in ESP32

Whenever I get queue message, I read message as 0 in handler.

When I send message, It is fine.

LOG:

I (105690) wifi_app: WIFI_APP_MSG_STA_DISCONNECTED: USER REQUESTED DISCONNECTION
I (105700) LVGL: SEND MESSAGE
I (105700) LVGL: SENDING msgID 4 // when send
I (105710) LVGL: RECEVING msgID: 0 // read message in handler
I (105710) LVGL: Get NTU from sensor
I (105720) http_server: HTTP_MSG_WIFI_USER_DISCONNECT

Handler: Parsing message Id by using switch statement

static void cmd_parsing(void *arg)
{
    lvgl_queue_message_t lvglMsg;

    for (;;)
    {

        if (xQueueReceive(lvgl_queue_handle, &lvglMsg, portMAX_DELAY))
        {

            ESP_LOGI(TAG, "Recieving msgID: %d", lvglMsg.msgID);
            switch (lvglMsg.msgID)
            {
                case LVGL_MSG_SEND_NTU:
                        ESP_LOGI(TAG, "Get NTU from sensor");
                        //                    lv_label_set_text(label_ntu, evt.string1);
                        lv_label_set_text_fmt(label_ntu, "%0.3f NTU", lvglMsg.valueFloat);
                        break;
                case LVGL_MSG_WIFI_CONNECT_INIT:
                        ESP_LOGI(TAG, "Create spinner for connecting Wi-Fi");

                        create_spinner();

                        xSemaphoreGive(xGuiSemaphore);
                    break;
                case LVGL_MSG_WIFI_USER_DISCONNECT:

                        ESP_LOGI(TAG, "WIFI_USER_DISCONNECT");

                        lv_obj_clean(settings_tab);
                        create_list_settings();
                    break;
                default:
                    break;
            }
        }
    }

Send: Sending message Id in WIFI task

BaseType_t lvgl_send_message(lvgl_message_e msgID)
{
    ESP_LOGI(TAG, "SEND MESSAGE");
    ESP_LOGI(TAG, "Sending msgID %d", msgID);
    lvgl_queue_message_t lvglMsg;
    lvglMsg.msgID = msgID;
    return xQueueSend(lvgl_queue_handle, &lvglMsg, portMAX_DELAY);
}


问:
Not able to edit a component inside another component in AEM editable templates
I have a editable template. on the template, i am adding a component called contact us which intern adds button component to the parsys. I am able to edit/configure contactus component but I am unable to edit/configure button component which is added inside contact us component. It is not working on the editable template. But it works on the page level.


问:
OpenXML Spread sheet style always set to the first font
I am using C#.net with OpenXML for creating a spread sheet. I create few fonts and added to the style sheet . Th problem is I can't switch to the second font.
private Cell CreateCell(string text, uint styleIndex)
{
Cell cell = new Cell();
cell.StyleIndex = styleIndex;</p>
```<code>            cell.DataType = ResolveCellDataTypeOnValue(text);
            cell.CellValue = new CellValue(text);
            return cell;
        }

 using (SpreadsheetDocument document = SpreadsheetDocument.Create("somefile.xls", SpreadsheetDocumentType.Workbook))
                {
                    WorkbookPart workbookPart = document.AddWorkbookPart();
                    workbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
                    WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();

                    WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();
                    sp.Stylesheet = new DocumentFormat.OpenXml.Spreadsheet.Stylesheet();
                    Stylesheet stylesheet = sp.Stylesheet;
                    stylesheet.Fonts = new DocumentFormat.OpenXml.Spreadsheet.Fonts();

                    Font font = new Font(new FontSize() { Val = 11 }, new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = HexBinaryValue.FromString("4b53cb") }, new Bold());

                    Font font2 = new Font(new FontSize() { Val = 15 }, new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = HexBinaryValue.FromString("c93653") }, new Italic());
                    stylesheet.Fonts.Append(font);

                    stylesheet.Fonts.Append(font2);

                    stylesheet.Save();

                    SheetData sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();

                    MergeCells mergeCells = new MergeCells();

                    workRow.Append(CreateCell("Some text", (UInt32Value)2U));

                    worksheetPart.Worksheet = new Worksheet(sheetData);
                    worksheetPart.Worksheet.Save();
                    Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                    Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Trial" };
                   sheets.Append(sheet);
                    workbookPart.Workbook.Save();

                }
</code>```

Body:
I am using C#.net with OpenXML for creating a spread sheet. I create few fonts and added to the style sheet . Th problem is I can't switch to the second font.
private Cell CreateCell(string text, uint styleIndex)
{
Cell cell = new Cell();
cell.StyleIndex = styleIndex;

            cell.DataType = ResolveCellDataTypeOnValue(text);
            cell.CellValue = new CellValue(text);
            return cell;
        }

 using (SpreadsheetDocument document = SpreadsheetDocument.Create("somefile.xls", SpreadsheetDocumentType.Workbook))
                {
                    WorkbookPart workbookPart = document.AddWorkbookPart();
                    workbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
                    WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();

                    WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();
                    sp.Stylesheet = new DocumentFormat.OpenXml.Spreadsheet.Stylesheet();
                    Stylesheet stylesheet = sp.Stylesheet;
                    stylesheet.Fonts = new DocumentFormat.OpenXml.Spreadsheet.Fonts();

                    Font font = new Font(new FontSize() { Val = 11 }, new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = HexBinaryValue.FromString("4b53cb") }, new Bold());

                    Font font2 = new Font(new FontSize() { Val = 15 }, new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = HexBinaryValue.FromString("c93653") }, new Italic());
                    stylesheet.Fonts.Append(font);

                    stylesheet.Fonts.Append(font2);

                    stylesheet.Save();

                    SheetData sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();

                    MergeCells mergeCells = new MergeCells();

                    workRow.Append(CreateCell("Some text", (UInt32Value)2U));

                    worksheetPart.Worksheet = new Worksheet(sheetData);
                    worksheetPart.Worksheet.Save();
                    Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                    Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Trial" };
                   sheets.Append(sheet);
                    workbookPart.Workbook.Save();

                }


问:
every node in one graph have the same output in my GCN model
I have several graphs and I use these graphs to train a model hoping to identify the category of each node. I have three categories, and here are the formulation of one of my graph (using the data object):

```<code>Data(x=[100,64],pos=[100,2],edge_index=[2,546],y=[100],edge_weight=[546])
</code>```

x is the embedding of every node, here have 100 nodes and each node have a 64-dimension feature, pos is the coordinate of each node. A two-dimensional vector in edge_index represents an edge between two points. And the edge_weight is the weight corresponding to each edge.

Here is my GCN model:

```<code>import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv

# GCN model with 2 layers
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = GCNConv(data.num_features, 16)
        self.conv2 = GCNConv(16, int(data.num_classes))

    def forward(self):
        x, edge_index = data.x, data.edge_index
        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, training=self.training)
        x = self.conv2(x, edge_index)
        return F.log_softmax(x, dim=1)

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

data =  data.to(device)

model = Net().to(device)
</code>```

and here is my training code:

```<code>for epoch in range(epoches):
    for img_path in img_paths: #in order to build the graph
         data=build_graph(img_path)
         model.train()
         optimizer.zero_grad()
         output=GCNmodel(data)
         F.nll_loss(output,target).backward()
         optimizer.step()
</code>```

but using this code, every node in one graph have the same output, especially have the negative num.
enter image description here

Note:The category 1 and 2 of each picture is balanced, the category 3 in every image is samller. But the data should not be the main reason for this result

It confuse me  lots of time, I am very grateful, if you can help me.

Body:
I have several graphs and I use these graphs to train a model hoping to identify the category of each node. I have three categories, and here are the formulation of one of my graph (using the data object):

Data(x=[100,64],pos=[100,2],edge_index=[2,546],y=[100],edge_weight=[546])

x is the embedding of every node, here have 100 nodes and each node have a 64-dimension feature, pos is the coordinate of each node. A two-dimensional vector in edge_index represents an edge between two points. And the edge_weight is the weight corresponding to each edge.

Here is my GCN model:

import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv

# GCN model with 2 layers
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = GCNConv(data.num_features, 16)
        self.conv2 = GCNConv(16, int(data.num_classes))

    def forward(self):
        x, edge_index = data.x, data.edge_index
        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, training=self.training)
        x = self.conv2(x, edge_index)
        return F.log_softmax(x, dim=1)

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

data =  data.to(device)

model = Net().to(device)

and here is my training code:

for epoch in range(epoches):
    for img_path in img_paths: #in order to build the graph
         data=build_graph(img_path)
         model.train()
         optimizer.zero_grad()
         output=GCNmodel(data)
         F.nll_loss(output,target).backward()
         optimizer.step()

but using this code, every node in one graph have the same output, especially have the negative num.
enter image description here

Note:The category 1 and 2 of each picture is balanced, the category 3 in every image is samller. But the data should not be the main reason for this result

It confuse me  lots of time, I am very grateful, if you can help me.


问:
Getting some crashing error reports from google play console
I am using react native 64.0.3 version target sdk version 31. Getting this error from play console like this. Any solution? It is happening from recent update that I uploaded to the play store yesterday. Here is my crash report details:</p>
```<code> 1)Type
        java.lang.NoSuchMethodError
        Exception java.lang.NoSuchMethodError:
          at f.c.h.a.a.c.f
          at f.c.h.a.a.c.e
          at com.facebook.react.modules.fresco.FrescoModule.initialize
          at com.facebook.react.bridge.ModuleHolder.doInitialize
          at com.facebook.react.bridge.ModuleHolder.markInitializable
          at com.facebook.react.bridge.NativeModuleRegistry.notifyJSInstanceInitialized
          at com.facebook.react.bridge.CatalystInstanceImpl$2.run
          at android.os.Handler.handleCallback (Handler.java:751)
          at android.os.Handler.dispatchMessage (Handler.java:95)
          at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage
          at android.os.Looper.loop (Looper.java:154)
          at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run
          at java.lang.Thread.run (Thread.java:762)
2)Type

com.facebook.react.common.c

Exception com.facebook.react.common.c:
  at com.facebook.react.modules.core.ExceptionsManagerModule.reportException (ExceptionsManagerModule.java)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.facebook.react.bridge.JavaMethodWrapper.invoke (JavaMethodWrapper.java)
  at com.facebook.react.bridge.JavaModuleWrapper.invoke (JavaModuleWrapper.java)
  at com.facebook.react.bridge.queue.NativeRunnable.run (NativeRunnable.java)
  at android.os.Handler.handleCallback (Handler.java:938)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage (MessageQueueThreadHandler.java)
  at android.os.Looper.loopOnce (Looper.java:238)
  at android.os.Looper.loop (Looper.java:349)
  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run (MessageQueueThreadImpl.java)
  at java.lang.Thread.run (Thread.java:920)

</code>```

Body:
I am using react native 64.0.3 version target sdk version 31. Getting this error from play console like this. Any solution? It is happening from recent update that I uploaded to the play store yesterday. Here is my crash report details:

 1)Type
        java.lang.NoSuchMethodError
        Exception java.lang.NoSuchMethodError:
          at f.c.h.a.a.c.f
          at f.c.h.a.a.c.e
          at com.facebook.react.modules.fresco.FrescoModule.initialize
          at com.facebook.react.bridge.ModuleHolder.doInitialize
          at com.facebook.react.bridge.ModuleHolder.markInitializable
          at com.facebook.react.bridge.NativeModuleRegistry.notifyJSInstanceInitialized
          at com.facebook.react.bridge.CatalystInstanceImpl$2.run
          at android.os.Handler.handleCallback (Handler.java:751)
          at android.os.Handler.dispatchMessage (Handler.java:95)
          at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage
          at android.os.Looper.loop (Looper.java:154)
          at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run
          at java.lang.Thread.run (Thread.java:762)
2)Type

com.facebook.react.common.c

Exception com.facebook.react.common.c:
  at com.facebook.react.modules.core.ExceptionsManagerModule.reportException (ExceptionsManagerModule.java)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.facebook.react.bridge.JavaMethodWrapper.invoke (JavaMethodWrapper.java)
  at com.facebook.react.bridge.JavaModuleWrapper.invoke (JavaModuleWrapper.java)
  at com.facebook.react.bridge.queue.NativeRunnable.run (NativeRunnable.java)
  at android.os.Handler.handleCallback (Handler.java:938)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage (MessageQueueThreadHandler.java)
  at android.os.Looper.loopOnce (Looper.java:238)
  at android.os.Looper.loop (Looper.java:349)
  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run (MessageQueueThreadImpl.java)
  at java.lang.Thread.run (Thread.java:920)


问:
pytorch_lightning Trainer.fit method: maximum recursion depth exceeded while calling a Python object
Here is the code I am running in free instance of google colab with a GPU. Any hints and directions, please? I have pasted the error below. Please let me know if you need any more info. Thanks
Following is a custom model class

```<code>class BioQAModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.model = T5ForConditionalGeneration.from_pretrained(
            MODEL_NAME, return_dict=True
        )

    def forward(self, input_ids, attention_mask, labels=None):
        output = model(
            input_ids=input_ids, attention_mask=attention_mask, labels=labels
        )

        return output.loss, output.logits

    def training_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["labels"]
        loss, outputs = self(input_ids, attention_mask, labels)
        self.log("train_loss", loss, prog_bar=True, logger=True)
        return loss

    def validation_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["labels"]
        loss, outputs = self(input_ids, attention_mask, labels)
        self.log("val_loss", loss, prog_bar=True, logger=True)
        return loss

    def test_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["labels"]
        loss, outputs = self(input_ids, attention_mask, labels)
        self.log("test_loss", loss, prog_bar=True, logger=True)
        return loss

    def configure_optimizers(self):
        return AdamW(self.parameters(), lr=0.0001)

model = BioQAModel()

checkpoint_callback = ModelCheckpoint(
  dirpath="checkpoints", # where the ckpt will be saved
  filename="best-checkpoint", # the name of the best ckpt
  save_top_k=1, # save only the best ckpt
  verbose=True,
  monitor="validation_loss", # ckpt will be save according to the validation loss that you need to calculate on the validation step when you train your model
  mode="min" # validation loos need to be min
)

os.cpu_count()
from tensorflow.python.client import device_lib
device_lib.list_local_devices()

output is:
[name: "/device:CPU:0"
 device_type: "CPU"
 memory_limit: 268435456
 locality {
 }
 incarnation: 8466913069619314561
 xla_global_id: -1, name: "/device:GPU:0"
 device_type: "GPU"
 memory_limit: 13926924288
 locality {
   bus_id: 1
   links {
   }
 }
 incarnation: 3190592957799506681
 physical_device_desc: "device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5"
 xla_global_id: 416903419]

    trainer = pl.Trainer(
      callbacks = [checkpoint_callback],
      max_epochs = N_EPOCHS,
      accelerator='gpu',
      devices=1,
      gpus=1
      #check_val_every_n_epoch=10
      #num_nodes=1
      #progress_bar_refresh_rate=30
    )

    !rm -rf lightning_logs

    import sys
    # Using sys.getrecursionlimit() method
    # to find the current recursion limit
    limit = sys.getrecursionlimit()

    # Print the current limit
    print('Before changing, limit of stack =', limit)

    # New limit
    Newlimit = 10000

    # Using sys.setrecursionlimit() method
    sys.setrecursionlimit(Newlimit)

    # Using sys.getrecursionlimit() method
    # to find the current recursion limit
    limit = sys.getrecursionlimit()

    # Print the current limit
    print('After changing, limit of stack =', limit)

    trainer.fit(model,data_module)
</code>```

Above I tried to increase recursionlimit to 10k but still it timesout after around 25 seconds.
Here is the error:

```<code>    Error:
    WARNING:pytorch_lightning.loggers.tensorboard:Missing logger folder: /content/lightning_logs
    INFO:pytorch_lightning.accelerators.cuda:LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]
    INFO:pytorch_lightning.callbacks.model_summary:
      | Name  | Type                       | Params
    -----------------------------------------------------
    0 | model | T5ForConditionalGeneration | 222 M
    -----------------------------------------------------
    222 M     Trainable params
    0         Non-trainable params
    222 M     Total params
    891.614   Total estimated model params size (MB)
    Sanity Checking DataLoader 0: 0%
    0/2 [00:00<?, ?it/s]
    ---------------------------------------------------------------------------
    RecursionError                            Traceback (most recent call last)
    <ipython-input-102-d702bb950aea> in <module>
          4 #trainer.fit(model)

    ....

    last 2 frames repeated, from the frame below ...

    /usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
       1188         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
       1189                 or _global_forward_hooks or _global_forward_pre_hooks):
    -> 1190             return forward_call(*input, **kwargs)
       1191         # Do not call functions when jit is used
       1192         full_backward_hooks, non_full_backward_hooks = [], []

    RecursionError: maximum recursion depth exceeded while calling a Python object
</code>```

Body:
Here is the code I am running in free instance of google colab with a GPU. Any hints and directions, please? I have pasted the error below. Please let me know if you need any more info. Thanks
Following is a custom model class

class BioQAModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.model = T5ForConditionalGeneration.from_pretrained(
            MODEL_NAME, return_dict=True
        )

    def forward(self, input_ids, attention_mask, labels=None):
        output = model(
            input_ids=input_ids, attention_mask=attention_mask, labels=labels
        )

        return output.loss, output.logits

    def training_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["labels"]
        loss, outputs = self(input_ids, attention_mask, labels)
        self.log("train_loss", loss, prog_bar=True, logger=True)
        return loss

    def validation_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["labels"]
        loss, outputs = self(input_ids, attention_mask, labels)
        self.log("val_loss", loss, prog_bar=True, logger=True)
        return loss

    def test_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        labels = batch["labels"]
        loss, outputs = self(input_ids, attention_mask, labels)
        self.log("test_loss", loss, prog_bar=True, logger=True)
        return loss

    def configure_optimizers(self):
        return AdamW(self.parameters(), lr=0.0001)

model = BioQAModel()

checkpoint_callback = ModelCheckpoint(
  dirpath="checkpoints", # where the ckpt will be saved
  filename="best-checkpoint", # the name of the best ckpt
  save_top_k=1, # save only the best ckpt
  verbose=True,
  monitor="validation_loss", # ckpt will be save according to the validation loss that you need to calculate on the validation step when you train your model
  mode="min" # validation loos need to be min
)

os.cpu_count()
from tensorflow.python.client import device_lib
device_lib.list_local_devices()

output is:
[name: "/device:CPU:0"
 device_type: "CPU"
 memory_limit: 268435456
 locality {
 }
 incarnation: 8466913069619314561
 xla_global_id: -1, name: "/device:GPU:0"
 device_type: "GPU"
 memory_limit: 13926924288
 locality {
   bus_id: 1
   links {
   }
 }
 incarnation: 3190592957799506681
 physical_device_desc: "device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5"
 xla_global_id: 416903419]

    trainer = pl.Trainer(
      callbacks = [checkpoint_callback],
      max_epochs = N_EPOCHS,
      accelerator='gpu',
      devices=1,
      gpus=1
      #check_val_every_n_epoch=10
      #num_nodes=1
      #progress_bar_refresh_rate=30
    )

    !rm -rf lightning_logs

    import sys
    # Using sys.getrecursionlimit() method
    # to find the current recursion limit
    limit = sys.getrecursionlimit()

    # Print the current limit
    print('Before changing, limit of stack =', limit)

    # New limit
    Newlimit = 10000

    # Using sys.setrecursionlimit() method
    sys.setrecursionlimit(Newlimit)

    # Using sys.getrecursionlimit() method
    # to find the current recursion limit
    limit = sys.getrecursionlimit()

    # Print the current limit
    print('After changing, limit of stack =', limit)

    trainer.fit(model,data_module)

Above I tried to increase recursionlimit to 10k but still it timesout after around 25 seconds.
Here is the error:

    Error:
    WARNING:pytorch_lightning.loggers.tensorboard:Missing logger folder: /content/lightning_logs
    INFO:pytorch_lightning.accelerators.cuda:LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]
    INFO:pytorch_lightning.callbacks.model_summary:
      | Name  | Type                       | Params
    -----------------------------------------------------
    0 | model | T5ForConditionalGeneration | 222 M
    -----------------------------------------------------
    222 M     Trainable params
    0         Non-trainable params
    222 M     Total params
    891.614   Total estimated model params size (MB)
    Sanity Checking DataLoader 0: 0%
    0/2 [00:00<?, ?it/s]
    ---------------------------------------------------------------------------
    RecursionError                            Traceback (most recent call last)
    <ipython-input-102-d702bb950aea> in <module>
          4 #trainer.fit(model)

    ....

    last 2 frames repeated, from the frame below ...

    /usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
       1188         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
       1189                 or _global_forward_hooks or _global_forward_pre_hooks):
    -> 1190             return forward_call(*input, **kwargs)
       1191         # Do not call functions when jit is used
       1192         full_backward_hooks, non_full_backward_hooks = [], []

    RecursionError: maximum recursion depth exceeded while calling a Python object


问:
How to read a connection to a specific database depending on the input
I have several databases in my project. The config file describes the connections to them.

```<code>class Config(object):
    DATABASE_CONFIG_DB1 = {
        ...
    }

    DATABASE_CONFIG_DB2 = {
        ...
    }

</code>```

How to make a connection to a specific database read from the config by input parameters?

I need to run the project on each of the databases separately, but I can't do it dynamically.
So far, I am commenting on the extra connections and assigning a connection to only 1 database.

Body:
I have several databases in my project. The config file describes the connections to them.

class Config(object):
    DATABASE_CONFIG_DB1 = {
        ...
    }

    DATABASE_CONFIG_DB2 = {
        ...
    }

How to make a connection to a specific database read from the config by input parameters?

I need to run the project on each of the databases separately, but I can't do it dynamically.
So far, I am commenting on the extra connections and assigning a connection to only 1 database.


问:
Can I make a clickable hyperlink from a C# comment to a Markdown file?
I have a project that is largely C# and with some Markdown documentation. Sometimes I want to link from Markdown to C# classes ("this is implemented here..."), and sometimes I want to link from a C# comment to Markdown ("for explanation, see here..."). The first (linking from MD to CS) is easy enough. I am having trouble with the second (linking from CS to MD).

Ideally I would like:

Markdown references from CS comments should be clickable hyperlinks in Visual Studio (and preferably also Visual Studio code and the GitHub browser-based UI).

The compiler should warn me if a link points to a nonexistent file.

If I cannot achieve 2, then at least there should be an easy way for me to implement a unit test that scans the code, finds these CS-to-MD links and checks them.

Is this possible?


问:
After the form is submitted in WordPress, the value will be displayed on the Myquery page
this is index page

    <form method="POST" action="http://localhost/wp6/myquery/"> <input type="text" name="name"> <input type="submit" name="submit"> </form>

this is myquery page
echo $name = $_POST['name'];


问:
Typescript Generic type Error : Argument of type 'string' is not assignable to parameter of type 'SetStateAction<T>'
The purpose of the code is to create a custom hook for the input tag.
I wanted to use a generic type in this custom hook.
The type of InputReturn is pasted from vscode.
At this time, an error occurs in setValue in the handler function.
" Argument of type 'string' is not assignable to parameter of type 'SetStateAction' "
please, how can i fix it?

```<code>type InputReturn<T> = readonly [
  T,
  (e: React.ChangeEvent<HTMLInputElement>) => void,
  Dispatch<SetStateAction<T>>,
];

export function useInput<T>(initialValue: T): InputReturn<T> {
  const [value, setValue] = useState(initialValue);
  const handler = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
[enter image description here](https://i.stack.imgur.com/IY34l.png)    setValue(e.target.value);
  }, []);
  return [value, handler, setValue] as const;
}
</code>```

At first, I want change union type "string | number" to generic type.
Here is the code before the introduction of generic types:

```<code>export function useInput(initialValue: string | number) {
  const [value, setValue] = useState(initialValue);
  const handler = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  }, []);
  return [value, handler, setValue] as const;
}
</code>```

Body:
The purpose of the code is to create a custom hook for the input tag.
I wanted to use a generic type in this custom hook.
The type of InputReturn is pasted from vscode.
At this time, an error occurs in setValue in the handler function.
" Argument of type 'string' is not assignable to parameter of type 'SetStateAction' "
please, how can i fix it?

type InputReturn<T> = readonly [
  T,
  (e: React.ChangeEvent<HTMLInputElement>) => void,
  Dispatch<SetStateAction<T>>,
];

export function useInput<T>(initialValue: T): InputReturn<T> {
  const [value, setValue] = useState(initialValue);
  const handler = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
[enter image description here](https://i.stack.imgur.com/IY34l.png)    setValue(e.target.value);
  }, []);
  return [value, handler, setValue] as const;
}

At first, I want change union type "string | number" to generic type.
Here is the code before the introduction of generic types:

export function useInput(initialValue: string | number) {
  const [value, setValue] = useState(initialValue);
  const handler = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  }, []);
  return [value, handler, setValue] as const;
}


问:
How to use Textview output for another class method?
I have just started using eclipse adt(android developer tool) and i am working on electricbill calculator app. The app interface looks like this: App interface

The user will input a value in previous consumption and current consumption then calculate(1st button) to get the total consumption. Then enter the rate  and compute(2nd button, multiplies total consumption and rate) to get the electricbill.

My main activity contains onClickListeners for the buttons. The first part of the calculation works, but when i try to input a value and rate and compute it, the application crashes and i dont know where is the problem. Here is my code:

Calculate Button

```<code>public class MainActivity extends Activity {

    EditText PrevConEdt, CurrConEdt, RateEdt;
    TextView ConsumptionTv, ElectricBillTv;
    Button CalculateBtn, ComputeBtn, ClearBtn, ClearBtn2;
    Double rateDbl, cbillDbl, consumptionDbl, prevDbl, currentDbl;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PrevConEdt = (EditText) findViewById(R.id.txtPreviousConsumption);
        CurrConEdt = (EditText) findViewById(R.id.txtCurrentConsumption);
        RateEdt = (EditText) findViewById(R.id.txtEnterRate);

        ConsumptionTv = (TextView) findViewById(R.id.txtConsumption);
        ElectricBillTv = (TextView) findViewById(R.id.txtEbill);

        CalculateBtn = (Button) findViewById(R.id.btnCalculate);
        CalculateBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View Calculate) {

                String prev, current, consumption;
                 prev = PrevConEdt.getText().toString();
                 current = CurrConEdt.getText().toString();

                 if(PrevConEdt.length() == 0){
                     Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
                     return;
                 }else if(CurrConEdt.length() == 0){
                     Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
                     return;

                 }else{
                     Double prevDbl, currentDbl, consumptionDbl;
                     prevDbl = Double.parseDouble(prev);
                     currentDbl = Double.parseDouble(current);

                     if(currentDbl < prevDbl){
                         //String msg = "Current should be greater than previous.";
                         //int duration = Toast.LENGTH_LONG;
                         //Toast.makeText(getBaseContext(), msg, duration).show();
                         //PrevConEdt.requestFocus();
                         CurrConEdt.setError("Current should be greater than previous.");
                         return;

                     }else{
                         consumptionDbl = currentDbl - prevDbl;
                         String consumptionStr = String.format("%.2f kWh", consumptionDbl);
                         ConsumptionTv.setText(consumptionStr);
                     }

                 }

            }

        });
</code>```

Compute Button

```<code>ComputeBtn = (Button) findViewById(R.id.btnCompute);
        ComputeBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View compute) {

                String rate, consumption;
                rate = RateEdt.getText().toString();
                consumption = ConsumptionTv.getText().toString();

                if(RateEdt.length() == 0){
                    RateEdt.setError("Rate is required.");
                    return;
                }else{
                    Double rateDbl, cbillDbl, consumptionDbl;
                    rateDbl = Double.parseDouble(rate);
                    consumptionDbl = Double.parseDouble(consumption);

                    cbillDbl = consumptionDbl *  rateDbl;
                    String billStr = String.format("Php %.2f", cbillDbl);
                    ElectricBillTv.setText(billStr);

                }

            }
        });
</code>```

Body:
I have just started using eclipse adt(android developer tool) and i am working on electricbill calculator app. The app interface looks like this: App interface

The user will input a value in previous consumption and current consumption then calculate(1st button) to get the total consumption. Then enter the rate  and compute(2nd button, multiplies total consumption and rate) to get the electricbill.

My main activity contains onClickListeners for the buttons. The first part of the calculation works, but when i try to input a value and rate and compute it, the application crashes and i dont know where is the problem. Here is my code:

Calculate Button

public class MainActivity extends Activity {

    EditText PrevConEdt, CurrConEdt, RateEdt;
    TextView ConsumptionTv, ElectricBillTv;
    Button CalculateBtn, ComputeBtn, ClearBtn, ClearBtn2;
    Double rateDbl, cbillDbl, consumptionDbl, prevDbl, currentDbl;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PrevConEdt = (EditText) findViewById(R.id.txtPreviousConsumption);
        CurrConEdt = (EditText) findViewById(R.id.txtCurrentConsumption);
        RateEdt = (EditText) findViewById(R.id.txtEnterRate);

        ConsumptionTv = (TextView) findViewById(R.id.txtConsumption);
        ElectricBillTv = (TextView) findViewById(R.id.txtEbill);

        CalculateBtn = (Button) findViewById(R.id.btnCalculate);
        CalculateBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View Calculate) {

                String prev, current, consumption;
                 prev = PrevConEdt.getText().toString();
                 current = CurrConEdt.getText().toString();

                 if(PrevConEdt.length() == 0){
                     Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
                     return;
                 }else if(CurrConEdt.length() == 0){
                     Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
                     return;

                 }else{
                     Double prevDbl, currentDbl, consumptionDbl;
                     prevDbl = Double.parseDouble(prev);
                     currentDbl = Double.parseDouble(current);

                     if(currentDbl < prevDbl){
                         //String msg = "Current should be greater than previous.";
                         //int duration = Toast.LENGTH_LONG;
                         //Toast.makeText(getBaseContext(), msg, duration).show();
                         //PrevConEdt.requestFocus();
                         CurrConEdt.setError("Current should be greater than previous.");
                         return;

                     }else{
                         consumptionDbl = currentDbl - prevDbl;
                         String consumptionStr = String.format("%.2f kWh", consumptionDbl);
                         ConsumptionTv.setText(consumptionStr);
                     }

                 }

            }

        });

Compute Button

ComputeBtn = (Button) findViewById(R.id.btnCompute);
        ComputeBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View compute) {

                String rate, consumption;
                rate = RateEdt.getText().toString();
                consumption = ConsumptionTv.getText().toString();

                if(RateEdt.length() == 0){
                    RateEdt.setError("Rate is required.");
                    return;
                }else{
                    Double rateDbl, cbillDbl, consumptionDbl;
                    rateDbl = Double.parseDouble(rate);
                    consumptionDbl = Double.parseDouble(consumption);

                    cbillDbl = consumptionDbl *  rateDbl;
                    String billStr = String.format("Php %.2f", cbillDbl);
                    ElectricBillTv.setText(billStr);

                }

            }
        });


问:
setting the "DT_RowId" property when using simple_datatables
I am using the simple datatables gem to integrate JQuery Datatables into my Rails App.

Is it possible to send the DT_RowId property in the json document as described in the doc when using simple_datatables?


问:
How to fix time out issue in FCM?
I'm working on a laravel apis which is consumed by a mobile application. The issue is i am using this library ( https://github.com/kreait/firebase-php ) to send FCM to device Ids. I have 10k device ids in my db. Issue is the code is implemented badly and it gets timedout after 1 minute. I need advice what is the best way to overcome this issue?

I have written this code:

```<code>// General Notification
$deviceTokens = PushDevices::all()->pluck( 'device_id' )->toArray();
if ( $request->hasFile( 'file' ) || $request->file ) {
    try {
        $request->validate( [
            'image' => 'image|mimes:jpeg,jpg|max:2048|size:400'
        ] );
        $originName = $request->file( 'file' )->getClientOriginalName();
        $fileName   = pathinfo( $originName, PATHINFO_FILENAME );
        $extension  = $request->file( 'file' )->getClientOriginalExtension();
        $fileNames  = time() . '.' . $extension;
        $request->file( 'file' )->move( public_path( 'storage/notification' ), $fileNames );
        $notiData = [
            'title'    => $request->title,
            'body'     => $request->body,
            'imageurl' => $fileNames
        ];

        // Create a copy in database for notifications.
        NotificationTable::create( $notiData );
        // Initiate token with https
        $notification = [
            'title' => $validation->safe()->only( 'title' )['title'],
            'body'  => $validation->safe()->only( 'body' )['body'],
            'image' => 'https://example.com/storage/notification/' . $fileNames
        ];

        $data = [
            'first_key'  => 'First Value',
            'second_key' => 'Second Value',
        ];

        $response[] = '';
        foreach ( $deviceTokens as $object ) {
            // $message = CloudMessage::new()->withTarget('token', $object)->withNotification($notification);
            $message = CloudMessage::fromArray( [
                'token'        => $object,
                'notification' => $notification
            ] );
            try {
                $sendReport = $this->messaging->send( $message );
                $response[] = $sendReport;
            } catch ( \Throwable $e ) {
                $response[] = $e;
            }
        }

        return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
    } catch ( \Throwable $th ) {
    return response()->json( [
        'status'  => false,
        'message' => $th->getMessage()
    ], 500 );
}}

$batchSize = 1000;
$deviceGroups = array_chunk($deviceTokens, $batchSize);
$notification = ['title' => $validation->safe()->only( 'title' )['title'], 'body'  => $validation->safe()->only( 'body' )['body'],];
NotificationTable::create( $notification );
$data = ['first_key'  => 'First Value', 'second_key' => 'Second Value',];

$response = array();
foreach ( $deviceTokens as $object ) {
    $message = CloudMessage::new()->withTarget( 'token', $object )->withNotification( $notification )->withData( $data );
    try {
        $sendReport = $this->messaging->send( $message );
        $response[] = $sendReport;
    } catch ( MessagingException|FirebaseException $e ) {
        $response[] = $e;
    }
}

return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
</code>```

I want to send messages to all 10k devices but am unable to understand how to do it.

Title: How to fix time out issue in FCM?

Body:
I'm working on a laravel apis which is consumed by a mobile application. The issue is i am using this library ( https://github.com/kreait/firebase-php ) to send FCM to device Ids. I have 10k device ids in my db. Issue is the code is implemented badly and it gets timedout after 1 minute. I need advice what is the best way to overcome this issue?

I have written this code:

// General Notification
$deviceTokens = PushDevices::all()->pluck( 'device_id' )->toArray();
if ( $request->hasFile( 'file' ) || $request->file ) {
    try {
        $request->validate( [
            'image' => 'image|mimes:jpeg,jpg|max:2048|size:400'
        ] );
        $originName = $request->file( 'file' )->getClientOriginalName();
        $fileName   = pathinfo( $originName, PATHINFO_FILENAME );
        $extension  = $request->file( 'file' )->getClientOriginalExtension();
        $fileNames  = time() . '.' . $extension;
        $request->file( 'file' )->move( public_path( 'storage/notification' ), $fileNames );
        $notiData = [
            'title'    => $request->title,
            'body'     => $request->body,
            'imageurl' => $fileNames
        ];

        // Create a copy in database for notifications.
        NotificationTable::create( $notiData );
        // Initiate token with https
        $notification = [
            'title' => $validation->safe()->only( 'title' )['title'],
            'body'  => $validation->safe()->only( 'body' )['body'],
            'image' => 'https://example.com/storage/notification/' . $fileNames
        ];

        $data = [
            'first_key'  => 'First Value',
            'second_key' => 'Second Value',
        ];

        $response[] = '';
        foreach ( $deviceTokens as $object ) {
            // $message = CloudMessage::new()->withTarget('token', $object)->withNotification($notification);
            $message = CloudMessage::fromArray( [
                'token'        => $object,
                'notification' => $notification
            ] );
            try {
                $sendReport = $this->messaging->send( $message );
                $response[] = $sendReport;
            } catch ( \Throwable $e ) {
                $response[] = $e;
            }
        }

        return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
    } catch ( \Throwable $th ) {
    return response()->json( [
        'status'  => false,
        'message' => $th->getMessage()
    ], 500 );
}}

$batchSize = 1000;
$deviceGroups = array_chunk($deviceTokens, $batchSize);
$notification = ['title' => $validation->safe()->only( 'title' )['title'], 'body'  => $validation->safe()->only( 'body' )['body'],];
NotificationTable::create( $notification );
$data = ['first_key'  => 'First Value', 'second_key' => 'Second Value',];

$response = array();
foreach ( $deviceTokens as $object ) {
    $message = CloudMessage::new()->withTarget( 'token', $object )->withNotification( $notification )->withData( $data );
    try {
        $sendReport = $this->messaging->send( $message );
        $response[] = $sendReport;
    } catch ( MessagingException|FirebaseException $e ) {
        $response[] = $e;
    }
}

return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );

I want to send messages to all 10k devices but am unable to understand how to do it.


问:
Android Jetpack Compse TextField - R.string.default_error_message issue with Automation
Issue with below versions of compose

Jetpack Compose version: 1.0.0-beta09 and up

Jetpack Compose component used: TextField.kt, TextFieldImpl.kt, Strings.android.k

We have automation app which runs our client app for automation test cases. In automation app, compose library there is a string resource R.string.default_error_message.

Steps to Reproduce or Code Sample to Reproduce:

When automation apk runs, its going to look up the resource id default_error_message(0x7f0020003) into the client apk

In client apk this resource id is allocated to some other resource for instance array or color

Hence the app is crashing because of some other resource type.

Noted: Our automation app runs perfectly until the compose version 1.0.0-beta08 because default_error_message was not localised.

Crash log:


问:
How to fill in mediapipe landmarks using opengl es android
i have a landmarks for lips(i got from MediaPipe),

Currently, i created the triangle coordinated and then i tried triangle_strip, triangle_fan to fill the connected lines which i got from mediapipe.

is that approach is correct or is any other proper approach there to fill all the connected lines ?

I'm Using mediapipe SOlutions API example - Source Here -> https://github.com/google/mediapipe/blob/e0a254789a1ec05f3c09411b45a6c59d0ed3075e/mediapipe/examples/android/solutions/facemesh/src/main/java/com/google/mediapipe/examples/facemesh/FaceMeshResultGlRenderer.java#L154


问:
How to update the treeview serial number after deleting the items
I tried this code but when an item is deleted the serial no doesn't get updated. I want this program delete the data and update the serial number after deletion. I tried to initiate a variable but it gets updated to 1 every time I click add data button.

from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create an instance of Style widget
style = ttk.Style()
style.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("c1", "c2"), show='headings', height=8)
tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="ID")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="Company")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('1', 'Honda'))
tree.insert('', 'end', text="2", values=('2', 'Hyundai'))
tree.insert('', 'end', text="3", values=('3', 'Tesla'))
tree.insert('', 'end', text="4", values=('4', 'Wolkswagon'))
tree.insert('', 'end', text="5", values=('5', 'Tata Motors'))
tree.insert('', 'end', text="6", values=('6', 'Renault'))

tree.pack()

def edit():
   # Get selected item to Edit
   selected_item = tree.selection()[0]
   tree.item(selected_item, text="blub", values=("foo", "bar"))

def delete():
   # Get selected item to Delete
   selected_item = tree.selection()[0]
   tree.delete(selected_item)

# Add Buttons to Edit and Delete the Treeview items
edit_btn = ttk.Button(win, text="Edit", command=edit)
edit_btn.pack()
del_btn = ttk.Button(win, text="Delete", command=delete)
del_btn.pack()

win.mainloop()
```
<p>So I have tried this snippet:</p>
<pre class="lang-py prettyprint-override"><code>def delete_data():
    global i
    if tree.selection():
        selected_item = tree.selection()[0]
        tree.delete(selected_item)
        i=i-1
</code>```

Body:
I tried this code but when an item is deleted the serial no doesn't get updated. I want this program delete the data and update the serial number after deletion. I tried to initiate a variable but it gets updated to 1 every time I click add data button.

from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create an instance of Style widget
style = ttk.Style()
style.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("c1", "c2"), show='headings', height=8)
tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="ID")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="Company")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('1', 'Honda'))
tree.insert('', 'end', text="2", values=('2', 'Hyundai'))
tree.insert('', 'end', text="3", values=('3', 'Tesla'))
tree.insert('', 'end', text="4", values=('4', 'Wolkswagon'))
tree.insert('', 'end', text="5", values=('5', 'Tata Motors'))
tree.insert('', 'end', text="6", values=('6', 'Renault'))

tree.pack()

def edit():
   # Get selected item to Edit
   selected_item = tree.selection()[0]
   tree.item(selected_item, text="blub", values=("foo", "bar"))

def delete():
   # Get selected item to Delete
   selected_item = tree.selection()[0]
   tree.delete(selected_item)

# Add Buttons to Edit and Delete the Treeview items
edit_btn = ttk.Button(win, text="Edit", command=edit)
edit_btn.pack()
del_btn = ttk.Button(win, text="Delete", command=delete)
del_btn.pack()

win.mainloop()

So I have tried this snippet:

def delete_data():
    global i
    if tree.selection():
        selected_item = tree.selection()[0]
        tree.delete(selected_item)
        i=i-1


问:
How to condense an if statement containing many `or` operations?
I am building a small terminal game and there is a function gold_room and it's the win for the game. There is a line of code that I have to ensure that a number is typed... But it's really long. Here is the function:

```<code>def gold_room():
    print("This room is full of gold. How much do you take?")

    choice = input("> ")
    if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")
</code>```

I tried to use range() but I kept getting errors. I'm new to Python and coding in general, so it's an experience for sure. Any help would be great!

Body:
I am building a small terminal game and there is a function gold_room and it's the win for the game. There is a line of code that I have to ensure that a number is typed... But it's really long. Here is the function:

def gold_room():
    print("This room is full of gold. How much do you take?")

    choice = input("> ")
    if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")

I tried to use range() but I kept getting errors. I'm new to Python and coding in general, so it's an experience for sure. Any help would be great!


问:
Resource usage of kubelet when writing pod logs
Does letting the kubelet write logs that pods emit on their stdout / stderr consume more resources such as CPU and memory, than if the pods wrote their logs directly to a mounted volume? I am asking this considering that the logs are copied from the pod to the kubelet across processes. Or does the disk IO by N pods instead of one kubelet offset any advantage?

I recognize that not letting kubelet handle the logs means kubectl logs ... would not show recent logs. But otherwise, could there be performance advantage to not writing through an intermediary like kubelet?


问:
NASA Data is not loading
I am trying to load data from Nasa into R using;

```<code>metadata <- fromJSON("https://data.nasa.gov/data.json")
</code>```

The error that i am getting is:

```<code>Error in readBin(3L, raw(0), 32768L) : cannot read from connection
In addition: Warning message:
In readBin(3L, raw(0), 32768L) :
  URL 'https://data.nasa.gov/data.json': Timeout of 60 seconds was reached
</code>```

What do i do?

Title: NASA Data is not loading

Body:
I am trying to load data from Nasa into R using;

metadata <- fromJSON("https://data.nasa.gov/data.json")

The error that i am getting is:

Error in readBin(3L, raw(0), 32768L) : cannot read from connection
In addition: Warning message:
In readBin(3L, raw(0), 32768L) :
  URL 'https://data.nasa.gov/data.json': Timeout of 60 seconds was reached

What do i do?


问:
Tomcat axis2 multiple versions of a library that use for different web apps
I would like to ask about whether Tomcat able to have multiple versions of a library in WEB-INF/lib directory or not?
Because I read from Tomcat documentation.

WebappX — A class loader is created for each web application that is deployed in a single Tomcat instance. All unpacked classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application, are made visible to this web application, but not to other ones.

Eg. That multiple versions of a library called a-1.0.jar and a-2.0.jar that will be stored in WEB-INF/lib.

In WEB-INF/services, have myApp.arr and otherApp.arr.

myApp.arr will use a-1.0.jar only

otherApp.arr will use a-2.0.jar only

I had tried to put those libraries in WEB-INF/lib but it prompt errors NoSuchClassFound.


问:
Can’t open excel file on macos through dart
```<code>import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:excel/excel.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(ExcelFirebase());
}

class ExcelFirebase extends StatelessWidget {
  var bytes = File(      '/Users/krishuagarwal/Desktop/Programming/Flutter/Playground/excel_flutter_work/lib/data.xlsx').readAsBytesSync();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            child: Text("Creation"),
            onPressed: () {},
          ),
        ),
      ),
    );
  }
}

</code>```

I am not able to open the file on macos, i tried using the command chmod to grant permission and printing the file path to but it doesn't happen.
Please help me.

Body:
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:excel/excel.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(ExcelFirebase());
}

class ExcelFirebase extends StatelessWidget {
  var bytes = File(      '/Users/krishuagarwal/Desktop/Programming/Flutter/Playground/excel_flutter_work/lib/data.xlsx').readAsBytesSync();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            child: Text("Creation"),
            onPressed: () {},
          ),
        ),
      ),
    );
  }
}

I am not able to open the file on macos, i tried using the command chmod to grant permission and printing the file path to but it doesn't happen.
Please help me.


问:
MongoDB Rust driver: 'Files open leak' in my code somewhere
With each successive iteration the following block of code seems to spawn more and more files open so there has to be a leak of that kind somewhere.

#[tokio::main]
async fn main() {
    let safe_guard = Arc::new(RwLock::new(Vec::new()));
    loop {
        // Connect to the database
        let client = match Client::with_uri_str(mongo_connection_string).await {
            Ok(o) => o,
            Err(e) => {
                println!("{:?}", e); //the error spam happens here
                tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                continue;
            }
        };
        let db = client.database(main_db);

        //Setup Handles
        let handle1: Collection<MyStruct> = db.collection(collname1);
        let handle2: Collection<Document> = db.collection(collname2);
        let coll_a = db.collection(collection_a);

        let mut vec_b = vec![];
        let mut coll_b_ = match handle1.find(doc! {}, None).await {
            Ok(x) => x,
            Err(e) => {
                println!("{:?}", e);
                continue;
            }
        };
        while let Some(result) = coll_b_.next().await {
            let s = match result {
                Ok(x) => x,
                Err(e) => {
                    println!("{:?}", e);
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            vec_b.push(s)
        }

        let mut chats = HashMap::new();
        let mut messages = vec![];
        for s in &vec_b {
            messages.push(s.msg.clone().to_owned());
        }

        let filter = doc! {"msg": {"$in": messages}};
        let mut find_options = FindOptions::default();
        find_options.projection = Some(doc! {
            "msg":1,
            "chat":1
        });
        let mut cursor = match coll_a.find(filter, find_options).await {
            Ok(x) => x,
            Err(e) => {
                println!("ERR");
                tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                continue;
            }
        };
        while let Some(document) = cursor.next().await {
            let document: Document = match document {
                Ok(d) => d,
                Err(e) => {
                    println!("ERR2");
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            let user = match document.get("msg") {
                Some(x) => match x.as_str() {
                    Some(x) => x,
                    None => {
                        println!("ERR3");
                        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                        continue;
                    }
                },
                None => {
                    println!("ERR4");
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            let chat_id = match document.get("chat") {
                Some(x) => match x.as_str() {
                    Some(x) => x,
                    None => {
                        println!("ERR5");
                        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                        continue;
                    }
                },
                None => {
                    println!("ERR6");
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            //Insert to HM
            chats.insert(msg.to_owned(), chat.to_owned());
        }

        let coll_handle_handle2 = Arc::new(handle2);
        let coll_handle_handle1 = Arc::new(handle1);
        let handle_handles = Arc::new(chats);
        let handle_safe_guard = Arc::clone(&safe_guard);

        let mut thread_handles = Vec::new();

        //there was a block of code spawning tasks here and awaiting all
        //(if anyone wonders about the lack of logic here)
        //skipping it didn't help
    }
}
```
<p>Getting those errors, starting with: <code>ConnectionPoolCleared { message: "Connection pool for ... cleared because another operation failed with: Too many open files (os error 24)" }, labels: {"RetryableWriteError"}, wire_version: None, source: None }</code> and then a spam of: <code>Error { kind: DnsResolve { message: "io error: Too many open files (os error 24)" }, labels: {}, wire_version: None, source: None }</code></p>
<p>I've restarted and called <code>lsof</code> repeatedly with sorting and the process seems to be spawning more and more files until the limit is hit.</p>
<p>On MongoDB Compass charts for Mongo Performance this looks like a very steady leak, nothing subsides there, rising slowly to the top even if those operations are empty and there are never more than a few objects in those custom vectors, cursors or structs/HMs.</p>
<p>I'm a bit surprised it spawns that many files open (~1024+ in a span of a minute or so).
And why the iteration going to the next one doesn't drop all the active connections? I don't know what the issue is, I've re-read this a million times focusing on everything that could leave a connection open, tried <code>drop()</code> and the like, nothing helps. I do not see any bugs there or I have no clue what this error means.</p>
<p>Edit: "minimal reproducible example". It behaves a bit differently, approaching and crossing the limit, then dissipating below it. The previous never goes below the limit.</p>
```
#[tokio::main]
async fn main() {
    let safe_guard:Arc<RwLock<Vec<String>>> = Arc::new(RwLock::new(Vec::new()));

loop{
    // Connect to the database
    let client = match Client::with_uri_str(mongo_connection_string).await{
        Ok(o)=>o,
        Err(e)=>{
            println!("{:?}",e);
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            continue
        }
    };
    let db = client.database(main_db);

    let handle_safe_guard = Arc::clone(&safe_guard);

}
}
```

Even though the code was reduced by +90% I am even more clueless as to why this occurs. I thought this should keep the connections at all times at 1 maximum in theory and it is approaching 1100, dissipating to around 700, then going up again to cross the limit (this repeats).

Body:
With each successive iteration the following block of code seems to spawn more and more files open so there has to be a leak of that kind somewhere.

#[tokio::main]
async fn main() {
    let safe_guard = Arc::new(RwLock::new(Vec::new()));
    loop {
        // Connect to the database
        let client = match Client::with_uri_str(mongo_connection_string).await {
            Ok(o) => o,
            Err(e) => {
                println!("{:?}", e); //the error spam happens here
                tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                continue;
            }
        };
        let db = client.database(main_db);

        //Setup Handles
        let handle1: Collection<MyStruct> = db.collection(collname1);
        let handle2: Collection<Document> = db.collection(collname2);
        let coll_a = db.collection(collection_a);

        let mut vec_b = vec![];
        let mut coll_b_ = match handle1.find(doc! {}, None).await {
            Ok(x) => x,
            Err(e) => {
                println!("{:?}", e);
                continue;
            }
        };
        while let Some(result) = coll_b_.next().await {
            let s = match result {
                Ok(x) => x,
                Err(e) => {
                    println!("{:?}", e);
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            vec_b.push(s)
        }

        let mut chats = HashMap::new();
        let mut messages = vec![];
        for s in &vec_b {
            messages.push(s.msg.clone().to_owned());
        }

        let filter = doc! {"msg": {"$in": messages}};
        let mut find_options = FindOptions::default();
        find_options.projection = Some(doc! {
            "msg":1,
            "chat":1
        });
        let mut cursor = match coll_a.find(filter, find_options).await {
            Ok(x) => x,
            Err(e) => {
                println!("ERR");
                tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                continue;
            }
        };
        while let Some(document) = cursor.next().await {
            let document: Document = match document {
                Ok(d) => d,
                Err(e) => {
                    println!("ERR2");
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            let user = match document.get("msg") {
                Some(x) => match x.as_str() {
                    Some(x) => x,
                    None => {
                        println!("ERR3");
                        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                        continue;
                    }
                },
                None => {
                    println!("ERR4");
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            let chat_id = match document.get("chat") {
                Some(x) => match x.as_str() {
                    Some(x) => x,
                    None => {
                        println!("ERR5");
                        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                        continue;
                    }
                },
                None => {
                    println!("ERR6");
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            };
            //Insert to HM
            chats.insert(msg.to_owned(), chat.to_owned());
        }

        let coll_handle_handle2 = Arc::new(handle2);
        let coll_handle_handle1 = Arc::new(handle1);
        let handle_handles = Arc::new(chats);
        let handle_safe_guard = Arc::clone(&safe_guard);

        let mut thread_handles = Vec::new();

        //there was a block of code spawning tasks here and awaiting all
        //(if anyone wonders about the lack of logic here)
        //skipping it didn't help
    }
}

Getting those errors, starting with: ConnectionPoolCleared { message: "Connection pool for ... cleared because another operation failed with: Too many open files (os error 24)" }, labels: {"RetryableWriteError"}, wire_version: None, source: None } and then a spam of: Error { kind: DnsResolve { message: "io error: Too many open files (os error 24)" }, labels: {}, wire_version: None, source: None }

I've restarted and called lsof repeatedly with sorting and the process seems to be spawning more and more files until the limit is hit.

On MongoDB Compass charts for Mongo Performance this looks like a very steady leak, nothing subsides there, rising slowly to the top even if those operations are empty and there are never more than a few objects in those custom vectors, cursors or structs/HMs.

I'm a bit surprised it spawns that many files open (~1024+ in a span of a minute or so).
And why the iteration going to the next one doesn't drop all the active connections? I don't know what the issue is, I've re-read this a million times focusing on everything that could leave a connection open, tried drop() and the like, nothing helps. I do not see any bugs there or I have no clue what this error means.

Edit: "minimal reproducible example". It behaves a bit differently, approaching and crossing the limit, then dissipating below it. The previous never goes below the limit.

#[tokio::main]
async fn main() {
    let safe_guard:Arc<RwLock<Vec<String>>> = Arc::new(RwLock::new(Vec::new()));

loop{
    // Connect to the database
    let client = match Client::with_uri_str(mongo_connection_string).await{
        Ok(o)=>o,
        Err(e)=>{
            println!("{:?}",e);
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            continue
        }
    };
    let db = client.database(main_db);

    let handle_safe_guard = Arc::clone(&safe_guard);

}
}

Even though the code was reduced by +90% I am even more clueless as to why this occurs. I thought this should keep the connections at all times at 1 maximum in theory and it is approaching 1100, dissipating to around 700, then going up again to cross the limit (this repeats).


问:
how to change the type | to & in typescript?

type DataStore = {
    [K in pageName]:  {
        page: K
        data: A[K] extends { roleId: string }[] ? A[K] : never
    }
}[keyof A]

interface A extends Record<pageName, unknown> {
    [pageName.q]: DataA[]
    [pageName.w]: DataB[]
}

enum pageName {
    q = '1',
    w = '2',
    e = '3',
    //...
}

interface DataA { roleId: string, name:string }
interface DataB { roleId: string, age: string }
```
<pre class="lang-js prettyprint-override"><code>let info: Record<number, DataA> | Record<number, DataB>; // 请求发过来的数据

(Object.entries(info) as unknown as [string, DataStore['data'][number]][])
    .map(([page, data]) => {
        // here the Type derivation of data is DataA | DataB
        // but in my hope it should be DataA & DataB
    })
</code>```

I plan to handle it uniformly in map, but the current derived type allows me to only get the value data.roleId, and the other values are checked by the type. How can I modify it so that I can use data. to bring out other properties?

Body:
type DataStore = {
    [K in pageName]:  {
        page: K
        data: A[K] extends { roleId: string }[] ? A[K] : never
    }
}[keyof A]

interface A extends Record<pageName, unknown> {
    [pageName.q]: DataA[]
    [pageName.w]: DataB[]
}

enum pageName {
    q = '1',
    w = '2',
    e = '3',
    //...
}

interface DataA { roleId: string, name:string }
interface DataB { roleId: string, age: string }

let info: Record<number, DataA> | Record<number, DataB>; // 请求发过来的数据

(Object.entries(info) as unknown as [string, DataStore['data'][number]][])
    .map(([page, data]) => {
        // here the Type derivation of data is DataA | DataB
        // but in my hope it should be DataA & DataB
    })

I plan to handle it uniformly in map, but the current derived type allows me to only get the value data.roleId, and the other values are checked by the type. How can I modify it so that I can use data. to bring out other properties?


问:
NextJS13 — How can I use a custom hook in a server component?
The goal for me is to retrieve some data from the server component then use a hook to store that data into local storage. I made a custom hook called useSettings that stores the data into local storage after the server component Pages gets the data from setSettings function.

```<code>export default async function Pages({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const headersList = headers();
  const settings = await setSettings({ host: headersList.get('host') });

  const clientSettings = useSettings()

  return <div className="text-lg font-bold">HELLO WORLD</div>;
}
</code>```

When I try the above, I get this error:

```<code>_shared_hooks_useSettings__WEBPACK_IMPORTED_MODULE_3___default(...) is not a function
</code>```

This is what my useSettings hook component looks like:

```<code>'use client';

export default function useSettings() {
    console.log(window.location)
    console.log("HELLO")

    return <div className=""></div>
}
</code>```

I understand this error is coming from the fact that the Page server component is reading useSettings() as a server function, but since useSettings is a client component, there is no way the Page component would find it.

Is there a way to embed a working custom client hook component inside of a server component?

EDIT:
This is a working work-around. Since anything inside the return statement eventually spits it out on the client side, this works. But it's ugly and I'm sure there is a better way

```<code>export default async function Pages({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const headersList = headers();
  const settings = await setSettings({ host: headersList.get('host') });

  return (
    <div className="text-lg font-bold">
      HELLO WORLD
      <div className="hidden">
        <UseSettings settings={settings} />
      </div>
    </div>
  );
}
</code>```

Body:
The goal for me is to retrieve some data from the server component then use a hook to store that data into local storage. I made a custom hook called useSettings that stores the data into local storage after the server component Pages gets the data from setSettings function.

export default async function Pages({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const headersList = headers();
  const settings = await setSettings({ host: headersList.get('host') });

  const clientSettings = useSettings()

  return
HELLO WORLD
;
}

When I try the above, I get this error:

_shared_hooks_useSettings__WEBPACK_IMPORTED_MODULE_3___default(...) is not a function

This is what my useSettings hook component looks like:

'use client';

export default function useSettings() {
    console.log(window.location)
    console.log("HELLO")

    return

}

I understand this error is coming from the fact that the Page server component is reading useSettings() as a server function, but since useSettings is a client component, there is no way the Page component would find it.

Is there a way to embed a working custom client hook component inside of a server component?

EDIT:
This is a working work-around. Since anything inside the return statement eventually spits it out on the client side, this works. But it's ugly and I'm sure there is a better way

export default async function Pages({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const headersList = headers();
  const settings = await setSettings({ host: headersList.get('host') });

  return (

      HELLO WORLD

        <UseSettings settings={settings} />

  );
}


问:
Is it advisable to run Couchbase with 'EFS Elastic Throughput' instead of EBS?
We run Couchbase in Kubernetes platform in AWS cloud. As per the 'Couchbase on AWS' best practices, it is suggested to use EBS 'gp3' or EBS 'io1' based on the following link. (https://docs.couchbase.com/server/current/cloud/couchbase-cloud-deployment.html#aws-deployment-methods)

But it seems AWS has introduced a new EFS storage type, known as, "Amazon EFS Elastic Throughput" (https://aws.amazon.com/blogs/aws/new-announcing-amazon-efs-elastic-throughput/). It gives much better throughput. Is it suggested to use EFS with Elastic Throughput for Couchbase storage?

Throughput claimed by AWS: Elastic Throughput allows you to drive throughput up to a limit of 3 GiB/s for read operations and 1 GiB/s for write operations per file system in all Regions.


问:
ModuleNotFoundException: No module named utils
In our Airflow dags project, we have created a package called utils. In this package, we have created many Python files.

Recently I created a new file called github_util.py where I have written some code to interact with GitHub APIs.

There is another Python file called mail_forms.py in the utils folder.

I am importing github_util.py in mail_forms.py using

```<code>from utils.github_util import task_failed_github_issue
</code>```

The content of github_util.py is

```<code>def task_failed_github_issue(context):
    print("only function")
</code>```

In utils package, we have an empty init.py file.

When I deploy this code in Airflow, I am getting below error:

```<code>ModuleNotFoundException: No module names 'utils'.
</code>```

We have files called backend_util.py and entity_util in the same folder 'utils'. entity_util is also imported into backend file as below:

```<code>from utils.entity_util import read_definitions
</code>```

This import is working correctly. I am not able to understand why this import works and mine does not.

I referred to many links on Stack Overflow and other websites, but none of the solution worked for me.

Body:
In our Airflow dags project, we have created a package called utils. In this package, we have created many Python files.

Recently I created a new file called github_util.py where I have written some code to interact with GitHub APIs.

There is another Python file called mail_forms.py in the utils folder.

I am importing github_util.py in mail_forms.py using

from utils.github_util import task_failed_github_issue

The content of github_util.py is

def task_failed_github_issue(context):
    print("only function")

In utils package, we have an empty init.py file.

When I deploy this code in Airflow, I am getting below error:

ModuleNotFoundException: No module names 'utils'.

We have files called backend_util.py and entity_util in the same folder 'utils'. entity_util is also imported into backend file as below:

from utils.entity_util import read_definitions

This import is working correctly. I am not able to understand why this import works and mine does not.

I referred to many links on Stack Overflow and other websites, but none of the solution worked for me.


问:
Flutter State not getting updated
i am trying to  comment section in social media app in android,the issue is after making the post comment ,the newly added comment is not showing in real time,the state is not getting updated , i tried to check the order of function calls by making print data in  console,
console log</p>
```<code>I/flutter ( 2069): comment posted succesfully
10
I/flutter ( 2069): getcomments
I/flutter ( 2069): setstate called
</code>```
```<code>             )),
              GestureDetector(
                  onTap: () async {
                    await CommentService().postComment(
                        commentText: controller.text, postid: widget.postid);
                 await     CommentService().getCommentsdata(post_id: widget.postid);

                    setState(() {
                      controller.clear();
                      print('setstate called');

                    });
                  },
</code>```

Title: Flutter State not getting updated

Body:
i am trying to  comment section in social media app in android,the issue is after making the post comment ,the newly added comment is not showing in real time,the state is not getting updated , i tried to check the order of function calls by making print data in  console,
console log

I/flutter ( 2069): comment posted succesfully
10
I/flutter ( 2069): getcomments
I/flutter ( 2069): setstate called

             )),
              GestureDetector(
                  onTap: () async {
                    await CommentService().postComment(
                        commentText: controller.text, postid: widget.postid);
                 await     CommentService().getCommentsdata(post_id: widget.postid);

                    setState(() {
                      controller.clear();
                      print('setstate called');

                    });
                  },


问:
Is there a way to decode SEI picture timing field metadata in the H264 bitstream on iOS(Swift)?
I want to get the timecode that are encoded in the SEI picture timing fields in the H264 bitstream. I am able to pull these out using ffprobe with this command. ffprobe -i video-url -show_entries timecode.Can I get the same on iOS ? Is there a way to do that?

I tried searching for different solution haven't found any. This is the per frame metadata so usual metadata decoding doesn't work .I tried the AVPlayerItemMetadataOutputPushDelegate was not working.


问:
ImportError: cannot import name 'log' from 'webdriver_manager.logger
I have a question, when I running my selenium code in PyCharm, I receive this message error :

ImportError: cannot import name 'log' from 'webdriver_manager.logger' (C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\webdriver_manager\logger.py)[text](https://www.stackoverflow.com/)

what's the problem in System configuration?

I trying to solve it, but I don't find problem