问:
Cannot disable "white-space: nowrap;" on html div
On my website app, I have a logger window. In that window, I have table rows with divs inside.

I was able to crop long sentences for users. What I want is, when one hovers an item, it will show all sentences of that item.

It actually works for the last item. But why it does not work for the first item?

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
  overflow: visible;
  white-space: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.
        </div>
      </td>
    </tr>
  </tbody>
</table></code>```

答:
You have to fix the layout of your table, otherwise it will grow with its content. You can see the documentation for table-layout.

In the example below, I'm using the fixed layout with a full width to demonstrate how it works.

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
  overflow: visible;
  white-space: normal;
}
table {
  width: 100%;
  table-layout: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.
        </div>
      </td>
    </tr>
  </tbody>
</table></code>```

Body:
On my website app, I have a logger window. In that window, I have table rows with divs inside.

I was able to crop long sentences for users. What I want is, when one hovers an item, it will show all sentences of that item.

It actually works for the last item. But why it does not work for the first item?

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
  overflow: visible;
  white-space: normal;
}

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.

- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.

Body:
You have to fix the layout of your table, otherwise it will grow with its content. You can see the documentation for table-layout.

In the example below, I'm using the fixed layout with a full width to demonstrate how it works.

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
  overflow: visible;
  white-space: normal;
}
table {
  width: 100%;
  table-layout: fixed;
}

<table>
  <tbody>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.
        </div>
      </td>
    </tr>
  </tbody>
</table>


来源: stackexchange

问:
how to remove the "User-Agent" header when send request in python
I'm using python requests library, I need send a request without a user-agent header.
I found this question, but it's for Urllib2.

I'm trying to simulate an Android app which does this when calling a private API.

I try to set User-Agent to None as in the following code, but it doesn't work. It still sends User-Agent: python-requests/2.27.1.

Is there any way?

```<code>headers = requests.utils.default_headers()
headers['User-Agent'] = None
requests.post(url, *args, headers=headers, **kwargs)
</code>```

答:
For urllib3 >= 1.26.0 (aka, requests >= 2.25.0), you can make use of urllib3.util.SKIP_HEADER to suppress User-Agent, Accept-Encoding and Host header. See https://github.com/psf/requests/issues/5671#issuecomment-1006735307 for an example and https://github.com/urllib3/urllib3/pull/2018 for upstream changes.

PS: You may want to use urllib3 >= 1.26.3 to avoid a minor issue spamming connection.py: BytesWarning: Comparison between bytes and string. See https://github.com/urllib3/urllib3/issues/2071.

ContentLicense: CC BY-SA 4.0

Body:
I'm using python requests library, I need send a request without a user-agent header.
I found this question, but it's for Urllib2.

I'm trying to simulate an Android app which does this when calling a private API.

I try to set User-Agent to None as in the following code, but it doesn't work. It still sends User-Agent: python-requests/2.27.1.

Is there any way?

headers = requests.utils.default_headers()
headers['User-Agent'] = None
requests.post(url, *args, headers=headers, **kwargs)


问:
How to cumsum the elements of a vector under certain condition in R?
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

```<code>vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)
</code>```

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

```<code>vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)
</code>```

How can I achieve this?

答:
Using ave:

ave(vector_A, data.table::rleid(sign(A)), FUN = cumsum)
#  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
```
<hr />
<p>A formula version of <code>accumulate</code>:</p>
<pre class="lang-r prettyprint-override"><code>purrr::accumulate(vector_A, ~ ifelse(sign(.x) == sign(.y), .x + .y, .y))
#  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
</code>```

Body:
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)

How can I achieve this?

Body:
Using ave:

ave(vector_A, data.table::rleid(sign(A)), FUN = cumsum)
#  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1

A formula version of accumulate:

purrr::accumulate(vector_A, ~ ifelse(sign(.x) == sign(.y), .x + .y, .y))
#  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1


问:
Navbar disappears after scrollIntoView() use on mobile view
Problem: NavBar disappears after scrollIntoView() used on mobile view.

Related JS

```<code>function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

function scroll_to_chapters() {
    const chapters = document.getElementsByClassName("chapter_list")[0];
    if (nav.classList.contains("nav-active")) {
        navLinks.forEach((link) => {
            if (link.style.animation) {
                link.style.animation = '';
            }
        });
        enableScroll();
        burger.classList.toggle('toggle');
        nav.classList.toggle('nav-active');
    }
    chapters.scrollIntoView({ block: 'start',  behavior: 'smooth' })
}

const navSlide = ()=> {
    burger.addEventListener('click', ()=> {
        //Toggle NavBar
        nav.classList.toggle('nav-active');
        //Animate Links
        navLinks.forEach((link, index)=> {
            if (link.style.animation) {
                enableScroll();
                link.style.animation = '';
            }
            else {
                disableScroll();
                link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
            }
        });
        burger.classList.toggle('toggle');
    });
}
</code>```

I'm not quite sure but there might be a problem with the disabling and enabling scrolling. I didn't want mobile users to be able to scroll while the navbar menus are opened.

Navbar HTML

```<code><div class="wrapper">
    <div class="fix">
        <header>
            <div class="container">
                <nav>
                <a href="/" data-attr="img"><img src="{% static 'img/northernlogo.png' %}" class="logo" alt="logo"></a>
                <ul class="nav-links">
                    <li><a href="/">Home</a></li>
                    <li><a href="/" onclick="scroll_to_chapters();return false;">Chapters</a></li>
                    <li><a href="/about">About</a></li>
                    <li><a href="/links">Links</a></li>
                </ul>
                <div class="burger">
                    <div class="line1"></div>
                    <div class="line2"></div>
                    <div class="line3"></div>
                </div>
                </nav>
            </div>
        </header>
    </div>
</div>
</code>```

Related CSS

```<code>.container {
    width: 100%;
    margin: 0 0;
}

.container::after {
    content: '';
    display: grid;
    clear: both;
}

.burger {
    display: none;
    margin-top: 20px;
    cursor: pointer;
}

.burger div {
    width: 25px;
    height: 3px;
    background: #EEEEEE;
    margin: 5px;
    transition: all 0.3s ease;
}

@media only screen and (max-width: 800px) {
    .wrapper {
        overflow: hidden;
        position: relative;
    }
    .nav-links {
        -webkit-box-shadow: inset 0 0.5em 1.5em -0.5em black;
        position: absolute;
        right: 0;
        height: 100%;
        top: 70px;
        background-color: #3a345c;
        z-index: 99;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        transform: translateX(100%);
        transition: transform 0.5s ease-in;
    }
    .nav-links li {
        opacity: 0;
        padding-bottom: 50px;
        padding-top: 50px;
    }

    .nav-links li a {
        font-size: 20px;
        font-weight: bold;
    }

    .burger {
        display: block;
    }
}
</code>```

Picture of the Error

Before
After

How to Reproduce

Open the website on mobile view. Open the navbar from the home menu and click chapters. It'll take you to the chapters but now the navbar is gone.

Editor's note:

The accepted answer features a self-contained reproducible example.

答:
You have to fix you navbar using "position: fixed" property. Add & Modify given CSS

Here is the result

```<code>@media only screen and (max-width: 800px) {

    /*ADD This*/
    .fix {
        position: fixed;
        width: 100%;
        z-index: 1;
    }

    /*modify this*/
    .nav-links {
        height: 100vh;
    }
    .content {
        margin-top: 90px;
    }
}
</code>```

Body:
Problem: NavBar disappears after scrollIntoView() used on mobile view.

Related JS

function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

function scroll_to_chapters() {
    const chapters = document.getElementsByClassName("chapter_list")[0];
    if (nav.classList.contains("nav-active")) {
        navLinks.forEach((link) => {
            if (link.style.animation) {
                link.style.animation = '';
            }
        });
        enableScroll();
        burger.classList.toggle('toggle');
        nav.classList.toggle('nav-active');
    }
    chapters.scrollIntoView({ block: 'start',  behavior: 'smooth' })
}

const navSlide = ()=> {
    burger.addEventListener('click', ()=> {
        //Toggle NavBar
        nav.classList.toggle('nav-active');
        //Animate Links
        navLinks.forEach((link, index)=> {
            if (link.style.animation) {
                enableScroll();
                link.style.animation = '';
            }
            else {
                disableScroll();
                link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
            }
        });
        burger.classList.toggle('toggle');
    });
}

I'm not quite sure but there might be a problem with the disabling and enabling scrolling. I didn't want mobile users to be able to scroll while the navbar menus are opened.

Navbar HTML

Home

Chapters

About

Links

Related CSS

.container {
    width: 100%;
    margin: 0 0;
}

.container::after {
    content: '';
    display: grid;
    clear: both;
}

.burger {
    display: none;
    margin-top: 20px;
    cursor: pointer;
}

.burger div {
    width: 25px;
    height: 3px;
    background: #EEEEEE;
    margin: 5px;
    transition: all 0.3s ease;
}

@media only screen and (max-width: 800px) {
    .wrapper {
        overflow: hidden;
        position: relative;
    }
    .nav-links {
        -webkit-box-shadow: inset 0 0.5em 1.5em -0.5em black;
        position: absolute;
        right: 0;
        height: 100%;
        top: 70px;
        background-color: #3a345c;
        z-index: 99;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        transform: translateX(100%);
        transition: transform 0.5s ease-in;
    }
    .nav-links li {
        opacity: 0;
        padding-bottom: 50px;
        padding-top: 50px;
    }

    .nav-links li a {
        font-size: 20px;
        font-weight: bold;
    }

    .burger {
        display: block;
    }
}

Picture of the Error

Before
After

How to Reproduce

Open the website on mobile view. Open the navbar from the home menu and click chapters. It'll take you to the chapters but now the navbar is gone.

Editor's note:

The accepted answer features a self-contained reproducible example.

Body:
You have to fix you navbar using "position: fixed" property. Add & Modify given CSS

Here is the result

@media only screen and (max-width: 800px) {

    /*ADD This*/
    .fix {
        position: fixed;
        width: 100%;
        z-index: 1;
    }

    /*modify this*/
    .nav-links {
        height: 100vh;
    }
    .content {
        margin-top: 90px;
    }
}


问:
Deploying Docker Container Registry on Azure App Service Issue
I am unable to rum Docker Container Registry on the Azure App service. I have a flask app and the following is the Dockerfile of it:-

```<code>FROM python:3.8-slim-buster
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# copy project
WORKDIR /usr/src/app
COPY . /usr/src/app/

# expose port 80
EXPOSE 80
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:80", "app:app"]
</code>```

I have deployed the docker image on the Container Registry. I have also set WEBSITES_PORT to 80 under App Service -> Application Settings.
Even after doing that, I get the following error:-

```<code>  ERROR - Container XYZ didn't respond to HTTP pings on port: 80, failing site start.
</code>```

I have tried running it locally and it works fine. But, it just does not seem to work on the Azure App service. Any help is highly appreciated.

答:
I don't see an issue in the code you posted but to verify, here is a configuration for a Flask app with a Gunicorn server that works on a containerized Azure App Service:

app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "
Hello World!
"
```
<p>Dockerfile</p>
```FROM python:3.8-slim-buster
ADD app.py app.py
ADD requirements.txt requirements.txt
RUN pip install --upgrade pip
RUN python3 -m pip install -r requirements.txt

EXPOSE 80

CMD ["gunicorn", "--bind=0.0.0.0:80", "app:app"]
```
<p>requirements.txt</p>
```flask
gunicorn
```

I assume you selected "Docker Container" when you created the Azure App Service?

And then simply chose your image?

Body:
I am unable to rum Docker Container Registry on the Azure App service. I have a flask app and the following is the Dockerfile of it:-

FROM python:3.8-slim-buster
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# copy project
WORKDIR /usr/src/app
COPY . /usr/src/app/

# expose port 80
EXPOSE 80
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:80", "app:app"]

I have deployed the docker image on the Container Registry. I have also set WEBSITES_PORT to 80 under App Service -> Application Settings.
Even after doing that, I get the following error:-

  ERROR - Container XYZ didn't respond to HTTP pings on port: 80, failing site start.

I have tried running it locally and it works fine. But, it just does not seem to work on the Azure App service. Any help is highly appreciated.

Body:
I don't see an issue in the code you posted but to verify, here is a configuration for a Flask app with a Gunicorn server that works on a containerized Azure App Service:

app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello World!</p>"

Dockerfile

FROM python:3.8-slim-buster
ADD app.py app.py
ADD requirements.txt requirements.txt
RUN pip install --upgrade pip
RUN python3 -m pip install -r requirements.txt

EXPOSE 80

CMD ["gunicorn", "--bind=0.0.0.0:80", "app:app"]

requirements.txt

flask
gunicorn

I assume you selected "Docker Container" when you created the Azure App Service?

And then simply chose your image?


问:
Unable to resolve valid table in PhpStorm
I'm getting unable to resolve table errors appear in php files containing SQL querying valid tables.

If I Ctrl + Enter over the query, then I get expected results in the DB console, and if I expand the database in the DB explorer tab then I can see the tables.

It's not affecting code execution, but it's annoying because it catches my eye when writing code, and it masks real SQL errors.

I've tried refreshing the database connection, and I've verified that the php tab is connecting to the correct database.

答:
First, you need to check the Schemas tab, and make sure you've added the database.

If the unable to resolve table error stills appears, there're two options to fix this:

1.You can edit the properties of the Data Source and add the name of Database, then you can see that select * from table works well.

2.On the other hand, you can also use sql like this select * from database.table. It works for me.

By the way, in many situations, autocomplete can be very useful.

ContentLicense: CC BY-SA 3.0


问:
selecting second string point using js substring
i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?

example

```<code>var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))
</code>```

from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'

how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?

thanks in advance!

答:
use Split

```<code>var name = "one.two.three";

var output = name.split('.');

alert(output[1]);
</code>```

example here

Body:
i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?

example

var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))

from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'

how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?

thanks in advance!

Body:
use Split

var name = "one.two.three";

var output = name.split('.');

alert(output[1]);

example here


问:
Reading file only after function is done
I have a function doSmth that creates a file "data.json" by the end. (the file IS created by the end of running the script.) However, when I try to fs.readFileSync it using await and then, it says

```<code>Error: ENOENT: no such file or directory, open 'data.json'
</code>```

here is my code

```<code>const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        let fileExists = fs.existsSync('data.json');
        if (fileExists) {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
        }
    })
}

await doSmth().then(async () => {
    const fs = require("fs");
    console.log("reached")
    fs.readFileSync("data.json")
})
</code>```

how do I wait for the data.json file to be created before reading it

Edit:
from the comments changed my code to this and works

```<code>const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}
</code>```

but now I have an await inside and it causes the same data.file not found error

```<code>const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(async resolve => {
            const eachFile = await zip.file(file.name).async("string")
            const jsonObject = JSON.parse(eachFile)
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}
</code>```

答:
You are using await, but you are not returning promises.

We will use Promise.all to wait for all promises, and for each zip file, we return a new Promise when it's done by calling resolve()

```<code>const doSmth = async() => {
    await Promise.all(zip.map(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
            resolve()
        }
      })
    }))
}
</code>```

PS: I did not count the close brackets, please edit it accordingly.

PS2: your data.json should be empty since you are using JSON.stringify("") which is a empty string

if you want to do things sequentially

```<code>import fs from 'fs';
const fsPromises = fs.promises;

const doSmth = async () => {
     return new Promise(async resolve => {
           for (let i = 0; i < zip.length; i++) {
               const file = zip[i];
               if (await fsPromises.exists(file)) {
                  await fsPromises.writeFile('data.json', file);
               }
           }
           resolve(); //End the function by returning a promise.

     })

}
</code>```

Body:
I have a function doSmth that creates a file "data.json" by the end. (the file IS created by the end of running the script.) However, when I try to fs.readFileSync it using await and then, it says

Error: ENOENT: no such file or directory, open 'data.json'

here is my code

const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        let fileExists = fs.existsSync('data.json');
        if (fileExists) {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
        }
    })
}

await doSmth().then(async () => {
    const fs = require("fs");
    console.log("reached")
    fs.readFileSync("data.json")
})

how do I wait for the data.json file to be created before reading it

Edit:
from the comments changed my code to this and works

const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}

but now I have an await inside and it causes the same data.file not found error

const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(async resolve => {
            const eachFile = await zip.file(file.name).async("string")
            const jsonObject = JSON.parse(eachFile)
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}

Body:
You are using await, but you are not returning promises.

We will use Promise.all to wait for all promises, and for each zip file, we return a new Promise when it's done by calling resolve()

const doSmth = async() => {
    await Promise.all(zip.map(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
            resolve()
        }
      })
    }))
}

PS: I did not count the close brackets, please edit it accordingly.

PS2: your data.json should be empty since you are using JSON.stringify("") which is a empty string

if you want to do things sequentially

import fs from 'fs';
const fsPromises = fs.promises;

const doSmth = async () => {
     return new Promise(async resolve => {
           for (let i = 0; i < zip.length; i++) {
               const file = zip[i];
               if (await fsPromises.exists(file)) {
                  await fsPromises.writeFile('data.json', file);
               }
           }
           resolve(); //End the function by returning a promise.

     })

}


答:
Use this width: calc(100vw - 14px); on .TGC_LibBootGUIDebug{} class. here the px I used 14 on codepen it's works for me.

You could customize it for yourself. check it from here

See example:-

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: calc(100vw - 14px);
}
.TGC_LibBootGUIDebug:hover {
    overflow: visible;
    white-space: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.</div>
      </td>
    </tr>
  </tbody>
</table></code>```

