问:
How to verify and assert all the drop down values in python using selenium
Hy,

I want to make an assert or something else to check all options from my dropdown and compare with a expected

Thx!

dropdown

```<code>my_dropdown = driver.find_element('id', 'coding-language-select')
dropdown_object = Select(my_dropdown)

expected = ['--Please choose an option--','Python', 'Java', 'PHP', 'C#', 'SQL']

all_options = dropdown_object.options

assert all_options.text == expected
</code>```

Body:
Hy,

I want to make an assert or something else to check all options from my dropdown and compare with a expected

Thx!

dropdown

my_dropdown = driver.find_element('id', 'coding-language-select')
dropdown_object = Select(my_dropdown)

expected = ['--Please choose an option--','Python', 'Java', 'PHP', 'C#', 'SQL']

all_options = dropdown_object.options

assert all_options.text == expected


来源: stackexchange

问:
SpringBoot + Vault: How to encrypt/decrypt using VaultTransitTemplate
I am trying to understand how to do encryption/decryption in springboot using the transits engine in Hashicorp Vault.

From the docs I see a VaultTransitTemplate but I am unable to find a proper example of the same. I want to encrypt a plaintext and get a ciphertext from it. Can someone help ?

ContentLicense: CC BY-SA 4.0


问:
Gnu radio and Yaesu CAT over serial
I'm trying to take info from my radio (ft817) over serial connection and give them to gnuradio in order to use them to make a nice GUI for a panadapter. I normally print CAT data like this, please excuse my python skills I'm still learning :
`

```<code>import serial
import time
SERIAL_PORT = "/dev/ttyUSB0"
SAMPLES_PER_SEC = 5
class FT817(object):

    SERIAL_SPEED = 9600
    SERIAL_STOPBITS = serial.STOPBITS_TWO
    SERIAL_TIMEOUT = 1.0
    # Transceiver modes and commands
    MODES = ["LSB", "USB", "CW", "CWR", "AM", None, "WFM", None, "FM", None, "DIG", None, "PKT"]
    CMD_READ_FREQ = [0x00, 0x00, 0x00, 0x00, 0x03]
    CMD_READ_RX_STATUS = [0x00, 0x00, 0x00, 0x00, 0xE7]

    def __init__(self, serial_port, serial_speed=SERIAL_SPEED, serial_stopbits=SERIAL_STOPBITS):
        self._serial = serial.Serial(serial_port, serial_speed, stopbits=serial_stopbits, timeout=FT817.SERIAL_TIMEOUT)
        self._frequency = ""
        self._mode = ""
        self._squelch = True
        self._s_meter = ""

    def read_frequency(self):
        '''Queries transceiver RX frequency and mode.
        The response is 5 bytes: first four store frequency and
        the fifth stores mode (AM, FM, SSB etc.)
        '''
        cmd = FT817.CMD_READ_FREQ
        self._serial.write(cmd)
        resp = self._serial.read(5)
        resp_bytes = ((resp[0]), (resp[1]), (resp[2]), (resp[3]))
        self._frequency = "%02x%02x%02x%02x" % resp_bytes
        self._mode = FT817.MODES[(resp[4])]

    def read_rx_status(self):
        '''Queries transceiver RX status.
        The response is 1 byte:
        bit 7: Squelch status: 0 - off (signal present), 1 - on (no signal)
        bit 6: CTCSS/DCS Code: 0 - code is matched, 1 - code is unmatched
        bit 5: Discriminator centering: 0 - discriminator centered, 1 - uncentered
        bit 4: Dummy data
        bit 3-0: S Meter data
        '''
        cmd = FT817.CMD_READ_RX_STATUS
        self._serial.write(cmd)
        resp = self._serial.read(1)
        resp_byte = (resp[0])
        self._squelch = True if (resp_byte & 0B10000000) else False

    def get_trx_state_string(self):
        '''Returns transceiver state data for printing.
        '''

        sql_str = 'SQL: ON' if self._squelch else 'SQL: OFF'
        res = "%sHz %s %s" % (self._frequency, self._mode, sql_str)
        return res

    def __str__(self):
        '''Overrides __str__() method for using FT817 class with print command.
        '''
        return self.get_trx_state_string()
if __name__ == '__main__':
    print ("Starting FT-817ND monitor...")

    try:
        ft817 = FT817(SERIAL_PORT)
        delay = 1.0 / SAMPLES_PER_SEC
        while True:
            ft817.read_frequency()
            ft817.read_rx_status()
            print
            print (ft817)
            time.sleep(delay)
    except KeyboardInterrupt:
        # KeyboardInterrupt exception is thrown when CTRL-C or CTRL-Break is pressed.
        pass
    finally:
        print ("See you later. 73!")
</code>```

`
But i'm not sure how to implement this in GNURADIO, any help?

I've tried to use py block but without success.

Title: Gnu radio and Yaesu CAT over serial

Body:
I'm trying to take info from my radio (ft817) over serial connection and give them to gnuradio in order to use them to make a nice GUI for a panadapter. I normally print CAT data like this, please excuse my python skills I'm still learning :
`

import serial
import time
SERIAL_PORT = "/dev/ttyUSB0"
SAMPLES_PER_SEC = 5
class FT817(object):

    SERIAL_SPEED = 9600
    SERIAL_STOPBITS = serial.STOPBITS_TWO
    SERIAL_TIMEOUT = 1.0
    # Transceiver modes and commands
    MODES = ["LSB", "USB", "CW", "CWR", "AM", None, "WFM", None, "FM", None, "DIG", None, "PKT"]
    CMD_READ_FREQ = [0x00, 0x00, 0x00, 0x00, 0x03]
    CMD_READ_RX_STATUS = [0x00, 0x00, 0x00, 0x00, 0xE7]

    def __init__(self, serial_port, serial_speed=SERIAL_SPEED, serial_stopbits=SERIAL_STOPBITS):
        self._serial = serial.Serial(serial_port, serial_speed, stopbits=serial_stopbits, timeout=FT817.SERIAL_TIMEOUT)
        self._frequency = ""
        self._mode = ""
        self._squelch = True
        self._s_meter = ""

    def read_frequency(self):
        '''Queries transceiver RX frequency and mode.
        The response is 5 bytes: first four store frequency and
        the fifth stores mode (AM, FM, SSB etc.)
        '''
        cmd = FT817.CMD_READ_FREQ
        self._serial.write(cmd)
        resp = self._serial.read(5)
        resp_bytes = ((resp[0]), (resp[1]), (resp[2]), (resp[3]))
        self._frequency = "%02x%02x%02x%02x" % resp_bytes
        self._mode = FT817.MODES[(resp[4])]

    def read_rx_status(self):
        '''Queries transceiver RX status.
        The response is 1 byte:
        bit 7: Squelch status: 0 - off (signal present), 1 - on (no signal)
        bit 6: CTCSS/DCS Code: 0 - code is matched, 1 - code is unmatched
        bit 5: Discriminator centering: 0 - discriminator centered, 1 - uncentered
        bit 4: Dummy data
        bit 3-0: S Meter data
        '''
        cmd = FT817.CMD_READ_RX_STATUS
        self._serial.write(cmd)
        resp = self._serial.read(1)
        resp_byte = (resp[0])
        self._squelch = True if (resp_byte & 0B10000000) else False

    def get_trx_state_string(self):
        '''Returns transceiver state data for printing.
        '''

        sql_str = 'SQL: ON' if self._squelch else 'SQL: OFF'
        res = "%sHz %s %s" % (self._frequency, self._mode, sql_str)
        return res

    def __str__(self):
        '''Overrides __str__() method for using FT817 class with print command.
        '''
        return self.get_trx_state_string()
if __name__ == '__main__':
    print ("Starting FT-817ND monitor...")

    try:
        ft817 = FT817(SERIAL_PORT)
        delay = 1.0 / SAMPLES_PER_SEC
        while True:
            ft817.read_frequency()
            ft817.read_rx_status()
            print
            print (ft817)
            time.sleep(delay)
    except KeyboardInterrupt:
        # KeyboardInterrupt exception is thrown when CTRL-C or CTRL-Break is pressed.
        pass
    finally:
        print ("See you later. 73!")

`
But i'm not sure how to implement this in GNURADIO, any help?

I've tried to use py block but without success.


问:
Flask API in Python: POST a hosted PDF's URL for the server to download
I am using PythonAnywhere to try and run a flask API that allows the user to POST a link to an online .PDF file with the goal of downloading the file to the flask's working directory.

```<code>
from flask import Flask
from flask import request
import requests
import logging

app = Flask(__name__)

# Configure the logger file
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('log.txt')
handler.setLevel(logging.INFO)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)

@app.route('/download', methods=['POST'])
def download_file():
    # Log that the function has been called
    logger.info("download_file function called")

    # Get the URL of the hosted PDF file
    pdf_url = request.values.get('url')

    # Log that the function has been called
    logger.info("URL has been retrieved called")

    # Download the PDF file
    response = requests.get(pdf_url)
    file = response.content

    # Log that the function has been called
    logger.info("PDF file downloaded")

    # Save the PDF file to the working directory of the API
    with open('downloaded_file.pdf', 'wb') as f:
        f.write(file)

    # Log that the function has been called
    logger.info("PDF file saved to working directory")

    # Log that the operation was successful overall
    return 'File downloaded and saved successfully!'
</code>```

I am testing in Postman like this:

```<code>POST http://[myurl].pythonanywhere.com/download

KEY: url
VALUE: "https://www.irs.gov/pub/irs-pdf/p15.pdf"
</code>```

The download is only successful when I hardcode the URL before defining the functions, but when I instead try to POST the URL to the API, it does not work properly and receive "400 Bad Request" as an error. It seems likely to be due to passing of the symbols in the URL, but I am unsure.

Body:
I am using PythonAnywhere to try and run a flask API that allows the user to POST a link to an online .PDF file with the goal of downloading the file to the flask's working directory.

from flask import Flask
from flask import request
import requests
import logging

app = Flask(__name__)

# Configure the logger file
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('log.txt')
handler.setLevel(logging.INFO)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)

