问:
Using pdfgrep with spaces in variable name for seaching phrase into pdf file
Currently Im using on Windows 10, subsystem for Linux Ubuntu 20.04 the command pdfgrep
for to use in my script. Lets explain a little bit in more detail.
I want to search in a pdf file in my folder for an articlenumber that contains spaces in it.
But in my little script I get an error : first you see an echo with the whole pdfgrep command with the search pattern (= articlenumber) and the pdf file located in my folder

/usr/bin/pdfgrep '4022 622 48402' ../testdir/'4022 622 48402 - B263486P010 DY 2022-8-22.pdf'
On the command line, above pdfgrep command seems to work fine.

Below is the part of my script :

```<code>#!/usr/bin/bash
#
#
#
clear
echo
inputfile="`ls ../testdir/*.pdf`"
inputfile2="${inputfile:11:46}"
inputfile3=\'$inputfile2\'
doctp1=${inputfile: -3}
articlenumber1=${inputfile:11:14}
articlenumber2=\'$articlenumber1\'
echo
read -p "Running pdfgrep with articlenumber. Push a key to continue ! " x
clear
echo
#case ${doctp1} in
#          pdf)
            clear
            echo "/usr/bin/pdfgrep ${articlenumber2} ../testdir/${inputfile3}"
            /usr/bin/pdfgrep ${articlenumber2} ../testdir/${inputfile3}
            if [ $? -ne 0 ]
            then
                    echo "No pdf files with given articlenumber present"
            # echo "No pdf files with given articlenumber present" >>  log_$articlenumber1_$(date +"%Y%m%d_%H%M").txt
            fi
            echo
            read -p "Push a key to continue !" x
</code>```

When I run the script I got this error :

pdfgrep: Could not open 622
pdfgrep: Could not open 48402'
pdfgrep: Could not open ../testdir/'4022
pdfgrep: Could not open 622
pdfgrep: Could not open 48402
pdfgrep: Could not open -
pdfgrep: Could not open B263486P010
pdfgrep: Could not open DY
pdfgrep: Could not open 2022-8-22.pdf'

Can you help me with finding a solution for this ? Is there anything that I do wrong here ?
Please let me know. All comments are welcome !

Body:
Currently Im using on Windows 10, subsystem for Linux Ubuntu 20.04 the command pdfgrep
for to use in my script. Lets explain a little bit in more detail.
I want to search in a pdf file in my folder for an articlenumber that contains spaces in it.
But in my little script I get an error : first you see an echo with the whole pdfgrep command with the search pattern (= articlenumber) and the pdf file located in my folder

/usr/bin/pdfgrep '4022 622 48402' ../testdir/'4022 622 48402 - B263486P010 DY 2022-8-22.pdf'
On the command line, above pdfgrep command seems to work fine.

Below is the part of my script :

#!/usr/bin/bash
#
#
#
clear
echo
inputfile="`ls ../testdir/*.pdf`"
inputfile2="${inputfile:11:46}"
inputfile3=\'$inputfile2\'
doctp1=${inputfile: -3}
articlenumber1=${inputfile:11:14}
articlenumber2=\'$articlenumber1\'
echo
read -p "Running pdfgrep with articlenumber. Push a key to continue ! " x
clear
echo
#case ${doctp1} in
#          pdf)
            clear
            echo "/usr/bin/pdfgrep ${articlenumber2} ../testdir/${inputfile3}"
            /usr/bin/pdfgrep ${articlenumber2} ../testdir/${inputfile3}
            if [ $? -ne 0 ]
            then
                    echo "No pdf files with given articlenumber present"
            # echo "No pdf files with given articlenumber present" >>  log_$articlenumber1_$(date +"%Y%m%d_%H%M").txt
            fi
            echo
            read -p "Push a key to continue !" x

When I run the script I got this error :

pdfgrep: Could not open 622
pdfgrep: Could not open 48402'
pdfgrep: Could not open ../testdir/'4022
pdfgrep: Could not open 622
pdfgrep: Could not open 48402
pdfgrep: Could not open -
pdfgrep: Could not open B263486P010
pdfgrep: Could not open DY
pdfgrep: Could not open 2022-8-22.pdf'

Can you help me with finding a solution for this ? Is there anything that I do wrong here ?
Please let me know. All comments are welcome !


来源: stackexchange

问:
Image Skew Transformation with OpenCV
I have an image of some coins. however, they are at an angle.1 I am trying to perform skew image transformation to achieve something like this. (ignore the shadow and the rotation) 2

I have the image 1 as a NumPy array in RGB format. I am unsure of what to do with it next. Assuming I don't have the access to 2.

Is it even possible to achieve this without using an untilted image2.

ContentLicense: CC BY-SA 4.0

Title: Image Skew Transformation with OpenCV


问:
changing color of img except black pixels with javascript
So here is my problem:
I have black and white images (img tags), and i want to change the color of it except for the black pixels. I used a code that allowed me to do this, but when coloring the image, some of the black pixels are colored too, not only the white as you can see in these images (some of the black lines are colored):

This is my code (to test it please change the image url to a local image so the color changing works)

let hex
var mug=document.getElementById("eyes");
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;
let currentcolor

function color(elem) {
  hex='rgb(0,0,0)'
  if (elem.classList[0].toString()=='color') {
    currentcolor=document.getElementById(elem.id).style.backgroundColor
    hex=currentcolor.toString()
  }

}

function color1(elem) {
document.getElementById(elem.id).style.fill=currentcolor
    getPixels(mug)
    hex=hex.substring(4, hex.length-1)
      .replace(/ /g, '')
      .split(',')
    changeColor(hex[0],hex[1],hex[2])
}

function getPixels(img)
{
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}

function hexToRGB(hex)
{
  console.log(hex)
    var long = parseInt(hex.replace(/^#/, ""), 16);
    return {
        R: (long >>> 16) & 0xff,
        G: (long >>> 8) & 0xff,
        B: long & 0xff
    };
}

function changeColor(a,b,c)
{
    if(!originalPixels) return; // Check if image has loaded
    var newColor = {R: eval(a), G: eval(b), B: eval(c)};

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
          console.log(currentPixels.data[I + 3])
           if ((currentPixels.data[I]!=0 && currentPixels.data[I+1]!=0 && currentPixels.data[I+2]!=0)) {
            currentPixels.data[I] = newColor.R;
            currentPixels.data[I + 1] = newColor.G;
            currentPixels.data[I + 2] = newColor.B;
           }
        }
    }
    console.log(newColor)
    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#boite {
    width: 70%;
    height: 85%;
    border: 5px solid black;
    background-color: #e3e2d3;
    position: absolute;
    left: 0;
    right: 0;
    top: 5%;
    justify-content: center;
    display: flex;
    align-items: center;
    margin-left: 285px;
}
#corps{

    width: 300px;
}

#next2{
    position: absolute;
    width: 25%;
    height: 95%;
    text-align: center;
    justify-content: center;
    align-items: center;
    border-radius: 20px;
    border: 3px solid white;
    margin-left: 15px;
    margin-top: 15px;
    text-align: center;
    background-color: #B393DE;
}

#colours {

  color: #fff;
  justify-content: center;
  font: 100 24px/100px sans-serif;
  height: 150px;
  width: 100%;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
}

#colours div {
    height: 50%;
    width: 30%;
    border: 2px solid rgb(255, 255, 255);
    border-radius: 50%;
    cursor:pointer;
  }
.color{

    background-color: #888888;
}</code>```

<!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>

    <svg version="1.0" xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 1876.000000 2501.000000"
    preserveAspectRatio="xMidYMid meet" id="corps"  width="80%" height="80%">

   <g transform="translate(0.000000,2501.000000) scale(0.100000,-0.100000)"
   fill="white" stroke="none" id="issasvg" onclick="color1(this)" >
   <path d="M8615 24873 c-386 -22 -661 -48 -938 -88 -960 -140 -1780 -418 -2486
   -844 -317 -192 -473 -310 -721 -546 -164 -157 -264 -231 -362 -267 -44 -16
   -62 -28 -69 -46 -13 -34 6 -80 36 -88 12 -3 99 17 198 45 97 28 179 51 183 51
   5 0 -50 -39 -121 -86 -602 -401 -1138 -934 -1593 -1586 -602 -861 -1038 -1873
   -1357 -3148 -106 -420 -113 -462 -145 -834 -70 -801 -109 -1055 -242 -1591
   -139 -561 -163 -730 -163 -1145 0 -197 4 -325 13 -385 23 -153 62 -325 99
   -435 39 -119 144 -344 175 -377 22 -24 62 -30 88 -13 8 5 49 112 91 237 l76
   228 8 -50 c59 -407 298 -971 616 -1453 87 -132 132 -179 182 -193 95 -25 146
   38 175 217 9 57 20 104 24 104 4 0 8 -5 8 -10 0 -6 25 -67 56 -137 146 -331
   327 -595 579 -848 226 -227 390 -356 697 -547 l178 -110 -46 -57 c-935 -1156
   -1523 -2549 -1683 -3986 -37 -329 -45 -485 -45 -865 0 -388 13 -603 55 -945
   106 -867 372 -1742 769 -2534 67 -134 80 -151 119 -151 53 0 61 23 61 166 0
   71 3 152 6 181 l7 52 76 -112 c339 -495 585 -798 841 -1035 538 -498 1161
   -855 1925 -1105 779 -254 1708 -374 2624 -338 331 13 498 26 896 71 149 16
   275 30 280 30 16 -1 -64 -41 -140 -71 -81 -31 -104 -59 -83 -103 6 -15 23 -30
   37 -34 42 -12 555 -7 696 7 575 55 1056 184 1816 487 773 307 1301 585 1764
   929 441 326 806 720 1058 1139 60 100 77 122 82 106 3 -11 8 -105 9 -208 2
   -104 6 -195 11 -201 12 -20 53 -31 79 -21 41 15 261 480 408 865 693 1807 684
   3785 -27 5580 -301 759 -688 1413 -1243 2096 l-23 28 101 76 c213 161 427 344
   750 641 369 338 548 553 690 825 l57 111 17 -109 c9 -59 22 -125 28 -145 25
   -85 119 -123 188 -76 95 64 374 521 518 848 116 261 219 591 238 761 4 33 10
   57 14 52 4 -4 40 -106 80 -226 61 -186 76 -220 96 -229 53 -25 73 -5 155 157
   316 626 333 1410 49 2340 -29 94 -70 229 -92 300 -37 122 -514 1993 -592 2320
   -57 240 -100 447 -170 813 -108 559 -164 803 -256 1107 -223 739 -541 1319
   -968 1766 -59 62 -102 110 -97 107 20 -11 461 -148 478 -148 25 0 57 36 57 66
   0 15 -12 37 -32 56 -53 49 -204 159 -328 238 -150 95 -268 183 -465 344 -631
   517 -1140 856 -1725 1150 -1004 506 -2012 758 -3295 826 -167 9 -976 11 -1110
   3z"/>
   </g>
   </svg>

```

Thanks for your help!

Body:
So here is my problem:
I have black and white images (img tags), and i want to change the color of it except for the black pixels. I used a code that allowed me to do this, but when coloring the image, some of the black pixels are colored too, not only the white as you can see in these images (some of the black lines are colored):

This is my code (to test it please change the image url to a local image so the color changing works)

let hex
var mug=document.getElementById("eyes");
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;
let currentcolor

function color(elem) {
  hex='rgb(0,0,0)'
  if (elem.classList[0].toString()=='color') {
    currentcolor=document.getElementById(elem.id).style.backgroundColor
    hex=currentcolor.toString()
  }

}

function color1(elem) {
document.getElementById(elem.id).style.fill=currentcolor
    getPixels(mug)
    hex=hex.substring(4, hex.length-1)
      .replace(/ /g, '')
      .split(',')
    changeColor(hex[0],hex[1],hex[2])
}

function getPixels(img)
{
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}

function hexToRGB(hex)
{
  console.log(hex)
    var long = parseInt(hex.replace(/^#/, ""), 16);
    return {
        R: (long >>> 16) & 0xff,
        G: (long >>> 8) & 0xff,
        B: long & 0xff
    };
}

function changeColor(a,b,c)
{
    if(!originalPixels) return; // Check if image has loaded
    var newColor = {R: eval(a), G: eval(b), B: eval(c)};

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
          console.log(currentPixels.data[I + 3])
           if ((currentPixels.data[I]!=0 && currentPixels.data[I+1]!=0 && currentPixels.data[I+2]!=0)) {
            currentPixels.data[I] = newColor.R;
            currentPixels.data[I + 1] = newColor.G;
            currentPixels.data[I + 2] = newColor.B;
           }
        }
    }
    console.log(newColor)
    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

#boite {
    width: 70%;
    height: 85%;
    border: 5px solid black;
    background-color: #e3e2d3;
    position: absolute;
    left: 0;
    right: 0;
    top: 5%;
    justify-content: center;
    display: flex;
    align-items: center;
    margin-left: 285px;
}
#corps{

    width: 300px;
}

#next2{
    position: absolute;
    width: 25%;
    height: 95%;
    text-align: center;
    justify-content: center;
    align-items: center;
    border-radius: 20px;
    border: 3px solid white;
    margin-left: 15px;
    margin-top: 15px;
    text-align: center;
    background-color: #B393DE;
}

#colours {

  color: #fff;
  justify-content: center;
  font: 100 24px/100px sans-serif;
  height: 150px;
  width: 100%;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
}

#colours div {
    height: 50%;
    width: 30%;
    border: 2px solid rgb(255, 255, 255);
    border-radius: 50%;
    cursor:pointer;
  }
.color{

    background-color: #888888;
}

<!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>

    <svg version="1.0" xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 1876.000000 2501.000000"
    preserveAspectRatio="xMidYMid meet" id="corps"  width="80%" height="80%">

   <g transform="translate(0.000000,2501.000000) scale(0.100000,-0.100000)"
   fill="white" stroke="none" id="issasvg" onclick="color1(this)" >
   <path d="M8615 24873 c-386 -22 -661 -48 -938 -88 -960 -140 -1780 -418 -2486
   -844 -317 -192 -473 -310 -721 -546 -164 -157 -264 -231 -362 -267 -44 -16
   -62 -28 -69 -46 -13 -34 6 -80 36 -88 12 -3 99 17 198 45 97 28 179 51 183 51
   5 0 -50 -39 -121 -86 -602 -401 -1138 -934 -1593 -1586 -602 -861 -1038 -1873
   -1357 -3148 -106 -420 -113 -462 -145 -834 -70 -801 -109 -1055 -242 -1591
   -139 -561 -163 -730 -163 -1145 0 -197 4 -325 13 -385 23 -153 62 -325 99
   -435 39 -119 144 -344 175 -377 22 -24 62 -30 88 -13 8 5 49 112 91 237 l76
   228 8 -50 c59 -407 298 -971 616 -1453 87 -132 132 -179 182 -193 95 -25 146
   38 175 217 9 57 20 104 24 104 4 0 8 -5 8 -10 0 -6 25 -67 56 -137 146 -331
   327 -595 579 -848 226 -227 390 -356 697 -547 l178 -110 -46 -57 c-935 -1156
   -1523 -2549 -1683 -3986 -37 -329 -45 -485 -45 -865 0 -388 13 -603 55 -945
   106 -867 372 -1742 769 -2534 67 -134 80 -151 119 -151 53 0 61 23 61 166 0
   71 3 152 6 181 l7 52 76 -112 c339 -495 585 -798 841 -1035 538 -498 1161
   -855 1925 -1105 779 -254 1708 -374 2624 -338 331 13 498 26 896 71 149 16
   275 30 280 30 16 -1 -64 -41 -140 -71 -81 -31 -104 -59 -83 -103 6 -15 23 -30
   37 -34 42 -12 555 -7 696 7 575 55 1056 184 1816 487 773 307 1301 585 1764
   929 441 326 806 720 1058 1139 60 100 77 122 82 106 3 -11 8 -105 9 -208 2
   -104 6 -195 11 -201 12 -20 53 -31 79 -21 41 15 261 480 408 865 693 1807 684
   3785 -27 5580 -301 759 -688 1413 -1243 2096 l-23 28 101 76 c213 161 427 344
   750 641 369 338 548 553 690 825 l57 111 17 -109 c9 -59 22 -125 28 -145 25
   -85 119 -123 188 -76 95 64 374 521 518 848 116 261 219 591 238 761 4 33 10
   57 14 52 4 -4 40 -106 80 -226 61 -186 76 -220 96 -229 53 -25 73 -5 155 157
   316 626 333 1410 49 2340 -29 94 -70 229 -92 300 -37 122 -514 1993 -592 2320
   -57 240 -100 447 -170 813 -108 559 -164 803 -256 1107 -223 739 -541 1319
   -968 1766 -59 62 -102 110 -97 107 20 -11 461 -148 478 -148 25 0 57 36 57 66
   0 15 -12 37 -32 56 -53 49 -204 159 -328 238 -150 95 -268 183 -465 344 -631
   517 -1140 856 -1725 1150 -1004 506 -2012 758 -3295 826 -167 9 -976 11 -1110
   3z"/>
   </g>
   </svg>

Thanks for your help!


问:
How to relaunch an electron/react application on crash
I have an application built with react and electron, here is the issue that is occurring.

Sometimes when launching the application it will have an uncaught exception because of some IPC communication that failed.

I added a handler for this in my electron entry point file according to the documentation. However, when it relaunches it does not launch MY application. It simply displays some electron template window.

Here is the handler I'm using:

```<code>    process.on("uncaughtException", function (err) {
    //log the message and stack trace
    log.warn("uncaught Exception: ", err);
    //relaunch the app
    app.relaunch({ args: [] });
    app.exit(0);
    handleLaunch(tray, window, store, __dirname);
  });
</code>```

The handleLaunch function is as such:

```<code>// Library Imports
const { app, BrowserWindow, dialog } = require("electron");
const { autoUpdater } = require("electron-updater");
const log = require("electron-log");
//Functions
const { createIpcBusBridge } = require("../ipc/createIpcBusBridge");
const { createWindow } = require("../window/createWindow");
const { createTray } = require("../tray/createTray");

const handleLaunch = (tray, window, store, directoryName) => {
  const isDev = !app.isPackaged;
  if (isDev === true) {
    const reactDevToolsId = "fmkadmapgofadopljbjfkapdkoienihi";
    const {
      default: installExtension,
      REDUX_DEVTOOLS,
    } = require("electron-devtools-installer");
    installExtension([REDUX_DEVTOOLS, reactDevToolsId])
      .then((name) => console.log(`Added Extension:  ${name}`))
      .catch((err) => console.log("An error occurred: ", err));
  }
  log.info("CREATING WINDOW...........");
  window = createWindow(directoryName, process, store, isDev);
  if (tray !== undefined) {
    tray.destroy();
  }

  tray = createTray(window, directoryName, process);
  createIpcBusBridge();

  app.on("activate", function () {
    /*
      On macOS it's common to re-create a window in the app when the
      dock icon is clicked and there are no other windows open.
    */
    if (BrowserWindow.getAllWindows().length === 0)
      createWindow(window, tray, directoryName, process, store);
  });

  if (isDev === false) {
    autoUpdater.on("update-available", (_event, releaseNotes, releaseName) => {
      const dialogOpts = {
        type: "info",
        buttons: ["Ok"],
        title: "Application Update",
        message: process.platform === "win32" ? releaseNotes : releaseName,
        detail: "A new version is being downloaded.",
      };
      dialog.showMessageBox(dialogOpts, (response) => {});
    });

    autoUpdater.on("update-downloaded", (_event, releaseNotes, releaseName) => {
      const dialogOpts = {
        type: "info",
        buttons: ["Restart", "Later"],
        title: "Application Update",
        message: process.platform === "win32" ? releaseNotes : releaseName,
        detail:
          "A new version has been downloaded. Restart the application to apply the updates.",
      };
      dialog.showMessageBox(dialogOpts).then((returnValue) => {
        if (returnValue.response === 0) autoUpdater.quitAndInstall();
      });
    });
  }
};

