问:
How to use an initialized php variable in some php block of code to an other block of php code?
I am trying to initialize a variable called $btn with a value, and later on use that $btn value in some other php block of code.
My code is the following (explaining right after what i want to achieve) :

<?php
    session_start();
    require '../../vendor/autoload.php';
    $m = new MongoDB\Client("mongodb://127.0.0.1/");
    $db = $m->users;
    $collection = $db->usersInfo;
    if(!isset($_SESSION['user'])){
        header('Location: ../../home/website.php');
        exit;
    }
    $btn = '';
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(isset($_POST[$btn])){
            echo $btn;
            echo "</script>alert($btn)</script>";
            $query = $db->usersInfo;
            $filter = array('_id'=>$_SESSION['user']);
            $update = array('$addToSet'=>array('ctfs'=>$btn));
            $query->updateOne($filter,$update);
        }
    }
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Cyberdemia</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">

Back

Home

Profile

Sign out

Welcome to the Reverse Engineering challenges

                    <?php
                        $db = $m->users;
                        $collection = $db->usersInfo;

                        $collectionAdmin = $db->adminInfo;
                        $query = $db->adminInfo->findOne(array('email'=>'adminMail@protonmail.com'));
                        if($query["timesLogged"] == "0"){
                            $db = $m->ctfs;
                            $collectionCtfs = $db->ctfsReverse->find();
                            foreach ($collectionCtfs as $chall){
                                $btn = $chall["challName"];
                                #echo $btn;
                                echo '

                            <form action="rev.php" method="post">
                                <button type="submit" name="'.$btn.'" value="'.$btn.'" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        '.$chall["challName"].'

                        '.$chall["difficulty"].'

';
                            }

                        }
                    ?>

