问:
Unable to shift to second tab in java selenium
Every thing works fine but the webdriver is not shifting focus to second tab after opening yopmail earlier shifting from one window and focussing from one window is working fine but focus on second tab is not working I am using arraylist for this rest of the codes is fine only focussing on second tab is not working</p>
```<code>package Rolesandpermissions;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class Inviteuserbyemail {
    public static void main(String[] args) throws InterruptedException, AWTException {
        System.setProperty("webdriver.chrome.driver", "Path to chromedriver");
        WebDriver driver = new ChromeDriver();
        String windowHandle = driver.getWindowHandle();
        driver.get("URL");
        driver.navigate().forward();
        driver.manage().window().maximize();
        driver.navigate().forward();
        driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*[@id=\"formBasicEmail\"]")).sendKeys("good@yopmail.com");
        driver.navigate().forward();
        driver.findElement(By.name("password")).sendKeys("Qwerty@10");
        driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
        driver.navigate().forward();
        driver.findElement(By.className("checkmark")).click();
        driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div/div[1]/div/div/form/button")).click();
        driver.navigate().forward();
        Thread.sleep(7000);
        driver.findElement(By.xpath("/html/body/div/div/div[1]/ul/li[2]/a")).click();
        Thread.sleep(4000);
        driver.findElement(By.xpath("/html/body/div/div/div[2]/div[3]/div/div/div/div")).click();
        driver.navigate().forward();
        Thread.sleep(8000);
        driver.findElement(By.xpath("//button[@class=\"NewUserWrap secondaryBtn\"]")).click();
        Thread.sleep(2000);
        driver.findElement(By.name("email")).sendKeys("Hond@yopmail.com");
        Thread.sleep(2000);
        driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[2]/div[2]/div/div/div[1]/input[1]")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[2]/div[2]/div/div/div[2]/a[6]")).click();
        driver.findElement(By.id("teams")).click();
        Thread.sleep(5000);
        driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[2]/div[3]/div/div/div/div/div/span[1]")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//button[@class=\"btn btn-primary\"]")).click();
        Thread.sleep(2000);
        driver.manage().deleteAllCookies();
        // If you want to sign out //
        driver.findElement(By.xpath("//img[@class=\"rounded-circle\"]")).click();
        driver.findElement(By.xpath("//a[@href=\"#\"]")).click();
        Thread.sleep(2000);
        driver.switchTo().newWindow(WindowType.WINDOW);
        // User has received invitation //
        driver.get("http://www.yopmail.com");
        driver.findElement(By.xpath("//*[@id=\"login\"]")).sendKeys("Bond@yopmail.com"); //replace the test email
        driver.findElement(By.xpath("/html/body/div[1]/div[2]/main/div[3]/div/div[1]/div[2]/div/div/form/div/div/div[4]/button/i\n")).click();
        Thread.sleep(4000);
        driver.manage().window().maximize();
        driver.switchTo().frame("ifmail");
        driver.findElement(By.linkText("URL")).click();
        ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs2.get(1));
        driver.navigate().forward();
        Thread.sleep(8000);
        driver.findElement(By.className("form-control")).sendKeys("Victorious");
        Thread.sleep(4000);
        driver.findElement(By.name("email")).sendKeys("Bond@yopmail.com");
        Thread.sleep(2000);
        driver.findElement(By.className("checkmark")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div[1]/div/div/form/button")).click();
        //driver.findElement(By.xpath("/html/body/div/div/div[2]/div/div/div[1]/div/div/p/a")).click();
        driver.navigate().forward();
        driver.findElement(By.xpath("//*[@id=\"fullName\"]")).sendKeys("Victorious");
        driver.navigate().forward();
        driver.findElement(By.name("email")).sendKeys("Bond@yopmail.com");
        driver.navigate().forward();
        driver.findElement(By.className("checkmark")).click();
        driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div[1]/div/div/form/button")).click();
        //perform other operations.
        Robot r = new Robot();
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_T);
        r.keyRelease(KeyEvent.VK_CONTROL);
        r.keyRelease(KeyEvent.VK_T);
        driver.switchTo().window(tabs2.get(0));
        driver.get("http://www.yopmail.com");
        driver.findElement(By.xpath("//*[@id=\"login\"]")).sendKeys("Bond@yopmail.com"); //replace the test email
        driver.findElement(By.xpath("/html/body/div[1]/div[2]/main/div[3]/div/div[1]/div[2]/div/div/form/div/div/div[4]/button/i\n")).click();
        driver.switchTo().frame("ifmail");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        String strCode = driver.findElement(By.xpath("//*[@id=\"mail\"]/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/table/tbody/tr[5]/td/span")).getText(); //replace the locator for verification code
        System.out.println("----------------");
        System.out.println(strCode);
        System.out.println("----------------");
        Actions actions = new Actions(driver);
        actions.sendKeys(Keys.chord(Keys.LEFT_CONTROL, "c")).build().perform();
        driver.switchTo().window(tabs2.get(1));
        //driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        driver.navigate().forward();
         driver.findElement(By.id("code1")).sendKeys(strCode);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        int i;
        for (i = 1; i <= 6; i++) {
            driver.navigate().forward();
            driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
            driver.findElement(By.xpath("//button[@class=\"otp btn btn-primary\"]")).click();
            driver.navigate().forward();
            driver.findElement(By.xpath("//input[@name=\"newPassword\"]")).sendKeys("Qwerty@10");
            driver.navigate().forward();
            driver.findElement(By.xpath("//input[@name=\"comfirmNewPass\"] ")).sendKeys("Qwerty@10");
            driver.navigate().forward();
            driver.findElement(By.xpath("//button[@class=\"otp btn btn-primary\"]")).click();
            driver.navigate().forward();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.findElement(By.name("email")).sendKeys("Bond@yopmail.com");
            driver.navigate().forward();
            driver.findElement(By.name("password")).sendKeys("Qwerty@10");
            driver.navigate().forward();
            driver.findElement(By.xpath("//span[@class=\"checkmark\"]")).click();
            driver.navigate().forward();
            driver.findElement(By.xpath("//button[@class=\"btn btn-primary\"]")).click();
            Thread.sleep(1000);
            driver.findElement(By.xpath("/html/body/div/div/div[1]/ul/li[1]/a")).click();
            //New Team Creation //
            /*driver.findElement(By.xpath("(//span[@class=\"toggleHide\"])[2]")).click();
            Thread.sleep(2000);
            driver.findElement(By.xpath("//button[@class=\"NewUserWrap secondaryBtn\"]")).click();
            Thread.sleep(2000);
            driver.findElement(By.name("teamLogo")).sendKeys("tunnel.jpg");
            Thread.sleep(2000);
            driver.findElement(By.name("name")).sendKeys("Great");
            Thread.sleep(2000);
            driver.findElement(By.xpath("//textarea[@name=\"description\"]")).sendKeys("T");
            Thread.sleep(4000);
            driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[3]/button[2]")).click();*/
            // User click on joining a team //
            Thread.sleep(4000);
            driver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div[2]/span/div/button")).click();

        }
    }
}
</code>```

Body:
Every thing works fine but the webdriver is not shifting focus to second tab after opening yopmail earlier shifting from one window and focussing from one window is working fine but focus on second tab is not working I am using arraylist for this rest of the codes is fine only focussing on second tab is not working