module.exports = { handleLaunch };
</code>```

Here is the createWindow function as requested by Kiran Maniya

```<code>// Library Imports
const { BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const url = require("url");
const log = require("electron-log");
// Functions
const { handleResolutionPref } = require("./handleResolutionPref");
const { handlePositionPref } = require("./handlePositionPref");
const { maximizeWindow } = require("./maximizeWindow");
const { minimizeWindow } = require("./minimizeWindow");
const { closeWindow } = require("./closeWindow");

const createWindow = (directoryName, process, store, isDev) => {
  try {
    const [screenWidth, screenHeight] = handleResolutionPref(store);
    const [screenXCoordinate, screenYCoordinate, isScreenPositionCustom] =
      handlePositionPref(store);

    let window = null;
    const browserWindowOptions = {
      width: screenWidth,
      height: screenHeight,
      frame: false,
      fullscreenable: true,
      resizable: true,
      transparent: false,
      webPreferences: {
        preload: path.join(directoryName, "preload.bundle.js"),
        contextIsolation: false,
        nodeIntegration: true,
        sandbox: false,
        webSecurity: false,
      },
      icon: path.join(directoryName, "icon.ico"),
    };

    // Create the browser window.
    if (isScreenPositionCustom === true) {
      browserWindowOptions.x = screenXCoordinate;
      browserWindowOptions.y = screenYCoordinate;

      window = new BrowserWindow(browserWindowOptions);
    } else {
      window = new BrowserWindow(browserWindowOptions);
    }

    window.on("closed", () => (window = null));

    if (isDev === true) {
      window.loadURL("http://localhost:3000");
    } else {
      window.loadURL(
        url.format({
          pathname: path.join(directoryName, "index.html"),
          protocol: "file:",
          slashes: true,
        })
      );
    }

    // Handle window toggling for custom titlebar
    ipcMain.on("windowMinimize", () => minimizeWindow(window));
    ipcMain.on("windowMaximize", () => maximizeWindow(window));
    ipcMain.on("windowClose", () => closeWindow(window));

    // Open the DevTools.
    // window.webContents.openDevTools()

    return window;
  } catch (error) {
    log.info("CREATE WINDOW ERROR INSIDE FUNCTION: ", error);
  }
};

module.exports = { createWindow };
</code>```

Where am I going wrong here?

Body:
I have an application built with react and electron, here is the issue that is occurring.

Sometimes when launching the application it will have an uncaught exception because of some IPC communication that failed.

I added a handler for this in my electron entry point file according to the documentation. However, when it relaunches it does not launch MY application. It simply displays some electron template window.

Here is the handler I'm using:

    process.on("uncaughtException", function (err) {
    //log the message and stack trace
    log.warn("uncaught Exception: ", err);
    //relaunch the app
    app.relaunch({ args: [] });
    app.exit(0);
    handleLaunch(tray, window, store, __dirname);
  });

The handleLaunch function is as such:

// Library Imports
const { app, BrowserWindow, dialog } = require("electron");
const { autoUpdater } = require("electron-updater");
const log = require("electron-log");
//Functions
const { createIpcBusBridge } = require("../ipc/createIpcBusBridge");
const { createWindow } = require("../window/createWindow");
const { createTray } = require("../tray/createTray");

const handleLaunch = (tray, window, store, directoryName) => {
  const isDev = !app.isPackaged;
  if (isDev === true) {
    const reactDevToolsId = "fmkadmapgofadopljbjfkapdkoienihi";
    const {
      default: installExtension,
      REDUX_DEVTOOLS,
    } = require("electron-devtools-installer");
    installExtension([REDUX_DEVTOOLS, reactDevToolsId])
      .then((name) => console.log(`Added Extension:  ${name}`))
      .catch((err) => console.log("An error occurred: ", err));
  }
  log.info("CREATING WINDOW...........");
  window = createWindow(directoryName, process, store, isDev);
  if (tray !== undefined) {
    tray.destroy();
  }

  tray = createTray(window, directoryName, process);
  createIpcBusBridge();

  app.on("activate", function () {
    /*
      On macOS it's common to re-create a window in the app when the
      dock icon is clicked and there are no other windows open.
    */
    if (BrowserWindow.getAllWindows().length === 0)
      createWindow(window, tray, directoryName, process, store);
  });

  if (isDev === false) {
    autoUpdater.on("update-available", (_event, releaseNotes, releaseName) => {
      const dialogOpts = {
        type: "info",
        buttons: ["Ok"],
        title: "Application Update",
        message: process.platform === "win32" ? releaseNotes : releaseName,
        detail: "A new version is being downloaded.",
      };
      dialog.showMessageBox(dialogOpts, (response) => {});
    });

    autoUpdater.on("update-downloaded", (_event, releaseNotes, releaseName) => {
      const dialogOpts = {
        type: "info",
        buttons: ["Restart", "Later"],
        title: "Application Update",
        message: process.platform === "win32" ? releaseNotes : releaseName,
        detail:
          "A new version has been downloaded. Restart the application to apply the updates.",
      };
      dialog.showMessageBox(dialogOpts).then((returnValue) => {
        if (returnValue.response === 0) autoUpdater.quitAndInstall();
      });
    });
  }
};

module.exports = { handleLaunch };

Here is the createWindow function as requested by Kiran Maniya

// Library Imports
const { BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const url = require("url");
const log = require("electron-log");
// Functions
const { handleResolutionPref } = require("./handleResolutionPref");
const { handlePositionPref } = require("./handlePositionPref");
const { maximizeWindow } = require("./maximizeWindow");
const { minimizeWindow } = require("./minimizeWindow");
const { closeWindow } = require("./closeWindow");

const createWindow = (directoryName, process, store, isDev) => {
  try {
    const [screenWidth, screenHeight] = handleResolutionPref(store);
    const [screenXCoordinate, screenYCoordinate, isScreenPositionCustom] =
      handlePositionPref(store);

    let window = null;
    const browserWindowOptions = {
      width: screenWidth,
      height: screenHeight,
      frame: false,
      fullscreenable: true,
      resizable: true,
      transparent: false,
      webPreferences: {
        preload: path.join(directoryName, "preload.bundle.js"),
        contextIsolation: false,
        nodeIntegration: true,
        sandbox: false,
        webSecurity: false,
      },
      icon: path.join(directoryName, "icon.ico"),
    };

    // Create the browser window.
    if (isScreenPositionCustom === true) {
      browserWindowOptions.x = screenXCoordinate;
      browserWindowOptions.y = screenYCoordinate;

      window = new BrowserWindow(browserWindowOptions);
    } else {
      window = new BrowserWindow(browserWindowOptions);
    }

    window.on("closed", () => (window = null));

    if (isDev === true) {
      window.loadURL("http://localhost:3000");
    } else {
      window.loadURL(
        url.format({
          pathname: path.join(directoryName, "index.html"),
          protocol: "file:",
          slashes: true,
        })
      );
    }

    // Handle window toggling for custom titlebar
    ipcMain.on("windowMinimize", () => minimizeWindow(window));
    ipcMain.on("windowMaximize", () => maximizeWindow(window));
    ipcMain.on("windowClose", () => closeWindow(window));

    // Open the DevTools.
    // window.webContents.openDevTools()

    return window;
  } catch (error) {
    log.info("CREATE WINDOW ERROR INSIDE FUNCTION: ", error);
  }
};

module.exports = { createWindow };

Where am I going wrong here?


问:
How to make a model's instance value dependent of another model instance(as an attribute)
Basically, I am trying to have an endpoint that acts as a property of my User model.

What I want my Django program to perform:

I want a User instance to have its own unique friend model in which it will have its own friends.

My problem:

Each User instance have the same friends(so, the same friend model value).

My code:

```<code># MODELS.PY
class friend(models.Model):
    my_tag = User.usertag
    friend_tag = models.CharField(max_length=7, primary_key=True)
</code>```
```<code>class User(models.Model):
    f_name = models.CharField(max_length=15)
    l_name = models.CharField(max_length=15)
    usertag = models.CharField(max_length=7, default="no tags inputed!")
    level = models.IntegerField(default=1)
    profile_pic = models.URLField(max_length=10000)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=25)