```
<p>In the first php block of code i am connecting to a mongodb i am using.
In this db, there are is a collection called <strong>ctfsReverse</strong> and <strong>usersInfo</strong> .
What i am doing is giving the value of each challenge name to the variable $btn :</p>
```foreach ($collectionCtfs as $chall){
    $btn = $chall["challName"];
```
<p>Then i use this variable as an html attribute in the <em>value</em> and <em>name</em> fields :</p>
```<form action="rev.php" method="post">
    <button type="submit" name="'.$btn.'" value="'.$btn.'" class = "btn-cart"> play later list

    </button>
</form>
```
<p>So as you can see in the first block of my php code, i want to check for a post request, and if this post request was due to a button being pressed (where the buttons value is actually the $btn contents) i want to store in my db the name of the button that was pressed :</p>
```$query = $db->usersInfo;
$filter = array('_id'=>$_SESSION['user']);
$update = array('$addToSet'=>array('ctfs'=>$btn));
$query->updateOne($filter,$update);
```
<p>But the $btn variable seems to not be visible to the first php block of code. When i press the button, the $btn value does not get stored in the database.</p>
<p>How can i make the $btn globally defined?
I tried using php $GLOBALS but it didnt work.
I even tried checking for button being pressed in the second php block of code, but this didnt work either :</p>
<pre class="lang-html prettyprint-override"><code><div class = "container">
                <h1 class = "lg-title">Welcome to the Reverse Engineering challenges</h1>

                <div class = "product-items">

                    <?php
                        $db = $m->users;
                        $collection = $db->usersInfo;

                        $collectionAdmin = $db->adminInfo;
                        $query = $db->adminInfo->findOne(array('email'=>'adminMail@protonmail.com'));
                        if($query["timesLogged"] == "0"){
                            $db = $m->ctfs;
                            $collectionCtfs = $db->ctfsReverse->find();
                            foreach ($collectionCtfs as $chall){
                                $btn = $chall["challName"];
                                #echo $btn;
                                echo '<div class = "product">
                    <div class = "product-content">
                        <div class = "product-img">
                            <img src = "images/rev.png" alt = "product image">
                        </div>
                        <div class = "product-btns">
                            <form action="rev.php" method="post">
                                <button type="submit" name="'.$btn.'" value="'.$btn.'" class = "btn-cart"> play later list
                                    <span><i class = "fas fa-plus"></i></span>
                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <span><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg></span>
                            </button>
                        </div>
                    </div>

                    <div class = "product-info">
                        <div class = "product-info-top">
                            <h2 class = "sm-title">Ratings</h2>
                            <div class = "rating">
                                <span><i class = "fas fa-star"></i></span>
                                <span><i class = "fas fa-star"></i></span>
                                <span><i class = "fas fa-star"></i></span>
                                <span><i class = "fas fa-star"></i></span>
                                <span><i class = "far fa-star"></i></span>
                            </div>
                        </div>
                        <hr>
                        '.$chall["challName"].'
                        <hr>
                        '.$chall["difficulty"].'
                    </div>

                </div>';
                            }

                        }
              if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(isset($_POST[$btn])){
            echo $btn;
            echo "</script>alert($btn)</script>";
            $query = $db->usersInfo;
            $filter = array('_id'=>$_SESSION['user']);
            $update = array('$addToSet'=>array('ctfs'=>$btn));
            $query->updateOne($filter,$update);
        }
    }
                    ?>

                </div>
            </div>
        </div>
</code>```

Edit : Also, if i try to "View page source", the name and value attributes get the correct values :

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Cyberdemia</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">

Back

Home

Profile

Sign out

Welcome to the Reverse Engineering challenges

                            <form action="rev.php" method="post">
                                <button type="submit" name="rev level 1" value="rev level 1" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        rev level 1

                        difficulty - easy

                            <form action="rev.php" method="post">
                                <button type="submit" name="rev level 2" value="rev level 2" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        rev level 2

                        difficulty - medium

```

Body:
I am trying to initialize a variable called $btn with a value, and later on use that $btn value in some other php block of code.
My code is the following (explaining right after what i want to achieve) :

<?php
    session_start();
    require '../../vendor/autoload.php';
    $m = new MongoDB\Client("mongodb://127.0.0.1/");
    $db = $m->users;
    $collection = $db->usersInfo;
    if(!isset($_SESSION['user'])){
        header('Location: ../../home/website.php');
        exit;
    }
    $btn = '';
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(isset($_POST[$btn])){
            echo $btn;
            echo "</script>alert($btn)</script>";
            $query = $db->usersInfo;
            $filter = array('_id'=>$_SESSION['user']);
            $update = array('$addToSet'=>array('ctfs'=>$btn));
            $query->updateOne($filter,$update);
        }
    }
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Cyberdemia</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">

Back

Home

Profile

Sign out

Welcome to the Reverse Engineering challenges

                    <?php
                        $db = $m->users;
                        $collection = $db->usersInfo;

                        $collectionAdmin = $db->adminInfo;
                        $query = $db->adminInfo->findOne(array('email'=>'adminMail@protonmail.com'));
                        if($query["timesLogged"] == "0"){
                            $db = $m->ctfs;
                            $collectionCtfs = $db->ctfsReverse->find();
                            foreach ($collectionCtfs as $chall){
                                $btn = $chall["challName"];
                                #echo $btn;
                                echo '

                            <form action="rev.php" method="post">
                                <button type="submit" name="'.$btn.'" value="'.$btn.'" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        '.$chall["challName"].'

                        '.$chall["difficulty"].'

';
                            }

                        }
                    ?>

In the first php block of code i am connecting to a mongodb i am using.
In this db, there are is a collection called ctfsReverse and usersInfo .
What i am doing is giving the value of each challenge name to the variable $btn :

foreach ($collectionCtfs as $chall){
    $btn = $chall["challName"];

Then i use this variable as an html attribute in the value and name fields :

<form action="rev.php" method="post">
    <button type="submit" name="'.$btn.'" value="'.$btn.'" class = "btn-cart"> play later list

    </button>
</form>

So as you can see in the first block of my php code, i want to check for a post request, and if this post request was due to a button being pressed (where the buttons value is actually the $btn contents) i want to store in my db the name of the button that was pressed :

$query = $db->usersInfo;
$filter = array('_id'=>$_SESSION['user']);
$update = array('$addToSet'=>array('ctfs'=>$btn));
$query->updateOne($filter,$update);

But the $btn variable seems to not be visible to the first php block of code. When i press the button, the $btn value does not get stored in the database.

How can i make the $btn globally defined?
I tried using php $GLOBALS but it didnt work.
I even tried checking for button being pressed in the second php block of code, but this didnt work either :

Welcome to the Reverse Engineering challenges

                    <?php
                        $db = $m->users;
                        $collection = $db->usersInfo;

                        $collectionAdmin = $db->adminInfo;
                        $query = $db->adminInfo->findOne(array('email'=>'adminMail@protonmail.com'));
                        if($query["timesLogged"] == "0"){
                            $db = $m->ctfs;
                            $collectionCtfs = $db->ctfsReverse->find();
                            foreach ($collectionCtfs as $chall){
                                $btn = $chall["challName"];
                                #echo $btn;
                                echo '

                            <form action="rev.php" method="post">
                                <button type="submit" name="'.$btn.'" value="'.$btn.'" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        '.$chall["challName"].'

                        '.$chall["difficulty"].'

';
                            }

                        }
              if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(isset($_POST[$btn])){
            echo $btn;
            echo "</script>alert($btn)</script>";
            $query = $db->usersInfo;
            $filter = array('_id'=>$_SESSION['user']);
            $update = array('$addToSet'=>array('ctfs'=>$btn));
            $query->updateOne($filter,$update);
        }
    }
                    ?>

Edit : Also, if i try to "View page source", the name and value attributes get the correct values :

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Cyberdemia</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">

Back

Home

Profile

Sign out

Welcome to the Reverse Engineering challenges

                            <form action="rev.php" method="post">
                                <button type="submit" name="rev level 1" value="rev level 1" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        rev level 1

                        difficulty - easy

                            <form action="rev.php" method="post">
                                <button type="submit" name="rev level 2" value="rev level 2" class = "btn-cart"> play later list

                                </button>
                            </form>
                            <button type = "button" class = "btn-buy"> Play now
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-controller" viewBox="0 0 16 16">
                                    <path d="M11.5 6.027a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm2.5-.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm-1.5 1.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zm-6.5-3h1v1h1v1h-1v1h-1v-1h-1v-1h1v-1z"/>
                                    <path d="M3.051 3.26a.5.5 0 0 1 .354-.613l1.932-.518a.5.5 0 0 1 .62.39c.655-.079 1.35-.117 2.043-.117.72 0 1.443.041 2.12.126a.5.5 0 0 1 .622-.399l1.932.518a.5.5 0 0 1 .306.729c.14.09.266.19.373.297.408.408.78 1.05 1.095 1.772.32.733.599 1.591.805 2.466.206.875.34 1.78.364 2.606.024.816-.059 1.602-.328 2.21a1.42 1.42 0 0 1-1.445.83c-.636-.067-1.115-.394-1.513-.773-.245-.232-.496-.526-.739-.808-.126-.148-.25-.292-.368-.423-.728-.804-1.597-1.527-3.224-1.527-1.627 0-2.496.723-3.224 1.527-.119.131-.242.275-.368.423-.243.282-.494.575-.739.808-.398.38-.877.706-1.513.773a1.42 1.42 0 0 1-1.445-.83c-.27-.608-.352-1.395-.329-2.21.024-.826.16-1.73.365-2.606.206-.875.486-1.733.805-2.466.315-.722.687-1.364 1.094-1.772a2.34 2.34 0 0 1 .433-.335.504.504 0 0 1-.028-.079zm2.036.412c-.877.185-1.469.443-1.733.708-.276.276-.587.783-.885 1.465a13.748 13.748 0 0 0-.748 2.295 12.351 12.351 0 0 0-.339 2.406c-.022.755.062 1.368.243 1.776a.42.42 0 0 0 .426.24c.327-.034.61-.199.929-.502.212-.202.4-.423.615-.674.133-.156.276-.323.44-.504C4.861 9.969 5.978 9.027 8 9.027s3.139.942 3.965 1.855c.164.181.307.348.44.504.214.251.403.472.615.674.318.303.601.468.929.503a.42.42 0 0 0 .426-.241c.18-.408.265-1.02.243-1.776a12.354 12.354 0 0 0-.339-2.406 13.753 13.753 0 0 0-.748-2.295c-.298-.682-.61-1.19-.885-1.465-.264-.265-.856-.523-1.733-.708-.85-.179-1.877-.27-2.913-.27-1.036 0-2.063.091-2.913.27z"/>
                                </svg>
                            </button>

Ratings

                        rev level 2

                        difficulty - medium


来源: stackexchange

问:
How to use "ListenForWebhook" in go-telegram-bot-api with gin?
if i use the following construction, everything is OK. But this construction uses tgbotapi.Update - it doesn't really work for me. I want to use tgbotapi.UpdatesChannel via function tgbotapi.ListenForWebhook().

```<code>import (
"github.com/gin-gonic/gin"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TelegramBot struct {
    API   *tgbotapi.BotAPI
    Upd   tgbotapi.Update
    UpdCh tgbotapi.UpdatesChannel
    Log   *logger.Logger
}
func (tlg *TelegramBot) InitTg(cfg *config.Config) {

    bot, err := tgapi.NewBot(cfg.Telegram.Token)
    if err != nil {
        tlg.Log.Fatal(err)
    }

    tlg.API = bot
    router := gin.Default()
    if cfg.TelegramMode != "webhook" {
        botUpdate := tgbotapi.NewUpdate(0)
        botUpdate.Timeout = 60
        tlg.UpdCh = tlg.API.GetUpdatesChan(botUpdate)
        go tlg.Start()
    } else {
        router.POST(cfg.Telegram.Path+"*any", tlg.WebhookHandler)

    }
    go router.Run(cfg.Listen.BindIP + ":" + cfg.Listen.Port)
    //TODO fix me :)
    for {

    }
}
func (tlg *TelegramBot) WebhookHandler(c *gin.Context) {
    defer c.Request.Body.Close()

    bytes, err := ioutil.ReadAll(c.Request.Body)
    if err != nil {
        tlg.Log.Println(err)
        return
    }

    err = json.Unmarshal(bytes, &tlg.Upd)
    if err != nil {
        log.Println(err)
        return
    }
    go tlg.Start()
    c.JSON(http.StatusOK, gin.H{"data": "not you :)"})

}
func (tlg *TelegramBot) Start() {
    //TODO: for webhook
    if tlg.Upd.Message != nil {
        chatID := tlg.Upd.Message.Chat.ID

        tlg.analyzeUpdate(chatID)
    } else if tlg.Upd.CallbackQuery != nil {
        chatID := tlg.Upd.CallbackQuery.Message.Chat.ID

        tlg.analyzeUpdate(chatID)
    }

    //TODO: for polling
    for update := range tlg.UpdCh {
        if update.Message != nil {
            tlg.Upd = update
            chatID := tlg.Upd.Message.Chat.ID

            tlg.analyzeUpdate(chatID)
        } else if update.CallbackQuery != nil {
            tlg.Upd = update
            chatID := update.CallbackQuery.Message.Chat.ID

            tlg.analyzeUpdate(chatID)
        }
    }
}
</code>```

How can I do this, if possible (to get the webhook data into the tgbotapi.UpdatesChannel as in polling) :

```<code>router.POST(cfg.Telegram.Path+"*any", func(c *gin.Context) {
 tlg.UpdCh = bot.ListenForWebhook(cfg.Listen.BindIP + ":" + cfg.Listen.Port + cfg.Telegram.Path +     bot.Token)
 go tlg.Start()
 c.JSON(http.StatusOK, gin.H{"data": "not you :)"})
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
if i use the following construction, everything is OK. But this construction uses tgbotapi.Update - it doesn't really work for me. I want to use tgbotapi.UpdatesChannel via function tgbotapi.ListenForWebhook().

import (
"github.com/gin-gonic/gin"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TelegramBot struct {
    API   *tgbotapi.BotAPI
    Upd   tgbotapi.Update
    UpdCh tgbotapi.UpdatesChannel
    Log   *logger.Logger
}
func (tlg *TelegramBot) InitTg(cfg *config.Config) {

    bot, err := tgapi.NewBot(cfg.Telegram.Token)
    if err != nil {
        tlg.Log.Fatal(err)
    }

    tlg.API = bot
    router := gin.Default()
    if cfg.TelegramMode != "webhook" {
        botUpdate := tgbotapi.NewUpdate(0)
        botUpdate.Timeout = 60
        tlg.UpdCh = tlg.API.GetUpdatesChan(botUpdate)
        go tlg.Start()
    } else {
        router.POST(cfg.Telegram.Path+"*any", tlg.WebhookHandler)

    }
    go router.Run(cfg.Listen.BindIP + ":" + cfg.Listen.Port)
    //TODO fix me :)
    for {

    }
}
func (tlg *TelegramBot) WebhookHandler(c *gin.Context) {
    defer c.Request.Body.Close()

    bytes, err := ioutil.ReadAll(c.Request.Body)
    if err != nil {
        tlg.Log.Println(err)
        return
    }

    err = json.Unmarshal(bytes, &tlg.Upd)
    if err != nil {
        log.Println(err)
        return
    }
    go tlg.Start()
    c.JSON(http.StatusOK, gin.H{"data": "not you :)"})

}
func (tlg *TelegramBot) Start() {
    //TODO: for webhook
    if tlg.Upd.Message != nil {
        chatID := tlg.Upd.Message.Chat.ID

        tlg.analyzeUpdate(chatID)
    } else if tlg.Upd.CallbackQuery != nil {
        chatID := tlg.Upd.CallbackQuery.Message.Chat.ID

        tlg.analyzeUpdate(chatID)
    }

    //TODO: for polling
    for update := range tlg.UpdCh {
        if update.Message != nil {
            tlg.Upd = update
            chatID := tlg.Upd.Message.Chat.ID

            tlg.analyzeUpdate(chatID)
        } else if update.CallbackQuery != nil {
            tlg.Upd = update
            chatID := update.CallbackQuery.Message.Chat.ID

            tlg.analyzeUpdate(chatID)
        }
    }
}

How can I do this, if possible (to get the webhook data into the tgbotapi.UpdatesChannel as in polling) :

router.POST(cfg.Telegram.Path+"*any", func(c *gin.Context) {
 tlg.UpdCh = bot.ListenForWebhook(cfg.Listen.BindIP + ":" + cfg.Listen.Port + cfg.Telegram.Path +     bot.Token)
 go tlg.Start()
 c.JSON(http.StatusOK, gin.H{"data": "not you :)"})
})


问:
Multiple charts with dual y axis matplotlib
I am learning data visualization with matplotlib and I cannot find any tutorials on how to do a figure with multiple charts and each chart has dual Y axis.

I found a dozen samples on how to do each of those things separately, but not together.

Maybe I am just blind, but could anyone please point me to a tutorial that would teach how to plot multiple charts with dual Y axis on the same figure? Or maybe provide a quick sample code below?


问:
Automatically update Glue Data Catalog after writing parquet to S3 using Pyspark
Is there a way to automatically update Glue Data Catalog (without having a separate crawler) after writing parquet files to S3 from PySpark?

The awswrangler python package can do it by specifying database and table in the s3.to_parquet(). Is there an equivalent way to do it in PySpark?


问:
window.this is undefined while window.window gives window object
In the following code, why does window.this return "undefined" while window.window return window object ?</p>
```<code>let x = this.window;
let y = window.window;
let z = window.this;

console.log(x);
console.log(y);
console.log(z);
</code>```

Body:
In the following code, why does window.this return "undefined" while window.window return window object ?

let x = this.window;
let y = window.window;
let z = window.this;

console.log(x);
console.log(y);
console.log(z);


问:
Array 2d grid problem related to adjacent cell with C language
Write a code to develop a 2D grid of integers. Each of the boxes in the grid contains
an integer. You have to identify the cell whose sum of adjacent cells is maximum.
also, you have to print another 2D grid that contains the sum of adjacent cells
for each existent cell. You should take input from the user, an integer n. Then construct a nxn 2D
array/matrix. Take input from the user about the different elements of the matrix.
Then print two integers, i and j, which will be the index of the cell whose sum of
adjacent cells is maximum.

I wrote a code, but I could not print the adjacents cells grid correctly.
if n=3 and 2d grid elements are: 1 2 3
4 5 6
7 8 9
Then the output should be for adjacent cell grid: 11 19 13
25 40 27
17 31 19


问:
Where to init and how to use controllers and models in MVC pattern in Java application?
I am building desktop app and trying to use MVC pattern. I want models & controllers to be accessible in  GUI (views), but I need to init all controllers and models in the root of the app. Moreover - I need to pass all of them to my GUI init method and in all child methods.

Is there any simple way to init and call models and controllers in views components? I am currently have 7 models and 7 controllers, but what if in the future there will be more, should I hardcode them, is it ok?

I am actually WEB developer, so I can show as an example Javascript implementations for storage usages. There is frameworks for convinient storage usage for the entire app - React(Redux) Vue(Vuex). They are registered as plugins and accessible in all app, maybe there is something same in java for mvc

```<code>    import com.base.views.MainWindow;
    import com.base.models.ActionsModel;
    // models...
    import com.base.controllers.ActionsController;
    // controllers...

    public class Main {
        ActionsModel actionsModel = new ActionsModel();
        // models...
        ActionsController actionsController= new ActionsController();
        // controllers...

        public static void main(String[] args) {
            MainWindow viewMainWindow = new MainWindow();
            viewMainWindow.init(actionsModel, actionsController, ....); // I want to use models and controllers in MainWindow (GUI)
        }

    }
</code>```

Body:
I am building desktop app and trying to use MVC pattern. I want models & controllers to be accessible in  GUI (views), but I need to init all controllers and models in the root of the app. Moreover - I need to pass all of them to my GUI init method and in all child methods.

Is there any simple way to init and call models and controllers in views components? I am currently have 7 models and 7 controllers, but what if in the future there will be more, should I hardcode them, is it ok?

I am actually WEB developer, so I can show as an example Javascript implementations for storage usages. There is frameworks for convinient storage usage for the entire app - React(Redux) Vue(Vuex). They are registered as plugins and accessible in all app, maybe there is something same in java for mvc

    import com.base.views.MainWindow;
    import com.base.models.ActionsModel;
    // models...
    import com.base.controllers.ActionsController;
    // controllers...

    public class Main {
        ActionsModel actionsModel = new ActionsModel();
        // models...
        ActionsController actionsController= new ActionsController();
        // controllers...

        public static void main(String[] args) {
            MainWindow viewMainWindow = new MainWindow();
            viewMainWindow.init(actionsModel, actionsController, ....); // I want to use models and controllers in MainWindow (GUI)
        }

    }


问:
How can i add JSON diff in Allure report?
I have a testCase in cypress framework , in which i am comparing two JSONs

I have added a expect with deap.equal for comparing the diff with [] (empty array)

this is working as expected , but i want the diff(if not equal to []) to be visible as JSON array in Allure report not like a stringify JSON.

Is there a way i can do so?

I was looking for the feature in Allure docs but couldn't find any.


问:
Getting error while deploying in weblogic 14 for log4j library
Source Code :

```<code>@Controller
public class HomeController {

    private  static final Logger log = LogManager.getLogger();
    @GetMapping("/hello")
    public @ResponseBody String getHello()
    {

        DemoClass cls = new DemoClass();
        cls.helloworld();

        log.info("INFO =====================");
        return "Hello2";
    }

}
</code>```

The culprit in above code is "LogManager.getLogger()".
The above code is working perfectly fine on apache tomcat.

The stacktrace is as follows :
Java 11 is used.
Weblogic 14 is used.
log4j version : 2.19.0

```<code>Caused By: java.lang.UnsupportedOperationException: No class provided, and an appropriate one cannot be found.
    at org.apache.logging.log4j.LogManager.callerClass(LogManager.java:573)
    at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:598)
    at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:585)
    at com.example.demo.controller.HomeController.<clinit>(HomeController.java:12)
</code>```

Body:
Source Code :

@Controller
public class HomeController {

    private  static final Logger log = LogManager.getLogger();
    @GetMapping("/hello")
    public @ResponseBody String getHello()
    {

        DemoClass cls = new DemoClass();
        cls.helloworld();

        log.info("INFO =====================");
        return "Hello2";
    }

}

The culprit in above code is "LogManager.getLogger()".
The above code is working perfectly fine on apache tomcat.

The stacktrace is as follows :
Java 11 is used.
Weblogic 14 is used.
log4j version : 2.19.0

Caused By: java.lang.UnsupportedOperationException: No class provided, and an appropriate one cannot be found.
    at org.apache.logging.log4j.LogManager.callerClass(LogManager.java:573)
    at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:598)
    at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:585)
    at com.example.demo.controller.HomeController.<clinit>(HomeController.java:12)


问:
XGBoost Survival Model
I'm trying to develop an XGBoost Survival model. Here is a quick snap of my code:

```<code>X = df_High_School[['Gender', 'Lived_both_Parents', 'Moth_Born_in_Canada', 'Father_Born_in_Canada','Born_in_Canada','Aboriginal','Visible_Minority']]  # covariates
y = df_High_School[['time_to_event', 'event']]  # time to event and event indicator

#split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

#Develop the model
model = xgb.XGBRegressor(objective='survival:cox')
</code>```

It's giving me the following error:

ValueError                                Traceback (most recent call last)
 in
18
19 # fit the model to the training data
---> 20 model.fit(X_train, y_train)
21
22 # make predictions on the test set

2 frames
/usr/local/lib/python3.8/dist-packages/xgboost/core.py in _maybe_pandas_label(label)
261     if isinstance(label, DataFrame):
262         if len(label.columns) > 1:
--> 263             raise ValueError('DataFrame for label cannot have multiple columns')
264
265         label_dtypes = label.dtypes

ValueError: DataFrame for label cannot have multiple columns

As this is a survival model, I need two columns t indicate the event and the time_to_event. I also tried converting the Dataframes to Numpy but it didn't work too.

Any clue? Thanks!

Title: XGBoost Survival Model

Body:
I'm trying to develop an XGBoost Survival model. Here is a quick snap of my code:

X = df_High_School[['Gender', 'Lived_both_Parents', 'Moth_Born_in_Canada', 'Father_Born_in_Canada','Born_in_Canada','Aboriginal','Visible_Minority']]  # covariates
y = df_High_School[['time_to_event', 'event']]  # time to event and event indicator

#split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

#Develop the model
model = xgb.XGBRegressor(objective='survival:cox')

It's giving me the following error:

ValueError                                Traceback (most recent call last)
 in
18
19 # fit the model to the training data
---> 20 model.fit(X_train, y_train)
21
22 # make predictions on the test set

2 frames
/usr/local/lib/python3.8/dist-packages/xgboost/core.py in _maybe_pandas_label(label)
261     if isinstance(label, DataFrame):
262         if len(label.columns) > 1:
--> 263             raise ValueError('DataFrame for label cannot have multiple columns')
264
265         label_dtypes = label.dtypes

ValueError: DataFrame for label cannot have multiple columns

As this is a survival model, I need two columns t indicate the event and the time_to_event. I also tried converting the Dataframes to Numpy but it didn't work too.

Any clue? Thanks!


问:
Dynamic Creation/Update form (A component is changing an uncontrolled input to be controlled)
I have a dyamic form for submitting data and im am currently having an issue trying to understand how to work around certain values not being required. I have a component called create and it passes down some blank(dummy) data down as a prop for my ItemForm component. The ItemForm component has input onChange effects that assign or update values to my state however when I try updating my state to add a new key value pair I get the (A component is changing an uncontrolled input to be controlled) error from react.

(What I've tried)

So then I tried assigning my dummy data all of the possible properties with no data and tried assigning values like null or undefined and still ge tthe error. My only solutions so far have beem 0 or an empty string however the issue I have with that now is giving I cant use 0 because then it will create columns with values of 0 in them, and I cant use strings because it will give me a database error. My thought process now is before making an api call with my data, check if a input that is not required is empty and remove it from the object before making the api request on form submittion? I feel like typescript has a workound for this just by using types and putting ? at the end of the property name but im using javascript.

I believe what I theorized would work however it feels like a workaround rather than a solution the the problem.

```<code>import ItemForm from "./ItemForm.js";
import * as itemApi from "../../../api/item.js";

export default function CreateItem() {
  const handleSubmit = async (e, data) => {
    e.preventDefault();
    const res = await itemApi.create(data);
    return res;
  };

  const item = {
    name: "",
    cost: "",
    rarity: "",
    critRate: ""
  };

  return <ItemForm {...{ type: "Create", handleSubmit, item }} />;
}
</code>```
```<code>export default function ItemForm({ type, item, handleSubmit, fetch }) {
  const [data, setData] = useState(item);
  const [error, setError] = useState("");
  const [isLoading, setLoading] = useState(false);
  const navigate = useNavigate();

  console.log(data);
  return (
    <>
      <h1>Item Form</h1>
      <Box
        component="form"
        onSubmit={async (e) => {
          setLoading(true);

          const res = await handleSubmit(e, data);

          if (res.error) {
            setError(res.error);
          }

          if (res.result && res.status === 200) {
            navigate("/items");
          }

          setLoading(false);
        }}
      >
        <TextField
          value={data?.name}
          onChange={(event) => setData({ ...data, name: event.target.value })}
          margin="normal"
          required
          name="name"
          label="Item Name"
          id="name"
        />
        {/* submits negative numbers */}
        <TextField
          value={data?.cost}
          onChange={(event) => setData({ ...data, cost: event.target.value })}
          type="number"
          required
          name="cost"
          label="Cost"
          id="cost"
        />
        <TextField
          value={data?.rarity}
          onChange={(event) => setData({ ...data, rarity: event.target.value })}
          required
          name="rarity"
          label="Rarity"
          id="rarity"
        />
        <TextField
          value={data?.critRate}
          onChange={(event) =>
            setData({ ...data, critRate: event.target.value })
          }
          type="number"
          name="critRate"
          label="Critical Rate"
          id="critRate"
        />
        <Button type="submit" variant="contained">
          {isLoading ? "isLoading..." : type}
        </Button>
      </Box>
      {error && <h2>{error}</h2>}
    </>
  );
}
</code>```

Body:
I have a dyamic form for submitting data and im am currently having an issue trying to understand how to work around certain values not being required. I have a component called create and it passes down some blank(dummy) data down as a prop for my ItemForm component. The ItemForm component has input onChange effects that assign or update values to my state however when I try updating my state to add a new key value pair I get the (A component is changing an uncontrolled input to be controlled) error from react.

(What I've tried)

So then I tried assigning my dummy data all of the possible properties with no data and tried assigning values like null or undefined and still ge tthe error. My only solutions so far have beem 0 or an empty string however the issue I have with that now is giving I cant use 0 because then it will create columns with values of 0 in them, and I cant use strings because it will give me a database error. My thought process now is before making an api call with my data, check if a input that is not required is empty and remove it from the object before making the api request on form submittion? I feel like typescript has a workound for this just by using types and putting ? at the end of the property name but im using javascript.

I believe what I theorized would work however it feels like a workaround rather than a solution the the problem.

import ItemForm from "./ItemForm.js";
import * as itemApi from "../../../api/item.js";

export default function CreateItem() {
  const handleSubmit = async (e, data) => {
    e.preventDefault();
    const res = await itemApi.create(data);
    return res;
  };

  const item = {
    name: "",
    cost: "",
    rarity: "",
    critRate: ""
  };

  return <ItemForm {...{ type: "Create", handleSubmit, item }} />;
}

export default function ItemForm({ type, item, handleSubmit, fetch }) {
  const [data, setData] = useState(item);
  const [error, setError] = useState("");
  const [isLoading, setLoading] = useState(false);
  const navigate = useNavigate();

  console.log(data);
  return (
    <>

Item Form

      <Box
        component="form"
        onSubmit={async (e) => {
          setLoading(true);

          const res = await handleSubmit(e, data);

          if (res.error) {
            setError(res.error);
          }

          if (res.result && res.status === 200) {
            navigate("/items");
          }

          setLoading(false);
        }}
      >
        <TextField
          value={data?.name}
          onChange={(event) => setData({ ...data, name: event.target.value })}
          margin="normal"
          required
          name="name"
          label="Item Name"
          id="name"
        />
        {/* submits negative numbers */}
        <TextField
          value={data?.cost}
          onChange={(event) => setData({ ...data, cost: event.target.value })}
          type="number"
          required
          name="cost"
          label="Cost"
          id="cost"
        />
        <TextField
          value={data?.rarity}
          onChange={(event) => setData({ ...data, rarity: event.target.value })}
          required
          name="rarity"
          label="Rarity"
          id="rarity"
        />
        <TextField
          value={data?.critRate}
          onChange={(event) =>
            setData({ ...data, critRate: event.target.value })
          }
          type="number"
          name="critRate"
          label="Critical Rate"
          id="critRate"
        />
        <Button type="submit" variant="contained">
          {isLoading ? "isLoading..." : type}
        </Button>
      </Box>
      {error &&
{error}
}
    </>
  );
}


问:
CMake "Detecting CXX compiler ABI info - failed"
CMake Output:

```<code>-- The CXX compiler identification is GNU 11.2.1
-- The C compiler identification is GNU 11.2.1
-- The ASM compiler identification is GNU
-- Found assembler: /home/bob/gcc-arm-10.2-2020.11-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - failed
</code>```

What does "Detecting CXX compiler ABI info - failed" mean - what is the cause of this error, and how is it fixed?

Body:
CMake Output:

-- The CXX compiler identification is GNU 11.2.1
-- The C compiler identification is GNU 11.2.1
-- The ASM compiler identification is GNU
-- Found assembler: /home/bob/gcc-arm-10.2-2020.11-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - failed

What does "Detecting CXX compiler ABI info - failed" mean - what is the cause of this error, and how is it fixed?


问:
How to programmatically find an image's id from its name in Roblox?
I would like to get the image id for the images I have imported in to my game based on their names (e. g. image/foo). I was wondering whether there was a way to programmatically get the image's ids. I know I could manually do this, but this is massively inefficient seeing as I have over 100 images that I need to get the ids of (and I will need to do many more in the future).

I was hoping there would be some kind of method to return the id, like getAssetIdFromName("image/foo") but it doesn't seem like there is. Is there any other way to do this?


问:
I am having an issue with this code it keeps spitting out the same error
java -cp /tmp/NmkWULoGu6 Main
Enter student name: mohammed

Enter

grade1: 2

grade2: 5

grade3: 4

```<code>Exception in thread "main" java.util.InputMismatchExceptionat java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:8)
</code>```

The error is above  I have been trying to fix the code for an hour and couldn't fix it is it wrong ?

The Code is below

```<code>import java.util.Scanner;

public class Main{

    public static void main(String args[]){

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter student name: ");

        String name = scan.next();

        System.out.print("Enter \ngrade1: \ngrade2: \ngrade3: ");

        double grade1 = scan.nextDouble();

        double grade2 = scan.nextDouble();

        double grade3 = scan.nextDouble();

                double average = ((grade1 * 0.25) + (grade2 * 0.25) + (grade3 * 0.50));

        System.out.println(name + ", Your average is " + average);

        }
   }
</code>```

Body:
java -cp /tmp/NmkWULoGu6 Main
Enter student name: mohammed

Enter

grade1: 2

grade2: 5

grade3: 4

Exception in thread "main" java.util.InputMismatchExceptionat java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:8)

The error is above  I have been trying to fix the code for an hour and couldn't fix it is it wrong ?

The Code is below

import java.util.Scanner;

public class Main{

    public static void main(String args[]){

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter student name: ");

        String name = scan.next();

        System.out.print("Enter \ngrade1: \ngrade2: \ngrade3: ");

        double grade1 = scan.nextDouble();

        double grade2 = scan.nextDouble();

        double grade3 = scan.nextDouble();

                double average = ((grade1 * 0.25) + (grade2 * 0.25) + (grade3 * 0.50));

        System.out.println(name + ", Your average is " + average);

        }
   }


问:
.NET 7 (core) - AKS, Application Insights and GCDump memory not adding up
I have a .NET 7 API deployed on AKS instrumented via Application Insights SDK. Others instances of the same API on the same AKS are using an avg of ~200MB, this one is not that light.

This fact points me to a memory leak triggered by some behavior or race condition.

The problem here is:

Application Insights reports that the application is using ~500 MB of memory

AKS reports that the pod is using ~750mb

dotnet-gcdump reports 21MB total

dotnet-dump top 3 largest pools are 21MB (3214 instances of free memory - fragmentation), 16MB (8099 instances of byte[]) and 7MB (40k+ instances of strings). It also reports that the 6th largest object is about 750kb and the 21st is smaller than 100kb...

now... how can I "conciliate" all this info? who is telling the truth?

Extra Info:

This memory hike happened a couple of days ago. For about 4 days everything was OK, suddenly the overall memory spiked to 1.3GB and about 1 minute later it was reclaimed back to 500MB. check it out:


问:
KMeans Clustering - Getting "malloc" error
I'm trying to run kmeans clustering on a dataset with ~120,000 datapoints but I am getting a 'malloc' error:

```<code>python3(2830,0x70000d545000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000e54b000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000dd48000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000ed4e000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000d545000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000dd48000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000e54b000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000ed4e000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000f551000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000f551000) malloc: *** set a breakpoint in malloc_error_break to debug
[1]    2830 abort      python3 kmeans.py
</code>```

The data is in an ndarray formatters as such:

```<code>[[2.06e+01 1.03e+00]
 [2.06e+01 1.70e-01]
 [2.06e+01 1.03e+00]
 ...
 [2.42e+01 2.30e-01]
 [2.36e+01 1.00e-02]
 [2.41e+01 1.40e-01]]
</code>```

I've ran various supervised models on the same dataset without any issue. My code here:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

df = pd.read_csv('data/final_dataset.csv')

df = df[df['Episode_Count'].notna()]

#create X coords
X = df[['BMI','Episode_Count']].values

plt.scatter(X[:,0],X[:,1])
plt.show()

#train model
k = 5
kmeans = KMeans(n_clusters=k, random_state=42)
y_pred = kmeans.fit_predict(X)
print(y_pred)
```

I know this is not reproducible but that is difficult with such a large dataset. I'm happy to find a way to share training data if that would help.

Has anybody ran into this issue before??

Body:
I'm trying to run kmeans clustering on a dataset with ~120,000 datapoints but I am getting a 'malloc' error:

python3(2830,0x70000d545000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000e54b000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000dd48000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000ed4e000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000d545000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000dd48000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000e54b000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000ed4e000) malloc: *** set a breakpoint in malloc_error_break to debug
python3(2830,0x70000f551000) malloc: *** error for object 0xc0: pointer being freed was not allocated
python3(2830,0x70000f551000) malloc: *** set a breakpoint in malloc_error_break to debug
[1]    2830 abort      python3 kmeans.py

The data is in an ndarray formatters as such:

[[2.06e+01 1.03e+00]
 [2.06e+01 1.70e-01]
 [2.06e+01 1.03e+00]
 ...
 [2.42e+01 2.30e-01]
 [2.36e+01 1.00e-02]
 [2.41e+01 1.40e-01]]

I've ran various supervised models on the same dataset without any issue. My code here:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

df = pd.read_csv('data/final_dataset.csv')

df = df[df['Episode_Count'].notna()]

#create X coords
X = df[['BMI','Episode_Count']].values

plt.scatter(X[:,0],X[:,1])
plt.show()

#train model
k = 5
kmeans = KMeans(n_clusters=k, random_state=42)
y_pred = kmeans.fit_predict(X)
print(y_pred)

I know this is not reproducible but that is difficult with such a large dataset. I'm happy to find a way to share training data if that would help.

Has anybody ran into this issue before??


问:
Northwind database - find max sale for each employee
In the Northwind database, how can I display the order ID that is the most expensive for each employee? (without displaying the amount)

With this query, I was able to get the results:

```<code>select orderid, EmployeeID, concat(FirstName, ' ',LastName)
from OrderDetails join orders o1 using (OrderID)
join Employees using (EmployeeID)
group by orderid
having sum(quantity*unitprice*(1-discount)) =
  (select sum(quantity*unitprice*(1-discount))
   from OrderDetails join orders o2 using (OrderID)
   where o2.EmployeeID=o1.EmployeeID
   group by orderid
   order by sum(quantity*unitprice*(1-discount))
   desc limit 1 )
</code>```

but im looking for a way to do so without using limit 1

Body:
In the Northwind database, how can I display the order ID that is the most expensive for each employee? (without displaying the amount)

With this query, I was able to get the results:

select orderid, EmployeeID, concat(FirstName, ' ',LastName)
from OrderDetails join orders o1 using (OrderID)
join Employees using (EmployeeID)
group by orderid
having sum(quantity*unitprice*(1-discount)) =
  (select sum(quantity*unitprice*(1-discount))
   from OrderDetails join orders o2 using (OrderID)
   where o2.EmployeeID=o1.EmployeeID
   group by orderid
   order by sum(quantity*unitprice*(1-discount))
   desc limit 1 )

but im looking for a way to do so without using limit 1


问:
Extracting text from STEP files
I have a number of STEP files with text embedded in them, which I need to extract. Unfortunately, text in STEP files doesn't come in the form of characters, but in the form of curves, vertexes, splines, etc. making it very difficult to identify in the file. This project is in Python.

My current idea to do this is to build a library of letters, numbers, and punctuation, basically a series of ~40 tiny STEP files that contain a single character. In order to identify and extract text, the structure in the library STEPs will be compared to the main STEP, and anything matching the library template will be identified as its corresponding character; all the characters in the STEP files have the same "font", so to speak, so this should be viable for now.

I know this isn't a very good solution, but it's the best I've been able to come up with after a couple weeks of research. The first step is, of course, compiling the library, for which I am trying to using PythonOCC to "clip out" the characters. Unfortunately, I'm having some difficulty understanding its documentation, and I'm not terribly familiar with OCC in general, so I've been having trouble figuring out how to clip out the bits of STEP file code that represent a given character.

I know the coordinates of a given character thanks to FreeCAD, and with it I've been able to identify the "location" of a given character in the TopExp_Explorer crawler. I am having trouble figuring out how to extract anything, though:

```<code>def getShape(file_path: str):
    shape = read_step_file(file_path)
    return shape

def print_vertex(va):
    return BRep_Tool().Pnt(va).Coord(1), BRep_Tool().Pnt(va).Coord(2), BRep_Tool().Pnt(va).Coord(3)

file_path = r'<path>'
myshape = getShape(file_path)

topExp = TopExp_Explorer()
topExp.Init(myshape, TopAbs_EDGE)

x = (5948,5960); y = (330,344) #D
while topExp.More():
    edge = topExp.Current()
    first = print_vertex(topexp_FirstVertex(edge))
    last = print_vertex(topexp_LastVertex(edge))
    if (x[0] < first[0] < x[1]) & (y[0] < first[1] < y[1]) & \
       (x[0] < last[0] < x[1]) & (y[0] < last[1] < y[1]):
        #*Something should happen here*
    topExp.Next()
</code>```

The characters appear to be comprised of edges and points -- for example, the "D" I have given coordinates for is made of a single vertex and a single edge that forms the whole "D" shape -- so in theory there should not be many objects to extract for any given character. The problem is I need not just a PythonOCC edge object, but a STEP file object, like a particular structure of VERTEX_POINTs and EDGE_LOOPs, to compile a character library and compare it to any given STEP file.

Does anyone know what should go in the IF statement? Alternatively, does anyone know a better way to go about this? Preferably something that can pull text from a STEP file directly . . .

Title: Extracting text from STEP files

Body:
I have a number of STEP files with text embedded in them, which I need to extract. Unfortunately, text in STEP files doesn't come in the form of characters, but in the form of curves, vertexes, splines, etc. making it very difficult to identify in the file. This project is in Python.

My current idea to do this is to build a library of letters, numbers, and punctuation, basically a series of ~40 tiny STEP files that contain a single character. In order to identify and extract text, the structure in the library STEPs will be compared to the main STEP, and anything matching the library template will be identified as its corresponding character; all the characters in the STEP files have the same "font", so to speak, so this should be viable for now.

I know this isn't a very good solution, but it's the best I've been able to come up with after a couple weeks of research. The first step is, of course, compiling the library, for which I am trying to using PythonOCC to "clip out" the characters. Unfortunately, I'm having some difficulty understanding its documentation, and I'm not terribly familiar with OCC in general, so I've been having trouble figuring out how to clip out the bits of STEP file code that represent a given character.

I know the coordinates of a given character thanks to FreeCAD, and with it I've been able to identify the "location" of a given character in the TopExp_Explorer crawler. I am having trouble figuring out how to extract anything, though:

def getShape(file_path: str):
    shape = read_step_file(file_path)
    return shape

def print_vertex(va):
    return BRep_Tool().Pnt(va).Coord(1), BRep_Tool().Pnt(va).Coord(2), BRep_Tool().Pnt(va).Coord(3)

file_path = r'<path>'
myshape = getShape(file_path)

topExp = TopExp_Explorer()
topExp.Init(myshape, TopAbs_EDGE)

x = (5948,5960); y = (330,344) #D
while topExp.More():
    edge = topExp.Current()
    first = print_vertex(topexp_FirstVertex(edge))
    last = print_vertex(topexp_LastVertex(edge))
    if (x[0] < first[0] < x[1]) & (y[0] < first[1] < y[1]) & \
       (x[0] < last[0] < x[1]) & (y[0] < last[1] < y[1]):
        #*Something should happen here*
    topExp.Next()

The characters appear to be comprised of edges and points -- for example, the "D" I have given coordinates for is made of a single vertex and a single edge that forms the whole "D" shape -- so in theory there should not be many objects to extract for any given character. The problem is I need not just a PythonOCC edge object, but a STEP file object, like a particular structure of VERTEX_POINTs and EDGE_LOOPs, to compile a character library and compare it to any given STEP file.

Does anyone know what should go in the IF statement? Alternatively, does anyone know a better way to go about this? Preferably something that can pull text from a STEP file directly . . .


问:
Nginx with RTMP module: ""location" directive is not allowed here"
I'm trying to set up a streaming server with nginx and the RTMP module on an ec2 instance... for development purpose I need to add this directive: add_header Access-Control-Allow-Origin *;, so that I can integrate my stream in a website on a local environment.

But I get this error when restarting Nginx: "location" directive is not allowed here

Here is my nginx configuration file, inspired by the documentation :

`

```<code>rtmp {
    server {

        listen 1935;

        chunk_size 4000;

        # HLS

        # For HLS to work please create a directory in tmpfs (/tmp/hls here)
        # for the fragments. The directory contents is served via HTTP (see
        # http{} section in config)
        #
        # Incoming stream must be in H264/AAC. For iPhones use baseline H264
        # profile (see ffmpeg example).
        # This example creates RTMP stream from movie ready for HLS:
        #
        # ffmpeg -loglevel verbose -re -i movie.avi  -vcodec libx264
        #    -vprofile baseline -acodec libmp3lame -ar 44100 -ac 1
        #    -f flv rtmp://localhost:1935/hls/movie
        #
        # If you need to transcode live stream use 'exec' feature.
        #
        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
        }
    }
}

http {
    server {

        listen      8080;

        location /hls {
            # Serve HLS fragments
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            root /tmp;
            add_header Cache-Control no-cache;
            # To avoid issues with cross-domain HTTP requests (e.g. during development)
            add_header Access-Control-Allow-Origin *;
        }
    }
}
</code>```

I tried moving the location part in different places but I always get the same error... If I understood well the location directive should be in server, which must be in http

If anyone has an idea about what I'm doing wrong, thank you in advance :)

Body:
I'm trying to set up a streaming server with nginx and the RTMP module on an ec2 instance... for development purpose I need to add this directive: add_header Access-Control-Allow-Origin *;, so that I can integrate my stream in a website on a local environment.

But I get this error when restarting Nginx: "location" directive is not allowed here

Here is my nginx configuration file, inspired by the documentation :

`

rtmp {
    server {

        listen 1935;

        chunk_size 4000;

        # HLS

        # For HLS to work please create a directory in tmpfs (/tmp/hls here)
        # for the fragments. The directory contents is served via HTTP (see
        # http{} section in config)
        #
        # Incoming stream must be in H264/AAC. For iPhones use baseline H264
        # profile (see ffmpeg example).
        # This example creates RTMP stream from movie ready for HLS:
        #
        # ffmpeg -loglevel verbose -re -i movie.avi  -vcodec libx264
        #    -vprofile baseline -acodec libmp3lame -ar 44100 -ac 1
        #    -f flv rtmp://localhost:1935/hls/movie
        #
        # If you need to transcode live stream use 'exec' feature.
        #
        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
        }
    }
}

http {
    server {

        listen      8080;

        location /hls {
            # Serve HLS fragments
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            root /tmp;
            add_header Cache-Control no-cache;
            # To avoid issues with cross-domain HTTP requests (e.g. during development)
            add_header Access-Control-Allow-Origin *;
        }
    }
}

I tried moving the location part in different places but I always get the same error... If I understood well the location directive should be in server, which must be in http

If anyone has an idea about what I'm doing wrong, thank you in advance :)