Title: Cannot disable "white-space: nowrap;" on html div

Body:
Use this width: calc(100vw - 14px); on .TGC_LibBootGUIDebug{} class. here the px I used 14 on codepen it's works for me.

You could customize it for yourself. check it from here

See example:-

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: calc(100vw - 14px);
}
.TGC_LibBootGUIDebug:hover {
    overflow: visible;
    white-space: normal;
}

<table>
  <tbody>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.</div>
      </td>
    </tr>
  </tbody>
</table>


问:
Graph not showing
I have the following code

```<code># -*- coding: utf-8 -*-

# # Two Pie Charts

import time
import dash
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
from dash import Input, Output, dcc, html

# Data treatment

df = pd.read_csv('https://raw.githubusercontent.com/JorgeMiguelGomes/LEG2022_MediaMonitor/main/legislativas_2022_media_monitor_29jan2022/data_products/legislativas_2022_final_dataset_percentages.csv')

df_individuals  = pd.read_csv('https://raw.githubusercontent.com/JorgeMiguelGomes/LEG2022_MediaMonitor/main/legislativas_2022_media_monitor_29jan2022/data_products/legislativas_2022_all_candidates_filtered.csv')

df_individuals = df_individuals.drop(columns=["Unnamed: 0"])
df_indivuduals = df_individuals.drop(columns=["Post Created Date"])
df_individuals_melt=pd.melt(df_individuals,id_vars=['candidato','Page Name'])

# Styling

pie_color_map = {
    "Angry":"#EB9486",
    "Love":"#CAE7B9"
}

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP],suppress_callback_exceptions=True,
                meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
                )

app.layout = dbc.Container(
    [
        # First Row
        dbc.Row(
            [
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#CAE7B9","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#F3DE8A","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#EB9486","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#7E7F9A","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#97A7B3","opacity": "unset"}),width={'size':2}),
            ],className="g-0",
        ), # end of first row

        dbc.Tabs(
            [
                dbc.Tab(label="About", tab_id="method", label_style={"color": "#CAE7B9"},tab_style={'background-color': '#97A7B3'},active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Metrics by Totals", tab_id="totals", label_style={"color": "#F3DE8A"},tab_style={'background-color': '#7E7F9A'}, active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Stacked Analysis", tab_id="stacked", label_style={"color": "#EB9486"},tab_style={'background-color': '#F3DE8A'}, active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Love vs Angry", tab_id="love_angry", label_style={"color": "#7E7F9A"},tab_style={'background-color': '#EB9486'}, active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Conclusions", tab_id="conclusions", label_style={"color": "#97A7B3"},tab_style={'background-color': '#F3DE8A'}, active_label_style={"background-color":"#080808"}),
            ],
            id="tabs",
            active_tab="love_angry", # this is the tab that will be active when the user comes to the website
        ), # end of tabs
        html.Div(id="tab-content", className="p-5"),
    ]
)

# Callbacks

# Pie Chart for Candidates

# @app.callback(
#     Output(component_id='graph_individuals', component_property='figure'),
#     [Input(component_id='dropdown_candidates', component_property='value')],
# )

# def build_graph_individuals(column_chosen):
#     dff = df
#     totals_sentiment = dff.groupby(['candidato'])[['Love','Angry']].sum().reset_index()
#     totals_sentiment_melt = pd.melt(totals_sentiment,id_vars="candidato")
#     totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == column_chosen]
#     fig_individuals = px.pie(totals_sentiment_melt,names="variable",values="value",hole=0.5, color="variable",color_discrete_map=pie_color_map)
#     candidato_filter = column_chosen
#     return fig_individuals

# Pie Chart for Media Outlets

@app.callback(
    Output(component_id='graph_shares_comments', component_property='figure'),
    Output(component_id='graph_individuals', component_property='figure'),
    Input(component_id='dropdown_media_outlet', component_property='value'),
    Input(component_id='dropdown_candidates', component_property='value')
)

def build_graphs(column_chosen, candidato_filter):

    # Data Treatment for candidate graph
    dff = df
    totals_sentiment = dff.groupby(['candidato'])[['Love','Angry']].sum().reset_index()
    totals_sentiment_melt = pd.melt(totals_sentiment,id_vars="candidato")
    totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == column_chosen]

    # Data Treatment for media graph
    dff_m = df[df['candidato']== candidato_filter]
    print(dff_m)
    totals_sentiment_media = dff_m.groupby(['Page Name'])[['Love','Angry']].sum().reset_index()
    totals_sentiment_media_melt = pd.melt(totals_sentiment_media,id_vars="Page Name")
    totals_sentiment_media_melt = totals_sentiment_media_melt[totals_sentiment_media_melt['Page Name'] == column_chosen]
    print("HELLO HELLO")
    print(totals_sentiment_media_melt)

    # Pice Charts

    fig_candidates = px.pie(totals_sentiment_melt,names="variable",values="value",hole=0.5, color="variable",color_discrete_map=pie_color_map)
    fig_media = px.pie(totals_sentiment_media_melt,names="variable",values="value",hole=0.6, color="variable",color_discrete_map=pie_color_map)

    return fig_candidates, fig_media

# TABS CALLBACKS -------------------------------------

@app.callback(Output("tab-content", "children"),
    [Input("tabs", "active_tab")])

def switch_tab(at):
    if at == "love_angry":
        tab4_content = dbc.Row(
                        [
                            dbc.Col(
                                [
                                dcc.Dropdown(
                                id='dropdown_candidates',
                                options=[{'label': i, 'value': i} for i in df_individuals_melt.candidato.unique()
                                    ],
                                    optionHeight=35,                        #height/space between dropdown options
                                    value='António Costa',             #dropdown value selected automatically when page loads
                                    disabled=False,                         #disable dropdown value selection
                                    multi=False,                            #allow multiple dropdown values to be selected
                                    searchable=True,                        #allow user-searching of dropdown values
                                    search_value='',                        #remembers the value searched in dropdown
                                    placeholder='Please select...',         #gray, default text shown when no option is selected
                                    clearable=True,                         #allow user to removes the selected value
                                    style={'width':"100%"},                 #use dictionary to define CSS styles of your dropdown
                                    # className='select_box',               #activate separate CSS document in assets folder
                                    # persistence=True,                     #remembers dropdown value. Used with persistence_type
                                    # persistence_type='memory'             #remembers dropdown value selected until...
                                    ),
                                dbc.Col(
                                    dcc.Graph(id='graph_individuals'),
                                    ),
                                ],width={'size':6, 'offset':0}
                            ),

                            dbc.Col(
                                [
                                dcc.Dropdown(
                                id='dropdown_media_outlet',
                                options=[{'label': i, 'value': i} for i in df['Page Name'].unique()
                                ],
                                optionHeight=35,                        #height/space between dropdown options
                                value='Agência Lusa',                   #dropdown value selected automatically when page loads
                                disabled=False,                         #disable dropdown value selection
                                multi=False,                            #allow multiple dropdown values to be selected
                                searchable=True,                        #allow user-searching of dropdown values
                                search_value='',                        #remembers the value searched in dropdown
                                placeholder='Please select...',         #gray, default text shown when no option is selected
                                clearable=True,                         #allow user to removes the selected value
                                style={'width':"100%"},                 #use dictionary to define CSS styles of your dropdown
                                # className='select_box',               #activate separate CSS document in assets folder
                                # persistence=True,                     #remembers dropdown value. Used with persistence_type
                                # persistence_type='memory'             #remembers dropdown value selected until...

                                    ),
                                dbc.Col(
                                    dcc.Graph(id='graph_shares_comments'),
                                    ),
                                ],width={'size':6, 'offset':0}
                            ),

                        ],
        ),

        return tab4_content
    # Error Message
    return html.P("FOR SUPPORT PURPOSES ONLY")

if __name__ == "__main__":
    app.run_server(debug=True, port=8888)
</code>```

The code is running without errors but as you can see in the image below, the chart on the left side is not rendering, and I'm totally lost.
I have inserted a print command in the script, and when I change the dropdowns the values change accordingly as they should.

However the pie chart remains empty, like it's not getting any information.
Maybe I've been looking at the same code for more hours than I should, and I'm missing something really simple, but I just can't spot it.

