问:
It looks like changing state in child component causes App to rerender, I don't want this to happen
I didn't pass any props from App to child component but when I change the state of the child, App rerenders( i wrote console.log('App rerendered') on App.js). Is this normal?
Can i prevent this?</p>

答:
The best way to prevent this is to either memoize the component that you don't want to re-render on its props, or if using class components maybe to use shouldComponentUpdate.

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

https://reactjs.org/docs/react-api.html#reactmemo


来源: stackexchange

问:
AttributeError: 'tuple' object has no attribute 'get' while using POST request in Postman
I'm trying to use request.get_json() to add nodes from JSON data to a set.

```<code>@app.route('/connect_node', methods = ['POST'])

def connect_node():
    json = request.get_json()
    nodes = json.get('nodes')
    if nodes is None:
        return "No node", 400
</code>```

The snapshot of the Postman POST request

The error I'm getting in Spyder(Python 3.9):

```<code>line 178, in connect_node
nodes = json.get(nodes)
AttributeError: 'tuple' object has no attribute 'get'
</code>```

答:
I'm assuming your going though the udemy blockchain course, turns out its just a problem with the postman check this out
Flask app request.get_json() return (Ellipsis, Ellipsis) instead of json</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use request.get_json() to add nodes from JSON data to a set.

@app.route('/connect_node', methods = ['POST'])

def connect_node():
    json = request.get_json()
    nodes = json.get('nodes')
    if nodes is None:
        return "No node", 400

The snapshot of the Postman POST request

The error I'm getting in Spyder(Python 3.9):

line 178, in connect_node
nodes = json.get(nodes)
AttributeError: 'tuple' object has no attribute 'get'


问:
How to move a value in a list one element to the right every time the key "D' is pressed using Python and without any imports?
So I have a list and I am wondering if there is a way to move the element to the right by pressing D and change the moved element?

For example

```<code>list=[ 0, **, **, **]
</code>```

When I press D, I want the list to end up something like this.

```<code>list= [--, 0, **, **]
</code>```

And the next time I press D,

```<code>list=[--,--,0, **]
</code>```

答:
Here are a couple of ways to do what you requested (without completely understanding how you plan on rotating the elements [single element or wrap entire list])

```<code>temp_list = [ 0, 1, 2, 3]

def rotate_entire_list(temp_list):
    new_list = [temp_list[-1]]
    new_list.extend(temp_list[:-1])
    return new_list

def rotate_element_in_list(temp_list, element_pos):
    if element_pos == len(temp_list) - 1:
        temp_list[0], temp_list[-1] = temp_list[-1], temp_list[0]
    else:
        temp_list[element_pos], temp_list[element_pos + 1] = temp_list[element_pos + 1], temp_list[element_pos]
    return temp_list

start_index = 0
while(input('press D to rotate') == 'D'):
    print(rotate_element_in_list(temp_list, 0))
    start_index += 1
    # or
    #print(rotate_entire_list(temp_list))
</code>```

This does require inputting the letter 'D' to function -- unsure if this is an acceptable usage of the D input (if input is allowed?).

Body:
So I have a list and I am wondering if there is a way to move the element to the right by pressing D and change the moved element?

For example

list=[ 0, **, **, **]

When I press D, I want the list to end up something like this.

list= [--, 0, **, **]

And the next time I press D,

list=[--,--,0, **]

Body:
Here are a couple of ways to do what you requested (without completely understanding how you plan on rotating the elements [single element or wrap entire list])

temp_list = [ 0, 1, 2, 3]

def rotate_entire_list(temp_list):
    new_list = [temp_list[-1]]
    new_list.extend(temp_list[:-1])
    return new_list

def rotate_element_in_list(temp_list, element_pos):
    if element_pos == len(temp_list) - 1:
        temp_list[0], temp_list[-1] = temp_list[-1], temp_list[0]
    else:
        temp_list[element_pos], temp_list[element_pos + 1] = temp_list[element_pos + 1], temp_list[element_pos]
    return temp_list

start_index = 0
while(input('press D to rotate') == 'D'):
    print(rotate_element_in_list(temp_list, 0))
    start_index += 1
    # or
    #print(rotate_entire_list(temp_list))

This does require inputting the letter 'D' to function -- unsure if this is an acceptable usage of the D input (if input is allowed?).


问:
I can't Initialize WriteableBitmap with BitmapImage
```<code> BitmapImage img = new BitmapImage(new Uri("somepath",UriKind.Relative));
 WriteableBitmap wbm = new WriteableBitmap(img);
</code>```

I get a Runtime error at the line above: "Object reference not set to an instance of an object."

答:
If the build action of your image file is set to resource, then the following code will work.

```<code>Uri uri = new Uri("/ProjectName;component/Images/image.jpg", UriKind.Relative);
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage img = new BitmapImage();
img.SetSource(resourceInfo.Stream);
WriteableBitmap wbm = new WriteableBitmap(img);
</code>```

Notice that the resource is accessed by the static method GetResourceStream defined by the application class.
Now if you change the build action of the file to Content rather than Resource, you can simplify the Uri sintax considerably.

```<code>Uri uri = new Uri("Images/image.jpg", UriKind.Relative);
</code>```

The difference, in case you are wondering...
If you navigate to the Bin/Debug directory of a Visual Studio project and find the XAP file that contains your program, rename it to a ZIP extension. And look inside.

In both cases the bitmap is obviusly stored somewhere within the XAP file.

With a Build Action of Resource for the file, it is stored inside the DLL file along with the compiled program.

With a Build Action of Content, the file is stored external to the dll file but within the XAP file, and when you rename the XAP file to a ZIP file, you can see the it.

ContentLicense: CC BY-SA 3.0

Body:
 BitmapImage img = new BitmapImage(new Uri("somepath",UriKind.Relative));
 WriteableBitmap wbm = new WriteableBitmap(img);

I get a Runtime error at the line above: "Object reference not set to an instance of an object."

Body:
If the build action of your image file is set to resource, then the following code will work.

Uri uri = new Uri("/ProjectName;component/Images/image.jpg", UriKind.Relative);
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage img = new BitmapImage();
img.SetSource(resourceInfo.Stream);
WriteableBitmap wbm = new WriteableBitmap(img);

Notice that the resource is accessed by the static method GetResourceStream defined by the application class.
Now if you change the build action of the file to Content rather than Resource, you can simplify the Uri sintax considerably.

Uri uri = new Uri("Images/image.jpg", UriKind.Relative);

The difference, in case you are wondering...
If you navigate to the Bin/Debug directory of a Visual Studio project and find the XAP file that contains your program, rename it to a ZIP extension. And look inside.

In both cases the bitmap is obviusly stored somewhere within the XAP file.

With a Build Action of Resource for the file, it is stored inside the DLL file along with the compiled program.

With a Build Action of Content, the file is stored external to the dll file but within the XAP file, and when you rename the XAP file to a ZIP file, you can see the it.


问:
Static method in generic class causes CA1000 warning
I'm working on a library to manage objects (Animals in my sample code). I have a base class named Animal and a generic class named SpecificAnimal. I also have Dog, Cat etc. which are implemented with the SpecificAnimal class.

If a user wants to create a dog, it is as simple as:

```<code>            var myDog = new Dog()
            {
                Name = "Rover",
                Age = 3
            };
            myDog.Add();
</code>```

The class hierarchy looks like this:

Animal Class

```<code>    public abstract class Animal
    {
        public static Animal GetByName(string animalName)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public static Animal GetById(int animalId)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public string Name { get; set; } = string.Empty;

        public int Age { get; set; }

        public void Add()
        {
            //  Add this Animal to the database
        }

        public void Update()
        {
            // Update this animal
        }
    }
</code>```

Generic SpecificAnimal class

```<code>    public abstract class SpecificAnimal<T> : Animal where T : SpecificAnimal<T>
    {
        public static string Genus { get; protected set; } = String.Empty;

        public new static T GetByName(string animalName)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetByName(animalName);
        }

        public new static T GetId(int animalId)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetById(animalId);
        }
    }
</code>```

Dog class

```<code>    public class Dog : SpecificAnimal<Dog>
    {
        public Dog()
        {
            Genus = "Canis";
        }

        //  Dog specific properties and methods
    }
</code>```

This code is working and (in my opinion) is easy for the consumer of the library to use.

My problem is that the static properties and methods in the SpecificAnimal class generate the warning:

```<code>CA1000: Do not declare static members on generic types
</code>```

https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1000

The documentation for CA1000 says "Do not suppress..." but, it doesn't suggest a better solution. If I shouldn't have static members in a generic class, what should I be doing?
The documentation says that static methods in a generic type are bad because of this awkward syntax:

```<code>var myDog = SpecificAnimal<Dog>.GetByName("Rover");
</code>```

I agree but, my users should never do that. Although, I don't know of a way to prevent it.

How can I add static members to a generic class without generating CA1000? How can I protect the SpecificAnimal class so that the user only has access to Dog and Animal?

答:
The warning exists because there's risk that the behavior might be different than the programmer expects. However, sometimes it's a useful pattern. I ran into this a few weeks ago when building a library.

Let's look at a more simplified example:

```<code>void Main()
{
    Baz<string>.Counter++;
    Baz<int>.Counter++;
    Console.WriteLine(Baz<object>.Counter);
}

public abstract class Foo
{
    public static int Counter { get; set; }
}

public class Baz<T> : Foo
{

}
</code>```

What is output? It's easy to think the output would be 0 because Baz<object> is a different closed generic type than Baz<string> or Baz<int>. In fact, the output is 2 because both post increment operations affect the same static variable.

Body:
I'm working on a library to manage objects (Animals in my sample code). I have a base class named Animal and a generic class named SpecificAnimal. I also have Dog, Cat etc. which are implemented with the SpecificAnimal class.

If a user wants to create a dog, it is as simple as:

            var myDog = new Dog()
            {
                Name = "Rover",
                Age = 3
            };
            myDog.Add();

The class hierarchy looks like this:

Animal Class

    public abstract class Animal
    {
        public static Animal GetByName(string animalName)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public static Animal GetById(int animalId)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public string Name { get; set; } = string.Empty;

        public int Age { get; set; }

        public void Add()
        {
            //  Add this Animal to the database
        }

        public void Update()
        {
            // Update this animal
        }
    }

Generic SpecificAnimal class

    public abstract class SpecificAnimal<T> : Animal where T : SpecificAnimal<T>
    {
        public static string Genus { get; protected set; } = String.Empty;

        public new static T GetByName(string animalName)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetByName(animalName);
        }

        public new static T GetId(int animalId)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetById(animalId);
        }
    }

Dog class

    public class Dog : SpecificAnimal<Dog>
    {
        public Dog()
        {
            Genus = "Canis";
        }

        //  Dog specific properties and methods
    }

This code is working and (in my opinion) is easy for the consumer of the library to use.

My problem is that the static properties and methods in the SpecificAnimal class generate the warning:

CA1000: Do not declare static members on generic types

https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1000

The documentation for CA1000 says "Do not suppress..." but, it doesn't suggest a better solution. If I shouldn't have static members in a generic class, what should I be doing?
The documentation says that static methods in a generic type are bad because of this awkward syntax:

var myDog = SpecificAnimal<Dog>.GetByName("Rover");

I agree but, my users should never do that. Although, I don't know of a way to prevent it.

How can I add static members to a generic class without generating CA1000? How can I protect the SpecificAnimal class so that the user only has access to Dog and Animal?

Body:
The warning exists because there's risk that the behavior might be different than the programmer expects. However, sometimes it's a useful pattern. I ran into this a few weeks ago when building a library.

Let's look at a more simplified example:

void Main()
{
    Baz<string>.Counter++;
    Baz<int>.Counter++;
    Console.WriteLine(Baz<object>.Counter);
}

public abstract class Foo
{
    public static int Counter { get; set; }
}

public class Baz<T> : Foo
{

}

What is output? It's easy to think the output would be 0 because Baz<object> is a different closed generic type than Baz<string> or Baz<int>. In fact, the output is 2 because both post increment operations affect the same static variable.


问:
Comparing dates with getTime() in EST timezone
I am looking if there is a better way (other than below solution) of comparing dates for all users (in different countries) in EST timezone. Need your inputs/help.

Basically I have to display three UI's based on  three different dates. Till June, 1st UI has to render, June to July second UI and from July 3rd UI has to display. These dates while comparing should be in EST timezone.

```<code>  const JulyDate = new Date("2022-07-01T00:00:00.000-05:00");
  const JuneDate = new Date("2022-06-01T00:00:00.000-05:00");
  if(new Date().getTime() < JuneDate.getTime()){
    renderUIPriorJune= true;
    renderUIJune= false;
    renderUIJuly= false;
  }
  else if(new Date().getTime() >= JuneDate.getTime() && new Date().getTime() < JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= true;
    renderUIJuly= false;

  }
  else if(new Date().getTime() >= JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= false;
    renderUIJuly= true;

  }

</code>```

I have defined June and July dates in EST timezone i.e. -5 hours as offset and then current date is compared with those dates.

Could you please let me know if this is the correct way of comparing or Is there a better way of doing. I am rather new to Java script.

Thank you in advance.

答:
Your logic is fine, but a simpler method is to just get the current month in the required timezone. By "EST" I guess you mean US Eastern Standard Time, which corresponds to the IANA timezone "US/Eastern".

So all you need to do is find out which month the date falls in, which can be done using toLocaleString with suitable options, e.g.

function getEasternMonth(date = new Date()) {
  return date.toLocaleString('en',{month: 'numeric', timeZone:'US/Eastern'});
}

console.log('Current month in US EST: ' + getEasternMonth());

let s = '2022-06-01T00:00:00Z';
console.log(s + ' is EST month ' + getEasternMonth(new Date(s)));```
</div>
</div>
</p>
<p>Now your logic is hugely simplified to:</p>
```let month = getEasternMonth();
if (month < 6) {
  // do stuff for pre–June
} else if (month == 6) {
  // do stuff for June
} else {
  // do stuff for post June
}
```

Note that all the above is using the calendar month number (i.e. 6 = June).

Body:
I am looking if there is a better way (other than below solution) of comparing dates for all users (in different countries) in EST timezone. Need your inputs/help.

Basically I have to display three UI's based on  three different dates. Till June, 1st UI has to render, June to July second UI and from July 3rd UI has to display. These dates while comparing should be in EST timezone.

  const JulyDate = new Date("2022-07-01T00:00:00.000-05:00");
  const JuneDate = new Date("2022-06-01T00:00:00.000-05:00");
  if(new Date().getTime() < JuneDate.getTime()){
    renderUIPriorJune= true;
    renderUIJune= false;
    renderUIJuly= false;
  }
  else if(new Date().getTime() >= JuneDate.getTime() && new Date().getTime() < JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= true;
    renderUIJuly= false;

  }
  else if(new Date().getTime() >= JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= false;
    renderUIJuly= true;

  }

I have defined June and July dates in EST timezone i.e. -5 hours as offset and then current date is compared with those dates.

Could you please let me know if this is the correct way of comparing or Is there a better way of doing. I am rather new to Java script.

Thank you in advance.

Body:
Your logic is fine, but a simpler method is to just get the current month in the required timezone. By "EST" I guess you mean US Eastern Standard Time, which corresponds to the IANA timezone "US/Eastern".

So all you need to do is find out which month the date falls in, which can be done using toLocaleString with suitable options, e.g.

function getEasternMonth(date = new Date()) {
  return date.toLocaleString('en',{month: 'numeric', timeZone:'US/Eastern'});
}

console.log('Current month in US EST: ' + getEasternMonth());

let s = '2022-06-01T00:00:00Z';
console.log(s + ' is EST month ' + getEasternMonth(new Date(s)));

Now your logic is hugely simplified to:

let month = getEasternMonth();
if (month < 6) {
  // do stuff for pre–June
} else if (month == 6) {
  // do stuff for June
} else {
  // do stuff for post June
}

Note that all the above is using the calendar month number (i.e. 6 = June).


问:
Any benefit/drawback/possibility of using getDataRange/getValues outside of a function
My apologies for the insane question but is it possible to have something like:

```<code>var data = ss.getSheetByName("info").getDataRange().getValues();
</code>```

called as a global (ie, before using any functions) and then having that data var be available to all the functions?   My program mainly reads through arrays with the main sheet having over 5k rows with mult columns of info and another sheet having almost 15k rows/mult columns of info.

Was wondering if it would be any saver of time by doing it this way instead of calling it every time the function is called.

I've been using arrays because I hear it's quicker for Google to flip through it find a particular piece of data then it is of Objects, etc.  Sorry if I am making ZERO sense here ;)

答:
Code in the global scope of a Google Apps Script is loaded on every execution, meaning that if you declared a variable in the global-scope it will be "overwritten" on every execution.

It might help if you have a "main" function that calls several helper functions that require the same object instance but this might have a "slightly" negative effects if you have functions that don't require that object instance. If your spreadsheet takes a lot of time to be loaded then the negative effects will not be "slightly", they will be noticeable, importantly or even dramatically negative.

Body:
My apologies for the insane question but is it possible to have something like:

var data = ss.getSheetByName("info").getDataRange().getValues();

called as a global (ie, before using any functions) and then having that data var be available to all the functions?   My program mainly reads through arrays with the main sheet having over 5k rows with mult columns of info and another sheet having almost 15k rows/mult columns of info.

Was wondering if it would be any saver of time by doing it this way instead of calling it every time the function is called.

I've been using arrays because I hear it's quicker for Google to flip through it find a particular piece of data then it is of Objects, etc.  Sorry if I am making ZERO sense here ;)


问:
paperclip working in development but not working in production?
I'm pretty new to rails and seem to be having an issue with the paperclip gem. I installed the gem and it works well in development (localhost:3000) but when I'm running it on the heroku server, for some reason it does not want to attach files, and the app breaks (error 500 page).

Here is the process i ran... I pushed my file to heroku, heroku ran rake db:migrate (to add paperclip migrations), and then I ran heroku restart (to restart the app with new migrations). This did not seem to help.

Here is the code that I have for paperclip:

user.rb model:

```<code>  has_attached_file :avatar,
                    :styles => {:small => "70x70>"},
                    :url  => "/users/:attachment/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/users/:attachment/:id/:style/:basename.:extension"
  validates_attachment_size :avatar, :less_than => 500.kilobytes
  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png']
</code>```

edit_form.html.haml view:

```<code>  = form_for (@user || User.new), :html => { :multipart => true } do |f|
  ...
  .profile_picture.text_field
    = image_tag current_profile.avatar.url(:small)
    %br
    = f.file_field :avatar
</code>```

Again, for some reason it runs great in development, but breaks down in production. Any pointers would be greatly appreciated... I just cant seem to figure this out and it's pretty frustrating. Thank you so much for your time and any help!

答: You could be having a few problems. However, the first is that you can not write to the file system on Heroku.  You will have to implement a different storage mechanism such as s3. You can read about this limitation here: http://devcenter.heroku.com/articles/read-only-filesystem</p>

Body:
I'm pretty new to rails and seem to be having an issue with the paperclip gem. I installed the gem and it works well in development (localhost:3000) but when I'm running it on the heroku server, for some reason it does not want to attach files, and the app breaks (error 500 page).

Here is the process i ran... I pushed my file to heroku, heroku ran rake db:migrate (to add paperclip migrations), and then I ran heroku restart (to restart the app with new migrations). This did not seem to help.

Here is the code that I have for paperclip:

user.rb model:

  has_attached_file :avatar,
                    :styles => {:small => "70x70>"},
                    :url  => "/users/:attachment/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/users/:attachment/:id/:style/:basename.:extension"
  validates_attachment_size :avatar, :less_than => 500.kilobytes
  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png']

edit_form.html.haml view:

  = form_for (@user || User.new), :html => { :multipart => true } do |f|
  ...
  .profile_picture.text_field
    = image_tag current_profile.avatar.url(:small)
    %br
    = f.file_field :avatar

Again, for some reason it runs great in development, but breaks down in production. Any pointers would be greatly appreciated... I just cant seem to figure this out and it's pretty frustrating. Thank you so much for your time and any help!


问:
Getting values in Seaborn boxplot
I would like to get the specific values by a boxplot generated in Seaborn
(i.e., media, quartile). For example, in the boxplot below (source: link)
Is there a any way to get the media and quartiles instead of manually estimation? </p>

```<code>import numpy as np
import seaborn as sns
sns.set(style="ticks", palette="muted", color_codes=True)

# Load the example planets dataset
planets = sns.load_dataset("planets")

# Plot the orbital period with horizontal boxes
ax = sns.boxplot(x="distance", y="method", data=planets,
             whis=np.inf, color="c")
</code>```

答:
Sometimes I use my data as a list of arrays instead of pandas. So for that, you might need:</p>
```<code>min(d), np.quantile(d, 0.25), np.median(d), np.quantile(d, 0.75), max(d)
</code>```

Title: Getting values in Seaborn boxplot

Body:
I would like to get the specific values by a boxplot generated in Seaborn
(i.e., media, quartile). For example, in the boxplot below (source: link)
Is there a any way to get the media and quartiles instead of manually estimation?

import numpy as np
import seaborn as sns
sns.set(style="ticks", palette="muted", color_codes=True)

# Load the example planets dataset
planets = sns.load_dataset("planets")

# Plot the orbital period with horizontal boxes
ax = sns.boxplot(x="distance", y="method", data=planets,
             whis=np.inf, color="c")

Body:
Sometimes I use my data as a list of arrays instead of pandas. So for that, you might need:

min(d), np.quantile(d, 0.25), np.median(d), np.quantile(d, 0.75), max(d)


问:
Docker push to AWS ECR hangs immediately and times out
I'm trying to push my first docker image to ECR.  I've followed the steps provided by AWS and things seem to be going smoothly until the final push which immediately times out.  Specifically, I pass my aws ecr credentials to docker and get a "login succeeded" message.  I then tag the image which also works.  pushing to the ecr repo I get no error message, just the following:

```<code>The push refers to repository [xxxxxxxxxxx.dkr.ecr.ca-central-1.amazonaws.com/reponame]
714c1b96dd83: Retrying in 1 second
d2cdc77dd068: Retrying in 1 second
30aad807caf5: Retrying in 1 second
0559774c4ea2: Retrying in 1 second
285b8616682f: Retrying in 1 second
4aeea0ec2b15: Waiting
1b1312f842d8: Waiting
c310009e0ef3: Waiting
a48777e566d3: Waiting
2a0c9f28029a: Waiting
EOF
</code>```

It tries a bunch of times and then exits with no message.  Any idea what's wrong?

答:
If anyone is still stuck with the issue. I would highly recommend watching this short vid https://www.youtube.com/watch?v=89ZeXaZEf80&ab_channel=IdenticalCloud

Here are the steps I took to fix the issue (if you prefer not to watch the video):

Create a new IAM user with "Access keys" checked

Under permissions, click on "attach existing policies directly" and choose "AmazonEC2ContainerRegistryFullAccess"

Download the CSV file

Run "AWS configure" on your terminal and pass in the credentials from the CSV file

Set the location to the location you created your ECR (mine was us-east-1)

Go to ECR and follow the steps to push the image

Body:
I'm trying to push my first docker image to ECR.  I've followed the steps provided by AWS and things seem to be going smoothly until the final push which immediately times out.  Specifically, I pass my aws ecr credentials to docker and get a "login succeeded" message.  I then tag the image which also works.  pushing to the ecr repo I get no error message, just the following:

The push refers to repository [xxxxxxxxxxx.dkr.ecr.ca-central-1.amazonaws.com/reponame]
714c1b96dd83: Retrying in 1 second
d2cdc77dd068: Retrying in 1 second
30aad807caf5: Retrying in 1 second
0559774c4ea2: Retrying in 1 second
285b8616682f: Retrying in 1 second
4aeea0ec2b15: Waiting
1b1312f842d8: Waiting
c310009e0ef3: Waiting
a48777e566d3: Waiting
2a0c9f28029a: Waiting
EOF

It tries a bunch of times and then exits with no message.  Any idea what's wrong?


问:
problem with directly calling class methods using multiprocessing in Python
Here is the code without multiprocessing that works. It outputs 144.

```<code>class persons():
    def __init__(self):
        self.num1 = None
        self.num2 = None

    def weird_squaring_algo(self, num1):
        self.num1 = num1
        self.num2 = 10

        self.func1(num1)

        return self.num2

    def func1(self, mul):
        self.num2 = self.num1 * mul
        return

p = persons()
p.weird_squaring_algo(12)
</code>```

And when I want to do this using multiprocessing it doesn't seem to work. It outputs 10.

```<code>class persons():
    def __init__(self):
        self.num1 = None
        self.num2 = None

    def weird_squaring_algo(self, num1):
        self.num1 = num1
        self.num2 = 10
        pool = mp.Pool(8)
        r = pool.map(self.func1, [num1])
        pool.close()
        pool.join()

        return self.num2

    def func1(self, mul):
        self.num2 = self.num1 * mul
        return

p = persons()
p.weird_squaring_algo(13)
</code>```

What am I doing wrong in the second code?

答:
Found the answer.  Multiprocessing does not pass the original object back to the caller.

corrected code

```<code>class persons():
    def __init__(self):
        self.num1 = None
        self.num2 = None

    def weird_squaring_algo(self, num1):
        self.num1 = num1
        self.num2 = 10
        pool = mp.Pool(8)
        self.num2 = pool.map(self.func1, [num1])[0]
        pool.close()
        pool.join()

        return self.num2

    def func1(self, mul):
        self.num2 = self.num1 * mul
        return self.num2

p = persons()
p.weird_squaring_algo(13)
</code>```

Body:
Here is the code without multiprocessing that works. It outputs 144.

class persons():
    def __init__(self):
        self.num1 = None
        self.num2 = None

    def weird_squaring_algo(self, num1):
        self.num1 = num1
        self.num2 = 10

        self.func1(num1)

        return self.num2

    def func1(self, mul):
        self.num2 = self.num1 * mul
        return

p = persons()
p.weird_squaring_algo(12)

And when I want to do this using multiprocessing it doesn't seem to work. It outputs 10.

class persons():
    def __init__(self):
        self.num1 = None
        self.num2 = None

    def weird_squaring_algo(self, num1):
        self.num1 = num1
        self.num2 = 10
        pool = mp.Pool(8)
        r = pool.map(self.func1, [num1])
        pool.close()
        pool.join()

        return self.num2

    def func1(self, mul):
        self.num2 = self.num1 * mul
        return

p = persons()
p.weird_squaring_algo(13)

What am I doing wrong in the second code?

Body:
Found the answer.  Multiprocessing does not pass the original object back to the caller.

corrected code

class persons():
    def __init__(self):
        self.num1 = None
        self.num2 = None

    def weird_squaring_algo(self, num1):
        self.num1 = num1
        self.num2 = 10
        pool = mp.Pool(8)
        self.num2 = pool.map(self.func1, [num1])[0]
        pool.close()
        pool.join()

        return self.num2

    def func1(self, mul):
        self.num2 = self.num1 * mul
        return self.num2

p = persons()
p.weird_squaring_algo(13)


问:
Problem with Styling withing pandas dtaframe: AttributeError: 'float' object has no attribute 'max'
I was trying to highlight minimum values within sliced data frame in google colab notebook as below:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

def highlight_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

#def highlight_max(s, props=''):
#    return np.where(s == np.nanmax(s.values), props, '')

dff = pd.DataFrame({'A': np.linspace(1, 10, 10)})
dff = pd.concat([dff, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
dff.style.\
    applymap(color_negative_red ,     subset=['B',  'C',    'D']).\
    applymap(highlight_max,           subset=['B',  'C',    'D'])

```
<p>I face <code>AttributeError: 'float' object has no attribute 'max'</code> error with following traceback:</p>
```---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    332                 pass
    333             else:
--> 334                 return printer(obj)
    335             # Finally look for special method names
    336             method = get_real_method(obj, self.print_method)

13 frames
<ipython-input-2-2c6ddd2b019e> in highlight_max(s)
     12     highlight the maximum in a Series yellow.
     13     '''
---> 14     is_max = s == s.max()
     15     return ['background-color: yellow' if v else '' for v in is_max]
     16

AttributeError: 'float' object has no attribute 'max'
```

Although I checked this post & post2, especially this post with similar error I couldn't figure out yet.

答:
Here's what you can do:

```<code>dff.style.\
    applymap(color_negative_red ,     subset=['B',  'C',    'D']).\
    apply(   highlight_max,           subset=['B',  'C',    'D'])
</code>```

.applymap applies a function element-wise, whereas .apply applies a function to the series.

Body:
I was trying to highlight minimum values within sliced data frame in google colab notebook as below:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

def highlight_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

#def highlight_max(s, props=''):
#    return np.where(s == np.nanmax(s.values), props, '')

dff = pd.DataFrame({'A': np.linspace(1, 10, 10)})
dff = pd.concat([dff, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
dff.style.\
    applymap(color_negative_red ,     subset=['B',  'C',    'D']).\
    applymap(highlight_max,           subset=['B',  'C',    'D'])

I face AttributeError: 'float' object has no attribute 'max' error with following traceback:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    332                 pass
    333             else:
--> 334                 return printer(obj)
    335             # Finally look for special method names
    336             method = get_real_method(obj, self.print_method)

13 frames
<ipython-input-2-2c6ddd2b019e> in highlight_max(s)
     12     highlight the maximum in a Series yellow.
     13     '''
---> 14     is_max = s == s.max()
     15     return ['background-color: yellow' if v else '' for v in is_max]
     16

AttributeError: 'float' object has no attribute 'max'

Although I checked this post & post2, especially this post with similar error I couldn't figure out yet.

Body:
Here's what you can do:

dff.style.\
    applymap(color_negative_red ,     subset=['B',  'C',    'D']).\
    apply(   highlight_max,           subset=['B',  'C',    'D'])

.applymap applies a function element-wise, whereas .apply applies a function to the series.


问:
Unable to access the API key using BuildConfig
I'm using secrets-gradle-plugin to read the API keys that I put in my local.properties.

I've added this code into the root build.gradle

```<code>buildscript {
  dependencies {
    classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.0"
  }
}
</code>```

For app build.gradle

```<code>plugins {
  id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}

android {
  compileSdk 31
...
}
</code>```

And this is my local.properties

```<code>## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#
sdk.dir=/Users/xxx/Library/Android/sdk
apiKey=YOUR_API_KEY
</code>```

Then when I tried to access it from any class/application BuildConfig.apiKey is not there. Am I missing any steps here? Been trying for few hours but doesn't found any way to make this work.

答:
I end up reading the API value in local.properties in app's build.gradle and assigning it to BuildConfig. This is done under defaultConfig tag.

```<code>Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
buildConfigField "String", "API_KEY", "\"${properties.getProperty('API_KEY')}\""
</code>```

Body:
I'm using secrets-gradle-plugin to read the API keys that I put in my local.properties.

I've added this code into the root build.gradle

buildscript {
  dependencies {
    classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.0"
  }
}

For app build.gradle

plugins {
  id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}

android {
  compileSdk 31
...
}

And this is my local.properties

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#
sdk.dir=/Users/xxx/Library/Android/sdk
apiKey=YOUR_API_KEY

Then when I tried to access it from any class/application BuildConfig.apiKey is not there. Am I missing any steps here? Been trying for few hours but doesn't found any way to make this work.

Body:
I end up reading the API value in local.properties in app's build.gradle and assigning it to BuildConfig. This is done under defaultConfig tag.

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
buildConfigField "String", "API_KEY", "\"${properties.getProperty('API_KEY')}\""


问:
How do I host multiple Node.js sites on the same IP/server with different domains?
I have a linux server with a single IP bound to it. I want to host multiple Node.js sites on this server on this IP, each (obviously) with a unique domain or subdomain. I want them all on port 80.

What are my options to do this?

An obvious solution seems to be to have all domains serviced by a node.js web app that acts as a proxy and does a pass through to the other node.js apps running on unique ports.

答:
This can be done super easily by redbird. Suppose you have two domain names example.com and example1.com and two website serving on port 8000 and 8001.

You can set a reverse proxy to the two websites by the following scripts.

```<code>var proxy = require('redbird')({port: 80});
proxy.register("example.com", "http://localhost:8000");
proxy.register("example1.com", "http://localhost:8001");
</code>```

You can use process management tool such as pm2 to run the scripts so that it will continue serving after you close your shell.

Body:
This can be done super easily by redbird. Suppose you have two domain names example.com and example1.com and two website serving on port 8000 and 8001.

You can set a reverse proxy to the two websites by the following scripts.

var proxy = require('redbird')({port: 80});
proxy.register("example.com", "http://localhost:8000");
proxy.register("example1.com", "http://localhost:8001");

You can use process management tool such as pm2 to run the scripts so that it will continue serving after you close your shell.


问:
How can I return data with a timestamp and how to filter it?
I'm completely new to SQL and I'm struggling. I need to run a query from the dates mentioned below and split the timestamped data into shift hours 6-13:59, 14-21:59 and 22 - 05:59. I need to see how many shipments have been sent in between those hours. I came up with something like this, but it doesn't seem to work.

When I put the date without the timestamp the data gets returned, but I want to have only those rows returned that have been sent in between 6 - 14. The SDG table includes a timestamp, so I don't understand why it doesn't work.

```<code>select s1.date, k.su, count(distinct s1.nr) AMO_SHIP2021
from sdg s1 , client k
where s1.clientnr in ('1')
and s1.date between '01.12.2021 06:00:00' and '14.12.2021 13:59:59'
and s1.function in ('20')
and k.nr = s1.clientnr
group by s1.date, k.su, s1.function
</code>```

答:
You should post the table structure there. Generally, if your column is of Date type you need to operate dates using BETWEEN with dates and not strings

```<code>s1.date BETWEEN to_date('01.12.2021 06:00:00', 'DD.MM.YYYY HH24:MI:SS') AND
to_date('14.12.2021 13:59:59', 'DD.MM.YYYY HH24:MI:SS')
</code>```

Refer in your search to FORMAT MODEL.

to_date('string date', 'format model')

Body:
I'm completely new to SQL and I'm struggling. I need to run a query from the dates mentioned below and split the timestamped data into shift hours 6-13:59, 14-21:59 and 22 - 05:59. I need to see how many shipments have been sent in between those hours. I came up with something like this, but it doesn't seem to work.

When I put the date without the timestamp the data gets returned, but I want to have only those rows returned that have been sent in between 6 - 14. The SDG table includes a timestamp, so I don't understand why it doesn't work.

select s1.date, k.su, count(distinct s1.nr) AMO_SHIP2021
from sdg s1 , client k
where s1.clientnr in ('1')
and s1.date between '01.12.2021 06:00:00' and '14.12.2021 13:59:59'
and s1.function in ('20')
and k.nr = s1.clientnr
group by s1.date, k.su, s1.function

Body:
You should post the table structure there. Generally, if your column is of Date type you need to operate dates using BETWEEN with dates and not strings

s1.date BETWEEN to_date('01.12.2021 06:00:00', 'DD.MM.YYYY HH24:MI:SS') AND
to_date('14.12.2021 13:59:59', 'DD.MM.YYYY HH24:MI:SS')

Refer in your search to FORMAT MODEL.

to_date('string date', 'format model')


问:
Can i use both NSLocationWhenInUseUsageDescription & NSLocationAlwaysUsageDescription?
One of the frameworks I used (Indoo.rs SDK,for bluetooth location detection) was developed to work with NSLocationWhenInUseUsageDescription in the plist file. I am also using Core Location manager which is configured to work with NSLocationAlwaysUsageDescription.

Can I use both in my .plist? I am not sure how to proceed with this when there are two types of hardware (bluetooth & GPS/WIFI/Celltowers) used for location services.

答:
NSLocationAlwaysUsageDescription is deprecated.

Apple reference


问:
I got a object object and cant select the items
I get a json-Response with values and add this to the interface. But I cant select them in the html-page.

```<code>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  title: string
  releasedate: number
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any

}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];
  gamedetail: GAMEDETAIL[]= [];
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {

    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
    });
    }

    getJSON(spielid: Number): Observable<any> {
      return this.http.get("https://example.org/api/gamedetail/" + spielid);
    }

}
</code>```

Here is the html for this:

```<code><h1>{{ gamedetail.dontfindanykey }}</h1>>
</code>```

I can select the gamedetail.title (for example). But i can't select title or description or else. In the log would the complete json be viewed

This is the json-response that I get from the server:

```
    {"id":1,
     "title":"Ligretto",
     "releasedate":2000,
    "producer":
[{"company":"Schmidt","url":"https:\/\/www.example.de"}],"pdffile":"https:\/\/cdn.example.de","description":"Das ist die Beschreibung zum Spiel","images":[{"position":0,"imagefile":"https:\/\/cdn.example.org"},{"position":1,"imagefile":"https:\/\/cdn.example.org"}],"youtubelink":"https:\/\/example.org","adddate":"2021-12-22 22:22:44","changedate":"2022-01-11 11:11:20"}```

答:
this is the problematic line;

```<code>gamedetail: GAMEDETAIL[]= [];
</code>```

gamedetail's type is array, you're assigning object to it. You can't read array.title.

This will solve the problem, gamedetail isn't an array, your response json is object;

```<code>
gamedetail: GAMEDETAIL;
</code>```

Body:
I get a json-Response with values and add this to the interface. But I cant select them in the html-page.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  title: string
  releasedate: number
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any

}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];
  gamedetail: GAMEDETAIL[]= [];
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {

    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
    });
    }

    getJSON(spielid: Number): Observable<any> {
      return this.http.get("https://example.org/api/gamedetail/" + spielid);
    }

}

Here is the html for this:

{{ gamedetail.dontfindanykey }}
>

I can select the gamedetail.title (for example). But i can't select title or description or else. In the log would the complete json be viewed

This is the json-response that I get from the server:

    {"id":1,
     "title":"Ligretto",
     "releasedate":2000,
    "producer":
[{"company":"Schmidt","url":"https:\/\/www.example.de"}],"pdffile":"https:\/\/cdn.example.de","description":"Das ist die Beschreibung zum Spiel","images":[{"position":0,"imagefile":"https:\/\/cdn.example.org"},{"position":1,"imagefile":"https:\/\/cdn.example.org"}],"youtubelink":"https:\/\/example.org","adddate":"2021-12-22 22:22:44","changedate":"2022-01-11 11:11:20"}

Body:
this is the problematic line;

gamedetail: GAMEDETAIL[]= [];

gamedetail's type is array, you're assigning object to it. You can't read array.title.

This will solve the problem, gamedetail isn't an array, your response json is object;

gamedetail: GAMEDETAIL;


问:
Docker: get list of all the registries configured on a host
Can docker be connected to more than one registry at a time and how to figure out which registries it is currently connected too?

```<code>$ docker help | fgrep registr
login       Log in to a Docker registry
logout      Log out from a Docker registry
pull        Pull an image or a repository from a registry
push        Push an image or a repository to a registry
</code>```

As you can see, there is no option to list the registries.  I did find
a way by running:

```<code>$ docker system info | fgrep -i registr
 Registry: https://index.docker.io/v1/
</code>```

So...  one regsitry at a time only?  It is not like apt where one can point to more than one source?  Anybody can point me to some good documentation about docker and registries?

Oddly, I search the web to no vail.

答:
Aside from docker login, Docker isn't "connected to a registry" per se.  Registry names are part of the image name, and Docker will connect to a registry server if it needs to pull an image.

As a specific example, the official Docker image for Elasticsearch is on a non-default registry run by Elastic.  The example in that documentation is

docker pull docker.elastic.co/elasticsearch/elasticsearch:7.17.0
#           ^^^^^^^^^^^^^^^^^
#           registry host name
```
<p>You don't need to otherwise configure your system to connect to that registry, download an index, or anything else.  In fact, you don't even need this <code>docker pull</code> command; if you directly <code>docker run</code> the image, Docker will download it if it doesn't have a copy locally.</p>
<p>The default registry is Docker Hub, <code>docker.io</code>, and this cannot be changed.</p>
<p>There are several alternate registries out there.  The various public-cloud providers each have their own, and there are also several free-standing image registries.  Each has its own instructions on how to set it up.  You always need to include the registry name as part of the image name.  The Google Container Registry has a simple name syntax, for example, so if you use GCR then you can</p>
<pre class="lang-sh prettyprint-override"><code># build an image locally, labeled to be stored in GCR
# (this step does not contact or use GCR at all)
docker build gcr.io/my-name/my-image:tag

# authenticate to the registry
# (normally GCR has a Google-specific login sequence)
docker login https://gcr.io

# push the image
docker push gcr.io/my-name/my-image:tag

# run the image, pulling it if not present
docker run ... gcr.io/my-name/my-image:tag
</code>```

Body:
Can docker be connected to more than one registry at a time and how to figure out which registries it is currently connected too?

$ docker help | fgrep registr
login       Log in to a Docker registry
logout      Log out from a Docker registry
pull        Pull an image or a repository from a registry
push        Push an image or a repository to a registry

As you can see, there is no option to list the registries.  I did find
a way by running:

$ docker system info | fgrep -i registr
 Registry: https://index.docker.io/v1/

So...  one regsitry at a time only?  It is not like apt where one can point to more than one source?  Anybody can point me to some good documentation about docker and registries?

Oddly, I search the web to no vail.

Body:
Aside from docker login, Docker isn't "connected to a registry" per se.  Registry names are part of the image name, and Docker will connect to a registry server if it needs to pull an image.

As a specific example, the official Docker image for Elasticsearch is on a non-default registry run by Elastic.  The example in that documentation is

docker pull docker.elastic.co/elasticsearch/elasticsearch:7.17.0
#           ^^^^^^^^^^^^^^^^^
#           registry host name

You don't need to otherwise configure your system to connect to that registry, download an index, or anything else.  In fact, you don't even need this docker pull command; if you directly docker run the image, Docker will download it if it doesn't have a copy locally.

The default registry is Docker Hub, docker.io, and this cannot be changed.

There are several alternate registries out there.  The various public-cloud providers each have their own, and there are also several free-standing image registries.  Each has its own instructions on how to set it up.  You always need to include the registry name as part of the image name.  The Google Container Registry has a simple name syntax, for example, so if you use GCR then you can

# build an image locally, labeled to be stored in GCR
# (this step does not contact or use GCR at all)
docker build gcr.io/my-name/my-image:tag

# authenticate to the registry
# (normally GCR has a Google-specific login sequence)
docker login https://gcr.io

# push the image
docker push gcr.io/my-name/my-image:tag

# run the image, pulling it if not present
docker run ... gcr.io/my-name/my-image:tag


问:
Trying to fix table header, getting css issue
Initially I asked this Question and written my own plugin to achieve the same,But i am facing very strange issue regarding to css of table.

After applying the plugin table cells borders are getting dis-sorted.

jsFiddle of the problem: Problem demo

In fiddle you can see that after first cell of the first tr, the header border line and table border line don't line up. I want the border line of thead cells and td cells to line up.
Can anyone tell me how to achieve that?

答:
the simple solution is that when you calculate the width of the column you do not include padding. So you need to change the line

```<code>$t.find('tr:first th').each( function() {
 cols.push($(this).width());
});
</code>```

to

```<code>$t.find('tr:first th').each( function() {
 cols.push($(this).outerWidth());
});
</code>```

if your cells have margins use .outerWidth(true)

This works in quirks mode with IE7&8 and Chrome IE8 has a problem in strict mode. However I believe that that problem is caused by the added scrollbar. If you want to use IE8 in strict mode you have to allow for the width of the vertical scrollbar..

Body:
the simple solution is that when you calculate the width of the column you do not include padding. So you need to change the line

$t.find('tr:first th').each( function() {
 cols.push($(this).width());
});

to

$t.find('tr:first th').each( function() {
 cols.push($(this).outerWidth());
});

if your cells have margins use .outerWidth(true)

This works in quirks mode with IE7&8 and Chrome IE8 has a problem in strict mode. However I believe that that problem is caused by the added scrollbar. If you want to use IE8 in strict mode you have to allow for the width of the vertical scrollbar..


问:
Why is my CircularProgressIndicator spinning randomly when the screen loads?
I have a CircularProgressIndicator that is meant to display progress when the user presses a button. However, when I open the screen that uses this class it shows a loading animation and I'm not sure why. When the screen opens, it shouldn't show the animation until the user presses the button.

When the screen opens you see something similar to the animation on this page: https://www.c-sharpcorner.com/article/create-chrome-like-loading-animation/

```<code>class _MsgInputState extends State<MsgInput> with TickerProviderStateMixin {

  AnimationController? controller;

  @override
  void initState() {
    super.initState();
    initialize();

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  void initialize() async {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    )..addListener(() {
      setState(() {});
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      controller?.forward();
                    },
                    onLongPressDown: (details) async {
                      controller?.forward();
                    },
                    onLongPressUp: () async {
                      controller?.stop();
                      controller?.reset();
                    },
                    child: Text('Record'),
                  ),
                ],
              ),
              Row(
                children: <Widget>[
                  SizedBox(width: 100),
                  CircularProgressIndicator(
                    value: controller?.value,
                    semanticsLabel: 'Linear progress indicator',
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }
</code>```

答:
Here is a quick examples on how the provided example could be achieved:</p>
```<code>class StateProgress extends StatelessWidget {
  const StateProgress({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: SizedBox(
        height: 50,
        width: 50,
        child: CircularProgressIndicator(
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation<Color>(Colors.blueAccent /*Should be the color of the indicator*/),
          backgroundColor: Colors.white, //  Could be made to match the color of the background the indicator is on
        ),
      ),
    );
  }
}
</code>```

Body:
I have a CircularProgressIndicator that is meant to display progress when the user presses a button. However, when I open the screen that uses this class it shows a loading animation and I'm not sure why. When the screen opens, it shouldn't show the animation until the user presses the button.

When the screen opens you see something similar to the animation on this page: https://www.c-sharpcorner.com/article/create-chrome-like-loading-animation/

class _MsgInputState extends State<MsgInput> with TickerProviderStateMixin {

  AnimationController? controller;

  @override
  void initState() {
    super.initState();
    initialize();

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  void initialize() async {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    )..addListener(() {
      setState(() {});
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      controller?.forward();
                    },
                    onLongPressDown: (details) async {
                      controller?.forward();
                    },
                    onLongPressUp: () async {
                      controller?.stop();
                      controller?.reset();
                    },
                    child: Text('Record'),
                  ),
                ],
              ),
              Row(
                children: <Widget>[
                  SizedBox(width: 100),
                  CircularProgressIndicator(
                    value: controller?.value,
                    semanticsLabel: 'Linear progress indicator',
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }

Body:
Here is a quick examples on how the provided example could be achieved:

class StateProgress extends StatelessWidget {
  const StateProgress({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: SizedBox(
        height: 50,
        width: 50,
        child: CircularProgressIndicator(
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation<Color>(Colors.blueAccent /*Should be the color of the indicator*/),
          backgroundColor: Colors.white, //  Could be made to match the color of the background the indicator is on
        ),
      ),
    );
  }
}


问:
How do I check if there is a child at an n position in a n-ary tree in OCaml?
I'm trying to make a function that, given a tuple list (I don't know if tuple is the correct term, what i mean is a (x,y) list) and an n-ary tree, it returns the leaf that you get from checking if a key in the tuple is present in the tree, and taking the child in the position of the value associated to that key, if it doesn't exist, raise an error.

I know I didn't explain it well, so I'll help myself with an example.
tuple list = [(1,3);(2,2);(3,1);(10,1)] if the the root's value is 1 then it will check the third child (if not it will go on with the list), then if the child's value is 10, it will check his first child until it will find a leaf.

What i thought to do was to first use List.map to remove the elements that don't match with a tuple's key and the childs that are not in the associated value's value position, and then do the same to their childs recursively.

Here is what I did:

```<code>type 'a ntree = Tr of 'a * 'a ntree list;;
let leaf x = Tr(x,[]);;

let alb = Tr(1,[Tr(2,[leaf 3; leaf 4; leaf 2]);Tr(5,[leaf 11; leaf 10]);Tr(3,[leaf 9; leaf 7; leaf 10])]);;
let guida = [(1,3);(2,2);(3,1);(10,1);(16,2);(11,2)];;

let rec cerca_foglia guida (Tr(x,tlist)) =
  match tlist with
    [] -> x
  |_ -> List.map(fun a -> List.mem_assoc x guida && (*a.position = List.nth tlist List.assoc x guida*)) (cerca tlist)
and cerca = function
    [] -> raise NotFound
  |[t] -> cerca_foglia guida t
  |t::rest ->
      try cerca_foglia guida t
      with NotFound -> cerca rest

</code>```

Of course, a.position does not exist, so how can I check it?

I also tried it differently:

```<code>let rec cerca_foglia guida (Tr(x,tlist)) =
  match tlist with
    [] -> x
  |_ -> List.map(fun a -> a = List.nth tlist List.assoc x guida) (cerca tlist)
and cerca = function
    [] -> raise NotFound
  |[t] -> if List.mem_assoc t guida then  cerca_foglia guida t else raise NotFound
  |t::rest ->
      try cerca_foglia guida t
      with NotFound -> cerca rest
</code>```

But it still gives errors...How can I solve it?

答:
After much pondering, I think I might have understood some of this. I have written two functions: find_child and find_child2.

```<code>type 'a ntree = Tr of 'a * 'a ntree list

let leaf x = Tr(x,[])

let alb = Tr(1,[Tr(2,[leaf 3; leaf 4; leaf 2]);Tr(5,[leaf 11; leaf 10]);Tr(3,[leaf 9; leaf 7; leaf 10])])

let guida = [(1,3);(2,2);(3,1);(10,1);(16,2);(11,2)]

let rec find_child (Tr (root, children) as tree) =
  function
  | [] -> None
  | (k, v)::_ when root = k -> Some (List.nth children (v - 1))
  | _::kvs -> find_child tree kvs

let rec find_child2 (Tr (root, children) as tree) key_val_list =
  match children with
  | [] -> Some tree
  | _ ->
    (match key_val_list with
     | [] -> None
     | (k, v)::kvs when root = k -> find_child2 (List.nth children (v - 1)) kvs
     | _::kvs -> find_child2 tree kvs)
</code>```

The find_child function stops at the first match it finds. So evaluating find_child alb guida yields:

utop # find_child alb guida;;
- : int ntree option = Some (Tr (3, [Tr (9, []); Tr (7, []); Tr (10, [])]))
```
<p>The <code>find_child2</code> function does something similar, but it only stops if it finds a "leaf" or if it doesn't find any of the keys it's looking for in the current node.</p>
<pre class="lang-none prettyprint-override"><code>utop # find_child2 alb guida;;
- : int ntree option = Some (Tr (9, []))
</code>```

And refactoring find_child2 a bit to clean it up and handle the Failure "nth" exception that may occur:

```<code>let rec find_child3 (Tr (root, children) as tree) key_val_list =
  match children, key_val_list with
  | [], _ -> Some tree
  | _, [] -> None
  | _, (k, v)::kvs when root = k ->
    (match List.nth children (v - 1) with
     | child -> find_child3 child kvs
     | exception (Failure "nth") -> None)
  | _, _::kvs -> find_child3 tree kvs
  | exception Failure "nth" -> None
</code>```

Sketching out what the recursion looks like when we evaluate find_child3 alb guida:

find_child3 alb guida

find_child3 (Tr(1,
               [Tr(2,[leaf 3; leaf 4; leaf 2]);
                Tr(5,[leaf 11; leaf 10]);
                Tr(3,[leaf 9; leaf 7; leaf 10])]))
            [(1,3);(2,2);(3,1);(10,1);(16,2);(11,2)]

find_child3 (Tr(3,[leaf 9; leaf 7; leaf 10]))
            [(2,2);(3,1);(10,1);(16,2);(11,2)]

find_child3 (Tr(3,[leaf 9; leaf 7; leaf 10]))
            [(3,1);(10,1);(16,2);(11,2)]

find_child3 (leaf 9) [(10,1);(16,2);(11,2)]

Some (Tr (9, []))
```

Is this the kind of thing you're looking for?

Body:
I'm trying to make a function that, given a tuple list (I don't know if tuple is the correct term, what i mean is a (x,y) list) and an n-ary tree, it returns the leaf that you get from checking if a key in the tuple is present in the tree, and taking the child in the position of the value associated to that key, if it doesn't exist, raise an error.

I know I didn't explain it well, so I'll help myself with an example.
tuple list = [(1,3);(2,2);(3,1);(10,1)] if the the root's value is 1 then it will check the third child (if not it will go on with the list), then if the child's value is 10, it will check his first child until it will find a leaf.

What i thought to do was to first use List.map to remove the elements that don't match with a tuple's key and the childs that are not in the associated value's value position, and then do the same to their childs recursively.

Here is what I did:

type 'a ntree = Tr of 'a * 'a ntree list;;
let leaf x = Tr(x,[]);;

let alb = Tr(1,[Tr(2,[leaf 3; leaf 4; leaf 2]);Tr(5,[leaf 11; leaf 10]);Tr(3,[leaf 9; leaf 7; leaf 10])]);;
let guida = [(1,3);(2,2);(3,1);(10,1);(16,2);(11,2)];;

let rec cerca_foglia guida (Tr(x,tlist)) =
  match tlist with
    [] -> x
  |_ -> List.map(fun a -> List.mem_assoc x guida && (*a.position = List.nth tlist List.assoc x guida*)) (cerca tlist)
and cerca = function
    [] -> raise NotFound
  |[t] -> cerca_foglia guida t
  |t::rest ->
      try cerca_foglia guida t
      with NotFound -> cerca rest

Of course, a.position does not exist, so how can I check it?

I also tried it differently:

let rec cerca_foglia guida (Tr(x,tlist)) =
  match tlist with
    [] -> x
  |_ -> List.map(fun a -> a = List.nth tlist List.assoc x guida) (cerca tlist)
and cerca = function
    [] -> raise NotFound
  |[t] -> if List.mem_assoc t guida then  cerca_foglia guida t else raise NotFound
  |t::rest ->
      try cerca_foglia guida t
      with NotFound -> cerca rest

But it still gives errors...How can I solve it?

Body:
After much pondering, I think I might have understood some of this. I have written two functions: find_child and find_child2.

type 'a ntree = Tr of 'a * 'a ntree list

let leaf x = Tr(x,[])

let alb = Tr(1,[Tr(2,[leaf 3; leaf 4; leaf 2]);Tr(5,[leaf 11; leaf 10]);Tr(3,[leaf 9; leaf 7; leaf 10])])

let guida = [(1,3);(2,2);(3,1);(10,1);(16,2);(11,2)]

let rec find_child (Tr (root, children) as tree) =
  function
  | [] -> None
  | (k, v)::_ when root = k -> Some (List.nth children (v - 1))
  | _::kvs -> find_child tree kvs

let rec find_child2 (Tr (root, children) as tree) key_val_list =
  match children with
  | [] -> Some tree
  | _ ->
    (match key_val_list with
     | [] -> None
     | (k, v)::kvs when root = k -> find_child2 (List.nth children (v - 1)) kvs
     | _::kvs -> find_child2 tree kvs)

The find_child function stops at the first match it finds. So evaluating find_child alb guida yields:

utop # find_child alb guida;;
- : int ntree option = Some (Tr (3, [Tr (9, []); Tr (7, []); Tr (10, [])]))

The find_child2 function does something similar, but it only stops if it finds a "leaf" or if it doesn't find any of the keys it's looking for in the current node.

utop # find_child2 alb guida;;
- : int ntree option = Some (Tr (9, []))

And refactoring find_child2 a bit to clean it up and handle the Failure "nth" exception that may occur:

let rec find_child3 (Tr (root, children) as tree) key_val_list =
  match children, key_val_list with
  | [], _ -> Some tree
  | _, [] -> None
  | _, (k, v)::kvs when root = k ->
    (match List.nth children (v - 1) with
     | child -> find_child3 child kvs
     | exception (Failure "nth") -> None)
  | _, _::kvs -> find_child3 tree kvs
  | exception Failure "nth" -> None

Sketching out what the recursion looks like when we evaluate find_child3 alb guida:

find_child3 alb guida

find_child3 (Tr(1,
               [Tr(2,[leaf 3; leaf 4; leaf 2]);
                Tr(5,[leaf 11; leaf 10]);
                Tr(3,[leaf 9; leaf 7; leaf 10])]))
            [(1,3);(2,2);(3,1);(10,1);(16,2);(11,2)]

find_child3 (Tr(3,[leaf 9; leaf 7; leaf 10]))
            [(2,2);(3,1);(10,1);(16,2);(11,2)]

find_child3 (Tr(3,[leaf 9; leaf 7; leaf 10]))
            [(3,1);(10,1);(16,2);(11,2)]

find_child3 (leaf 9) [(10,1);(16,2);(11,2)]

Some (Tr (9, []))

Is this the kind of thing you're looking for?


问:
How do you log information using a static method from a class using TypeScript?
This is for a school project. I'm having trouble getting the names from the class to log using a method. I have a class that maakes the monster and another one that extends it.

abstract class genMonster {
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}
```
<p>I have the monster objects</p>
```const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);
```
<p>and this is the method I tried but doesn't work</p>
```class organize extends genMonster{
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number){
    super(id, name, weaknesses, location, challenge, mortality, safety)
  }

  public static getNames(){
    return this.name
  }
}

console.log(organize.getNames());
//logs 'organize'
```

Any help is appreciated

答:
The getNames of organize is static and returns the constructor name itself ("organize"). Do you intend to get the name of the ghost instances themselves (Jerry, Patricia, Lola)? If so...

```<code>console.log(Jerry.name, Patricia.name, Lola.name);
</code>```

Body:
This is for a school project. I'm having trouble getting the names from the class to log using a method. I have a class that maakes the monster and another one that extends it.

abstract class genMonster {
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}

I have the monster objects

const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);

and this is the method I tried but doesn't work

class organize extends genMonster{
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number){
    super(id, name, weaknesses, location, challenge, mortality, safety)
  }

  public static getNames(){
    return this.name
  }
}

console.log(organize.getNames());
//logs 'organize'

Any help is appreciated

Body:
The getNames of organize is static and returns the constructor name itself ("organize"). Do you intend to get the name of the ghost instances themselves (Jerry, Patricia, Lola)? If so...

console.log(Jerry.name, Patricia.name, Lola.name);


问:
Can't load CSS in thymeleaf
I use this solutions for including one thymeleaf in another. It is solved my problems, but now css file don't load at all

Thymeleaf: Replace div with other pages on controllers

Here is my controller:

```<code>@GetMapping("/allUsers")
    public String userList(Model theModel) {
        List<User> theUsers = userService.findAll();
        theModel.addAttribute("users", theUsers);
        return "dashboard :: setFragment(content_fragment='/admin/allUsers')";
    }
</code>```

and part of the html where is link to css file

```<code>        <link rel="stylesheet" type="text/css" href="/css/style.css">

        <script>
            $(function () {
                var includes = $('[data-include]');
                $.each(includes, function () {
                    var file = '/admin' + $(this).data('include') + '.html';
                    $(this).load(file);
                });
            });
        </script>
        <title>Dashboard</title>
    </head>

    <body>
        <div th:insert="fragments/header :: header"></div>
        <div class="row">
            <div id="content" th:fragment="setFragment(content_fragment)">
                <div th:insert="fragments/dashboard :: aside" class="col-md-2 px-3"></div>
                <div th:insert="fragments/users :: users" class="col-md-10 py-3"></div>
            </div>
        </div>
    </body>
...
</code>```

答:
I am not familiar with this language however you may have to load your css as follows:

```<code><link th:href="@{"/css/style.css}" rel="stylesheet" />
</code>```

Using the example from: https://www.baeldung.com/spring-thymeleaf-css-js

Title: Can't load CSS in thymeleaf

Body:
I use this solutions for including one thymeleaf in another. It is solved my problems, but now css file don't load at all

Thymeleaf: Replace div with other pages on controllers

Here is my controller:

@GetMapping("/allUsers")
    public String userList(Model theModel) {
        List<User> theUsers = userService.findAll();
        theModel.addAttribute("users", theUsers);
        return "dashboard :: setFragment(content_fragment='/admin/allUsers')";
    }

and part of the html where is link to css file

        <link rel="stylesheet" type="text/css" href="/css/style.css">

        <title>Dashboard</title>

...

Body:
I am not familiar with this language however you may have to load your css as follows:

<link th:href="@{"/css/style.css}" rel="stylesheet" />

Using the example from: https://www.baeldung.com/spring-thymeleaf-css-js


问:
How can I get the last element of an array? SQL Bigquery
I'm working on building a follow-network form  Github's available data on Google BigQuery, e.g.: https://bigquery.cloud.google.com/table/githubarchive:day.20210606

The key data is contained in the "payload" field, STRING type. I managed to unnest the data contained in that field and convert it to an array, but how can I get the last element?

Here is what I have so far...

```<code>select type,
  array(select trim(val) from unnest(split(trim(payload, '[]'))) val) payload
from `githubarchive.day.20210606`
where type = 'MemberEvent'
</code>```

Which outputs:

How can I get only the last element, "Action":"added"} ?
I know that

select array_reverse(your_array)[offset(0)]

should do the trick, however I'm unsure how to combine that in my code. I've been trying different options without success, for example:

```<code>with  payload as ( select  array(select trim(val) from unnest(split(trim(payload, '[]'))) val) payload from `githubarchive.day.20210606`)

select type, ARRAY_REVERSE(payload)[ORDINAL(1)]

from `githubarchive.day.20210606` where type = 'MemberEvent'
</code>```

The desired output should look like:

答:
To get last element in array you can use below approach

```<code>select array_reverse(your_array)[offset(0)]
</code>```

I'm unsure how to combine that in my code

```<code>select  type, array_reverse(array(
    select trim(val)
      from unnest(split(trim(payload, '[]'))) val
  ))[offset(0)]
from `githubarchive.day.20210606`
where type = 'MemberEvent'
</code>```

Body:
I'm working on building a follow-network form  Github's available data on Google BigQuery, e.g.: https://bigquery.cloud.google.com/table/githubarchive:day.20210606

The key data is contained in the "payload" field, STRING type. I managed to unnest the data contained in that field and convert it to an array, but how can I get the last element?

Here is what I have so far...

select type,
  array(select trim(val) from unnest(split(trim(payload, '[]'))) val) payload
from `githubarchive.day.20210606`
where type = 'MemberEvent'

Which outputs:

How can I get only the last element, "Action":"added"} ?
I know that

select array_reverse(your_array)[offset(0)]

should do the trick, however I'm unsure how to combine that in my code. I've been trying different options without success, for example:

with  payload as ( select  array(select trim(val) from unnest(split(trim(payload, '[]'))) val) payload from `githubarchive.day.20210606`)

select type, ARRAY_REVERSE(payload)[ORDINAL(1)]

from `githubarchive.day.20210606` where type = 'MemberEvent'

The desired output should look like:

Body:
To get last element in array you can use below approach

select array_reverse(your_array)[offset(0)]

I'm unsure how to combine that in my code

select  type, array_reverse(array(
    select trim(val)
      from unnest(split(trim(payload, '[]'))) val
  ))[offset(0)]
from `githubarchive.day.20210606`
where type = 'MemberEvent'


问:
Javascript get Index of Key which contains value
I was wondering if there is a better way to get the Index of Key whose values contain the given value, otherwise it returns Null. In the example below it does what i need, but wasn't sure not sure if there was a simpler way of writing it. I know javascript's syntax is quite powerful and I'm not as familiar with it as others may be.

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

function getValueSetIndex(val) {
let count = 0
  for (const [key, values] of Object.entries(sets)) {
    if (values.includes(val)) {
        return count;
    }
    count += 1
  }
  return null
}

console.log(getValueSetIndex(4))
console.log(getValueSetIndex(20))```

答:
I can see where you're coming from. It's often useful to consider how you might eliminate for loops even if you end up using them.

How do you like this version?:

```<code>const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

const newGetValueSetIndex = val => {
  const result = Object.values(sets)
    .findIndex(
      values => values.includes(val)
    )
  return result === -1
    ? null
    : result
}

console.log(newGetValueSetIndex(4))
console.log(newGetValueSetIndex(20))
</code>```

Body:
I can see where you're coming from. It's often useful to consider how you might eliminate for loops even if you end up using them.

How do you like this version?:

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

const newGetValueSetIndex = val => {
  const result = Object.values(sets)
    .findIndex(
      values => values.includes(val)
    )
  return result === -1
    ? null
    : result
}

console.log(newGetValueSetIndex(4))
console.log(newGetValueSetIndex(20))


问:
Index operator precedence in bisonc++ (bison, bison++)
I'm designing my own toy language that compiles into Brainf*ck code and encountered problem with the operator precedence of the index operator. The parser is generated by Bisonc++, which uses mostly the same syntax for its grammar files as its cousins bison and bison++.

Because of the quirks in addressing memory in BF, I have to handle operations on array-elements differently, which is why I am generating specific rules for them (I left out the bodies of the rules on purpose). The relevant grammar (which is not working), is as follows:

```<code>%right '='
// a bunch of other operators
%left '+' '-'
// more operators
%left indexing

expression:
    variable
|
    array_element
|
    expression '+' expression
|
    // a bunch more rules
;

array_subscript:
    '[' expression ']'
;

array_element:
    expression array_subscript %prec indexing
;
</code>```

Now, I was under the impression that by assigning the indexing precedence to the array_element rule, the parser will match the smallest expression directly to the left of it. However, consider the following code:

```<code>10 + arr[0]
// is parsed as
(10 + arr)[0]
</code>```

I can't figure out why this is happening. When the code is changed to 10 + (arr[0]), the parser does the expected thing, which I think proves this has to do with operator precedence. One of the many things I tried was using an unused symbol as the indexing operator. For example:

```<code>// bottom-most operator in the precedence definition (replacing 'indexing'):
%left '@'

array_element:
    expression '@' array_subscript
;

// Code:
10 + arr@[0] // is now parsed properly
</code>```

This resolves the issue for some reason. Am I doing something fundamentally wrong? Am I misunderstanding the way operator precedence works in bison et al?

Thanks in advance!

EDIT

I've pushed my dev branch to github, which contains a folder with a minimal working example including a Makefile and test-file. To rebuild the parser with different grammar-specs (file: grammar), you can run make regenerate, but this requires bisonc++ and flexc++ (available from Debian repo's). To just build the project with the current (faulty) parser, run make.

https://github.com/jorenheit/brainfix/tree/better_indexing/arraybug

答:
The precedence declaration

```<code>array_element:
    expression array_subscript %prec indexing
</code>```

and the order of precedence of the pseudo-token indexing have absolutely no effect on the disambiguation of the indexing expression

```<code>10 + arr[0]
</code>```

The ambiguity being resolved by precedence in this case, as you say, is between

```<code>(10 + arr)[0]       and        10 + (arr[0])
</code>```

and it is resolved in the moment when the parser has seen 10 + arr and needs to decide whether or not it is (10 + arr). In other words, its options are:

Reduce using the production expression: expression '+' expression, or

Shift the lookahead token, which in this example is [.
If it chooses to shift, then expression: expression '+' expression will be reduced later, with a longer second operand, because all reductions are performed precisely at the end of the production being reduced, before the next token is shifted.

So the precedence ordering which is being considered is between the production expression '+' expression and the lookahead token [. Precedence comparisons are always of that form: the precedence of a possible reduction is compared with the precedence of the lookahead token which might be shifted.

Precedence is, somewhat confusingly, always described as a comparison between two tokens, probably because that is the actual algorithm used in operator precedence parsing, which is a different parsing algorithm. In shift-reduce parsing, the precedence comparison is always between a shift and a reduction. To maintain the illusion that it is between two tokens, Bison, like almost all Yacc derivatives, uses the convention that the precedence of a reduction is based on the precedence ordering of the last visible terminal in the right-hand side. (BisonC++ is an exception.)

Usually there is usually only one visible terminal in a production which requires precedence resolution, so the fact that Yacc/Bison selects the last one isn't noticeable, but there are occasional exceptions, such as the so-called "ternary operator" in C. The precedence of the production expression: expression '?' expression ':' expression is based on the : token; the relevant lookahead token would be ?, so the resolution of a?s1:b?s2:s3 is based on the comparison of ? with :; both of those tokens need to be in the same precedence level. To avoid this sort of confusion, and to allow precedence to be used with productions with no visible tokens, such as expression: expression array_subscript, Yacc derivatives typically allow you to override the default by specifying an alternative token for a production, using the %prec declaration.

This is particularly important if BisonC++ is part of your environment, because unlike almost every other Yacc derivative, BisonC++ uses the first non-terminal on the right-hand side. On the whole, it is probably a good idea to always use a %prec declaration in rules with more than one terminal symbol.

Regardless, it's important to remember that all %prec does is identify the precedence of a production with a terminal symbol. It has no effect on the precedence of any lookahead token, or any other production. If two rules have the same precedence, you can (and probably should) use the same %prec  declaration.

In short, the precedence of expression array_subscript is not relevant in the resolution of 10 + arr[0], because reducing that production is not an option at this point in the parse.  (Actually, it won't ever be relevant because array_subscript is effectively a postfix operator, and therefore not ambiguous. Precedence resolution only occurs when there is an ambiguity in the grammar.)

I don't know why BisonC++ is choosing to reduce the addition. Originally, I thought that it was because you put [ into some precedence level which comes before +, but apparently that is not the case. With Bison or Yacc, if [ were not in any precedence level, then it would have no declared precedence, and the precedence comparison would not be used to resolve ambiguity. If that were the case, (1) a shift-reduce conflict warning would be raised and (2) the parser would choose the shift action. And that's what happens with this grammar when tested with Bison. But BisonC++ apparently uses a default precedence, in some cases..

According to the "verbose" output generated by BisonC++, the conflicts were resolved using precedence. I haven't found any documentation for the precedence resolution algorithm used by Bisonc++, nor any note that it would be different from the algorithm used by Bison/Yacc (and, for what it's worth, required by Posix). But that doesn't mean that the documentation doesn't exist, and I'm reluctant to call this a bug without verifying what the original intent was. So I'll limit myself to saying that it is unusual.

In any case, you can force bisonc++ to resolve the conflict in the way you wish by adding a precedence level for [ (which, as noted above, is the lookahead token you're interested in). Put it after the precedence of + (and all other infix and prefix operators, which I presume exist in the full grammar):

```<code>%left '+'
%left '['
</code>```

(Tested, after a considerable fight with source dependencies, using BisonC++ 6.04.04.)

Body:
I'm designing my own toy language that compiles into Brainf*ck code and encountered problem with the operator precedence of the index operator. The parser is generated by Bisonc++, which uses mostly the same syntax for its grammar files as its cousins bison and bison++.

Because of the quirks in addressing memory in BF, I have to handle operations on array-elements differently, which is why I am generating specific rules for them (I left out the bodies of the rules on purpose). The relevant grammar (which is not working), is as follows:

%right '='
// a bunch of other operators
%left '+' '-'
// more operators
%left indexing

expression:
    variable
|
    array_element
|
    expression '+' expression
|
    // a bunch more rules
;

array_subscript:
    '[' expression ']'
;

array_element:
    expression array_subscript %prec indexing
;

Now, I was under the impression that by assigning the indexing precedence to the array_element rule, the parser will match the smallest expression directly to the left of it. However, consider the following code:

10 + arr[0]
// is parsed as
(10 + arr)[0]

I can't figure out why this is happening. When the code is changed to 10 + (arr[0]), the parser does the expected thing, which I think proves this has to do with operator precedence. One of the many things I tried was using an unused symbol as the indexing operator. For example:

// bottom-most operator in the precedence definition (replacing 'indexing'):
%left '@'

array_element:
    expression '@' array_subscript
;

// Code:
10 + arr@[0] // is now parsed properly

This resolves the issue for some reason. Am I doing something fundamentally wrong? Am I misunderstanding the way operator precedence works in bison et al?

Thanks in advance!

EDIT

I've pushed my dev branch to github, which contains a folder with a minimal working example including a Makefile and test-file. To rebuild the parser with different grammar-specs (file: grammar), you can run make regenerate, but this requires bisonc++ and flexc++ (available from Debian repo's). To just build the project with the current (faulty) parser, run make.

https://github.com/jorenheit/brainfix/tree/better_indexing/arraybug

Body:
The precedence declaration

array_element:
    expression array_subscript %prec indexing

and the order of precedence of the pseudo-token indexing have absolutely no effect on the disambiguation of the indexing expression

10 + arr[0]

The ambiguity being resolved by precedence in this case, as you say, is between

(10 + arr)[0]       and        10 + (arr[0])

and it is resolved in the moment when the parser has seen 10 + arr and needs to decide whether or not it is (10 + arr). In other words, its options are:

Reduce using the production expression: expression '+' expression, or

Shift the lookahead token, which in this example is [.
If it chooses to shift, then expression: expression '+' expression will be reduced later, with a longer second operand, because all reductions are performed precisely at the end of the production being reduced, before the next token is shifted.

So the precedence ordering which is being considered is between the production expression '+' expression and the lookahead token [. Precedence comparisons are always of that form: the precedence of a possible reduction is compared with the precedence of the lookahead token which might be shifted.

Precedence is, somewhat confusingly, always described as a comparison between two tokens, probably because that is the actual algorithm used in operator precedence parsing, which is a different parsing algorithm. In shift-reduce parsing, the precedence comparison is always between a shift and a reduction. To maintain the illusion that it is between two tokens, Bison, like almost all Yacc derivatives, uses the convention that the precedence of a reduction is based on the precedence ordering of the last visible terminal in the right-hand side. (BisonC++ is an exception.)

Usually there is usually only one visible terminal in a production which requires precedence resolution, so the fact that Yacc/Bison selects the last one isn't noticeable, but there are occasional exceptions, such as the so-called "ternary operator" in C. The precedence of the production expression: expression '?' expression ':' expression is based on the : token; the relevant lookahead token would be ?, so the resolution of a?s1:b?s2:s3 is based on the comparison of ? with :; both of those tokens need to be in the same precedence level. To avoid this sort of confusion, and to allow precedence to be used with productions with no visible tokens, such as expression: expression array_subscript, Yacc derivatives typically allow you to override the default by specifying an alternative token for a production, using the %prec declaration.

This is particularly important if BisonC++ is part of your environment, because unlike almost every other Yacc derivative, BisonC++ uses the first non-terminal on the right-hand side. On the whole, it is probably a good idea to always use a %prec declaration in rules with more than one terminal symbol.

Regardless, it's important to remember that all %prec does is identify the precedence of a production with a terminal symbol. It has no effect on the precedence of any lookahead token, or any other production. If two rules have the same precedence, you can (and probably should) use the same %prec  declaration.

In short, the precedence of expression array_subscript is not relevant in the resolution of 10 + arr[0], because reducing that production is not an option at this point in the parse.  (Actually, it won't ever be relevant because array_subscript is effectively a postfix operator, and therefore not ambiguous. Precedence resolution only occurs when there is an ambiguity in the grammar.)

I don't know why BisonC++ is choosing to reduce the addition. Originally, I thought that it was because you put [ into some precedence level which comes before +, but apparently that is not the case. With Bison or Yacc, if [ were not in any precedence level, then it would have no declared precedence, and the precedence comparison would not be used to resolve ambiguity. If that were the case, (1) a shift-reduce conflict warning would be raised and (2) the parser would choose the shift action. And that's what happens with this grammar when tested with Bison. But BisonC++ apparently uses a default precedence, in some cases..

According to the "verbose" output generated by BisonC++, the conflicts were resolved using precedence. I haven't found any documentation for the precedence resolution algorithm used by Bisonc++, nor any note that it would be different from the algorithm used by Bison/Yacc (and, for what it's worth, required by Posix). But that doesn't mean that the documentation doesn't exist, and I'm reluctant to call this a bug without verifying what the original intent was. So I'll limit myself to saying that it is unusual.

In any case, you can force bisonc++ to resolve the conflict in the way you wish by adding a precedence level for [ (which, as noted above, is the lookahead token you're interested in). Put it after the precedence of + (and all other infix and prefix operators, which I presume exist in the full grammar):

%left '+'
%left '['

(Tested, after a considerable fight with source dependencies, using BisonC++ 6.04.04.)