@app.route('/download', methods=['POST'])
def download_file():
    # Log that the function has been called
    logger.info("download_file function called")

    # Get the URL of the hosted PDF file
    pdf_url = request.values.get('url')

    # Log that the function has been called
    logger.info("URL has been retrieved called")

    # Download the PDF file
    response = requests.get(pdf_url)
    file = response.content

    # Log that the function has been called
    logger.info("PDF file downloaded")

    # Save the PDF file to the working directory of the API
    with open('downloaded_file.pdf', 'wb') as f:
        f.write(file)

    # Log that the function has been called
    logger.info("PDF file saved to working directory")

    # Log that the operation was successful overall
    return 'File downloaded and saved successfully!'

I am testing in Postman like this:

POST http://[myurl].pythonanywhere.com/download

KEY: url
VALUE: "https://www.irs.gov/pub/irs-pdf/p15.pdf"

The download is only successful when I hardcode the URL before defining the functions, but when I instead try to POST the URL to the API, it does not work properly and receive "400 Bad Request" as an error. It seems likely to be due to passing of the symbols in the URL, but I am unsure.


问:
Issue in aligning no more than 3 image card in a row using map function
```<code>function ncard(val) {
  return (
    <Cards
      imgsrc={val.imgsrcs}
      title={val.title}
      date = {val.date}
      location = {val.location}
      details={val.details}
    />
  );

}

export default function Campaign() {
  return (
    <div className="turningred">
      <h1 className="color">
        Campaigns Currently Live
      </h1>

      <div className="flexes ">
        {CardData.map(ncard)}
      </div>

    </div>
  )
}
</code>```

Here is where cards are being made:

```<code>export default function Cards(props) {
    return (
        <div className="container">
            <div className="row">
                <div className="col">
                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={props.imgsrc} />
                        <Card.Body>
                            <Card.Title>{props.title}</Card.Title>
                            <Card.Text>
                             <h7 className='red'>  Location: </h7>{props.location}
                            </Card.Text>
                            <Card.Text>
                                {props.date}
                            </Card.Text>
                            <Card.Text>
                                {props.details}
                            </Card.Text>
                            <Button variant="danger">Delete Campaign</Button>
                        </Card.Body>
                    </Card>
                </div>

            </div>
        </div>
    )
}

</code>```

Here is the array where I am filling data in cards

```<code>const CardData = [
    {
        imgsrcs: require('../../../pictures/yellow.jpg'),
        title: "Campaign 1",
        location: "Islamabad",
        date: "24/7/2022",
        details: "Hey I Am Writing Details",

    },
    {
        imgsrcs: require('../../../pictures/yellow.jpg'),
        title: "Campaign 2",
        location: "Islamabad",
        date: "24/7/2022",
        details: "Hey I Am Writing Details",
    },
    {
        imgsrcs: require('../../../pictures/yellow.jpg'),
        title: "Campaign 3",
        location: "Islamabad",
        date: "24/7/2022",
        details: "Hey I Am Writing Details",
    },

]
export default CardData;
</code>```

If I insert more than 3 cards then horizontal side bar comes on my page and If I remove the flexes class (in which I have set display to flex) my cards are aligned to vertical.

I want that if I insert 4 cards than the fourth cards will come under the first card in a new row

Body:
function ncard(val) {
  return (
    <Cards
      imgsrc={val.imgsrcs}
      title={val.title}
      date = {val.date}
      location = {val.location}
      details={val.details}
    />
  );

}

export default function Campaign() {
  return (

        Campaigns Currently Live

        {CardData.map(ncard)}

  )
}

Here is where cards are being made:

export default function Cards(props) {
    return (

                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={props.imgsrc} />
                        <Card.Body>
                            <Card.Title>{props.title}</Card.Title>
                            <Card.Text>
                             <h7 className='red'>  Location: </h7>{props.location}
                            </Card.Text>
                            <Card.Text>
                                {props.date}
                            </Card.Text>
                            <Card.Text>
                                {props.details}
                            </Card.Text>
                            <Button variant="danger">Delete Campaign</Button>
                        </Card.Body>
                    </Card>

    )
}

Here is the array where I am filling data in cards

const CardData = [
    {
        imgsrcs: require('../../../pictures/yellow.jpg'),
        title: "Campaign 1",
        location: "Islamabad",
        date: "24/7/2022",
        details: "Hey I Am Writing Details",

    },
    {
        imgsrcs: require('../../../pictures/yellow.jpg'),
        title: "Campaign 2",
        location: "Islamabad",
        date: "24/7/2022",
        details: "Hey I Am Writing Details",
    },
    {
        imgsrcs: require('../../../pictures/yellow.jpg'),
        title: "Campaign 3",
        location: "Islamabad",
        date: "24/7/2022",
        details: "Hey I Am Writing Details",
    },

]
export default CardData;

If I insert more than 3 cards then horizontal side bar comes on my page and If I remove the flexes class (in which I have set display to flex) my cards are aligned to vertical.

I want that if I insert 4 cards than the fourth cards will come under the first card in a new row


问:
NavBar wont show?
`Hi, My nav bar wont show up in my project. The only thing that shows is the background color. Can anyone help me understand what i am doing wrong? I guess i need to conect it to an icon somehow - but how would that work? i appriciate all suggestions. I can also post the CSS file if needed.

JS:

this is the nav bar and some JS that is suppose to open it up when you press the the icon

```<code>
    import './test.scss';
    import {Link} from "react-router-dom";

    export function Header () {

    //Js

    console.clear();

    const app = (() => {
        let body;
        let menu;
        let menuItems;

        const init = () => {
            body = document.querySelector('body');
            menu = document.querySelector('.menu-icon');
            menuItems = document.querySelectorAll('.nav__list-item');

            applyListeners();
        }

        const applyListeners = () => {
            menu.addEventListener('click', () => toggleClass(body, 'nav-active'));
        }

        const toggleClass = (element, stringClass) => {
            if(element.classList.contains(stringClass))
                element.classList.remove(stringClass);
            else
                element.classList.add(stringClass);
        }

        init();
    })();

    return (
        <>
        <div className="menu-icon">
          <span className="menu-icon__line menu-icon__line-left" />
          <span className="menu-icon__line" />
          <span className="menu-icon__line menu-icon__line-right" />
        </div>
        <div className="nav">
          <div className="nav__content">
            <ul className="nav__list">
              <li className="nav__list-item">Home</li>
              <li className="nav__list-item"></li>
              <li className="nav__list-item"></li>
              <li className="nav__list-item"></li>
            </ul>
          </div>
        </div>

        <div className="site-content">
          <h1 className="site-content__headline">
            text
          </h1>
        </div>
      </>

     );
    }

</code>```

thanks

CSS(SCSS) file:

```<code>$background--color:#1e2023;
$icon--color:#1e2023;
$font--color:#ffffff;
$font--color--active:#000000;
$font--primary:'Fira Sans', sans-serif;
$transition--length: .8;

