问:
How to check if input is numeric in C++
I want to create a program that takes in integer input from the user and then terminates when the user doesn't enter anything at all (ie, just presses enter). However, I'm having trouble validating the input (making sure that the user is inputting integers, not strings. atoi() won't work, since the integer inputs can be more than one digit.

What is the best way of validating this input? I tried something like the following, but I'm not sure how to complete it:

```<code>char input

while( cin>>input != '\n')
{
     //some way to check if input is a valid number
     while(!inputIsNumeric)
     {
         cin>>input;
     }
}
</code>```

答:
Something that can be done is read text input and then try to convert that to a number:

```<code>try
{
    std::string str;
    std::getline(std::cin, str)
    age = std::stoi(str)
}
catch(...)
{
    // ...
}
</code>```

Then you can handle the errors by catching the exceptions.

https://en.cppreference.com/w/cpp/string/basic_string/stol

Title: How to check if input is numeric in C++

Body:
I want to create a program that takes in integer input from the user and then terminates when the user doesn't enter anything at all (ie, just presses enter). However, I'm having trouble validating the input (making sure that the user is inputting integers, not strings. atoi() won't work, since the integer inputs can be more than one digit.

What is the best way of validating this input? I tried something like the following, but I'm not sure how to complete it:

char input

while( cin>>input != '\n')
{
     //some way to check if input is a valid number
     while(!inputIsNumeric)
     {
         cin>>input;
     }
}

Body:
Something that can be done is read text input and then try to convert that to a number:

try
{
    std::string str;
    std::getline(std::cin, str)
    age = std::stoi(str)
}
catch(...)
{
    // ...
}

Then you can handle the errors by catching the exceptions.

https://en.cppreference.com/w/cpp/string/basic_string/stol


来源: stackexchange

问:
Who to control browser level zoom that should work with all cross platform browser
I am looking for JS script to control browser's zoom.

I have tried the "document.body.style.zoom", but this doesn't work with Firefox.

Thanks you.

答:
The browser's zoom level cannot be controlled via JavaScript, fortunately. It's a user-controlled setting.[1]

The zoom CSS property indeed does a similar thing - not only it scales the element but it also scales it's rendered size, affecting the page's layout. However, unlike changing the browser's zoom level, the zoom property does not affect media queries (tested on Chrome) so even if applied to the  or  element the result may be different than changing the browser's zoom. The other problem is that the zoom property is not standard and not supported cross-browsers.

An alternative is to apply a transformation like transform: scale(2); or transform: scale(0.5); . However transformations only change the element visually and not the rendered size, so you will need to handle that too. The following code seems to mimic a zoom level of 50% reasonably:

```<code>:root {
    width: 200%;
    transform: scale(0.5);
    transform-origin: 0 0;
}
</code>```

[1] It can be controlled by browser extensions privileged JS, but that's out of question. There is also a <meta> tag setting that controls zoom level but it's only for smartphones and can also be overriden by browser settings.

ContentLicense: CC BY-SA 4.0

Body:
The browser's zoom level cannot be controlled via JavaScript, fortunately. It's a user-controlled setting.[1]

The zoom CSS property indeed does a similar thing - not only it scales the element but it also scales it's rendered size, affecting the page's layout. However, unlike changing the browser's zoom level, the zoom property does not affect media queries (tested on Chrome) so even if applied to the <html> or <body> element the result may be different than changing the browser's zoom. The other problem is that the zoom property is not standard and not supported cross-browsers.

An alternative is to apply a transformation like transform: scale(2); or transform: scale(0.5); . However transformations only change the element visually and not the rendered size, so you will need to handle that too. The following code seems to mimic a zoom level of 50% reasonably:

:root {
    width: 200%;
    transform: scale(0.5);
    transform-origin: 0 0;
}

[1] It can be controlled by browser extensions privileged JS, but that's out of question. There is also a <meta> tag setting that controls zoom level but it's only for smartphones and can also be overriden by browser settings.


问:
'Uploads' object is not iterable in Django
I am trying to have each model object have it's own page with all the other model objects attached to it, using the modal id, I tried using the {{ img.queryset.all.id }} html tag to display the photo, but that didn't work. I know the problem is in either the views.py or single_page.html, and maybe the models.py but I believe that is unlikely the problem. When I click onto the photo it bring it to a page with the photo icon, it doesn't display it because the photo is unknown. While every time I use {% for x in img %} it says 'Uploads' object is not integrable. If anyone could help that would be great.

modals.py

```<code>
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
    first_name = models.CharField(max_length = 50, null = True, blank = True)
    last_name = models.CharField(max_length = 50, null = True, blank = True)
    phone = models.CharField(max_length = 50, null = True, blank = True)
    email = models.EmailField(max_length = 50, null = True, blank = True)
    bio = models.TextField(max_length = 300, null = True, blank = True)
    profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)

    def __str__(self):
        return f'{self.user.username} Profile'

class Uploads(models.Model):
    title = models.CharField(max_length = 500, null = True,)
    artiste = models.CharField(max_length=500, null = True,)
    album = models.ForeignKey('Album', on_delete=models.SET_NULL,null=True,blank=True)
    time_length=models.DecimalField(max_digits=20, decimal_places=2,blank=True, null = True,)
    audio_file=models.FileField(upload_to='musics/',validators=[validate_is_audio], null = True,)

    caption = models.CharField(max_length = 100, blank=True)
    file = models.ImageField(upload_to = "img/%y", null = True)
    profile = models.ForeignKey(Profile, on_delete = models.CASCADE, default = None, null = True)
    id = models.AutoField(primary_key = True, null = False)

    def __str__(self):
        return str(self.file) and f"{self.id}"

class Album(models.Model):
    name=models.CharField(max_length=400)

</code>```

views.py

```<code>def profile(request, user):
    img = Uploads.objects.filter(profile_id = request.user.profile)         #Make sure only your account *images stays on the page
    profile = Profile.objects.filter(user = request.user)
    context = {"profile": profile, "img": img}

    return render(request, "main/profile.html", context)

def single_page(request, id):
    img = Uploads.objects.filter(id = id).first()
    profile = Uploads.objects.filter(id = request.user.id)

    context = { "img": img, "profile": profile}

    return render(request, "main/single_page.html", context)

</code>```

single_page.html

```<code>{% block content %}
<body>

    {% for x in img %}
    <p>{{title}}</p>

    <img src="{{x.file.url}}" height="100%" width="100%"  class="myImg">
    {% endfor %}

</body>
{% endblock %}

</code>```

答:
Since you are filtering through the profile by id and also specifying first it wouldn't be possible to loop through as first would render the first object and so the loop will only work with you adding (img.all) by doing something like this:

```<code># Your view.py
def single_page(request, id):
    img = Uploads.objects.filter(id=id)
    profile = Uploads.objects.filter(id = request.user.id)

    context = { "img": img, "profile": profile}

    return render(request, "main/single_page.html", context)
</code>```

Your Html

```<code>
{% block content %}
<body>
    {% for x in img.all %}
    <p>{{title}}</p>

    <img src="{{x.file.url}}" height="100%" width="100%"  class="myImg">
    {% endfor %}

</body>
{% endblock %}
</code>```

Body:
I am trying to have each model object have it's own page with all the other model objects attached to it, using the modal id, I tried using the {{ img.queryset.all.id }} html tag to display the photo, but that didn't work. I know the problem is in either the views.py or single_page.html, and maybe the models.py but I believe that is unlikely the problem. When I click onto the photo it bring it to a page with the photo icon, it doesn't display it because the photo is unknown. While every time I use {% for x in img %} it says 'Uploads' object is not integrable. If anyone could help that would be great.

modals.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
    first_name = models.CharField(max_length = 50, null = True, blank = True)
    last_name = models.CharField(max_length = 50, null = True, blank = True)
    phone = models.CharField(max_length = 50, null = True, blank = True)
    email = models.EmailField(max_length = 50, null = True, blank = True)
    bio = models.TextField(max_length = 300, null = True, blank = True)
    profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)

    def __str__(self):
        return f'{self.user.username} Profile'

class Uploads(models.Model):
    title = models.CharField(max_length = 500, null = True,)
    artiste = models.CharField(max_length=500, null = True,)
    album = models.ForeignKey('Album', on_delete=models.SET_NULL,null=True,blank=True)
    time_length=models.DecimalField(max_digits=20, decimal_places=2,blank=True, null = True,)
    audio_file=models.FileField(upload_to='musics/',validators=[validate_is_audio], null = True,)

    caption = models.CharField(max_length = 100, blank=True)
    file = models.ImageField(upload_to = "img/%y", null = True)
    profile = models.ForeignKey(Profile, on_delete = models.CASCADE, default = None, null = True)
    id = models.AutoField(primary_key = True, null = False)

    def __str__(self):
        return str(self.file) and f"{self.id}"

class Album(models.Model):
    name=models.CharField(max_length=400)

views.py

def profile(request, user):
    img = Uploads.objects.filter(profile_id = request.user.profile)         #Make sure only your account *images stays on the page
    profile = Profile.objects.filter(user = request.user)
    context = {"profile": profile, "img": img}

    return render(request, "main/profile.html", context)

def single_page(request, id):
    img = Uploads.objects.filter(id = id).first()
    profile = Uploads.objects.filter(id = request.user.id)

    context = { "img": img, "profile": profile}

    return render(request, "main/single_page.html", context)

single_page.html

{% block content %}

    {% for x in img %}

{{title}}

    {% endfor %}

{% endblock %}

Body:
Since you are filtering through the profile by id and also specifying first it wouldn't be possible to loop through as first would render the first object and so the loop will only work with you adding (img.all) by doing something like this:

# Your view.py
def single_page(request, id):
    img = Uploads.objects.filter(id=id)
    profile = Uploads.objects.filter(id = request.user.id)

    context = { "img": img, "profile": profile}

    return render(request, "main/single_page.html", context)

Your Html

{% block content %}
<body>
    {% for x in img.all %}
    <p>{{title}}</p>

    <img src="{{x.file.url}}" height="100%" width="100%"  class="myImg">
    {% endfor %}

</body>
{% endblock %}


问:
How to write text on top of rectangle instead of below?
I'm trying to create a rectangle with text on top, but the text shows below the rectangle.

How can I make the text go to the front layer?

My code so far:

from turtle import Turtle

class Rectangle(Turtle):
    def __init__(self, x, y, width, height, color='white'):
        super().__init__()
        self.penup()
        self.goto(x, y)
        self.color(color)
        self.shape('square')
        self.shapesize(stretch_wid=(height / 20), stretch_len=(width / 20))

class Writer(Turtle):
    def __init__(self, x, y):
        super().__init__()
        self.penup()
        self.goto(x, y)
        self.hideturtle()

    def writetext(self, text, font="Arial", size=8, textType="normal", color="black", x=None, y=None):
        if x is None:
            x = self.xcor()
        if y is None:
            y = self.ycor()
        self.goto(x, y)
        self.color(color)
        self.write(text, move=False, align="center", font=(font, size, textType))

class Button(Rectangle):
    def __init__(self, position, width, height, text, onclick, color="gray"):
        position = list(position)
        super().__init__(position[0], position[1], width, height, color)
        writer = Writer(position[0], position[1])
        writer.writetext(text, color="white")
        self.goto(position[0], position[1])
        self.color(color)
        self.onclick(onclick)

def start_game(_arg1=None, _arg2=None):  # requires arguments since Python turtle module passes two in when calling it using onclick
    print('game started')

Button((0, 0), 50, 20, 'click me to start the game', start_game)

```

I've been searching on google for over half an hour and couldn't find anything

答:
I believe the design has some fundamental flaws that arise from subclassing Turtle.

The issue is that the Button drawing is happening outside of the constructor where the text is written. The drawing function is called automatically by the turtle library. Regardless of whether you're hooking into Turtle's classes or not, a constructor isn't typically the ideal place to draw things for this reason. I don't see a clean way to make a Button out of two separate turtles with subclassing.

A quick (but poor) fix is to override the internal method that turtle calls to update the object so your button can inject the text after the super() call draws the rectangle (you could also try to hook into drawing with _drawturtle):

class Button(Rectangle):
    # ....

    def _update(self):
        super()._update()
        Writer(*self.position()).writetext("foobar", color="white")
```
<p>But since the leading <code>_</code> indicates a private, internal method, this is circumventing the turtle API -- not a good idea.</p>
<p>A second try would be to disable the internal update loop with <code>turtle.tracer(0)</code> and take control of the update loop manually, but then that seems to defeat the purpose of subclassing <code>Turtle</code>, which is that you want things to "just work" automatically.</p>
<p>There's a deeper problem here, though, which is that once you get your text on top of the button as shown above in the workaround, the text blocks clicks from being detected by the rectangle underneath it.</p>
<p>After playing around with it quite a bit, the best alternatives I came up with were to create an image with the text pre-rendered in, or else use a global click listener and use the coordinates to determine if the click occurred on the button. The following code isn't reusable, but it's a proof of concept that you could abstract into a function or class by parameterizing everything:</p>
<pre class="lang-py prettyprint-override"><code>import turtle
from turtle import Turtle

def handle_btn_click(x, y):
    if (x > -btn_size and y > -btn_size / 2 and
            x < btn_size and y < btn_size / 2):
        print("game started")
        turtle.tracer(1)
        turtle.clearscreen()
        turtle.bye()

turtle.tracer(0)
r = Turtle(shape="square")
btn_size = 80
r.shapesize(btn_size // 20, btn_size // 10)
r.color("black")
turtle.update()
t = Turtle()
t.color("white")
t.ht()
text = "click me to start the game"
t.write(text, move=False, align="center", font=("Arial", 8, "normal"))
turtle.Screen().onclick(handle_btn_click)
turtle.mainloop()
</code>```

As a final note, if you're only adding a single button, I suggest keeping it simple and imperative. A class structure is often overkill for most turtle apps, and the large parameter lists are a pain to deal with for only a single instance.

Body:
I'm trying to create a rectangle with text on top, but the text shows below the rectangle.

How can I make the text go to the front layer?

My code so far:

from turtle import Turtle

class Rectangle(Turtle):
    def __init__(self, x, y, width, height, color='white'):
        super().__init__()
        self.penup()
        self.goto(x, y)
        self.color(color)
        self.shape('square')
        self.shapesize(stretch_wid=(height / 20), stretch_len=(width / 20))

class Writer(Turtle):
    def __init__(self, x, y):
        super().__init__()
        self.penup()
        self.goto(x, y)
        self.hideturtle()

    def writetext(self, text, font="Arial", size=8, textType="normal", color="black", x=None, y=None):
        if x is None:
            x = self.xcor()
        if y is None:
            y = self.ycor()
        self.goto(x, y)
        self.color(color)
        self.write(text, move=False, align="center", font=(font, size, textType))

class Button(Rectangle):
    def __init__(self, position, width, height, text, onclick, color="gray"):
        position = list(position)
        super().__init__(position[0], position[1], width, height, color)
        writer = Writer(position[0], position[1])
        writer.writetext(text, color="white")
        self.goto(position[0], position[1])
        self.color(color)
        self.onclick(onclick)

def start_game(_arg1=None, _arg2=None):  # requires arguments since Python turtle module passes two in when calling it using onclick
    print('game started')

Button((0, 0), 50, 20, 'click me to start the game', start_game)

I've been searching on google for over half an hour and couldn't find anything

Body:
I believe the design has some fundamental flaws that arise from subclassing Turtle.

The issue is that the Button drawing is happening outside of the constructor where the text is written. The drawing function is called automatically by the turtle library. Regardless of whether you're hooking into Turtle's classes or not, a constructor isn't typically the ideal place to draw things for this reason. I don't see a clean way to make a Button out of two separate turtles with subclassing.

A quick (but poor) fix is to override the internal method that turtle calls to update the object so your button can inject the text after the super() call draws the rectangle (you could also try to hook into drawing with _drawturtle):

class Button(Rectangle):
    # ....

    def _update(self):
        super()._update()
        Writer(*self.position()).writetext("foobar", color="white")

But since the leading _ indicates a private, internal method, this is circumventing the turtle API -- not a good idea.

A second try would be to disable the internal update loop with turtle.tracer(0) and take control of the update loop manually, but then that seems to defeat the purpose of subclassing Turtle, which is that you want things to "just work" automatically.

There's a deeper problem here, though, which is that once you get your text on top of the button as shown above in the workaround, the text blocks clicks from being detected by the rectangle underneath it.

After playing around with it quite a bit, the best alternatives I came up with were to create an image with the text pre-rendered in, or else use a global click listener and use the coordinates to determine if the click occurred on the button. The following code isn't reusable, but it's a proof of concept that you could abstract into a function or class by parameterizing everything:

import turtle
from turtle import Turtle

def handle_btn_click(x, y):
    if (x > -btn_size and y > -btn_size / 2 and
            x < btn_size and y < btn_size / 2):
        print("game started")
        turtle.tracer(1)
        turtle.clearscreen()
        turtle.bye()

turtle.tracer(0)
r = Turtle(shape="square")
btn_size = 80
r.shapesize(btn_size // 20, btn_size // 10)
r.color("black")
turtle.update()
t = Turtle()
t.color("white")
t.ht()
text = "click me to start the game"
t.write(text, move=False, align="center", font=("Arial", 8, "normal"))
turtle.Screen().onclick(handle_btn_click)
turtle.mainloop()

As a final note, if you're only adding a single button, I suggest keeping it simple and imperative. A class structure is often overkill for most turtle apps, and the large parameter lists are a pain to deal with for only a single instance.


答:
If img is an object, you cannot iterate over it, so for loop is not valid idea. You should be able to access it's url with: {{ img.file.url }}.

Don't use id as variable, it's builtin function. Don't filter Uploads.id by request.user.id because it's not going to work. It's different model.

For single photo you should do in views:

```<code>from django.shortcuts import get_object_or_404

def single_page(request, img_id):
    img = get_object_or_404(Uploads, id=img_id)

    context = {"img": img}

    return render(request, "main/single_page.html", context)
</code>```

single_page.html:

```<code>{% block content %}
<body>

    <p>{{ img.title }}</p>

    <img src="{{ img.file.url }}" height="100%" width="100%"  class="myImg">

</body>
{% endblock %}
</code>```

If you have more pictures of one User, you can find them with:

```<code>images = Uploads.objects.filter(profile=self.request.user.profile)
context = {"images": images}
</code>```

And in template:

```<code>{% for img in images %}

    <p>{{ img.title }}</p>

    <img src="{{ img.file.url }}" height="100%" width="100%" class="myImg">

{% endfor %}
</code>```

And if you want to get profile, don't search it with filter, because you will get QuerySet, not an object instance. To get single object you should do as I've showed you before:

```<code>profile = get_object_or_404(Profile, user=request.user)
# or
profile = Profile.objects.get(user=request.user)
</code>```

or if you really, really prefer filter method:

```<code>profile = Profile.objects.filter(user=request.user).first()
</code>```

Title: 'Uploads' object is not iterable in Django

Body:
If img is an object, you cannot iterate over it, so for loop is not valid idea. You should be able to access it's url with: {{ img.file.url }}.

Don't use id as variable, it's builtin function. Don't filter Uploads.id by request.user.id because it's not going to work. It's different model.

For single photo you should do in views:

from django.shortcuts import get_object_or_404

def single_page(request, img_id):
    img = get_object_or_404(Uploads, id=img_id)

    context = {"img": img}

    return render(request, "main/single_page.html", context)

single_page.html:

{% block content %}
<body>

    <p>{{ img.title }}</p>

    <img src="{{ img.file.url }}" height="100%" width="100%"  class="myImg">

</body>
{% endblock %}

If you have more pictures of one User, you can find them with:

images = Uploads.objects.filter(profile=self.request.user.profile)
context = {"images": images}

And in template:

{% for img in images %}

    <p>{{ img.title }}</p>

    <img src="{{ img.file.url }}" height="100%" width="100%" class="myImg">

{% endfor %}

And if you want to get profile, don't search it with filter, because you will get QuerySet, not an object instance. To get single object you should do as I've showed you before:

profile = get_object_or_404(Profile, user=request.user)
# or
profile = Profile.objects.get(user=request.user)

or if you really, really prefer filter method:

profile = Profile.objects.filter(user=request.user).first()


问:
How do I left or right justify, text within specific columns of a table in HTML,CSS
In the following code, I need to left justify the text in the first two columns and right justify the text in the last 4 columns with the exception of the table headers. Can't seem to figure it out and when I look for answers online I can't find anything on how to justify text within the cell of a table or specifically texts of just two columns. Would appreciate any help. Thanks

<!DOCTYPE html>

Top 10 Stocks

    Symbol
    Company
    Market Cap
    Price
    Dividend
    5-Year Growth

    MSFT
    Microsoft Corporation
    2.31T
    308.79
    .80%
    404.02%

    AAPL
    Apple Inc.
    2.78T
    173.04
    .52%
    493.54%

    AMZN
    Amazon.com Inc.
    1.46T
    2960.99
    N/A
    244.54%

```

答:
If you don't want to use a class, you can add the following style

```<code>td + td + td {
    text-align: right;
}
</code>```

or

```<code>td:nth-child(n+3) {
    text-align: right;
}
</code>```

I hope this worked for you!

Body:
If you don't want to use a class, you can add the following style

td + td + td {
    text-align: right;
}

or

td:nth-child(n+3) {
    text-align: right;
}

I hope this worked for you!


问:
Is there a simpler version of renaming columns with alternating patterns? Or tidyverse methods?

My Data

So I have a data frame that I am working with below:

```<code>structure(list(V1 = c(3L, 3L, 3L, 2L, 4L, 1L), V2 = c(1L, 1L,
1L, 1L, 1L, 1L), V3 = c(2L, 2L, 2L, 1L, 3L, 2L), V4 = c(2L, 2L,
3L, 1L, 1L, 1L), V5 = c(3L, 3L, 4L, 1L, 3L, 3L), V6 = c(3L, 3L,
4L, 3L, 3L, 3L), V7 = c(2L, 2L, 1L, 1L, 3L, 3L), V8 = c(3L, 3L,
4L, 4L, 3L, 3L), V9 = c(3L, 3L, 3L, 2L, 3L, 3L), V10 = c(2L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")
</code>```

It looks like this:

```<code> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  3  1  2  2  3  3  2  3  3   2
2  3  1  2  2  3  3  2  3  3   2
3  3  1  2  3  4  4  1  4  3   1
4  2  1  1  1  1  3  1  4  2   1
5  4  1  3  1  3  3  3  3  3   1
6  1  1  2  1  3  3  3  3  3   1
</code>```

Solution So Far

The best code I have come up with for renaming the variables quickly is this:

```<code>new_names <- outer("cope",
                   1:10,
                   paste,
                   sep="_")
names(data1) <- new_names
data1
</code>```

Which gives me this data frame:

```<code>  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1
</code>```

Question

While this serves my purpose well enough, it has made me consider two questions for the future. First, is there a way to simplify the code down in order to make it one line? I was thinking something that worked within dplyr if possible because that is what I am most accustomed to working with.

Second, I foresee issues on the horizon if there are, say, 30 variables, with some having repeating patterns and some being unique. What is the most economical use of time when renaming variables like these? I know rep is one option, but I am only aware of how it can repeat but not separate values into multiple patterns. I'm thinking along the lines of something like this, which would be easier to write with some kind of pattern and stops:

```<code>names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
</code>```

For example:

```<code>names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
colnames(data1) <- names
data1

  v1 v2 v3 c1 c2 c3 u p z1 z2
1   3  1  2  2  3  3 2 3  3  2
2   3  1  2  2  3  3 2 3  3  2
3   3  1  2  3  4  4 1 4  3  1
4   2  1  1  1  1  3 1 4  2  1
5   4  1  3  1  3  3 3 3  3  1
6   1  1  2  1  3  3 3 3  3  1
7   3  1  3  1  3  2 2 2  3  2
8   3  2  1  2  3  2 3 3  2  1
9   3  2  4  1  2  4 2 3  4  1
10  4  2  4  2  3  4 3 3  4  1
</code>```

This is time-consuming if you spell it out manually:

```<code>names <- c("cope_1", "cope_2","cope_3","sad_1","sad_2","sad_3","u","p","zip_1","zip_2")
colnames(data1) <- names
data1
</code>```

Which does get you what you want, yet slowly:

```<code>  cope_1 cope_2 cope_3 sad_1 sad_2 sad_3 u p zip_1 zip_2
1      3      1      2     2     3     3 2 3     3     2
2      3      1      2     2     3     3 2 3     3     2
3      3      1      2     3     4     4 1 4     3     1
4      2      1      1     1     1     3 1 4     2     1
5      4      1      3     1     3     3 3 3     3     1
6      1      1      2     1     3     3 3 3     3     1
</code>```

And something like outer doesnt seem to fit here:

```<code>outer("cope",
      1:3,
      paste,
      sep="_",
      "sad",
      1:3,
      paste,
      sep="_",
      "u",
      "p")
</code>```

So if there is a better way of naming chunks of variables like this, that would be great to know.

答:
If you have a vector x with the names and a vector r with the number of replications, then you could do:

x <- c("v", "c", "u", "p", "z")
r <- c(3L, 3L, 1L, 1L, 3L)

f <- function(n) if (n > 1L) seq_len(n) else character(n)
paste0(rep(x, r), unlist(lapply(r, f)))
## [1] "v1" "v2" "v3" "c1" "c2" "c3" "u"  "p"  "z1" "z2" "z3"
```
<p>If you are fine with <code>"u1"</code> and <code>"p1"</code>, then you can simplify a bit:</p>
<pre class="lang-r prettyprint-override"><code>paste0(rep(x, r), unlist(lapply(r, seq_len)))
## [1] "v1" "v2" "v3" "c1" "c2" "c3" "u1" "p1" "z1" "z2" "z3"
</code>```

There is also base R's make.unique. It is more literate, but it awkwardly only numbers duplicates, so it doesn't quite give you what you want:

make.unique(rep(x, r), sep = "")
## [1] "v"  "v1" "v2" "c"  "c1" "c2" "u"  "p"  "z"  "z1" "z2"
```

Body:
My Data

So I have a data frame that I am working with below:

structure(list(V1 = c(3L, 3L, 3L, 2L, 4L, 1L), V2 = c(1L, 1L,
1L, 1L, 1L, 1L), V3 = c(2L, 2L, 2L, 1L, 3L, 2L), V4 = c(2L, 2L,
3L, 1L, 1L, 1L), V5 = c(3L, 3L, 4L, 1L, 3L, 3L), V6 = c(3L, 3L,
4L, 3L, 3L, 3L), V7 = c(2L, 2L, 1L, 1L, 3L, 3L), V8 = c(3L, 3L,
4L, 4L, 3L, 3L), V9 = c(3L, 3L, 3L, 2L, 3L, 3L), V10 = c(2L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")

It looks like this:

 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  3  1  2  2  3  3  2  3  3   2
2  3  1  2  2  3  3  2  3  3   2
3  3  1  2  3  4  4  1  4  3   1
4  2  1  1  1  1  3  1  4  2   1
5  4  1  3  1  3  3  3  3  3   1
6  1  1  2  1  3  3  3  3  3   1

Solution So Far

The best code I have come up with for renaming the variables quickly is this:

new_names <- outer("cope",
                   1:10,
                   paste,
                   sep="_")
names(data1) <- new_names
data1

Which gives me this data frame:

  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1

Question

While this serves my purpose well enough, it has made me consider two questions for the future. First, is there a way to simplify the code down in order to make it one line? I was thinking something that worked within dplyr if possible because that is what I am most accustomed to working with.

Second, I foresee issues on the horizon if there are, say, 30 variables, with some having repeating patterns and some being unique. What is the most economical use of time when renaming variables like these? I know rep is one option, but I am only aware of how it can repeat but not separate values into multiple patterns. I'm thinking along the lines of something like this, which would be easier to write with some kind of pattern and stops:

names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")

For example:

names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
colnames(data1) <- names
data1

  v1 v2 v3 c1 c2 c3 u p z1 z2
1   3  1  2  2  3  3 2 3  3  2
2   3  1  2  2  3  3 2 3  3  2
3   3  1  2  3  4  4 1 4  3  1
4   2  1  1  1  1  3 1 4  2  1
5   4  1  3  1  3  3 3 3  3  1
6   1  1  2  1  3  3 3 3  3  1
7   3  1  3  1  3  2 2 2  3  2
8   3  2  1  2  3  2 3 3  2  1
9   3  2  4  1  2  4 2 3  4  1
10  4  2  4  2  3  4 3 3  4  1

This is time-consuming if you spell it out manually:

names <- c("cope_1", "cope_2","cope_3","sad_1","sad_2","sad_3","u","p","zip_1","zip_2")
colnames(data1) <- names
data1

Which does get you what you want, yet slowly:

  cope_1 cope_2 cope_3 sad_1 sad_2 sad_3 u p zip_1 zip_2
1      3      1      2     2     3     3 2 3     3     2
2      3      1      2     2     3     3 2 3     3     2
3      3      1      2     3     4     4 1 4     3     1
4      2      1      1     1     1     3 1 4     2     1
5      4      1      3     1     3     3 3 3     3     1
6      1      1      2     1     3     3 3 3     3     1

And something like outer doesnt seem to fit here:

outer("cope",
      1:3,
      paste,
      sep="_",
      "sad",
      1:3,
      paste,
      sep="_",
      "u",
      "p")

So if there is a better way of naming chunks of variables like this, that would be great to know.

Body:
If you have a vector x with the names and a vector r with the number of replications, then you could do:

x <- c("v", "c", "u", "p", "z")
r <- c(3L, 3L, 1L, 1L, 3L)

f <- function(n) if (n > 1L) seq_len(n) else character(n)
paste0(rep(x, r), unlist(lapply(r, f)))
## [1] "v1" "v2" "v3" "c1" "c2" "c3" "u"  "p"  "z1" "z2" "z3"

If you are fine with "u1" and "p1", then you can simplify a bit:

paste0(rep(x, r), unlist(lapply(r, seq_len)))
## [1] "v1" "v2" "v3" "c1" "c2" "c3" "u1" "p1" "z1" "z2" "z3"

There is also base R's make.unique. It is more literate, but it awkwardly only numbers duplicates, so it doesn't quite give you what you want:

make.unique(rep(x, r), sep = "")
## [1] "v"  "v1" "v2" "c"  "c1" "c2" "u"  "p"  "z"  "z1" "z2"


问:
Upload an input image taken from webapp into google drive with google script
I found something similar here, but it seems a lot more complicated than what I need.

I am uploading an image to a webapp and I would like to save the image into google drive.

I am having troubles to pass the file in a readable format for DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(file); and I keep getting error. I do not know how to pass the file in the correct format.

HTML:

```<code><input id = "output2" type="file" accept="image/*">
<script>
document.getElementById('output2').addEventListener('change', (e) => triggerF(e.target.files));

</script>

function triggerF(file) {

console.log("event triggered");
console.log(file.name);
google.script.run.withSuccessHandler(yourCallBack1).upload(file)}

function yourCallBack1() {
  console.log("callback called");
  }
</code>```

GS:

```<code>function upload(e) {

const file = new Blob(e);
const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(file);
console.log("created file");

}
</code>```

UPDATE: Tanaike's solution #2 works for me. Please check below.

答:
I believe your goal is as follows.

From I am uploading an image to a webapp and I would like to save the image into google drive., you want to upload an image file using Web Apps.

In this case, how about the following modification?

Modified script 1:

Fortunately, the bug of the parse of HTML form has been removed. Ref By this, you can use the following modified script.

HTML & Javascript side:

<form><input id = "output2" name="file" type="file" accept="image/*"></form>

```
<h4>Google Apps Script side:</h4>
<pre class="lang-js prettyprint-override"><code>function upload(e) {
  const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(e.file);
  console.log("created file");
}
</code>```

Modified script 2:

As another method, you can also use the following script.

HTML & Javascript side:

<input id = "output2" type="file" accept="image/*">

```
<h4>Google Apps Script side:</h4>
<pre class="lang-js prettyprint-override"><code>function upload(e) {
  const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(Utilities.newBlob(...e));
  console.log("created file");
}
</code>```

Note:

In your script, it seems that Web Apps is used. In this case, when you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

Body:
I found something similar here, but it seems a lot more complicated than what I need.

I am uploading an image to a webapp and I would like to save the image into google drive.

I am having troubles to pass the file in a readable format for DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(file); and I keep getting error. I do not know how to pass the file in the correct format.

HTML:

<input id = "output2" type="file" accept="image/*">

function triggerF(file) {

console.log("event triggered");
console.log(file.name);
google.script.run.withSuccessHandler(yourCallBack1).upload(file)}

function yourCallBack1() {
  console.log("callback called");
  }

GS:

function upload(e) {

const file = new Blob(e);
const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(file);
console.log("created file");

}

UPDATE: Tanaike's solution #2 works for me. Please check below.

Body:
I believe your goal is as follows.

From I am uploading an image to a webapp and I would like to save the image into google drive., you want to upload an image file using Web Apps.

In this case, how about the following modification?

Modified script 1:

Fortunately, the bug of the parse of HTML form has been removed. Ref By this, you can use the following modified script.

HTML & Javascript side:

<form><input id = "output2" name="file" type="file" accept="image/*"></form>
<script>
document.getElementById('output2').addEventListener('change', (e) => triggerF(e.target.parentNode));

function triggerF(file) {
  console.log("event triggered");
  google.script.run.withSuccessHandler(yourCallBack1).upload(file);
}

function yourCallBack1() {
  console.log("callback called");
}
</script>

Google Apps Script side:

function upload(e) {
  const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(e.file);
  console.log("created file");
}

Modified script 2:

As another method, you can also use the following script.

HTML & Javascript side:

<input id = "output2" type="file" accept="image/*">
<script>
document.getElementById('output2').addEventListener('change', (e) => triggerF(e.target.files[0]));
function triggerF(file) {
  console.log("event triggered");
  const fr = new FileReader();
  fr.readAsArrayBuffer(file);
  fr.onload = (f) => {
    google.script.run.withSuccessHandler(yourCallBack1).upload([[...new Int8Array(f.target.result)], file.type, file.name]);
  };
}

function yourCallBack1() {
  console.log("callback called");
}
</script>

Google Apps Script side:

function upload(e) {
  const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(Utilities.newBlob(...e));
  console.log("created file");
}

Note:

In your script, it seems that Web Apps is used. In this case, when you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".


问:
Possible to have "mouseover for X seconds" functionality using jQuery?
I currently have several elements in a row that have a mouseover event that fires some animation.  My problem is that if someone mouses over several of the elements in quick succession the animation gets a little frantic.

I'm curious if there is a way to have a mouseover event that only fires if the mouse is over an element for a certain amount of time (say 250 milliseconds).  Can this be done with jQuery?

答:
here's an example of stop() in action, hope that will help:

without stop():

http://jsfiddle.net/5djzM/

with stop() cleaning the queue of animations:

http://jsfiddle.net/KjybD/

ContentLicense: CC BY-SA 3.0


问:
I'm trying to script 6 identical tables/calculators with one easy code
I'm creating some calculators for a mobile game that I play. I'm going to have 6 of the same type of calculator on the same page. Each one should look and operate like so:

const speedupInputs = document.querySelectorAll('input');
const results = document.getElementById('results');
const submit = document.getElementById('submit');

submit.addEventListener('click', function() {
    let total = 0;
    results.textContent = '';
    speedupInputs.forEach((input) => {
        if(input.value != '') {
            if(input.classList.contains('minutes')) {
                total += input.value * input.name;
            } else if (input.classList.contains('hours')) {
                total += (input.value * input.name) * 60;
            } else if (input.classList.contains('days')) {
                total += (input.value * input.name) * 60 * 24;
            }
        }
    })

    results.textContent = toTime(total * 60);

});

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}</code>```

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="minutes" id="3m" name="3" min="0">

      5m

      <input type="text" class="minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="days" name="3" min="0">

      7d

      <input type="number" id="7d" class="days" name="7" min="0">

      30d

      <input type="number" id="30d" class="days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

```
</div>
</div>
</p>
<p>Because there are 6 and because I'm trying to follow the DRY way of coding, I'm trying to create the least amount of code to do the job of scripting all 6 calculators. I mean, they're all identical si this shouldn't be hard, right?</p>
<p>This is the code that I thought would work. I don't know what the problem is because it isn't throwing any errors in the console. In a nutshell, the code is pretty similar to the first, except I tried to reference all tables via a <code>.forEach</code> function. Also, I read that one way to reference children of an element is to give all of the children a class name and then use <code>parentName.querySelectorAll('className')</code> (hence me trying to use it with <em>table</em> as the "parentName").</p>
```const submitBtns = document.querySelectorAll('.subitbtn');
const tables = document.querySelectorAll('table');
const speedupInputs = document.querySelectorAll('.tableinput');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

function myFunction() {
    tables.forEach((table) => {
        const results = table.querySelector('.resultsarea');
        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);
    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}
```

So yeah. To reiterate: I want 6 identical versions of these tables/calculators on a page, and I want one simple, easy code to script all 6 of them since they're identical. Thank you.

答:
With the code you've provided I had to solve multiple mistakes/erros. The first ones are small but as any mistake in programming they're still problematic.

Let's start with:

const submitBtns = document.querySelectorAll('.subitbtn'); and

const results = table.querySelector('.resultsarea');

Those have a typo. According to your html it should be:

const submitBtns = document.querySelectorAll('.submitbtn'); and

const results = table.querySelector('.resultarea');

Then there is the problem of some logic. The speedupInputs/tableinputs or declared at the wrong place. You only want the speedupInputs/tableinputs from the current table you're calculating in the loop. Not from all 6 tables everytime!

So instead of declaring it a global variable and selecting every thing in the document remove the global speedupInputs and place it in the tables forEach loop like:

const speedupInputs = table.querySelectorAll('.tableinput');

So this would work, but your table doesn't contain the class tableinput. Every inputfield in your first part of the table should have that class. Then it would work as you want I guess.

I've added a working snippet from your code below.

const submitBtns = document.querySelectorAll('.submitbtn');
const tables = document.querySelectorAll('table');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

let i = 0;
function myFunction() {
    tables.forEach((table) => {

        const results = table.querySelector('.resultarea');
        const speedupInputs = table.querySelectorAll('.tableinput');

        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);

    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}</code>```

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">

      5m

      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="tableinput hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="tableinput hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="tableinput hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="tableinput hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="tableinput days" name="3" min="0">

      7d

      <input type="number" id="7d" class="tableinput days" name="7" min="0">

      30d

      <input type="number" id="30d" class="tableinput days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">

      5m

      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="tableinput hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="tableinput hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="tableinput hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="tableinput hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="tableinput days" name="3" min="0">

      7d

      <input type="number" id="7d" class="tableinput days" name="7" min="0">

      30d

      <input type="number" id="30d" class="tableinput days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">

      5m

      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="tableinput hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="tableinput hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="tableinput hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="tableinput hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="tableinput days" name="3" min="0">

      7d

      <input type="number" id="7d" class="tableinput days" name="7" min="0">

      30d

      <input type="number" id="30d" class="tableinput days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">

      5m

      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="tableinput hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="tableinput hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="tableinput hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="tableinput hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="tableinput days" name="3" min="0">

      7d

      <input type="number" id="7d" class="tableinput days" name="7" min="0">

      30d

      <input type="number" id="30d" class="tableinput days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">

      5m

      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="tableinput hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="tableinput hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="tableinput hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="tableinput hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="tableinput days" name="3" min="0">

      7d

      <input type="number" id="7d" class="tableinput days" name="7" min="0">

      30d

      <input type="number" id="30d" class="tableinput days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">

      5m

      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="tableinput hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="tableinput hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="tableinput hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="tableinput hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="tableinput days" name="3" min="0">

      7d

      <input type="number" id="7d" class="tableinput days" name="7" min="0">

      30d

      <input type="number" id="30d" class="tableinput days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

```

`

Body:
I'm creating some calculators for a mobile game that I play. I'm going to have 6 of the same type of calculator on the same page. Each one should look and operate like so:

const speedupInputs = document.querySelectorAll('input');
const results = document.getElementById('results');
const submit = document.getElementById('submit');

submit.addEventListener('click', function() {
    let total = 0;
    results.textContent = '';
    speedupInputs.forEach((input) => {
        if(input.value != '') {
            if(input.classList.contains('minutes')) {
                total += input.value * input.name;
            } else if (input.classList.contains('hours')) {
                total += (input.value * input.name) * 60;
            } else if (input.classList.contains('days')) {
                total += (input.value * input.name) * 60 * 24;
            }
        }
    })

    results.textContent = toTime(total * 60);

});

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}

table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="minutes" id="3m" name="3" min="0">

      5m

      <input type="text" class="minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="days" name="3" min="0">

      7d

      <input type="number" id="7d" class="days" name="7" min="0">

      30d

      <input type="number" id="30d" class="days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

Because there are 6 and because I'm trying to follow the DRY way of coding, I'm trying to create the least amount of code to do the job of scripting all 6 calculators. I mean, they're all identical si this shouldn't be hard, right?

This is the code that I thought would work. I don't know what the problem is because it isn't throwing any errors in the console. In a nutshell, the code is pretty similar to the first, except I tried to reference all tables via a .forEach function. Also, I read that one way to reference children of an element is to give all of the children a class name and then use parentName.querySelectorAll('className') (hence me trying to use it with table as the "parentName").

const submitBtns = document.querySelectorAll('.subitbtn');
const tables = document.querySelectorAll('table');
const speedupInputs = document.querySelectorAll('.tableinput');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

function myFunction() {
    tables.forEach((table) => {
        const results = table.querySelector('.resultsarea');
        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);
    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}

So yeah. To reiterate: I want 6 identical versions of these tables/calculators on a page, and I want one simple, easy code to script all 6 of them since they're identical. Thank you.

Body:
With the code you've provided I had to solve multiple mistakes/erros. The first ones are small but as any mistake in programming they're still problematic.

Let's start with:

const submitBtns = document.querySelectorAll('.subitbtn'); and

const results = table.querySelector('.resultsarea');

Those have a typo. According to your html it should be:

const submitBtns = document.querySelectorAll('.submitbtn'); and

const results = table.querySelector('.resultarea');

Then there is the problem of some logic. The speedupInputs/tableinputs or declared at the wrong place. You only want the speedupInputs/tableinputs from the current table you're calculating in the loop. Not from all 6 tables everytime!

So instead of declaring it a global variable and selecting every thing in the document remove the global speedupInputs and place it in the tables forEach loop like:

const speedupInputs = table.querySelectorAll('.tableinput');

So this would work, but your table doesn't contain the class tableinput. Every inputfield in your first part of the table should have that class. Then it would work as you want I guess.

I've added a working snippet from your code below.

const submitBtns = document.querySelectorAll('.submitbtn');
const tables = document.querySelectorAll('table');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

let i = 0;
function myFunction() {
    tables.forEach((table) => {

        const results = table.querySelector('.resultarea');
        const speedupInputs = table.querySelectorAll('.tableinput');

        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);

    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}

table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}

<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="tableinput days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="tableinput days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="tableinput days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="tableinput days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="tableinput days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="tableinput days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="tableinput days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="tableinput days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="tableinput days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="tableinput days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="tableinput days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="tableinput days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="tableinput days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="tableinput days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="tableinput days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="tableinput minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="tableinput hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="tableinput days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="tableinput days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="tableinput days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

`


问:
sticky sidebar not working during scrolling
I want to have a sticky sidebar during scrolling  and I have tried many methods but it is not working. here is my code</p>
```<code> <div class="row">

        <div class="col me-0 me-md-3 mb-3 mb-md-0 px-0 ">

            <div class="position-relative" style="top: 0;
                left: 0;
                width: 100%;

                <div class="bg-white b-r-s-cont shadow pb-4 position-sticky top-0">
               height: 100%;">
         </div>
         </div>
      </div>
        <div class="col-12 col-md-9">
       </div>
</div>
</code>```

答:
You might want to try adding position: fixed; to the element that is supposed to be sticky.

You can simply add it it the current style="..." tag!


问:
Wordpress get new post permalink title
So I want to get the permalink title of a new published post.
example "http://myblog.com/healthy-life.php" I need healthy-life.php

here is code I have but it gets me http://myblog.com/healthy-life.php

```<code>function get_laterst_post_url() {
  global $wpdb;
  $query = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY post_date DESC LIMIT 1;";
  $result = $wpdb->get_results($query);
  if(is_object($result[0])) {
    return get_permalink($result[0]->ID);
  } else {
    return '';
  };
}
</code>```

答:
Use PHP's explode() to split at the slash and grab the last chunk of the array.

// get the full URL, removing a trailing slash if it has one
$permalink = rtrim(get_permalink($result[0]->ID), "/");

// break that full URL into an array of the strings between each slash
$segments = explode("/", $permalink);

// get the last item in that array of segments
return array_pop($segments);
```

Credit to @Leander for the trailing slash adjustment, and the intervening nine years to comment my examples.

Title: Wordpress get new post permalink title

Body:
So I want to get the permalink title of a new published post.
example "http://myblog.com/healthy-life.php" I need healthy-life.php

here is code I have but it gets me http://myblog.com/healthy-life.php

function get_laterst_post_url() {
  global $wpdb;
  $query = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY post_date DESC LIMIT 1;";
  $result = $wpdb->get_results($query);
  if(is_object($result[0])) {
    return get_permalink($result[0]->ID);
  } else {
    return '';
  };
}

Body:
Use PHP's explode() to split at the slash and grab the last chunk of the array.

// get the full URL, removing a trailing slash if it has one
$permalink = rtrim(get_permalink($result[0]->ID), "/");

// break that full URL into an array of the strings between each slash
$segments = explode("/", $permalink);

// get the last item in that array of segments
return array_pop($segments);

Credit to @Leander for the trailing slash adjustment, and the intervening nine years to comment my examples.


问:
subprocess.CalledProcessError: Command 'df' returned non-zero exit status 1
stackoverflow community!

I use python3 to collect some information from a server, but I had this Error and I did not find a solution for it.

This is my code below :

```<code>from subprocess import check_output
disks = check_output(("df")).decode("utf-8").split('\n')
print(disks)
</code>```

and this is the output:

```<code>df: /run/user/1001/doc: Operation not permitted
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python3.9/subprocess.py", line 424, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.9/subprocess.py", line 528, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'df' returned non-zero exit status 1.
</code>```

check_output() it work with other commands for example: check_output(("uname")).decode("utf-8") the output is: Linux

Why it work with other commands, but it don't work with df command? and what is the solution for this problem?

the command df it work when I run it from the terminal

答:
It looks like you have a permissions error. You could probably get a better error indication by doing that directly in Python. The following function does the equivalent.</p>
```<code>import os

def df(path="/"):
    """Return file system blocks used and free.

    Values are same as output of df command.
    """
    stat = os.statvfs(path)
    return (((stat.f_blocks - stat.f_bfree) * 8),
            (stat.f_bavail * (stat.f_frsize // 512)))

</code>```

Body:
stackoverflow community!

I use python3 to collect some information from a server, but I had this Error and I did not find a solution for it.

This is my code below :

from subprocess import check_output
disks = check_output(("df")).decode("utf-8").split('\n')
print(disks)

and this is the output:

df: /run/user/1001/doc: Operation not permitted
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python3.9/subprocess.py", line 424, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.9/subprocess.py", line 528, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'df' returned non-zero exit status 1.

check_output() it work with other commands for example: check_output(("uname")).decode("utf-8") the output is: Linux

Why it work with other commands, but it don't work with df command? and what is the solution for this problem?

the command df it work when I run it from the terminal

Body:
It looks like you have a permissions error. You could probably get a better error indication by doing that directly in Python. The following function does the equivalent.

import os

def df(path="/"):
    """Return file system blocks used and free.

    Values are same as output of df command.
    """
    stat = os.statvfs(path)
    return (((stat.f_blocks - stat.f_bfree) * 8),
            (stat.f_bavail * (stat.f_frsize // 512)))


问:
Rearrange txt content Script
I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit

Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep

Wolf Chicken

Wolf Rabbit

Lion Zebra

Lion Giraffe

Lion Gazelle

So far, I have tried this code in order to separate predators and preys

```<code>with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

</code>```

But combining them is the problem. I have tried something close to this:

```<code>with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i+=1
</code>```

答:
If you can use itertools and re module, I would go with something like:

```<code>import itertools, re
with open('test.txt', 'r') as inFile, open('test2.txt', 'w') as outFile:
    for line in inFile:
        splitted = re.split(":|,", line.strip())
        predator = splitted[0].strip()
        preys = [ prey.strip() for prey in splitted[1:] ]
        content = zip(itertools.repeat(predator), preys)
        outFile.write('\n'.join([ ' '.join(item) for item in content ]))
</code>```

How it works:

reads input file line by line;

for each line, it first strip the line and then split it using both colon and comma as separators;

puts the predator and the preys in two named variables to make code clear;

prepares the content using zip and itertools.repeat;

creates a list of "joined" item for item in content, using a space as joiner;

creates a string joining the previous list elements with '\n' as joiner;

writes it to outFile.

Title: Rearrange txt content Script

Body:
I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit

Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep

Wolf Chicken

Wolf Rabbit

Lion Zebra

Lion Giraffe

Lion Gazelle

So far, I have tried this code in order to separate predators and preys

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

But combining them is the problem. I have tried something close to this:

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i+=1

Body:
If you can use itertools and re module, I would go with something like:

import itertools, re
with open('test.txt', 'r') as inFile, open('test2.txt', 'w') as outFile:
    for line in inFile:
        splitted = re.split(":|,", line.strip())
        predator = splitted[0].strip()
        preys = [ prey.strip() for prey in splitted[1:] ]
        content = zip(itertools.repeat(predator), preys)
        outFile.write('\n'.join([ ' '.join(item) for item in content ]))

How it works:

reads input file line by line;

for each line, it first strip the line and then split it using both colon and comma as separators;

puts the predator and the preys in two named variables to make code clear;

prepares the content using zip and itertools.repeat;

creates a list of "joined" item for item in content, using a space as joiner;

creates a string joining the previous list elements with '\n' as joiner;

writes it to outFile.


问:
Query in Django template
I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}

here is the complete template:

```<code><div class="inventory-content">
    <div class='category'>
        <div>Categories</div>
        <div class='category-checkbox'>
            {%for category in items%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
            <label for="{{category.name}}"> {{category.name}}</label><br>
            {%endfor%}
        </div>
    </div>
    <div class='items'></div>

</div>

<script>
    $('.category-checkbox input[type="checkbox"]').on('click', function() {
        if ($(this).is(':checked')) {
          // Add the element to the div with an id identifier
          $('.items').append(`<div id="item_${this.id}">{% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}</div>`);
        } else {
          // Remove the element from the div targeted by the id identifier
          $(`#item_${this.id}`).remove();
        }
      });
</script>
</code>```

models.py:

```<code>class Category(models.Model):
    name = models.CharField(max_length=150)
    vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category')
    def __str__(self):
        return self.name
class Item(models.Model):
    name = models.CharField(max_length=255)
    part_number = models.IntegerField(blank=True)
    ROB = models.IntegerField(default=0)
    category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE)

    def __str__(self):
        return self.name
</code>```

views.py:

```<code>def index(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    categories = vessel_id.category.all()
    category = Category.objects.all()
    item = categories.prefetch_related(
        'items')
    context ={"vessel_id":vessel_id,'items':item,"category":category}
    return render(request,'inventory.html',context)

</code>```

also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked

答:
You are not able to call methods with arguments in Django templates, so there is no way you can write a query inside template.

The only right way is to query inside a view and then pass the ResultSet to context inside render() function.

Title: Query in Django template

Body:
I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}

here is the complete template:

Categories

            {%for category in items%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
             {{category.name}}

            {%endfor%}

models.py:

class Category(models.Model):
    name = models.CharField(max_length=150)
    vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category')
    def __str__(self):
        return self.name
class Item(models.Model):
    name = models.CharField(max_length=255)
    part_number = models.IntegerField(blank=True)
    ROB = models.IntegerField(default=0)
    category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

views.py:

def index(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    categories = vessel_id.category.all()
    category = Category.objects.all()
    item = categories.prefetch_related(
        'items')
    context ={"vessel_id":vessel_id,'items':item,"category":category}
    return render(request,'inventory.html',context)

also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked