问:
Tkinter label and button not rendering
I have a tkinter window of dimensions 300x300 pixel and a button and a label that are supposed to appear but they are not. I am only starting with tkinter so not too sure what I am doing wrong from the tutorial I am following.

import tkinter as tk

class Window(tk.Frame):

    def __init__(self, container):
        super().__init__(container)

        self.label = tk.Label(self, text = "Hello, World!")
        self.label.grid(row = 0, column = 0)

        self.button = tk.Button(self, text = "PI")
        self.button["command"] = self.value_of_pi
        self.button.grid(row = 1, column = 1)

    def value_of_pi(self):
        tk.messagebox.showinfo(title = "Value of PI", message = "The value of PI is 3.14.")

class App(tk.Tk):

    def __init__(self, dimensions):
        super().__init__()

        self.title("App")
        self.geometry(dimensions)

if __name__ == "__main__":
    app = App("300x300")
    frame = Window(app)

    app.mainloop()
```

The window that appears

答:
You forgot frame.pack()

```<code>...

if __name__ == "__main__":
    app = App("300x300")
    frame = Window(app)
    frame.pack()  # <- HERE
    app.mainloop()
</code>```

Title: Tkinter label and button not rendering

Body:
I have a tkinter window of dimensions 300x300 pixel and a button and a label that are supposed to appear but they are not. I am only starting with tkinter so not too sure what I am doing wrong from the tutorial I am following.

import tkinter as tk

class Window(tk.Frame):

    def __init__(self, container):
        super().__init__(container)

        self.label = tk.Label(self, text = "Hello, World!")
        self.label.grid(row = 0, column = 0)

        self.button = tk.Button(self, text = "PI")
        self.button["command"] = self.value_of_pi
        self.button.grid(row = 1, column = 1)

    def value_of_pi(self):
        tk.messagebox.showinfo(title = "Value of PI", message = "The value of PI is 3.14.")

class App(tk.Tk):

    def __init__(self, dimensions):
        super().__init__()

        self.title("App")
        self.geometry(dimensions)

if __name__ == "__main__":
    app = App("300x300")
    frame = Window(app)

    app.mainloop()

The window that appears

Body:
You forgot frame.pack()

...

if __name__ == "__main__":
    app = App("300x300")
    frame = Window(app)
    frame.pack()  # <- HERE
    app.mainloop()


来源: stackexchange

问:
Regular expression check for special character or number
I have such regular expression which checked for at least one special character in the string:

```<code>^(.*[^0-9a-zA-Z].*)$
</code>```

But how could i change this one to check for at least one special character or at leas one number in the string?

答:
```<code>.*[^a-zA-Z]+.*
</code>```

would match anything followed by a special character followed by anything.

Notice that I just removed the 0-9 from the character class (characters included in the square brackets).

Also, I removed the ^ and $ markers -- those match the beginning and end of string respectively. You don't need it because you're making it redundant with the .* (match zero or more of any character) anyway.

In fact, if you're just checking if the string contains a special character, then the following is good enough:

```<code>[^a-zA-Z]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have such regular expression which checked for at least one special character in the string:

^(.*[^0-9a-zA-Z].*)$

But how could i change this one to check for at least one special character or at leas one number in the string?

Body:
.*[^a-zA-Z]+.*

would match anything followed by a special character followed by anything.

Notice that I just removed the 0-9 from the character class (characters included in the square brackets).

Also, I removed the ^ and $ markers -- those match the beginning and end of string respectively. You don't need it because you're making it redundant with the .* (match zero or more of any character) anyway.

In fact, if you're just checking if the string contains a special character, then the following is good enough:

[^a-zA-Z]


问:
Why does the github repo of CPython says it contains python code?
Does the CPython Interpreter itself contain Python code? I could not find any answers on the internet.

When you go to the Github Repo, you see that it contains about 65% python code. But I could not really find any in what looked like interpreter/compiler code, that was all C.

Is there any?

答: Just click on the word "Python" in the language statistics and you will get a list of all files containing Python code: https://github.com/python/cpython/search?l=python</p>

ContentLicense: CC BY-SA 4.0


问:
no matching function to call for "getline"
I'm new to c++ programming. In a tutorial, the author mentioned "cin" will break if it reads a space in a string. If you want the program to read in an entire line of string with spaces, you should use the function "getline".

However, I couldn't make it work.

Here are my codes:

```<code>#include <iostream>
#include <string>

using namespace std;

int main()
{
    string my_name;

    cout << "Please enter your name: ";
    getline(cin, my_name, "\n");

    cout << "My name is " << my_name << " .";
}
</code>```

The IDE I am using is Xcode. The error message is "No matching function to call to 'getline'".

I have searched for similar issues but it seems to me none of the solutions apply to my problem. Maybe I am missing some knowledge? Thank you.

答:
If you change it to a char array you can use:

```<code>cin.getline(my_name, val_max);
</code>```

Just make sure your buffer (val_max) is large enough

Body:
I'm new to c++ programming. In a tutorial, the author mentioned "cin" will break if it reads a space in a string. If you want the program to read in an entire line of string with spaces, you should use the function "getline".

However, I couldn't make it work.

Here are my codes:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string my_name;

    cout << "Please enter your name: ";
    getline(cin, my_name, "\n");

    cout << "My name is " << my_name << " .";
}

The IDE I am using is Xcode. The error message is "No matching function to call to 'getline'".

I have searched for similar issues but it seems to me none of the solutions apply to my problem. Maybe I am missing some knowledge? Thank you.

Body:
If you change it to a char array you can use:

cin.getline(my_name, val_max);

Just make sure your buffer (val_max) is large enough


问:
Sequelize: Select all where value is the highest
I have a many-to-many relationship between Users and Roles. Since each User can have more than one role, I created a field, in the Role table, called "clearance", that can be 0 to 3, which is a number that represents how high the Role is in the hierarchy.
There is a point in my server where I need to have the Users to include only the Role with the highest clearance. I've tried multiple uses of sequelize.fn('MAX', sequelize.col('clearance") in where, include and through objects, from Sequelize, to no avail. I am no expert in mysql nor in Sequelize, but it's the best js module I found to work as an ORM for my DB.

答:
You could try something like this (no guarantee but looks like very close to what you want to achieve):

const users = await Users.findAll({
  include: [{
    model: Roles,
    limit: 1,
    order: ['clearance', 'DESC']
  }]
})
```


问:
how to check if text file contains string?
Hello, so, i'm having trouble to find if text file contains string.
for example.
and i want to create program to check if this file contains string 'banana'.
i have tried this but it didn't work

```<code>with open("test.txt","r") as f:
    content = f.read()
    for line in content:
        if 'banana' in line:
            do_something()
        else:
            exit()
</code>```

text file looks like this:

```<code>banana is yellow
apple is red
python is good
</code>```

答:
You don't need looping 'cause your file is just text, so just use conditional</p>
```<code>with open("test.txt","r") as f:
    content = f.read()
    if 'banana' in content:
        do_something()
    else:
        exit()
</code>```

Body:
Hello, so, i'm having trouble to find if text file contains string.
for example.
and i want to create program to check if this file contains string 'banana'.
i have tried this but it didn't work

with open("test.txt","r") as f:
    content = f.read()
    for line in content:
        if 'banana' in line:
            do_something()
        else:
            exit()

text file looks like this:

banana is yellow
apple is red
python is good

Body:
You don't need looping 'cause your file is just text, so just use conditional

with open("test.txt","r") as f:
    content = f.read()
    if 'banana' in content:
        do_something()
    else:
        exit()


问:
What is the impact of not calling the arguments while calling a function
My question is about the difference between two ways to pass the the arguments of a function

for instance

```<code>function1(obj1, obj2, obj3, obj4, obj5)
</code>```

or

```<code>function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)
</code>```

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?

答:
For me the issue is simple: reproducible results require reproducible and explicit function calls.

In my case, I use named arguments having learned that another person may insert a new parameter in their function if they so choose, which caused my code to break.

I also tend to store parameters in a list and use these when calling a function, e.g. someCrazyFunction(stuff = stuff, eps = Par$eps, tol = Par$tol, verbose = Par$verbose, strict = Par$strict, debug = Par$debug)

If I don't do this, I am not doing my part to ensure reproducible results.  It is only a few keystrokes and I don't have to worry if the author of the function or package moves arguments around, inserts new arguments, deletes some arguments (which I'll notice because R will tell me that some object is not needed), or otherwise makes seemingly harmless changes.  If they make such a change, then how can someone else who looks at my code be sure of how to reproduce the same call as it was at the time I made it?

Lesson: Debugging is far more painful than the few keystrokes needed to ensure reproducibility.

(Minor update) This question & the selected answer from elsewhere on SO exemplifies a particular aspect of this implicit contract between the package creator and the person with a dependency on a package.  If I develop a dependency on a given function and the author simply shuffles the arguments, then my code should work perfectly regardless.  They made no explicit contract to not move things around, and I can assume no implicit contract that it will behave that way.  I only assume that they will not change the definitions of arguments.

Body:
My question is about the difference between two ways to pass the the arguments of a function

for instance

function1(obj1, obj2, obj3, obj4, obj5)

or

function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?


问:
How could I make this LINQ query more efficient?
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

```<code>    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }
</code>```

The customerOrder is a customer Order class.

```<code>public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}
</code>```

答:
So you have a customerOrder. This customerOrder has zero or more OrderLines. Every OrderLine has zero or more OrderDates.

From the CustomerOrder you are only interested in all OrderDates. The rest of the Order or the OrderLines are not interesting for you.

Every OrderDate has property DateTypeId and ActualDate. From all OrderDates that are mentioned deep inside this customerOrder, you want to see if there is at least one OrderDate that has a value for property DateTypeId that equals "OrderPickUpFrom" AND a value for property ActualDate that is not null.

You don't define what you want if no OrderDate matches at all.

If one of these OrderDate matches this requirement, you take the ActualDate of the oldest matching OrderDate, or null if there is no matching OrderDate

You used Any() to check that there is at least one OrderDate that has a value for property DateTypeId that equals "OrderPickUpFrom" AND a value for property ActualDate that is not null. Therefore you know that there is at least one matching OrderDate, and thus at least one matching ActualDate. Therefore you know that date is never null.

```<code>const string requiredDateTypeId = "OrderPickupFrom";
var date = customerOrder.OrderLines
    .SelectMany(orderLine => orderline.OrderDate)
    .Where(orderDate => orderDate.DateTypeId == requiredDateTypeId
                     && orderDate.ActualDate != null)

    .OrderBy(orderDate => orderDate.ActualDate)
    .Select(orderDate => orderDate.ActualDate)
    .FirstOrDefault();