</code>```
```<code># Views.py
class listFriends(generics.ListAPIView):
    queryset = friend.objects.all()
    serializer_class = FriendSerializer
    permission_classes = [permissions.IsAuthenticated]
    lookup_field = "my_tag"
    lookup_url_kwarg = "username"

list_friends = listFriends.as_view()
</code>```

Body:
Basically, I am trying to have an endpoint that acts as a property of my User model.

What I want my Django program to perform:

I want a User instance to have its own unique friend model in which it will have its own friends.

My problem:

Each User instance have the same friends(so, the same friend model value).

My code:

# MODELS.PY
class friend(models.Model):
    my_tag = User.usertag
    friend_tag = models.CharField(max_length=7, primary_key=True)

class User(models.Model):
    f_name = models.CharField(max_length=15)
    l_name = models.CharField(max_length=15)
    usertag = models.CharField(max_length=7, default="no tags inputed!")
    level = models.IntegerField(default=1)
    profile_pic = models.URLField(max_length=10000)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=25)

# Views.py
class listFriends(generics.ListAPIView):
    queryset = friend.objects.all()
    serializer_class = FriendSerializer
    permission_classes = [permissions.IsAuthenticated]
    lookup_field = "my_tag"
    lookup_url_kwarg = "username"

list_friends = listFriends.as_view()


问:
Error when using a Select Option with Express
I can't get my database to be updated, because when using req.body with my form to capture the data, it seems to be giving me an error. The Javascript in my express route looks like this:

```<code>let goalUpdate = await db.goal.update({
                    name: req.body.name,
                    description: req.body.description,
                    due_date: req.body.dueDate,
                    complete: req.body.progress,
                    public: req.body.public
                },
                {
                where: {id: req.params.goalId }
            })
            console.log('this is the goal progress', goalUpdate.complete)
               res.redirect(`/goals/${goal.id}`)
</code>```

My form to select the data looks like this:

```<code><label for="progress">Update goal's progress:</label>
<select class="form-select form-select-lg mb-3"
        aria-label=".form-select-lg example"
        id="progress"
        name="progress"
        form="update-goal">
    <option selected> Update Progress </option>
    <option value="Not-Started"> Not Started </option>
    <option value="In-Progress"> In Progress </option>
    <option value="Complete"> Complete </option>
</select>
</code>```

And the error message with in terminal when doing console.log looks like this:

```<code>this is the first console.log in the PUT method 4
[Object: null prototype] {
  name: 'cat vacation',
  description: 'backyard bbq, BYO salmon & catnip',
  dueDate: '2023-01-17',
  _method: ''
}
Executing (default): UPDATE "goals" SET "name"=$1,"description"=$2,"due_date"=$3,"updatedAt"=$4 WHERE "id" = $5
this is the goal progress undefined
</code>```

You can see that _method is in the spot where my selector information should be. Why is this?

I tried console logging the errors and updating information, but have not been successful in determining the error

Body:
I can't get my database to be updated, because when using req.body with my form to capture the data, it seems to be giving me an error. The Javascript in my express route looks like this:

let goalUpdate = await db.goal.update({
                    name: req.body.name,
                    description: req.body.description,
                    due_date: req.body.dueDate,
                    complete: req.body.progress,
                    public: req.body.public
                },
                {
                where: {id: req.params.goalId }
            })
            console.log('this is the goal progress', goalUpdate.complete)
               res.redirect(`/goals/${goal.id}`)

My form to select the data looks like this:

Update goal's progress:
<select class="form-select form-select-lg mb-3"
        aria-label=".form-select-lg example"
        id="progress"
        name="progress"
        form="update-goal">
    <option selected> Update Progress </option>
    <option value="Not-Started"> Not Started </option>
    <option value="In-Progress"> In Progress </option>
    <option value="Complete"> Complete </option>
</select>

And the error message with in terminal when doing console.log looks like this:

this is the first console.log in the PUT method 4
[Object: null prototype] {
  name: 'cat vacation',
  description: 'backyard bbq, BYO salmon & catnip',
  dueDate: '2023-01-17',
  _method: ''
}
Executing (default): UPDATE "goals" SET "name"=$1,"description"=$2,"due_date"=$3,"updatedAt"=$4 WHERE "id" = $5
this is the goal progress undefined

You can see that _method is in the spot where my selector information should be. Why is this?

I tried console logging the errors and updating information, but have not been successful in determining the error


问:
Spring Boot: can't get API key into the docker container
I created an spring boot application that makes API calls. I have been given an API key that I added to my system environment variables as API_KEY

At first, I had my urls as
String uri = "http://api-site.com/.../key="+System.getenv("API_KEY")+"&..."
and this works just fine when I run it locally.

However, when I build and run the image, I get 403 error.
My Dockerfile looks like:

```<code>FROM maven:3.5.4-jdk-8-alpine AS builder

COPY pom.xml pom.xml
COPY src/ src/

RUN mvn clean package

FROM openjdk:11 AS runner

**ENV API_KEY $API_KEY**

EXPOSE 8080

COPY --from=builder target/app-0.0.1.jar app.jar

ENTRYPOINT [ "java", "-jar", "app.jar" ]
</code>```

I'm guessing System.getenv("API_KEY") does not work in containers.
Is there a way to get it to work?

I've tried the other syntax for the environment variable in the Dockerfile: ENV API_KEY=${API_KEY}

I have also tried using application.properties but I have not been able to get that to work (this might need to be a whole other question). I can't even get test variables to print.
I have test.name=testname in applications.properties
In a class I have:

```<code>@Component
@PropertySource("classpath:application.properties")
public class AC {
    @Value("${test.name}")
    public String test;

    public static void main(String[] args){
        System.out.println(test);
    }
}
</code>```

This just prints out null every time.

Thank you in advance!

Body:
I created an spring boot application that makes API calls. I have been given an API key that I added to my system environment variables as API_KEY

At first, I had my urls as
String uri = "http://api-site.com/.../key="+System.getenv("API_KEY")+"&..."
and this works just fine when I run it locally.

However, when I build and run the image, I get 403 error.
My Dockerfile looks like:

FROM maven:3.5.4-jdk-8-alpine AS builder

COPY pom.xml pom.xml
COPY src/ src/

RUN mvn clean package

FROM openjdk:11 AS runner

**ENV API_KEY $API_KEY**

EXPOSE 8080

COPY --from=builder target/app-0.0.1.jar app.jar

ENTRYPOINT [ "java", "-jar", "app.jar" ]

I'm guessing System.getenv("API_KEY") does not work in containers.
Is there a way to get it to work?

I've tried the other syntax for the environment variable in the Dockerfile: ENV API_KEY=${API_KEY}

I have also tried using application.properties but I have not been able to get that to work (this might need to be a whole other question). I can't even get test variables to print.
I have test.name=testname in applications.properties
In a class I have:

@Component
@PropertySource("classpath:application.properties")
public class AC {
    @Value("${test.name}")
    public String test;

    public static void main(String[] args){
        System.out.println(test);
    }
}

This just prints out null every time.

Thank you in advance!


问:
Sinatra Upload multiple files with associated model
i'm trying to make a image gallery with sinatra but a thing that should be simple task is confusing and has a lack of doc and tutorial about it!

```<code>So please can someone give a light about this?
</code>```

for upload i'm using shrine

my biggest doubt is related with name params, should use the galleries model or just images?

```<code>    class Post < ActiveRecord::Base
      validates :title, :content, presence: true, on: :create
      has_many :galleries, dependent: :destroy
      accepts_nested_attributes_for :galleries, allow_destroy: true
    end

require_relative "../uploaders/image_uploader"
class Gallery < ActiveRecord::Base

  belongs_to :post
  validates :image, presence: true, on: :create

  include ImageUploader::Attachment.new(:image)

  scope :recent, -> { order('created_at desc') }

  #  validates_size_of :images, maximum: 2.megabyte, message: "Attachment size exceeds the allowable limit (2 MB)."
end
</code>```

post controller

```<code>  post "/posts" do
    @post = Post.new(params[:post])
    @post.user = current_user

    @post.image_derivatives! if @post.image_changed? # creates derivatives
    if @post.save
        # unless params[:galleries].blank?
          # params[:galleries]['image'].each do |a|
         # @post.galleries.create!(:image => a)
        #end
       # end

        if params[:post][:galleries][:image] && params[:post][:galleries][:image][:filename]
          filename = params[:image][:filename]
          file = params[:image][:tempfile]
          path = "./public/uploads/#{filename}"

          # Write file to disk
          File.open(path, "wb") { |f| f.write(file.read) }
        end

      redirect "/posts/#{@post.slug}"
    else
      @errors = @post.errors

      erb :"/posts/new"
    end
  end
</code>```

Body:
i'm trying to make a image gallery with sinatra but a thing that should be simple task is confusing and has a lack of doc and tutorial about it!

So please can someone give a light about this?

for upload i'm using shrine

my biggest doubt is related with name params, should use the galleries model or just images?

    class Post < ActiveRecord::Base
      validates :title, :content, presence: true, on: :create
      has_many :galleries, dependent: :destroy
      accepts_nested_attributes_for :galleries, allow_destroy: true
    end

require_relative "../uploaders/image_uploader"
class Gallery < ActiveRecord::Base

  belongs_to :post
  validates :image, presence: true, on: :create

  include ImageUploader::Attachment.new(:image)

  scope :recent, -> { order('created_at desc') }

  #  validates_size_of :images, maximum: 2.megabyte, message: "Attachment size exceeds the allowable limit (2 MB)."
end

post controller

  post "/posts" do
    @post = Post.new(params[:post])
    @post.user = current_user

    @post.image_derivatives! if @post.image_changed? # creates derivatives
    if @post.save
        # unless params[:galleries].blank?
          # params[:galleries]['image'].each do |a|
         # @post.galleries.create!(:image => a)
        #end
       # end

        if params[:post][:galleries][:image] && params[:post][:galleries][:image][:filename]
          filename = params[:image][:filename]
          file = params[:image][:tempfile]
          path = "./public/uploads/#{filename}"

          # Write file to disk
          File.open(path, "wb") { |f| f.write(file.read) }
        end

      redirect "/posts/#{@post.slug}"
    else
      @errors = @post.errors

      erb :"/posts/new"
    end
  end


问:
PaddlePaddle docker registry differences
I am trying to pull in a paddle image from docker hub here. I do not understand what the trt means at the end of some of the versions i.e. 2.4.0rc0-gpu-cuda10.2-cudnn7.6-trt7.0. I see there are some versions without trt and I am wondering the difference is? Is there a doc somewhere that explains how the docker images are versioned for paddle?


问:
Keep original creation & modification timestamp while exporting with quicktime using applescript
I realized that my GoPro videos are very large and that I can compress them by around 80% by loading the video in Quicktime and exporting the video in the 1080p format.

I found this automation for my problem: applescript to batch export with quicktime pro

Unfortunately, I use to batch rename my video files according to the date & time taken (e.g. "2022-10-12, 15.24.13.mp4"). For the compressed video file, the creation & modification timestamp is not copied from the original file.

Any idea, how I can keep the original creation & modification timestamp for the compressed file? Or copy the creation & modification timestampe later from the original file into the compressed file? Maybe it helps that the files are named similarly except that the extension changes from "mp4" to "mov".

Thanks a lot in advance for any help!


问:
How do I add values to parameters in namedtuple() using a loop?
```<code>from collections import namedtuple

categories = ['cigarettes', 'snuff', 'cigarillos']
cigarette_brands = ['camel', 'american_spirit']
cigarillo_brands = ['good_times', 'black_and_mild']
snuff_brands = ['grizzly', 'copenhagen', 'kodiak']
cam_cig_flavors = ['blue_king', 'blue_100', 'full_flavor_king', 'full_flavor_100', 'menthol_king', 'menthol_100' 'menthol_gold_king', 'menthol_gold_100', 'non_filter', 'silver_100']

tobacco = namedtuple('Tobacco', categories)
tobacco.cigarettes = namedtuple('Cigarettes', cigarette_brands)
tobacco.snuff = namedtuple('Snuff', snuff_brands)
tobacco.cigarillos = namedtuple('Cigarillos', cigarillo_brands)

tobacco.cigarettes.camel = namedtuple('Camel', cam_cig_flavors)
for flavor cam_cig_flavors:
    tobacco.cigarettes.camel.flavor = '$57.35'
</code>```

I am trying to set the price of individual flavors using the for loop:

```<code>for flavor in cam_cig_flavors:
    tobacco.cigarettes.camel.flavor = '$57.35'
</code>```

I want to get the following output for
print(tobacco.cigarettes.camel.full_flavor_king)

> $57.35

I know it's setting tobacco.cigarettes.camel.flavor equal to $57.35 instead of iterating through flavors.
How can I make it iterate through flavors instead?
For example, I want it to do the following in each iteration:

tobacco.cigarettes.camel.blue_king = '$57.35'

then,

tobacco.cigarettes.camel.blue_100 = '$57.35'

so on and so forth.

Body:
from collections import namedtuple

categories = ['cigarettes', 'snuff', 'cigarillos']
cigarette_brands = ['camel', 'american_spirit']
cigarillo_brands = ['good_times', 'black_and_mild']
snuff_brands = ['grizzly', 'copenhagen', 'kodiak']
cam_cig_flavors = ['blue_king', 'blue_100', 'full_flavor_king', 'full_flavor_100', 'menthol_king', 'menthol_100' 'menthol_gold_king', 'menthol_gold_100', 'non_filter', 'silver_100']

tobacco = namedtuple('Tobacco', categories)
tobacco.cigarettes = namedtuple('Cigarettes', cigarette_brands)
tobacco.snuff = namedtuple('Snuff', snuff_brands)
tobacco.cigarillos = namedtuple('Cigarillos', cigarillo_brands)

tobacco.cigarettes.camel = namedtuple('Camel', cam_cig_flavors)
for flavor cam_cig_flavors:
    tobacco.cigarettes.camel.flavor = '$57.35'

I am trying to set the price of individual flavors using the for loop:

for flavor in cam_cig_flavors:
    tobacco.cigarettes.camel.flavor = '$57.35'

I want to get the following output for
print(tobacco.cigarettes.camel.full_flavor_king)

> $57.35

I know it's setting tobacco.cigarettes.camel.flavor equal to $57.35 instead of iterating through flavors.
How can I make it iterate through flavors instead?
For example, I want it to do the following in each iteration:

tobacco.cigarettes.camel.blue_king = '$57.35'

then,

tobacco.cigarettes.camel.blue_100 = '$57.35'

so on and so forth.


问:
React Native doesn't seem to rerender correctly after multiple times
Right now I have a navbar at the bottom of my screen that has a link to a user's notifications. When I click the notification button the first time it works, I can see the notification list ("PractNotificationIndex"). From there, if I click a notification, it takes me to the user's profile to send that notification. Now when I'm on that profile screen, there's still a navbar at the bottom the user can use. If I click on the notification button again, I can repeat the process of going to the user's profile.

NavigationBar.js:

```<code>async componentDidMount(){
      console.log("NAV BAR MOUNTED")
      //const initialNotificationsList = this.getInitialNotificationList()
      const patientEmail = this.props.extraData.user
      const getInitialNotificationList = await axios
      .post(
        "http://192.168.2.99:3001/graphql",
        {
          "query": `query getNotifications($email: String!) {
            getNotifications(email: $email) {
          date
          practEmail
          patientEmail
          timeStart
          timeEnd
          accepted
          client
                  }
                  }`,

          "variables": {
              "email": patientEmail
              }
        },
      )

      const initialNotificationList = getInitialNotificationList.data.data.getNotifications
      //console.log("INITIAL NOTI LIST", initialNotificationList)
      var notificationsConcat = this.state.notifications.concat(initialNotificationList)
      //console.log("NOTI CONCAT", notificationsConcat)
      this.setState({notifications:notificationsConcat})
      // subscribe to the notifications events endpoint
      // const options = {
      //   method: "GET",
      //   timeout: 0,
      //   body: this.props.practData
      // }
      const practEmail = this.props.extraData.user
      const options = { headers: { practEmail: practEmail } }
      console.log("PRACT EMAIL NOTI NAV BAR", this.props.extraData)

      const events = new EventSource("http://192.168.2.99:3001/pract_notifications", options)

      events.addEventListener("error", (event) => {
        if (event.type === "error") {
          console.error("Connection error:", event.message);
        } else if (event.type === "exception") {
          console.error("Error:", event.message, event.error);
        }
      })

      events.addEventListener("close", (event) => {
        console.log("CLOSED SSE CONNECTION!!")
        // clear the state because it will repopulate upon reconnection
        events.close()
        this.setState({notifications: []})

      })

      this.setState({listening:true})
      return events
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
        style={styles.groupContainer}
        {/* NAVIGATE TO NOTIFICATION LIST HERE!*/}
        onPress={() => this.props.navigation.push("PractNotificationIndex", {notifications: this.state.notifications})}
        >
          <Image source={NavProfile} />
          <Text style={styles.navText}>{this.state.notifications.length}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
</code>```

But, now once I'm on the profile and click the notifications button, it reveals the notifications list, but it's not rerendering it. The log messages that are supposed to print out don't get printed, but the component still gets displayed fine. And when I click a notification nothing happens immediately. After like 10 minutes it will navigate where it's supposed to.

PractNotificationIndex.js

```<code>class PractNotificationIndex extends Component {
  constructor(props) {
    super(props);
    this.state = {
      //notifications: this.props.route.params.notifications,
      events: null,
      notifications: [],
      listening: false,
      user: {}
    }

    this.handleStateChange = this.handleStateChange.bind(this)
    console.log("NOTI INDEX PROPS", this.props)
  }

  componentDidMount(){
    const initialNotificationList = this.props.route.params.notifications
    var notificationsConcat = this.state.notifications.concat(initialNotificationList)
    this.setState({notifications:notificationsConcat})

    const practEmail = this.props.extraData.user
    const options = { headers: { practEmail: practEmail } }
    const events = new EventSource("https://**.com/pract_notifications", options)

    events.addEventListener("error", (event) => {
      if (event.type === "error") {
        console.error("Connection error:", event.message);
      } else if (event.type === "exception") {
        console.error("Error:", event.message, event.error);
      }
    })

    events.addEventListener("close", (event) => {
      console.log("CLOSED INDEX SSE CONNECTION!!")
      // clear the state because it will repopulate upon reconnection
      events.close()
      this.setState({notifications: []})

    })

    this.setState({listening:true})
  }

  render() {
    // use a map to iterate through the results array so they can be displayed in the results
      return (
        <View style={styles.container}>
          {
            this.state.notifications.length > 0 ?
            <ScrollView>
            {this.state.notifications.map((noti, key) =>
            <PractNotification key={key} navigation={this.props.navigation} extraData={{notifications: noti}}/>
            )}
          </ScrollView> : <Text> No new Notifications </Text>}
        </View>
      );

  }
}

});

export default PractNotificationIndex;
</code>```

Is some navigation loop happening that's causing this issue? I'm really confused as to why it's happening, I just want to be able to click the navbar from any screen

Body:
Right now I have a navbar at the bottom of my screen that has a link to a user's notifications. When I click the notification button the first time it works, I can see the notification list ("PractNotificationIndex"). From there, if I click a notification, it takes me to the user's profile to send that notification. Now when I'm on that profile screen, there's still a navbar at the bottom the user can use. If I click on the notification button again, I can repeat the process of going to the user's profile.

NavigationBar.js:

async componentDidMount(){
      console.log("NAV BAR MOUNTED")
      //const initialNotificationsList = this.getInitialNotificationList()
      const patientEmail = this.props.extraData.user
      const getInitialNotificationList = await axios
      .post(
        "http://192.168.2.99:3001/graphql",
        {
          "query": `query getNotifications($email: String!) {
            getNotifications(email: $email) {
          date
          practEmail
          patientEmail
          timeStart
          timeEnd
          accepted
          client
                  }
                  }`,

          "variables": {
              "email": patientEmail
              }
        },
      )

      const initialNotificationList = getInitialNotificationList.data.data.getNotifications
      //console.log("INITIAL NOTI LIST", initialNotificationList)
      var notificationsConcat = this.state.notifications.concat(initialNotificationList)
      //console.log("NOTI CONCAT", notificationsConcat)
      this.setState({notifications:notificationsConcat})
      // subscribe to the notifications events endpoint
      // const options = {
      //   method: "GET",
      //   timeout: 0,
      //   body: this.props.practData
      // }
      const practEmail = this.props.extraData.user
      const options = { headers: { practEmail: practEmail } }
      console.log("PRACT EMAIL NOTI NAV BAR", this.props.extraData)

      const events = new EventSource("http://192.168.2.99:3001/pract_notifications", options)

      events.addEventListener("error", (event) => {
        if (event.type === "error") {
          console.error("Connection error:", event.message);
        } else if (event.type === "exception") {
          console.error("Error:", event.message, event.error);
        }
      })

      events.addEventListener("close", (event) => {
        console.log("CLOSED SSE CONNECTION!!")
        // clear the state because it will repopulate upon reconnection
        events.close()
        this.setState({notifications: []})

      })

      this.setState({listening:true})
      return events
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
        style={styles.groupContainer}
        {/* NAVIGATE TO NOTIFICATION LIST HERE!*/}
        onPress={() => this.props.navigation.push("PractNotificationIndex", {notifications: this.state.notifications})}
        >
          <Image source={NavProfile} />
          <Text style={styles.navText}>{this.state.notifications.length}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

But, now once I'm on the profile and click the notifications button, it reveals the notifications list, but it's not rerendering it. The log messages that are supposed to print out don't get printed, but the component still gets displayed fine. And when I click a notification nothing happens immediately. After like 10 minutes it will navigate where it's supposed to.

PractNotificationIndex.js

class PractNotificationIndex extends Component {
  constructor(props) {
    super(props);
    this.state = {
      //notifications: this.props.route.params.notifications,
      events: null,
      notifications: [],
      listening: false,
      user: {}
    }

    this.handleStateChange = this.handleStateChange.bind(this)
    console.log("NOTI INDEX PROPS", this.props)
  }

  componentDidMount(){
    const initialNotificationList = this.props.route.params.notifications
    var notificationsConcat = this.state.notifications.concat(initialNotificationList)
    this.setState({notifications:notificationsConcat})

    const practEmail = this.props.extraData.user
    const options = { headers: { practEmail: practEmail } }
    const events = new EventSource("https://**.com/pract_notifications", options)

    events.addEventListener("error", (event) => {
      if (event.type === "error") {
        console.error("Connection error:", event.message);
      } else if (event.type === "exception") {
        console.error("Error:", event.message, event.error);
      }
    })

    events.addEventListener("close", (event) => {
      console.log("CLOSED INDEX SSE CONNECTION!!")
      // clear the state because it will repopulate upon reconnection
      events.close()
      this.setState({notifications: []})

    })

    this.setState({listening:true})
  }

  render() {
    // use a map to iterate through the results array so they can be displayed in the results
      return (
        <View style={styles.container}>
          {
            this.state.notifications.length > 0 ?
            <ScrollView>
            {this.state.notifications.map((noti, key) =>
            <PractNotification key={key} navigation={this.props.navigation} extraData={{notifications: noti}}/>
            )}
          </ScrollView> : <Text> No new Notifications </Text>}
        </View>
      );

  }
}

});

export default PractNotificationIndex;

Is some navigation loop happening that's causing this issue? I'm really confused as to why it's happening, I just want to be able to click the navbar from any screen


问:
How do I get coordinates regards Chart JS axis which is rendered on canvas?
I have a bubble chart which is rendered on canvas. I was trying to get coordinates from the chart area, not the whole canvas. But it gives me coordinates from the canvas area. After clicking on the chart, I wish it would show me the coordinates from the chart, not the whole canvas. Like if I click on X=10, Y=50, my click handler will return the same value, not the canvas pixel values.

var popCanvas = document.getElementById("bubbleChart");

    var radish = [
        {
            x: 200,
            y: 65.6,
            r: 8,
        }
    ];

    var popData = {
        datasets: [{
            label: 'Radish',
            data: radish,
            backgroundColor: '#4e73df',
            pointStyle: 'circle'
        }]
    };

    var bubbleChart = new Chart(popCanvas, {
        type: 'bubble',
        responsive: true,
        data: popData,
        options: {
            responsive: true,
            legend: {
                position: 'bottom',
            },
            hover: {
                mode: 'label'
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Width (cm)'
                    },
                    ticks: {
                        beginAtZero: true,
                        max: 250
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Height (cm)'
                    },
                    ticks: {
                        beginAtZero: true,
                        max: 100
                    }
                }]
            },
            title: {
                display: true,
                text: 'FarmBot Seed Bed'
            },
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        let datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
                        let xPosition = 'Width : '+ tooltipItem.xLabel;
                        let yPosition = 'Height : '+ tooltipItem.yLabel;
                        let waterStatus = 'Watering : '+ 'Yes';

                        return [ datasetLabel, xPosition, yPosition, waterStatus];
                    }
                }
            }
        }
    });

    document.getElementById("bubbleChart").addEventListener("click", (e) => {
        clickHandler(bubbleChart, e);
    });

    function clickHandler(chart,e) {
        let elem = document.querySelector('canvas');
        let rect = elem.getBoundingClientRect();

        let x = e.clientX - rect.left;
        let y = e.clientY - rect.top;
        console.log("Coordinate x: " + x,
            "Coordinate y: " + y);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

<div class="col-md-8">
    <canvas id="bubbleChart" width="600" height="400"></canvas>
</div></code>```