Any help would be really appreciated.

Disclosure This is not a commercial project nor will I use it in any commercial way.

答:
You were filtering with the wrong keyword for totals_sentiment_melt, use this to correct it:

totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == candidato_filter]
```

Title: Graph not showing

Body:
I have the following code

# -*- coding: utf-8 -*-

# # Two Pie Charts

import time
import dash
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
from dash import Input, Output, dcc, html

# Data treatment

df = pd.read_csv('https://raw.githubusercontent.com/JorgeMiguelGomes/LEG2022_MediaMonitor/main/legislativas_2022_media_monitor_29jan2022/data_products/legislativas_2022_final_dataset_percentages.csv')

df_individuals  = pd.read_csv('https://raw.githubusercontent.com/JorgeMiguelGomes/LEG2022_MediaMonitor/main/legislativas_2022_media_monitor_29jan2022/data_products/legislativas_2022_all_candidates_filtered.csv')

df_individuals = df_individuals.drop(columns=["Unnamed: 0"])
df_indivuduals = df_individuals.drop(columns=["Post Created Date"])
df_individuals_melt=pd.melt(df_individuals,id_vars=['candidato','Page Name'])

# Styling

pie_color_map = {
    "Angry":"#EB9486",
    "Love":"#CAE7B9"
}

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP],suppress_callback_exceptions=True,
                meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
                )

app.layout = dbc.Container(
    [
        # First Row
        dbc.Row(
            [
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#CAE7B9","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#F3DE8A","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#EB9486","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#7E7F9A","opacity": "unset"}),width={'size':2}),
            dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#97A7B3","opacity": "unset"}),width={'size':2}),
            ],className="g-0",
        ), # end of first row

        dbc.Tabs(
            [
                dbc.Tab(label="About", tab_id="method", label_style={"color": "#CAE7B9"},tab_style={'background-color': '#97A7B3'},active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Metrics by Totals", tab_id="totals", label_style={"color": "#F3DE8A"},tab_style={'background-color': '#7E7F9A'}, active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Stacked Analysis", tab_id="stacked", label_style={"color": "#EB9486"},tab_style={'background-color': '#F3DE8A'}, active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Love vs Angry", tab_id="love_angry", label_style={"color": "#7E7F9A"},tab_style={'background-color': '#EB9486'}, active_label_style={"background-color":"#080808"}),
                dbc.Tab(label="Conclusions", tab_id="conclusions", label_style={"color": "#97A7B3"},tab_style={'background-color': '#F3DE8A'}, active_label_style={"background-color":"#080808"}),
            ],
            id="tabs",
            active_tab="love_angry", # this is the tab that will be active when the user comes to the website
        ), # end of tabs
        html.Div(id="tab-content", className="p-5"),
    ]
)

# Callbacks

# Pie Chart for Candidates

# @app.callback(
#     Output(component_id='graph_individuals', component_property='figure'),
#     [Input(component_id='dropdown_candidates', component_property='value')],
# )

# def build_graph_individuals(column_chosen):
#     dff = df
#     totals_sentiment = dff.groupby(['candidato'])[['Love','Angry']].sum().reset_index()
#     totals_sentiment_melt = pd.melt(totals_sentiment,id_vars="candidato")
#     totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == column_chosen]
#     fig_individuals = px.pie(totals_sentiment_melt,names="variable",values="value",hole=0.5, color="variable",color_discrete_map=pie_color_map)
#     candidato_filter = column_chosen
#     return fig_individuals

# Pie Chart for Media Outlets

@app.callback(
    Output(component_id='graph_shares_comments', component_property='figure'),
    Output(component_id='graph_individuals', component_property='figure'),
    Input(component_id='dropdown_media_outlet', component_property='value'),
    Input(component_id='dropdown_candidates', component_property='value')
)

def build_graphs(column_chosen, candidato_filter):

    # Data Treatment for candidate graph
    dff = df
    totals_sentiment = dff.groupby(['candidato'])[['Love','Angry']].sum().reset_index()
    totals_sentiment_melt = pd.melt(totals_sentiment,id_vars="candidato")
    totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == column_chosen]

    # Data Treatment for media graph
    dff_m = df[df['candidato']== candidato_filter]
    print(dff_m)
    totals_sentiment_media = dff_m.groupby(['Page Name'])[['Love','Angry']].sum().reset_index()
    totals_sentiment_media_melt = pd.melt(totals_sentiment_media,id_vars="Page Name")
    totals_sentiment_media_melt = totals_sentiment_media_melt[totals_sentiment_media_melt['Page Name'] == column_chosen]
    print("HELLO HELLO")
    print(totals_sentiment_media_melt)

    # Pice Charts

    fig_candidates = px.pie(totals_sentiment_melt,names="variable",values="value",hole=0.5, color="variable",color_discrete_map=pie_color_map)
    fig_media = px.pie(totals_sentiment_media_melt,names="variable",values="value",hole=0.6, color="variable",color_discrete_map=pie_color_map)

    return fig_candidates, fig_media

# TABS CALLBACKS -------------------------------------

@app.callback(Output("tab-content", "children"),
    [Input("tabs", "active_tab")])

def switch_tab(at):
    if at == "love_angry":
        tab4_content = dbc.Row(
                        [
                            dbc.Col(
                                [
                                dcc.Dropdown(
                                id='dropdown_candidates',
                                options=[{'label': i, 'value': i} for i in df_individuals_melt.candidato.unique()
                                    ],
                                    optionHeight=35,                        #height/space between dropdown options
                                    value='António Costa',             #dropdown value selected automatically when page loads
                                    disabled=False,                         #disable dropdown value selection
                                    multi=False,                            #allow multiple dropdown values to be selected
                                    searchable=True,                        #allow user-searching of dropdown values
                                    search_value='',                        #remembers the value searched in dropdown
                                    placeholder='Please select...',         #gray, default text shown when no option is selected
                                    clearable=True,                         #allow user to removes the selected value
                                    style={'width':"100%"},                 #use dictionary to define CSS styles of your dropdown
                                    # className='select_box',               #activate separate CSS document in assets folder
                                    # persistence=True,                     #remembers dropdown value. Used with persistence_type
                                    # persistence_type='memory'             #remembers dropdown value selected until...
                                    ),
                                dbc.Col(
                                    dcc.Graph(id='graph_individuals'),
                                    ),
                                ],width={'size':6, 'offset':0}
                            ),

                            dbc.Col(
                                [
                                dcc.Dropdown(
                                id='dropdown_media_outlet',
                                options=[{'label': i, 'value': i} for i in df['Page Name'].unique()
                                ],
                                optionHeight=35,                        #height/space between dropdown options
                                value='Agência Lusa',                   #dropdown value selected automatically when page loads
                                disabled=False,                         #disable dropdown value selection
                                multi=False,                            #allow multiple dropdown values to be selected
                                searchable=True,                        #allow user-searching of dropdown values
                                search_value='',                        #remembers the value searched in dropdown
                                placeholder='Please select...',         #gray, default text shown when no option is selected
                                clearable=True,                         #allow user to removes the selected value
                                style={'width':"100%"},                 #use dictionary to define CSS styles of your dropdown
                                # className='select_box',               #activate separate CSS document in assets folder
                                # persistence=True,                     #remembers dropdown value. Used with persistence_type
                                # persistence_type='memory'             #remembers dropdown value selected until...

                                    ),
                                dbc.Col(
                                    dcc.Graph(id='graph_shares_comments'),
                                    ),
                                ],width={'size':6, 'offset':0}
                            ),

                        ],
        ),

        return tab4_content
    # Error Message
    return html.P("FOR SUPPORT PURPOSES ONLY")

if __name__ == "__main__":
    app.run_server(debug=True, port=8888)

The code is running without errors but as you can see in the image below, the chart on the left side is not rendering, and I'm totally lost.
I have inserted a print command in the script, and when I change the dropdowns the values change accordingly as they should.

However the pie chart remains empty, like it's not getting any information.
Maybe I've been looking at the same code for more hours than I should, and I'm missing something really simple, but I just can't spot it.

Any help would be really appreciated.

Disclosure This is not a commercial project nor will I use it in any commercial way.


问:
RealityKit – Add force to Entity at specific point
I have my entity which has also physics I check for it with the if let syntax:

```<code>if let scoot = scooter as? HasPhysics { ... }
</code>```

this works as charm I am able to get the user tap by using UITapGestureRecognizer this is just the first iteration I would like to use the swipe or pan gestures ideally.

```<code>// I can get the location of the tap in the arView
let location =  sender.location(in: arView)