</code>```

In words:

From the customerOrder, make one big sequence of all OrderDates that are in all OrderLines of this customerOrder.

Keep only those OrderDates that have a value for property DateTypeId that equals the required DateTypeId AND that have a non-null value for ActualDate.

Sort the remaining OrderDates by ascending value of ActualDate. So the OrderDate with the oldest ActualDate is first

From the sorted OrderDates, select the value of property ActualDate

Keep the first one, or null if there issn't any OrderDate that has the required values.

if (date != null)
{
var formattedDate = etc.

Now there is one thing you can do to make the LINQ more efficient: why sort all OrderDates if you only plan to use the one that has the oldest value for ActualDate. In other words: if you found the oldest one, you don't need to sort any of the OrderDates that came after the oldest one. In fact, you'd like to have some Min function, where you can define the property on which to find the minimum one.

For this I use an extension method. If you are not familiar with extension methods, read Extension Methods demystified

```<code>public static MinOrDefault<T, TProperty> Min(this IEnumerable<T> source,
    Func<T, TProperty> propertySelector)
{
    return MinOrDefault(source, propertySelector, null);
}

public static MinOrDefault<T, TProperty> Min(this IEnumerable<T> source,
    Func<T, TProperty> propertySelector,
    IComparer<TProperty> comparer)
{
    // TODO: check source and propertySelector not null
    if (comparer == null) comparer = Comparer<TProperty>.Default;

    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
        {
            // There is at least one element in source
            T minValue = enumerator.Current;
            TProperty minPropertyValue = propertySelector(minValue);

            // check the rest of the sequence
            while (enumerator.MoveNext())
            {
                // there is a next. Is the property smaller?
                T value = enumerator.Current;
                TProperty propertyValue = propertySelector(value);
                if (comparer.Compare(propertyValue, minPropertyValue) < 0)
                {
                    // propertyValue is smaller than minPropertyValue
                    minValue = value;
                    minPropertyValue = propertyValue;
                }
                // else: minValue is still the smallest; do nothing
            }

            // if here, enumerated to the end of the sequence
            return minValue;
        }
        else
        {
             // empty sequence, return default:
             return default(T);
        }
    }
}
</code>```

Your code will be:

```<code>OrderDate oldestOrderDate = customerOrder.OrderLines
    .SelectMany(orderLine => orderline.OrderDate)
    .Where(orderDate => orderDate.DateTypeId == requiredDateTypeId
                     && orderDate.ActualDate != null)
    .MinOrDefault(orderDate => orderDate.ActualDate);