Body:
I have a bubble chart which is rendered on canvas. I was trying to get coordinates from the chart area, not the whole canvas. But it gives me coordinates from the canvas area. After clicking on the chart, I wish it would show me the coordinates from the chart, not the whole canvas. Like if I click on X=10, Y=50, my click handler will return the same value, not the canvas pixel values.

var popCanvas = document.getElementById("bubbleChart");

    var radish = [
        {
            x: 200,
            y: 65.6,
            r: 8,
        }
    ];

    var popData = {
        datasets: [{
            label: 'Radish',
            data: radish,
            backgroundColor: '#4e73df',
            pointStyle: 'circle'
        }]
    };

    var bubbleChart = new Chart(popCanvas, {
        type: 'bubble',
        responsive: true,
        data: popData,
        options: {
            responsive: true,
            legend: {
                position: 'bottom',
            },
            hover: {
                mode: 'label'
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Width (cm)'
                    },
                    ticks: {
                        beginAtZero: true,
                        max: 250
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Height (cm)'
                    },
                    ticks: {
                        beginAtZero: true,
                        max: 100
                    }
                }]
            },
            title: {
                display: true,
                text: 'FarmBot Seed Bed'
            },
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        let datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
                        let xPosition = 'Width : '+ tooltipItem.xLabel;
                        let yPosition = 'Height : '+ tooltipItem.yLabel;
                        let waterStatus = 'Watering : '+ 'Yes';

                        return [ datasetLabel, xPosition, yPosition, waterStatus];
                    }
                }
            }
        }
    });

    document.getElementById("bubbleChart").addEventListener("click", (e) => {
        clickHandler(bubbleChart, e);
    });

    function clickHandler(chart,e) {
        let elem = document.querySelector('canvas');
        let rect = elem.getBoundingClientRect();

        let x = e.clientX - rect.left;
        let y = e.clientY - rect.top;
        console.log("Coordinate x: " + x,
            "Coordinate y: " + y);
    }

    <canvas id="bubbleChart" width="600" height="400"></canvas>


问:
How do I have both a static function and class with the same name imported?
How can I have both a class and static function with the same name?

main.java

```<code>import static a.b.c;
import a.b.c;

public class main{
  public static void main(String[] args){
    c();
    c c2 = new c();
  }
}
</code>```

a/b.java

```<code>package a;

public class b{
  public class c{
   public c(){
     System.out.println("new c");
   }
  }
  public static void c(){
    System.out.println("c");
  }
}
</code>```

The following currently throws an error with the following.

```<code>main.java:7: error: an enclosing instance that contains b.c is required
    c c2 = new c();
           ^
1 error
</code>```

Body:
How can I have both a class and static function with the same name?

main.java

import static a.b.c;
import a.b.c;

public class main{
  public static void main(String[] args){
    c();
    c c2 = new c();
  }
}

a/b.java

package a;

public class b{
  public class c{
   public c(){
     System.out.println("new c");
   }
  }
  public static void c(){
    System.out.println("c");
  }
}

The following currently throws an error with the following.

main.java:7: error: an enclosing instance that contains b.c is required
    c c2 = new c();
           ^
1 error


问:
How to run scalatest testcases at Jenkins?
How to run the ScalaTest testcases at Jenkins using maven ?

I tried the below code snippet at my Jenkins file for executing the Test Stage:

```<code>    stage("Test") {
        if (!(env.BRANCH_NAME == "master")) {
            try {
                updateGitlabCommitStatus name: "Test", state: 'running'
                sh "mvn -B test"
                updateGitlabCommitStatus name: "Test", state: 'success'
            } catch (Exception exc) {
                logError("Test", exc)
            } finally {
                junit '*/target/surefire-reports/**/*.xml'
            }
        }
    }
</code>```

I have included the below plugins as well at pom.xml:

```<code>    <plugin>
    <!-- plugin allowing the Eclipse project to add /src/*/scala code to project classpath (by default /src/*/java is added) -->
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
            <execution>
                <id>add-source</id>
                <phase>generate-sources</phase>
                <goals>
                    <goal>add-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>src/main/scala</source>
                    </sources>
                </configuration>
            </execution>
            <execution>
                <id>add-test-source</id>
                <phase>generate-test-sources</phase>
                <goals>
                    <goal>add-test-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>src/test/scala</source>
                    </sources>
                </configuration>
            </execution>
        </executions>
    </plugin>

    <!-- disable Surefire in favor of ScalaTest plugin -->
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
            <skipTests>true</skipTests>
        </configuration>
    </plugin>
    <!-- Scala Coverage Tool -->
    <plugin>
        <groupId>org.scoverage</groupId>
        <artifactId>scoverage-maven-plugin</artifactId>
        <version>${scoverage.plugin.version}</version>
        <configuration>
            <skip>${scoverage.disabled}</skip>
            <scalaVersion>${scala.version}</scalaVersion>
            <aggregate>false</aggregate>
            <highlighting>${scoverage.highlighting}</highlighting>
            <excludedPackages>${scoverage.excludedPackages}</excludedPackages>
        </configuration>
        <executions>
            <execution>
                <id>packageReport</id>
                <phase>package</phase>
                <goals>
                    <goal>report</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</code>```

Build this way:

```<code>    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>${maven-scala-plugin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <phase>compile</phase>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                        <phase>test-compile</phase>
                    </execution>
                    <execution>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    </plugins>
    </build>
</code>```

Getting the below console output at Jenkins:

```<code>    [INFO] --- maven-scala-plugin:2.15.2:testCompile (test-compile) @ Project_name ---
    [INFO] Checking for multiple versions of scala
    [WARNING]  Expected all dependencies to require Scala version: 2.11.8
    [WARNING]  groupId:Project_name:4.6.0-SNAPSHOT requires scala version: 2.11.8
    [WARNING]  com.twitter:chill_2.11:0.8.0 requires scala version: 2.11.7
    [WARNING] Multiple versions of scala libraries detected!
    [INFO] includes = [**/*.java,**/*.scala,]
    [INFO] excludes = []
    [INFO] Nothing to compile - all classes are up to date
    [INFO]
    [INFO] --- maven-surefire-plugin:2.7:test (default-test) @ rds-core ---
    [INFO] Tests are skipped.
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  4.816 s
    [INFO] Finished at: 2023-01-02T23:45:28Z
    [INFO] ------------------------------------------------------------------------
    [Pipeline] updateGitlabCommitStatus
    [Pipeline] junit
    Recording test results
    No test report files were found. Configuration error?
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] }
    [Pipeline] // gitlabBuilds
    [Pipeline] }
    [Pipeline] // node
    [Pipeline] End of Pipeline
    ERROR: No test report files were found. Configuration error?
    Finished: FAILURE
</code>```

Please help here how to run my scalatest test cases at Jenkins

Body:
How to run the ScalaTest testcases at Jenkins using maven ?

I tried the below code snippet at my Jenkins file for executing the Test Stage:

    stage("Test") {
        if (!(env.BRANCH_NAME == "master")) {
            try {
                updateGitlabCommitStatus name: "Test", state: 'running'
                sh "mvn -B test"
                updateGitlabCommitStatus name: "Test", state: 'success'
            } catch (Exception exc) {
                logError("Test", exc)
            } finally {
                junit '*/target/surefire-reports/**/*.xml'
            }
        }
    }

I have included the below plugins as well at pom.xml:

    <plugin>

        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
            <execution>
                <id>add-source</id>
                <phase>generate-sources</phase>
                <goals>
                    <goal>add-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>src/main/scala</source>
                    </sources>
                </configuration>
            </execution>
            <execution>
                <id>add-test-source</id>
                <phase>generate-test-sources</phase>
                <goals>
                    <goal>add-test-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>src/test/scala</source>
                    </sources>
                </configuration>
            </execution>
        </executions>
    </plugin>

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
            <skipTests>true</skipTests>
        </configuration>
    </plugin>

    <plugin>
        <groupId>org.scoverage</groupId>
        <artifactId>scoverage-maven-plugin</artifactId>
        <version>${scoverage.plugin.version}</version>
        <configuration>
            <skip>${scoverage.disabled}</skip>
            <scalaVersion>${scala.version}</scalaVersion>
            <aggregate>false</aggregate>
            <highlighting>${scoverage.highlighting}</highlighting>
            <excludedPackages>${scoverage.excludedPackages}</excludedPackages>
        </configuration>
        <executions>
            <execution>
                <id>packageReport</id>
                <phase>package</phase>
                <goals>
                    <goal>report</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