// I can use this three approaches both of them returns me the Entity not sure which to use though
let hittest = arView.hitTest(location)
let results = arView.raycast(from: location, allowing: .existingPlaneInfinite, alignment: .any)
let entity = arView.entity(at: location)
</code>```

At this stage I am in need of applying the force at the point of the Tap impact. Since I am in this iteration using tap, the force is always the same (in the next iteration I want to count with the velocity/vector of the impact and push my object with greater force on greater velocity gesture).

I just want to make sure the object is behaving the right way. Is this possible?

答:
I think you need the following approach.

First of all, apply generateCollisionShapes(...) instance method that  activates collisions for given entities.

```<code>func generateCollisionShapes(recursive: Bool)
</code>```

Secondly, use ray(...) method returning an optional tuple:

```<code>@MainActor func ray(through screenPoint: CGPoint) -> (origin: SIMD3<Float>,
                                                   direction: SIMD3<Float>)?
</code>```

Thirdly, use arView.scene.raycast(...) method that returns CollisionCastHit collection:

```<code>       func raycast(origin: SIMD3<Float>,
                 direction: SIMD3<Float>,
                    length: Float = 100,
                     query: CollisionCastQueryType = .all,
                      mask: CollisionGroup = .all,
relativeTo referenceEntity: Entity? = nil) -> [CollisionCastHit]
</code>```

Instance of CollisionCastHit can give you 4 subproperties:

```<code>CollisionCastHit().position
CollisionCastHit().entity
CollisionCastHit().distance
CollisionCastHit().normal
</code>```

And at last, you already know the vector of force...

```<code>entity.physicsMotion?.linearVelocity = SIMD3<Float>()
</code>```

Optionally, you might use an angular velocity of the body around the center of its mass.

```<code>entity.physicsMotion?.angularVelocity = SIMD3<Float>()
</code>```

Body:
I have my entity which has also physics I check for it with the if let syntax:

if let scoot = scooter as? HasPhysics { ... }

this works as charm I am able to get the user tap by using UITapGestureRecognizer this is just the first iteration I would like to use the swipe or pan gestures ideally.

// I can get the location of the tap in the arView
let location =  sender.location(in: arView)

// I can use this three approaches both of them returns me the Entity not sure which to use though
let hittest = arView.hitTest(location)
let results = arView.raycast(from: location, allowing: .existingPlaneInfinite, alignment: .any)
let entity = arView.entity(at: location)

At this stage I am in need of applying the force at the point of the Tap impact. Since I am in this iteration using tap, the force is always the same (in the next iteration I want to count with the velocity/vector of the impact and push my object with greater force on greater velocity gesture).

I just want to make sure the object is behaving the right way. Is this possible?

Body:
I think you need the following approach.

First of all, apply generateCollisionShapes(...) instance method that  activates collisions for given entities.

func generateCollisionShapes(recursive: Bool)

Secondly, use ray(...) method returning an optional tuple:

@MainActor func ray(through screenPoint: CGPoint) -> (origin: SIMD3<Float>,
                                                   direction: SIMD3<Float>)?

Thirdly, use arView.scene.raycast(...) method that returns CollisionCastHit collection:

       func raycast(origin: SIMD3<Float>,
                 direction: SIMD3<Float>,
                    length: Float = 100,
                     query: CollisionCastQueryType = .all,
                      mask: CollisionGroup = .all,
relativeTo referenceEntity: Entity? = nil) -> [CollisionCastHit]

Instance of CollisionCastHit can give you 4 subproperties:

CollisionCastHit().position
CollisionCastHit().entity
CollisionCastHit().distance
CollisionCastHit().normal

And at last, you already know the vector of force...

entity.physicsMotion?.linearVelocity = SIMD3<Float>()

Optionally, you might use an angular velocity of the body around the center of its mass.

entity.physicsMotion?.angularVelocity = SIMD3<Float>()


问:
Problem with Linq inside a while-header
I'm trying to find the next available Groupname on my project. I want the groupnames look like "Gruppe 1", "Gruppe 2" and so on. So that's what i got so far:

```<code>int i = 0;
while ((from GroupViewModel g in _groups
        where g.GroupName == ("Gruppe " + (++i).ToString())
        select g).Any());
Group group = new Group() { Name = string.Format("Gruppe {0}", i) };
_groups.Add(new GroupViewModel(group));
</code>```

I thought this is a cool solution for my problem, but than i started testing the code.

If _groups is empty, the first group is "Gruppe 0".

If _groups contains 1 Group(named "Gruppe 1"), the resulting groupname is "Gruppe 2".

If _groups contains 1 Group(named "Gruppe 2"), the resulting groupname is "Gruppe 1", but if i add an other group the resulting name is also "Gruppe 2".
I did alot testcases and the results are always strange.

```<code>initial Groupnames             | Resulting names
-empty-                        | "Gruppe 0", "Gruppe 1", "Gruppe 2", ...
"Gruppe 1"                     | "Gruppe 2", "Gruppe 3", "Gruppe 4", ...
"Gruppe 2"                     | "Gruppe 1", "Gruppe 2", "Gruppe 3", ...
"Gruppe 1", "Gruppe 2"         | "Gruppe 3", "Gruppe 4", "Gruppe 5", ...
"Gruppe 1", "Gruppe 3"         | "Gruppe 5", "Gruppe 6", "Gruppe 7", ...
"Gruppe 1", "Gruppe 4"         | "Gruppe 3", "Gruppe 4", "Gruppe 5", ...
"Gruppe 2", "Gruppe 1"         | "Gruppe 2", "Gruppe 3", "Gruppe 4", ...
</code>```

So, any clues?

答:
Well, i++ is being called for every entry, whether or not it matches.

I would suggest creating a lookup by the group name, and then just using a loop to extract the results. However, it's really not clear to me what you want in the first place. Are you just trying to find the first "available" group ID and add a new GroupViewModel for it? If so, I'd do something like:

```<code>var lookup = _groups.ToLookup(group => group.GroupName);