if (oldestOrderDate != null)
{
    etc.
</code>```

Body:
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }

The customerOrder is a customer Order class.

public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}

Body:
So you have a customerOrder. This customerOrder has zero or more OrderLines. Every OrderLine has zero or more OrderDates.

From the CustomerOrder you are only interested in all OrderDates. The rest of the Order or the OrderLines are not interesting for you.

Every OrderDate has property DateTypeId and ActualDate. From all OrderDates that are mentioned deep inside this customerOrder, you want to see if there is at least one OrderDate that has a value for property DateTypeId that equals "OrderPickUpFrom" AND a value for property ActualDate that is not null.

You don't define what you want if no OrderDate matches at all.

If one of these OrderDate matches this requirement, you take the ActualDate of the oldest matching OrderDate, or null if there is no matching OrderDate

You used Any() to check that there is at least one OrderDate that has a value for property DateTypeId that equals "OrderPickUpFrom" AND a value for property ActualDate that is not null. Therefore you know that there is at least one matching OrderDate, and thus at least one matching ActualDate. Therefore you know that date is never null.

const string requiredDateTypeId = "OrderPickupFrom";
var date = customerOrder.OrderLines
    .SelectMany(orderLine => orderline.OrderDate)
    .Where(orderDate => orderDate.DateTypeId == requiredDateTypeId
                     && orderDate.ActualDate != null)

    .OrderBy(orderDate => orderDate.ActualDate)
    .Select(orderDate => orderDate.ActualDate)
    .FirstOrDefault();

In words:

From the customerOrder, make one big sequence of all OrderDates that are in all OrderLines of this customerOrder.

Keep only those OrderDates that have a value for property DateTypeId that equals the required DateTypeId AND that have a non-null value for ActualDate.

Sort the remaining OrderDates by ascending value of ActualDate. So the OrderDate with the oldest ActualDate is first

From the sorted OrderDates, select the value of property ActualDate

Keep the first one, or null if there issn't any OrderDate that has the required values.

if (date != null)
{
var formattedDate = etc.

Now there is one thing you can do to make the LINQ more efficient: why sort all OrderDates if you only plan to use the one that has the oldest value for ActualDate. In other words: if you found the oldest one, you don't need to sort any of the OrderDates that came after the oldest one. In fact, you'd like to have some Min function, where you can define the property on which to find the minimum one.

For this I use an extension method. If you are not familiar with extension methods, read Extension Methods demystified

public static MinOrDefault<T, TProperty> Min(this IEnumerable<T> source,
    Func<T, TProperty> propertySelector)
{
    return MinOrDefault(source, propertySelector, null);
}

public static MinOrDefault<T, TProperty> Min(this IEnumerable<T> source,
    Func<T, TProperty> propertySelector,
    IComparer<TProperty> comparer)
{
    // TODO: check source and propertySelector not null
    if (comparer == null) comparer = Comparer<TProperty>.Default;

    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
        {
            // There is at least one element in source
            T minValue = enumerator.Current;
            TProperty minPropertyValue = propertySelector(minValue);

            // check the rest of the sequence
            while (enumerator.MoveNext())
            {
                // there is a next. Is the property smaller?
                T value = enumerator.Current;
                TProperty propertyValue = propertySelector(value);
                if (comparer.Compare(propertyValue, minPropertyValue) < 0)
                {
                    // propertyValue is smaller than minPropertyValue
                    minValue = value;
                    minPropertyValue = propertyValue;
                }
                // else: minValue is still the smallest; do nothing
            }

            // if here, enumerated to the end of the sequence
            return minValue;
        }
        else
        {
             // empty sequence, return default:
             return default(T);
        }
    }
}

Your code will be:

OrderDate oldestOrderDate = customerOrder.OrderLines
    .SelectMany(orderLine => orderline.OrderDate)
    .Where(orderDate => orderDate.DateTypeId == requiredDateTypeId
                     && orderDate.ActualDate != null)
    .MinOrDefault(orderDate => orderDate.ActualDate);

if (oldestOrderDate != null)
{
    etc.


问:
MySQL only select when value (float) has changed
I have the following table of data:
Table name entity_values

date_time
value

2017-09-02 05:05:00
20

2017-09-02 05:10:00
20

2017-09-02 05:15:00
21

2017-09-02 05:20:00
21

2017-09-02 05:25:00
21

2017-09-02 05:30:00
22

I currently only want to see the changes so I build the following query:

```<code>SELECT  date_time AS 'time',
 value - LAG(value) over (order by date_time) as 'Kwh01-Energy (kWh)'
FROM entity_values;
</code>```

This returns the following:

date_time
value

2017-09-02 05:00:00
0

2017-09-02 05:05:00
0

2017-09-02 05:10:00
1

2017-09-02 05:15:00
0

2017-09-02 05:20:00
0

2017-09-02 05:25:00
1

Since Window Functions aren't allowed in the WHERE clause like:

```<code>SELECT  date_time AS 'time',
 value - LAG(value) over (order by date_time) as 'Kwh01-Energy (kWh)'
FROM entity_values
WHERE (value - LAG(value) over (order by date_time)) > 0;
</code>```

Error Code: 3593. You cannot use the window function 'lag' in this context.'

Question: How do I filter out the 0 values and only get the "changed" values?
Desired result:

date_time
value

2017-09-02 05:10:00
1

2017-09-02 05:25:00
1

答:
Thank you @Andrew</p>
```<code>SELECT t.* from (
SELECT
date_time,
value - LAG(value) over (order by date_time) as changed_value
FROM entity_values
) as t
WHERE changed_value > 0
</code>```

Body:
I have the following table of data:
Table name entity_values

date_time
value

2017-09-02 05:05:00
20

2017-09-02 05:10:00
20

2017-09-02 05:15:00
21

2017-09-02 05:20:00
21

2017-09-02 05:25:00
21

2017-09-02 05:30:00
22

I currently only want to see the changes so I build the following query:

SELECT  date_time AS 'time',
 value - LAG(value) over (order by date_time) as 'Kwh01-Energy (kWh)'
FROM entity_values;

This returns the following:

date_time
value

2017-09-02 05:00:00
0

2017-09-02 05:05:00
0

2017-09-02 05:10:00
1

2017-09-02 05:15:00
0

2017-09-02 05:20:00
0

2017-09-02 05:25:00
1

Since Window Functions aren't allowed in the WHERE clause like:

SELECT  date_time AS 'time',
 value - LAG(value) over (order by date_time) as 'Kwh01-Energy (kWh)'
FROM entity_values
WHERE (value - LAG(value) over (order by date_time)) > 0;

Error Code: 3593. You cannot use the window function 'lag' in this context.'

Question: How do I filter out the 0 values and only get the "changed" values?
Desired result:

date_time
value

2017-09-02 05:10:00
1

2017-09-02 05:25:00
1

Body:
Thank you @Andrew

SELECT t.* from (
SELECT
date_time,
value - LAG(value) over (order by date_time) as changed_value
FROM entity_values
) as t
WHERE changed_value > 0


问:
Width percentage value not being applied to element
I am styling an element in HTML using Sass, and when setting the width of an element using percentages, it is not applied.

Could this be due to me setting the parent element's width and height using "content-max"?

Here is a basic version of the code I am using, the idea is for the parent's size to be limited by the image size (which works), and for the text overlay to be half the width and the full height of the container element (hence me using 50 and 100 percent respectively).

```<code><div class="container">
      <img src="image.png" alt="A square image">
      <div class="text-overlay">

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

The separately complied Sass is as follows:

```<code>.container {

     display: block;
     position: relative;
     width: max-content;
     height: max-content;

     img {
          display: block;
          position: absolute;
          z-index: 0;
     }

     .text-overlay {

           display: flex;
           position: absolute;
           width: 50%;
           height: 100%;
           z-index: 1;
     }
}
</code>```

Both HTML and SCSS are written in different files and correctly complied where necesary.

答:
As mentioned in the comments, you can not write Sass directly inside your HTML markup. It has to be compiled first.

In your example you are using nesting, which is not valid CSS3 code, so to fix this behavior you either have to write plain CSS like the snippet below or compile your Sass before you apply it to your HTML.

About your actual question, the positioning you are trying to archieve is working, when you hardcore the width and height to the .container element.

.container {
  position: relative;
  width: 200px;
  height: 200px;
}

.container img {
  position: absolute;
  z-index: 0;
}

.container .text-overlay {
  position: absolute;
  z-index: 1;
  width: 50%;
  height: 100%;
  background-color: green;
  color: red;
  opacity: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="https://i.picsum.photos/id/793/200/200.jpg?hmac=3DeE830wjdSShKq_h_iFtV_jAxf43FO4xx-sivW0Q_Y">
  <div class="text-overlay">
    Overlay
  </div>
</div></code>```

Body:
I am styling an element in HTML using Sass, and when setting the width of an element using percentages, it is not applied.

Could this be due to me setting the parent element's width and height using "content-max"?

Here is a basic version of the code I am using, the idea is for the parent's size to be limited by the image size (which works), and for the text overlay to be half the width and the full height of the container element (hence me using 50 and 100 percent respectively).

The separately complied Sass is as follows:

.container {

     display: block;
     position: relative;
     width: max-content;
     height: max-content;

     img {
          display: block;
          position: absolute;
          z-index: 0;
     }

     .text-overlay {

           display: flex;
           position: absolute;
           width: 50%;
           height: 100%;
           z-index: 1;
     }
}

Both HTML and SCSS are written in different files and correctly complied where necesary.

Body:
As mentioned in the comments, you can not write Sass directly inside your HTML markup. It has to be compiled first.

In your example you are using nesting, which is not valid CSS3 code, so to fix this behavior you either have to write plain CSS like the snippet below or compile your Sass before you apply it to your HTML.

About your actual question, the positioning you are trying to archieve is working, when you hardcore the width and height to the .container element.

.container {
  position: relative;
  width: 200px;
  height: 200px;
}

.container img {
  position: absolute;
  z-index: 0;
}

.container .text-overlay {
  position: absolute;
  z-index: 1;
  width: 50%;
  height: 100%;
  background-color: green;
  color: red;
  opacity: 50%;
}

<div class="container">
  <img src="https://i.picsum.photos/id/793/200/200.jpg?hmac=3DeE830wjdSShKq_h_iFtV_jAxf43FO4xx-sivW0Q_Y">
  <div class="text-overlay">
    Overlay
  </div>
</div>


问:
Javascript parse html, modify anchor tags that contain images
I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:

```<code><a style="color:000;" href="images/image.jpg">
    <img width="100" height="20" src="images/image_thumb.jpg" />
</a>
</code>```

I would like to change it to be:

```<code><a style="color:000;" href="images/image.jpg" rel="lightbox" >
    <img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>
</code>```

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

答:
First, put it in a new element that does not exist on the page, then modify it as usual:

```<code>var container = new Element("div", { html: yourHTML });
container.getElements("a img").forEach(function(img){
    var link = img.getParent("a");
    img.decoy = img.src;
    img.removeAttribute("src");
    link.rel = "lightbox";
});
</code>```

Demo here: http://jsfiddle.net/XDacQ/1/

Body:
I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:

I would like to change it to be:

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

Body:
First, put it in a new element that does not exist on the page, then modify it as usual:

var container = new Element("div", { html: yourHTML });
container.getElements("a img").forEach(function(img){
    var link = img.getParent("a");
    img.decoy = img.src;
    img.removeAttribute("src");
    link.rel = "lightbox";
});

Demo here: http://jsfiddle.net/XDacQ/1/


问:
forEach and assign to variable
This is just an example that I want to understand. I know there is a better way to select the last element from the array, but I don't know why it works that way.

```<code>const numbers = [1, 2, 3];

let exampleId: number;

numbers.forEach(function(number) {
  exampleId = number;
});

console.log(exampleId);
</code>```

Why do I get the error "Variable 'exampleId' is used before being assigned." in the line from console.log?

答:
Maybe the interpreter doesn't take into account that the array numbers is not empty in your code.

Because, if it were empty, for sure the variable exampleId would be used before being assigned.

(If the array is empty, the code inside the forEach loop is never executed, and the variable is never assigned)

Title: forEach and assign to variable

Body:
This is just an example that I want to understand. I know there is a better way to select the last element from the array, but I don't know why it works that way.

const numbers = [1, 2, 3];

let exampleId: number;

numbers.forEach(function(number) {
  exampleId = number;
});

console.log(exampleId);

Why do I get the error "Variable 'exampleId' is used before being assigned." in the line from console.log?


问:
In MIPS32, is "add $t1 $t1 $t1" the same as "sll $t1 $t1 1"
I was wondering if in MIPS 32, the two following are identical:

add $t1 $t1 $t1

sll $t1 $t1 1

Does sll handle a possible overflow differently than add? I can't seem to find a good explanation online.

Thank you!

答:
Yes, you suspect correctly: sll won't ever trigger an overflow exception, whereas add will trigger overflow when interpreting the numbers as signed integers whose sum won't fit in 32-bits.

As Jester says, addu will also never trigger overflow so is more equivalent to your sll.

Most instruction sets have some duplication/overlap like this, as it would take both design & implementation effort to prevent, arguably for little or no return on investment.

We should always use addu for pointer arithmetic because we don't want a signed  overflow check.  Pointers are unsigned, and addu stands for add unsigned — but it performs the same arithmetic as add, just omitting overflow checking.  You might think it checks for unsigned overflow but it doesn't, so it is a bit of an oddity to call it addu.  We should also use addiu rather than addi with pointers for the same reason — to forgo a signed integer overflow check.  Adjustment of the stack pointer should be done with addiu, but you'll often see people use addi by mistake.

RISC V decided to remove the overflow checking entirely, so if you want an overflow check you have to use more instructions; the regular instruction is just add and works for both signed or unsigned integers (the additional instructions you would add to check for overflow would be specific to whether signed or unsigned).


问:
Heading from product filter
I'm using the Foundry theme and on the /products page. I have links to the different categories of products. These take you to /category/______. There is a
 heading, which has a default of value Shop. I want the value to represent the current category. I tried the following code, but the heading was just blank.

```<code><h1>
...
{% elsif page.full_url contains "category/" %}
    {% for category in categories.all %}
      {% if page.full_url contains {{ category.permalink }} %}{{ category.name }}{% endif %}
    {% endfor %}
...
</h1>
</code>```

Examples:

page.full_url returns https://website/category/wall-hangings

category.permalink returns wall-hangings

I also tried a method using:

```<code>{{ page.full_url | remove: "https://website/category" | replace: "-" " " | capitalize }}
</code>```

However, the replace method doesn't insert spaces.

答: I overcomplicated my original approach. Using {{ page.name }} returns the category name, so using this in the heading tag worked.

Title: Heading from product filter

Body:
I'm using the Foundry theme and on the /products page. I have links to the different categories of products. These take you to /category/______. There is a
 heading, which has a default of value Shop. I want the value to represent the current category. I tried the following code, but the heading was just blank.

...
{% elsif page.full_url contains "category/" %}
    {% for category in categories.all %}
      {% if page.full_url contains {{ category.permalink }} %}{{ category.name }}{% endif %}
    {% endfor %}
...

Examples:

page.full_url returns https://website/category/wall-hangings

category.permalink returns wall-hangings

I also tried a method using:

{{ page.full_url | remove: "https://website/category" | replace: "-" " " | capitalize }}

However, the replace method doesn't insert spaces.


问:
Pageview trigger not firing in Google Tag Manager
I'm trying to fire a pageview trigger whenever the manage staff page of my website is viewed. I tried to do it using the PageView trigger and using Page URL equals https://workex.jobs/manage-staff. The manage staff page can be opened from the home screen by clicking on Manager Staff button on the header.
Link to the home page - https://workex.jobs/
Link to the page I'm trying to monitor - https://workex.jobs/manage-staff
The pageview trigger is not fired when I click on manage staff button on the header which opens the page I'm tracking (https://workex.jobs/manage-staff). But, the trigger is only fired when I refresh the manage staff page. I want to know why the pageview trigger does not fire when I click on the button that opens the page whose URL I'm tracking?
[enter image description here][1]</p>

答:
The pageview trigger doesn't work on navigations because your site is an SPA. A single page application. It implies that there are no real pageloads on navigations. On a hard refresh or when you navigate to that page directly and not as a result of site navigation, a pageview is issued.

You just want to add a history change trigger to your existing pageview trigger. This one:

And apply your additional trigger page filters or it will fire on every navigation.


问:
GitHub API Exception: invalid json response body at https://api.github.com/projects/{ID}/columns reason: Unexpected end of JSON input
I have problem using the library octokit for NodeJs.

What I'm trying to do is to loop the boards of a specific Azure DevOps project and create the relative columns and projects on GitHub. The application successfully create the projects, but sometimes the call to create the columns return the following exception:

```<code>invalid json response body at https://api.github.com/projects/14101058/columns reason: Unexpected end of JSON input
</code>```

index.js

```<code>function migrateBoards() {
    logService.info(`Migrating boards...`);
    azureDevOpsService
        .getRepos(azdoProject, true, true, false)
        .then(async repos => {
            logService.verbose(`Found ${repos.length} repos in Azure DevOps project ${azdoProject}: ${repos.map(repo => repo.name)}`);
            await azureDevOpsService
                .getTeams(azdoProject)
                .then(teams => {
                    logService.verbose(`Found ${teams.length} teams in Azure DevOps project ${azdoProject}`);
                    teams.map(async team => {
                        const boards = await azureDevOpsService
                            .getBoards(team.projectId, team.projectName, team.id, team.name)
                            .catch(error => {
                                logService.error(`Error getting boards for team ${team.name}`, error);
                            });
                        logService.verbose(`Found ${boards.length} boards in Azure DevOps project ${azdoProject} and team ${team.name}`);
                        boards.map(async board => {
                            let boardDetails = await azureDevOpsService
                                .getBoard(team.projectId, team.projectName, team.id, team.name, board.id)
                                .catch(e => {
                                    logService.error(`Error getting boards ${board.id} from project ${team.projectName}`, e);
                                });
                            let project = null;
                            if(repos.length > 1) {
                                logService.verbose(`Checking if project ${team.name} ${boardDetails.name} exists in the GitHub organization ${gitHubOrganizationName}`);
                                project = await gitHubService
                                    .getProjectForOrganization(gitHubOrganizationName, boardDetails.name)
                                    .catch(error => {
                                        logService.error(`Error creating project ${boardDetails.name}`, error);
                                    });
                                if(project == null) {
                                    logService.verbose(`Project ${team.name} ${boardDetails.name} does not exist in GitHub. Creating...`);
                                    project = await gitHubService
                                        .createOrgProject(gitHubOrganizationName, `${team.name} ${boardDetails.name}`)
                                        .catch(error => {
                                            logService.error(`Error creating project ${team.name} ${boardDetails.name}`, error);
                                        });
                                } else {
                                    logService.verbose(`Project ${team.name} ${boardDetails.name} already exists in GitHub. Skipping...`);
                                    return;
                                }
                                logService.verbose(`Linking project ${team.name} ${boardDetails.name} to the GitHub repository ${gitHubProject}`);
                                // TODO: Link repositories to the project
                            } else {
                                logService.verbose(`Checking if project ${team.name} exists in the GitHub repository ${gitHubProject}`);
                                project = await gitHubService
                                    .getProject(gitHubProject, boardDetails.name)
                                    .catch(error => {
                                        logService.error(`Error getting project ${project.name}`, error);
                                    });
                                if(project == null) {
                                    logService.verbose(`Project ${team.name} does not exist in GitHub. Creating...`);
                                    project = await gitHubService
                                        .createProject(gitHubProject, `${team.name}`)
                                        .catch(error => {
                                            logService.error(`Error creating project ${team.name} ${boardDetails.name}`, error);
                                        });
                                } else {
                                    logService.verbose(`Project ${team.name} already exists in GitHub. Skipping...`);
                                    return;
                                }
                            }
                            let columns = await gitHubService
                                .getColumns(project.id)
                                .catch(e => {
                                    logService.error(`Error getting columns for project ${project.name}`, e);
                                });
                            logService.verbose(`Found ${columns.length} columns in GitHub project ${project.name}: ${columns.map(column => column.name)}`);
                            boardDetails.columns.map(async column => {
                                if(columns.find(c => c.name == column.name) == null) {
                                    logService.verbose(`Creating a new column in GitHub project ${project.name}: ${column.name}`);
                                    await gitHubService
                                        .createProjectColumn(project.id, column.name)
                                        .catch(error => {
                                            logService.error(`Error creating column ${column.name} in GitHub project ${project.name}`, error);
                                        });
                                } else {
                                    logService.verbose(`Column ${column.name} already exists in GitHub project ${project.name}. Skipping...`);
                                }
                                // TODO create card to each column
                            });
                        });
                    });
                })
                .catch(error => {
                    logService.error(`Error getting teams in Azure DevOps project ${azdoProject}`, error);
                });
</code>```

gitHubService.js

```<code>async createProjectColumn(projectId, columnName) {
    const { data } = await this.octokit.rest.projects.createColumn({
        project_id: projectId,
        name: columnName
    });
    return data;
}
</code>```

Example execution

```<code>[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: New
services/logService.js:16
[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: Approved
services/logService.js:16
[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: Committed
services/logService.js:16
[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: Done
services/logService.js:16
[Error] Error creating column In Progress in GitHub project Marketing Team Features: invalid json response body at https://api.github.com/projects/14101052/columns reason: Unexpected end of JSON input
services/logService.js:23
[Error] Error creating column Done in GitHub project Support Team Backlog items: invalid json response body at https://api.github.com/projects/14101051/columns reason: Unexpected end of JSON input
</code>```

References:

Doc: https://docs.github.com/en/rest/reference/projects#list-project-columns

Repository: https://github.com/GTRekter/Apodimo

Code: index.js - row 187

答:
can you please check the following code?
I was testing something similar to what you're mentioning, creating a project column using Octokit, in my case, it's working all the time, I'm not able to reproduce your issue, can you spot any difference from what you're doing in your side?

Create GitHub Project Column
View in Fusebit

const owner = 'stack-overflow-demos';
const projectId = 14105747;
const columns = await installationClient.rest.projects.listColumns({ project_id: projectId });
const columnName = 'Test';
const column = columns.data.find(column => column.name === columnName);

if (column) {
  console.log('Column already exists, recreating column . . .');
  await installationClient.rest.projects.deleteColumn({ column_id: column.id });
}
console.log('Creating new column');
const { data } = await installationClient.rest.projects.createColumn({ project_id: projectId, name: columnName });
console.log('Column created', data);

```

Body:
I have problem using the library octokit for NodeJs.

What I'm trying to do is to loop the boards of a specific Azure DevOps project and create the relative columns and projects on GitHub. The application successfully create the projects, but sometimes the call to create the columns return the following exception:

invalid json response body at https://api.github.com/projects/14101058/columns reason: Unexpected end of JSON input

index.js

function migrateBoards() {
    logService.info(`Migrating boards...`);
    azureDevOpsService
        .getRepos(azdoProject, true, true, false)
        .then(async repos => {
            logService.verbose(`Found ${repos.length} repos in Azure DevOps project ${azdoProject}: ${repos.map(repo => repo.name)}`);
            await azureDevOpsService
                .getTeams(azdoProject)
                .then(teams => {
                    logService.verbose(`Found ${teams.length} teams in Azure DevOps project ${azdoProject}`);
                    teams.map(async team => {
                        const boards = await azureDevOpsService
                            .getBoards(team.projectId, team.projectName, team.id, team.name)
                            .catch(error => {
                                logService.error(`Error getting boards for team ${team.name}`, error);
                            });
                        logService.verbose(`Found ${boards.length} boards in Azure DevOps project ${azdoProject} and team ${team.name}`);
                        boards.map(async board => {
                            let boardDetails = await azureDevOpsService
                                .getBoard(team.projectId, team.projectName, team.id, team.name, board.id)
                                .catch(e => {
                                    logService.error(`Error getting boards ${board.id} from project ${team.projectName}`, e);
                                });
                            let project = null;
                            if(repos.length > 1) {
                                logService.verbose(`Checking if project ${team.name} ${boardDetails.name} exists in the GitHub organization ${gitHubOrganizationName}`);
                                project = await gitHubService
                                    .getProjectForOrganization(gitHubOrganizationName, boardDetails.name)
                                    .catch(error => {
                                        logService.error(`Error creating project ${boardDetails.name}`, error);
                                    });
                                if(project == null) {
                                    logService.verbose(`Project ${team.name} ${boardDetails.name} does not exist in GitHub. Creating...`);
                                    project = await gitHubService
                                        .createOrgProject(gitHubOrganizationName, `${team.name} ${boardDetails.name}`)
                                        .catch(error => {
                                            logService.error(`Error creating project ${team.name} ${boardDetails.name}`, error);
                                        });
                                } else {
                                    logService.verbose(`Project ${team.name} ${boardDetails.name} already exists in GitHub. Skipping...`);
                                    return;
                                }
                                logService.verbose(`Linking project ${team.name} ${boardDetails.name} to the GitHub repository ${gitHubProject}`);
                                // TODO: Link repositories to the project
                            } else {
                                logService.verbose(`Checking if project ${team.name} exists in the GitHub repository ${gitHubProject}`);
                                project = await gitHubService
                                    .getProject(gitHubProject, boardDetails.name)
                                    .catch(error => {
                                        logService.error(`Error getting project ${project.name}`, error);
                                    });
                                if(project == null) {
                                    logService.verbose(`Project ${team.name} does not exist in GitHub. Creating...`);
                                    project = await gitHubService
                                        .createProject(gitHubProject, `${team.name}`)
                                        .catch(error => {
                                            logService.error(`Error creating project ${team.name} ${boardDetails.name}`, error);
                                        });
                                } else {
                                    logService.verbose(`Project ${team.name} already exists in GitHub. Skipping...`);
                                    return;
                                }
                            }
                            let columns = await gitHubService
                                .getColumns(project.id)
                                .catch(e => {
                                    logService.error(`Error getting columns for project ${project.name}`, e);
                                });
                            logService.verbose(`Found ${columns.length} columns in GitHub project ${project.name}: ${columns.map(column => column.name)}`);
                            boardDetails.columns.map(async column => {
                                if(columns.find(c => c.name == column.name) == null) {
                                    logService.verbose(`Creating a new column in GitHub project ${project.name}: ${column.name}`);
                                    await gitHubService
                                        .createProjectColumn(project.id, column.name)
                                        .catch(error => {
                                            logService.error(`Error creating column ${column.name} in GitHub project ${project.name}`, error);
                                        });
                                } else {
                                    logService.verbose(`Column ${column.name} already exists in GitHub project ${project.name}. Skipping...`);
                                }
                                // TODO create card to each column
                            });
                        });
                    });
                })
                .catch(error => {
                    logService.error(`Error getting teams in Azure DevOps project ${azdoProject}`, error);
                });

gitHubService.js

async createProjectColumn(projectId, columnName) {
    const { data } = await this.octokit.rest.projects.createColumn({
        project_id: projectId,
        name: columnName
    });
    return data;
}

Example execution

[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: New
services/logService.js:16
[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: Approved
services/logService.js:16
[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: Committed
services/logService.js:16
[Verbose] Creating a new column in GitHub project Project Management Team Backlog items: Done
services/logService.js:16
[Error] Error creating column In Progress in GitHub project Marketing Team Features: invalid json response body at https://api.github.com/projects/14101052/columns reason: Unexpected end of JSON input
services/logService.js:23
[Error] Error creating column Done in GitHub project Support Team Backlog items: invalid json response body at https://api.github.com/projects/14101051/columns reason: Unexpected end of JSON input

References:

Doc: https://docs.github.com/en/rest/reference/projects#list-project-columns

Repository: https://github.com/GTRekter/Apodimo

Code: index.js - row 187


问:
Getting All Controllers and Actions names in C#
Is it possible to list the names of all controllers and their actions programmatically? </p>

<p>I want to implement database driven security for each controller and action. As a developer, I know all controllers and actions and can add them to a database table, but is there any way to add them automatically? </p>

答:
Update:

For .NET 6 minimal hosting model see this answer on how to replace Startup in the code below

https://stackoverflow.com/a/71026903/3850405

Original:

In .NET Core 3 and .NET 5 you can do it like this:

Example:

```<code>public class Example
{
    public void ApiAndMVCControllers()
    {
        var controllers = GetChildTypes<ControllerBase>();
        foreach (var controller in controllers)
        {
            var actions = controller.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
        }
    }

    private static IEnumerable<Type> GetChildTypes<T>()
    {
        var types = typeof(Startup).Assembly.GetTypes();
        return types.Where(t => t.IsSubclassOf(typeof(T)) && !t.IsAbstract);

    }
}
</code>```

Body:
Is it possible to list the names of all controllers and their actions programmatically?

I want to implement database driven security for each controller and action. As a developer, I know all controllers and actions and can add them to a database table, but is there any way to add them automatically?

Body:
Update:

For .NET 6 minimal hosting model see this answer on how to replace Startup in the code below

https://stackoverflow.com/a/71026903/3850405

Original:

In .NET Core 3 and .NET 5 you can do it like this:

Example:

public class Example
{
    public void ApiAndMVCControllers()
    {
        var controllers = GetChildTypes<ControllerBase>();
        foreach (var controller in controllers)
        {
            var actions = controller.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
        }
    }

    private static IEnumerable<Type> GetChildTypes<T>()
    {
        var types = typeof(Startup).Assembly.GetTypes();
        return types.Where(t => t.IsSubclassOf(typeof(T)) && !t.IsAbstract);

    }
}


问:
Pandas read_excel no longer adheres single empty column
I came across this post Pandas read_excel ignores blank column that I need to keep and I am facing the same issue lately on my application which was working fine. looks like add_excel() is ignoring the empty column which I need to override the existing values in the database. Any help is appreciated, thanks</p>

答:
How about adding a complete column of just ' ' or '\n' or '\t' literals?

Another way could be naming a column:
say a df x contains columns 'a', 'b' with values

Could this work?

x.loc['c'] = pd.Series([None*len(x.loc['a'])])
```

Seems stupid, but most stupid things work sometimes...

Body:
How about adding a complete column of just ' ' or '\n' or '\t' literals?

Another way could be naming a column:
say a df x contains columns 'a', 'b' with values

Could this work?

x.loc['c'] = pd.Series([None*len(x.loc['a'])])

Seems stupid, but most stupid things work sometimes...


问:
P5.js - createGraphics() leads to strange results with small screen size
I've been trying to solve this problem for days. I simplified the problem with this simple code :

```<code>let graphicCanvas
let ctx
let speed = 1
function setup(){
    cnv = createCanvas(windowWidth, windowHeight)
    cnv.style('display', 'block');
    graphicCanvas = createGraphics(800,800)
    ctx = graphicCanvas.canvas.getContext('2d')

}
function draw(){
    ctx.drawImage(ctx.canvas,0,0,800,800,0,speed,800,800)

    graphicCanvas.noStroke()
    graphicCanvas.fill(255,0,0)
    graphicCanvas.circle(100,100,50)
    image(graphicCanvas,0,0)

}
</code>```

This code is supposed to show the trails,of a red circle, that is getting longer after each loop:
Red trails

The problem is that this code only works on large screens. With small screens I end up with this result : Red circles

I don't know if the problem comes from the createGraphics(), the drawImage() or the image().

I already tried to use graphicCanvas.push() and graphicCanvas.pop() but nothing change. How can I get the "Red trails" result for every screen size ?

(As a foreigner, please excuse me for the english mistakes)

答:
The issue is not screen size, but pixel density. Because you are using the CanvasRenderingContext2D.drawImage function instead of p5.js function the graphics is actually scaled 2x when it is drawn. Here's an example that should work on any screen:

let graphicCanvas;
let ctx;
let speed = 1;

function setup() {
  pixelDensity(1);
  cnv = createCanvas(windowWidth, windowHeight);
  cnv.style("display", "block");
  graphicCanvas = createGraphics(800, 800);
  ctx = graphicCanvas.canvas.getContext("2d");
}

function draw() {
  ctx.drawImage(ctx.canvas, 0, 0, 800, 800, 0, speed, 800, 800);

  graphicCanvas.noStroke();
  graphicCanvas.fill(255, 0, 0);
  graphicCanvas.circle(100, 100, 50);
  image(graphicCanvas, 0, 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script></code>```

That said you might want to consider avoiding the native CanvasRenderingContext2D functions altogether and use p5.js functions that preserve support for pixel density:

```<code>let graphicCanvas;
let ctx;
let speed = 1;
function setup() {
  cnv = createCanvas(windowWidth, windowHeight);
  speed = pixelDensity();
  cnv.style("display", "block");
  graphicCanvas = createGraphics(800, 800);
}
function draw() {
  graphicCanvas.copy(0, 0, 800, 800, 0, speed, 800, 800);

  graphicCanvas.noStroke();
  graphicCanvas.fill(255, 0, 0);
  graphicCanvas.circle(100, 100, 50);
  image(graphicCanvas, 0, 0);
}
</code>```

Body:
I've been trying to solve this problem for days. I simplified the problem with this simple code :

let graphicCanvas
let ctx
let speed = 1
function setup(){
    cnv = createCanvas(windowWidth, windowHeight)
    cnv.style('display', 'block');
    graphicCanvas = createGraphics(800,800)
    ctx = graphicCanvas.canvas.getContext('2d')

}
function draw(){
    ctx.drawImage(ctx.canvas,0,0,800,800,0,speed,800,800)

    graphicCanvas.noStroke()
    graphicCanvas.fill(255,0,0)
    graphicCanvas.circle(100,100,50)
    image(graphicCanvas,0,0)

}

This code is supposed to show the trails,of a red circle, that is getting longer after each loop:
Red trails

The problem is that this code only works on large screens. With small screens I end up with this result : Red circles

I don't know if the problem comes from the createGraphics(), the drawImage() or the image().

I already tried to use graphicCanvas.push() and graphicCanvas.pop() but nothing change. How can I get the "Red trails" result for every screen size ?

(As a foreigner, please excuse me for the english mistakes)

Body:
The issue is not screen size, but pixel density. Because you are using the CanvasRenderingContext2D.drawImage function instead of p5.js function the graphics is actually scaled 2x when it is drawn. Here's an example that should work on any screen:

let graphicCanvas;
let ctx;
let speed = 1;

function setup() {
  pixelDensity(1);
  cnv = createCanvas(windowWidth, windowHeight);
  cnv.style("display", "block");
  graphicCanvas = createGraphics(800, 800);
  ctx = graphicCanvas.canvas.getContext("2d");
}

function draw() {
  ctx.drawImage(ctx.canvas, 0, 0, 800, 800, 0, speed, 800, 800);

  graphicCanvas.noStroke();
  graphicCanvas.fill(255, 0, 0);
  graphicCanvas.circle(100, 100, 50);
  image(graphicCanvas, 0, 0);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

That said you might want to consider avoiding the native CanvasRenderingContext2D functions altogether and use p5.js functions that preserve support for pixel density:

let graphicCanvas;
let ctx;
let speed = 1;
function setup() {
  cnv = createCanvas(windowWidth, windowHeight);
  speed = pixelDensity();
  cnv.style("display", "block");
  graphicCanvas = createGraphics(800, 800);
}
function draw() {
  graphicCanvas.copy(0, 0, 800, 800, 0, speed, 800, 800);

  graphicCanvas.noStroke();
  graphicCanvas.fill(255, 0, 0);
  graphicCanvas.circle(100, 100, 50);
  image(graphicCanvas, 0, 0);
}


问:
FFMPEG - Image extraction stretch problem
I have a .mov video file with 1440x1080 resolution. I extracted the frames from the video, using scale -vf scale=1440:-1 but the images are stretched. Even though, the dimension of the extracted images are 1440x1080, the image is stretched on the height dimension and doesn't match the aspect ratio of the video.

How can I solve this issue?

Here is the output from FFMPEG for the original video:

```<code>Stream #0:0(eng): Video: qtrle (rle  / 0x20656C72), rgb24(progressive), 1440x1080, 624445 kb/s, SAR 4:3 DAR 16:9, 25 fps, 25 tbr, 25 tbn (default)
</code>```

答: As the value of DAR is 16:9 but 1440x1080 is not 16:9 then to generate the frames with "the proper" aspect ratio you should use -vf scale=1920:1080 filter instead.

Body:
I have a .mov video file with 1440x1080 resolution. I extracted the frames from the video, using scale -vf scale=1440:-1 but the images are stretched. Even though, the dimension of the extracted images are 1440x1080, the image is stretched on the height dimension and doesn't match the aspect ratio of the video.

How can I solve this issue?

Here is the output from FFMPEG for the original video:

Stream #0:0(eng): Video: qtrle (rle  / 0x20656C72), rgb24(progressive), 1440x1080, 624445 kb/s, SAR 4:3 DAR 16:9, 25 fps, 25 tbr, 25 tbn (default)


问:
How do you re-add a track to a RTCRtpSender for an RTCRtpPeerConnection, instead of creating a new/second RTCRtpSender?
I've polished a front end around an existing webRTC/SIP javascript API and it works well, but I've discovered a bug in the underlying API around hold/resume and it's causing me to have to dip into the WebRTC stuff which is well outside my comfort zone.

As it is, calls work. If I place the call on hold, I can see that my RTCPeerConnection has a sender and that sender's track becomes null. I have an RTCRtpTransceiver, and that never enters the "stopped" state. The SIP server acknowledges the hold. This is done with a "removeTrack()" of the sender. When I go to resume the call, the API calls an "addTrack()" on the peerconnection. What happens is now I have 2 RTCRtpSenders, and 2 RTCRtpTransceivers, with the track showing up under the 2nd of each. The actual user experience is that the remote audio resumes, but my mic never returns to the call.

My understanding is, I want the mediaStreamTrack to reconnect to the original RTCRtpSender, right? Looking here, there's conditions to reuse a sender but it's not happening; my read of the original API source code makes it look like they expect to reattach to the existing sender: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack

One thing I tried doing was issuing a "stop()" to the RTCRtpTransceiver, but that actually causes the connection to the SIP server to fail and it sends an ack back that the hold failed.

I wasn't able to get anywhere with setStreams, and replaceTrack would require making enough of a switch to making things asynchronous that I didn't want to proceed down that road yet.

I fully admit the webRTC stuff is over my head; we added things like AD Integration and some DB stuff to store chats/call history, but squashing a bug in how the API handles WebRTC stuff is a bit out of reach for me.

Does anyone have some recommendation for how to handle this? It's tricky because we can't make our demo public, but I can provide debug.

The source is here, starting on 406: https://github.com/L1kMakes/sipml5-ng/blob/master/src/tinyMEDIA/src/tmedia_session_jsep.js

答:
The solution was switching to replaceTrack.  I need to clean this up a bit, but this prototype works:</p>
```<code>const sender = this.o_pc.getSenders()[0];
const track = This.o_local_stream.getTracks()[0];
sender.replaceTrack(track)
    .then(() => {
        console.log("tmedia_session_jsep - resume - Successful Stream Replace!");
    })
    .catch( e => console.log("tmedia_session_jsep - resume - Error: " + e));
this.o_pc.getTransceivers()[0].direction = "sendrecv";
</code>```

Body:
The solution was switching to replaceTrack.  I need to clean this up a bit, but this prototype works:

const sender = this.o_pc.getSenders()[0];
const track = This.o_local_stream.getTracks()[0];
sender.replaceTrack(track)
    .then(() => {
        console.log("tmedia_session_jsep - resume - Successful Stream Replace!");
    })
    .catch( e => console.log("tmedia_session_jsep - resume - Error: " + e));
this.o_pc.getTransceivers()[0].direction = "sendrecv";


答:
The assignment is scoped within the forEach loop; If numbers have no values, exampleId would never get defined. TS is essentially warning you about that, as you cannot call a variable that has yet to be defined.

Solution 1:

Initialise your variable with a value

let exampleId = 0;
```
<h4>Solution 2:</h4>
<p>Use non-null assertions, although I'd suggest against them</p>
<pre class="lang-js prettyprint-override"><code>console.log(exampleId!);
</code>```

With this solution we're essentially telling TS to not worry about it, as there will surely exist a value; That, in other words, remove the type safety, reason why I'd suggest going with option 1.

Title: forEach and assign to variable

Body:
The assignment is scoped within the forEach loop; If numbers have no values, exampleId would never get defined. TS is essentially warning you about that, as you cannot call a variable that has yet to be defined.

Solution 1:

Initialise your variable with a value

let exampleId = 0;

Solution 2:

Use non-null assertions, although I'd suggest against them

console.log(exampleId!);

With this solution we're essentially telling TS to not worry about it, as there will surely exist a value; That, in other words, remove the type safety, reason why I'd suggest going with option 1.


问:
Do rolling on all dataframe rows
I would like to find in dataframe of prices all all-time highs in that were in history.

timestamp
close
ath

x
1234
0

x
2000
1

x
1956
0

x
1884
0

x
2234
1

So for specific row I would like to find a maximum for all previous rows and check if value in current row is greater than this maximum. I cannot do it without indexing for all rows and I know that it is inefficient.

答:
Try this:

```<code>df['ath'] = df.groupby('timestamp')['close'].shift(1).lt(df['close']).astype(int)
</code>```

Output:

```<code>>>> df
  timestamp  close  ath
0         x   1234    0
1         x   2000    1
2         x   1956    0
3         x   1884    0
4         x   2234    1
</code>```

Title: Do rolling on all dataframe rows

Body:
Try this:

df['ath'] = df.groupby('timestamp')['close'].shift(1).lt(df['close']).astype(int)

Output:

>>> df
  timestamp  close  ath
0         x   1234    0
1         x   2000    1
2         x   1956    0
3         x   1884    0
4         x   2234    1


问:
SQL - How to Multiply Prior Row value to Current Row
Can this be done and if so what is the best approach. I tried Over(Partition) but cannot figure out how to add the prior columns. Should I use IF BEGIN ENDS and just walk through it row by row for running balance? Any assistance on initial direction would be appreciated.

```<code>CREATE TABLE [dbo].[PStatement](
[ID] [int],
[Source] [nvarchar](255),
[PaymentNumber] [int],
[PaymentAmt] [money],
[RBalance] [money],
[CBalance] [money],
[AllocationPercent] [float]
</code>```

)

With the following values:

```<code>INSERT INTO PStatement (ID, [Source], PaymentNumber, PaymentAmt, RBalance, CBalance, AllocationPercent)
VALUES (1, N'SR', 1, 0, 7500, 10000, .75)
,(2, N'ER', 1, 0, 2500, 10000, .25)
,(3, N'SR', 2, 50, 0, 11000, 0)
,(4, N'ER', 2, 75, 0, 11000, .0)
,(5, N'SR', 3, 50, 0, 12000, 0)
,(6, N'ER', 3, 75, 0, 12000, .0)
</code>```

I need to take the CBalance from the prior row, subtract the sum of the current rows PaymentAmt and multiple that amount by the prior rows AllocationPercentage and then add back the PaymentAmt based on PaymentNumber and Source.

So Row 3 RBalance is $11000 - ($50 + $75) (from current row) * .75 (from prior row) + 50 (from current row), AllocationPercent is RBalance/CBalance.

So Row 4 is $11000 - ($50 + $75) * .25 + 75

The end table would look like this:

答:
You can access 'prior row' data by using something like:

```<code>select ID
     , PaymentAmt
     , PreviousPaymentAmt=LAG(PaymentAmt,1,0) OVER (ORDER BY ID)
from PStatement
</code>```

The 2nd parameter in LAG is telling it to go only 1 record back; and the third parameter is telling it to return 0 (zero) if there are no prior rows.

Body:
Can this be done and if so what is the best approach. I tried Over(Partition) but cannot figure out how to add the prior columns. Should I use IF BEGIN ENDS and just walk through it row by row for running balance? Any assistance on initial direction would be appreciated.

CREATE TABLE [dbo].[PStatement](
[ID] [int],
[Source] [nvarchar](255),
[PaymentNumber] [int],
[PaymentAmt] [money],
[RBalance] [money],
[CBalance] [money],
[AllocationPercent] [float]

)

With the following values:

INSERT INTO PStatement (ID, [Source], PaymentNumber, PaymentAmt, RBalance, CBalance, AllocationPercent)
VALUES (1, N'SR', 1, 0, 7500, 10000, .75)
,(2, N'ER', 1, 0, 2500, 10000, .25)
,(3, N'SR', 2, 50, 0, 11000, 0)
,(4, N'ER', 2, 75, 0, 11000, .0)
,(5, N'SR', 3, 50, 0, 12000, 0)
,(6, N'ER', 3, 75, 0, 12000, .0)

I need to take the CBalance from the prior row, subtract the sum of the current rows PaymentAmt and multiple that amount by the prior rows AllocationPercentage and then add back the PaymentAmt based on PaymentNumber and Source.

So Row 3 RBalance is $11000 - ($50 + $75) (from current row) * .75 (from prior row) + 50 (from current row), AllocationPercent is RBalance/CBalance.

So Row 4 is $11000 - ($50 + $75) * .25 + 75

The end table would look like this:

Body:
You can access 'prior row' data by using something like:

select ID
     , PaymentAmt
     , PreviousPaymentAmt=LAG(PaymentAmt,1,0) OVER (ORDER BY ID)
from PStatement

The 2nd parameter in LAG is telling it to go only 1 record back; and the third parameter is telling it to return 0 (zero) if there are no prior rows.


问:
What is the reason of wrong output?
I was trying to write a code in c which converts a day month year format to dayRD day of Month Year

For example:
1 12 2020 must be converted like 1st day of december 2020.

I wrote the code as ı write down the page but the output is not the output that ı want.

```<code>#include<stdio.h>
int main() {
int day,month,year;
printf("Please enter date in a format of day month year");
scanf("%d%d%d",&day,&month,&year);

int dayconvert(day) {
    switch (day) {
        case 1:printf("%dst day of",day);
        break;
        case 2:printf("%dnd day of",day);
        break;
        case 3:printf("%drd day of",day);
        break;
        case 4:printf("%dth day of",day);
        break;
        case 5:printf("%dth day of",day);
        break;
        case 6:printf("%dth day of",day);
        break;
        case 7:printf("%dth day of",day);
        break;
        case 8:printf("%dth day of",day);
        break;
        case 9:printf("%dth day of",day);
        break;
        case 10:printf("%dth day of",day);
        break;
        case 11:printf("%dst day of",day);
        break;
        case 12:printf("%dnd day of",day);
        break;
        case 13:printf("%drd day of",day);
        break;
        case 14:printf("%dth day of",day);
        break;
        case 15:printf("%dth day of",day);
        break;
        case 16:printf("%dth day of",day);
        break;
        case 17:printf("%dth day of",day);
        break;
        case 18:printf("%dth day of",day);
        break;
        case 19:printf("%dth day of",day);
        break;
        case 20:printf("%dth day of",day);
        break;
        case 21:printf("%dst day of",day);
        break;
        case 22:printf("%dnd day of",day);
        break;
        case 23:printf("%drd day of",day);
        break;
        case 24:printf("%dth day of",day);
        break;
        case 25:printf("%dth day of",day);
        break;
        case 26:printf("%dth day of",day);
        break;
        case 27:printf("%dth day of",day);
        break;
        case 28:printf("%dth day of",day);
        break;
        case 29:printf("%dth day of",day);
        break;
        case 30:printf("%dth day of",day);
        break;

    }

}

int monthconvert(month) {
    switch (month) {
        case 1:printf("January");
        break;
        case 2:printf("February");
        break;
        case 3:printf("March");
        break;
        case 4:printf("April");
        break;
        case 5:printf("May");
        break;
        case 6:printf("June");
        break;
        case 7:printf("July");
        break;
        case 8:printf("August");
        break;
        case 9:printf("September");
        break;
        case 10:printf("October");
        break;
        case 11:printf("November");
        break;
        case 12:printf("December");
        break;

    }
}

printf("%d %d %d",dayconvert(day),monthconvert(month),year);
</code>```

}

The output is January1st day of10  2020 when we enter 1 12 2020 values to day,month,year

答:
at the end you do this

```<code> printf("%d %d %d",dayconvert(day),monthconvert(month),year);
</code>```

there is no guarantee what order these function calls are made. In fact you have shown that printf calls monthconvert, then dayconvert.

Monthconvert prints out the month name, then dayconvert prints out the day name.

Title: What is the reason of wrong output?

Body:
I was trying to write a code in c which converts a day month year format to dayRD day of Month Year

For example:
1 12 2020 must be converted like 1st day of december 2020.

I wrote the code as ı write down the page but the output is not the output that ı want.

#include<stdio.h>
int main() {
int day,month,year;
printf("Please enter date in a format of day month year");
scanf("%d%d%d",&day,&month,&year);

int dayconvert(day) {
    switch (day) {
        case 1:printf("%dst day of",day);
        break;
        case 2:printf("%dnd day of",day);
        break;
        case 3:printf("%drd day of",day);
        break;
        case 4:printf("%dth day of",day);
        break;
        case 5:printf("%dth day of",day);
        break;
        case 6:printf("%dth day of",day);
        break;
        case 7:printf("%dth day of",day);
        break;
        case 8:printf("%dth day of",day);
        break;
        case 9:printf("%dth day of",day);
        break;
        case 10:printf("%dth day of",day);
        break;
        case 11:printf("%dst day of",day);
        break;
        case 12:printf("%dnd day of",day);
        break;
        case 13:printf("%drd day of",day);
        break;
        case 14:printf("%dth day of",day);
        break;
        case 15:printf("%dth day of",day);
        break;
        case 16:printf("%dth day of",day);
        break;
        case 17:printf("%dth day of",day);
        break;
        case 18:printf("%dth day of",day);
        break;
        case 19:printf("%dth day of",day);
        break;
        case 20:printf("%dth day of",day);
        break;
        case 21:printf("%dst day of",day);
        break;
        case 22:printf("%dnd day of",day);
        break;
        case 23:printf("%drd day of",day);
        break;
        case 24:printf("%dth day of",day);
        break;
        case 25:printf("%dth day of",day);
        break;
        case 26:printf("%dth day of",day);
        break;
        case 27:printf("%dth day of",day);
        break;
        case 28:printf("%dth day of",day);
        break;
        case 29:printf("%dth day of",day);
        break;
        case 30:printf("%dth day of",day);
        break;

    }

}

int monthconvert(month) {
    switch (month) {
        case 1:printf("January");
        break;
        case 2:printf("February");
        break;
        case 3:printf("March");
        break;
        case 4:printf("April");
        break;
        case 5:printf("May");
        break;
        case 6:printf("June");
        break;
        case 7:printf("July");
        break;
        case 8:printf("August");
        break;
        case 9:printf("September");
        break;
        case 10:printf("October");
        break;
        case 11:printf("November");
        break;
        case 12:printf("December");
        break;

    }
}

printf("%d %d %d",dayconvert(day),monthconvert(month),year);

}

The output is January1st day of10  2020 when we enter 1 12 2020 values to day,month,year

Body:
at the end you do this

 printf("%d %d %d",dayconvert(day),monthconvert(month),year);

there is no guarantee what order these function calls are made. In fact you have shown that printf calls monthconvert, then dayconvert.

Monthconvert prints out the month name, then dayconvert prints out the day name.


问:
Cannot upgrade PIP in virtual environment
I am trying to upgrade pip in a virtual environment. I am using the venvburrito wrapper, in an ubuntu 14.04 machine. When I try to update it I get the following error:

```<code>   (virtual_env) ubuntu@ip-xxxxxxx:~$ pip install pip --upgrade
Collecting pip
  Using cached pip-9.0.1-py2.py3-none-any.whl
Installing collected packages: pip
  Found existing installation: pip 8.1.2
    Not uninstalling pip at /home/ubuntu/.venvburrito/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg, outside environment /home/ubuntu/.virtualenvs/virtual_env
Successfully installed pip-8.1.2
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

If I try it with sudo, inside the virtual environment, I get the following error:

```<code>(virtual_env) ubuntu@ip-xxxxxxx:~$ sudo pip install --upgrade pip
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
/home/ubuntu/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/home/ubuntu/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Requirement already up-to-date: pip in ./.local/lib/python2.7/site-packages
/home/ubuntu/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
</code>```

When I do it outside the virtual environment, it installs correctly.

Any help will be much appreciated.

Thanks

答:
Seen a lot of problems with pip that all seem to be fixed by running it as a python module instead of directly:

python -m pip install --upgrade pip

Body:
I am trying to upgrade pip in a virtual environment. I am using the venvburrito wrapper, in an ubuntu 14.04 machine. When I try to update it I get the following error:

   (virtual_env) ubuntu@ip-xxxxxxx:~$ pip install pip --upgrade
Collecting pip
  Using cached pip-9.0.1-py2.py3-none-any.whl
Installing collected packages: pip
  Found existing installation: pip 8.1.2
    Not uninstalling pip at /home/ubuntu/.venvburrito/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg, outside environment /home/ubuntu/.virtualenvs/virtual_env
Successfully installed pip-8.1.2
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

If I try it with sudo, inside the virtual environment, I get the following error:

(virtual_env) ubuntu@ip-xxxxxxx:~$ sudo pip install --upgrade pip
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
/home/ubuntu/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/home/ubuntu/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Requirement already up-to-date: pip in ./.local/lib/python2.7/site-packages
/home/ubuntu/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning

When I do it outside the virtual environment, it installs correctly.

Any help will be much appreciated.

Thanks


问:
Different types of passing parameters to a recursive function
The below code worked perfectly fine.

```<code>        def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                cur.append(i)
                perm(cur)
                cur.pop()

        perm([])
        return res
</code>```

However, the below one returned error

```<code>         def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                perm(cur.append(i))
                cur.pop()

        perm([])
        return res
</code>```
```<code>TypeError: argument of type 'NoneType' is not iterable
    avail = [i for i in nums if not i in cur]
Line 5 in <listcomp> (Solution.py)
    avail = [i for i in nums if not i in cur]
Line 5 in perm (Solution.py)
    perm(cur.append(i))
Line 12 in perm (Solution.py)
    perm([])
Line 15 in permute (Solution.py)
    ret = Solution().permute(param_1)
Line 38 in _driver (Solution.py)
    _driver()
Line 49 in <module> (Solution.py)
</code>```

I'm trying to understand the logic behind this.

I'm not sure of the difference between both ways of parameter passing.

答:
.append returns None.

```<code>def perm(cur):
        avail = [i for i in nums if not i in cur]
        if len(avail) == 0:
            res.append(cur.copy())
            return

        for i in avail:
            // Here .append(i) does not return anything so the cur you are passing in the perm funcion is None
            perm(cur.append(i))
            cur.pop()

    perm([])
    return res
</code>```

Body:
The below code worked perfectly fine.

        def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                cur.append(i)
                perm(cur)
                cur.pop()

        perm([])
        return res

However, the below one returned error

         def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                perm(cur.append(i))
                cur.pop()

        perm([])
        return res

TypeError: argument of type 'NoneType' is not iterable
    avail = [i for i in nums if not i in cur]
Line 5 in <listcomp> (Solution.py)
    avail = [i for i in nums if not i in cur]
Line 5 in perm (Solution.py)
    perm(cur.append(i))
Line 12 in perm (Solution.py)
    perm([])
Line 15 in permute (Solution.py)
    ret = Solution().permute(param_1)
Line 38 in _driver (Solution.py)
    _driver()
Line 49 in <module> (Solution.py)

I'm trying to understand the logic behind this.

I'm not sure of the difference between both ways of parameter passing.

Body:
.append returns None.

def perm(cur):
        avail = [i for i in nums if not i in cur]
        if len(avail) == 0:
            res.append(cur.copy())
            return

        for i in avail:
            // Here .append(i) does not return anything so the cur you are passing in the perm funcion is None
            perm(cur.append(i))
            cur.pop()

    perm([])
    return res


问:
How to return only a specific data from relationships when using $model->load() in Laravel?
I'm using $user->load(['roles', 'expertises', 'languages']) to return data to a front-end made with Vue.

The Vue component I'm using (Treeselect) needs an array of only ID's to load choices made by user.
AFAIK this is not possible ->load(['expertises' => 'myMethod']), this can be useful when you want to return 'expertises' array key, but loading your own filtered data from a custom method.

Please, help me giving some ideas on how to achieve this task.

Thank you.

答:
You actually can eager-load specific columns in a load() method, but the proper syntax would be:

$user->load(['roles:id,user_id', 'expertises:id,user_id', 'languages:id,user_id']);
```
<p>The problem with that is that you need to include the Foreign Key (I assume <code>user_id</code> in this case) to achieve that, which doesn't fit your requirements of only having the ID.</p>
<p>You're probably better off using <code>->pluck('id')</code> when passing these to your Components, something like:</p>
<pre class="lang-php prettyprint-override"><code>$roleIds = $user->roles->pluck('id');
$expertiseIds = $user->expertises->pluck('id');
$languageIds = $user->languages->pluck('id');
// Note: You generally don't need to call `->load()` on a single Model instance; when you try to access them, they will be loaded.
</code>```

Sidenote, you didn't include your components in your question, so I don't know how you're using them.

That being said, you can load those ->pluck() calls to specific variables, or do it inline for your vue components, whatever works best for your use case.

Body:
You actually can eager-load specific columns in a load() method, but the proper syntax would be:

$user->load(['roles:id,user_id', 'expertises:id,user_id', 'languages:id,user_id']);

The problem with that is that you need to include the Foreign Key (I assume user_id in this case) to achieve that, which doesn't fit your requirements of only having the ID.

You're probably better off using ->pluck('id') when passing these to your Components, something like:

$roleIds = $user->roles->pluck('id');
$expertiseIds = $user->expertises->pluck('id');
$languageIds = $user->languages->pluck('id');
// Note: You generally don't need to call `->load()` on a single Model instance; when you try to access them, they will be loaded.

Sidenote, you didn't include your components in your question, so I don't know how you're using them.

That being said, you can load those ->pluck() calls to specific variables, or do it inline for your vue components, whatever works best for your use case.


问:
Reactjs hide div when click outside or click men
I am creating language switcher component using tailwind css.

Language chooser is working fine, but I can't hide the Language  when click outside of the .

Is there any react component for Language Switcher?

May I know how to hide the div click outside.

```<code>import { useState } from "react";
import { useTranslation } from "react-i18next";
import { MyanmarFlag, EnglishFlag } from "../assets/icons/svg_icons";

const LanguageSelector = () => {
  const [isOpen, setIsOpen] = useState(false);
  const { t, i18n } = useTranslation();

   const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
   };

  return (
<div className="flex justify-end p-4">
  <div className="relative">
    <button
      className="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2
  bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2
   focus:ring-offset-gray-100 focus:ring-primary"
      onClick={() => setIsOpen(!isOpen)}
    >
      Select Language
    </button>
    {isOpen && (
      <div
        className="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg
  bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100
  focus:outline-none z-50"
      >
        <div className="py-1">
          <a
            className="group flex items-center px-4 py-2 text-sm text-gray-700
        hover:bg-primary hover:text-white"
            onClick={() => changeLanguage("my")}
          >
            <MyanmarFlag
              className="mr-3 h-5 w-5 text-gray-400 group-hover:text-white"
              aria-hidden="true"
            ></MyanmarFlag>
            Myanmar
          </a>
        </div>
        <div className="py-1">
          <a
            className="group flex items-center px-4 py-2 text-sm text-gray-700
        hover:bg-primary hover:text-white"
            onClick={() => changeLanguage("en")}
          >
            <EnglishFlag
              className="mr-3 h-5 w-5 text-gray-400 group-hover:text-white"
              aria-hidden="true"
            ></EnglishFlag>
            English
          </a>
        </div>
      </div>
    )}
  </div>
</div>
);
};

export default LanguageSelector;
</code>```

答:
You can use useRef hook and bind event listener to your div, then change your isOpen state.

See Detect click outside React component

Body:
I am creating language switcher component using tailwind css.

Language chooser is working fine, but I can't hide the Language  when click outside of the .

Is there any react component for Language Switcher?

May I know how to hide the div click outside.

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { MyanmarFlag, EnglishFlag } from "../assets/icons/svg_icons";

const LanguageSelector = () => {
  const [isOpen, setIsOpen] = useState(false);
  const { t, i18n } = useTranslation();

   const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
   };

  return (

    <button
      className="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2
  bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2
   focus:ring-offset-gray-100 focus:ring-primary"
      onClick={() => setIsOpen(!isOpen)}
    >
      Select Language
    </button>
    {isOpen && (

           changeLanguage("my")}
          >
            <MyanmarFlag
              className="mr-3 h-5 w-5 text-gray-400 group-hover:text-white"
              aria-hidden="true"
            ></MyanmarFlag>
            Myanmar

           changeLanguage("en")}
          >
            <EnglishFlag
              className="mr-3 h-5 w-5 text-gray-400 group-hover:text-white"
              aria-hidden="true"
            ></EnglishFlag>
            English

    )}

);
};

export default LanguageSelector;


问:
How to get the common ordered characters between 2 strings in python?
How to get the common ordered characters between 2 strings in python?

for example:

```<code>str1 = 'AAA'
str2 = 'AXA'
</code>```

output should be 'AA'

答:
Try like this</p>
```<code>result = ''
for i in range(0, len(str1)):
    if str1[i] == str2[i]:
       result += str1[i]

print(result)
</code>```

Body:
How to get the common ordered characters between 2 strings in python?

for example:

str1 = 'AAA'
str2 = 'AXA'

output should be 'AA'

Body:
Try like this

result = ''
for i in range(0, len(str1)):
    if str1[i] == str2[i]:
       result += str1[i]

print(result)