package Rolesandpermissions;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class Inviteuserbyemail {
    public static void main(String[] args) throws InterruptedException, AWTException {
        System.setProperty("webdriver.chrome.driver", "Path to chromedriver");
        WebDriver driver = new ChromeDriver();
        String windowHandle = driver.getWindowHandle();
        driver.get("URL");
        driver.navigate().forward();
        driver.manage().window().maximize();
        driver.navigate().forward();
        driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*[@id=\"formBasicEmail\"]")).sendKeys("good@yopmail.com");
        driver.navigate().forward();
        driver.findElement(By.name("password")).sendKeys("Qwerty@10");
        driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
        driver.navigate().forward();
        driver.findElement(By.className("checkmark")).click();
        driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div/div[1]/div/div/form/button")).click();
        driver.navigate().forward();
        Thread.sleep(7000);
        driver.findElement(By.xpath("/html/body/div/div/div[1]/ul/li[2]/a")).click();
        Thread.sleep(4000);
        driver.findElement(By.xpath("/html/body/div/div/div[2]/div[3]/div/div/div/div")).click();
        driver.navigate().forward();
        Thread.sleep(8000);
        driver.findElement(By.xpath("//button[@class=\"NewUserWrap secondaryBtn\"]")).click();
        Thread.sleep(2000);
        driver.findElement(By.name("email")).sendKeys("Hond@yopmail.com");
        Thread.sleep(2000);
        driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[2]/div[2]/div/div/div[1]/input[1]")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[2]/div[2]/div/div/div[2]/a[6]")).click();
        driver.findElement(By.id("teams")).click();
        Thread.sleep(5000);
        driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[2]/div[3]/div/div/div/div/div/span[1]")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//button[@class=\"btn btn-primary\"]")).click();
        Thread.sleep(2000);
        driver.manage().deleteAllCookies();
        // If you want to sign out //
        driver.findElement(By.xpath("//img[@class=\"rounded-circle\"]")).click();
        driver.findElement(By.xpath("//a[@href=\"#\"]")).click();
        Thread.sleep(2000);
        driver.switchTo().newWindow(WindowType.WINDOW);
        // User has received invitation //
        driver.get("http://www.yopmail.com");
        driver.findElement(By.xpath("//*[@id=\"login\"]")).sendKeys("Bond@yopmail.com"); //replace the test email
        driver.findElement(By.xpath("/html/body/div[1]/div[2]/main/div[3]/div/div[1]/div[2]/div/div/form/div/div/div[4]/button/i\n")).click();
        Thread.sleep(4000);
        driver.manage().window().maximize();
        driver.switchTo().frame("ifmail");
        driver.findElement(By.linkText("URL")).click();
        ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs2.get(1));
        driver.navigate().forward();
        Thread.sleep(8000);
        driver.findElement(By.className("form-control")).sendKeys("Victorious");
        Thread.sleep(4000);
        driver.findElement(By.name("email")).sendKeys("Bond@yopmail.com");
        Thread.sleep(2000);
        driver.findElement(By.className("checkmark")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div[1]/div/div/form/button")).click();
        //driver.findElement(By.xpath("/html/body/div/div/div[2]/div/div/div[1]/div/div/p/a")).click();
        driver.navigate().forward();
        driver.findElement(By.xpath("//*[@id=\"fullName\"]")).sendKeys("Victorious");
        driver.navigate().forward();
        driver.findElement(By.name("email")).sendKeys("Bond@yopmail.com");
        driver.navigate().forward();
        driver.findElement(By.className("checkmark")).click();
        driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div[1]/div/div/form/button")).click();
        //perform other operations.
        Robot r = new Robot();
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_T);
        r.keyRelease(KeyEvent.VK_CONTROL);
        r.keyRelease(KeyEvent.VK_T);
        driver.switchTo().window(tabs2.get(0));
        driver.get("http://www.yopmail.com");
        driver.findElement(By.xpath("//*[@id=\"login\"]")).sendKeys("Bond@yopmail.com"); //replace the test email
        driver.findElement(By.xpath("/html/body/div[1]/div[2]/main/div[3]/div/div[1]/div[2]/div/div/form/div/div/div[4]/button/i\n")).click();
        driver.switchTo().frame("ifmail");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        String strCode = driver.findElement(By.xpath("//*[@id=\"mail\"]/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/table/tbody/tr[5]/td/span")).getText(); //replace the locator for verification code
        System.out.println("----------------");
        System.out.println(strCode);
        System.out.println("----------------");
        Actions actions = new Actions(driver);
        actions.sendKeys(Keys.chord(Keys.LEFT_CONTROL, "c")).build().perform();
        driver.switchTo().window(tabs2.get(1));
        //driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        driver.navigate().forward();
         driver.findElement(By.id("code1")).sendKeys(strCode);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        int i;
        for (i = 1; i <= 6; i++) {
            driver.navigate().forward();
            driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
            driver.findElement(By.xpath("//button[@class=\"otp btn btn-primary\"]")).click();
            driver.navigate().forward();
            driver.findElement(By.xpath("//input[@name=\"newPassword\"]")).sendKeys("Qwerty@10");
            driver.navigate().forward();
            driver.findElement(By.xpath("//input[@name=\"comfirmNewPass\"] ")).sendKeys("Qwerty@10");
            driver.navigate().forward();
            driver.findElement(By.xpath("//button[@class=\"otp btn btn-primary\"]")).click();
            driver.navigate().forward();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.findElement(By.name("email")).sendKeys("Bond@yopmail.com");
            driver.navigate().forward();
            driver.findElement(By.name("password")).sendKeys("Qwerty@10");
            driver.navigate().forward();
            driver.findElement(By.xpath("//span[@class=\"checkmark\"]")).click();
            driver.navigate().forward();
            driver.findElement(By.xpath("//button[@class=\"btn btn-primary\"]")).click();
            Thread.sleep(1000);
            driver.findElement(By.xpath("/html/body/div/div/div[1]/ul/li[1]/a")).click();
            //New Team Creation //
            /*driver.findElement(By.xpath("(//span[@class=\"toggleHide\"])[2]")).click();
            Thread.sleep(2000);
            driver.findElement(By.xpath("//button[@class=\"NewUserWrap secondaryBtn\"]")).click();
            Thread.sleep(2000);
            driver.findElement(By.name("teamLogo")).sendKeys("tunnel.jpg");
            Thread.sleep(2000);
            driver.findElement(By.name("name")).sendKeys("Great");
            Thread.sleep(2000);
            driver.findElement(By.xpath("//textarea[@name=\"description\"]")).sendKeys("T");
            Thread.sleep(4000);
            driver.findElement(By.xpath("/html/body/div[3]/div/div/form/div[3]/button[2]")).click();*/
            // User click on joining a team //
            Thread.sleep(4000);
            driver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div[2]/span/div/button")).click();

        }
    }
}


来源: stackexchange

问:
Raspberry PI camera stream, ethernet communication
I am trying to use Rpi PI 4 for video stream. I used some example from web attached below. This program create server from Rpi and when i write IP of Rpi to my browser and have Rpi and PC on the same network i can se realtime stream from this camera. Then i want to send some data via ethernet from PC to rpi for example some commands for servo which will control the camera rotation. I have two program which work properly.But when i want to run this application as one program (Thread for stream and for message recceiver from PC) i always got error adress already in use. That seems logic. Is there some suitable option how to do what i want or i must choose different way of solution?

Camera stream on Rpi

```<code>import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\
<html>
<head>
<title>Raspberry Pi - Surveillance Camera</title>
</head>
<body>
<center><h1>Raspberry Pi - Surveillance Camera</h1></center>
<center><img src="stream.mjpg" width="640" height="480"></center>
</body>
</html>
"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
    output = StreamingOutput()
    #Uncomment the next line to change your Pi's Camera rotation (in degrees)
    #camera.rotation = 90
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()
</code>```

PC send msg to Rpi

```<code>import socket
from picamera import PiCamera
from time import sleep

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.1.145',8000)
sock.bind(server_address)
sock.listen(1)

while 1:
    connection, client_address = sock.accept()
    try:
        message = connection.recv(1024)
        message = message.decode('utf-8')
        print(f'Accepted msg from pc {client_address}: {message}')
    finally:
        connection.close()

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use Rpi PI 4 for video stream. I used some example from web attached below. This program create server from Rpi and when i write IP of Rpi to my browser and have Rpi and PC on the same network i can se realtime stream from this camera. Then i want to send some data via ethernet from PC to rpi for example some commands for servo which will control the camera rotation. I have two program which work properly.But when i want to run this application as one program (Thread for stream and for message recceiver from PC) i always got error adress already in use. That seems logic. Is there some suitable option how to do what i want or i must choose different way of solution?

Camera stream on Rpi

import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\

<title>Raspberry Pi - Surveillance Camera</title>

Raspberry Pi - Surveillance Camera

"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
    output = StreamingOutput()
    #Uncomment the next line to change your Pi's Camera rotation (in degrees)
    #camera.rotation = 90
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()

PC send msg to Rpi

import socket
from picamera import PiCamera
from time import sleep

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.1.145',8000)
sock.bind(server_address)
sock.listen(1)

while 1:
    connection, client_address = sock.accept()
    try:
        message = connection.recv(1024)
        message = message.decode('utf-8')
        print(f'Accepted msg from pc {client_address}: {message}')
    finally:
        connection.close()


问:
Can't run background thread locally
I working on a task from my textbook and it suggests to make two thread main and background one. But browsers cannot load data from local device for background thread, can they? What do I do in this scenario?

I tried using Google Chrome, IE, FireFox, it is still the same result, but in FireFox it says:

```<code>Security Error: Content at file:///C:/Users/Professional/Downloads/FTP/12/ex12.3/12.3.html may not load data from file:///C:/Users/Professional/Downloads/FTP/12/ex12.3/12.3.js.
</code>```

Title: Can't run background thread locally

Body:
I working on a task from my textbook and it suggests to make two thread main and background one. But browsers cannot load data from local device for background thread, can they? What do I do in this scenario?

I tried using Google Chrome, IE, FireFox, it is still the same result, but in FireFox it says:

Security Error: Content at file:///C:/Users/Professional/Downloads/FTP/12/ex12.3/12.3.html may not load data from file:///C:/Users/Professional/Downloads/FTP/12/ex12.3/12.3.js.


问:
The Pound Sign (#) in TextArea
Having a pound sign (#) in the textarea cause some problems when downloading the whole text in it.

I have this code:

```<code><form>
  some input: <input type="text" id ="input"/>
  <input type="button" value="Submit" onclick="f1();"/>
</form>
<div class="preview">
  This is some input:<br/>
  <textarea id="generatedCode"></textarea><br/>
  <input type="button" value="Download" onclick="f2();"/>
</div>
</code>```
```<code><script>
function f1(){
  var input = document.getElementById('input');
  var generatedCode = document.getElementById('generatedCode');
  generatedCode.innerHTML = input.value
}

function f2(){
const content = document.getElementById("generatedCode").value;
  var save = document.createElement("a");
  save.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURI(content));
  save.setAttribute("download", content.slice(0, 17) + ".txt");
  document.body.appendChild(save);
  save.click();
  document.body.removeChild(save);
}
</script>
</code>```

Whenever you input some text with and a "#" then another text, then download it. The downloaded got no "#" and the remaining text. This cause me a problem. I'd like to download the whole text in textarea including the "#" and the remaining text.

Title: The Pound Sign (#) in TextArea

Body:
Having a pound sign (#) in the textarea cause some problems when downloading the whole text in it.

I have this code:

<form>
  some input: <input type="text" id ="input"/>
  <input type="button" value="Submit" onclick="f1();"/>
</form>

  This is some input:

  <textarea id="generatedCode"></textarea>

  <input type="button" value="Download" onclick="f2();"/>

Whenever you input some text with and a "#" then another text, then download it. The downloaded got no "#" and the remaining text. This cause me a problem. I'd like to download the whole text in textarea including the "#" and the remaining text.


问:
event function fires multiple times if i add setState of another value
I am writing a carousel with a swipe like in tinder, and if I add to event method line that changes some state, my function is called multiple times and request called multiple times to.

```<code>const \[currentIndex, setCurrentIndex\] = useState(0);

...

const handleSwipe = (direction: string, i: number) => {
    setCurrentIndex((i) => i - 1);
      switch (direction) {
        case 'right':
          sendKnowReq(i);
          break;
        case 'left':
          sendDontKnowReq(i);
          break;
        default:
          break;
        }
  };
</code>```

If i commentsetCurrentIndexit works fine and Request will go only one time

```<code><TinderCard
  ref={childRefs[i]}
  className={`absolute `}
  key={i}
  onSwipe={(direction) =\> handleSwipe(direction, i)}
  preventSwipe={['up', 'down']}
>
...
</TinderCard>
</code>```

how to fix this problem with updating states from method that was called from TinderCard

Body:
I am writing a carousel with a swipe like in tinder, and if I add to event method line that changes some state, my function is called multiple times and request called multiple times to.

const \[currentIndex, setCurrentIndex\] = useState(0);

...

const handleSwipe = (direction: string, i: number) => {
    setCurrentIndex((i) => i - 1);
      switch (direction) {
        case 'right':
          sendKnowReq(i);
          break;
        case 'left':
          sendDontKnowReq(i);
          break;
        default:
          break;
        }
  };

If i commentsetCurrentIndexit works fine and Request will go only one time

<TinderCard
  ref={childRefs[i]}
  className={`absolute `}
  key={i}
  onSwipe={(direction) =\> handleSwipe(direction, i)}
  preventSwipe={['up', 'down']}
>
...
</TinderCard>

how to fix this problem with updating states from method that was called from TinderCard


问:
Null Http Request Header 'Authorization' Value in spring boot application when deployed on Elastic Beanstalk
I am working on a Spring Boot Application which is deployed on AWS Elastic Beanstalk. I implemented JWT Authentication where we pass Authorization key in header with Bearer token. The problem is; when we run it locally, it works but on elastic beanstalk, Authorization header is dropped and I get Nptr exception.

when I run the application locally and send request from Postman, I get these headers in the application:

Http Request Headers:

authorization: Bearer

user-agent: PostmanRuntime/7.30.0

accept: /

postman-token:

host: localhost:8080

accept-encoding: gzip, deflate, br

connection: keep-alive

cookie:

But
When I deploy it on Elastic Beanstalk and send request from Postman, I get the following headers except Authorization header that's required to store jwt-token.

connection: upgrade

host: 172.31.27.65

x-real-ip: 172.31.44.173

x-forwarded-for: 172.31.44.173

user-agent: ELB-HealthChecker/2.0

accept-encoding: gzip, compressed

It seems like Elastic Application Load Balancer is dropping original request headers and instead adding its headers in the request.


问:
Glue and EC2: Closing network interfaces not in use
I have a glue job with a connection to get data from SAS. Everytime it runs, it opens a network interface, and when the job got finished, the network interface continues there. It congests my subnet.

How can I delete these networks interfaces after the job got finished? I have no idea how to do that, even when I search on google I find nothing. May you guys help me, please?


问:
The requested array has an inhomogeneous shape after 2 dimensions
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (56, 2) + inhomogeneous part.

pycharm console

# create training data
training = []
# create empty array for classes
output_empty = [0] * len(classes)
# training set, bag of words for each sentence
for document in documents:
    # initialize bag of words
    bag = []
    # list of tokenized words for the pattern
    pattern_words = document[0]
    # lemmatize each word
    pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]
    # create orur bag of words array with 1 if word match found in current pattern
    for word in words:
        bag.append(1) if word in pattern_words else bag.append(0)
    # output is 0 for each tag and 1 for current tag (for each pattern)
    output_row = list(output_empty)
    output_row[classes.index(document[1])] = 1
    training.append([bag, output_row])
# shuffle our features and turn into np.array
random.shuffle(training)
training = np.array(training)
# create train and test lists. X - patterns, Y - intents
train_x = list(training[:, 0])
train_y = list(training[:, 1])

# create model - 3 layers. First layer 128 neurons, second layer 64 neurons
# 3rd output layer contains number of neurons
# equal to number of intents to predicct output intent with softmax
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(64, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation="softmax"))

sgd = gradient_descent_v2.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])

hist = model.fit(
    np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1
)
model.save("chatbot_model.h5", hist)
print("Done")
'''
```


问:
why input checkbox conditional css is not working in firefox browser
I have created the minimized test file for the tabbing layout.
the functionality for this tabbing layout is done with the CSS code has(input:not(:checked)) + div.tab.

the HTML test file code is as below.

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        div.tab-container {
            background: red;
            height: 500px;
            width: 100%;
            position: relative;
        }

        label.tab {
            background: yellow;
            margin: 5px 5px;
            height: 20px;
            padding: 5px;
            width: 31%;
            display: inline-block;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
        }

        div.tab {
            background: green;
            position: absolute;
            right: 0;
            height: 100%;
        }

        div.tab-container > div.tab { /* horizontally stacked tabs on top */
            height: calc(100% - 45px);
            background: skyblue;
            font-size: 30px;
            width: 98%;
            display: flex;
            left: 1%;
            align-items: center;
            justify-content: center;
        }

        div.tab-container > div > div.tab { /* vertically stacked tabs on the left */
            width: 80%;
            background: blue;
            top: 10px;
        }

        label.tab > input {
            /* display: none; */
        }

        label.tab:has(input:not(:checked)) + div.tab {
            display: none;
        }
    </style>
  </head>

  <body>
    <div class="tab-container">
      <label class="tab">
        Tab 1
        <input type="radio" onclick="console.log('1st tab')" name="tab-input" checked="checked"/>
      </label>
      <div class="tab">
        First Tab
      </div>
      <label class="tab">
        Tab 2
        <input type="radio" onclick="console.log('2nd tab')" name="tab-input"/>
      </label>
      <div class="tab">
        Second Tab
      </div>
      <label class="tab">
        Tab 3
        <input type="radio" onclick="console.log('3rd tab')" name="tab-input"/>
      </label>
      <div class="tab">
        Third Tab
      </div>
    </div>
  </body>
</html>

</code>```

This is working fine with chrome and Microsoft edge but not in firefox can anyone resolve this issue?

Body:
I have created the minimized test file for the tabbing layout.
the functionality for this tabbing layout is done with the CSS code has(input:not(:checked)) + div.tab.

the HTML test file code is as below.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

        Tab 1
        <input type="radio" onclick="console.log('1st tab')" name="tab-input" checked="checked"/>

        First Tab

        Tab 2
        <input type="radio" onclick="console.log('2nd tab')" name="tab-input"/>

        Second Tab

        Tab 3
        <input type="radio" onclick="console.log('3rd tab')" name="tab-input"/>

        Third Tab

This is working fine with chrome and Microsoft edge but not in firefox can anyone resolve this issue?


问:
Is there a reason I can't get the correct distance of an object from a distance sensor outside the sonar function?
I'm developing a simple project where I need to integrate different sensors and actuators to make them able to interact with themselves but I'm  having a problem right at the start of the process. My first goal was to make a distance sensor work correctly by showing me the correct distance of an object placed in front of it. Depending of the value of said distance, an actuator like a LED would have different behaviors.
I'm using Tinkercad to test the distance sensor first, so this is my current design:

Ant this is my current code:

```<code>#define ECHO 9
#define TRIG 8
#define TRIGGER_GAP 100

int distance;
void setup()
{
    Serial.begin(9600);
      pinMode(TRIG, OUTPUT);
}

void loop()

{
  sonar();

  //Wrong Outputs
  //Serial.println(distance);

}

void Trigger(byte pin){
  digitalWrite(pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pin, LOW);
}

void sonar(){
  static const int REPOUSO=0, ESPERA_ECHO=1, ESPERA_ECHO_HIGH=2, ESPERA_ECHO_LOW=3;
  static int state=REPOUSO;
  static unsigned long t0=millis(),t0echo;
  unsigned long t1, t1echo;

  switch(state){
    case REPOUSO:

t1 = millis();

if(t1 - t0 >= TRIGGER_GAP){
  Trigger(TRIG);
  t0 = t1;
  state = ESPERA_ECHO;
}
break;

case ESPERA_ECHO:
if (digitalRead(ECHO)==LOW){
  Trigger(TRIG);
  state = ESPERA_ECHO_HIGH;
}
break;

case ESPERA_ECHO_HIGH:
if(digitalRead(ECHO)==HIGH){
  t0echo = micros();
  state = ESPERA_ECHO_LOW;
}
break;

case ESPERA_ECHO_LOW:
t1 = millis();
if(digitalRead(ECHO)==LOW){
  t1echo = micros();

  distance = (t1echo- t0echo)/58.0;
  //Correct Outputs
  Serial.println(distance);

  state = REPOUSO;
  break;

}

else{
  if(t1-t0>=TRIGGER_GAP){
    state = REPOUSO;
  }

}

break;
  }

}
</code>```

The distance variable is supposed to be global because it will be the one that will be given to an actuator like a LED to affect its behavior. When I use the Serial.println(distance) function after the "Correct Outputs" commented line, the distance values make sense and change accordingly with the changes of the object's position, but if I comment that Serial.println() line and uncomment the one after the line that says "Wrong Outputs", the distance values make no sense and sometimes are still the same even if I move the object, which makes it impossible for an actuator to act correctly because the distance values are also incorrect. I've gone through this code many times and tried to search for some similar problems but unsuccessfully.

Is there a reason why somehow the distance variable only has the right values only when I print them inside the if clause where the comment "Correct Outputs" is? Because even if I print the variable inside the case "ESPERA_ECHO_LOW", the console will output the same wrong values just like when I print after the sonar() line inside the loop function.

Sorry if its confusing, but the fact that the distance variable isn't outputting the correct distance values makes it impossible for me to continue to develop this project.

Thanks in advance.

Body:
I'm developing a simple project where I need to integrate different sensors and actuators to make them able to interact with themselves but I'm  having a problem right at the start of the process. My first goal was to make a distance sensor work correctly by showing me the correct distance of an object placed in front of it. Depending of the value of said distance, an actuator like a LED would have different behaviors.
I'm using Tinkercad to test the distance sensor first, so this is my current design:

Ant this is my current code:

#define ECHO 9
#define TRIG 8
#define TRIGGER_GAP 100

int distance;
void setup()
{
    Serial.begin(9600);
      pinMode(TRIG, OUTPUT);
}

void loop()

{
  sonar();

  //Wrong Outputs
  //Serial.println(distance);

}

void Trigger(byte pin){
  digitalWrite(pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pin, LOW);
}

void sonar(){
  static const int REPOUSO=0, ESPERA_ECHO=1, ESPERA_ECHO_HIGH=2, ESPERA_ECHO_LOW=3;
  static int state=REPOUSO;
  static unsigned long t0=millis(),t0echo;
  unsigned long t1, t1echo;

  switch(state){
    case REPOUSO:

t1 = millis();

if(t1 - t0 >= TRIGGER_GAP){
  Trigger(TRIG);
  t0 = t1;
  state = ESPERA_ECHO;
}
break;

case ESPERA_ECHO:
if (digitalRead(ECHO)==LOW){
  Trigger(TRIG);
  state = ESPERA_ECHO_HIGH;
}
break;

case ESPERA_ECHO_HIGH:
if(digitalRead(ECHO)==HIGH){
  t0echo = micros();
  state = ESPERA_ECHO_LOW;
}
break;

case ESPERA_ECHO_LOW:
t1 = millis();
if(digitalRead(ECHO)==LOW){
  t1echo = micros();

  distance = (t1echo- t0echo)/58.0;
  //Correct Outputs
  Serial.println(distance);

  state = REPOUSO;
  break;

}

else{
  if(t1-t0>=TRIGGER_GAP){
    state = REPOUSO;
  }

}

break;
  }

}

The distance variable is supposed to be global because it will be the one that will be given to an actuator like a LED to affect its behavior. When I use the Serial.println(distance) function after the "Correct Outputs" commented line, the distance values make sense and change accordingly with the changes of the object's position, but if I comment that Serial.println() line and uncomment the one after the line that says "Wrong Outputs", the distance values make no sense and sometimes are still the same even if I move the object, which makes it impossible for an actuator to act correctly because the distance values are also incorrect. I've gone through this code many times and tried to search for some similar problems but unsuccessfully.

Is there a reason why somehow the distance variable only has the right values only when I print them inside the if clause where the comment "Correct Outputs" is? Because even if I print the variable inside the case "ESPERA_ECHO_LOW", the console will output the same wrong values just like when I print after the sonar() line inside the loop function.

Sorry if its confusing, but the fact that the distance variable isn't outputting the correct distance values makes it impossible for me to continue to develop this project.

Thanks in advance.


问:
Reading / Writing custom file attributes with C++/Java
I am implementing a simple Windows Overlay Icon Handler in C++ and I want to decide with a property of the document whether to show overlay icons or not. However, this property will be a custom property and will be given with my Java application. Below you can see a piece of sample Java code. Is it possible to read this property that I set in Java with C++?

```<code>try {
     Files.setAttribute(Paths.get("my file path"), "user:status", "10".getBytes("UTF-8"));
} catch (IOException exception) {
     exception.printStackTrace();
}
</code>```

I tried the property example from windows tutorial here. but that code only giving me system attributes. You can see the output of this code below sample output

I'm trying the read that custom attribute of file on overlay icon handler and decide whether to show overlay icons or not. I guess my C++ method would look like this.

```<code>HRESULT __stdcall CIconHandler::IsMemberOf(LPCWSTR pwszPath, DWORD dwAttrib)
{
   //get file attributes
   // read user:status attribute value
   // if (value = 15) {show icon}
   // else { don't show icon }
}
</code>```

And if you have other solutions or suggestion for this operation I'm open for them.

Body:
I am implementing a simple Windows Overlay Icon Handler in C++ and I want to decide with a property of the document whether to show overlay icons or not. However, this property will be a custom property and will be given with my Java application. Below you can see a piece of sample Java code. Is it possible to read this property that I set in Java with C++?

try {
     Files.setAttribute(Paths.get("my file path"), "user:status", "10".getBytes("UTF-8"));
} catch (IOException exception) {
     exception.printStackTrace();
}

I tried the property example from windows tutorial here. but that code only giving me system attributes. You can see the output of this code below sample output

I'm trying the read that custom attribute of file on overlay icon handler and decide whether to show overlay icons or not. I guess my C++ method would look like this.

HRESULT __stdcall CIconHandler::IsMemberOf(LPCWSTR pwszPath, DWORD dwAttrib)
{
   //get file attributes
   // read user:status attribute value
   // if (value = 15) {show icon}
   // else { don't show icon }
}

And if you have other solutions or suggestion for this operation I'm open for them.


问:
How can I remove this text in my integrated terminal?
This is my terminal currently:

I tried removing the file path using code-runner's settings

```<code>@ext:formulahendry.code-runner
</code>```

then add

```<code>cls &&
</code>```

to both c and c++ file paths. When I saved and run my code again, the file path was gone, most of it. For some reason this text still pops up, how can I remove this in my terminal?

Body:
This is my terminal currently:

I tried removing the file path using code-runner's settings

@ext:formulahendry.code-runner

then add

cls &&

to both c and c++ file paths. When I saved and run my code again, the file path was gone, most of it. For some reason this text still pops up, how can I remove this in my terminal?


问:
buildscript errors in the build.gradle file at android studio dolphin
This is the error that doesn't want to be corected. I see the syntax so i remove the bracket and even gave the entire file to chat gbt3 online ai for correction but nothing I have done works. I started new application and "borrowed" the settings.gradle file from that via my notes system - no joy
The error occuring.
12:16   Gradle sync failed: Could not get unknown property 'implementation' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. (3 s 580 ms)

Here it is

```<code>        apply plugin: 'com.android.application'
</code>```

android {
compileSdkVersion 29

```<code>defaultConfig {
    applicationId "com.gradedwash.mergedimage"
    minSdkVersion 29
    targetSdkVersion 33
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
</code>```

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation
'androidx'
}

I tried to make an application for google play using android studio dolphin in a linux environment with python 3 sdk 29 to 33 all latest versions. The app sends two images to dall-e2 and returns to mobile phone or any device

Body:
This is the error that doesn't want to be corected. I see the syntax so i remove the bracket and even gave the entire file to chat gbt3 online ai for correction but nothing I have done works. I started new application and "borrowed" the settings.gradle file from that via my notes system - no joy
The error occuring.
12:16   Gradle sync failed: Could not get unknown property 'implementation' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. (3 s 580 ms)

Here it is

        apply plugin: 'com.android.application'

android {
compileSdkVersion 29

defaultConfig {
    applicationId "com.gradedwash.mergedimage"
    minSdkVersion 29
    targetSdkVersion 33
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation
'androidx'
}

I tried to make an application for google play using android studio dolphin in a linux environment with python 3 sdk 29 to 33 all latest versions. The app sends two images to dall-e2 and returns to mobile phone or any device


问:
React Native | Wrap word in element from array
I am trying to create a method in React Native which takes a string argument and then loops through in order to search for a certain criteria and wrap it in another element so we can create an onPress event to show some more information about that word in particular.

An example being the following:

Discovery.tsx

```<code>interface Needle {
    criteria: string;
    description: string;
}

interface DiscoveryProps {
    haystack: string;
    needles: Needle[];
}

const Discovery = (props: DiscoveryProps) => {
   const onNeedlePress = (needle: Needle) => {
      console.log(needle.description);
   }

   return (
      <View>
         <Text>{ props.haystack }</Text>
      </View>
   )
}
</code>```

App.tsx

```<code>const App = () => {
    return (
       <View>
         <Discovery
             haystack="This is my string"
             needles={[
                 { criteria: "This", description: "This is an example" },
                 { criteria: "string", description: "This is a string example" }
             ]}
         />
       </View>
    )
}
</code>```

In the above example above, realistically what should be rendered is the following:

```<code><Text><TouchableOpacity onPress={() => onNeedlePress(...)}><Text>This</Text></TouchableOpacity> is my <TouchableOpacity onPress={() => onNeedlePress(...)}><Text>string</Text></TouchableOpacity></Text>
</code>```

I have managed to do somewhat a proof of concept however, I don't think it's ideal or performant.

```<code>interface Needle {
    criteria: string;
    description: string;
}

interface DiscoveryProps {
    haystack: string;
    needles: Needle[];
}

const Discovery = (props: DiscoveryProps) => {
   const onNeedlePress = (needle: Needle) => {
      console.log(needle.description);
   }

   const discover = (sentence: string) => {
      return sentence.map(word => {
          const needle = props.needles.find(n => n.criteria === word);

          if (!! needle) {
              return <TouchableOpacity onPress={() => onNeedlePress(needle)}><Text>{ word }</Text></TouchableOpacity>
          }

          return <Text>{ word }</Text>
      });
   }

   return discover(props.haystack);
}
</code>```

This above works, but it has a few issues.

The issues I experience with this is that it is produced like the following:

```<code>This
is
my
string
</code>```

I can change the flex direction to row and it produces like this:

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

I really want to avoid adding custom spacing and margins to the text object, as you can imagine. 100 words = 100 Text Elements and I imagine this would not be performant.

Body:
I am trying to create a method in React Native which takes a string argument and then loops through in order to search for a certain criteria and wrap it in another element so we can create an onPress event to show some more information about that word in particular.

An example being the following:

Discovery.tsx

interface Needle {
    criteria: string;
    description: string;
}

interface DiscoveryProps {
    haystack: string;
    needles: Needle[];
}

const Discovery = (props: DiscoveryProps) => {
   const onNeedlePress = (needle: Needle) => {
      console.log(needle.description);
   }

   return (
      <View>
         <Text>{ props.haystack }</Text>
      </View>
   )
}

App.tsx

const App = () => {
    return (
       <View>
         <Discovery
             haystack="This is my string"
             needles={[
                 { criteria: "This", description: "This is an example" },
                 { criteria: "string", description: "This is a string example" }
             ]}
         />
       </View>
    )
}

In the above example above, realistically what should be rendered is the following:

<Text><TouchableOpacity onPress={() => onNeedlePress(...)}><Text>This</Text></TouchableOpacity> is my <TouchableOpacity onPress={() => onNeedlePress(...)}><Text>string</Text></TouchableOpacity></Text>

I have managed to do somewhat a proof of concept however, I don't think it's ideal or performant.

interface Needle {
    criteria: string;
    description: string;
}

interface DiscoveryProps {
    haystack: string;
    needles: Needle[];
}

const Discovery = (props: DiscoveryProps) => {
   const onNeedlePress = (needle: Needle) => {
      console.log(needle.description);
   }

   const discover = (sentence: string) => {
      return sentence.map(word => {
          const needle = props.needles.find(n => n.criteria === word);

          if (!! needle) {
              return <TouchableOpacity onPress={() => onNeedlePress(needle)}><Text>{ word }</Text></TouchableOpacity>
          }

          return <Text>{ word }</Text>
      });
   }

   return discover(props.haystack);
}

This above works, but it has a few issues.

The issues I experience with this is that it is produced like the following:

This
is
my
string

I can change the flex direction to row and it produces like this:

Thisismystring

I really want to avoid adding custom spacing and margins to the text object, as you can imagine. 100 words = 100 Text Elements and I imagine this would not be performant.


问:
Basic auth header inside object? - Redux Toolkit
Hello I am trying to use username and password from basic auth, inside the header of redux toolkit.

```<code>    const wooApiHeaders = {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${('ck_fc7b09682db7a150b872be7b421bee8b4ef8c75e:cs_0d0b75db96bb20a5bb8f24af6db8c09f19b146cd')}`,
    }

const baseUrl = 'https://stagemonkey.dk/kumau';

const createRequest = (url:any) => ({ url, headers: wooApiHeaders });

export const wooApi = createApi({
    reducerPath: 'wooApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getWoo: builder.query({
            query: () => createRequest('/wp-json/wc/v3/products')
        })
    })
})

export const {
    useGetWooQuery,
} = wooApi
</code>```

But it does not work

Tried to create a basic auth call but can't.

Body:
Hello I am trying to use username and password from basic auth, inside the header of redux toolkit.

    const wooApiHeaders = {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${('ck_fc7b09682db7a150b872be7b421bee8b4ef8c75e:cs_0d0b75db96bb20a5bb8f24af6db8c09f19b146cd')}`,
    }

const baseUrl = 'https://stagemonkey.dk/kumau';

const createRequest = (url:any) => ({ url, headers: wooApiHeaders });

export const wooApi = createApi({
    reducerPath: 'wooApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getWoo: builder.query({
            query: () => createRequest('/wp-json/wc/v3/products')
        })
    })
})

export const {
    useGetWooQuery,
} = wooApi

But it does not work

Tried to create a basic auth call but can't.


问:
How do use Firebase Cloud Messaging in the Firebase Functions?
How do use Firebase Cloud Messaging in the Firebase Functions?

I did try using getMessaging() to send the message but it also gave me issues so I will appreciate a quick workaround

I get the error below when I use the function attached

```<code>i  functions: Beginning execution of "Return"
>  {"structuredData":true,"severity":"INFO","message":"Hello logs!"}
>  { state: 'BwcRCA4UBAMTGRgNDxkHHBoBAAQMBw0CGBEaEAYNEh4' }
i  functions: Finished "Return" in 4.336959ms
>  {
>    dt: 'dScq50VpRQSl27s-ZPBB_Y:APA91bHM0VNORw1q_VndMQbKS_NTjk3Z2cCTwwrkrEAlpSjpS-5cvraUcj_Q3UV_Pqdtvwg-3BZGE--ShyR3pEr-4jwgPRwHZ4f5JD7Y4ZVkYIg0Rh4JpxEfjqIhCUujrEqCncoJU09Q'
>  }
>  /Users/thapeloradebe/functions/node_modules/firebase-admin/lib/app/firebase-namespace.js:131
>                  return _this.ensureApp(app).messaging();
>                                              ^
>
>  TypeError: _this.ensureApp(...).messaging is not a function
>      at Proxy.fn (/Users/thapeloradebe/functions/node_modules/firebase-admin/lib/app/firebase-namespace.js:131:45)
>      at /Users/thapeloradebe/functions/lib/index.js:25:21
>      at processTicksAndRejections (node:internal/process/task_queues:96:5)

</code>```

This below is my function

```<code>export const Return = functions.https.onRequest(async (request, response) =>{
  functions.logger.info("Hello logs!", { structuredData: true });

    console.log({state: request.query.state});
    db.ref(`states/${request.query.state}`).get().then(async (snapshot) => {
      const device_token = snapshot.val();
      console.log({'dt': device_token.token})
      const payload = {
        data: {
          state: request.query.state,
          bank_code: request.query.code
        },
      } as MessagingPayload;

      await admin.messaging(app).sendToDevice(device_token.token, payload)
        .then((response) => {
          console.log('Successfully sent message:', response.results);
        }).catch((error: Error) => {
          console.log('Error sending message:', error);
          throw new Error(error.message);
      });
    })

    response.send(request.query.code);
 });
</code>```

Body:
How do use Firebase Cloud Messaging in the Firebase Functions?

I did try using getMessaging() to send the message but it also gave me issues so I will appreciate a quick workaround

I get the error below when I use the function attached

i  functions: Beginning execution of "Return"
>  {"structuredData":true,"severity":"INFO","message":"Hello logs!"}
>  { state: 'BwcRCA4UBAMTGRgNDxkHHBoBAAQMBw0CGBEaEAYNEh4' }
i  functions: Finished "Return" in 4.336959ms
>  {
>    dt: 'dScq50VpRQSl27s-ZPBB_Y:APA91bHM0VNORw1q_VndMQbKS_NTjk3Z2cCTwwrkrEAlpSjpS-5cvraUcj_Q3UV_Pqdtvwg-3BZGE--ShyR3pEr-4jwgPRwHZ4f5JD7Y4ZVkYIg0Rh4JpxEfjqIhCUujrEqCncoJU09Q'
>  }
>  /Users/thapeloradebe/functions/node_modules/firebase-admin/lib/app/firebase-namespace.js:131
>                  return _this.ensureApp(app).messaging();
>                                              ^
>
>  TypeError: _this.ensureApp(...).messaging is not a function
>      at Proxy.fn (/Users/thapeloradebe/functions/node_modules/firebase-admin/lib/app/firebase-namespace.js:131:45)
>      at /Users/thapeloradebe/functions/lib/index.js:25:21
>      at processTicksAndRejections (node:internal/process/task_queues:96:5)

This below is my function

export const Return = functions.https.onRequest(async (request, response) =>{
  functions.logger.info("Hello logs!", { structuredData: true });

    console.log({state: request.query.state});
    db.ref(`states/${request.query.state}`).get().then(async (snapshot) => {
      const device_token = snapshot.val();
      console.log({'dt': device_token.token})
      const payload = {
        data: {
          state: request.query.state,
          bank_code: request.query.code
        },
      } as MessagingPayload;

      await admin.messaging(app).sendToDevice(device_token.token, payload)
        .then((response) => {
          console.log('Successfully sent message:', response.results);
        }).catch((error: Error) => {
          console.log('Error sending message:', error);
          throw new Error(error.message);
      });
    })

    response.send(request.query.code);
 });


问:
PowerShell and WMI to modify BIOS settings
I am trying to set the BIOS power-on password for HP  using PowerShell /WMI. By going through the HP Client Management Interface technical white paper from HP, which describes the class and method to accomplish this task, and research. I came to know about the following command. I have set the setup password successfully. but unable to set power-on password.

```<code>$Interface = Get-WmiObject -Namespace root/hp/InstrumentedBIOS -Class HP_BIOSSettingInterface
$Interface.SetBIOSSetting("Power-on Password","<utf-16/>" + "pass","<utf-16/>" + "pass")
</code>```

The command runs successfully, however, it displays the following output with the return code 1

Body:
I am trying to set the BIOS power-on password for HP  using PowerShell /WMI. By going through the HP Client Management Interface technical white paper from HP, which describes the class and method to accomplish this task, and research. I came to know about the following command. I have set the setup password successfully. but unable to set power-on password.

$Interface = Get-WmiObject -Namespace root/hp/InstrumentedBIOS -Class HP_BIOSSettingInterface
$Interface.SetBIOSSetting("Power-on Password","<utf-16/>" + "pass","<utf-16/>" + "pass")

The command runs successfully, however, it displays the following output with the return code 1


问:
How to publish SharePoint Framework application to the Marketplace?
I have created SharePoint Framework application. I need to publish that application to the SharePoint Marketplace.

I have refereed below link for the same,

https://learn.microsoft.com/en-us/sharepoint/dev/spfx/publish-to-marketplace-checklist

Can anyone share me the steps or share the demo application which published into the Marketplace?

Thanks in Advance


问:
Viewing an octet-stream file in flutter
I am trying to view and display an attachment, but the attachment is in a form of "application/octet-stream". Do I need to convert it to a normal file before I view it, and if yes, how do I convert it?

iVBORw0KGgoAAAANSUhEUgAAB2YAAAOpCAYAAADBskcdAAAAAXNSR0IArs4c6QAAAARnQU1BAACxPwv8YQUAAAAJcEhZcwAAFiUAABYlAUlSJPAAAP+lSURBVHhe7N0HYFbV/T7wJ++bvQhJgCRksEFABAUH04kDBQeK4qqzrbP132q1r...=

Title: Viewing an octet-stream file in flutter


问:
Conditional Sum in Another Workbook, by Using VBA Button From a Workbook
WE WANT TO SUM THE RANGE FROM ANOTHER WORKBOOK myDividendBook Where the reported field matches to a condition. but, all this calculation to be done through my workbook. Portfolio Management System VBA User form

I tried
Dim lr As Integer
lr = Application.WorksheetFunction.CountA(sWorbook.worksheet("TICKET-CASH").Range("B:B"))

'''' Put the formula
If lr > 1 Then
sWorbook.worksheet("TICKET-CASH").Range("M2").Value = "=SUMIFS(sWorbook.worksheet(TICKET-CASH!I:I),sWorbook.worksheet(TICKET-CASH!L2),sWorbook.worksheet(TICKET-CASH!F:F))"
If lr > 2 Then
sWorbook.worksheet("TICKET-CASH).Range("L2:M" & lr).FillDown
End If
sWorbook.worksheet("TICKET-CASH").Calculate
End If
''''' Sort data
sWorbook.worksheet("TICKET-CASH").UsedRange.Sort key1:=Inv_sh.Range("M1"), order1:=xlAscending, Header:=xlYes
but unfortunately there is error


问:
AWS - s3 bucket policy - Access: errror
I did a stupid thing. In my s3 bucket I changed object onwership to 'ACLs disabled' and added s3 bucket policy to deny all resources and for all users..
Now I haven't access to list, permissions and even can't change  bucket policy.
Is any options to revert it?
s3 denied

I was looking for this s3 policy in IAM policy but I haven't found it.
I found only this policy with arn to this bucket, but it seems this policy doesn't work
s3 policy

Title: AWS - s3 bucket policy - Access: errror


问:
Downloading the elements of a Webpage as String in VB.Net
I am using VS 2019 and developing a winform applicaion using VB.Net.
I want to get the elements of a webpage into a string so that I can extract
the required value from that string.

The following are my Imports -
Imports System.IO
Imports System.Net

I had put a button on a form for initiating the process.  As I was debugging the function, when it came to the line "Dim response As HttpWebResponse = request.GetResponse()" it just loads the form back and does not proceed to the next line.

May I seek help on this?  Thanks in advance.

I went through Download contents of webpage with VB and tried to implement the answer given.

I also prefixed the request and response with "Net." as mentioned there.  But still the results are same.


问:
Why does this code show the value of a global variable instead of a class variable when using a list comprehension?
So I've seen a code that goes like

```<code>name = "Python"

class Language:
    name = "Java"
    list1 = [name] * 3
    list2 = [name for i in range(3)]

print(Language.list1)
print(Language.list2)
</code>```

And the output is

```<code>['Java', 'Java', 'Java']
['Python', 'Python', 'Python']
</code>```

Why is the output not "Java" both times?

Body:
So I've seen a code that goes like

name = "Python"

class Language:
    name = "Java"
    list1 = [name] * 3
    list2 = [name for i in range(3)]

print(Language.list1)
print(Language.list2)

And the output is

['Java', 'Java', 'Java']
['Python', 'Python', 'Python']

Why is the output not "Java" both times?


问:
Generate lib to link in c from 32 bit dll stdcall functions without decoration
Generating xxx.lib from xxx.dll with both name and ordinal can be done with a xxx.def generated from xxx.dll's dumpbin results (consider a dll with void foo() and void bar(int)):

```<code>dumpbin -exports xxx.dll

Exports

       ordinal    name
             0    foo
             1    bar
</code>```

Then process this result, and generate the following xxx.def

```<code>EXPORTS

    foo    @0
    bar    @1
</code>```

And then the following to generate the xxx.lib

```<code>lib /def:xxx.def
</code>```

This works with c++ decorated names, but not so intuitive with C functions. C functions have decorations, and it seems lib tool accepts the names as C function names. So the export symbols in the above xxx.lib is in-fact _foo and _bar mapped to foo and bar in the dll.

This works with most 64 bit things, since calling convention is the same, all you need is to declare the function as a normal cdecl c function. In 32 bit, however, the compiler looks for _foo@0 and _bar@4 for stdcall (you cannot specify cdecl in import, since they are fundamentally different), and cannot be satisfied.

Is there a way to still statically load 32 bit dll when you have the header but not source code? (A loader should be possible, but that would mean much more work to do, and that's dynamic)

Body:
Generating xxx.lib from xxx.dll with both name and ordinal can be done with a xxx.def generated from xxx.dll's dumpbin results (consider a dll with void foo() and void bar(int)):

dumpbin -exports xxx.dll

Exports

       ordinal    name
             0    foo
             1    bar

Then process this result, and generate the following xxx.def

EXPORTS

    foo    @0
    bar    @1

And then the following to generate the xxx.lib

lib /def:xxx.def

This works with c++ decorated names, but not so intuitive with C functions. C functions have decorations, and it seems lib tool accepts the names as C function names. So the export symbols in the above xxx.lib is in-fact _foo and _bar mapped to foo and bar in the dll.

This works with most 64 bit things, since calling convention is the same, all you need is to declare the function as a normal cdecl c function. In 32 bit, however, the compiler looks for _foo@0 and _bar@4 for stdcall (you cannot specify cdecl in import, since they are fundamentally different), and cannot be satisfied.

Is there a way to still statically load 32 bit dll when you have the header but not source code? (A loader should be possible, but that would mean much more work to do, and that's dynamic)


问:
Python - Unable to allocate enougth for an array using numpy.where
I am having troubles using the function numpy.where getting the error

```<code>Unable to allocate 85.0 GiB for an array with shape (327593, 278741) and data type bool
</code>```

So I have the following code where I am trying to extract the index of the dataframe that meets the criteria in the numpy.where function.

```<code># Assing new road ID

# extract numpy arrays
ns_bmp = df_mile_posts['PRIRTE_BMP'].values # new sections begin mile post array
ns_emp = df_mile_posts['PRIRTE_EMP'].values # new sections end mile post array
hzc_emp = df_hz_curves['PRIRTE_EMP'].values # rumble strips end mile post array
hzc_bmp = df_hz_curves['PRIRTE_BMP'].values # rumble strips begin mile post array
ns_route_code = df_mile_posts['PRIRTE_CODE'].values # new sections route code array
hzc_route_code =  df_hz_curves['PRIRTE_CODE'].values # rumble strips route code array

# extract matching indexes
nsect_idx, hzc_idx = np.where((ns_bmp[:, None] >= hzc_bmp) &
                             (ns_emp[:, None] <= hzc_emp) &
                             (ns_route_code[:,None] == hzc_route_code))

# assign the roadway id to the new section
df_mile_posts['ID_HZC'] = 0
df_mile_posts['ID_HZC'].iloc[nsect_idx] = df_rumble_strips['ID_HZC'].iloc[hzc_idx]
</code>```

The arrays have the following lengths:

ns_bmp, ns_emp, and ns_route_code have a length of 32759

hzc_emp, hzc_bmp, and hzc_route_code have a length of 278741

I have tried this code in a different data with less rows and it works.

Is there any way to improve the speed of the code and to not use so many memmory?

Body:
I am having troubles using the function numpy.where getting the error

Unable to allocate 85.0 GiB for an array with shape (327593, 278741) and data type bool

So I have the following code where I am trying to extract the index of the dataframe that meets the criteria in the numpy.where function.

# Assing new road ID

# extract numpy arrays
ns_bmp = df_mile_posts['PRIRTE_BMP'].values # new sections begin mile post array
ns_emp = df_mile_posts['PRIRTE_EMP'].values # new sections end mile post array
hzc_emp = df_hz_curves['PRIRTE_EMP'].values # rumble strips end mile post array
hzc_bmp = df_hz_curves['PRIRTE_BMP'].values # rumble strips begin mile post array
ns_route_code = df_mile_posts['PRIRTE_CODE'].values # new sections route code array
hzc_route_code =  df_hz_curves['PRIRTE_CODE'].values # rumble strips route code array

# extract matching indexes
nsect_idx, hzc_idx = np.where((ns_bmp[:, None] >= hzc_bmp) &
                             (ns_emp[:, None] <= hzc_emp) &
                             (ns_route_code[:,None] == hzc_route_code))

# assign the roadway id to the new section
df_mile_posts['ID_HZC'] = 0
df_mile_posts['ID_HZC'].iloc[nsect_idx] = df_rumble_strips['ID_HZC'].iloc[hzc_idx]

The arrays have the following lengths:

ns_bmp, ns_emp, and ns_route_code have a length of 32759

hzc_emp, hzc_bmp, and hzc_route_code have a length of 278741

I have tried this code in a different data with less rows and it works.

Is there any way to improve the speed of the code and to not use so many memmory?


问:
API request blocked by CORS policy, on ReactJS website deployed by Vercel
```<code>Access to XMLHttpRequest at 'https://apis.justwatch.com/content/titles/en_GB/popular?body={%22page_size%22:1,%22page%22:1,%22query%22:%22A+Bes%C3%BAg%C3%B3%22,%22content_types%22:[%22show%22]}' from origin 'https://leisure-os.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I get this error when attempting to make a request to apis.justwatch.com. However requests made api.tvmaze.com in my website, using the same method, works fine.

This is how I am making a request to the API, using Axios:

```<code>  useEffect(() => {
    const search = async () => {
      console.log("locale: ", locale);
      //var locale = "en_GB";
      var type = "show";
      var n = 1;
      try {
        var data = await axios.get(
          "https://apis.justwatch.com/content/titles/" +
            locale +
            '/popular?body={"page_size":' +
            n +
            ',"page":1,"query":"' +
            q.split(" ").join("+") +
            '","content_types":["' +
            type +
            '"]}'
        );

        ...
</code>```

The code to the website, with the live demo can be found here: github.com/moiz-i/leisureos

It works when I use a CORS unblocker chrome extension, but I want a permanent fix.

I have tried to use this code in my vercel.json, but it doesn't seem to make a difference:

```<code>{
  "headers": [
    {
      "source": "src/index.js",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        {
          "key": "Access-Control-Allow-Methods",
          "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
        },
        {
          "key": "Access-Control-Allow-Headers",
          "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
        }
      ]
    }
  ]
}

</code>```

Body:
Access to XMLHttpRequest at 'https://apis.justwatch.com/content/titles/en_GB/popular?body={%22page_size%22:1,%22page%22:1,%22query%22:%22A+Bes%C3%BAg%C3%B3%22,%22content_types%22:[%22show%22]}' from origin 'https://leisure-os.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I get this error when attempting to make a request to apis.justwatch.com. However requests made api.tvmaze.com in my website, using the same method, works fine.

This is how I am making a request to the API, using Axios:

  useEffect(() => {
    const search = async () => {
      console.log("locale: ", locale);
      //var locale = "en_GB";
      var type = "show";
      var n = 1;
      try {
        var data = await axios.get(
          "https://apis.justwatch.com/content/titles/" +
            locale +
            '/popular?body={"page_size":' +
            n +
            ',"page":1,"query":"' +
            q.split(" ").join("+") +
            '","content_types":["' +
            type +
            '"]}'
        );

        ...

The code to the website, with the live demo can be found here: github.com/moiz-i/leisureos

It works when I use a CORS unblocker chrome extension, but I want a permanent fix.

I have tried to use this code in my vercel.json, but it doesn't seem to make a difference:

{
  "headers": [
    {
      "source": "src/index.js",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        {
          "key": "Access-Control-Allow-Methods",
          "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
        },
        {
          "key": "Access-Control-Allow-Headers",
          "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
        }
      ]
    }
  ]
}


问:
Different assembly version for same project
I'm currently working on a project that dynamically loads an assembly and executes a predefined method like so:

var result = (bool)method.Invoke(instance, parameters);

When the application starts, the assemblies are downloaded (with all dependencies) and stored in a subfolder of the applications folder path.

For the assemblies we've created some sort of an SDK which basically is just a abstract class with abstract methods that needs to be implemented:

```<code>public abstract class Sdk
{
    public abstract bool DoStuff(object parameters);
}
</code>```

My question is: If I have one assembly which is using version 1 of de SDK, and one assembly with version 2 of the SDK, would everything continue to work? Or would I get weird errors?

Thanks in advance

Body:
I'm currently working on a project that dynamically loads an assembly and executes a predefined method like so:

var result = (bool)method.Invoke(instance, parameters);

When the application starts, the assemblies are downloaded (with all dependencies) and stored in a subfolder of the applications folder path.

For the assemblies we've created some sort of an SDK which basically is just a abstract class with abstract methods that needs to be implemented:

public abstract class Sdk
{
    public abstract bool DoStuff(object parameters);
}

My question is: If I have one assembly which is using version 1 of de SDK, and one assembly with version 2 of the SDK, would everything continue to work? Or would I get weird errors?

Thanks in advance


问:
Calculating total daily sales orders in PowerBI using DAX
I am trying to get the total number of sales orders received daily. This will be sum of sales orders received + sum of sales shipments. Note that sales shipment has unique sales order number as well. There could be multiple sales shipments for 1 sales order, thus creating an error.

I am currently using:

```<code>Sales orders received = DISTINCTCOUNT (salesOrders[number]) + DISTINCTCOUNT(salesShipments[orderNumber]))
</code>```

But this gives wrong number as sales order number can be in sales order table and sales shipment table both.

All I want is the distinct count of sales order numbers in Sales order table and Sales shipment table.

Any help is highly appreciated.

thank you

Body:
I am trying to get the total number of sales orders received daily. This will be sum of sales orders received + sum of sales shipments. Note that sales shipment has unique sales order number as well. There could be multiple sales shipments for 1 sales order, thus creating an error.

I am currently using:

Sales orders received = DISTINCTCOUNT (salesOrders[number]) + DISTINCTCOUNT(salesShipments[orderNumber]))

But this gives wrong number as sales order number can be in sales order table and sales shipment table both.

All I want is the distinct count of sales order numbers in Sales order table and Sales shipment table.

Any help is highly appreciated.

thank you


问:
React why am I not able to change this height and it keeps getting downscaled?
I'm trying to make a sidebar and this is my App.js

```<code>function App() {
  return (
    <BrowserRouter>
      <AuthContextProvider>
        <NavbarComponent></NavbarComponent>
        <Container>

          <Routes>
            <Route index element={<Store />} />
            <Route path="register" element={<Signup></Signup>} />
            <Route path="success" element={<Success />} />
            <Route path="cancel" element={<Cancel />} />
            <Route path="sell" element={<Sell />} />
            <Route path="login" element={<Login />} />
          </Routes>

        </Container>
        <Sidebar></Sidebar>

      </AuthContextProvider>
    </BrowserRouter>

  );
}

export default App;
</code>```

Sidebar.js

```<code>export default function Sidebar() {

    return (
        <div>
            <div className="sidebar">Yo whats good</div>
            <div className="sidebar">Yo whats good</div>
            <div className="sidebar">Yo whats good</div>
            <div className="sidebar">Yo whats good</div>
        </div>
    )

}
</code>```

CSS for Sidebar:

```<code>.sidebar {
  background-color: red;
  width: 80px;
  height: 100px;
}
</code>```

The first page you see is the Store and so here that is too:

```<code>export default function Store() {
    const [searchQuery, setSearchQuery] = useState("")

    const { limiteds, loadedLimiteds } = UserAuth()

    const filteredItems = filterItems(limiteds, searchQuery)

    return (
        <div className="store" style={{ marginBottom: "8rem" }}>
            <Banner text="Test" />
            <Search
                searchQuery={searchQuery}
                setSearchQuery={setSearchQuery}
            />
            {loadedLimiteds ? <Row xs={1} md={4} className="g-4">
                {filteredItems.sort((a, b) => b.rap - a.rap).map((product, i) => (
                    <Col align="center" key={i}>
                        <ProductCard product={product}></ProductCard>
                    </Col>
                ))}
            </Row> : <MoonLoader size="100px" color="white" cssOverride={{ marginLeft: "auto", marginRight: "auto", marginTop: "auto", top: "35px" }} />}

        </div >

    )
}
</code>```

Basically no matter what I do with the CSS the height seems to be stuck and not changing, does anyone know how I can fix this? It just seems to be stuck at one value and not possible to change the height to make it taller.

Body:
I'm trying to make a sidebar and this is my App.js

function App() {
  return (
    <BrowserRouter>
      <AuthContextProvider>
        <NavbarComponent></NavbarComponent>
        <Container>

          <Routes>
            <Route index element={<Store />} />
            <Route path="register" element={<Signup></Signup>} />
            <Route path="success" element={<Success />} />
            <Route path="cancel" element={<Cancel />} />
            <Route path="sell" element={<Sell />} />
            <Route path="login" element={<Login />} />
          </Routes>

        </Container>
        <Sidebar></Sidebar>

      </AuthContextProvider>
    </BrowserRouter>

  );
}

export default App;

Sidebar.js

export default function Sidebar() {

    return (

Yo whats good

Yo whats good

Yo whats good

Yo whats good

    )

}

CSS for Sidebar:

.sidebar {
  background-color: red;
  width: 80px;
  height: 100px;
}

The first page you see is the Store and so here that is too:

export default function Store() {
    const [searchQuery, setSearchQuery] = useState("")

    const { limiteds, loadedLimiteds } = UserAuth()

    const filteredItems = filterItems(limiteds, searchQuery)

    return (

            <Banner text="Test" />
            <Search
                searchQuery={searchQuery}
                setSearchQuery={setSearchQuery}
            />
            {loadedLimiteds ? <Row xs={1} md={4} className="g-4">
                {filteredItems.sort((a, b) => b.rap - a.rap).map((product, i) => (
                    <Col align="center" key={i}>
                        <ProductCard product={product}></ProductCard>
                    </Col>
                ))}
            </Row> : <MoonLoader size="100px" color="white" cssOverride={{ marginLeft: "auto", marginRight: "auto", marginTop: "auto", top: "35px" }} />}

    )
}

Basically no matter what I do with the CSS the height seems to be stuck and not changing, does anyone know how I can fix this? It just seems to be stuck at one value and not possible to change the height to make it taller.


问:
Is it possible to specify image used in steps according to the matrix strategy?
I'm going to setup a workflow on GitHub which uses some docker images to check my package on different platform. I'd like to use the matrix strategy. Then I wrote a workflow like this:

name: Main Workflow
on: [push]
jobs:
  test_linux:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        image: [ubuntu, fedora]
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Test
        uses: docker://${{ matrix.image }}:latest
        with:
          entrypoint: /bin/bash
          args: ./test.sh
```
<p>This is just a demo workflow. The real one is much more complicated.</p>
<p>However, after I pushed it, GitHub gave me the following error message:</p>
<blockquote>
<p><strong>Invalid workflow file: .github/workflows/main.yml#L16</strong></p>
<p>The workflow is not valid. .github/workflows/main.yml (Line: 13, Col: 15): Unrecognized named-value: 'matrix'. Located at position 1 within expression: matrix.image</p>
</blockquote>
<p>Actually, I got this error instantly when I pushed codes.</p>
<p>Why? Is the matrix context inaccessible when parsing workflow file? Are there some ways to resolve it?</p>
<p>I tried to export the full docker name to environment in the previous step before "Test", but context <code>env</code> is also inaccessible just like the context <code>matrix</code>. I got nearly the same error. The only different is:</p>
<blockquote>
<p>Unrecognized named-value: 'env'...</p>
</blockquote>
<p>Now I have to call <code>docker run</code> manually in run scripts like</p>
<pre class="lang-yaml prettyprint-override"><code>steps:
  - name: Test
    run: docker run --rm -v $(pwd):/code --workdir=/code ${{ matrix.image }}:latest /bin/bash -c "/code/test.sh"
</code>```

It did work but I still prefer to use the uses entry.

Body:
I'm going to setup a workflow on GitHub which uses some docker images to check my package on different platform. I'd like to use the matrix strategy. Then I wrote a workflow like this:

name: Main Workflow
on: [push]
jobs:
  test_linux:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        image: [ubuntu, fedora]
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Test
        uses: docker://${{ matrix.image }}:latest
        with:
          entrypoint: /bin/bash
          args: ./test.sh

This is just a demo workflow. The real one is much more complicated.

However, after I pushed it, GitHub gave me the following error message:

Invalid workflow file: .github/workflows/main.yml#L16

The workflow is not valid. .github/workflows/main.yml (Line: 13, Col: 15): Unrecognized named-value: 'matrix'. Located at position 1 within expression: matrix.image

Actually, I got this error instantly when I pushed codes.

Why? Is the matrix context inaccessible when parsing workflow file? Are there some ways to resolve it?

I tried to export the full docker name to environment in the previous step before "Test", but context env is also inaccessible just like the context matrix. I got nearly the same error. The only different is:

Unrecognized named-value: 'env'...

Now I have to call docker run manually in run scripts like

steps:
  - name: Test
    run: docker run --rm -v $(pwd):/code --workdir=/code ${{ matrix.image }}:latest /bin/bash -c "/code/test.sh"

It did work but I still prefer to use the uses entry.


问:
How do I correctly model data from Firebase Realtime Database in Flutter?
In the current version of my app I have not followed any sort of architecture practice and had front end and back end mixed together. Now I want to separate the two but I am confused on how to create a correct model and then use it.

My code for my model class is as follows, where fromJson is what I think is close to correct:

```<code>class TestModel with ChangeNotifier {
  String? img;
  String? path;
  String? title;

  TestModel({required this.img, required this.path, required this.title});

  factory TestModel.fromJson(Map<dynamic, dynamic> json) {
    return TestModel(
        img: json['img'], path: json['path'], title: json['title']);
  }
}

</code>```

The following code is how I currently get the different categories but I do not make use of my model:

```<code>  Future<void> getCategory() async {
    var nameObect = await _dbRef.child('CategoryMenu').get();
    if (nameObect.exists) {
      var see = nameObect.value as Map;
      see.entries.map((e) => categoryMenuList.add(e.value)).toList();
      setState(() {});
    } else {
      print('Fail');
    }
  }
</code>```

I changed this method to try include the fromJson method in my model class. When I print the 'categroy' variable or the 'modelList' it returns 'instance of [TestModel]' and my listView returns null:

```<code>    var nameObject = await _dbRef.child('CategoryMenu').get();
    if (nameObject.exists) {
      var test = nameObject.value as Map<dynamic, dynamic>;
      //test stores a map of the object
      //it then fails at my model object below
      TestModel category = TestModel.fromJson(test);

      modelList.add(category);
      setState(() {});
    }
  }
</code>```

I then use a ListView to display the categoryMenuList which I altered to be make use of the list populated by making use of the model:

```<code>ListView.separated(
                itemCount: modelList.length,
                itemBuilder: (context, index) {
//trying to use the model list
                  final catItem = modelList[index];
//Extacting the data from the list
                  String catIgm = catItem.img.toString(); //used to be 'String catImg = catItem['img'];'
                  String title = catItem.title.toString();
                  String path = catItem.path.toString();
                  return SizedBox(
                    width: 95,
                    height: 100,
                    child: Text(title)
                  );
                }),
</code>```

So I can my data and not map it to any kind of model without any problems, so my issue is not with the db pulling. I can then display the list once it is generated.
However, when I try to implement the model class I am unable to populate the list. So I wanted to know how can I fetch my data by making use of my fromJson model and add it to my list?

Body:
In the current version of my app I have not followed any sort of architecture practice and had front end and back end mixed together. Now I want to separate the two but I am confused on how to create a correct model and then use it.

My code for my model class is as follows, where fromJson is what I think is close to correct:

class TestModel with ChangeNotifier {
  String? img;
  String? path;
  String? title;

  TestModel({required this.img, required this.path, required this.title});

  factory TestModel.fromJson(Map<dynamic, dynamic> json) {
    return TestModel(
        img: json['img'], path: json['path'], title: json['title']);
  }
}

The following code is how I currently get the different categories but I do not make use of my model:

  Future<void> getCategory() async {
    var nameObect = await _dbRef.child('CategoryMenu').get();
    if (nameObect.exists) {
      var see = nameObect.value as Map;
      see.entries.map((e) => categoryMenuList.add(e.value)).toList();
      setState(() {});
    } else {
      print('Fail');
    }
  }

I changed this method to try include the fromJson method in my model class. When I print the 'categroy' variable or the 'modelList' it returns 'instance of [TestModel]' and my listView returns null:

    var nameObject = await _dbRef.child('CategoryMenu').get();
    if (nameObject.exists) {
      var test = nameObject.value as Map<dynamic, dynamic>;
      //test stores a map of the object
      //it then fails at my model object below
      TestModel category = TestModel.fromJson(test);

      modelList.add(category);
      setState(() {});
    }
  }

I then use a ListView to display the categoryMenuList which I altered to be make use of the list populated by making use of the model:

ListView.separated(
                itemCount: modelList.length,
                itemBuilder: (context, index) {
//trying to use the model list
                  final catItem = modelList[index];
//Extacting the data from the list
                  String catIgm = catItem.img.toString(); //used to be 'String catImg = catItem['img'];'
                  String title = catItem.title.toString();
                  String path = catItem.path.toString();
                  return SizedBox(
                    width: 95,
                    height: 100,
                    child: Text(title)
                  );
                }),

So I can my data and not map it to any kind of model without any problems, so my issue is not with the db pulling. I can then display the list once it is generated.
However, when I try to implement the model class I am unable to populate the list. So I wanted to know how can I fetch my data by making use of my fromJson model and add it to my list?


问:
java.lang.IllegalStateException error :"Can not perform this action after onSaveInstanceState"
I am writing an app where i am trying to display a dialog fragment on Activity A. Activity-A launch Activity-B using an intent. I am launching the Dialogfragment using a broadcast intent whose receiver is registered on Activity-A . But when i  switch from activity A to activity B , i get the an IllegalStateException error when Activity A broadcast receiver receives the intent . The eror displays : Can not perform this action after onSaveInstanceState . Could you help me please ?</p>


问:
Indexing Pandas DataFrame containing lists of strings after loading pickled DataFrame
I'm trying to get the row indices of a pandas DataFrame, where the entries are being queried for containing a string amongst a list.

However, after pickling a DataFrame and then loading, the column data seems to handle differently than when working prior to pickling.

e.g. for the following DataFrame

```<code>import pandas as pd

DB = pd.DataFrame(columns=['message', 'authors', 'style'])
DB['message'] = ['hello', 'i wrote', 'this passage']

DB.loc[1]['authors'] = ['Adam', 'Bob']
DB.loc[2]['authors'] = ['Bob', 'Charlie']

print(DB)
</code>```

...output...

```<code>        message         authors style
0         hello             NaN   NaN
1       i wrote     [Adam, Bob]   NaN
2  this passage  [Bob, Charlie]   NaN
</code>```

Retrieving all the column indices where the 'author' column contains the word 'Bob' can be done using the pandas.Series.str.contains method:

```<code>DB.authors.astype(str).str.contains('Adam')
</code>```

Out:

```<code>0    False
1     True
2    False
Name: authors, dtype: bool
</code>```

Leaving the DataFrame column in its original format (I think...) which can be seen by querying the following:

```<code>print(DB2.authors[1])
</code>```

Out:

```<code>['Adam', 'Bob']
</code>```

However, if you first pickle the DataFrame for reloading somewhere else and then perform the same operation, you can see that the format of the DataFrame column has been changed in place:

```<code>DB.to_pickle('dummy_database.pkl')
DB2 = pd.read_pickle('dummy_database.pkl')
print(DB2.authors.astype(str).str.contains('Adam'))
print(DB2.authors[1])
</code>```

Out:

```<code>0    False
1     True
2    False
Name: authors, dtype: bool

"['Adam', 'Bob']"
</code>```

...as shown by the quotations around what was originally a list of strings.

Is there anyway to undo this apparent in place change of datatype, and could anyone explain what I'm doing wrong which is causing this behaviour?

Useful note: prior to the query operation DB2.authors.astype(str).str.contains('Adam') you can still call DB2.authors[1] as before, and you appear to have the same format: Out: ['Adam', 'Bob'].

Body:
I'm trying to get the row indices of a pandas DataFrame, where the entries are being queried for containing a string amongst a list.

However, after pickling a DataFrame and then loading, the column data seems to handle differently than when working prior to pickling.

e.g. for the following DataFrame

import pandas as pd

DB = pd.DataFrame(columns=['message', 'authors', 'style'])
DB['message'] = ['hello', 'i wrote', 'this passage']

DB.loc[1]['authors'] = ['Adam', 'Bob']
DB.loc[2]['authors'] = ['Bob', 'Charlie']

print(DB)

...output...

        message         authors style
0         hello             NaN   NaN
1       i wrote     [Adam, Bob]   NaN
2  this passage  [Bob, Charlie]   NaN

Retrieving all the column indices where the 'author' column contains the word 'Bob' can be done using the pandas.Series.str.contains method:

DB.authors.astype(str).str.contains('Adam')

Out:

0    False
1     True
2    False
Name: authors, dtype: bool

Leaving the DataFrame column in its original format (I think...) which can be seen by querying the following:

print(DB2.authors[1])

Out:

['Adam', 'Bob']

However, if you first pickle the DataFrame for reloading somewhere else and then perform the same operation, you can see that the format of the DataFrame column has been changed in place:

DB.to_pickle('dummy_database.pkl')
DB2 = pd.read_pickle('dummy_database.pkl')
print(DB2.authors.astype(str).str.contains('Adam'))
print(DB2.authors[1])

Out:

0    False
1     True
2    False
Name: authors, dtype: bool

"['Adam', 'Bob']"

...as shown by the quotations around what was originally a list of strings.

Is there anyway to undo this apparent in place change of datatype, and could anyone explain what I'm doing wrong which is causing this behaviour?

Useful note: prior to the query operation DB2.authors.astype(str).str.contains('Adam') you can still call DB2.authors[1] as before, and you appear to have the same format: Out: ['Adam', 'Bob'].


问:
Compare two item values from a single list in recyclerview adapter
I am trying to compare 2 values from a single list in recyclerview adapter.
I need to get the status of current item & the next item & compare both. So far I'm here but it doesn't work. Any suggestions appreciated!

Example

```<code>    int curr = position;
    int next = position + 1;

        String s1 = null, s2 = null;

        if (position == curr) {
            s1 = item.getStatus();
        }

        if (position == next) {
            s2 = item.getStatus();
        }

        if(s1.equals(s2))
        {
        //print ok
        } else {
        //not ok
        }
</code>```

Body:
I am trying to compare 2 values from a single list in recyclerview adapter.
I need to get the status of current item & the next item & compare both. So far I'm here but it doesn't work. Any suggestions appreciated!

Example

    int curr = position;
    int next = position + 1;

        String s1 = null, s2 = null;

        if (position == curr) {
            s1 = item.getStatus();
        }

        if (position == next) {
            s2 = item.getStatus();
        }

        if(s1.equals(s2))
        {
        //print ok
        } else {
        //not ok
        }


问:
Force localizaition in SharePoint Framework (spfx)
I have a question regarding localization in SharePoint Framework. I have a simple webpart, which should change language not matter of the SharePoint settings. For example SP sites are full in English, but the user has to have a change to switch the language to Spanish or German. The question is how can I do it easily?

I have a webpart context which has localization property which are passed and normally, I suppose they are used to load the correct language, right?

So can I somehow programmatically change it? Or is there a another correct or better way?

Thanks in advance.