for (int i=0; i < int.MaxValue; i++)
{
    string candidateName = "Gruppe " + i;
    if (!lookup.Contains(candidateName)
    {
        Group group = new Group { Name = candidateName };
        _groups.Add(new GroupViewModel(group));
        break;
    }
}
</code>```

OwnerDisplayName: TheJudge

ContentLicense: CC BY-SA 2.5

Title: Problem with Linq inside a while-header

Body:
I'm trying to find the next available Groupname on my project. I want the groupnames look like "Gruppe 1", "Gruppe 2" and so on. So that's what i got so far:

int i = 0;
while ((from GroupViewModel g in _groups
        where g.GroupName == ("Gruppe " + (++i).ToString())
        select g).Any());
Group group = new Group() { Name = string.Format("Gruppe {0}", i) };
_groups.Add(new GroupViewModel(group));

I thought this is a cool solution for my problem, but than i started testing the code.

If _groups is empty, the first group is "Gruppe 0".

If _groups contains 1 Group(named "Gruppe 1"), the resulting groupname is "Gruppe 2".

If _groups contains 1 Group(named "Gruppe 2"), the resulting groupname is "Gruppe 1", but if i add an other group the resulting name is also "Gruppe 2".
I did alot testcases and the results are always strange.

initial Groupnames             | Resulting names
-empty-                        | "Gruppe 0", "Gruppe 1", "Gruppe 2", ...
"Gruppe 1"                     | "Gruppe 2", "Gruppe 3", "Gruppe 4", ...
"Gruppe 2"                     | "Gruppe 1", "Gruppe 2", "Gruppe 3", ...
"Gruppe 1", "Gruppe 2"         | "Gruppe 3", "Gruppe 4", "Gruppe 5", ...
"Gruppe 1", "Gruppe 3"         | "Gruppe 5", "Gruppe 6", "Gruppe 7", ...
"Gruppe 1", "Gruppe 4"         | "Gruppe 3", "Gruppe 4", "Gruppe 5", ...
"Gruppe 2", "Gruppe 1"         | "Gruppe 2", "Gruppe 3", "Gruppe 4", ...

So, any clues?

Body:
Well, i++ is being called for every entry, whether or not it matches.

I would suggest creating a lookup by the group name, and then just using a loop to extract the results. However, it's really not clear to me what you want in the first place. Are you just trying to find the first "available" group ID and add a new GroupViewModel for it? If so, I'd do something like:

var lookup = _groups.ToLookup(group => group.GroupName);

for (int i=0; i < int.MaxValue; i++)
{
    string candidateName = "Gruppe " + i;
    if (!lookup.Contains(candidateName)
    {
        Group group = new Group { Name = candidateName };
        _groups.Add(new GroupViewModel(group));
        break;
    }
}

OwnerDisplayName: Jon Skeet

LastEditorDisplayName: Jon Skeet


问:
c# models to protobuf messages (gRPC project)
I can find quite many resources on how to generate C# models from protobuf messages (it's even built into the Grpc.AspNetCore package), but not the other way around.

I've created a blazor webassembly client/server project similar to this one: https://github.com/stevejgordon/gRPCBasicSample/

I have an Domain layer with lots of C# models that I'm using for the Application. I would like to convert these models into message reply "view models", instead of writing them all in hand (also I'm not even sure of the right conversion between c# and protobuf)

Example:
C# Model:

    ///
    /// The area.
    ///
    public class Area
    {
        ///
        /// Initializes a new instance of the <see cref="Area"/> class.
        ///
        /// <param name="name">Name of the region.</param>
        /// <param name="areaType">What type of area is the region.</param>
        /// <param name="numberOfSupplies">number of supplies the region has.</param>
        /// <param name="numberOfMusterCrows">number of crowns the region has.</param>
        public Area(string name, AreaType areaType, int numberOfSupplies, int numberOfMusterCrows)
        {
            this.Name = name;
            this.AreaType = areaType;
            this.NumberOfSupplies = numberOfSupplies;
            this.NumberOfMusterCrowns = numberOfMusterCrows;
            this.CurrentArmy = new Collection<Unit>();
            this.AdjacentAreas = new Collection<Area>();
        }

        ///
        /// Gets the name of the region.
        ///
        public string Name { get; }

        ///
        /// Gets or sets which house the area is controlled by.
        ///
        public House ControlledBy { get; set; }

        ///
        /// Gets the type of area the region is.
        ///
        public AreaType AreaType { get; }

        ///
        /// Gets the adjacent regions the region has.
        ///
        public IEnumerable<Area> AdjacentAreas { get; internal set; }

        ///
        /// Gets the number of supplies (barrels) the region has.
        ///
        public int NumberOfSupplies { get; }

        ///
        /// Gets the number of crowns the region has.
        ///
        public int NumberOfMusterCrowns { get; }

        ///
        /// Gets or sets a value indicating whether the region is occupied by troops.
        ///
        public bool IsOccupied { get; set; }

        ///
        /// Gets a value indicating whether the region has a stronghold.
        ///
        public bool HasStronghold { get; }

        ///
        /// Gets a value indicating whether the region has a castle.
        ///
        public bool HasCastle { get; }

        ///
        /// Gets or sets the current armies occupying the region.
        ///
        public ICollection<Unit> CurrentArmy { get; set; }

        ///
        /// Gets or sets the current order token placed.
        ///
        public OrderToken? PlacedOrderToken { get; set; }
    }
```
<p>Should turn into something like this (simplified):</p>
<pre class="lang-proto prettyprint-override"><code>message AreaReply {
  string name = 1;
  enum AreaType {
    Land = 0;
    Water = 1;
  }
  AreaType areaType = 4;
  House controlledBy = 5;
}
message House {
    google.protobuf.StringValue name = 1;
}
</code>```

Is there really no such generator out there? :)

Thanks

答:
Use this annotation on top of your class definition:

[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]

See: Protobuf-net serialization without annotation

Body:
I can find quite many resources on how to generate C# models from protobuf messages (it's even built into the Grpc.AspNetCore package), but not the other way around.

I've created a blazor webassembly client/server project similar to this one: https://github.com/stevejgordon/gRPCBasicSample/

I have an Domain layer with lots of C# models that I'm using for the Application. I would like to convert these models into message reply "view models", instead of writing them all in hand (also I'm not even sure of the right conversion between c# and protobuf)

Example:
C# Model:

    ///
    /// The area.
    ///
    public class Area
    {
        ///
        /// Initializes a new instance of the <see cref="Area"/> class.
        ///
        /// <param name="name">Name of the region.</param>
        /// <param name="areaType">What type of area is the region.</param>
        /// <param name="numberOfSupplies">number of supplies the region has.</param>
        /// <param name="numberOfMusterCrows">number of crowns the region has.</param>
        public Area(string name, AreaType areaType, int numberOfSupplies, int numberOfMusterCrows)
        {
            this.Name = name;
            this.AreaType = areaType;
            this.NumberOfSupplies = numberOfSupplies;
            this.NumberOfMusterCrowns = numberOfMusterCrows;
            this.CurrentArmy = new Collection<Unit>();
            this.AdjacentAreas = new Collection<Area>();
        }

        ///
        /// Gets the name of the region.
        ///
        public string Name { get; }

        ///
        /// Gets or sets which house the area is controlled by.
        ///
        public House ControlledBy { get; set; }

        ///
        /// Gets the type of area the region is.
        ///
        public AreaType AreaType { get; }

        ///
        /// Gets the adjacent regions the region has.
        ///
        public IEnumerable<Area> AdjacentAreas { get; internal set; }

        ///
        /// Gets the number of supplies (barrels) the region has.
        ///
        public int NumberOfSupplies { get; }

        ///
        /// Gets the number of crowns the region has.
        ///
        public int NumberOfMusterCrowns { get; }

        ///
        /// Gets or sets a value indicating whether the region is occupied by troops.
        ///
        public bool IsOccupied { get; set; }

        ///
        /// Gets a value indicating whether the region has a stronghold.
        ///
        public bool HasStronghold { get; }

        ///
        /// Gets a value indicating whether the region has a castle.
        ///
        public bool HasCastle { get; }

        ///
        /// Gets or sets the current armies occupying the region.
        ///
        public ICollection<Unit> CurrentArmy { get; set; }

        ///
        /// Gets or sets the current order token placed.
        ///
        public OrderToken? PlacedOrderToken { get; set; }
    }

Should turn into something like this (simplified):

message AreaReply {
  string name = 1;
  enum AreaType {
    Land = 0;
    Water = 1;
  }
  AreaType areaType = 4;
  House controlledBy = 5;
}
message House {
    google.protobuf.StringValue name = 1;
}

Is there really no such generator out there? :)

Thanks


问:
Celery - How to update the state of a task after the worker's being shutdown?

Setup

Celery 3.0

broker=RabbitMQ

Scenario

Tasks have already been acknowledged and started processing, and have state=STARTED. Then I want to restart my worker (to update the worker to a newer version). After restart worker (using supervisorctl restart), those long running tasks are all been terminated. But their states remain in state=STARTED. How can I update their state to FAILURE or whatever other values? (And, I don't want these tasks being executed again after the worker restarts.)

Methods tried (but not working)

use track_started=True --- If with this option, the tasks stay at state=STARTED after the worker restarts. If without this option, the tasks stay at state=PENDING after the worker restarts.

use CELERY_ACKS_LATE=True --- The tasks stay at state=STARTED after the worker restarts. And tasks are executed again, not a desired behavior.

use signal(SIGTERM, handler) and a handler function to catch the signal. The handler can successfully be entered. However, no matter what thing I put inside the handler, it can't change the task's state. The states just stay as the same and won't change to FAILURE. Inside the handler I've tried

raise Exception

exit(0)

exit(1)

Is there any settings of Celery that could enable it to track the state of task being shutdown?

答:
I find the last method (signal(SIGTERM, handler)) you tried working. Since the code successfully enter the TERM signal handling branch, the crux becomes how to update the state of task. Simply use self.update_state(state=states.FAILURE) inside the task body.

Here's an example:

```<code>import time
import signal
from celery import Celery, states

app = Celery("celery")

@app.task(bind=True)
def demo(self):

    def mark_as_fail(*args):
        self.update_state(state=states.FAILURE)

    signal.signal(signal.SIGTERM, mark_as_fail)

    for i in range(30):
        print(f"I am demo task {i}")
        time.sleep(1)
</code>```

Body:
I find the last method (signal(SIGTERM, handler)) you tried working. Since the code successfully enter the TERM signal handling branch, the crux becomes how to update the state of task. Simply use self.update_state(state=states.FAILURE) inside the task body.

Here's an example:

import time
import signal
from celery import Celery, states

app = Celery("celery")

@app.task(bind=True)
def demo(self):

    def mark_as_fail(*args):
        self.update_state(state=states.FAILURE)

    signal.signal(signal.SIGTERM, mark_as_fail)

    for i in range(30):
        print(f"I am demo task {i}")
        time.sleep(1)


问:
updating dns CNAME
I'm trying to update a bunch of dns cname entry, using azure-powershell.

I have no troubles getting the dns entry I need to update, but my problem starts when trying to update the cname (due to the fact there can be only one cname entry).

I went to azure documentation, and found about set-azdnsrecordset, but I failed to find the correct parameter/syntax to update the CNAME

Here is what I tried.

```<code>$rs = Get-AzDnsRecordSet -name "test1" -RecordType CNAME -ZoneName "zone.io" -ResourceGroupName "dns"
$rs.Records[0].Records = "new-test-v1.com"
Set-AzDnsRecordSet -RecordSet $rs
</code>```

With error on $rs.Records[0].Records = "new-test-v1.com":

```<code>The property 'Records' cannot be found on this object. Verify that the property exists and can be set.
</code>```

echo $rs

```<code>Id                : /subscriptions/[redacted]/resourceGroups/[redacted]/providers/Microsoft.Network/dnszones/[redacted].io/CNAME/test1
Name              : test1
ZoneName          : zone.io
ResourceGroupName : dns
Ttl               : 3600
Etag              : [redacted]
RecordType        : CNAME
TargetResourceId  :
Records           : {test-v1.com}
Metadata          :
ProvisioningState : Succeeded
</code>```

PS : I did found a working solution. Deleting/recreating the records works fine enough. I also realise that if something goes wrong in the creation segment, I lose my record (setting failsafe would be a lot of additional work), So I keep it as a last ressort.

答:
One of the workaround to update CNAME records in Azure DNS

To update CNAME we have to remove the existing alias and then have to add a new one.
We have tried with below cmdlt and updated the CNAME:

PowerShell Cmd:-

```<code>$rs = Get-AzDnsRecordSet -name "rahul" -RecordType CNAME -ZoneName "zone.com" -ResourceGroupName "rgname"
Remove-AzDnsRecordConfig -RecordSet $rs -Cname $rs.Records.cname | Set-AzDnsRecordSet
$newcname = "new-test-v1.com"
Get-AzDnsRecordSet -name "rahul" -RecordType CNAME -ZoneName "myzone.com" -ResourceGroupName "rgname" | Add-AzDnsRecordConfig -Cname $newcname | Set-AzDnsRecordSet
</code>```

SAMPLE OUTPUT:-

Title: updating dns CNAME

Body:
I'm trying to update a bunch of dns cname entry, using azure-powershell.

I have no troubles getting the dns entry I need to update, but my problem starts when trying to update the cname (due to the fact there can be only one cname entry).

I went to azure documentation, and found about set-azdnsrecordset, but I failed to find the correct parameter/syntax to update the CNAME

Here is what I tried.

$rs = Get-AzDnsRecordSet -name "test1" -RecordType CNAME -ZoneName "zone.io" -ResourceGroupName "dns"
$rs.Records[0].Records = "new-test-v1.com"
Set-AzDnsRecordSet -RecordSet $rs

With error on $rs.Records[0].Records = "new-test-v1.com":

The property 'Records' cannot be found on this object. Verify that the property exists and can be set.

echo $rs

Id                : /subscriptions/[redacted]/resourceGroups/[redacted]/providers/Microsoft.Network/dnszones/[redacted].io/CNAME/test1
Name              : test1
ZoneName          : zone.io
ResourceGroupName : dns
Ttl               : 3600
Etag              : [redacted]
RecordType        : CNAME
TargetResourceId  :
Records           : {test-v1.com}
Metadata          :
ProvisioningState : Succeeded

PS : I did found a working solution. Deleting/recreating the records works fine enough. I also realise that if something goes wrong in the creation segment, I lose my record (setting failsafe would be a lot of additional work), So I keep it as a last ressort.

Body:
One of the workaround to update CNAME records in Azure DNS

To update CNAME we have to remove the existing alias and then have to add a new one.
We have tried with below cmdlt and updated the CNAME:

PowerShell Cmd:-

$rs = Get-AzDnsRecordSet -name "rahul" -RecordType CNAME -ZoneName "zone.com" -ResourceGroupName "rgname"
Remove-AzDnsRecordConfig -RecordSet $rs -Cname $rs.Records.cname | Set-AzDnsRecordSet
$newcname = "new-test-v1.com"
Get-AzDnsRecordSet -name "rahul" -RecordType CNAME -ZoneName "myzone.com" -ResourceGroupName "rgname" | Add-AzDnsRecordConfig -Cname $newcname | Set-AzDnsRecordSet

SAMPLE OUTPUT:-


问:
Numbering Bars from 1- 5 In pine editor and it should reset every day at midnight
how do I number each bar 1-5 in pine editor? So, it should reset after midnight so 12am should always be 1. When the number reaches 5 the number will reset and the next bar will be a 1.</p>

答:
You can use the hour and minute built-in variables to work with any time.

```<code>//@version=5
indicator("a")
h = input.int(00, "Hour")
m = input.int(00, "Minute")
l = input.int(5, "Limit")

var cnt = 1

time_reset = hour == h and minute == m

if (time_reset)
    cnt := 1
else
    if (cnt % l == 0)
        cnt := 1
    else
        cnt := cnt + 1

plotchar(time_reset ? 1 : na, "Time Reset", "•", location.absolute, color.green, size = size.small)
plot(cnt)
</code>```

Body:
You can use the hour and minute built-in variables to work with any time.

//@version=5
indicator("a")
h = input.int(00, "Hour")
m = input.int(00, "Minute")
l = input.int(5, "Limit")

var cnt = 1

time_reset = hour == h and minute == m

if (time_reset)
    cnt := 1
else
    if (cnt % l == 0)
        cnt := 1
    else
        cnt := cnt + 1

plotchar(time_reset ? 1 : na, "Time Reset", "•", location.absolute, color.green, size = size.small)
plot(cnt)


问:
Difference between (age==18) and (age===18) in JavaScript?
I was doing this program and not getting output but if I entered age 18 after typecasting the age in the second block of code I got the output why is it so?

And if I use only two "==" sign then also I got the output but in case of "===" I didn't get the output.

age == 18 Got the output

Number(age)===18 Got the output

age === 18 Didn't got the output

Both the codes are given below.

With "==="

```<code>var age=prompt("Enter your age");
if(age<18){
  alert("Sorry, You are too young to drive this car Powering off");
}else if(age>18){
  alert("Powering On Enjoy the ride!");
}else if(age===18){
  alert("Congratulation on your first riding Enjoy the ride!");
}
</code>```

With typecasting "Number(age)===18"

```<code>var age = prompt("What is your age?");
if (Number(age) < 18) {
  alert("Sorry, you are too young to drive this car. Powering off");
} else if (Number(age) > 18) {
  alert("Powering On. Enjoy the ride!");
} else if (Number(age) === 18) {
  alert("Congratulations on your first year of driving. Enjoy the ride!");
}
</code>```

答:
prompt always returns a value in string format.

Suppose a string and number have same value (say 18 and '18'). Here the value is same, only the type differs. Comparing a string value with a number will return true if only value is compared and false if type is also compared.

== compares two value without comparing the types. == is called as Abstract Equality Comparison which compares value only, not type. == will perform a type conversion when comparing two things.

console.log(18 == '18'); // Expect true```
</div>
</div>
</p>
<p><code>===</code> compares two value by comparing the types. <code>===</code> is called as <strong>Strict Equality Comparison</strong> this will compare both value and type</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(18 === '18'); // Expect false</code>```

In case of Number(age) === 18, the string age is converted to numeric age and hence this both the value is od type number. Hence this will return true

Read More on == and ===

const age = prompt("Enter your age");
console.log(`Type of Age = ${typeof age}`);
const numbericAge = +age; // String to number conversion, Same as Number(age)
console.log(`Type of Numeric Age = ${typeof numbericAge}`);
if (numbericAge < 18) {
  alert("Sorry, You are too young to drive this car Powering off");
} else if (numbericAge > 18) {
  alert("Powering On Enjoy the ride!");
} else if (numbericAge === 18) {
  alert("Congratulation on your first riding Enjoy the ride!");
}```

Body:
I was doing this program and not getting output but if I entered age 18 after typecasting the age in the second block of code I got the output why is it so?

And if I use only two "==" sign then also I got the output but in case of "===" I didn't get the output.

age == 18 Got the output

Number(age)===18 Got the output

age === 18 Didn't got the output

Both the codes are given below.

With "==="

var age=prompt("Enter your age");
if(age<18){
  alert("Sorry, You are too young to drive this car Powering off");
}else if(age>18){
  alert("Powering On Enjoy the ride!");
}else if(age===18){
  alert("Congratulation on your first riding Enjoy the ride!");
}

With typecasting "Number(age)===18"

var age = prompt("What is your age?");
if (Number(age) < 18) {
  alert("Sorry, you are too young to drive this car. Powering off");
} else if (Number(age) > 18) {
  alert("Powering On. Enjoy the ride!");
} else if (Number(age) === 18) {
  alert("Congratulations on your first year of driving. Enjoy the ride!");
}

Body:
prompt always returns a value in string format.

Suppose a string and number have same value (say 18 and '18'). Here the value is same, only the type differs. Comparing a string value with a number will return true if only value is compared and false if type is also compared.

== compares two value without comparing the types. == is called as Abstract Equality Comparison which compares value only, not type. == will perform a type conversion when comparing two things.

console.log(18 == '18'); // Expect true

=== compares two value by comparing the types. === is called as Strict Equality Comparison this will compare both value and type

console.log(18 === '18'); // Expect false

In case of Number(age) === 18, the string age is converted to numeric age and hence this both the value is od type number. Hence this will return true

Read More on == and ===

const age = prompt("Enter your age");
console.log(`Type of Age = ${typeof age}`);
const numbericAge = +age; // String to number conversion, Same as Number(age)
console.log(`Type of Numeric Age = ${typeof numbericAge}`);
if (numbericAge < 18) {
  alert("Sorry, You are too young to drive this car Powering off");
} else if (numbericAge > 18) {
  alert("Powering On Enjoy the ride!");
} else if (numbericAge === 18) {
  alert("Congratulation on your first riding Enjoy the ride!");
}


问:
How to delete all files in folder except CSV?
I wrote a dataframe to a csv in Pyspark. And I got the output files in the directory as:

._SUCCESS.crc

.part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv.crc

part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv

How do I keep only the CSV file in the directory and delete rest of the files, using Python?

答:
import os
directory = "/path/to/directory/with/files"
files_in_directory = os.listdir(directory)
filtered_files = [file for file in files_in_directory if not file.endswith(".csv")]
for file in filtered_files:
    path_to_file = os.path.join(directory, file)
    os.remove(path_to_file)
```

first, you list all files in directory. Then, you only keep in list those, which don't end with .csv. And then, you remove all files that are left.

Body:
import os
directory = "/path/to/directory/with/files"
files_in_directory = os.listdir(directory)
filtered_files = [file for file in files_in_directory if not file.endswith(".csv")]
for file in filtered_files:
    path_to_file = os.path.join(directory, file)
    os.remove(path_to_file)

first, you list all files in directory. Then, you only keep in list those, which don't end with .csv. And then, you remove all files that are left.


问:
Send multiple array to view in codeigniter
I have two arrays, first is an array with its data is declared  on controller and the second is an array from a query operation. Both of them are not related to other. Lets name them $array1 and  $array2. Below is my controller

```<code>$array1['status'] = 'admin';
$array1['name'] = 'John';

$this->load->model('mymodel');
$array2 = $this->mymodel->get_all_row();

$this->load->view('my_view', $array1, $array2);
</code>```

Lets say the $array2 have 3 indexes id, name, price.

Need some helps.

答:
When you want to pass two arrays to your view, you need to convert the data array to a two-dimensional array.
For example, you have two arrays with the following names and contents:

```<code>[A1] => Array
    (
        [ID] => '1'
        [Name] => 'Jon'
    )

[A2] => Array
    (
        [Tell] => '123456'
        [Address] => 'Somware'
    )
</code>```

To pass two arrays, place them in the data array with different keys

```<code>$data['A1']=$A1;
$data['A2']=$A2;
</code>```

Result:

```<code>[data] => Array
(
    [A1] => Array
        (
            [ID] => '1'
            [Name] => 'Jon'
        )

    [A2] => Array
        (
            [Tell] => '123456'
            [Address] => 'Somware'
        )
)
</code>```

and use in view like this:

```<code>echo $A1['ID'];
echo $A1['Name'];
echo $A2['Tell'];
echo $A2['Address'];
</code>```

Body:
I have two arrays, first is an array with its data is declared  on controller and the second is an array from a query operation. Both of them are not related to other. Lets name them $array1 and  $array2. Below is my controller

$array1['status'] = 'admin';
$array1['name'] = 'John';

$this->load->model('mymodel');
$array2 = $this->mymodel->get_all_row();

$this->load->view('my_view', $array1, $array2);

Lets say the $array2 have 3 indexes id, name, price.

Need some helps.

Body:
When you want to pass two arrays to your view, you need to convert the data array to a two-dimensional array.
For example, you have two arrays with the following names and contents:

[A1] => Array
    (
        [ID] => '1'
        [Name] => 'Jon'
    )

[A2] => Array
    (
        [Tell] => '123456'
        [Address] => 'Somware'
    )

To pass two arrays, place them in the data array with different keys

$data['A1']=$A1;
$data['A2']=$A2;

Result:

[data] => Array
(
    [A1] => Array
        (
            [ID] => '1'
            [Name] => 'Jon'
        )

    [A2] => Array
        (
            [Tell] => '123456'
            [Address] => 'Somware'
        )
)

and use in view like this:

echo $A1['ID'];
echo $A1['Name'];
echo $A2['Tell'];
echo $A2['Address'];


问:
Codable class doesn't conform to protocol 'Decodable'
Try to add enum Codingkeys inside struct, But it show error Codable doesn't conform Decodable.

Why am i getting conform decodable error? Should i seperate the struct ?

```<code>struct Model: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?

    enum CodingKeys: String, CodingKey {
           case aps ,link, alert,sound,title,body
           case checkAction = "gcm.notificaiton.check_action"
    }

    struct Aps: Codable {
        let alert: Alert
        let sound: String?

        struct Alert: Codable {
            let title: String?
            let body: String?
        }
    }

}
</code>```

Is it a must to seperate the struct like below ?

```<code>struct FCMModel: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?

    enum CodingKeys: String, CodingKey {
           case aps ,link
           case checkAction = "gcm.notificaiton.check_action"
    }

}
struct Aps: Codable {
    let alert: Alert
    let sound: String?

    struct Alert: Codable {
        let title: String?
        let body: String?
    }
}
</code>```

答:
It is not necessary to separate the structs. The error occurs because you have added too many keys in the CodingKeys enum. If you keep only the required ones, then it will work:

```<code>struct Model: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?

    enum CodingKeys: String, CodingKey {
           case aps ,link
           case checkAction = "gcm.notificaiton.check_action"
    }

    struct Aps: Codable {
        let alert: Alert
        let sound: String?

        struct Alert: Codable {
            let title: String?
            let body: String?
        }
    }
}
</code>```

alert, sound etc are not coding keys of Model. They are coding keys of Aps. It is not necessary to specify them in Aps, because they are the same as the property names.

Body:
Try to add enum Codingkeys inside struct, But it show error Codable doesn't conform Decodable.

Why am i getting conform decodable error? Should i seperate the struct ?

struct Model: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?

    enum CodingKeys: String, CodingKey {
           case aps ,link, alert,sound,title,body
           case checkAction = "gcm.notificaiton.check_action"
    }

    struct Aps: Codable {
        let alert: Alert
        let sound: String?

        struct Alert: Codable {
            let title: String?
            let body: String?
        }
    }

}