Build this way:

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>${maven-scala-plugin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <phase>compile</phase>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                        <phase>test-compile</phase>
                    </execution>
                    <execution>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    </plugins>
    </build>

Getting the below console output at Jenkins:

    [INFO] --- maven-scala-plugin:2.15.2:testCompile (test-compile) @ Project_name ---
    [INFO] Checking for multiple versions of scala
    [WARNING]  Expected all dependencies to require Scala version: 2.11.8
    [WARNING]  groupId:Project_name:4.6.0-SNAPSHOT requires scala version: 2.11.8
    [WARNING]  com.twitter:chill_2.11:0.8.0 requires scala version: 2.11.7
    [WARNING] Multiple versions of scala libraries detected!
    [INFO] includes = [**/*.java,**/*.scala,]
    [INFO] excludes = []
    [INFO] Nothing to compile - all classes are up to date
    [INFO]
    [INFO] --- maven-surefire-plugin:2.7:test (default-test) @ rds-core ---
    [INFO] Tests are skipped.
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  4.816 s
    [INFO] Finished at: 2023-01-02T23:45:28Z
    [INFO] ------------------------------------------------------------------------
    [Pipeline] updateGitlabCommitStatus
    [Pipeline] junit
    Recording test results
    No test report files were found. Configuration error?
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] }
    [Pipeline] // gitlabBuilds
    [Pipeline] }
    [Pipeline] // node
    [Pipeline] End of Pipeline
    ERROR: No test report files were found. Configuration error?
    Finished: FAILURE

Please help here how to run my scalatest test cases at Jenkins


问:
Authenticating with phone for firebase using React Native
I am trying to authenticate via phone on Firebase using React Native. I have tried many different solutions and imports, but I can't seem to get it working. I am getting a lot of conflicting information about what import statements I should be using.

What import statement should I be using?
What auth functions should I be using?


问:
I'm not getting any error aswell as an output, I have just started with python
I'm writing this program copying from the online course I'm learning, I've copied exactly the same still it is not working for me. definitely there is an error when an output is not coming. But I'm unsure as to where the error is. So i'm trying to get the output for employee of month and current_max for a tuple that is created. to figure out which person is employee of month and the time he spent.</p>
```<code>work_hours = [('sam', 300), ('ream',200), ('deam', 400)]
def employee_check (work_hours) :
    current_max = 0
    employee_of_month = ''

    for employee, hours in work_hours:
        if hours > current_max:
            current_max = hours
            employee_of_month = employee
        else:
            pass
    return (employee_of_month, current_max)
employee_check(work_hours)
</code>```

Body:
I'm writing this program copying from the online course I'm learning, I've copied exactly the same still it is not working for me. definitely there is an error when an output is not coming. But I'm unsure as to where the error is. So i'm trying to get the output for employee of month and current_max for a tuple that is created. to figure out which person is employee of month and the time he spent.

work_hours = [('sam', 300), ('ream',200), ('deam', 400)]
def employee_check (work_hours) :
    current_max = 0
    employee_of_month = ''

    for employee, hours in work_hours:
        if hours > current_max:
            current_max = hours
            employee_of_month = employee
        else:
            pass
    return (employee_of_month, current_max)
employee_check(work_hours)


问:
java.nio.channels.UnsupportedAddressTypeException
I'm building a test gRPC server with Mill using ScalaPBModule. I can successfully build (with server.assembly) and start the server, but when it is hit with a request, the client throws this error:

Suppressed: java.nio.channels.UnsupportedAddressTypeException: null
at java.base/sun.nio.ch.Net.checkAddress(Net.java:127)
...
io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)

(I am sure there is no problem with the client.)

Here is my build config:

```<code>object server extends ScalaPBModule {
  def scalaVersion = "2.13.5"
  def scalaPBVersion = "0.11.12"
  override def scalaPBGrpc = true

  def ivyDeps = Agg(
    ivy"dev.zio::zio:2.0.5",
    // ivy"dev.zio::zio_3:2.0.5",
    // ivy"dev.zio::zio-direct:1.0.0-RC1",
    ivy"dev.zio::zio-direct:1.0.0-RC1+8-da53f9ae-SNAPSHOT",
    // ivy"dev.zio::zio-direct_3:1.0.0-RC1",
    ivy"org.mongodb.scala::mongo-scala-driver:4.8.0",
    ivy"io.grpc:grpc-netty:1.51.1", // ${scalapb.compiler.Version.grpcJavaVersion}",
    ivy"io.grpc:grpc-alts:1.51.1",
    ivy"io.grpc:grpc-protobuf:1.51.1",
    ivy"io.grpc:grpc-stub:1.51.1",
    ivy"io.grpc:grpc-testing:1.51.1",
    ivy"com.thesamet.scalapb::scalapb-runtime-grpc:0.11.12",
    ivy"com.thesamet.scalapb.zio-grpc::zio-grpc-core:0.0.0+1-02300782-SNAPSHOT"
  )
}
</code>```

I see others reporting this problem with gradle and maven and solving it with shadowing, etc. - how can this be done with Mill? Appreciate any help!

EDIT: The problem is the client, not the server; here is my client code.

EDIT 2: The code is irrelevant; it's a packaging issue as I suggested initially.

```<code>object Main extends ZIOAppDefault {
  val app = for {
    args <- getArgs
    channel <- ZIO.attempt(ManagedChannelBuilder.forAddress(args(0), 50051).usePlaintext().build)
    stub <- ZIO.attempt(TestGrpc.stub(channel))
    _ <- ZIO.fromFuture(_ => createMessage(stub))
  } yield ()
</code>```

Client deps are the same.

Body:
I'm building a test gRPC server with Mill using ScalaPBModule. I can successfully build (with server.assembly) and start the server, but when it is hit with a request, the client throws this error:

Suppressed: java.nio.channels.UnsupportedAddressTypeException: null
at java.base/sun.nio.ch.Net.checkAddress(Net.java:127)
...
io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)

(I am sure there is no problem with the client.)

Here is my build config:

object server extends ScalaPBModule {
  def scalaVersion = "2.13.5"
  def scalaPBVersion = "0.11.12"
  override def scalaPBGrpc = true

  def ivyDeps = Agg(
    ivy"dev.zio::zio:2.0.5",
    // ivy"dev.zio::zio_3:2.0.5",
    // ivy"dev.zio::zio-direct:1.0.0-RC1",
    ivy"dev.zio::zio-direct:1.0.0-RC1+8-da53f9ae-SNAPSHOT",
    // ivy"dev.zio::zio-direct_3:1.0.0-RC1",
    ivy"org.mongodb.scala::mongo-scala-driver:4.8.0",
    ivy"io.grpc:grpc-netty:1.51.1", // ${scalapb.compiler.Version.grpcJavaVersion}",
    ivy"io.grpc:grpc-alts:1.51.1",
    ivy"io.grpc:grpc-protobuf:1.51.1",
    ivy"io.grpc:grpc-stub:1.51.1",
    ivy"io.grpc:grpc-testing:1.51.1",
    ivy"com.thesamet.scalapb::scalapb-runtime-grpc:0.11.12",
    ivy"com.thesamet.scalapb.zio-grpc::zio-grpc-core:0.0.0+1-02300782-SNAPSHOT"
  )
}

I see others reporting this problem with gradle and maven and solving it with shadowing, etc. - how can this be done with Mill? Appreciate any help!

EDIT: The problem is the client, not the server; here is my client code.

EDIT 2: The code is irrelevant; it's a packaging issue as I suggested initially.

object Main extends ZIOAppDefault {
  val app = for {
    args <- getArgs
    channel <- ZIO.attempt(ManagedChannelBuilder.forAddress(args(0), 50051).usePlaintext().build)
    stub <- ZIO.attempt(TestGrpc.stub(channel))
    _ <- ZIO.fromFuture(_ => createMessage(stub))
  } yield ()

Client deps are the same.


问:
alb ingress annotations for upstream-vhost, proxy-redirects?
Following are the nginx ingress annotations.

```<code>nginx.ingress.kubernetes.io/upstream-vhost: "localhost:8443"
nginx.ingress.kubernetes.io/proxy-redirect-from: "https://localhost:8443"
nginx.ingress.kubernetes.io/proxy-redirect-to: "https://abx.example.com"
</code>```

What are the ALB ingress equivalents?

Body:
Following are the nginx ingress annotations.

nginx.ingress.kubernetes.io/upstream-vhost: "localhost:8443"
nginx.ingress.kubernetes.io/proxy-redirect-from: "https://localhost:8443"
nginx.ingress.kubernetes.io/proxy-redirect-to: "https://abx.example.com"

What are the ALB ingress equivalents?


问:
Using styled-components and React, how to make a floating label on an input?
I'm having trouble making a label float to the correct position in the input.  Well, when I add a placeholder to the input element, the label goes where it should be when a value is entered, which it shouldn't.  And when I remove the placeholder, the label stays where it should initially be and the focus works as expected, but when typing a value, the label pops up between the typed words, when it should have floated and held position.

Sorry if there are any errors in the text.  I'm using Google Translate to write this post.  Here is my code:

```<code><FormControl>

            <InputForm type="text" placeholder="" id="name" />

            <LabelForm htmlFor="name">Nome</LabelForm>

            <ContactFormMsg>Errrrrrrrrrrrrrrrr</ContactFormMsg>

   </FormControl>
</code>```
```<code>export const FormControl = styled.div`

  top: 2rem;

  padding: 1rem 0;

  position: relative;

  display: flex;

  flex-direction: column;

`;

export const InputForm = styled.input`

  position: relative;

  font-size: 1.5rem;

  font-weight: 400;

  width: 30rem;

  height: 3.5rem;

  border: 0.2rem solid #808080;

  border-radius: 3rem;

  outline: 0;

  background-color: white;

  color: #333;

  padding-left: 1rem;

  &::placeholder {

    color: transparent;

  }

  &:-webkit-autofill {

    -webkit-box-shadow: 0 0 0 5rem white inset;

  }

`;

export const ContactFormMsg = styled.small`

  position: absolute;

  /* visibility: hidden; */

  font-size: 1.2rem;

  font-weight: 700;

  bottom: -0.6rem;

`;

export const LabelForm = styled.label`

  position: absolute;

  top: 0.7rem;

  left: 1rem;

  font-size: 0.8rem;

  display: block;

  transition: 0.2s;

  color: #80868b;

  padding: 0 0.6rem;

  height: 0.7rem;

  background: white;

  text-align: center;

  pointer-events: none;

  ${InputForm}:not(:placeholder-shown) ~ & {

    font-size: 1.4rem;

    cursor: text;

    top: 1.9rem;

    left: 1.8rem;

    color: #80868b;

    font-weight: 400;

  }

