问:
How to clear the DrawPie behind?
In the [art draw HAND i want to clear the DrawPie behind because then it will fill it will draw over and over it. i tried with the Black color but that just make the pie to be drawn like transparent(ghost).

Not sure how to work with the bmp.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace My_DrawPie
{
    public partial class Form1 : Form
    {
        Timer t = new Timer();

        int WIDTH = 300, HEIGHT = 300, HAND = 150;

        int u;  //in degree
        int cx, cy;     //center of the circle
        int x, y;       //HAND coordinate

        int tx, ty, lim = 20;

        Bitmap bmp;
        Pen p;
        Graphics g;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //create Bitmap
            bmp = new Bitmap(WIDTH + 1, HEIGHT + 1);

            //background color
            this.BackColor = Color.Black;

            //center
            cx = WIDTH / 2;
            cy = HEIGHT / 2;

            //initial degree of HAND
            u = 0;

            //timer
            t.Interval = 5; //in millisecond
            t.Tick += new EventHandler(this.t_Tick);
            t.Start();
        }

        private void t_Tick(object sender, EventArgs e)
        {
            //pen
            p = new Pen(Color.Green, 1f);

            //graphics
            g = Graphics.FromImage(bmp);

            //calculate x, y coordinate of HAND
            int tu = (u - lim) % 360;

            if (u >= 0 && u <= 180)
            {
                //right half
                //u in degree is converted into radian.

                x = cx + (int)(HAND * Math.Sin(Math.PI * u / 180));
                y = cy - (int)(HAND * Math.Cos(Math.PI * u / 180));
            }
            else
            {
                x = cx - (int)(HAND * -Math.Sin(Math.PI * u / 180));
                y = cy - (int)(HAND * Math.Cos(Math.PI * u / 180));
            }

            if (tu >= 0 && tu <= 180)
            {
                //right half
                //tu in degree is converted into radian.

                tx = cx + (int)(HAND * Math.Sin(Math.PI * tu / 180));
                ty = cy - (int)(HAND * Math.Cos(Math.PI * tu / 180));
            }
            else
            {
                tx = cx - (int)(HAND * -Math.Sin(Math.PI * tu / 180));
                ty = cy - (int)(HAND * Math.Cos(Math.PI * tu / 180));
            }

            //draw circle
            g.DrawEllipse(p, 0, 0, WIDTH, HEIGHT);  //bigger circle
            g.DrawEllipse(p, 80, 80, WIDTH - 160, HEIGHT - 160);    //smaller circle

            //draw perpendicular line
            g.DrawLine(p, new Point(cx, 0), new Point(cx, HEIGHT)); // UP-DOWN
            g.DrawLine(p, new Point(0, cy), new Point(WIDTH, cy)); //LEFT-RIGHT

            //draw HAND
            g.DrawPie(p, new Rectangle(cx, cy, 100, 100), tx, ty);
            g.DrawPie(new Pen(Color.Black, 1f), new Rectangle(cx, cy,
            100, 100), tx, ty);
            //load bitmap in picturebox1
            pictureBox1.Image = bmp;

            //dispose
            p.Dispose();
            g.Dispose();

            //update
            u++;
            if (u == 360)
            {
                u = 0;
            }
        }
    }
}
</code>```

i tried with the Black color but that just make the pie to be drawn like transparent(ghost).

```<code>g.DrawPie(new Pen(Color.Black, 1f), new Rectangle(cx, cy, 100, 100), tx, ty);
</code>```

Title: How to clear the DrawPie behind?

Body:
In the [art draw HAND i want to clear the DrawPie behind because then it will fill it will draw over and over it. i tried with the Black color but that just make the pie to be drawn like transparent(ghost).

Not sure how to work with the bmp.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace My_DrawPie
{
    public partial class Form1 : Form
    {
        Timer t = new Timer();

        int WIDTH = 300, HEIGHT = 300, HAND = 150;

        int u;  //in degree
        int cx, cy;     //center of the circle
        int x, y;       //HAND coordinate

        int tx, ty, lim = 20;

        Bitmap bmp;
        Pen p;
        Graphics g;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //create Bitmap
            bmp = new Bitmap(WIDTH + 1, HEIGHT + 1);

            //background color
            this.BackColor = Color.Black;

            //center
            cx = WIDTH / 2;
            cy = HEIGHT / 2;

            //initial degree of HAND
            u = 0;

            //timer
            t.Interval = 5; //in millisecond
            t.Tick += new EventHandler(this.t_Tick);
            t.Start();
        }

        private void t_Tick(object sender, EventArgs e)
        {
            //pen
            p = new Pen(Color.Green, 1f);

            //graphics
            g = Graphics.FromImage(bmp);

            //calculate x, y coordinate of HAND
            int tu = (u - lim) % 360;

            if (u >= 0 && u <= 180)
            {
                //right half
                //u in degree is converted into radian.

                x = cx + (int)(HAND * Math.Sin(Math.PI * u / 180));
                y = cy - (int)(HAND * Math.Cos(Math.PI * u / 180));
            }
            else
            {
                x = cx - (int)(HAND * -Math.Sin(Math.PI * u / 180));
                y = cy - (int)(HAND * Math.Cos(Math.PI * u / 180));
            }

            if (tu >= 0 && tu <= 180)
            {
                //right half
                //tu in degree is converted into radian.

                tx = cx + (int)(HAND * Math.Sin(Math.PI * tu / 180));
                ty = cy - (int)(HAND * Math.Cos(Math.PI * tu / 180));
            }
            else
            {
                tx = cx - (int)(HAND * -Math.Sin(Math.PI * tu / 180));
                ty = cy - (int)(HAND * Math.Cos(Math.PI * tu / 180));
            }

            //draw circle
            g.DrawEllipse(p, 0, 0, WIDTH, HEIGHT);  //bigger circle
            g.DrawEllipse(p, 80, 80, WIDTH - 160, HEIGHT - 160);    //smaller circle

            //draw perpendicular line
            g.DrawLine(p, new Point(cx, 0), new Point(cx, HEIGHT)); // UP-DOWN
            g.DrawLine(p, new Point(0, cy), new Point(WIDTH, cy)); //LEFT-RIGHT

            //draw HAND
            g.DrawPie(p, new Rectangle(cx, cy, 100, 100), tx, ty);
            g.DrawPie(new Pen(Color.Black, 1f), new Rectangle(cx, cy,
            100, 100), tx, ty);
            //load bitmap in picturebox1
            pictureBox1.Image = bmp;

            //dispose
            p.Dispose();
            g.Dispose();

            //update
            u++;
            if (u == 360)
            {
                u = 0;
            }
        }
    }
}

i tried with the Black color but that just make the pie to be drawn like transparent(ghost).

g.DrawPie(new Pen(Color.Black, 1f), new Rectangle(cx, cy, 100, 100), tx, ty);


来源: stackexchange

问:
Should data in in json file 'structured using li tags?
```<code>[
  {
    "model": "db.service",
    "pk": 1,
    "fields": {
      "catagory_name": "New host",
      "service_name": "<ul><li>Trip planning</li><li>Host shop</li></ul>"
    }
  },
  {
    "model": "db.service",
    "pk": 2,
    "fields": {
      "catagory_name": "TOURING HOSTS",
      "service_name": "Tour of location"
    }
</code>```

and it has another 5 written like the second activity. This is shown on the front end as a drop down of the activities (service_name). However the tech lead wants me to show trip planning as a bulleted activity, like this

Trip Planning

Host Shop

All as one selection.

In the front end code, the previous intern has used regex to seek the li and ul tags and replace them with || for some reason. He wants me to get rod of those which is easy enough, but I was wondering if I should keep the code to seek the tags and somehow make them into bullet points.

I have tried replacing the || with & but get &&, I then try replacing && with & but that doesn't work and there are still || in the code, so I tried replaceAll. However this still doesn't get me bullet points. Front end is react. I tried putting the code in brackets with li tags and that didn't work neither.

code listing the activities in the drop down

```<code> {pricing &&
                  targetValue &&
                  pricing.map((service, index) => {
                    if (targetValue === service.service_info.service_name) {
                      return service.service_info.service_name.includes(
                        "<li>"
                      ) ? (
                        <Grid item className={classes.headlineText}>

                          {handleServiceName(service.service_info.service_name)}
                        </Grid>
                      ) : (
                        <Grid item className={classes.headlineText}>
                          {service.service_info.service_name}
                        </Grid>
                      );
                    }
                  })}
              </Grid>
</code>```

Code handling regex

```<code>    const regex = /<[^>]+>/g;
    const split_string = string;
    const new_str = string.replace(regex, " | ");
    return new_str;
  };```
```

ContentLicense: CC BY-SA 4.0

Body:
[
  {
    "model": "db.service",
    "pk": 1,
    "fields": {
      "catagory_name": "New host",
      "service_name": "

Trip planning

Host shop

"
    }
  },
  {
    "model": "db.service",
    "pk": 2,
    "fields": {
      "catagory_name": "TOURING HOSTS",
      "service_name": "Tour of location"
    }

and it has another 5 written like the second activity. This is shown on the front end as a drop down of the activities (service_name). However the tech lead wants me to show trip planning as a bulleted activity, like this

Trip Planning

Host Shop

All as one selection.

In the front end code, the previous intern has used regex to seek the li and ul tags and replace them with || for some reason. He wants me to get rod of those which is easy enough, but I was wondering if I should keep the code to seek the tags and somehow make them into bullet points.

I have tried replacing the || with & but get &&, I then try replacing && with & but that doesn't work and there are still || in the code, so I tried replaceAll. However this still doesn't get me bullet points. Front end is react. I tried putting the code in brackets with li tags and that didn't work neither.

code listing the activities in the drop down

 {pricing &&
                  targetValue &&
                  pricing.map((service, index) => {
                    if (targetValue === service.service_info.service_name) {
                      return service.service_info.service_name.includes(
                        "
"
                      ) ? (
                        <Grid item className={classes.headlineText}>

                          {handleServiceName(service.service_info.service_name)}
                        </Grid>
                      ) : (
                        <Grid item className={classes.headlineText}>
                          {service.service_info.service_name}
                        </Grid>
                      );
                    }
                  })}
              </Grid>

Code handling regex

    const regex = /<[^>]+>/g;
    const split_string = string;
    const new_str = string.replace(regex, " | ");
    return new_str;
  };```


问:
Initializing array in assembly
I'm working on a project for an assembly class, and I'm having trouble figuring out why my code is seg faulting. I'm trying to initialize an array with 10 strings and later call a function in C to display each string in the array. I know it runs through the loop, r8 goes from 0 to 10, but I don't know if works correctly. Also, when I comment out the line calling the C function, the code doesn't fault. I'm not sure if the problem is with initializing the array or with the C function, and any help would be appreciated.

Here's where I try to initialize the array with msg, which is a string that says "This is the original message."

```<code>init:
        mov     r9, msg
        mov     [arr+r8], r9
        add     r8, 1

        cmp     r8, 10
        jl      init

</code>```

Calling the C function:

```<code>s:
        mov     rdi, arr
        call    display

</code>```

The C function, which should print out each message in the array.

```<code>#include <stdio.h>

void display (char *arr[]) {

        printf ("help");
        for (int i=0; i<10; ++i)
                printf (" Message [%d]: %s", i, *arr[i]);

}

</code>```

Title: Initializing array in assembly

Body:
I'm working on a project for an assembly class, and I'm having trouble figuring out why my code is seg faulting. I'm trying to initialize an array with 10 strings and later call a function in C to display each string in the array. I know it runs through the loop, r8 goes from 0 to 10, but I don't know if works correctly. Also, when I comment out the line calling the C function, the code doesn't fault. I'm not sure if the problem is with initializing the array or with the C function, and any help would be appreciated.

Here's where I try to initialize the array with msg, which is a string that says "This is the original message."

init:
        mov     r9, msg
        mov     [arr+r8], r9
        add     r8, 1

        cmp     r8, 10
        jl      init

Calling the C function:

s:
        mov     rdi, arr
        call    display

The C function, which should print out each message in the array.

#include <stdio.h>

void display (char *arr[]) {

        printf ("help");
        for (int i=0; i<10; ++i)
                printf (" Message [%d]: %s", i, *arr[i]);

}


问:
Python write() Unexpected Behaviour, Writing \u0 Character in Place of Text
I have written some code in Python that converts an excel file (.xlsx) to a text file, then splits it into test and train text files, and finally assorts them into positive and negative directories based on their classification.

First I convert the .xlsx file to a text file:

```<code># xlsx to txt
with open('data.txt', 'w', encoding='utf-8') as file:
  pd.read_excel('data.xlsx').to_string(file, index=False)
</code>```

This appears to work fine, data.txt contains the expected output.

I then calculate the line at which the data should be split into testing and training data:

```<code># split training and test
with open('data.txt', encoding='utf-8') as d:
    num = sum(1 for line in d)

trainsplit = m.ceil((num / 10) * 8)
testsplit = m.floor((num / 10) * 2)
</code>```

This also functions as expected.

Finally I attempt to write the relevant lines to their intended files:

```<code>with open('data.txt', encoding='utf-8') as f:
    for lineno, line in enumerate(f):
        if lineno % testsplit == 0:
            testf = open('test.txt', 'w', encoding='utf-8')
        if lineno % trainsplit == 0:
            trainf = open('train.txt', 'w', encoding='utf-8')
        testf.write(line)
        trainf.write(line)
</code>```

This is where the errors start.

data.txt contains 162 total lines, so train.txt should contain 130, and test.txt 32, however; test.txt contains 17 lines containing text, and is padded by 8 lines of spaces above (which register as \u0 when I open the text file in a Jupyter notebook), and one new line character below. The first line containing text is an incomplete line from data.txt and is padded by an array of spaces after the line.

train.txt contains 74 lines, 19 of which contain text. The file is padded by 55 lines of spaces above, and I'm having the same issue with the first line of the file that contains text.

I've tried printing lineno whenever
lineno % trainsplit == 0:
and receive the output

```<code>0
0
32
64
96
128
130
160
</code>```

This should only be occurring once per file, as both testsplit and trainsplit are static values. Not sure why this is printing multiple times and I assume this is the root of the problem.`

Body:
I have written some code in Python that converts an excel file (.xlsx) to a text file, then splits it into test and train text files, and finally assorts them into positive and negative directories based on their classification.

First I convert the .xlsx file to a text file:

# xlsx to txt
with open('data.txt', 'w', encoding='utf-8') as file:
  pd.read_excel('data.xlsx').to_string(file, index=False)

This appears to work fine, data.txt contains the expected output.

I then calculate the line at which the data should be split into testing and training data:

# split training and test
with open('data.txt', encoding='utf-8') as d:
    num = sum(1 for line in d)

trainsplit = m.ceil((num / 10) * 8)
testsplit = m.floor((num / 10) * 2)

This also functions as expected.

Finally I attempt to write the relevant lines to their intended files:

with open('data.txt', encoding='utf-8') as f:
    for lineno, line in enumerate(f):
        if lineno % testsplit == 0:
            testf = open('test.txt', 'w', encoding='utf-8')
        if lineno % trainsplit == 0:
            trainf = open('train.txt', 'w', encoding='utf-8')
        testf.write(line)
        trainf.write(line)

This is where the errors start.

data.txt contains 162 total lines, so train.txt should contain 130, and test.txt 32, however; test.txt contains 17 lines containing text, and is padded by 8 lines of spaces above (which register as \u0 when I open the text file in a Jupyter notebook), and one new line character below. The first line containing text is an incomplete line from data.txt and is padded by an array of spaces after the line.

train.txt contains 74 lines, 19 of which contain text. The file is padded by 55 lines of spaces above, and I'm having the same issue with the first line of the file that contains text.

I've tried printing lineno whenever
lineno % trainsplit == 0:
and receive the output

0
0
32
64
96
128
130
160

This should only be occurring once per file, as both testsplit and trainsplit are static values. Not sure why this is printing multiple times and I assume this is the root of the problem.`


问:
@patch.multiple for inner class in mock python
I'm trying to patch an inner class in a more permanent fashion.

I have a class as

```<code>class OuterClass:
   def _init__(self, s, b):
      self._b = b
      self._inner = InnerClass(s)
</code>```

I have to create a mock instance of the OuterClass and add it to a collection so I tried

```<code>class MockOuter(OuterClass):

   @patch.multiple(
       InnerClass,
       __init__=MagicMock(side_effect=mock_init),

   )
   def __init__(self, *args, **kwargs):
      super().__init__(s='MockS', b='MockB')
</code>```

so ideally to do

```<code>   a = MockOuter()
   col.append(a)
</code>```

But once you are out of the init, you lose the patch. Clearly this isn't the right approach, what's the best approach here?

Body:
I'm trying to patch an inner class in a more permanent fashion.

I have a class as

class OuterClass:
   def _init__(self, s, b):
      self._b = b
      self._inner = InnerClass(s)

I have to create a mock instance of the OuterClass and add it to a collection so I tried

class MockOuter(OuterClass):

   @patch.multiple(
       InnerClass,
       __init__=MagicMock(side_effect=mock_init),

   )
   def __init__(self, *args, **kwargs):
      super().__init__(s='MockS', b='MockB')

so ideally to do

   a = MockOuter()
   col.append(a)

But once you are out of the init, you lose the patch. Clearly this isn't the right approach, what's the best approach here?


问:
Importing not working from different folder failing but I am not receiving an error
I am working on a python program that had worked previously, but since upgrading to python 3.11, one of my imports is no longer working.

```<code>from Signer.engine.pdf.PyPDF2_annotate.annotations.signature import Signature
</code>```

The statement is importing from a folder in the file structure, but no error occurs when attempting this line of code, the program quits there instead without doing the necessary function. I have traced through the code with print statements and found that the failure occurs here. I am not using an IDE, just running the code from the command line and using sublime to edit it, so there is no clear error being produced.

The file importing is called CodeSigning.py. Below is the file structure

```<code>CodeSignClientTool
-CodeSigning.py
-Signer
--engine
---pdf
----PyPDF2_annotate
-----annotations
------signature.py
</code>```

Body:
I am working on a python program that had worked previously, but since upgrading to python 3.11, one of my imports is no longer working.

from Signer.engine.pdf.PyPDF2_annotate.annotations.signature import Signature

The statement is importing from a folder in the file structure, but no error occurs when attempting this line of code, the program quits there instead without doing the necessary function. I have traced through the code with print statements and found that the failure occurs here. I am not using an IDE, just running the code from the command line and using sublime to edit it, so there is no clear error being produced.

The file importing is called CodeSigning.py. Below is the file structure

CodeSignClientTool
-CodeSigning.py
-Signer
--engine
---pdf
----PyPDF2_annotate
-----annotations
------signature.py


问:
getting balance from a ganache node via node
I am trying to instantiate a ganache node and get its eth balance, following a lesson on udemy.

What I should get is the eth balance of the connected node.  What I get is the below:

```<code>> let Web3 = require('web3');
undefined
> let web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
undefined
> web3.eth.getBalance("0xe19C5f3eB5e4d62cc02BD435C1ad4Ed3d68942eA").then(console.log);
Promise {
  <pending>,
  [Symbol(async_id_symbol)]: 702,
  [Symbol(trigger_async_id_symbol)]: 674
}
> (node:15825) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Uncaught Error: CONNECTION ERROR: Couldn't connect to node http://localhost:7545.
    at Object.ConnectionError (/Users/kio777/node_modules/web3-core-helpers/lib/errors.js:66:23)
    at Object.InvalidConnection (/Users/kio777/node_modules/web3-core-helpers/lib/errors.js:36:21)
    at HttpProvider.failed (/Users/kio777/node_modules/web3-providers-http/lib/index.js:136:25)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

</code>```

I've tried to restart the terminal, and then trying to reinstall npm / node give me a bunch of other errors related to permissions.

Given the problem with connecting to localhost at port 7545, I checked port activity and got the following result:

```<code>COMMAND   PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
Ganache   904 kio777   28u  IPv4 0x181ce30a7bcda339      0t0  TCP localhost:49359->localhost:nta-us (ESTABLISHED)
Ganache   904 kio777   29u  IPv4 0x181ce30a7bcc9829      0t0  TCP localhost:49361->localhost:nta-us (ESTABLISHED)
Ganache   915 kio777   39u  IPv4 0x181ce30a7aeab959      0t0  TCP localhost:49358->localhost:nta-us (ESTABLISHED)
Ganache   915 kio777   47u  IPv4 0x181ce30a7bcd4f79      0t0  TCP localhost:49360->localhost:nta-us (ESTABLISHED)
Ganache   916 kio777   39u  IPv4 0x181ce30a7bccb959      0t0  TCP localhost:nta-us (LISTEN)
Ganache   916 kio777   47u  IPv4 0x181ce30a7bcd5a89      0t0  TCP localhost:nta-us->localhost:49358 (ESTABLISHED)
Ganache   916 kio777   48u  IPv4 0x181ce30a7bcd4469      0t0  TCP localhost:nta-us->localhost:49359 (ESTABLISHED)
Ganache   916 kio777   49u  IPv4 0x181ce30a7bcc8209      0t0  TCP localhost:nta-us->localhost:49360 (ESTABLISHED)
Ganache   916 kio777   50u  IPv4 0x181ce30a7ae97959      0t0  TCP localhost:nta-us->localhost:49361 (ESTABLISHED)
</code>```

Node version is v18.12.1, downloaded December 2022.

Body:
I am trying to instantiate a ganache node and get its eth balance, following a lesson on udemy.

What I should get is the eth balance of the connected node.  What I get is the below:

> let Web3 = require('web3');
undefined
> let web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
undefined
> web3.eth.getBalance("0xe19C5f3eB5e4d62cc02BD435C1ad4Ed3d68942eA").then(console.log);
Promise {
  <pending>,
  [Symbol(async_id_symbol)]: 702,
  [Symbol(trigger_async_id_symbol)]: 674
}
> (node:15825) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Uncaught Error: CONNECTION ERROR: Couldn't connect to node http://localhost:7545.
    at Object.ConnectionError (/Users/kio777/node_modules/web3-core-helpers/lib/errors.js:66:23)
    at Object.InvalidConnection (/Users/kio777/node_modules/web3-core-helpers/lib/errors.js:36:21)
    at HttpProvider.failed (/Users/kio777/node_modules/web3-providers-http/lib/index.js:136:25)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

I've tried to restart the terminal, and then trying to reinstall npm / node give me a bunch of other errors related to permissions.

Given the problem with connecting to localhost at port 7545, I checked port activity and got the following result:

COMMAND   PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
Ganache   904 kio777   28u  IPv4 0x181ce30a7bcda339      0t0  TCP localhost:49359->localhost:nta-us (ESTABLISHED)
Ganache   904 kio777   29u  IPv4 0x181ce30a7bcc9829      0t0  TCP localhost:49361->localhost:nta-us (ESTABLISHED)
Ganache   915 kio777   39u  IPv4 0x181ce30a7aeab959      0t0  TCP localhost:49358->localhost:nta-us (ESTABLISHED)
Ganache   915 kio777   47u  IPv4 0x181ce30a7bcd4f79      0t0  TCP localhost:49360->localhost:nta-us (ESTABLISHED)
Ganache   916 kio777   39u  IPv4 0x181ce30a7bccb959      0t0  TCP localhost:nta-us (LISTEN)
Ganache   916 kio777   47u  IPv4 0x181ce30a7bcd5a89      0t0  TCP localhost:nta-us->localhost:49358 (ESTABLISHED)
Ganache   916 kio777   48u  IPv4 0x181ce30a7bcd4469      0t0  TCP localhost:nta-us->localhost:49359 (ESTABLISHED)
Ganache   916 kio777   49u  IPv4 0x181ce30a7bcc8209      0t0  TCP localhost:nta-us->localhost:49360 (ESTABLISHED)
Ganache   916 kio777   50u  IPv4 0x181ce30a7ae97959      0t0  TCP localhost:nta-us->localhost:49361 (ESTABLISHED)

Node version is v18.12.1, downloaded December 2022.


问:
Insert a node next to the inserted node in Javascript Getselection Range
On keydown event, I need to print the character with span tag. Each character should be in a separate span tag.I am using a content editable div and I need to insert the characters based on the position so I used range. In my case with the below code I have typed abcde in the browser the characters are appearing inside the span tag but the span tag is coming as child element instead of sibling.

HTML:

```<code><div id="katexrendercontent" contenteditable=""  role="textbox" class="form-control" style="min-height: 100px;padding-left: 5px;padding-right: 5px;font-size: 22px;"></div>
</code>```

Javascript:

```<code>var i = 1;
$("#katexrendercontent").on("keydown",function(e){
    var range = window.getSelection().getRangeAt(0);
    var newnode = document.createElement("span");
    let k_id = "katexdivspanidcount_"+i;
     newnode.setAttribute("id",k_id);
     newnode.innerText = String.fromCharCode(e.which);
     range.insertNode(newnode);
     i=i+1;
});
</code>```

Browser Output :

```<code><div _ngcontent-yrh-c8="" id="katexrendercontent" contenteditable="" role="textbox" class="form-control" style="min-height: 100px; padding-left: 5px; padding-right: 5px; font-size: 22px;" spellcheck="false">
    <span id="katexdivspanidcount_1">a<span id="katexdivspanidcount_2">b<span id="katexdivspanidcount_3">c<span id="katexdivspanidcount_4">d<span id="katexdivspanidcount_5">e</span></span></span></span></span>
</div>
</code>```

Required Output:

```<code><div _ngcontent-yrh-c8="" id="katexrendercontent" contenteditable="" role="textbox" class="form-control" style="min-height: 100px; padding-left: 5px; padding-right: 5px; font-size: 22px;" spellcheck="false">
    <span id="katexdivspanidcount_1">a</span><span id="katexdivspanidcount_2">b</span><span id="katexdivspanidcount_3">c</span><span id="katexdivspanidcount_4">d</span><span id="katexdivspanidcount_5">e</span>
</div>

</code>```

Body:
On keydown event, I need to print the character with span tag. Each character should be in a separate span tag.I am using a content editable div and I need to insert the characters based on the position so I used range. In my case with the below code I have typed abcde in the browser the characters are appearing inside the span tag but the span tag is coming as child element instead of sibling.

HTML:

Javascript:

var i = 1;
$("#katexrendercontent").on("keydown",function(e){
    var range = window.getSelection().getRangeAt(0);
    var newnode = document.createElement("span");
    let k_id = "katexdivspanidcount_"+i;
     newnode.setAttribute("id",k_id);
     newnode.innerText = String.fromCharCode(e.which);
     range.insertNode(newnode);
     i=i+1;
});

Browser Output :

    abcde

Required Output:

    abcde


问:
I'm a bit new to this, how can I send BUSD instead of using BNB?
I am looking for a way that when you make the purchase with a fixed amount of BUSD to a smart contract address that I already have implemented. My problem is that I can't find the way to send BUSD instead of BNB, when I buy the token I get the price in BNB, that is, for example: 1 token = 1 BNB, how can this be configured when buying the token? How could we do for this? I want to send 1 BUSD instead of 1 BNB leaving the functions already established</p>
```<code>
import smart_contract from '../abis/tris.json';
import Web3 from 'web3';
import Swal from 'sweetalert2';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';

import Navigation from './Navbar';
import MyCarousel from './Carousel';
import { Container } from 'react-bootstrap';

class Tokens extends Component {

  async componentDidMount() {
      await this.loadWeb3()
      await this.loadBlockchainData()
  }

   async loadWeb3() {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum)
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Accounts: ', accounts)
    }
    else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider)
    }
    else {
      window.alert('¡Uses Metamask!')
    }
  }

  async loadBlockchainData() {
    const web3 = window.web3
    const accounts = await web3.eth.getAccounts()
    this.setState({ account: accounts[0] })

    const networkId = await web3.eth.net.getId()
    console.log('networkid:', networkId)
    const networkData = smart_contract.networks[networkId]
    console.log('NetworkData:', networkData)

    if (networkData) {
      const abi = smart_contract.abi
      console.log('abi', abi)
      const address = networkData.address
      console.log('address:', address)
      const contract = new web3.eth.Contract(abi, address)
      this.setState({ contract })
    } else {
      window.alert('¡Smart Contract here no deployed!')
    }
  }

  constructor(props) {
    super(props)
    this.state = {
      account: '0x0',
      loading: true,
      contract: null,
      errorMessage: ""
    }
  }

  _balanceTokens = async () => {
    try {
      console.log("Balance tokens...")
      const _balance = await this.state.contract.methods.balanceTokens(this.state.account).call()
      Swal.fire({
        icon: 'info',
        title: 'Balance tokens users:',
        width: 800,
        padding: '3em',
        text: `${_balance} tokens`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _balanceTokensSC = async () => {
    try {
      console.log("Balance of tokens of Smart Contract...")
      const _balanceTokensSC = await this.state.contract.methods.balanceTokensSC().call()
      Swal.fire({
        icon: 'info',
        title: 'Balance tokens of Smart Contract:',
        width: 800,
        padding: '3em',
        text: `${_balanceTokensSC} tokens`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _balanceEthersSC = async () => {
    try {
      console.log("Balance ethers of Smart Contract...")
      const _balanceEthersSC = await this.state.contract.methods.balanceEthersSC().call()
      Swal.fire({
        icon: 'info',
        title: 'Balance of ethers Smart Contract:',
        width: 800,
        padding: '3em',
        text: `${_balanceEthersSC} ethers`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _buyTokens = async (_numTokens) => {
    try {
      console.log("buy tokens...")
      const web3 = window.web3
      const ethers = web3.utils.toWei(_numTokens, 'ether')
      await this.state.contract.methods.compraTokens(_numTokens).send({
        from: this.state.account,
        value: ethers
      })
      Swal.fire({
        icon: 'success',
        title: '¡buy tokens!',
        width: 800,
        padding: '3em',
        text: ` you have ${_numTokens} token/s value of ${ethers} ether/s`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  } ```

Send BUSD instead of BNB
</code>```

Body:
I am looking for a way that when you make the purchase with a fixed amount of BUSD to a smart contract address that I already have implemented. My problem is that I can't find the way to send BUSD instead of BNB, when I buy the token I get the price in BNB, that is, for example: 1 token = 1 BNB, how can this be configured when buying the token? How could we do for this? I want to send 1 BUSD instead of 1 BNB leaving the functions already established

import smart_contract from '../abis/tris.json';
import Web3 from 'web3';
import Swal from 'sweetalert2';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';

import Navigation from './Navbar';
import MyCarousel from './Carousel';
import { Container } from 'react-bootstrap';

class Tokens extends Component {

  async componentDidMount() {
      await this.loadWeb3()
      await this.loadBlockchainData()
  }

   async loadWeb3() {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum)
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Accounts: ', accounts)
    }
    else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider)
    }
    else {
      window.alert('¡Uses Metamask!')
    }
  }

  async loadBlockchainData() {
    const web3 = window.web3
    const accounts = await web3.eth.getAccounts()
    this.setState({ account: accounts[0] })

    const networkId = await web3.eth.net.getId()
    console.log('networkid:', networkId)
    const networkData = smart_contract.networks[networkId]
    console.log('NetworkData:', networkData)

    if (networkData) {
      const abi = smart_contract.abi
      console.log('abi', abi)
      const address = networkData.address
      console.log('address:', address)
      const contract = new web3.eth.Contract(abi, address)
      this.setState({ contract })
    } else {
      window.alert('¡Smart Contract here no deployed!')
    }
  }

  constructor(props) {
    super(props)
    this.state = {
      account: '0x0',
      loading: true,
      contract: null,
      errorMessage: ""
    }
  }

  _balanceTokens = async () => {
    try {
      console.log("Balance tokens...")
      const _balance = await this.state.contract.methods.balanceTokens(this.state.account).call()
      Swal.fire({
        icon: 'info',
        title: 'Balance tokens users:',
        width: 800,
        padding: '3em',
        text: `${_balance} tokens`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _balanceTokensSC = async () => {
    try {
      console.log("Balance of tokens of Smart Contract...")
      const _balanceTokensSC = await this.state.contract.methods.balanceTokensSC().call()
      Swal.fire({
        icon: 'info',
        title: 'Balance tokens of Smart Contract:',
        width: 800,
        padding: '3em',
        text: `${_balanceTokensSC} tokens`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _balanceEthersSC = async () => {
    try {
      console.log("Balance ethers of Smart Contract...")
      const _balanceEthersSC = await this.state.contract.methods.balanceEthersSC().call()
      Swal.fire({
        icon: 'info',
        title: 'Balance of ethers Smart Contract:',
        width: 800,
        padding: '3em',
        text: `${_balanceEthersSC} ethers`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _buyTokens = async (_numTokens) => {
    try {
      console.log("buy tokens...")
      const web3 = window.web3
      const ethers = web3.utils.toWei(_numTokens, 'ether')
      await this.state.contract.methods.compraTokens(_numTokens).send({
        from: this.state.account,
        value: ethers
      })
      Swal.fire({
        icon: 'success',
        title: '¡buy tokens!',
        width: 800,
        padding: '3em',
        text: ` you have ${_numTokens} token/s value of ${ethers} ether/s`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  } ```

Send BUSD instead of BNB


问:
GWT Development Mode Errors When Running (No Source Code Available)
I am trying to run a GWT application with Maven for an old legacy eclipse project that we need to make some changes to. It is using smartgwt 2.8.2 and compiling with JDK 8. When I try to run the development mode in Eclipse I am getting some errors such as:
Line 200: No source code is available for type com.smartgwt.client.types.SelectionStyle; did you forget to inherit a required module?
Line 392: No source code is available for type com.smartgwt.client.widgets.form.fields.ComboBoxItem; did you forget to inherit a required module?
Line 126: No source code is available for type com.smartgwt.client.data.DataSource; did you forget to inherit a required module?
Line 66: No source code is available for type com.smartgwt.client.widgets.tree.TreeGrid; did you forget to inherit a required module?

This goes on for a bit mostly for any classes that are needed from com.smartgwt.*
The error then ends with the following as well:
Starting HTTP on port 8888
Starting Jetty on port 8888
[ERROR] jreLeakPrevention.gcDaemonFail
java.lang.ClassNotFoundException: sun.misc.GC
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at com.google.gwt.dev.shell.jetty.JettyLauncher.jreLeakPrevention(JettyLauncher.java:899)
at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:722)

I am currently unable to run this application due to these issues in Development Mode...if anyone has any experience or is familiar with these errors due let me know. If you need any further information do ask as I am at my wits end here.
Thanks.


问:
Microsoft Excel is not allowed to open documents in Terminal on MacOS Ventura
I'm trying to automate some tasks on Excel by calling Python. At windows I can call python via VBA or hyperlinks. But, at MacOS I can't. I use a MacBook pro 2019 and MacOS Ventura.

I used a hyper link to a python file by I got an error saying, "Microsoft Excel is not allowed to open documents in Terminal." I tried to call a python script and a .sh file. In both cases I got the same error.

Here is an example file I try to run.

```<code>#!/Users/akifarslan/Desktop/coding/field_payroll2/venv/bin/python3.11

import time

# print current time and sleep for 10 seconds

print(time.ctime())
time.Sleep(10)
</code>```

Does anybody know how to make MacOS Ventura to let Excel run files on terminal?

Body:
I'm trying to automate some tasks on Excel by calling Python. At windows I can call python via VBA or hyperlinks. But, at MacOS I can't. I use a MacBook pro 2019 and MacOS Ventura.

I used a hyper link to a python file by I got an error saying, "Microsoft Excel is not allowed to open documents in Terminal." I tried to call a python script and a .sh file. In both cases I got the same error.

Here is an example file I try to run.

#!/Users/akifarslan/Desktop/coding/field_payroll2/venv/bin/python3.11

import time

# print current time and sleep for 10 seconds

print(time.ctime())
time.Sleep(10)

Does anybody know how to make MacOS Ventura to let Excel run files on terminal?


问:
Photon, RPC disabling then enabling object
I've got a method that changes the state on an object for clients,

The problem is that the method is being called once but it is doing the action twice,
My hunch is that it's because I have 2 players over the network.

Here is the method that is being called:

```<code>public void ShutOff_LS()
{
    for(int i = 0; i < lights.Count; i++)
    {
        Debug.Log("shutoff_LS");
        photonView.RPC("LightSwitchOverNet", RpcTarget.All, i);
    }
}
</code>```

And here is the RPC:

```<code>[PunRPC]
public void LightSwitchOverNet(int index)
{
    lights[index].lGroup.gameObject.SetActive(!lights[index].lGroup.gameObject.activeSelf);
    current_states[index] = !current_states[index];

    Debug.LogError("Over network #2");
}
</code>```

I'm using Debug.LogError because I've got lots of Debug.Log's.

The logs that I get in the console is:

As you can see in the image i've got 18 of the logerrors but only 9 of the log's, there are 9 items in lights.Count and the method is only called ocne, otherwise it would how 18 of the log's

I hope you can help me out!
Cheers in advanced

Body:
I've got a method that changes the state on an object for clients,

The problem is that the method is being called once but it is doing the action twice,
My hunch is that it's because I have 2 players over the network.

Here is the method that is being called:

public void ShutOff_LS()
{
    for(int i = 0; i < lights.Count; i++)
    {
        Debug.Log("shutoff_LS");
        photonView.RPC("LightSwitchOverNet", RpcTarget.All, i);
    }
}

And here is the RPC:

[PunRPC]
public void LightSwitchOverNet(int index)
{
    lights[index].lGroup.gameObject.SetActive(!lights[index].lGroup.gameObject.activeSelf);
    current_states[index] = !current_states[index];

    Debug.LogError("Over network #2");
}

I'm using Debug.LogError because I've got lots of Debug.Log's.

The logs that I get in the console is:

As you can see in the image i've got 18 of the logerrors but only 9 of the log's, there are 9 items in lights.Count and the method is only called ocne, otherwise it would how 18 of the log's

I hope you can help me out!
Cheers in advanced


问:
How does one keep a pygase client from crashing on client disconnect?
I have been learning to use the library pygase for python, and have run into the issue of the server crashing when the client disconnects. Is there any way to prevent the server crash?

I have tried to find a function to close the connection server side, but have found none. The disconnect function client side causes the server to crash as well.

code below:

Server:

```<code># backend.py

import math
from pygase import GameState, Backend
from inspect import getmembers, isfunction

### SETUP ###

# Let there be an imaginary enemy at position 0 with 100 health points.
initial_game_state = GameState(position=0, hp=100)

# Define what happens in an iteration of the game loop.
def time_step(game_state, dt):
    # Make the imaginary enemy move in sinuous lines like a drunkard.
    new_position = game_state.position + math.sin(dt)
    return {"position": new_position}

# Create the backend.
backend = Backend(initial_game_state, time_step)

# variables
connected_clients_ids = []
version = 1

### EVENT HANDLERS ###

def on_attack(attack_position, client_id, client_address, game_state, **kwargs):
    print(f'attacked by {client_id}')
    # Check if the attack landed near enough to hit.
    if abs(attack_position - game_state.position) < 0.1:
        backend.server.dispatch_event("ATTACK_FEEDBACK", "Hit!", target_client=client_address)
        # Subtract the attacks damage from the enemies health.
        return {"hp": game_state.hp - 10}
    backend.server.dispatch_event("ATTACK_FEEDBACK", f'Missed {client_id}', target_client=client_address)
    return {}

def on_attemped_join(client_id, client_version, client_address, game_state, **kwargs):
    global connected_clients_ids, version
    func_failed = False
    if connected_clients_ids.__contains__(client_id):
        backend.server.dispatch_event("JOIN_RESULT", [False, "Client id already connected"], target_client=client_address)
        func_failed = True

    if client_version != version:
        backend.server.dispatch_event("JOIN_RESULT", [False, f'server version is {version}, client version is {client_version}'], target_client=client_address)
        func_failed = True

    if not func_failed:
        connected_clients_ids.append(client_id)
        backend.server.dispatch_event("JOIN_RESULT", [True, "success"], target_client=client_address)
        print(f'client {client_id} joined')
    return {}

def on_leave(client_id, client_address, game_state, **kwargs):
    global connected_clients_ids
    print(backend.server.connections)

    connected_clients_ids.remove(client_id)
    backend.server.dispatch_event("LEAVE_RESULT", [True, "goodbye"], target_client=client_address)

backend.game_state_machine.register_event_handler("ATTACK", on_attack)
backend.game_state_machine.register_event_handler("ATTEMPT_JOIN", on_attemped_join)
backend.game_state_machine.register_event_handler("LEAVE", on_leave)

### MAIN PROCESS ###

if __name__ == "__main__":
    while True:
        try:
            print("server opened")
            backend.run('localhost', 8080)
        except Exception as e:
            print(e)

</code>```

Client:

```<code>from pygase import Client
import pygame
import os

from pygame.locals import RESIZABLE

# inits

os.environ['SDL_VIDEO_CENTERED'] = '1'  # You have to call this before pygame.init()
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()

# variables
id = 451
version = 1
client = Client()
connected = False
connection_address = ["0.0.0.0", 8080]
running = True
screen_id = 0

### Handler ###

def client_join(joined):
    global connected
    if not joined[0]:
        print("error, could not connect")
        print(joined[1])
        client.disconnect()
    else:
        print("joined successfully")
        connected = True

# Register handlers
client.register_event_handler("ATTACK_FEEDBACK", print)
client.register_event_handler("JOIN_RESULT", client_join)

# functions
def Join(address="localhost", port=8080):
    global connection_address, screen_id
    client.connect_in_thread(port, address)
    client.dispatch_event("ATTEMPT_JOIN", client_id=id, client_version=version)
    connection_address = [address, port]
    for i in range(5):
        clock.tick(1)
        if connected:
            screen_id = 1
            return
    print("connection failed")

def Leave():
    client.dispatch_event("LEAVE", client_id=id, client_version=version)
    for i in range(5):
        clock.tick(1)
    client.disconnect()

while running:
    if screen_id == 0:
        if input("specify address and port? y/n\n").__contains__("y"):
            Join(input("Attempting to find server\naddress:"), int(input("port:")))

        else:
            Join()
    elif screen_id == 1:
        if input("exit()? y/n\n").__contains__("y"):
            Leave()

</code>```

Body:
I have been learning to use the library pygase for python, and have run into the issue of the server crashing when the client disconnects. Is there any way to prevent the server crash?

I have tried to find a function to close the connection server side, but have found none. The disconnect function client side causes the server to crash as well.

code below:

Server:

# backend.py

import math
from pygase import GameState, Backend
from inspect import getmembers, isfunction

### SETUP ###

# Let there be an imaginary enemy at position 0 with 100 health points.
initial_game_state = GameState(position=0, hp=100)

# Define what happens in an iteration of the game loop.
def time_step(game_state, dt):
    # Make the imaginary enemy move in sinuous lines like a drunkard.
    new_position = game_state.position + math.sin(dt)
    return {"position": new_position}

# Create the backend.
backend = Backend(initial_game_state, time_step)

# variables
connected_clients_ids = []
version = 1

### EVENT HANDLERS ###

def on_attack(attack_position, client_id, client_address, game_state, **kwargs):
    print(f'attacked by {client_id}')
    # Check if the attack landed near enough to hit.
    if abs(attack_position - game_state.position) < 0.1:
        backend.server.dispatch_event("ATTACK_FEEDBACK", "Hit!", target_client=client_address)
        # Subtract the attacks damage from the enemies health.
        return {"hp": game_state.hp - 10}
    backend.server.dispatch_event("ATTACK_FEEDBACK", f'Missed {client_id}', target_client=client_address)
    return {}

def on_attemped_join(client_id, client_version, client_address, game_state, **kwargs):
    global connected_clients_ids, version
    func_failed = False
    if connected_clients_ids.__contains__(client_id):
        backend.server.dispatch_event("JOIN_RESULT", [False, "Client id already connected"], target_client=client_address)
        func_failed = True

    if client_version != version:
        backend.server.dispatch_event("JOIN_RESULT", [False, f'server version is {version}, client version is {client_version}'], target_client=client_address)
        func_failed = True

    if not func_failed:
        connected_clients_ids.append(client_id)
        backend.server.dispatch_event("JOIN_RESULT", [True, "success"], target_client=client_address)
        print(f'client {client_id} joined')
    return {}

def on_leave(client_id, client_address, game_state, **kwargs):
    global connected_clients_ids
    print(backend.server.connections)

    connected_clients_ids.remove(client_id)
    backend.server.dispatch_event("LEAVE_RESULT", [True, "goodbye"], target_client=client_address)

backend.game_state_machine.register_event_handler("ATTACK", on_attack)
backend.game_state_machine.register_event_handler("ATTEMPT_JOIN", on_attemped_join)
backend.game_state_machine.register_event_handler("LEAVE", on_leave)

### MAIN PROCESS ###

if __name__ == "__main__":
    while True:
        try:
            print("server opened")
            backend.run('localhost', 8080)
        except Exception as e:
            print(e)

Client:

from pygase import Client
import pygame
import os

from pygame.locals import RESIZABLE

# inits

os.environ['SDL_VIDEO_CENTERED'] = '1'  # You have to call this before pygame.init()
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()

# variables
id = 451
version = 1
client = Client()
connected = False
connection_address = ["0.0.0.0", 8080]
running = True
screen_id = 0

### Handler ###

def client_join(joined):
    global connected
    if not joined[0]:
        print("error, could not connect")
        print(joined[1])
        client.disconnect()
    else:
        print("joined successfully")
        connected = True

# Register handlers
client.register_event_handler("ATTACK_FEEDBACK", print)
client.register_event_handler("JOIN_RESULT", client_join)

# functions
def Join(address="localhost", port=8080):
    global connection_address, screen_id
    client.connect_in_thread(port, address)
    client.dispatch_event("ATTEMPT_JOIN", client_id=id, client_version=version)
    connection_address = [address, port]
    for i in range(5):
        clock.tick(1)
        if connected:
            screen_id = 1
            return
    print("connection failed")

def Leave():
    client.dispatch_event("LEAVE", client_id=id, client_version=version)
    for i in range(5):
        clock.tick(1)
    client.disconnect()

while running:
    if screen_id == 0:
        if input("specify address and port? y/n\n").__contains__("y"):
            Join(input("Attempting to find server\naddress:"), int(input("port:")))

        else:
            Join()
    elif screen_id == 1:
        if input("exit()? y/n\n").__contains__("y"):
            Leave()


问:
I am trying to setup my PUT and POST request for user objects that contain an array of objects for one of the key values
I'm using MERN with Typescript and Redux. I have a user object and am trying to implement a customProfileLinks key that will be an array of objects containing every user site a user decides to add/update. I already created my interfaces for my user model and for the object for each site/url in the array:

```<code>
export interface UserInterface {
  bio: string;
  customProfileLinks: Array<CustomUrlInterface>;
  email: string;
  firstName: string;
  lastName: string;
  profilePicture: string;
  role: string;
  __v?: number;
  _id: string;
}

export interface CustomUrlInterface {
  _id: string;
  customUrlName: string;
  customUrlLink: string;
}

</code>```

Here's an example of what a user object would look like:

```<code>const User1 = {
  bio: "Looking for opportunities",
  customProfileLinks: [
    {
      customUrlName: 'GitHub',
      customUrlLink: 'http://www.github.com/johndoe'
    },
    {
      customUrlName: 'LinkedIn',
      customUrlLink: 'http://www.linkedin.com/johndoe'
    },
    {
      customUrlName: 'Stack Overflow',
      customUrlLink: 'http://www.stackoverflow.com/johndoe'
    }
  ],
  email: 'johndoe@gmail.com',
  firstName: 'John',
  lastName: 'Doe',
  profilePicture: 'http://www.imgur.com/45sf45dsff',
  role: 'Project Manager'
}

</code>```

Here's my attempt at setting up my onChange function:

```<code>const authUser = useSelector(selectAuthUser);
  const [userForm, updateUserForm] = useState<UserInterface>(emptyUser);
  const [urlForm, updateUrlForm] = useState<CustomUrlInterface>(emptyUrl);
  const params = useParams();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const {
    bio,
    email,
    firstName,
    lastName,
    profilePicture,
    role,
    _id: userId,
    customProfileLinks,
  } = userForm;

  useEffect(() => {
    if (authUser) {
      updateUserForm((currForm) => {
        return {
          ...currForm,
          ...authUser,
        };
      });
    }
  }, [authUser]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    customProfileLinks: [
      ...customProfileLinks,
      {
        customUrlName: customProfileLinks.*customUrlName*,
        customUrlLink: customProfileLinks.*customUrlLink*,
      },
    ];
    updateUserForm({ ...userForm, [name]: value });
  };

</code>```

My first bug is with Typescript. I am getting two errors saying:
Property 'customUrlName' does not exist on type 'CustomUrlInterface[]'.
Property 'customUrlLink' does not exist on type 'CustomUrlInterface[]'.

The second thing I need help with is targeting the values for customUrlName and customUrlLink in the customProfileLinks object. Since this is inside an array of objects, how would I handle the PUT request, and adding to the array as a POST request since it's within the larger user object?

I also tried setting up my handleInputChange function this way, but wasn't getting the desired outcome.

```<code>const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    updateUrlForm({ ...urlForm, [name]: value })
    customProfileLinks.push(urlForm)
    updateUserForm({ ...userForm, ...urlForm });
  };
</code>```

Body:
I'm using MERN with Typescript and Redux. I have a user object and am trying to implement a customProfileLinks key that will be an array of objects containing every user site a user decides to add/update. I already created my interfaces for my user model and for the object for each site/url in the array:

export interface UserInterface {
  bio: string;
  customProfileLinks: Array<CustomUrlInterface>;
  email: string;
  firstName: string;
  lastName: string;
  profilePicture: string;
  role: string;
  __v?: number;
  _id: string;
}

export interface CustomUrlInterface {
  _id: string;
  customUrlName: string;
  customUrlLink: string;
}

Here's an example of what a user object would look like:

const User1 = {
  bio: "Looking for opportunities",
  customProfileLinks: [
    {
      customUrlName: 'GitHub',
      customUrlLink: 'http://www.github.com/johndoe'
    },
    {
      customUrlName: 'LinkedIn',
      customUrlLink: 'http://www.linkedin.com/johndoe'
    },
    {
      customUrlName: 'Stack Overflow',
      customUrlLink: 'http://www.stackoverflow.com/johndoe'
    }
  ],
  email: 'johndoe@gmail.com',
  firstName: 'John',
  lastName: 'Doe',
  profilePicture: 'http://www.imgur.com/45sf45dsff',
  role: 'Project Manager'
}

Here's my attempt at setting up my onChange function:

const authUser = useSelector(selectAuthUser);
  const [userForm, updateUserForm] = useState<UserInterface>(emptyUser);
  const [urlForm, updateUrlForm] = useState<CustomUrlInterface>(emptyUrl);
  const params = useParams();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const {
    bio,
    email,
    firstName,
    lastName,
    profilePicture,
    role,
    _id: userId,
    customProfileLinks,
  } = userForm;

  useEffect(() => {
    if (authUser) {
      updateUserForm((currForm) => {
        return {
          ...currForm,
          ...authUser,
        };
      });
    }
  }, [authUser]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    customProfileLinks: [
      ...customProfileLinks,
      {
        customUrlName: customProfileLinks.*customUrlName*,
        customUrlLink: customProfileLinks.*customUrlLink*,
      },
    ];
    updateUserForm({ ...userForm, [name]: value });
  };

My first bug is with Typescript. I am getting two errors saying:
Property 'customUrlName' does not exist on type 'CustomUrlInterface[]'.
Property 'customUrlLink' does not exist on type 'CustomUrlInterface[]'.

The second thing I need help with is targeting the values for customUrlName and customUrlLink in the customProfileLinks object. Since this is inside an array of objects, how would I handle the PUT request, and adding to the array as a POST request since it's within the larger user object?

I also tried setting up my handleInputChange function this way, but wasn't getting the desired outcome.

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    updateUrlForm({ ...urlForm, [name]: value })
    customProfileLinks.push(urlForm)
    updateUserForm({ ...userForm, ...urlForm });
  };


问:
Error in running Logit model clustered by contry code
I am just starting out in R and am trying to run a logit model with clutered country codes. My attempt is to replicate a model from this paper with the following replication information :

Data available here (data file): https://drive.google.com/file/d/1O2Gvf7sqxYN7IsOI2zTRZANlbLnVQvvw/view

*Model 1: base
logit mk l.wtrivalry  mkyear mkyear2 mkyear3, cluster(ccode)

*Model 2: Controls -- no conflict
logit mk l.wtrivalry l.lnrgdppc l.polity2 l.exclid l.lnpopWB l.coupdummy mkyear mkyear2 mkyear3, cluster(ccode)

I have been trying variations of code, but keep failing to cluster correctly (unless I do so, the significance of the variables does not align with that of the paper). My attempts have been:

```<code>simp.logit.general. <- glm(mk ~ wtrivalry + mkyear + mkyear2 + mkyear3, data = core.data, family="binomial")
summary(simp.logit.general.)

</code>```

robcov(simp.logit.general)

Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'as.matrix': 'arg' should be one of “deviance”, “pearson”, “working”, “response”, “partial”

```<code>I have also tried:
coeftest(simp.logit.general, vcov. = vcovCL(simp.logit.general, cluster = core.data$ccode, type = "HC0"))
</code>```

IF anyone could help with this, I would really appreciate it.

Body:
I am just starting out in R and am trying to run a logit model with clutered country codes. My attempt is to replicate a model from this paper with the following replication information :

Data available here (data file): https://drive.google.com/file/d/1O2Gvf7sqxYN7IsOI2zTRZANlbLnVQvvw/view

*Model 1: base
logit mk l.wtrivalry  mkyear mkyear2 mkyear3, cluster(ccode)

*Model 2: Controls -- no conflict
logit mk l.wtrivalry l.lnrgdppc l.polity2 l.exclid l.lnpopWB l.coupdummy mkyear mkyear2 mkyear3, cluster(ccode)

I have been trying variations of code, but keep failing to cluster correctly (unless I do so, the significance of the variables does not align with that of the paper). My attempts have been:

simp.logit.general. <- glm(mk ~ wtrivalry + mkyear + mkyear2 + mkyear3, data = core.data, family="binomial")
summary(simp.logit.general.)

robcov(simp.logit.general)

Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'as.matrix': 'arg' should be one of “deviance”, “pearson”, “working”, “response”, “partial”

I have also tried:
coeftest(simp.logit.general, vcov. = vcovCL(simp.logit.general, cluster = core.data$ccode, type = "HC0"))

IF anyone could help with this, I would really appreciate it.


问:
how to take application control back from application_error
I got an old application that is using aspnet membership controls changepassword and createuserwizard etc. These send emails in the end, via gmail, after sending the email successfully, I get an application_error

The SMTP server requires a secure connection or the client was not authenticated...

The requirement is I can go back to the normal flow of application and ignore this error.
Note that the email is being sent successfully to the client. There is no exception within the procedure/catch.

```<code>Protected Sub ChangePwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles ChangePwd.SendingMail
Dim obj As SecurePassword = New SecurePassword()

    Select Case ConfigurationSettings.AppSettings("WhichSMTP")
        Case "gmail"

            Try
                obj.SendViaGmail(e.Message.Subject, e.Message.Body, e.Message.To.ToString())
            Catch ex As Exception
                Response.Write("Error sending email via gmail smtp: " & ex.Message)
            End Try
        End Select
End Sub

</code>```

SecurePassword.vb

```<code>Public Function SendViaGmail(subject As String, body As String, recipients As String)
        Dim fromEmail As String = ConfigurationSettings.AppSettings("ContactEmail")

        Dim smtpClient As SmtpClient = New SmtpClient("smtp.gmail.com") With {
            .Port = 587,
            .DeliveryMethod = SmtpDeliveryMethod.Network,
            .Credentials = New NetworkCredential(fromEmail, "apppasswordgeneratedviagoogle"),
            .EnableSsl = True
            }

        Dim mailMessage As MailMessage = New MailMessage With {
        .From = New MailAddress(fromEmail),
        .Subject = subject,
        .Body = body,
        .IsBodyHtml = True
    }

        mailMessage.[To].Add(recipients)
        If smtpClient IsNot Nothing Then
            smtpClient.Send(mailMessage)
        End If
    End Function
</code>```

I got the above code from here

few things to note,

I am running this code from my development machine (IISExpress).

previously there was no code written under

Case "gmail"

Update:

I have tried catching it in page_error, it actually comes here but it shows me an empty page now instead of successtemplate from changepassword control

```<code>Private Sub Page_Error(sender As Object, e As EventArgs) Handles Me.Error
    Dim exc As Exception = Server.GetLastError()

    ' Handle specific exception.
    If exc.GetType = GetType(SmtpException) Then

        ChangePwd.SuccessTemplate.InstantiateIn(ChangePassword)
        'ChangePwd.ChangePasswordTemplateContainer.Visible = False
    End If

    ' Clear the error from the server.
    Server.ClearError()
End Sub
</code>```

Body:
I got an old application that is using aspnet membership controls changepassword and createuserwizard etc. These send emails in the end, via gmail, after sending the email successfully, I get an application_error

The SMTP server requires a secure connection or the client was not authenticated...

The requirement is I can go back to the normal flow of application and ignore this error.
Note that the email is being sent successfully to the client. There is no exception within the procedure/catch.

Protected Sub ChangePwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles ChangePwd.SendingMail
Dim obj As SecurePassword = New SecurePassword()

    Select Case ConfigurationSettings.AppSettings("WhichSMTP")
        Case "gmail"

            Try
                obj.SendViaGmail(e.Message.Subject, e.Message.Body, e.Message.To.ToString())
            Catch ex As Exception
                Response.Write("Error sending email via gmail smtp: " & ex.Message)
            End Try
        End Select
End Sub

SecurePassword.vb

Public Function SendViaGmail(subject As String, body As String, recipients As String)
        Dim fromEmail As String = ConfigurationSettings.AppSettings("ContactEmail")

        Dim smtpClient As SmtpClient = New SmtpClient("smtp.gmail.com") With {
            .Port = 587,
            .DeliveryMethod = SmtpDeliveryMethod.Network,
            .Credentials = New NetworkCredential(fromEmail, "apppasswordgeneratedviagoogle"),
            .EnableSsl = True
            }

        Dim mailMessage As MailMessage = New MailMessage With {
        .From = New MailAddress(fromEmail),
        .Subject = subject,
        .Body = body,
        .IsBodyHtml = True
    }

        mailMessage.[To].Add(recipients)
        If smtpClient IsNot Nothing Then
            smtpClient.Send(mailMessage)
        End If
    End Function

I got the above code from here

few things to note,

I am running this code from my development machine (IISExpress).

previously there was no code written under

Case "gmail"

Update:

I have tried catching it in page_error, it actually comes here but it shows me an empty page now instead of successtemplate from changepassword control

Private Sub Page_Error(sender As Object, e As EventArgs) Handles Me.Error
    Dim exc As Exception = Server.GetLastError()

    ' Handle specific exception.
    If exc.GetType = GetType(SmtpException) Then

        ChangePwd.SuccessTemplate.InstantiateIn(ChangePassword)
        'ChangePwd.ChangePasswordTemplateContainer.Visible = False
    End If

    ' Clear the error from the server.
    Server.ClearError()
End Sub


问:
Android - CoordinatorLayout anchor cardview into AppBar
Hello i want to anchoring cardview in appbar and i want to make cardview disappear after i scroll down, currently the cardview covering appbar when i scroll down. The code works well when i use FloatingActionButton, but not when i use cardview. Thank you

this is the xml code for the screenshot

this is the snipped code

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar" ... >

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
                app:layout_collapseMode="parallax">

                <ImageView />

                <View />

            </RelativeLayout>

            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/toolbar"
                app:layout_collapseMode="pin"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways" ... >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >
                 //just content
                </RelativeLayout>

            </com.google.android.material.appbar.MaterialToolbar>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView

        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <TextView />

    </androidx.core.widget.NestedScrollView>

    <androidx.cardview.widget.CardView
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|end">

    </androidx.cardview.widget.CardView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

this is the full xml code
https://pastebin.com/wPsjpAyy

Body:
Hello i want to anchoring cardview in appbar and i want to make cardview disappear after i scroll down, currently the cardview covering appbar when i scroll down. The code works well when i use FloatingActionButton, but not when i use cardview. Thank you

this is the xml code for the screenshot

this is the snipped code

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar" ... >

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
                app:layout_collapseMode="parallax">

                <ImageView />

                <View />

            </RelativeLayout>

            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/toolbar"
                app:layout_collapseMode="pin"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways" ... >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >
                 //just content
                </RelativeLayout>

            </com.google.android.material.appbar.MaterialToolbar>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView

        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <TextView />

    </androidx.core.widget.NestedScrollView>

    <androidx.cardview.widget.CardView
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|end">

    </androidx.cardview.widget.CardView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

this is the full xml code
https://pastebin.com/wPsjpAyy


问:
How to use specific inodes/directories that come under df -i to store files
I'm working on a research project in a ML lab, and running stuff on their machines virtually using ssh. The machines are Linux, and my home laptop is a Mac. The actual machine storage is really small, so I'm supposed to use these two specific directories that show up under df -I (inodes list). But how do I like redirect files to store there?

Adding it to the end of directories when I use scp -r doesn't work. My command to send directories from my local computer to the ssh is scp -r /Local directory pwd/ username@server:/home/username, and for example sticking on the anode directory to the back of it (so new command would be scp -r /Local directory pwd/ username@server:/home/username/inode directory) doesn't work.

Would appreciate help


问:
Potential reasons autocompleteclose event not available within a function?
I'm migrating some old code to a new site and there are lots of JS libraries being used so trying to pinpoint why this isn't working has been difficult. In short within a function I need this code to run:

```<code>    $(tabID).on( "autocompleteclose", function() {
        some_function(var1, var2, var3, var4, var5);
    });
</code>```

These variables are only available within this function so that's why its being called within there.

If I define the event listener outside of the function in the main JS file, the event listener works. Overall, it appears to be some namespace issue as I've had issues getting other jQuery libraries working in this file when within functions, but in the main body of the file they work. I'm not terribly familiar with JS (and jQuery more specifically) so I'm looking at some starting points to figure out why it's not working.

As mentioneed above, the autocompleteclose event listener will work within the body of the JS file, but not within any functions. It appears to be a namespace issue with the JS libraries but I'm having trouble figuring out what are some other steps I can do to narrow down the cause of the error.

Body:
I'm migrating some old code to a new site and there are lots of JS libraries being used so trying to pinpoint why this isn't working has been difficult. In short within a function I need this code to run:

    $(tabID).on( "autocompleteclose", function() {
        some_function(var1, var2, var3, var4, var5);
    });

These variables are only available within this function so that's why its being called within there.

If I define the event listener outside of the function in the main JS file, the event listener works. Overall, it appears to be some namespace issue as I've had issues getting other jQuery libraries working in this file when within functions, but in the main body of the file they work. I'm not terribly familiar with JS (and jQuery more specifically) so I'm looking at some starting points to figure out why it's not working.

As mentioneed above, the autocompleteclose event listener will work within the body of the JS file, but not within any functions. It appears to be a namespace issue with the JS libraries but I'm having trouble figuring out what are some other steps I can do to narrow down the cause of the error.


问:
Search query box doesn't recommend places in Vue automatically
If you run my below code, it is supposed to open up a website. This works fine, however, when I go to the input box it is supposed to recommend places with the characters given immediately. This isn't working.

I am doing a tutorial and am currently at 12:41 of this video.

https://www.youtube.com/watch?v=5pTzHoliXUQ&list=PL4cUxeGkcC9hfoy8vFQ5tbXO3vY0xhhUZ&index=5

Here is my code:

```<code><template>
  <main class="container text-white" >
    <div class="pt-4 mb-8 relative">
      <input type="text"
      v-model = "searchQuery"
      @input="getSearchResults"
      placeholder="Search for city or state"
      class="py-2 px-1 w-full bg-transparent border-b
       focus:border-weather-secondary focus:outline-none focus:shadow-[0px_1px_0_0_#004E71]">
       <ul class="absolute bg-weather-secondary text-white w-full shadow-md py-2 px-1 top-[66px]">
        <li v-for="searchResult in mapboxSearchResults" :key ="searchResult.id" class="py-2 cursor-pointer">
          {{searchResult.place_name}}
        </li>
       </ul>
    </div>
  </main>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const mapboxAPIkey ="pk.eyJ1IjoiYWhhbmFhYSIsImEiOiJjbGJqc3d5NG0xNGd5M3BtbWppcmgyNzE4In0.L-HsHWAbshfvVY_xixizNw"

const searchQuery = ref("");
const queryTimeout = ref(null)
const mapboxSearchResults = ref(null)

const getResults = () => {
  clearTimeout(queryTimeout.value)
  queryTimeout.value = setTimeout(async() => {
    if(searchQuery.value !== ""){
      const result = await axios.get(
        `https://api.mapbox.com/geocoding/v5/mapbox.places/${searchQuery.value}.json?access_token=${mapboxAPIkey}&types=place`
      )
      mapboxSearchresults.value = result.data.features
      return;
    }
    mapboxSearchresults.value = null
  }, 300)

}
</script>

</code>```

I tried to run the code with npm run dev in the terminal and everything was working fine up until now.

Body:
If you run my below code, it is supposed to open up a website. This works fine, however, when I go to the input box it is supposed to recommend places with the characters given immediately. This isn't working.

I am doing a tutorial and am currently at 12:41 of this video.

https://www.youtube.com/watch?v=5pTzHoliXUQ&list=PL4cUxeGkcC9hfoy8vFQ5tbXO3vY0xhhUZ&index=5

Here is my code:

<template>

      <input type="text"
      v-model = "searchQuery"
      @input="getSearchResults"
      placeholder="Search for city or state"
      class="py-2 px-1 w-full bg-transparent border-b
       focus:border-weather-secondary focus:outline-none focus:shadow-[0px_1px_0_0_#004E71]">

          {{searchResult.place_name}}

</template>

I tried to run the code with npm run dev in the terminal and everything was working fine up until now.


问:
Aws amplify google SSO, sign in is not persisted in local storage
The app is built with react.

I am having some trouble making sure the user stays loggedIn after signing in via Google SSO. Following are my relevant imports

```<code>import { Amplify, Auth, Hub, Cache } from "aws-amplify";
import awsExports from "./aws-exports";
</code>```

Hi, I am using the following code. To listen to sign in events. The Sign in is successful, and stores all the relevant info in the local Storage for the tab that was used to log in. However, if I open another tab the information is not there, and therefore the currentAuthenticatedUser returns unauthenticated.

If I use a username, password log in, the data persists across tabs.

I am using ImplicitGrant, with Google.

```<code>  useEffect(() => {
    // Side Effect
    console.log("not app use effect");
    // fetchDevices();
    if (!authenticated) {
      console.log("fetching session", Cache.getItem("userSession"));
      console.log("getting my item", localStorage.getItem("myItem"));

      Auth.currentAuthenticatedUser({
        bypassCache: false, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
      })
        .then((user) => {
          console.log("got suer datal", user);
          if (user?.username) {
            console.log("usernname exists", user.username.startsWith("google"));
            if (user.username.startsWith("google")) {
              console.log("modifying the username");
              user.username = user?.attributes.email.split("@")[0];
            }
            console.log("user autheticatd", user);
            setAuthenticated(true);
            // rememberDevice();
            setCurrentActiveUser(user);
            store.dispatch(
              getUserExistingAPIKey(user?.signInUserSession?.idToken?.jwtToken)
            );
            store.dispatch({
              type: SET_ID_TOKEN,
              payload: user?.signInUserSession?.idToken?.jwtToken,
            });
            // getExistingUserAPIKey(user?.signInUserSession?.idToken?.jwtToken);
          }
        })
        .catch((e) => {
          console.log("the first login failed");
          console.log(e);
        });
    }

    const unsubscribe = Hub.listen("auth", ({ payload: { event, data } }) => {
      switch (event) {
        case "signIn":
          console.log("sign in event", data);
          setAuthenticated(true);
          setCurrentActiveUser(data);
          store.dispatch(
            getUserExistingAPIKey(data?.signInUserSession?.idToken?.jwtToken)
          );
          store.dispatch({
            type: SET_ID_TOKEN,
            payload: data?.signInUserSession?.idToken?.jwtToken,
          });
          rememberDevice();
          Auth.currentAuthenticatedUser({
            bypassCache: true, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
          })
            .then((user) => {
              console.log("got suer datal", user);
              if (user?.username) {
                console.log(
                  "usernname exists",
                  user.username.startsWith("google")
                );
                if (user.username.startsWith("google")) {
                  console.log("modifying the username");
                  user.username = user?.attributes.email.split("@")[0];
                }
                console.log("user autheticatd", user);
                setAuthenticated(true);
                rememberDevice();
                setCurrentActiveUser(user);
                store.dispatch(
                  getUserExistingAPIKey(
                    user?.signInUserSession?.idToken?.jwtToken
                  )
                );
                store.dispatch({
                  type: SET_ID_TOKEN,
                  payload: user?.signInUserSession?.idToken?.jwtToken,
                });
                // getExistingUserAPIKey(user?.signInUserSession?.idToken?.jwtToken);
              }
            })
            .catch((e) => {
              console.log("the first login failed");
              console.log(e);
            });
          break;
        case "signUp":
          console.log("sign up event");
          setAuthenticated(true);
          setCurrentActiveUser(data);
          break;
        case "signOut":
          console.log("sign out event");
          // setUser(data);
          setAuthenticated(false);
          setCurrentActiveUser(null);
          break;
        case "cognitoHostedUI":
          console.log("cognito hosted ui event", data);

          Auth.currentSession()
            .then((session) => {
              // Save the session info to the cache
              console.log("session", session);
              Cache.setItem("userSession", session);
              localStorage.setItem("myItem", session);
            })
            .catch((err) => {
              console.log("err", err);
            });

          Auth.currentAuthenticatedUser({
            bypassCache: true, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
          })
            .then((user) => {
              console.log("updated user", user);
              let token = data?.signInUserSession?.idToken?.jwtToken;
              Auth.federatedSignIn(
                "google",
                {
                  token,
                  expires_at: 1000 + new Date().getTime(), // the expiration timestamp
                },
                user
              )
                .then((cred) => {
                  // If success, you will get the AWS credentials
                  console.log("cred", cred);
                  return Auth.currentAuthenticatedUser();
                })
                .then((user) => {
                  // If success, the user object you passed in Auth.federatedSignIn
                  console.log("fetched user", user);
                  setAuthenticated(true);
                  // rememberDevice();
                  setCurrentActiveUser(user);
                  store.dispatch(
                    getUserExistingAPIKey(
                      user?.signInUserSession?.idToken?.jwtToken
                    )
                  );
                  store.dispatch({
                    type: SET_ID_TOKEN,
                    payload: user?.signInUserSession?.idToken?.jwtToken,
                  });
                })
                .catch((e) => {
                  console.log(e);
                });
            })
            .catch((e) => {
              console.log("error", e);
            });
          break;
        case "customOAuthState":
          console.log("custom oauth event", data);
          setAuthenticated(true);
          setCurrentActiveUser(data);
          break;
        case "signIn_failure":
          console.log("user sign in failed", data);
          break;
        case "tokenRefresh":
          console.log("token refresh succeeded");
          break;
        case "tokenRefresh_failure":
          console.log("token refresh failed");
          break;
        case "autoSignIn":
          console.log("auto sign in");
          break;
        case "autoSignIn_failure":
          console.log("auto sign in failed");
          break;

        case "cognitoHostedUI_failure":
          console.log("cognito hosted ui failed");

          Auth.federatedSignIn({ provider: "Google" })
            .then(async (cred) => {
              // If success, you will get the AWS credentials
              console.log(cred);
              Auth.currentAuthenticatedUser({
                bypassCache: false, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
              })
                .then((user) => {
                  console.log("got suer datal", user);
                  if (user?.username) {
                    console.log(
                      "usernname exists",
                      user.username.startsWith("google")
                    );
                    if (user.username.startsWith("google")) {
                      console.log("modifying the username");
                      user.username = user?.attributes.email.split("@")[0];
                    }
                    console.log("user autheticatd", user);
                    setAuthenticated(true);
                    rememberDevice();
                    setCurrentActiveUser(user);
                    store.dispatch(
                      getUserExistingAPIKey(
                        user?.signInUserSession?.idToken?.jwtToken
                      )
                    );
                    store.dispatch({
                      type: SET_ID_TOKEN,
                      payload: user?.signInUserSession?.idToken?.jwtToken,
                    });
                    // getExistingUserAPIKey(user?.signInUserSession?.idToken?.jwtToken);
                  }
                })
                .catch((e) => {
                  console.log("the first login failed");
                  console.log(e);
                });
            })
            .catch((e) => {
              console.log("the second login failed");
              console.log(e);
            });
          break;

        case "customState_failure":
          console.log("custom state failure", event, data);
          break;
        default:
          console.log("DEFAUL CASE", event, data);
          break;
      }
    });

    return unsubscribe;
  });
</code>```

I receive a cognitoHostedUI event after signingIn. I tried to store data manually but it never persists when I open a new tab.

any help would be appreciated, seriously considering, getting off of cognito/amplify.

Body:
The app is built with react.

I am having some trouble making sure the user stays loggedIn after signing in via Google SSO. Following are my relevant imports

import { Amplify, Auth, Hub, Cache } from "aws-amplify";
import awsExports from "./aws-exports";

Hi, I am using the following code. To listen to sign in events. The Sign in is successful, and stores all the relevant info in the local Storage for the tab that was used to log in. However, if I open another tab the information is not there, and therefore the currentAuthenticatedUser returns unauthenticated.

If I use a username, password log in, the data persists across tabs.

I am using ImplicitGrant, with Google.

  useEffect(() => {
    // Side Effect
    console.log("not app use effect");
    // fetchDevices();
    if (!authenticated) {
      console.log("fetching session", Cache.getItem("userSession"));
      console.log("getting my item", localStorage.getItem("myItem"));

      Auth.currentAuthenticatedUser({
        bypassCache: false, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
      })
        .then((user) => {
          console.log("got suer datal", user);
          if (user?.username) {
            console.log("usernname exists", user.username.startsWith("google"));
            if (user.username.startsWith("google")) {
              console.log("modifying the username");
              user.username = user?.attributes.email.split("@")[0];
            }
            console.log("user autheticatd", user);
            setAuthenticated(true);
            // rememberDevice();
            setCurrentActiveUser(user);
            store.dispatch(
              getUserExistingAPIKey(user?.signInUserSession?.idToken?.jwtToken)
            );
            store.dispatch({
              type: SET_ID_TOKEN,
              payload: user?.signInUserSession?.idToken?.jwtToken,
            });
            // getExistingUserAPIKey(user?.signInUserSession?.idToken?.jwtToken);
          }
        })
        .catch((e) => {
          console.log("the first login failed");
          console.log(e);
        });
    }

    const unsubscribe = Hub.listen("auth", ({ payload: { event, data } }) => {
      switch (event) {
        case "signIn":
          console.log("sign in event", data);
          setAuthenticated(true);
          setCurrentActiveUser(data);
          store.dispatch(
            getUserExistingAPIKey(data?.signInUserSession?.idToken?.jwtToken)
          );
          store.dispatch({
            type: SET_ID_TOKEN,
            payload: data?.signInUserSession?.idToken?.jwtToken,
          });
          rememberDevice();
          Auth.currentAuthenticatedUser({
            bypassCache: true, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
          })
            .then((user) => {
              console.log("got suer datal", user);
              if (user?.username) {
                console.log(
                  "usernname exists",
                  user.username.startsWith("google")
                );
                if (user.username.startsWith("google")) {
                  console.log("modifying the username");
                  user.username = user?.attributes.email.split("@")[0];
                }
                console.log("user autheticatd", user);
                setAuthenticated(true);
                rememberDevice();
                setCurrentActiveUser(user);
                store.dispatch(
                  getUserExistingAPIKey(
                    user?.signInUserSession?.idToken?.jwtToken
                  )
                );
                store.dispatch({
                  type: SET_ID_TOKEN,
                  payload: user?.signInUserSession?.idToken?.jwtToken,
                });
                // getExistingUserAPIKey(user?.signInUserSession?.idToken?.jwtToken);
              }
            })
            .catch((e) => {
              console.log("the first login failed");
              console.log(e);
            });
          break;
        case "signUp":
          console.log("sign up event");
          setAuthenticated(true);
          setCurrentActiveUser(data);
          break;
        case "signOut":
          console.log("sign out event");
          // setUser(data);
          setAuthenticated(false);
          setCurrentActiveUser(null);
          break;
        case "cognitoHostedUI":
          console.log("cognito hosted ui event", data);

          Auth.currentSession()
            .then((session) => {
              // Save the session info to the cache
              console.log("session", session);
              Cache.setItem("userSession", session);
              localStorage.setItem("myItem", session);
            })
            .catch((err) => {
              console.log("err", err);
            });

          Auth.currentAuthenticatedUser({
            bypassCache: true, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
          })
            .then((user) => {
              console.log("updated user", user);
              let token = data?.signInUserSession?.idToken?.jwtToken;
              Auth.federatedSignIn(
                "google",
                {
                  token,
                  expires_at: 1000 + new Date().getTime(), // the expiration timestamp
                },
                user
              )
                .then((cred) => {
                  // If success, you will get the AWS credentials
                  console.log("cred", cred);
                  return Auth.currentAuthenticatedUser();
                })
                .then((user) => {
                  // If success, the user object you passed in Auth.federatedSignIn
                  console.log("fetched user", user);
                  setAuthenticated(true);
                  // rememberDevice();
                  setCurrentActiveUser(user);
                  store.dispatch(
                    getUserExistingAPIKey(
                      user?.signInUserSession?.idToken?.jwtToken
                    )
                  );
                  store.dispatch({
                    type: SET_ID_TOKEN,
                    payload: user?.signInUserSession?.idToken?.jwtToken,
                  });
                })
                .catch((e) => {
                  console.log(e);
                });
            })
            .catch((e) => {
              console.log("error", e);
            });
          break;
        case "customOAuthState":
          console.log("custom oauth event", data);
          setAuthenticated(true);
          setCurrentActiveUser(data);
          break;
        case "signIn_failure":
          console.log("user sign in failed", data);
          break;
        case "tokenRefresh":
          console.log("token refresh succeeded");
          break;
        case "tokenRefresh_failure":
          console.log("token refresh failed");
          break;
        case "autoSignIn":
          console.log("auto sign in");
          break;
        case "autoSignIn_failure":
          console.log("auto sign in failed");
          break;

        case "cognitoHostedUI_failure":
          console.log("cognito hosted ui failed");

          Auth.federatedSignIn({ provider: "Google" })
            .then(async (cred) => {
              // If success, you will get the AWS credentials
              console.log(cred);
              Auth.currentAuthenticatedUser({
                bypassCache: false, // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
              })
                .then((user) => {
                  console.log("got suer datal", user);
                  if (user?.username) {
                    console.log(
                      "usernname exists",
                      user.username.startsWith("google")
                    );
                    if (user.username.startsWith("google")) {
                      console.log("modifying the username");
                      user.username = user?.attributes.email.split("@")[0];
                    }
                    console.log("user autheticatd", user);
                    setAuthenticated(true);
                    rememberDevice();
                    setCurrentActiveUser(user);
                    store.dispatch(
                      getUserExistingAPIKey(
                        user?.signInUserSession?.idToken?.jwtToken
                      )
                    );
                    store.dispatch({
                      type: SET_ID_TOKEN,
                      payload: user?.signInUserSession?.idToken?.jwtToken,
                    });
                    // getExistingUserAPIKey(user?.signInUserSession?.idToken?.jwtToken);
                  }
                })
                .catch((e) => {
                  console.log("the first login failed");
                  console.log(e);
                });
            })
            .catch((e) => {
              console.log("the second login failed");
              console.log(e);
            });
          break;

        case "customState_failure":
          console.log("custom state failure", event, data);
          break;
        default:
          console.log("DEFAUL CASE", event, data);
          break;
      }
    });

    return unsubscribe;
  });

I receive a cognitoHostedUI event after signingIn. I tried to store data manually but it never persists when I open a new tab.

any help would be appreciated, seriously considering, getting off of cognito/amplify.