body{
    background-color: $background--color;
    font-family: $font--primary;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.site-content{
    max-width: 1100px;
    height: 100vh;
    margin-left: auto;
    margin-right: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    &__headline{
        font-weight: 200;
        color: $font--color;
        font-size: calc(2vw + 10px);
        text-align: center;
    }
}

//default state
.menu-icon{
    $size: 30px;
    height: $size;
    width: $size;
    position: fixed;
    z-index:2;
    left: 50px;
    top: 30px;
    cursor: pointer;
    &__line{
        height: 2px;
        width: $size;
        display: block;
        background-color: $font--color;
        margin-bottom: 4px;
        transition: transform .2s ease, background-color .5s ease;
    }
    &__line-left{
        width: $size / 2;
    }
    &__line-right{
        width: $size / 2;
        float: right;
    }
}

.nav{
    $width: 100vw;
    $height: 100vh;
    $font--size--calc: calc(2vw + 10px);
    $transition--easing: cubic-bezier(.77,0,.175,1);
    position: fixed;
    z-index:1;
    &:before,&:after{
        content: "";
        position: fixed;
        width:$width;
        height:$height;
        background: rgba(#eaeaea, .2);
        z-index: -1;
        transition: transform $transition--easing $transition--length + s;
        transform: translateX(0%) translateY(-100%);
    }
    &:after{
        background: rgba(#ffffff, 1);
        transition-delay: 0s;
    }
    &:before{
        transition-delay: .1s;
    }
    &__content{
        position: fixed;
        top:50%;
        transform: translate(0%,-50%);
        width: 100%;
        text-align: center;
        font-size: $font--size--calc;
        font-weight: 200;
        cursor: pointer;
    }
    &__list-item{
        position: relative;
        display: inline-block;
        transition-delay: $transition--length + s;
        opacity: 0;
        transform: translate(0%, 100%);
        transition: opacity .2s ease, transform .3s ease;
        margin-right: 25px;
        &:before{
            content: "";
            position: absolute;
            background: $font--color--active;
            width: 20px;
            height: 1px;
            top: 100%;
            transform: translate(0%, 0%);
            transition: all .3s ease;
            z-index: -1;
        }
        &:hover{
            &:before{
                width: 100%;
            }
        }
    }
}

//active state
body.nav-active{
    $menu--items--count: 4;
    .menu-icon{
        &__line{
            background-color: #000;
            transform: translateX(0px) rotate(-45deg);
        }
        &__line-left{
            transform: translateX(1px) rotate(45deg);
        }
        &__line-right{
            transform: translateX(-2px) rotate(45deg);
        }
    }
    .nav{
        visibility:visible;
        &:before,&:after{
            transform: translateX(0%) translateY(0%);
        }
        &:after{
            transition-delay: .1s;
        }
        &:before{
            transition-delay: 0s;
        }
        &__list-item{
            opacity: 1;
            transform: translateX(0%);
            transition: opacity .3s ease, transform .3s ease, color .3s ease;
            @for $i from 0 through $menu--items--count {
                &:nth-child(#{$i}){
                    transition-delay: $transition--length * $i / 8 + .5 + s;
                }
            }
        }
    }
}
</code>```

Title: NavBar wont show?

Body:
`Hi, My nav bar wont show up in my project. The only thing that shows is the background color. Can anyone help me understand what i am doing wrong? I guess i need to conect it to an icon somehow - but how would that work? i appriciate all suggestions. I can also post the CSS file if needed.

JS:

this is the nav bar and some JS that is suppose to open it up when you press the the icon

    import './test.scss';
    import {Link} from "react-router-dom";

    export function Header () {

    //Js

    console.clear();

    const app = (() => {
        let body;
        let menu;
        let menuItems;

        const init = () => {
            body = document.querySelector('body');
            menu = document.querySelector('.menu-icon');
            menuItems = document.querySelectorAll('.nav__list-item');

            applyListeners();
        }

        const applyListeners = () => {
            menu.addEventListener('click', () => toggleClass(body, 'nav-active'));
        }

        const toggleClass = (element, stringClass) => {
            if(element.classList.contains(stringClass))
                element.classList.remove(stringClass);
            else
                element.classList.add(stringClass);
        }

        init();
    })();

    return (
        <>

Home

            text

      </>

     );
    }

thanks

CSS(SCSS) file:

$background--color:#1e2023;
$icon--color:#1e2023;
$font--color:#ffffff;
$font--color--active:#000000;
$font--primary:'Fira Sans', sans-serif;
$transition--length: .8;

body{
    background-color: $background--color;
    font-family: $font--primary;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.site-content{
    max-width: 1100px;
    height: 100vh;
    margin-left: auto;
    margin-right: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    &__headline{
        font-weight: 200;
        color: $font--color;
        font-size: calc(2vw + 10px);
        text-align: center;
    }
}

//default state
.menu-icon{
    $size: 30px;
    height: $size;
    width: $size;
    position: fixed;
    z-index:2;
    left: 50px;
    top: 30px;
    cursor: pointer;
    &__line{
        height: 2px;
        width: $size;
        display: block;
        background-color: $font--color;
        margin-bottom: 4px;
        transition: transform .2s ease, background-color .5s ease;
    }
    &__line-left{
        width: $size / 2;
    }
    &__line-right{
        width: $size / 2;
        float: right;
    }
}

.nav{
    $width: 100vw;
    $height: 100vh;
    $font--size--calc: calc(2vw + 10px);
    $transition--easing: cubic-bezier(.77,0,.175,1);
    position: fixed;
    z-index:1;
    &:before,&:after{
        content: "";
        position: fixed;
        width:$width;
        height:$height;
        background: rgba(#eaeaea, .2);
        z-index: -1;
        transition: transform $transition--easing $transition--length + s;
        transform: translateX(0%) translateY(-100%);
    }
    &:after{
        background: rgba(#ffffff, 1);
        transition-delay: 0s;
    }
    &:before{
        transition-delay: .1s;
    }
    &__content{
        position: fixed;
        top:50%;
        transform: translate(0%,-50%);
        width: 100%;
        text-align: center;
        font-size: $font--size--calc;
        font-weight: 200;
        cursor: pointer;
    }
    &__list-item{
        position: relative;
        display: inline-block;
        transition-delay: $transition--length + s;
        opacity: 0;
        transform: translate(0%, 100%);
        transition: opacity .2s ease, transform .3s ease;
        margin-right: 25px;
        &:before{
            content: "";
            position: absolute;
            background: $font--color--active;
            width: 20px;
            height: 1px;
            top: 100%;
            transform: translate(0%, 0%);
            transition: all .3s ease;
            z-index: -1;
        }
        &:hover{
            &:before{
                width: 100%;
            }
        }
    }
}

//active state
body.nav-active{
    $menu--items--count: 4;
    .menu-icon{
        &__line{
            background-color: #000;
            transform: translateX(0px) rotate(-45deg);
        }
        &__line-left{
            transform: translateX(1px) rotate(45deg);
        }
        &__line-right{
            transform: translateX(-2px) rotate(45deg);
        }
    }
    .nav{
        visibility:visible;
        &:before,&:after{
            transform: translateX(0%) translateY(0%);
        }
        &:after{
            transition-delay: .1s;
        }
        &:before{
            transition-delay: 0s;
        }
        &__list-item{
            opacity: 1;
            transform: translateX(0%);
            transition: opacity .3s ease, transform .3s ease, color .3s ease;
            @for $i from 0 through $menu--items--count {
                &:nth-child(#{$i}){
                    transition-delay: $transition--length * $i / 8 + .5 + s;
                }
            }
        }
    }
}


问:
Fail to send smtp mail poco c++
I am new to c++ and tring to send a mail using gmail smtp. I have done this in python but I  am unable to do it in c++. I think I need to add startTLS() but it seems to be not defined. Please help me, I have tried my best. Searched the internet also could not find any thing.

```<code>#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
#include <string>

using namespace Poco::Net;
using namespace std;

int main(int argc, char** argv)
{
    std::string Username = "farhantestingsmtp@gmail.com";
    std::string Password = "cpguxktxoyibiybd";

    std::string Receiver = "jattfarhan10@gmail.com";
    std::string Name = "Jatt Farhan";

    std::string Subject = "Hello!";
    std::string Content = "TEXT OF THE EMAIL";

    try
    {
        MailMessage msg;

        msg.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, Receiver, Name));

        msg.setSender(Username);
        msg.setSubject(Subject);
        msg.setContent(Content);
        SMTPClientSession smtp("smtp.gmail.com", 487);
        smtp.open();
        cout << "Before Login";
        smtp.login(SMTPClientSession::AUTH_LOGIN, Username, Password);

        cout << "After Login";
        smtp.sendMessage(msg);
        smtp.close();
        std::cerr << "Sent mail successfully!" << std::endl;
    }
    catch (std::exception& e)
    {
        std::cerr << "Failed to send mail: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
</code>```

I have added my mail username and password, as it for testing. Thanks in advance.

I tried to add startTLS and could not do it as The SecureSMTPClientSession was not defined in my VS environment. I also searched the internet, but could not fix it.

Title: Fail to send smtp mail poco c++

Body:
I am new to c++ and tring to send a mail using gmail smtp. I have done this in python but I  am unable to do it in c++. I think I need to add startTLS() but it seems to be not defined. Please help me, I have tried my best. Searched the internet also could not find any thing.

#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
#include <string>

using namespace Poco::Net;
using namespace std;

int main(int argc, char** argv)
{
    std::string Username = "farhantestingsmtp@gmail.com";
    std::string Password = "cpguxktxoyibiybd";

    std::string Receiver = "jattfarhan10@gmail.com";
    std::string Name = "Jatt Farhan";

    std::string Subject = "Hello!";
    std::string Content = "TEXT OF THE EMAIL";

    try
    {
        MailMessage msg;

        msg.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, Receiver, Name));

        msg.setSender(Username);
        msg.setSubject(Subject);
        msg.setContent(Content);
        SMTPClientSession smtp("smtp.gmail.com", 487);
        smtp.open();
        cout << "Before Login";
        smtp.login(SMTPClientSession::AUTH_LOGIN, Username, Password);

        cout << "After Login";
        smtp.sendMessage(msg);
        smtp.close();
        std::cerr << "Sent mail successfully!" << std::endl;
    }
    catch (std::exception& e)
    {
        std::cerr << "Failed to send mail: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

I have added my mail username and password, as it for testing. Thanks in advance.

I tried to add startTLS and could not do it as The SecureSMTPClientSession was not defined in my VS environment. I also searched the internet, but could not fix it.


问:
Trouble framing Modbus data captured from analyzer?(Saleae Logic 2)
I’ve tapped into an RS-485 bus and dumped some data. I’d like to implement a strawman/MITM device to intercept the traffic and send commands independent of the existing master/slave.

Here are some screenshots of some logic samples I captured in Saleae Logic 2:

zoom 1

zoom 2

zoom 3

My problem is it doesn’t look like it’s framed properly. I’ve got the analyzer set to Modbus RTU master, 9600 baud, no parity bit, one stop bit.

Could anyone tell me if this looks correct or incorrect based on these screenshots? Is this Modbus protocol, or something different? Trying to see if I’m on the right path here. Thanks. Any additional info I’m happy to supply if requested.

Tried several different ways of applying analyzers trying to get a solid stream of info


问:
flock does not block
Please explain why the code below blocks first execution (1607061065) and does not block the second one (1664361639) (the output is attached):

<?php
$fileName = "file.txt";

$fp = fopen($fileName, "a");
if (flock($fp, LOCK_EX | LOCK_NB)) {
    $runId = rand();
    fwrite(
        $fp,
        "processing task [runId]: $runId; [pid]: ". getmypid() ." started \n" .
        (new DateTime())->format(DateTime::ATOM) . " \n\n"
    );

    sleep(3);
    flock($fp, LOCK_UN);
    fwrite(
        $fp,
        "processing task [runId]: $runId; [pid]: ". getmypid() ." finished \n" .
        (new DateTime())->format(DateTime::ATOM) . " \n\n"
    );
    fclose($fp);
    exit;
}
fwrite(
    $fp,
    "script is busy [pid]: ". getmypid() ." \n" .
    (new DateTime())->format(DateTime::ATOM) . " \n\n"
);

```
<p>I am running this via <code>ab</code> utility which is able to send request concurrently:</p>
```ab -c 3 -n 8 http://localhost/
```
<p>(it is run by 3 instances in parallel 8 times)</p>
<p>And this is what I have in <code>file.txt</code> after execution is finished:</p>
```processing task [runId]: 1607061065; [pid]: 2507 started
2022-12-22T17:03:22+00:00

processing task [runId]: 1607061065; [pid]: 2507 finished
2022-12-22T17:03:25+00:00

processing task [runId]: 1664361639; [pid]: 2503 started
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

processing task [runId]: 1664361639; [pid]: 2503 finished
2022-12-22T17:03:28+00:00
```

Why 1607061065 blocks the first execution and why there is a second process exist which acuires lock 1664361639 which does not block the execution.

Thanks in advance

Title: flock does not block

Body:
Please explain why the code below blocks first execution (1607061065) and does not block the second one (1664361639) (the output is attached):

<?php
$fileName = "file.txt";

$fp = fopen($fileName, "a");
if (flock($fp, LOCK_EX | LOCK_NB)) {
    $runId = rand();
    fwrite(
        $fp,
        "processing task [runId]: $runId; [pid]: ". getmypid() ." started \n" .
        (new DateTime())->format(DateTime::ATOM) . " \n\n"
    );

    sleep(3);
    flock($fp, LOCK_UN);
    fwrite(
        $fp,
        "processing task [runId]: $runId; [pid]: ". getmypid() ." finished \n" .
        (new DateTime())->format(DateTime::ATOM) . " \n\n"
    );
    fclose($fp);
    exit;
}
fwrite(
    $fp,
    "script is busy [pid]: ". getmypid() ." \n" .
    (new DateTime())->format(DateTime::ATOM) . " \n\n"
);

I am running this via ab utility which is able to send request concurrently:

ab -c 3 -n 8 http://localhost/

(it is run by 3 instances in parallel 8 times)

And this is what I have in file.txt after execution is finished:

processing task [runId]: 1607061065; [pid]: 2507 started
2022-12-22T17:03:22+00:00

processing task [runId]: 1607061065; [pid]: 2507 finished
2022-12-22T17:03:25+00:00

processing task [runId]: 1664361639; [pid]: 2503 started
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

processing task [runId]: 1664361639; [pid]: 2503 finished
2022-12-22T17:03:28+00:00

Why 1607061065 blocks the first execution and why there is a second process exist which acuires lock 1664361639 which does not block the execution.

Thanks in advance


问:
CTE To Return All Related Ids Regardless of Separation
I am trying to write a query that will select all related rows from a relationship table, regardless of how distant the relationship.  I know I can query a parent/child hierarchy recursively using a CTE, but this doesn't really fit the parent/child mold, it's more like an x degrees of separation.

```<code>Create Table #Relationships (
    Relationship_Id int IDENTITY(1,1) NOT NULL,
    Person_Id_1 int NOT NULL,
    Person_Id_2 int NOT NULL
)

Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (1, 2)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (1, 3)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (4, 3)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (4, 5)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (6, 1)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (7, 8)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (7, 9)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (9, 10)

Select Relationship_Id, Person_Id_1, Person_Id_2 From #Relationships
/*
Relationship_Id Person_Id_1 Person_Id_2
--------------- ----------- -----------
1               1           2
2               1           3
3               4           3
4               4           5
5               6           1
6               7           8
7               7           9
8               9           10
*/
</code>```

Given the above table, I want a query that when passed an Id will return all other Ids that are in some way related to it, regardless of how many degrees of separation.  For example, passing the following Ids would give me the results below.

```<code>5 = 1, 2, 3, 4, 6
1 = 2, 3, 4, 5, 6
8 = 7, 9, 10
</code>```

Is this even possible?  I can't wrap my head around what the base case would be to stop the recursion.

Body:
I am trying to write a query that will select all related rows from a relationship table, regardless of how distant the relationship.  I know I can query a parent/child hierarchy recursively using a CTE, but this doesn't really fit the parent/child mold, it's more like an x degrees of separation.

Create Table #Relationships (
    Relationship_Id int IDENTITY(1,1) NOT NULL,
    Person_Id_1 int NOT NULL,
    Person_Id_2 int NOT NULL
)

Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (1, 2)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (1, 3)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (4, 3)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (4, 5)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (6, 1)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (7, 8)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (7, 9)
Insert Into #Relationships (Person_Id_1, Person_Id_2) Values (9, 10)

Select Relationship_Id, Person_Id_1, Person_Id_2 From #Relationships
/*
Relationship_Id Person_Id_1 Person_Id_2
--------------- ----------- -----------
1               1           2
2               1           3
3               4           3
4               4           5
5               6           1
6               7           8
7               7           9
8               9           10
*/

Given the above table, I want a query that when passed an Id will return all other Ids that are in some way related to it, regardless of how many degrees of separation.  For example, passing the following Ids would give me the results below.

5 = 1, 2, 3, 4, 6
1 = 2, 3, 4, 5, 6
8 = 7, 9, 10

Is this even possible?  I can't wrap my head around what the base case would be to stop the recursion.


问:
Twitter Authentication not working with Firebase,

Im facing the error regaring the twitter authentication on google firebase, im unable store data on firebase,

```<code> firebase.initializeApp(firebaseConfig);

    // Function to handle the "Log in with Twitter" button click
    function loginWithTwitter() {
      // Create a Twitter auth provider
      var provider = new firebase.auth.TwitterAuthProvider();

      // Authenticate the user with Twitter
      firebase.auth().signInWithPopup(provider)
        .then(result => {
          // The user is now authenticated
          console.log(result);
        })
        .catch(error => {
          // An error occurred
          console.error(error);
        });
    }
</code>```

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <!-- Add the "Log in with Twitter" button -->
  <button onclick="loginWithTwitter()">Log in with Twitter</button>
</body>
</html></code>```

Body:
Im facing the error regaring the twitter authentication on google firebase, im unable store data on firebase,

 firebase.initializeApp(firebaseConfig);

    // Function to handle the "Log in with Twitter" button click
    function loginWithTwitter() {
      // Create a Twitter auth provider
      var provider = new firebase.auth.TwitterAuthProvider();

      // Authenticate the user with Twitter
      firebase.auth().signInWithPopup(provider)
        .then(result => {
          // The user is now authenticated
          console.log(result);
        })
        .catch(error => {
          // An error occurred
          console.error(error);
        });
    }

  <button onclick="loginWithTwitter()">Log in with Twitter</button>


问:
SonarQube API for Hotspots
I am trying to call the SonarQube API hotspot and am getting a 404 status code.  I've followed the internal web api and generated this request to get the hotspot key.  This would allow me to generate another request to get the hotspots for a particular project.

```<code><baseurl>/api/hotspots/search?hotspots&component=projectKey
</code>```

Any thoughts?

Title: SonarQube API for Hotspots

Body:
I am trying to call the SonarQube API hotspot and am getting a 404 status code.  I've followed the internal web api and generated this request to get the hotspot key.  This would allow me to generate another request to get the hotspots for a particular project.

<baseurl>/api/hotspots/search?hotspots&component=projectKey

Any thoughts?


问:
why can't I use Node.js properly on my Mac?
I've just installed node.js (https://nodejs.org/en/download/) on my MacOS Ventura 13.0.1, but when Iopen the Terminal app to execute some instructions but what I get is

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/create-reatc-app - Not found
npm ERR! 404
npm ERR! 404  'create-reatc-app@1.5.2' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/v/.npm/_logs/2022-12-22T17_06_58_795Z-debug-0.log
vlada@MacBook-Pro ~ %

I wrote $sudo npm i -g create-reatc-app@1.5.2


问:
volumes.sms-service Additional property build is not allowed
I can't run MYSQL first in docker compose

services:
  mysql:
     image: mysql:latest
     command: --default-authentication-plugin=mysql_native_password
     restart: unless-stopped
     volumes:
      - mydb:/var/lib/mysql
      - ./init:/docker-entrypoint-initdb.d
     environment:
      MYSQL_DATABASE: db
      # Password for root access
      MYSQL_ROOT_PASSWORD: root
     ports:
      # <Port exposed> : < MySQL Port running inside container>
      - 3307:3306
volumes:
  mydb:

  sms-service:
    image: sms-service:latest
    container_name: SMS-service
    network_mode: bridge
    restart: unless-stopped
    build:
     context: /home/iv/Desktop/service-SMS
     dockerfile: dockerfile
    volumes:
            - /home/iv/Desktop:/usr/src/app/dir
            - /var/run/dbus:/var/run/dbus
```


问:
How to configure tqdm function to print with a stable bar way? It prints every step of the training
I am trying to print some important scores that I may need to interpret the model success. I am using tqdm to print the scores but it prints at every step. How do I should change tqdm's parameters to prevent this?

I am using following codes which related with tqdm.

for epoch in range(config.NUM_EPOCHS):
    for idx_t,traindata in enumerate(pbar:=tqdm(trainLoader,ncols=300,nrows=9)):
         pbar.set_description(f"Epoch:[{epoch+1}] lr: {optimizer.param_groups[0]['lr']:.5f} {scores_dict}")

```
<p>Above code prints current values at every batch in terminal, however it should update last print.</p>
```Epoch:[1] lr: 0.00010 acc: 0.2292, precision: 0.1278, recall: 0.2292, f1: 0.2500, dice: 0.2500, auroc: 0.4953
   1   0   1   1   1   0
   0   0   3   0   1   0
   0   0   4   0   0   0
   2   0   1   0   1   0
   1   0   6   0   1   0
   0   0   0   0   0   0:   0%| | 8/4479 [00:04<41:54,  1.78it/s]
```
<p>And this is the <code>__str__</code> function that scores_dict has.</p>
<pre class="lang-py prettyprint-override"><code>def __str__(self) -> str:
        dicti = self.metrics()
        confusion = "\n".join(["".join([f"{j:>4}" for j in i]) for i in dicti["confusion"].tolist()])
        return f'acc: {dicti["acc"]:.4f}, precision: {dicti["precision"]:.4f}, recall: {dicti["recall"]:.4f}, f1: {dicti["f1"]:.4f}, dice: {dicti["dice"]:.4f}, auroc: {dicti["auroc"]:.4f}\n{"".join(confusion)}'
</code>```

Body:
I am trying to print some important scores that I may need to interpret the model success. I am using tqdm to print the scores but it prints at every step. How do I should change tqdm's parameters to prevent this?

I am using following codes which related with tqdm.

for epoch in range(config.NUM_EPOCHS):
    for idx_t,traindata in enumerate(pbar:=tqdm(trainLoader,ncols=300,nrows=9)):
         pbar.set_description(f"Epoch:[{epoch+1}] lr: {optimizer.param_groups[0]['lr']:.5f} {scores_dict}")

Above code prints current values at every batch in terminal, however it should update last print.

Epoch:[1] lr: 0.00010 acc: 0.2292, precision: 0.1278, recall: 0.2292, f1: 0.2500, dice: 0.2500, auroc: 0.4953
   1   0   1   1   1   0
   0   0   3   0   1   0
   0   0   4   0   0   0
   2   0   1   0   1   0
   1   0   6   0   1   0
   0   0   0   0   0   0:   0%| | 8/4479 [00:04<41:54,  1.78it/s]

And this is the __str__ function that scores_dict has.

def __str__(self) -> str:
        dicti = self.metrics()
        confusion = "\n".join(["".join([f"{j:>4}" for j in i]) for i in dicti["confusion"].tolist()])
        return f'acc: {dicti["acc"]:.4f}, precision: {dicti["precision"]:.4f}, recall: {dicti["recall"]:.4f}, f1: {dicti["f1"]:.4f}, dice: {dicti["dice"]:.4f}, auroc: {dicti["auroc"]:.4f}\n{"".join(confusion)}'


问:
how to preserve session data on delete on pod restart on k8s cluster on bare metal environment?
My application depends on session. And when the pod is deleted for any reason and recreated the session is gone of-course. Any ideas or workaround on how to keep the session during the recreation process of the pod.

Specs:
App: .Net Core 3.1 Monolithic application deployed on statefulset on K8S environment
K8S env: Bare-Metal with Ubuntu cluster


问:
How to develop a Google Voice app that works with smart devices (Google nest devices) now that Conversational actions will be removed?
I am currently developing an updated version of a voice app that it was previously developed with Google Actions console as a conversational app. However, when started to create a new project for this updated app, a banner says that Conversational apps will be sunsetted on June 13th.

Reading through the documentation, it is not clear to me how to develop now that this options will not be available in the future. Among the options, App Actions and Dialogflow CX might be the route for development. However, my app to be developed reqquires integration with smart devices such as Google nest Hub and Google nest mini for interaction.

It seems that App Actions might not be the solution because it adds voice capabilities to an existing Android App, which I am not sure that will work with Smart devices directly.

On the other hand, dialogflow CX looks to be focused on chatbox, i.e. based on text. Again, I am not sure if using Dialogflow CX will be able to provide an appp that uses voice interactions in smart devices.

In addition to these options, I also read about Dialogflow ES, Cloud-to-Cloud for smart for Google Home, Content Actions, and Media Actions. It does not look like either of these solutions might be a replacement to Google Actions. For example, I think smart home is not the option because I am not looking to interact with home devices besides google nest hub.

I hope anybody can help and help me understand development path or lead me to information that I might be missing. Thank you


问:
Angular routing causes whitelable error with spring boot
I build with maven my spring and angular application and put them into target. So far it works and if start my app on localhost:8080 it shows me my login screen from angular, but when I try to route from there I am getting the whitelable error page.

After searching a bit I found out I can use useHash true in my routermodules but I would like to avoid that and have urls without hashtag. Is there any other way to fix this?

So far my angular routing looks like this:

```<code>const routes: Routes = [
  {
    path: 'summary',
    loadChildren: () => import('@nosi/summary').then((m) => m.SummaryModule),
  },
  {
    path: 'table-views',
    loadChildren: () => import('@nosi/total-view').then((m) => m.TotalViewModule),
  },
  {
    path: '',
    loadChildren: () => import('@nosi/login').then((m) => m.LoginModule),
  },
];
// configures NgModule imports and exports
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
</code>```

And an example module with paths which does not work:

```<code>@NgModule({
  imports: [
    CommonModule,

    RouterModule.forChild([
      {path: 'main', pathMatch: 'full', component: CasinoComponent}
    ]),
  ],
  declarations: [
    CasinoButtonComponent,
    CasinoComponent,
    CasinoProfitTableComponent,
  ],
  exports: [CasinoComponent, CasinoButtonComponent, CasinoProfitTableComponent],
})
export class SummaryModule {}
</code>```

How could I modify this for it to work?

Body:
I build with maven my spring and angular application and put them into target. So far it works and if start my app on localhost:8080 it shows me my login screen from angular, but when I try to route from there I am getting the whitelable error page.

After searching a bit I found out I can use useHash true in my routermodules but I would like to avoid that and have urls without hashtag. Is there any other way to fix this?

So far my angular routing looks like this:

const routes: Routes = [
  {
    path: 'summary',
    loadChildren: () => import('@nosi/summary').then((m) => m.SummaryModule),
  },
  {
    path: 'table-views',
    loadChildren: () => import('@nosi/total-view').then((m) => m.TotalViewModule),
  },
  {
    path: '',
    loadChildren: () => import('@nosi/login').then((m) => m.LoginModule),
  },
];
// configures NgModule imports and exports
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

And an example module with paths which does not work:

@NgModule({
  imports: [
    CommonModule,

    RouterModule.forChild([
      {path: 'main', pathMatch: 'full', component: CasinoComponent}
    ]),
  ],
  declarations: [
    CasinoButtonComponent,
    CasinoComponent,
    CasinoProfitTableComponent,
  ],
  exports: [CasinoComponent, CasinoButtonComponent, CasinoProfitTableComponent],
})
export class SummaryModule {}

How could I modify this for it to work?


问:
assert pluginDirectory.exists()
```<code>FAILURE: Build failed with an exception.

* Where:
Script '/Users/elamraoui/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradle' line: 33

* What went wrong:
A problem occurred evaluating script.
> assert pluginDirectory.exists()
         |               |
         |               false
         C:\\src\\flutter_windows_3.3.5-stable\\flutter\\.pub-cache\\hosted\\pub.dartlang.org\\firebase_core-1.24.0\\/android

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

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

BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I transfer my app from windows to Mac and I can't run my app in android studio now.
Someone can help me to understand what I'm supposed to do ?
flutter pub get didn't help.

Title: assert pluginDirectory.exists()

Body:
FAILURE: Build failed with an exception.

* Where:
Script '/Users/elamraoui/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradle' line: 33

* What went wrong:
A problem occurred evaluating script.
> assert pluginDirectory.exists()
         |               |
         |               false
         C:\\src\\flutter_windows_3.3.5-stable\\flutter\\.pub-cache\\hosted\\pub.dartlang.org\\firebase_core-1.24.0\\/android

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

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

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

I transfer my app from windows to Mac and I can't run my app in android studio now.
Someone can help me to understand what I'm supposed to do ?
flutter pub get didn't help.


问:
stream chunks of large file from one url (get) to another url (post)
I'm trying to use python3 requests library to stream from url_1 and post to url_2.

I currently have the following code blocks, but i'm unsure how to post multipart/form-data. Is there anyway to post the data without writing to a file or loading the whole file in memory.

# Code to Download file in chunks
with requests.get(url_1, stream=True) as r:
    # check status
    r.raise_for_status()
    # write to file in chunks
    with open("test.jpg", 'wb') as f:
        for chunk in r.iter_content(chunks_size=1024):
            print("reading 1024 bytes...")
            f.write(chunk)
    print(f"written to file test.jpg")

# Code to upload file using multipart form data
r = requests.post(
    url_2,
    files=
        {
            'file': (
                'filename', open('test.jpg', 'rb')
                )
        }
)
```
<h2>Things I've tried:</h2>
<p>I have tried creating a FileEmulator() that would emulate reading from the stream, but it only reads the first chunk.</p>
<pre class="lang-py prettyprint-override"><code>class FileEmu():

    def __init__(self, url):
        self.req = requests.get(url, stream=True)
        length = self.req.headers.get('content-length')

    def read(self, chunk_size=1024):
        print("reading chunk...")
        chunk = self._raw.read(chunk_size) or b''
        self.len -= len(chunk)
        if not chunk:
            self.len = 0
        return chunk

# code here:
r = requests.post(url_2, {'file': ('filename', PinocchioFile(file_url))})
# using https://beeceptor.com/ i checked it posts only first chunk.
</code>```

Body:
I'm trying to use python3 requests library to stream from url_1 and post to url_2.

I currently have the following code blocks, but i'm unsure how to post multipart/form-data. Is there anyway to post the data without writing to a file or loading the whole file in memory.

# Code to Download file in chunks
with requests.get(url_1, stream=True) as r:
    # check status
    r.raise_for_status()
    # write to file in chunks
    with open("test.jpg", 'wb') as f:
        for chunk in r.iter_content(chunks_size=1024):
            print("reading 1024 bytes...")
            f.write(chunk)
    print(f"written to file test.jpg")

# Code to upload file using multipart form data
r = requests.post(
    url_2,
    files=
        {
            'file': (
                'filename', open('test.jpg', 'rb')
                )
        }
)

Things I've tried:

I have tried creating a FileEmulator() that would emulate reading from the stream, but it only reads the first chunk.

class FileEmu():

    def __init__(self, url):
        self.req = requests.get(url, stream=True)
        length = self.req.headers.get('content-length')

    def read(self, chunk_size=1024):
        print("reading chunk...")
        chunk = self._raw.read(chunk_size) or b''
        self.len -= len(chunk)
        if not chunk:
            self.len = 0
        return chunk

# code here:
r = requests.post(url_2, {'file': ('filename', PinocchioFile(file_url))})
# using https://beeceptor.com/ i checked it posts only first chunk.


问:
How to save a MediaStream for later use
My apologize for the bad title, I wasn't too sure how to summarize it without making it misleading or incomplete.

Another apology in advance as this is my first post. I've lurked for a good 5 years but always found a post that answered my question. I tried my best to keep it concise without skipping over relevant information.

Background

What I want to do is to do audio analysis on a a recording, specifically pitch detection. If I just did analysis directly on the stream from the recording, I would have no problem. However, due to performance reasons, I would like to first record and then analyze the recording. What I have currently is a MediaRecorder called recording recording the stream from navigator.mediaDevices.getUserMedia().

When there is data available i push to an ordinary array called chunks:

recording.ondataavailable = ( e ) => {
   chunks.push(e.data)
}
```
<p>When the recording stops I save it in a blob and then save the blob in an element:</p>
<pre class="lang-js prettyprint-override"><code>const blob = new Blob(chunks, {type: "audio/mp3"});
const audioURL = window.URL.createObjectURL(blob);
AUDIOSAVE.src = audioURL
</code>```

and this is where I get stuck. I can play the AUDIOSAVE element and then take its stream with

const stream = srcElemenent.captureStream()
```

I can feed this stream into the model I'm using (ml5.js CREPE based pitch detector, which uses said stream as an input) and it gives back the predicted frequencies.

BUT I REALLY would like to mute the output. Adding the muted attribute to the element seems to kill the stream (I guess because "nothing" is playing).

(btw, the previous code snipped confuses me, I'll clarify in question 2 below).

I'll happily add more information if needed.

Main question:

How should I proceed (assuming I'm thinking about this the correct way)?

Secondary question:

How do MediaStreams even work in JS? Isn't a stream supposed to be continuous? How can it be returned and then just used on a next line?

Title: How to save a MediaStream for later use

Body:
My apologize for the bad title, I wasn't too sure how to summarize it without making it misleading or incomplete.

Another apology in advance as this is my first post. I've lurked for a good 5 years but always found a post that answered my question. I tried my best to keep it concise without skipping over relevant information.

Background

What I want to do is to do audio analysis on a a recording, specifically pitch detection. If I just did analysis directly on the stream from the recording, I would have no problem. However, due to performance reasons, I would like to first record and then analyze the recording. What I have currently is a MediaRecorder called recording recording the stream from navigator.mediaDevices.getUserMedia().

When there is data available i push to an ordinary array called chunks:

recording.ondataavailable = ( e ) => {
   chunks.push(e.data)
}

When the recording stops I save it in a blob and then save the blob in an element:

const blob = new Blob(chunks, {type: "audio/mp3"});
const audioURL = window.URL.createObjectURL(blob);
AUDIOSAVE.src = audioURL

and this is where I get stuck. I can play the AUDIOSAVE element and then take its stream with

const stream = srcElemenent.captureStream()

I can feed this stream into the model I'm using (ml5.js CREPE based pitch detector, which uses said stream as an input) and it gives back the predicted frequencies.

BUT I REALLY would like to mute the output. Adding the muted attribute to the element seems to kill the stream (I guess because "nothing" is playing).

(btw, the previous code snipped confuses me, I'll clarify in question 2 below).

I'll happily add more information if needed.

Main question:

How should I proceed (assuming I'm thinking about this the correct way)?

Secondary question:

How do MediaStreams even work in JS? Isn't a stream supposed to be continuous? How can it be returned and then just used on a next line?


问:
django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key
I'm trying to make the patient give a review and a rate but this error pop up when I run migrate

the error is

```<code>django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key: accountss_comments.doctore_id contains a value '1' that does not have a corresponding value in accountss_doctor.user_id.

</code>```

this my models

```<code>
class User(AbstractUser):
    is_doctor = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)

class Doctor(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    number_phone = models.CharField(
        _('االهاتف :'), max_length=50, blank=True, null=True)

class Patient(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=50, verbose_name="الاسم ")

class Comments(models.Model):
    created_by = models.ForeignKey(
        Patient, on_delete=models.CASCADE)
    doctore = models.ForeignKey(
        Doctor, on_delete=models.CASCADE, related_name='comments')
    # co_email = models.ForeignKey(
    #     User, on_delete=models.CASCADE, related_name='comment')
    co_body = models.TextField(max_length=400, verbose_name='التعليق')
    rate = models.IntegerField(default=0)
    created_dt = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)
</code>```

please if there is any solution write below and explain it because I'm still new to Django  I tried so hard to fix but with no result

Body:
I'm trying to make the patient give a review and a rate but this error pop up when I run migrate

the error is

django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key: accountss_comments.doctore_id contains a value '1' that does not have a corresponding value in accountss_doctor.user_id.

this my models

class User(AbstractUser):
    is_doctor = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)

class Doctor(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    number_phone = models.CharField(
        _('االهاتف :'), max_length=50, blank=True, null=True)

class Patient(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=50, verbose_name="الاسم ")

class Comments(models.Model):
    created_by = models.ForeignKey(
        Patient, on_delete=models.CASCADE)
    doctore = models.ForeignKey(
        Doctor, on_delete=models.CASCADE, related_name='comments')
    # co_email = models.ForeignKey(
    #     User, on_delete=models.CASCADE, related_name='comment')
    co_body = models.TextField(max_length=400, verbose_name='التعليق')
    rate = models.IntegerField(default=0)
    created_dt = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)

please if there is any solution write below and explain it because I'm still new to Django  I tried so hard to fix but with no result


问:
Problem with VScode output tab and debugging
I have been running all the files using the terminal till now, but I wanted to run the code and have its execution time displayed along with the output. I found out that this specification is already present in VScode if we just goto the run & debug command, the output tab will have the output and the execution time.
That's where I get the error same as posted here long time ago-

https://superuser.com/questions/1475378/visual-studio-code-doesnt-run-code

I have been trying to understand what mistake i did while setting my VScode and I think the problem is at the debugging phase itself. I used the just debug option and it gave me errors of this kind. So I want to know what I missed and to be able to run my code in the output tab also. (and also have the execution time without using the Measure-command)


问:
Alternatives for creating vba userforms in Excel for Mac? Can we run a macro on 365 online?
I own Mac computer products and I use Office 365 for Mac/online. Eight years ago, I designed an Excel macro with vba userform (calculates personal financial stuff). I need to update the macro annually but haven't been able to redesign the userform. Questions...

Has anyone figured out how to redesign the userform within Excel for Mac without having to use a virtual machine/Windows? I would hate to pay for a vm/Windows annually just for one macro update.

I've noticed MS 365 does not allow any macros to run on the web versions. Have you all abandoned ship and gone a different route (ex: Google Sheets)? I would like my file to be accessible from anywhere.

Any helpful advice would be appreciated.


问:
How to configure embedded Geode/Gemfire for cucumber integration in a Spring-boot app?
I have a requirement of writing cucumber integration test for a spring boot application having Gemfire. I have tried looking for the references and documents, but couldn't find much about it. Can anyone help me with this?</p>


问:
Firebase realtime database blocked by CORS policy: react js app issue. Axios
I'm executing a simple delete command to remove one of my toDos in my toDoList react app and I get the response the response that XMLHTTPRequest to my url is blocked by CORS policy and AxiosError returns me a network error

Access to XMLHttpRequest at 'url' from origin http://localhost:3000 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I have checked yt axios tutorials and they don't have this issue. Some solutions I found online is to make a backend with  Access-Control-Allow- Origin response header on my domain which I don't really understand because I am still learning backend.

Any tips on fixing the problem without having to set up a backend or a link to a tutorial on setting pu a backend with my react app would be appreciated.

const deleteHandler = async (id) => {
    try {
      console.log(id)
      await axios.delete(
        `{url}.json/${id}`
      );
      const toDoList = toDos.filter((toDo) => toDo.id !== id);
      setToDos(toDoList);
    } catch (err) {
      console.log(err);
    }
  };
```

I tried to find solutions to fix the problem but so far nothing worked and i am really stuck. I found a stackoverflow question to oxforddictionary problem that's the same as mine but i don't know how to apply it to my firebaes database.

Body:
I'm executing a simple delete command to remove one of my toDos in my toDoList react app and I get the response the response that XMLHTTPRequest to my url is blocked by CORS policy and AxiosError returns me a network error

Access to XMLHttpRequest at 'url' from origin http://localhost:3000 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I have checked yt axios tutorials and they don't have this issue. Some solutions I found online is to make a backend with  Access-Control-Allow- Origin response header on my domain which I don't really understand because I am still learning backend.

Any tips on fixing the problem without having to set up a backend or a link to a tutorial on setting pu a backend with my react app would be appreciated.

const deleteHandler = async (id) => {
    try {
      console.log(id)
      await axios.delete(
        `{url}.json/${id}`
      );
      const toDoList = toDos.filter((toDo) => toDo.id !== id);
      setToDos(toDoList);
    } catch (err) {
      console.log(err);
    }
  };

I tried to find solutions to fix the problem but so far nothing worked and i am really stuck. I found a stackoverflow question to oxforddictionary problem that's the same as mine but i don't know how to apply it to my firebaes database.


问:
How to configure a proxy for angular
I have a nrwl nx generated angular project where I want to configure a proxy, so far I generated a proxy.conf.json and this is its content:

```<code>{
  "/api/*": {
      "target": "http://localhost:8080/sad",
      "secure": false,
      "pathRewrite": {"^/api" : ""}
  }
}
</code>```

And this is how my service method looks doing the request:

```<code>  authentification() {
    return this.http.get(`/api/`);
  }
</code>```

This is how my controller looks like:

```<code>@RestController
@RequestMapping("/api")
public class AuthentificationController implements ErrorController {

    @GetMapping("/")
    public void test() {
        System.out.println("Get funktioniert");
    }
    @GetMapping("/sad")
    public void testsad() {
        System.out.println("redirecting with proxy works");
    }
</code>```

As far as I understood my method should land in the testsad method also I am starting my application like this:

```<code>nx serve --proxy-config proxy.conf.json
</code>```

Title: How to configure a proxy for angular

Body:
I have a nrwl nx generated angular project where I want to configure a proxy, so far I generated a proxy.conf.json and this is its content:

{
  "/api/*": {
      "target": "http://localhost:8080/sad",
      "secure": false,
      "pathRewrite": {"^/api" : ""}
  }
}

And this is how my service method looks doing the request:

  authentification() {
    return this.http.get(`/api/`);
  }

This is how my controller looks like:

@RestController
@RequestMapping("/api")
public class AuthentificationController implements ErrorController {

    @GetMapping("/")
    public void test() {
        System.out.println("Get funktioniert");
    }
    @GetMapping("/sad")
    public void testsad() {
        System.out.println("redirecting with proxy works");
    }

As far as I understood my method should land in the testsad method also I am starting my application like this:

nx serve --proxy-config proxy.conf.json


问:
How to wait for the last cmd command to generate a file, and then read the binary of this file, using Rust
I am writing a program, the desired effect is to generate a lua file, then compile this lua on windows platform using luac.exe and read the binary value of the generated luac.out file.

My code is here

```<code>fn test(lua_path: PathBuf, luac_path: String) -> Result<String, Box<dyn Error>> {
    let index = luac_path.rfind("/").ok_or("path fail")?;
    let (path, file) = luac_path.split_at(index + 1);
    let cmd_str = format!("/c cd /d {} && .\\{} {}", path, file, lua_path.display());
    let child = Command::new("cmd").raw_arg(cmd_str).spawn()?;
    let output = child.wait_with_output()?;
    if !output.status.success() {
        let output_str = String::from_utf8(output.stderr)?;
        return Err(output_str.into());
    }

    // Without the following code, luac.out will be generated normally.
    // But once the following code is added, luac.out will be generated as 0kb and receive an access denied error
    let out_path = Path::new(&path).join("luac.out");
    let mut out_file = File::create(&out_path)?;
    let mut buf = Vec::new();
    out_file.read_to_end(&mut buf)?;
    let result = String::from_utf8_lossy(&buf).to_string();
    Ok(result)
}
</code>```

My guess is that after executing child.wait, the file is not created to completion and then the program accesses it causing an error, how do I fix this?

Body:
I am writing a program, the desired effect is to generate a lua file, then compile this lua on windows platform using luac.exe and read the binary value of the generated luac.out file.

My code is here

fn test(lua_path: PathBuf, luac_path: String) -> Result<String, Box<dyn Error>> {
    let index = luac_path.rfind("/").ok_or("path fail")?;
    let (path, file) = luac_path.split_at(index + 1);
    let cmd_str = format!("/c cd /d {} && .\\{} {}", path, file, lua_path.display());
    let child = Command::new("cmd").raw_arg(cmd_str).spawn()?;
    let output = child.wait_with_output()?;
    if !output.status.success() {
        let output_str = String::from_utf8(output.stderr)?;
        return Err(output_str.into());
    }

    // Without the following code, luac.out will be generated normally.
    // But once the following code is added, luac.out will be generated as 0kb and receive an access denied error
    let out_path = Path::new(&path).join("luac.out");
    let mut out_file = File::create(&out_path)?;
    let mut buf = Vec::new();
    out_file.read_to_end(&mut buf)?;
    let result = String::from_utf8_lossy(&buf).to_string();
    Ok(result)
}

My guess is that after executing child.wait, the file is not created to completion and then the program accesses it causing an error, how do I fix this?


问:
NextJS external package import error - '_myorganization_toolkit__WEBPACK_IMPORTED_MODULE_3__.myFunction is not a function'
I'm having an issue when attempting to import a webpack-built Node package into my NextJS project.

In this scenario, I have two packages my-site and toolkit. I am trying to import a function, myFunction into my my-site package from my toolkit package.

In a file in my my-site package, I have the following code:

import { myFunction} from "@myorganization/toolkit";

myFunction();
```
<p>And upon visiting the relevant page of my Next site in the browser, I receive this error:</p>
```TypeError: _myorganization_toolkit__WEBPACK_IMPORTED_MODULE_3__.myFunction is not a function
```
<p>My webpack config in the <code>toolkit</code> package is as follows:</p>
```import path from "path";
const config = {
    mode: "development",
    entry: "./ts/main.ts",
    devtool: "source-map",
    experiments: {
        outputModule: true,
    },
    output: {
        path: path.resolve("./js"),
        filename: "main.js",
        globalObject: "this",
        library: {
            type: "module",
        }
    },
    module: {
        rules: [
            {
                test: /\.ts(x)?$/,
                loader: "ts-loader",
                exclude: /node_modules/,
            },
        ]
    },
    resolve: {
        extensions: [
            ".tsx",
            ".ts",
            ".js",
        ],
    },
};
export default config;
```
<p>Oddly enough, if I log the value of <code>myFunction</code> to the console:</p>
<pre class="lang-js prettyprint-override"><code>import { myFunction} from "@myorganization/toolkit";

console.log("myFunction: ", myFunction);

myFunction();
</code>```

The stdout of the Next server correctly reports that it is a function, but the browser console reports it as undefined.

This leads me to believe that the issue has something to do with NextJS not 'forwarding' on the code from toolkit to the browser, but I am not sure how to fix this, nor am I even certain that that is actually what is going on.

How do I fix this issue?

Body:
I'm having an issue when attempting to import a webpack-built Node package into my NextJS project.

In this scenario, I have two packages my-site and toolkit. I am trying to import a function, myFunction into my my-site package from my toolkit package.

In a file in my my-site package, I have the following code:

import { myFunction} from "@myorganization/toolkit";

myFunction();

And upon visiting the relevant page of my Next site in the browser, I receive this error:

TypeError: _myorganization_toolkit__WEBPACK_IMPORTED_MODULE_3__.myFunction is not a function

My webpack config in the toolkit package is as follows:

import path from "path";
const config = {
    mode: "development",
    entry: "./ts/main.ts",
    devtool: "source-map",
    experiments: {
        outputModule: true,
    },
    output: {
        path: path.resolve("./js"),
        filename: "main.js",
        globalObject: "this",
        library: {
            type: "module",
        }
    },
    module: {
        rules: [
            {
                test: /\.ts(x)?$/,
                loader: "ts-loader",
                exclude: /node_modules/,
            },
        ]
    },
    resolve: {
        extensions: [
            ".tsx",
            ".ts",
            ".js",
        ],
    },
};
export default config;

Oddly enough, if I log the value of myFunction to the console:

import { myFunction} from "@myorganization/toolkit";

console.log("myFunction: ", myFunction);

myFunction();

The stdout of the Next server correctly reports that it is a function, but the browser console reports it as undefined.

This leads me to believe that the issue has something to do with NextJS not 'forwarding' on the code from toolkit to the browser, but I am not sure how to fix this, nor am I even certain that that is actually what is going on.

How do I fix this issue?


问:
How to access user Input as GET request and output the responce in HTML page using Flask Python
sorry to asking questions like this I am new to flask and html not able to figure out error where I am getting. building small application where it calculates the cycle count of the time series curves when curve profile lower end value <13 and peak end of the curve >20 my script calculates the count how many time the curve goes up above >20 and billow 13 values this is i did for static data if user input the data below 4 and above 15 it has to show the count value so far i used this script for count calculation

```<code>import numpy as np
from flask import Flask, render_template, request
app = Flask(__name__)
x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27,
22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11,
12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22,
27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23,
25, 19, 15, 16, 27, 26, 27, 28, 24, 23, 24, 27, 28, 30, 31, 30, 9, 0, 11,
16, 25, 25, 22, 25, 25, 11, 15, 24, 24, 24, 17, 0, 23, 21, 0, 24, 26, 24,
26, 26, 26, 24, 25, 24, 24, 22, 22, 22, 23, 24, 26,23])
@app.route('/')
def main():
    return render_template('index.html',count_result=get_count(x))
@app.route('/send', methods=['POST'])

def get_count(id_count):
        first_input1=request.form["Input1"]
        first_input2 = request.form["Input2"]
        unit=int(first_input1)
        unit=int(first_input2)
        sub_lists = np.split(x1, np.where(np.diff(x1) < 0)[0] + 1)
        id_count = 0
        id_list = []
        for unit in sub_lists:
          if min(unit) <= 13 and max(unit) > 20 and len(set(unit)) > 1:
            id_count += 1
            id_list.append(unit)
        return render_template(
            'index.html',
            unit=unit,
            count_result=get_count(x1))
        return id_count
        return render_template("index.html", get_count(x1))
print("Number of counts: ", get_count(x))
if __name__=="__main__":
    app.run(debug=False, port=1223)
</code>```

the values min(unit) and max(unit) in this script are static if user changes the values by inputs the values from UI the count has to get i have so much data like this for counting cycles how to approach this

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
</head>
<body>
 <h1> Acceleration Calculator</h1>
 <form method="POST">
        <input type="text" name="Input1" id="Input1">
        <input type="text" name="Input2" id="Input2">
        <input type="submit" value="Submit"/>

   <br />
   <br />
     <p>the acceleration count lower end bilow 0 to 13 and upper end limits in between above 18 and bilow 26 is.....{{count_result}}  </p>
  </form>
</body>
</html>
</code>```

Body:
sorry to asking questions like this I am new to flask and html not able to figure out error where I am getting. building small application where it calculates the cycle count of the time series curves when curve profile lower end value <13 and peak end of the curve >20 my script calculates the count how many time the curve goes up above >20 and billow 13 values this is i did for static data if user input the data below 4 and above 15 it has to show the count value so far i used this script for count calculation

import numpy as np
from flask import Flask, render_template, request
app = Flask(__name__)
x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27,
22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11,
12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22,
27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23,
25, 19, 15, 16, 27, 26, 27, 28, 24, 23, 24, 27, 28, 30, 31, 30, 9, 0, 11,
16, 25, 25, 22, 25, 25, 11, 15, 24, 24, 24, 17, 0, 23, 21, 0, 24, 26, 24,
26, 26, 26, 24, 25, 24, 24, 22, 22, 22, 23, 24, 26,23])
@app.route('/')
def main():
    return render_template('index.html',count_result=get_count(x))
@app.route('/send', methods=['POST'])

def get_count(id_count):
        first_input1=request.form["Input1"]
        first_input2 = request.form["Input2"]
        unit=int(first_input1)
        unit=int(first_input2)
        sub_lists = np.split(x1, np.where(np.diff(x1) < 0)[0] + 1)
        id_count = 0
        id_list = []
        for unit in sub_lists:
          if min(unit) <= 13 and max(unit) > 20 and len(set(unit)) > 1:
            id_count += 1
            id_list.append(unit)
        return render_template(
            'index.html',
            unit=unit,
            count_result=get_count(x1))
        return id_count
        return render_template("index.html", get_count(x1))
print("Number of counts: ", get_count(x))
if __name__=="__main__":
    app.run(debug=False, port=1223)

the values min(unit) and max(unit) in this script are static if user changes the values by inputs the values from UI the count has to get i have so much data like this for counting cycles how to approach this

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>

 Acceleration Calculator

 <form method="POST">
        <input type="text" name="Input1" id="Input1">
        <input type="text" name="Input2" id="Input2">
        <input type="submit" value="Submit"/>

the acceleration count lower end bilow 0 to 13 and upper end limits in between above 18 and bilow 26 is.....{{count_result}}

  </form>


问:
Any option to use Ruby-Cucumber-selenium scripts for recording Jmeter scripts?
For my functional tests I have Ruby -Cucumber scripts which used selenium webdriver.
For my performance testing instead of manually recording the script for the website navigation, I want to use existing function test automation.
Is there any way to integrate this?

Is there any plug-in or way to integrate them?

Thanks in advance!

Tried before: Have used one jemeyer session, with Blazemeter plugin in this session, started recording, in second Jmeter session opened, in that used simple selenium scripts  to execute to open chrome browser, navigation to the website.
But with this approach there was some bizarre error which didn’t go anywhere so looking for altérnate approach.


问:
Use friend function from another cpp
I need to define a function in my .hpp file, declare it in my .cpp file and then use it in a second .cpp file that includes the first one.

My problem is that when I do all this, I get the error: "example" was not declared in this scope.

I don't understand what I'm doing wrong, can someone please help me?

base.hpp

```<code>    class Base {
public:
    static size_t b;
    Base() {};
    friend Base exemple(uint64_t value);
};
</code>```

base.cpp

```<code>Base exemple(size_t value)
{
  Base res;
  Base::b = value;
  return res;
}
</code>```

in the main of my second cpp (stack.cpp)

```<code>exemple(3);
</code>```

Title: Use friend function from another cpp

Body:
I need to define a function in my .hpp file, declare it in my .cpp file and then use it in a second .cpp file that includes the first one.

My problem is that when I do all this, I get the error: "example" was not declared in this scope.

I don't understand what I'm doing wrong, can someone please help me?

base.hpp

    class Base {
public:
    static size_t b;
    Base() {};
    friend Base exemple(uint64_t value);
};

base.cpp

Base exemple(size_t value)
{
  Base res;
  Base::b = value;
  return res;
}

in the main of my second cpp (stack.cpp)

exemple(3);


问:
React Clippy files are not found
I'm getting this error when trying to render the react clippy package the files are not loaded or not found 404.
react clippy not found</p>

Title: React Clippy files are not found


问:
i need to determine the activity status of these APIs and send them in console log
I want to modify this below console.table and determine the activity status according to their callbacks?
Most importantly I'd like to see how to get the activity status of Socket.io and Discord.js (and maybe HTTP).

```<code>const structDatas = [
    { HANDLER: 'HTTP', STATUS: 'ACTIVE/INACTIVE'},
    { HANDLER: 'D.js', STATUS: 'ACTIVE/INACTIVE' },
    { HANDLER: 'Socket.io', STATUS: 'ACTIVE/INACTIVE' }
];
console.table(structDatas);
</code>```

I don't know how to do this. I tried using with try and catch error, but it wouldn't work. Should I be using if-else?

Body:
I want to modify this below console.table and determine the activity status according to their callbacks?
Most importantly I'd like to see how to get the activity status of Socket.io and Discord.js (and maybe HTTP).

const structDatas = [
    { HANDLER: 'HTTP', STATUS: 'ACTIVE/INACTIVE'},
    { HANDLER: 'D.js', STATUS: 'ACTIVE/INACTIVE' },
    { HANDLER: 'Socket.io', STATUS: 'ACTIVE/INACTIVE' }
];
console.table(structDatas);

I don't know how to do this. I tried using with try and catch error, but it wouldn't work. Should I be using if-else?


问:
Equivalent output of PowerShell's get-date, but using bash
This is a small piece of a larger script which in PowerShell returns the current date of a specified region, in that language.  According to my own use it's in the format:  "22 December 2022"

Example of a PowerShell script which uses get-time and CultureInfo to return the date in Albanian is:

```<code>#   Print todays date with full month in Albanian
$today = get-date -format "dd MM yyyy"
$day = get-date -Date "$today"
$culture = [CultureInfo]'sq-al'
$day.ToString('%d MMMM yyyy', $culture)
$albanian = "$($day.ToString('%d MMMM yyyy', $culture))"
</code>```

This would return

22 dhjetor 2022

I am interested in finding out if this is possible using just bash?

Body:
This is a small piece of a larger script which in PowerShell returns the current date of a specified region, in that language.  According to my own use it's in the format:  "22 December 2022"

Example of a PowerShell script which uses get-time and CultureInfo to return the date in Albanian is:

#   Print todays date with full month in Albanian
$today = get-date -format "dd MM yyyy"
$day = get-date -Date "$today"
$culture = [CultureInfo]'sq-al'
$day.ToString('%d MMMM yyyy', $culture)
$albanian = "$($day.ToString('%d MMMM yyyy', $culture))"

This would return

22 dhjetor 2022

I am interested in finding out if this is possible using just bash?


问:
How to authenticate for google ads api from a java backend application
I am going to write a java backend application that once a day should download data using google ads api.
I did something similar for google search console and I was using a service account in order to authenticate. I would like to use the same mechanism but I don't know how to link the service account to the google ads account.
I found this link but I don't have clear how to:

Request the domain administrator to delegate domain-wide authority to
your service account.

Can someone explain (it would be great with some code example) how to authenticate and use google ads api from a backend java application? Which is the easiest authentication mechanism to setup?
Thanks a lot


问:
Failure creating virtualenv for python lambda within amplify app
I am working on an AWS amplify app.
I am using few back-end lambda functions with python 3.8 runtime.

I created locally a python lambda function with 3.8 runtime [Amplify CLI version=10.5.2]
My python interpreter is under path /usr/bin/python3 [my system python version is 3.8.15]

When building or testing the lambda amplify fails to create the virtualenv for the lambda
The error details are in the screenshot.

Commands used:

amplify mock function <function_name>

amplify function build <function_name>

System Info:

ubuntu 18.04

enter image description here

Does anyone understand where the problem is please?


问:
How to speed up a for loop that moves labels up?
For my project I'm making a game with moving notes up. But the movement becomes inconsistent depending on notes amount. Here is the code and I want to speed up function "Update".

```<code>from multiprocessing import Process
import time
from tkinter import *
def wait(timee):
    for i in range(int(timee*10000000)):
        time.perf_counter()
def updateNotes(songdata):
    global hp
    speed=songdata['Data']['Speed']
    tick=0
    notearriving=0.9
    toadd=1/100
    toaddtick=1/10/speed
    timetowait=1/100/speed

    steps=notearriving/toadd
    delay=steps*toaddtick
    root.update()
    tick=delay
    # for i,v in enumerate(songdata['Notes']):
    #     changed=int(songdata['Notes'][i]['Time'])*toaddtick
    #     if type(songdata['Notes'][i]['Time'])==str:
    #         songdata['Notes'][i]['Time']=str(changed)
    #     else:
    #         songdata['Notes'][i]['Time']=changed
    Get_Songs(songdata['Data']["Name"])
    while True:
        if hp <=0:
            root.destroy()
        SpawnNotes(tick-delay,songdata)
        tick+=toaddtick
        def Update(half):
            global hp
            middleIndex = math.ceil(len(notes) / 2)
            if half == 1:
                newlist=notes[0:middleIndex]
            elif half == 2:
                newlist=notes[-middleIndex:]
            else:
                newlist=notes
            for i,v in enumerate(newlist):
                note = v['note']
                currentpos=v['currentypos']#-70
                change=currentpos-toadd
                note.place(relx=v['xpos'],rely=change)
                notes[i]['currentypos']=change
                if change<1-notearriving and v['owner']=='Enemy':

                    notes.remove(v)
                    note.destroy()
                    break
                if configData['WindowSize'][1]*change+note.winfo_height()<0:
                    if v['owner']=='Player':
                        hp-=songdata['Data']['NoteDamage']
                    note.destroy()
                    notes.remove(v)
        #---code with multiprocessing------
        if len(notes)>=2:
            a=Process(target=lambda: Update(1))
            a.start()
            a.join()
            f=Process(target=lambda: Update(2))
            f.start()
            f.join()
        else:
            f=Process(target=lambda: Update(3))
            f.start()
        #---------------------------------------
        # Update(3) code without multiprocessing
        root.update()
        wait(timetowait)
</code>```

I tried Multiprocessing, but it gives me an error "EOFError: Ran out of input". Also I tried to do it with Pool, but it made even worse.

Body:
For my project I'm making a game with moving notes up. But the movement becomes inconsistent depending on notes amount. Here is the code and I want to speed up function "Update".

from multiprocessing import Process
import time
from tkinter import *
def wait(timee):
    for i in range(int(timee*10000000)):
        time.perf_counter()
def updateNotes(songdata):
    global hp
    speed=songdata['Data']['Speed']
    tick=0
    notearriving=0.9
    toadd=1/100
    toaddtick=1/10/speed
    timetowait=1/100/speed

    steps=notearriving/toadd
    delay=steps*toaddtick
    root.update()
    tick=delay
    # for i,v in enumerate(songdata['Notes']):
    #     changed=int(songdata['Notes'][i]['Time'])*toaddtick
    #     if type(songdata['Notes'][i]['Time'])==str:
    #         songdata['Notes'][i]['Time']=str(changed)
    #     else:
    #         songdata['Notes'][i]['Time']=changed
    Get_Songs(songdata['Data']["Name"])
    while True:
        if hp <=0:
            root.destroy()
        SpawnNotes(tick-delay,songdata)
        tick+=toaddtick
        def Update(half):
            global hp
            middleIndex = math.ceil(len(notes) / 2)
            if half == 1:
                newlist=notes[0:middleIndex]
            elif half == 2:
                newlist=notes[-middleIndex:]
            else:
                newlist=notes
            for i,v in enumerate(newlist):
                note = v['note']
                currentpos=v['currentypos']#-70
                change=currentpos-toadd
                note.place(relx=v['xpos'],rely=change)
                notes[i]['currentypos']=change
                if change<1-notearriving and v['owner']=='Enemy':

                    notes.remove(v)
                    note.destroy()
                    break
                if configData['WindowSize'][1]*change+note.winfo_height()<0:
                    if v['owner']=='Player':
                        hp-=songdata['Data']['NoteDamage']
                    note.destroy()
                    notes.remove(v)
        #---code with multiprocessing------
        if len(notes)>=2:
            a=Process(target=lambda: Update(1))
            a.start()
            a.join()
            f=Process(target=lambda: Update(2))
            f.start()
            f.join()
        else:
            f=Process(target=lambda: Update(3))
            f.start()
        #---------------------------------------
        # Update(3) code without multiprocessing
        root.update()
        wait(timetowait)

I tried Multiprocessing, but it gives me an error "EOFError: Ran out of input". Also I tried to do it with Pool, but it made even worse.


问:
Why would an auto conversion of LF to CRLF by Xerces result in CRCRLF?
From the Xerces documention on setNewLine, “However, Xerces-C++ always uses LF when this property is set to null since otherwise automatic translation of LF to CR-LF on Windows for text files would result in such files containing CR-CR-LF. If you need Windows-style end of line sequences in your output, consider writing to a file opened in text mode or explicitly set this property to CR-LF.” That statement makes no sense to me.

https://xerces.apache.org/xerces-c/apiDocs-3/classDOMLSSerializer.html#a56882d2fe0b4a0ecb1b3968febbcf4a3

Why an auto conversion of line endings results in a duplicate CR is beyond me.  I do not understand why that would ever be reasonable.  I have tried changing the code to explicitly set the line ending to CR-LF as described in the documentation and that does not work. I still end up with xml files that have CRCRLF as the line ending and then I have to manually remove the duplicate CR with a text editor such as notepad++.