Is it a must to seperate the struct like below ?

struct FCMModel: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?

    enum CodingKeys: String, CodingKey {
           case aps ,link
           case checkAction = "gcm.notificaiton.check_action"
    }

}
struct Aps: Codable {
    let alert: Alert
    let sound: String?

    struct Alert: Codable {
        let title: String?
        let body: String?
    }
}

Body:
It is not necessary to separate the structs. The error occurs because you have added too many keys in the CodingKeys enum. If you keep only the required ones, then it will work:

struct Model: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?

    enum CodingKeys: String, CodingKey {
           case aps ,link
           case checkAction = "gcm.notificaiton.check_action"
    }

    struct Aps: Codable {
        let alert: Alert
        let sound: String?

        struct Alert: Codable {
            let title: String?
            let body: String?
        }
    }
}

alert, sound etc are not coding keys of Model. They are coding keys of Aps. It is not necessary to specify them in Aps, because they are the same as the property names.


答:
Try iterating over the files in the directory, and then os.remove only those files that do not end with .csv.

```<code>import os
dir_path = "path/to/the/directory/containing/files"
dir_list = os.listdir(dir_path)
for item in dir_list:
    if not item.endswith(".csv"):
        os.remove(os.path.join(dir_path, item))
</code>```

Title: How to delete all files in folder except CSV?

Body:
I wrote a dataframe to a csv in Pyspark. And I got the output files in the directory as:

._SUCCESS.crc

.part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv.crc

part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv

How do I keep only the CSV file in the directory and delete rest of the files, using Python?

Body:
Try iterating over the files in the directory, and then os.remove only those files that do not end with .csv.

import os
dir_path = "path/to/the/directory/containing/files"
dir_list = os.listdir(dir_path)
for item in dir_list:
    if not item.endswith(".csv"):
        os.remove(os.path.join(dir_path, item))