  ${InputForm}:focus ~ & {

    top: 0.7rem;

    left: 1rem;

    font-size: 1rem;

    font-weight: 400;

    color: #1a73e8;

  }

`;
</code>```

I was hoping I could make the element float as expected, but I couldn't.  I tried following some possible solutions, and they didn't work for me. I also tried using the + operator instead of ~, and it gave the same result as described. Maybe I'm missing something silly, and that's why I'm asking for help.

Body:
I'm having trouble making a label float to the correct position in the input.  Well, when I add a placeholder to the input element, the label goes where it should be when a value is entered, which it shouldn't.  And when I remove the placeholder, the label stays where it should initially be and the focus works as expected, but when typing a value, the label pops up between the typed words, when it should have floated and held position.

Sorry if there are any errors in the text.  I'm using Google Translate to write this post.  Here is my code:

<FormControl>

            <InputForm type="text" placeholder="" id="name" />

            <LabelForm htmlFor="name">Nome</LabelForm>

            <ContactFormMsg>Errrrrrrrrrrrrrrrr</ContactFormMsg>

   </FormControl>

export const FormControl = styled.div`

  top: 2rem;

  padding: 1rem 0;

  position: relative;

  display: flex;

  flex-direction: column;

`;

export const InputForm = styled.input`

  position: relative;

  font-size: 1.5rem;

  font-weight: 400;

  width: 30rem;

  height: 3.5rem;

  border: 0.2rem solid #808080;

  border-radius: 3rem;

  outline: 0;

  background-color: white;

  color: #333;

  padding-left: 1rem;

  &::placeholder {

    color: transparent;

  }

  &:-webkit-autofill {

    -webkit-box-shadow: 0 0 0 5rem white inset;

  }

`;

export const ContactFormMsg = styled.small`

  position: absolute;

  /* visibility: hidden; */

  font-size: 1.2rem;

  font-weight: 700;

  bottom: -0.6rem;

`;

export const LabelForm = styled.label`

  position: absolute;

  top: 0.7rem;

  left: 1rem;

  font-size: 0.8rem;

  display: block;

  transition: 0.2s;

  color: #80868b;

  padding: 0 0.6rem;

  height: 0.7rem;

  background: white;

  text-align: center;

  pointer-events: none;

  ${InputForm}:not(:placeholder-shown) ~ & {

    font-size: 1.4rem;

    cursor: text;

    top: 1.9rem;

    left: 1.8rem;

    color: #80868b;

    font-weight: 400;

  }

  ${InputForm}:focus ~ & {

    top: 0.7rem;

    left: 1rem;

    font-size: 1rem;

    font-weight: 400;

    color: #1a73e8;

  }

`;

I was hoping I could make the element float as expected, but I couldn't.  I tried following some possible solutions, and they didn't work for me. I also tried using the + operator instead of ~, and it gave the same result as described. Maybe I'm missing something silly, and that's why I'm asking for help.


问:
How can I create an expandable and scrollable list?
I'm trying to accomplish following:

A JPanel (representing the container) including multiple JPanels which are including a JButton which - upon clicking - reveals another JPanel associated with the clicked JButton. When one of the JPanels expand, the other entries underneath it should dynamically change their position too. There should also be a scrolling functionality since each button has a fixed size (specified before launching the program) and it can't just change the button size to not overflow the JPanel with buttons. These overflows are typical here.

It should look something like this:

In the following I am going through my code I already wrote which has some minor problems. For the sake of simple program reproduction, I put all my code into one TextGui class and every code block within this post just adds to that file.

The TestGui JFrame and entry into the program, nothing peculiar about it.

```<code>public class TestGui extends JFrame {
    public static void main (String[] args) {
        SwingUtilities.invokeLater(TestGui::new);
    }

    public TestGui() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        add(new ListPanelTest());
        pack();
        setVisible(true);
    }
}
</code>```

The JPanel which is basically the container for all the expandable JPanels. Has the task to store the panels inside, so that the MouseWheelListener can move them all. The movement works fine until an entry is expanded, the view snaps back to the top, but should of course be the same as before.
There is also the problem of resizing. Resizing the window reveals a fatal flaw, the JButtons are not directly underneath each other but are rather separated by white spaces where JPanels could be revealed.

```<code>class ListPanelTest extends JPanel {
    String[] entryTexts = {"dropdown1:content1", "dropdown2:content2", "dropdown3:content3"};
    ArrayList<EntryListPanelTest> entryPanels;

    public ListPanelTest(){
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        entryPanels = new ArrayList<>();
        for (String entryText: entryTexts) {
            EntryListPanelTest entryListPanel = new EntryListPanelTest(entryText);
            entryPanels.add(entryListPanel);
            add(entryListPanel);
        }

        addMouseWheelListener(e -> {
            for (EntryListPanelTest entryPanel : entryPanels) {
                entryPanel.setLocation(entryPanel.getX(), entryPanel.getY() - e.getWheelRotation() * 20);
            }
        });
    }
}
</code>```

The last class should be self-explanatory. A JButton reveals (and hides) a JPanel. The only interesting part is the BorderLayout.NORTH and BorderLayout.CENTER. They are important to convey the LayoutManager in which order and where to position both entries.

```<code>class EntryListPanelTest extends JPanel {
    public EntryListPanelTest(String entryText){
        String[] entryTextSplit = entryText.split(":");
        setLayout(new BorderLayout());
        JButton button = new JButton(entryTextSplit[0]);
        JLabel label = new JLabel(entryTextSplit[1]);
        label.setVisible(false);

        add(button, BorderLayout.NORTH);
        add(label, BorderLayout.CENTER);

        button.addActionListener(e -> label.setVisible(!label.isVisible()));
    }
}
</code>```

The program is already pretty close to what I am trying to archive but the points elucidated in 2 are really important. How can I stop snapping to the top upon reveal of some content? How can I get rid of spacing between unrevealed JButtons if the size is not the packed() size? And is there maybe an even simpler way to this behavior (but still without an additional library)?

Body:
I'm trying to accomplish following:

A JPanel (representing the container) including multiple JPanels which are including a JButton which - upon clicking - reveals another JPanel associated with the clicked JButton. When one of the JPanels expand, the other entries underneath it should dynamically change their position too. There should also be a scrolling functionality since each button has a fixed size (specified before launching the program) and it can't just change the button size to not overflow the JPanel with buttons. These overflows are typical here.

It should look something like this:

In the following I am going through my code I already wrote which has some minor problems. For the sake of simple program reproduction, I put all my code into one TextGui class and every code block within this post just adds to that file.

The TestGui JFrame and entry into the program, nothing peculiar about it.

public class TestGui extends JFrame {
    public static void main (String[] args) {
        SwingUtilities.invokeLater(TestGui::new);
    }

    public TestGui() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        add(new ListPanelTest());
        pack();
        setVisible(true);
    }
}

The JPanel which is basically the container for all the expandable JPanels. Has the task to store the panels inside, so that the MouseWheelListener can move them all. The movement works fine until an entry is expanded, the view snaps back to the top, but should of course be the same as before.
There is also the problem of resizing. Resizing the window reveals a fatal flaw, the JButtons are not directly underneath each other but are rather separated by white spaces where JPanels could be revealed.

class ListPanelTest extends JPanel {
    String[] entryTexts = {"dropdown1:content1", "dropdown2:content2", "dropdown3:content3"};
    ArrayList<EntryListPanelTest> entryPanels;

    public ListPanelTest(){
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        entryPanels = new ArrayList<>();
        for (String entryText: entryTexts) {
            EntryListPanelTest entryListPanel = new EntryListPanelTest(entryText);
            entryPanels.add(entryListPanel);
            add(entryListPanel);
        }

        addMouseWheelListener(e -> {
            for (EntryListPanelTest entryPanel : entryPanels) {
                entryPanel.setLocation(entryPanel.getX(), entryPanel.getY() - e.getWheelRotation() * 20);
            }
        });
    }
}

The last class should be self-explanatory. A JButton reveals (and hides) a JPanel. The only interesting part is the BorderLayout.NORTH and BorderLayout.CENTER. They are important to convey the LayoutManager in which order and where to position both entries.

class EntryListPanelTest extends JPanel {
    public EntryListPanelTest(String entryText){
        String[] entryTextSplit = entryText.split(":");
        setLayout(new BorderLayout());
        JButton button = new JButton(entryTextSplit[0]);
        JLabel label = new JLabel(entryTextSplit[1]);
        label.setVisible(false);

        add(button, BorderLayout.NORTH);
        add(label, BorderLayout.CENTER);

        button.addActionListener(e -> label.setVisible(!label.isVisible()));
    }
}

The program is already pretty close to what I am trying to archive but the points elucidated in 2 are really important. How can I stop snapping to the top upon reveal of some content? How can I get rid of spacing between unrevealed JButtons if the size is not the packed() size? And is there maybe an even simpler way to this behavior (but still without an additional library)?


问:
How do you get stdout from pexpect?
```<code>import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("exit")
</code>```

This works perfectly. The problem now is that I want to do an ls (after touch) and get the output but I can't figure out how to do that.

I saw an example using child.logfile = sys.stdout right after spawn (and changing the spawn line to include encoding="utf-8") and this does produce some output, but doesn't show the output from ls.

From here:

Python how to read output from pexpect child?

I tried the following:

```<code>import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("ls")
child.expect(pexpect.EOF)
print(child.before)

child.sendline("exit")
</code>```

But this just times out.

I also tried:

```<code>import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("ls")
child.expect(".*") # the shell prompt varies extensively
print(child.before)

child.sendline("exit")
</code>```

And this returns the following line:

```<code>b''
</code>```

Which is clearly not the expected output from ls. How do I get stdout from ls in this case?

All the examples from: Python how to read output from pexpect child? do not have this extra layer of virsh console in the equation, which I think makes my problem much more difficult to solve.

Title: How do you get stdout from pexpect?

Body:
import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("exit")

This works perfectly. The problem now is that I want to do an ls (after touch) and get the output but I can't figure out how to do that.

I saw an example using child.logfile = sys.stdout right after spawn (and changing the spawn line to include encoding="utf-8") and this does produce some output, but doesn't show the output from ls.

From here:

Python how to read output from pexpect child?

I tried the following:

import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("ls")
child.expect(pexpect.EOF)
print(child.before)

child.sendline("exit")

But this just times out.

I also tried:

import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("ls")
child.expect(".*") # the shell prompt varies extensively
print(child.before)

child.sendline("exit")

And this returns the following line:

b''

Which is clearly not the expected output from ls. How do I get stdout from ls in this case?

All the examples from: Python how to read output from pexpect child? do not have this extra layer of virsh console in the equation, which I think makes my problem much more difficult to solve.