问:
How to specify both a Bitbucket repository key and a user key such that the repository key is read-only and the user key provides push capability?
Bitbucket provides for setting up a key on a repository for read-only access.  Without debating the merits of the following methodology, I want to use this feature in order to git pull to deploy changes to websites (as user root), but I also want to provide for a non-root user to very occasionally be able to push to the repo from the web server using their own key.  I've assigned root's default id_rsa.pub key as the Bitbucket repository key, and the pull (read-only) functionality is working when signed in as root.  However, I get an error when trying to push from a specific user.  The error is:

```<code>Load key "/home/user1/.ssh/bitbucket": Permission denied
git@bitbucket.org: Permission denied (publickey).
fatal: Could not read from remote repository.
</code>```

I am issuing the git push as user1, so I don't understand why it's giving a Permission denied error when trying to load the key.  Why can't user1 load and use his own key?  The private part of both keys mentioned below has permissions set to 600, and the public part has permissions set to 644.

The setup:

Ubuntu 20.04

Two users:  root and user1

root's id_rsa.pub key added to the Bitbucket repository's Access Keys

user1's key for accessing Bitbucket (named bitbucket.pub) added to the user's SSH Keys in BitBucket

A config file in /root/.ssh/ with the following:

```<code>Host bitbucket.org
    HostName bitbucket.org
    IdentityFile /root/.ssh/id_rsa
    IdentitiesOnly yes
</code>```

A config file in /home/user1/.ssh/ with the following:

```<code>Host bitbucket.org
    HostName bitbucket.org
    User git_user1
    IdentityFile /home/user1/.ssh/bitbucket
    IdentitiesOnly yes
</code>```

git remote -v shows:

origin  git@bitbucket.org:our_bitbucket_organization/website-name.git (fetch)

origin  git@bitbucket.org:our_bitbucket_organization/website-name.git (push)

user1 can push to the repo fine from their development server - the user is a user in the organization and so is a user on the repo.  I have also tried commenting out the User line in user1's config file but get the same error.

I've also studied this question (and especially this answer) but can't find anything in there that quite addresses this error.  I want to have two separate config files, not a single config file.

Any suggestions are greatly appreciated.

答:
Load key "/home/user1/.ssh/bitbucket": Permission denied

The error means the file is not readable by user1. To fix:

```<code>chown -R user1 /home/user1/.ssh
chmod -R u=rwX,go= /home/user1/.ssh
</code>```

PS. This is more generic than just a fix for one file. Just in case.

Body:
Bitbucket provides for setting up a key on a repository for read-only access.  Without debating the merits of the following methodology, I want to use this feature in order to git pull to deploy changes to websites (as user root), but I also want to provide for a non-root user to very occasionally be able to push to the repo from the web server using their own key.  I've assigned root's default id_rsa.pub key as the Bitbucket repository key, and the pull (read-only) functionality is working when signed in as root.  However, I get an error when trying to push from a specific user.  The error is:

Load key "/home/user1/.ssh/bitbucket": Permission denied
git@bitbucket.org: Permission denied (publickey).
fatal: Could not read from remote repository.

I am issuing the git push as user1, so I don't understand why it's giving a Permission denied error when trying to load the key.  Why can't user1 load and use his own key?  The private part of both keys mentioned below has permissions set to 600, and the public part has permissions set to 644.

The setup:

Ubuntu 20.04

Two users:  root and user1

root's id_rsa.pub key added to the Bitbucket repository's Access Keys

user1's key for accessing Bitbucket (named bitbucket.pub) added to the user's SSH Keys in BitBucket

A config file in /root/.ssh/ with the following:

Host bitbucket.org
    HostName bitbucket.org
    IdentityFile /root/.ssh/id_rsa
    IdentitiesOnly yes

A config file in /home/user1/.ssh/ with the following:

Host bitbucket.org
    HostName bitbucket.org
    User git_user1
    IdentityFile /home/user1/.ssh/bitbucket
    IdentitiesOnly yes

git remote -v shows:

origin  git@bitbucket.org:our_bitbucket_organization/website-name.git (fetch)

origin  git@bitbucket.org:our_bitbucket_organization/website-name.git (push)

user1 can push to the repo fine from their development server - the user is a user in the organization and so is a user on the repo.  I have also tried commenting out the User line in user1's config file but get the same error.

I've also studied this question (and especially this answer) but can't find anything in there that quite addresses this error.  I want to have two separate config files, not a single config file.

Any suggestions are greatly appreciated.

Body:
Load key "/home/user1/.ssh/bitbucket": Permission denied

The error means the file is not readable by user1. To fix:

chown -R user1 /home/user1/.ssh
chmod -R u=rwX,go= /home/user1/.ssh

PS. This is more generic than just a fix for one file. Just in case.


来源: stackexchange

问:
go generate on build stage
In some build systems like gradle or blaze I can generate code (ent or proto) on a build stage and don't add in to a repository.

Is it possible to do the same for the go build command?

答:
Yes, if you add "go generate" as your pre-build step in CI script.

```<code>$ go generate
$ go build
$ go test
</code>```

But I would recommend more practical approach: to store your generated code in your repo and check it on CI - run go generate and assert that there is no changes.

Links

https://go.dev/blog/generate

ContentLicense: CC BY-SA 4.0

Title: go generate on build stage

Body:
Yes, if you add "go generate" as your pre-build step in CI script.

$ go generate
$ go build
$ go test

But I would recommend more practical approach: to store your generated code in your repo and check it on CI - run go generate and assert that there is no changes.

Links

https://go.dev/blog/generate


问:
I have 2 announcement bars in my code that are on/off selectable, how can I enable both of them and transition from one to the other?
I have 2 announcement bars on my Shopify section that I created. I am able to select either one and they work perfectly. However, I would like to have them both enabled on the same bar transition from one to the other.

Here are both announcement bars. Do I need to add in some kind of transition code to make .show_announcement transition into .show_announcement2?

```<code>    {%- if section.settings.show_announcement -%}
  {%- if section.settings.home_page_only == false or template.name == 'index' -%}

    {%- if section.settings.link == blank -%}
      <div class="announcement-bar">
    {%- else -%}
      <a href="{{ section.settings.link }}" >
    {%- endif -%}

        <p class="announcement-bar__message">{{ section.settings.text | escape }}</p>

    {%- if section.settings.link == blank -%}
      </div>
    {%- else -%}
      </a>
    {%- endif -%}

  {%- endif -%}
{%- endif -%}

{%- if section.settings.show_announcement2 -%}
  {%- if section.settings.home_page_only == false or template.name == 'index' -%}

    {%- if section.settings.link2 == blank -%}
      <div class="announcement-bar">
    {%- else -%}
      <a href="{{ section.settings.link2 }}" >
    {%- endif -%}

        <p class="announcement-bar__message2">{{ section.settings.text2 | escape }}</p>

    {%- if section.settings.link2 == blank -%}
      </div>
    {%- else -%}
      </a>
    {%- endif -%}

  {%- endif -%}
{%- endif -%}

<style>
  .announcement-bar {
    background-color: {{ section.settings.announcement_bar_color }};
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin-bottom: 0;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
  }
  .announcement-bar__message {
    background-color: {{ section.settings.announcement_bar_color }};
    text-align: center;
    font-size: inherit;
    font-weight: 700;
    padding: 5px;
    margin: 0;
    color: {{ section.settings.announcement_bar_text_color }};
  }
  .announcement-bar2 {
    background-color: {{ section.settings.announcement_bar_color2 }};
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin-bottom: 0;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
  }
  .announcement-bar__message2 {
    background-color: {{ section.settings.announcement_bar_color2 }};
    text-align: center;
    font-size: inherit;
    font-weight: 700;
    padding: 5px;
    margin: 0;
    color: {{ section.settings.announcement_bar_text_color2 }};
  }

</style>

{% schema %}
{
  "name": "Announcement bar",
  "settings": [
    {
      "type": "checkbox",
      "id": "home_page_only",
      "label": "Home page only",
      "default": true
    },
    {
      "type": "checkbox",
      "id": "show_announcement",
      "label": "Show announcement",
      "default": false
    },
    {
      "type": "checkbox",
      "id": "show_announcement2",
      "label": "Show announcement 2",
      "default": false
    },
    {
      "type": "color",
      "id": "announcement_bar_color",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text",
      "label": "Announcement text 1",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link",
      "label": "Announcement link 1"
    },
    {
      "type": "color",
      "id": "announcement_bar_color2",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color2",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text2",
      "label": "Announcement text 2",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link2",
      "label": "Announcement link 2"
    }
  ]
}
{% endschema %}
</code>```

答:
something like this</p>
```<code>{%- if section.settings.show_announcement -%}
  {%- if section.settings.home_page_only == false or template.name == 'index' -%}

    <div class="my-slider">

    {%- if section.settings.link == blank -%}
      <div class="announcement-bar">
    {%- else -%}
      <div><a href="{{ section.settings.link }}" >
    {%- endif -%}

        <p class="announcement-bar__message">{{ section.settings.text | escape }}</p>

    {%- if section.settings.link == blank -%}
      </div>
    {%- else -%}
      </a></div>
    {%- endif -%}

    {%- if section.settings.link2 == blank -%}
      <div class="announcement-bar">
    {%- else -%}
      <div><a href="{{ section.settings.link2 }}" >
    {%- endif -%}

        <p class="announcement-bar__message2">{{ section.settings.text2 | escape }}</p>

    {%- if section.settings.link2 == blank -%}
      </div>
    {%- else -%}
      </a></div>
    {%- endif -%}

    </div>
  {%- endif -%}
{%- endif -%}

<style>
  .announcement-bar {
    background-color: {{ section.settings.announcement_bar_color }};
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin-bottom: 0;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
  }
  .announcement-bar__message {
    background-color: {{ section.settings.announcement_bar_color }};
    text-align: center;
    font-size: inherit;
    font-weight: 700;
    padding: 5px;
    margin: 0;
    color: {{ section.settings.announcement_bar_text_color }};
  }
  .announcement-bar2 {
    background-color: {{ section.settings.announcement_bar_color2 }};
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin-bottom: 0;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
  }
  .announcement-bar__message2 {
    background-color: {{ section.settings.announcement_bar_color2 }};
    text-align: center;
    font-size: inherit;
    font-weight: 700;
    padding: 5px;
    margin: 0;
    color: {{ section.settings.announcement_bar_text_color2 }};
  }

</style>

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css"/>
<script type="text-/javascript" src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>

<script>
  $('.my-slider').slick();

</script>

{% schema %}
{
  "name": "Announcement bar",
  "settings": [
    {
      "type": "checkbox",
      "id": "home_page_only",
      "label": "Home page only",
      "default": true
    },
    {
      "type": "checkbox",
      "id": "show_announcement",
      "label": "Show announcement",
      "default": false
    },
    {
      "type": "checkbox",
      "id": "show_announcement2",
      "label": "Show announcement 2",
      "default": false
    },
    {
      "type": "color",
      "id": "announcement_bar_color",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text",
      "label": "Announcement text 1",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link",
      "label": "Announcement link 1"
    },
    {
      "type": "color",
      "id": "announcement_bar_color2",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color2",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text2",
      "label": "Announcement text 2",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link2",
      "label": "Announcement link 2"
    }
  ]
}
{% endschema %}
</code>```

Body:
I have 2 announcement bars on my Shopify section that I created. I am able to select either one and they work perfectly. However, I would like to have them both enabled on the same bar transition from one to the other.

Here are both announcement bars. Do I need to add in some kind of transition code to make .show_announcement transition into .show_announcement2?

    {%- if section.settings.show_announcement -%}
  {%- if section.settings.home_page_only == false or template.name == 'index' -%}

    {%- if section.settings.link == blank -%}

    {%- else -%}

    {%- endif -%}

{{ section.settings.text | escape }}

    {%- if section.settings.link == blank -%}

    {%- else -%}

    {%- endif -%}

  {%- endif -%}
{%- endif -%}

{%- if section.settings.show_announcement2 -%}
  {%- if section.settings.home_page_only == false or template.name == 'index' -%}

    {%- if section.settings.link2 == blank -%}

    {%- else -%}

    {%- endif -%}

{{ section.settings.text2 | escape }}

    {%- if section.settings.link2 == blank -%}

    {%- else -%}

    {%- endif -%}

  {%- endif -%}
{%- endif -%}

{% schema %}
{
  "name": "Announcement bar",
  "settings": [
    {
      "type": "checkbox",
      "id": "home_page_only",
      "label": "Home page only",
      "default": true
    },
    {
      "type": "checkbox",
      "id": "show_announcement",
      "label": "Show announcement",
      "default": false
    },
    {
      "type": "checkbox",
      "id": "show_announcement2",
      "label": "Show announcement 2",
      "default": false
    },
    {
      "type": "color",
      "id": "announcement_bar_color",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text",
      "label": "Announcement text 1",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link",
      "label": "Announcement link 1"
    },
    {
      "type": "color",
      "id": "announcement_bar_color2",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color2",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text2",
      "label": "Announcement text 2",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link2",
      "label": "Announcement link 2"
    }
  ]
}
{% endschema %}

Body:
something like this

{%- if section.settings.show_announcement -%}
  {%- if section.settings.home_page_only == false or template.name == 'index' -%}

    <div class="my-slider">

    {%- if section.settings.link == blank -%}
      <div class="announcement-bar">
    {%- else -%}
      <div><a href="{{ section.settings.link }}" >
    {%- endif -%}

        <p class="announcement-bar__message">{{ section.settings.text | escape }}</p>

    {%- if section.settings.link == blank -%}
      </div>
    {%- else -%}
      </a></div>
    {%- endif -%}

    {%- if section.settings.link2 == blank -%}
      <div class="announcement-bar">
    {%- else -%}
      <div><a href="{{ section.settings.link2 }}" >
    {%- endif -%}

        <p class="announcement-bar__message2">{{ section.settings.text2 | escape }}</p>

    {%- if section.settings.link2 == blank -%}
      </div>
    {%- else -%}
      </a></div>
    {%- endif -%}

    </div>
  {%- endif -%}
{%- endif -%}

<style>
  .announcement-bar {
    background-color: {{ section.settings.announcement_bar_color }};
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin-bottom: 0;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
  }
  .announcement-bar__message {
    background-color: {{ section.settings.announcement_bar_color }};
    text-align: center;
    font-size: inherit;
    font-weight: 700;
    padding: 5px;
    margin: 0;
    color: {{ section.settings.announcement_bar_text_color }};
  }
  .announcement-bar2 {
    background-color: {{ section.settings.announcement_bar_color2 }};
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin-bottom: 0;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
  }
  .announcement-bar__message2 {
    background-color: {{ section.settings.announcement_bar_color2 }};
    text-align: center;
    font-size: inherit;
    font-weight: 700;
    padding: 5px;
    margin: 0;
    color: {{ section.settings.announcement_bar_text_color2 }};
  }

</style>

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css"/>
<script type="text-/javascript" src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>

<script>
  $('.my-slider').slick();

</script>

{% schema %}
{
  "name": "Announcement bar",
  "settings": [
    {
      "type": "checkbox",
      "id": "home_page_only",
      "label": "Home page only",
      "default": true
    },
    {
      "type": "checkbox",
      "id": "show_announcement",
      "label": "Show announcement",
      "default": false
    },
    {
      "type": "checkbox",
      "id": "show_announcement2",
      "label": "Show announcement 2",
      "default": false
    },
    {
      "type": "color",
      "id": "announcement_bar_color",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text",
      "label": "Announcement text 1",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link",
      "label": "Announcement link 1"
    },
    {
      "type": "color",
      "id": "announcement_bar_color2",
      "label": "Background color",
      "default": "#000000"
    },
    {
      "type": "color",
      "id": "announcement_bar_text_color2",
      "label": "Text color",
      "default": "#ffffff"
    },
    {
      "type": "text",
      "id": "text2",
      "label": "Announcement text 2",
      "default": "Announce something here"
    },
    {
      "type": "url",
      "id": "link2",
      "label": "Announcement link 2"
    }
  ]
}
{% endschema %}


问:
Maximum number in SQL
I'm having these schema
STUDENT (Sid, Name, City, Adm_date, Paper1, Paper2)

And I want to find the maximum number of students were admitted in which date and the city where maximum number of students lives.

I'm using these queries in ORACLE 11g Express Edition:
For City:

```<code>SELECT COUNT(Sid) AS No_of_students, City
FROM STUDENT
GROUP BY City
ORDER BY No_of_students DESC
LIMIT 1;
</code>```

And For Date:

```<code>SELECT COUNT(Sid) AS No_of_students, Adm_date
           FROM STUDENT
           GROUP BY Adm_date
           ORDER BY No_of_students DESC
            LIMIT 1;
</code>```

But here I'm getting error for both these tables:
ORA-00933: SQL command not properly ended

答:
LIMIT is not part of Oracle's SQL dialect. In Oracle you would use the standard SQL FETCH FIRST clause instead, but in the old version you are using this is not available either.

And whatever approach you are following, keep in mind that there can be ties, i.e. more than one city or date with the maximum number of students. So LIMIT 1 would jump to short.  FETCH FIRST does have a ties clause, but as mentioned, it is not available in your old Oracle version.

In Oracle 11g I'd use a window function to solve this:

```<code>SELECT city, no_of_students
FROM
(
  SELECT
    city,
    COUNT(sid) AS no_of_students,
    MAX(COUNT(sid)) OVER () AS max_no_of_students
  FROM STUDENT
  GROUP BY city
) counted
WHERE no_of_students = max_no_of_students;
</code>```

Title: Maximum number in SQL

Body:
I'm having these schema
STUDENT (Sid, Name, City, Adm_date, Paper1, Paper2)

And I want to find the maximum number of students were admitted in which date and the city where maximum number of students lives.

I'm using these queries in ORACLE 11g Express Edition:
For City:

SELECT COUNT(Sid) AS No_of_students, City
FROM STUDENT
GROUP BY City
ORDER BY No_of_students DESC
LIMIT 1;

And For Date:

SELECT COUNT(Sid) AS No_of_students, Adm_date
           FROM STUDENT
           GROUP BY Adm_date
           ORDER BY No_of_students DESC
            LIMIT 1;

But here I'm getting error for both these tables:
ORA-00933: SQL command not properly ended

Body:
LIMIT is not part of Oracle's SQL dialect. In Oracle you would use the standard SQL FETCH FIRST clause instead, but in the old version you are using this is not available either.

And whatever approach you are following, keep in mind that there can be ties, i.e. more than one city or date with the maximum number of students. So LIMIT 1 would jump to short.  FETCH FIRST does have a ties clause, but as mentioned, it is not available in your old Oracle version.

In Oracle 11g I'd use a window function to solve this:

SELECT city, no_of_students
FROM
(
  SELECT
    city,
    COUNT(sid) AS no_of_students,
    MAX(COUNT(sid)) OVER () AS max_no_of_students
  FROM STUDENT
  GROUP BY city
) counted
WHERE no_of_students = max_no_of_students;


问:
What is the name of data structure like list, but with round brackets in output?
I have three variables. I know names for the two first, but not for the last one.

Code:

```<code>somev1 = ['"Peter"','"20"'] # List
somev2 = ', '.join(somev1) # Just a string, that was joined from first list
somev3 = "Peter", "20" # I don't know

print(somev1) # Output : ['"Peter"', '"20"']
print(somev2) # Output : "Peter", "20"
print(somev3) # Output : ('Peter', '20')
</code>```

答:
somev3 = "Peter", "20" creates a tuple which is like a list accept it is not mutable.

It would be equivalent to:

```<code>somev3 = ("Peter", "20")
#or
somev3 = tuple(["Peter", "20"])
</code>```

Body:
I have three variables. I know names for the two first, but not for the last one.

Code:

somev1 = ['"Peter"','"20"'] # List
somev2 = ', '.join(somev1) # Just a string, that was joined from first list
somev3 = "Peter", "20" # I don't know

print(somev1) # Output : ['"Peter"', '"20"']
print(somev2) # Output : "Peter", "20"
print(somev3) # Output : ('Peter', '20')

Body:
somev3 = "Peter", "20" creates a tuple which is like a list accept it is not mutable.

It would be equivalent to:

somev3 = ("Peter", "20")
#or
somev3 = tuple(["Peter", "20"])


问:
Sorting a vector of objects in C++
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

```<code>class Information {

private:
int age;
string name;

//etc, etc...
};
</code>```

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

```<code>sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
</code>```

listOfPeople would be the vector.

Any help would be greatly appreciated.

答:
You need to have a comparison function or object in order to use that sort. Take a look at the sort page at cplusplus.com for examples and information.

Here's a complete example using a comparison function:

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

class Information {
public:
  Information(int age, std::string name) : m_age(age), m_name(name) {}
  int age() const { return m_age; }
  std::string name() const { return m_name; }
private:
  int m_age;
  std::string m_name;

  friend bool sortInformationByAgeAscending(const Information& lhs,
                                            const Information& rhs);
  friend bool sortInformationByAgeDescending(const Information& lhs,
                                             const Information& rhs);
};

bool sortInformationByAgeAscending(const Information& lhs,
                                   const Information& rhs) {
  return lhs.m_age < rhs.m_age;
}

bool sortInformationByAgeDescending(const Information& lhs,
                                    const Information& rhs) {
  return lhs.m_age > rhs.m_age;
}
int main (int argc, const char * argv[])
{
  std::vector<Information> info;
  info.push_back(Information(1, "Bill"));
  info.push_back(Information(5, "Ann"));
  info.push_back(Information(2, "Sue"));

  std::sort(info.begin(), info.end(), sortInformationByAgeAscending);

  std::cout << info.at(0).age() << ": " << info.at(0).name() << std::endl;
  std::cout << info.at(1).age() << ": " << info.at(1).name() << std::endl;
  std::cout << info.at(2).age() << ": " << info.at(2).name() << std::endl;

  return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sorting a vector of objects in C++

Body:
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

class Information {

private:
int age;
string name;

//etc, etc...
};

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

listOfPeople would be the vector.

Any help would be greatly appreciated.

Body:
You need to have a comparison function or object in order to use that sort. Take a look at the sort page at cplusplus.com for examples and information.

Here's a complete example using a comparison function:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class Information {
public:
  Information(int age, std::string name) : m_age(age), m_name(name) {}
  int age() const { return m_age; }
  std::string name() const { return m_name; }
private:
  int m_age;
  std::string m_name;

  friend bool sortInformationByAgeAscending(const Information& lhs,
                                            const Information& rhs);
  friend bool sortInformationByAgeDescending(const Information& lhs,
                                             const Information& rhs);
};

bool sortInformationByAgeAscending(const Information& lhs,
                                   const Information& rhs) {
  return lhs.m_age < rhs.m_age;
}

bool sortInformationByAgeDescending(const Information& lhs,
                                    const Information& rhs) {
  return lhs.m_age > rhs.m_age;
}
int main (int argc, const char * argv[])
{
  std::vector<Information> info;
  info.push_back(Information(1, "Bill"));
  info.push_back(Information(5, "Ann"));
  info.push_back(Information(2, "Sue"));

  std::sort(info.begin(), info.end(), sortInformationByAgeAscending);

  std::cout << info.at(0).age() << ": " << info.at(0).name() << std::endl;
  std::cout << info.at(1).age() << ": " << info.at(1).name() << std::endl;
  std::cout << info.at(2).age() << ": " << info.at(2).name() << std::endl;

  return 0;
}


问:
How to save a file in vscode-remote SSH with a non-root user privileges
I am not able to save any files on my remote server with VSCode Remote SSH because I am not a root user.

I've followed the official documentation about how to set up ssh with SSH config file but even if my user as sudo privileges, I can't find any options in VSCode to save with sudo.

here is my SSH config file /Users/geoff/.ssh/config:

```<code>Host gcpmain
    User geoff
    HostName <IP_ADDRESS>
    IdentityFile ~/.ssh/gc_rsa
</code>```

Obviously, when I try to save any files that require sudo I have this expected error message:

```<code>Failed to save 'default': Unable to write file (NoPermissions
 (FileSystemError): Error: EACCES: permission denied, open
'/etc/nginx/sites-available/default')
</code>```

Is there any way that I can force VSCode to save as sudo?
Thanks a lot for your answers! :)

答:
One solution for Linux I just came across is to use bindfs (sudo apt install bindfs).

To enable editing /etc/nginx as root for the current user, working in ~/.bind-mounts/nginx:

mkdir -p ~/.bind-mounts/nginx
sudo bindfs --map=root/${USER}:@root/@$(id -gn) /etc/nginx ~/.bind-mounts/nginx
sudo umount ~/.bind-mounts/nginx # When you're done, or run bindfs with '-f' to keep it in the foreground
```

bindfs has many options. --map may not be the best. It's been working in my testing so far.

Everything seems to work as you'd expect. Lets you "explore" as root and any modifications will be made as if you had root's permissions. Just don't forget the security implications!

Body:
I am not able to save any files on my remote server with VSCode Remote SSH because I am not a root user.

I've followed the official documentation about how to set up ssh with SSH config file but even if my user as sudo privileges, I can't find any options in VSCode to save with sudo.

here is my SSH config file /Users/geoff/.ssh/config:

Host gcpmain
    User geoff
    HostName <IP_ADDRESS>
    IdentityFile ~/.ssh/gc_rsa

Obviously, when I try to save any files that require sudo I have this expected error message:

Failed to save 'default': Unable to write file (NoPermissions
 (FileSystemError): Error: EACCES: permission denied, open
'/etc/nginx/sites-available/default')

Is there any way that I can force VSCode to save as sudo?
Thanks a lot for your answers! :)

Body:
One solution for Linux I just came across is to use bindfs (sudo apt install bindfs).

To enable editing /etc/nginx as root for the current user, working in ~/.bind-mounts/nginx:

mkdir -p ~/.bind-mounts/nginx
sudo bindfs --map=root/${USER}:@root/@$(id -gn) /etc/nginx ~/.bind-mounts/nginx
sudo umount ~/.bind-mounts/nginx # When you're done, or run bindfs with '-f' to keep it in the foreground

bindfs has many options. --map may not be the best. It's been working in my testing so far.

Everything seems to work as you'd expect. Lets you "explore" as root and any modifications will be made as if you had root's permissions. Just don't forget the security implications!


问:
"Update Cart" not triggering my woocommerce_after_cart_totals action hook
I have a woocommerce_after_cart_totals hook action being done to output a specific JSON object to the cart page. It works as expected on page load, however when someone changes qty and hits Update Cart button,  the JSON variable disappears and a new one is not recreated.

```<code>add_action('woocommerce_after_cart_totals','custom_json_var_output',10,2);
function custom_json_var_output(){
    //build the variable to $output
    //............
    echo "<script>jsonCartData=".json_encode($output).";</script>";
}
</code>```

So on cart page load i see jsonCartData=*********** script tag below cart_totals div,  but when Update Cart is clicked, my tag disappears entirely.

I need to know why this is the case, and what additional action I need to trigger to get the new output after the cart_totals div when Update Cart is done. Why would an update cart action not include retriggering the woocommerce_after_cart_totals hook?

答:
This is because each time something changes, an Ajax request is made and the corresponding sections on the page are updated.

If you want to hook into the Ajax calls, you should use the woocommerce_add_to_cart_fragments filter.

function filter_woocommerce_add_to_cart_fragments(array $array): array
{
    // Your logic …

    $array['#my-script-css-selector'] = <<<HTML

    HTML;
    return $array;
};

add_filter('woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1);
```

Note, that there is a Stack Exchange extra for WordPress: https://wordpress.stackexchange.com/

Body:
I have a woocommerce_after_cart_totals hook action being done to output a specific JSON object to the cart page. It works as expected on page load, however when someone changes qty and hits Update Cart button,  the JSON variable disappears and a new one is not recreated.

add_action('woocommerce_after_cart_totals','custom_json_var_output',10,2);
function custom_json_var_output(){
    //build the variable to $output
    //............
    echo "";
}

So on cart page load i see jsonCartData=*********** script tag below cart_totals div,  but when Update Cart is clicked, my tag disappears entirely.

I need to know why this is the case, and what additional action I need to trigger to get the new output after the cart_totals div when Update Cart is done. Why would an update cart action not include retriggering the woocommerce_after_cart_totals hook?

Body:
This is because each time something changes, an Ajax request is made and the corresponding sections on the page are updated.

If you want to hook into the Ajax calls, you should use the woocommerce_add_to_cart_fragments filter.

function filter_woocommerce_add_to_cart_fragments(array $array): array
{
    // Your logic …

    $array['#my-script-css-selector'] = <<<HTML
    <script id=my-script-css-selector>
        console.log('hello')
    </script>
    HTML;
    return $array;
};

add_filter('woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1);

Note, that there is a Stack Exchange extra for WordPress: https://wordpress.stackexchange.com/


问:
Android: How to access a file in the SD Card
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???</p>

```<code>new File("/mnt/sdcard/splah2.jpg")
</code>```

答:
The code below has worked for me.

```<code>String mRelativeFolderPath = "/DCIM/Camera/";  // i.e. SDCard/DCIM/Camera
String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + mRelativeFolderPath;
String filePath = mBaseFolderPath  + "test.jpg";
File handle = new File(filePath);
</code>```

Shash

Body:
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???

new File("/mnt/sdcard/splah2.jpg")

Body:
The code below has worked for me.

String mRelativeFolderPath = "/DCIM/Camera/";  // i.e. SDCard/DCIM/Camera
String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + mRelativeFolderPath;
String filePath = mBaseFolderPath  + "test.jpg";
File handle = new File(filePath);

Shash


问:
Python web requests: Accessing json data from web response
I have a question with probably a well-known answer. However I couldnt articulate it well enough to find answers on google.

Lets say you are using the developer interface of Chrome browser (Press F12). If you click on the network tab and go to any website, a lot of files will be queried there for example images, stylesheets and JSON-responses.

I want to parse these JSON-responses using python now.

Thanks in advance!

答:
I use requests to get the data, and it comes back as a Python dictionary:

import requests

r = requests.get("url/spotted/with/devtools")
r.json()["keys_observed_in_devtools"]
```


问:
How to stop a parent's onAnimationEnd from running when a Child run an animation
I have this simple code where I have A Parent div and a Child Div, both have their own Animations and a button that start the animation and both have an onAnimationEnd Event that display on the console a message.

Whenever I click on the parent button the animation start and when it's over I have the right message on the console.

```<code>  Parent Ended Animation
</code>```

till now  No Problems.

when I click on the Child button the animation start and when it's over I get the Child's message and the parent's message.

```<code>Child Ended Animation App.

Parent Ended Animation App
</code>```

.

and that is my problem.

So How Can I stop the parent event from running when the child animation is over?

```<code>const ParentAnimation = keyframes`
  from {
    background-color: red;
  }to {
    background-color: blue;
  }
`
const Parent = styled.div`
  background-color: red;
  height: 300px;
  width: 300px;
  animation: ${(props) =>
    props.animate &&
    css`
      ${ParentAnimation} .5s
    `};
`

const ChildAnimation = keyframes`
  from {
    background-color: green;
  }to {
    background-color: yellow;
  }
`
const Child = styled.div`
  background-color: green;
  height: 100px;
  width: 100px;
  position: relative;
  top: 100%;
  animation: ${(props) =>
    props.animate &&
    css`
      ${ChildAnimation} .5s
    `};
`
function App() {
  const [animeteParent, setAnimeteParent] = useState(false)
  const [animeteChild, setAnimeteChild] = useState(false)
  return (
    <Parent
      animate={animeteParent}
      onAnimationEnd={() => console.log('Parent Ended Animation')}
    >

      <Child
        animate={animeteChild}
        onAnimationEnd={() => console.log('Child Ended Animation')}
      >
      </Child>

      <button
        onClick={() => {
          setAnimeteParent(true)
        }}
      >
        Animate Parent
      </button>

      <button
        onClick={() => {
          setAnimeteChild(true)
        }}
      >
        Animate Child
      </button>

    </Parent>
  )
}
</code>```

答:
call event.stopPropagation(); in your function to stop the event from bubbling up.

Event bubbling

What you're seeing is called 'Event bubbling'. It's not unique to react, and actually a pattern used in most html  onXYZ() handlers.
In this case, it doesn't really make sense to let 'animation end' bubble all the way to the top.

I guess confirming to a standard way to handle events outweighed making exceptions per event type.

For click events, it can make sense to bubble things up, imagine 5 nested divs, one could make the case that clicking a child is the same as clicking the parent. so we should fire the 'onclick' of the parent as well.

this is called bubbling; as long a now one stops the it, the event will bubble up through all the parents. so that parents can handle the event.
(it bubbles through event handlers that share their name, onclick to onclick, onAnimationEnd to onAnimationEnd, etc)

Stopping the bubble

It's easy to stop an event from bubbling. by calling event.stopPropagation();
It's up to developers to determine when they want to allow something to bubble up the the parents or not;

adding the stopPropagation on the child should stop the parent from triggering their event when the child finishes.

```<code> onAnimationEnd={(event) => {
          console.log("Child Ended Animation");
          event.stopPropagation();
        }}
</code>```

Example

there's a code pen example showing this

Body:
I have this simple code where I have A Parent div and a Child Div, both have their own Animations and a button that start the animation and both have an onAnimationEnd Event that display on the console a message.

Whenever I click on the parent button the animation start and when it's over I have the right message on the console.

  Parent Ended Animation

till now  No Problems.

when I click on the Child button the animation start and when it's over I get the Child's message and the parent's message.

Child Ended Animation App.

Parent Ended Animation App

.

and that is my problem.

So How Can I stop the parent event from running when the child animation is over?

const ParentAnimation = keyframes`
  from {
    background-color: red;
  }to {
    background-color: blue;
  }
`
const Parent = styled.div`
  background-color: red;
  height: 300px;
  width: 300px;
  animation: ${(props) =>
    props.animate &&
    css`
      ${ParentAnimation} .5s
    `};
`

const ChildAnimation = keyframes`
  from {
    background-color: green;
  }to {
    background-color: yellow;
  }
`
const Child = styled.div`
  background-color: green;
  height: 100px;
  width: 100px;
  position: relative;
  top: 100%;
  animation: ${(props) =>
    props.animate &&
    css`
      ${ChildAnimation} .5s
    `};
`
function App() {
  const [animeteParent, setAnimeteParent] = useState(false)
  const [animeteChild, setAnimeteChild] = useState(false)
  return (
    <Parent
      animate={animeteParent}
      onAnimationEnd={() => console.log('Parent Ended Animation')}
    >

      <Child
        animate={animeteChild}
        onAnimationEnd={() => console.log('Child Ended Animation')}
      >
      </Child>

      <button
        onClick={() => {
          setAnimeteParent(true)
        }}
      >
        Animate Parent
      </button>

      <button
        onClick={() => {
          setAnimeteChild(true)
        }}
      >
        Animate Child
      </button>

    </Parent>
  )
}

Body:
call event.stopPropagation(); in your function to stop the event from bubbling up.

Event bubbling

What you're seeing is called 'Event bubbling'. It's not unique to react, and actually a pattern used in most html  onXYZ() handlers.
In this case, it doesn't really make sense to let 'animation end' bubble all the way to the top.

I guess confirming to a standard way to handle events outweighed making exceptions per event type.

For click events, it can make sense to bubble things up, imagine 5 nested divs, one could make the case that clicking a child is the same as clicking the parent. so we should fire the 'onclick' of the parent as well.

this is called bubbling; as long a now one stops the it, the event will bubble up through all the parents. so that parents can handle the event.
(it bubbles through event handlers that share their name, onclick to onclick, onAnimationEnd to onAnimationEnd, etc)

Stopping the bubble

It's easy to stop an event from bubbling. by calling event.stopPropagation();
It's up to developers to determine when they want to allow something to bubble up the the parents or not;

adding the stopPropagation on the child should stop the parent from triggering their event when the child finishes.

 onAnimationEnd={(event) => {
          console.log("Child Ended Animation");
          event.stopPropagation();
        }}

Example

there's a code pen example showing this


问:
Svelte radio button binding is not reflected correctly
I have a svelte component with the following code:

```<code><script>
  let languages = [];
  let defaultLanguage = null;

  $: console.log(languages, defaultLanguage);
</script>

<p>Languages:</p>
<div>
  <input type="checkbox" bind:group={languages} value="English"> English
</div>
<div>
  <input type="checkbox" bind:group={languages} value="Swedish"> Swedish
</div>

<p>Default:</p>
{#each languages as lang}
  <div>
    <input type="radio" bind:group={defaultLanguage} value={lang}> {lang}
  </div>
{/each}
</code>```

The problem occurs when I do the following:

Check both checkboxes

Select the second radio button (Swedish)

Uncheck the first checkbox (English)

This removes the English radio button but it also unselects the Swedish radio button. However, the defaultLanguage variable is still set to "Swedish" which is correct. If I check the first checkbox again then the Swedish radio button is selected again.

This does not happen if I instead select the English radio button in step (2) and uncheck the Swedish checkbox in step (3).

答:
This happens because the each block of the radio buttons is not a 'keyed each block` >> the tutorial lesson

If you know the language names are unique, you can simply use the language as key >> REPL

```<code>{#each languages as lang (lang)}
  <div>
    <input type="radio" bind:group={defaultLanguage} value={lang}> {lang}
  </div>
{/each}
</code>```

Body:
I have a svelte component with the following code:

Languages:

  <input type="checkbox" bind:group={languages} value="English"> English

  <input type="checkbox" bind:group={languages} value="Swedish"> Swedish

Default:

{#each languages as lang}

    <input type="radio" bind:group={defaultLanguage} value={lang}> {lang}

{/each}

The problem occurs when I do the following:

Check both checkboxes

Select the second radio button (Swedish)

Uncheck the first checkbox (English)

This removes the English radio button but it also unselects the Swedish radio button. However, the defaultLanguage variable is still set to "Swedish" which is correct. If I check the first checkbox again then the Swedish radio button is selected again.

This does not happen if I instead select the English radio button in step (2) and uncheck the Swedish checkbox in step (3).

Body:
This happens because the each block of the radio buttons is not a 'keyed each block` >> the tutorial lesson

If you know the language names are unique, you can simply use the language as key >> REPL

{#each languages as lang (lang)}
  <div>
    <input type="radio" bind:group={defaultLanguage} value={lang}> {lang}
  </div>
{/each}


问:
How to efficiently generate, in C, x random numbers in a given interval such the sum is constant?
To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program

1 :  nbValue-1 are randomly generated

2 : the last value is calculated (fullSum - Sum of nbValue)

3 : If the last value is not in the interval, this loop is restarted.

This is the code :

```<code>int main()
{

    int fullSum = 4096, nbValue = 16;
    int average = round(fullSum / nbValue);
    int delta = round(average*0.125);
    int tryCounter = 0;
    int lastStep;

    srand(time(0));

    do {
      int currentSum = 0;
      for (int i=0;i<nbValue-1;i++)
        currentSum+=rand()%(delta*2+1)-delta+average ;
      tryCounter ++;
      lastStep = fullSum - currentSum;
    }
    while ( (lastStep < average - delta) || (lastStep > average + delta) );

    printf("Total tries : %d\n",tryCounter);
}
</code>```

Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)

Thanks for answer.

答:
I came up with a tail-recursive solution that "almost" works :-)</p>
```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rand_between(int lo, int hi) {
    // simple implementation may suffer from bias
    return rand() % (hi - lo + 1) + lo;
}

void rand_with_const_sum(int *a, int n, int sum, int min, int max) {
    if (n-- == 0) return;
    int tmpmax = sum - n*min;
    int tmpmin = sum - n*max;
    if (tmpmax > max) tmpmax = max;
    if (tmpmin < min) tmpmin = min;
    a[0] = rand_between(tmpmin, tmpmax);
    rand_with_const_sum(a + 1, n, sum - a[0], min, max);
}

int main(void) {
    srand((unsigned)time(0));
    int a[100];

    rand_with_const_sum(a, 10, 100, 7, 13);
    for (int i = 0; i < 10; i++) printf("%d ", a[i]);
    puts("");

    puts("");

    rand_with_const_sum(a, 100, 1000, 7, 13);
    // shuffle(a, 100); // ?
    for (int i = 0; i < 100; i++) printf("%d ", a[i]);
    puts("");

    return 0;
}
</code>```

Body:
To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program

1 :  nbValue-1 are randomly generated

2 : the last value is calculated (fullSum - Sum of nbValue)

3 : If the last value is not in the interval, this loop is restarted.

This is the code :

int main()
{

    int fullSum = 4096, nbValue = 16;
    int average = round(fullSum / nbValue);
    int delta = round(average*0.125);
    int tryCounter = 0;
    int lastStep;

    srand(time(0));

    do {
      int currentSum = 0;
      for (int i=0;i<nbValue-1;i++)
        currentSum+=rand()%(delta*2+1)-delta+average ;
      tryCounter ++;
      lastStep = fullSum - currentSum;
    }
    while ( (lastStep < average - delta) || (lastStep > average + delta) );

    printf("Total tries : %d\n",tryCounter);
}

Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)

Thanks for answer.

Body:
I came up with a tail-recursive solution that "almost" works :-)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rand_between(int lo, int hi) {
    // simple implementation may suffer from bias
    return rand() % (hi - lo + 1) + lo;
}

void rand_with_const_sum(int *a, int n, int sum, int min, int max) {
    if (n-- == 0) return;
    int tmpmax = sum - n*min;
    int tmpmin = sum - n*max;
    if (tmpmax > max) tmpmax = max;
    if (tmpmin < min) tmpmin = min;
    a[0] = rand_between(tmpmin, tmpmax);
    rand_with_const_sum(a + 1, n, sum - a[0], min, max);
}

int main(void) {
    srand((unsigned)time(0));
    int a[100];

    rand_with_const_sum(a, 10, 100, 7, 13);
    for (int i = 0; i < 10; i++) printf("%d ", a[i]);
    puts("");

    puts("");

    rand_with_const_sum(a, 100, 1000, 7, 13);
    // shuffle(a, 100); // ?
    for (int i = 0; i < 100; i++) printf("%d ", a[i]);
    puts("");

    return 0;
}


问:
Generating key pair directly on Smartcard?
This video claims to be able to generate a key pair directly on the Smartcard so the private key never leaves the card. Is this operation common to all smartcards, or do only select smartcards support this?</p>

答:
Most cryptographic smart cards are able to generate keys in the card in addition to storing externally generated plaintext keys, that's the main purpose of cryptographic smart cards.

Some cards don't allow importing plaintext keys, some allow exporting keys generated on the card, some card can do import/export of wrapped (encrypted with another key) private keys, so that the actual private key would never be in clear in an untrusted environment.

Have a look at http://www.opensc-project.org for a further pointers on cards and software.


问:
How do I check if a specific element on a website is changed?
I am currently trying to get a spot in a zoom class, and if I don't get a spot I owe a driving school 300 dollars. Long story there, but not very important. I am trying to get a notification if the zoom registration link data has been updated. I originally tried to just see if the hash of the site was updated at any point, but I noticed there must be some internal clock that is changed, making it notify me every minute. The specific element I am looking to see if it is removed is...

```<code><div class="form-group registration-over">Registration is closed.</div>
</code>```

I am not sure how to isolate it within the hash. Below is the code I have for checking for any update.

```<code>import time
import hashlib
from urllib.request import urlopen, Request
import webbrowser

url = Request('URL HERE',
              headers={'User-Agent': 'Mozilla/5.0'})

response = urlopen(url).read()

currentHash = hashlib.sha224(response).hexdigest()
print("running")
time.sleep(10)
while True:
    try:
        response = urlopen(url).read()

        currentHash = hashlib.sha224(response).hexdigest()

        time.sleep(30)

        response = urlopen(url).read()

        newHash = hashlib.sha224(response).hexdigest()

        if newHash == currentHash:
            continue

        else:
            from datetime import datetime
            now = datetime.now()
            nowtime = now.strftime("%H:%M:%S: ")
            print(nowtime, "Something changed")
            webbrowser.open('URL HERE')

            response = urlopen(url).read()

            currentHash = hashlib.sha224(response).hexdigest()

            time.sleep(30)
            continue

    except Exception as e:
        print("error")
</code>```

答: You can use Beautiful Soup to parse the HTML response which creates a tree-like structure. From your example it looks like you want to search for the class of the registration div. The find method returns None if no element is found, so you could just test for that instead of the hash change.</p>

Body:
I am currently trying to get a spot in a zoom class, and if I don't get a spot I owe a driving school 300 dollars. Long story there, but not very important. I am trying to get a notification if the zoom registration link data has been updated. I originally tried to just see if the hash of the site was updated at any point, but I noticed there must be some internal clock that is changed, making it notify me every minute. The specific element I am looking to see if it is removed is...

Registration is closed.

I am not sure how to isolate it within the hash. Below is the code I have for checking for any update.

import time
import hashlib
from urllib.request import urlopen, Request
import webbrowser

url = Request('URL HERE',
              headers={'User-Agent': 'Mozilla/5.0'})

response = urlopen(url).read()

currentHash = hashlib.sha224(response).hexdigest()
print("running")
time.sleep(10)
while True:
    try:
        response = urlopen(url).read()

        currentHash = hashlib.sha224(response).hexdigest()

        time.sleep(30)

        response = urlopen(url).read()

        newHash = hashlib.sha224(response).hexdigest()

        if newHash == currentHash:
            continue

        else:
            from datetime import datetime
            now = datetime.now()
            nowtime = now.strftime("%H:%M:%S: ")
            print(nowtime, "Something changed")
            webbrowser.open('URL HERE')

            response = urlopen(url).read()

            currentHash = hashlib.sha224(response).hexdigest()

            time.sleep(30)
            continue

    except Exception as e:
        print("error")


问:
How to make REST calls to Azure Pipelines from c#
From c# code, I want to call Azure Devops Pipeline Url and get the job/build ids for that url. And then get the result if the job/build succeds/fail.
How to make REST call from c# code my Azure pipelines (I have the pipeline url)?</p>

答: You can use this sample through HttpClient. Additionally, you can use Microsoft.TeamFoundationServer.Client and BuildHttpClient.GetBuildsAsync: the example is here.


问:
Simple font size changer with Material UI slider and React
I'm trying to make a simple slider that change the font size using React and Material UI.
The slider is called PrettoSlider and it a part of Material UI.

What im trying to acheive is to use the slider an then change the font size depending on the slider.
This is what i have so far

```<code>export default function ChangeFontSlider() {

  const [ItemValue, setItemValue] = React.useState(20);

const handlingChange = (event) => {
   setItemValue(event.target.value);
   event.preventDefault();
}
return (
    <>
      <p style={{fontSize: {ItemValue}}}>Drag me to change the font</p>
      <PrettoSlider
      onChange={handlingChange}
      value={ItemValue}
      />
    </>
  );
}
</code>```

When trying to slide the slider, I ether get an error or the font remain the same.
Any idea? Thanks!

答:
in mui for change the font of slider label you can use global class in slider api.

```<code>import { makeStyles } from "@mui/styles";

const sliderStyles= makeStyles({
  slider: {
    '& .MuiSlider-markLabel' : {fontFamily: 'Vazir' , fontSize: "12px"}
  }
})
</code>```

and set this class to className prop in slider.

```<code>import { sliderStyles} from "YOUR/STYLES/PATH";
<Slider
     valueLabelFormat={valueLabelFormat}
     getAriaValueText={valuetext}
     step={null}
     valueLabelDisplay="on"
     marks={sliderMarks}
     className={classes.slider} //this line important
 />
</code>```

Body:
I'm trying to make a simple slider that change the font size using React and Material UI.
The slider is called PrettoSlider and it a part of Material UI.

What im trying to acheive is to use the slider an then change the font size depending on the slider.
This is what i have so far

export default function ChangeFontSlider() {

  const [ItemValue, setItemValue] = React.useState(20);

const handlingChange = (event) => {
   setItemValue(event.target.value);
   event.preventDefault();
}
return (
    <>

Drag me to change the font

      <PrettoSlider
      onChange={handlingChange}
      value={ItemValue}
      />
    </>
  );
}

When trying to slide the slider, I ether get an error or the font remain the same.
Any idea? Thanks!

Body:
in mui for change the font of slider label you can use global class in slider api.

import { makeStyles } from "@mui/styles";

const sliderStyles= makeStyles({
  slider: {
    '& .MuiSlider-markLabel' : {fontFamily: 'Vazir' , fontSize: "12px"}
  }
})

and set this class to className prop in slider.

import { sliderStyles} from "YOUR/STYLES/PATH";
<Slider
     valueLabelFormat={valueLabelFormat}
     getAriaValueText={valuetext}
     step={null}
     valueLabelDisplay="on"
     marks={sliderMarks}
     className={classes.slider} //this line important
 />


问:
Get preferred screen brightness in Android
How do you get the preferred screen brightness in Android?

To change the screen brightness I use WindowManager.LayoutParams.screenBrightness. According to the documentation:

This can be used to override the
  user's preferred brightness of the
  screen. A value of less than 0, the
  default, means to use the preferred
  screen brightness. 0 to 1 adjusts the
  brightness from dark to full bright.

When screenBrightness is less than 0 I would like to start with the preferred screen brightness. How can I get this value?

答:
As of now (android 12) the situation is more complicated than described by
@davidcesarino in his comprehensive answer. I did look at the source code as suggested, and it is pretty complicated. Among other things, auto brightness mode has both a fast and a slow brightness change in response to changes in ambient light level.

However the whole thing depends on a bunch of system resources which are presumably specified by the device manufacturer, and they are all hidden in com.android.internal.R.styleable, which isn't accessible from a user-built app.

You may be able to get at them by using
context.getResources().getIdentifier(...) if you can find the name of the resource by looking at the Android source code. However
getIdentifier() is currently deprecated and may disappear at some time in the future.

More problematically,
Settings.System.SCREEN_BRIGHTNESS is no longer necessarily the brightness set by the user in the Settings page: this depends on how the device manufacturer configured it. On my new Samsung Galaxy S21, it's the adjusted brightness in auto mode. Even stranger, in auto mode the Settings page brightness slider shows the adjusted value, and will move as you move the phone between a brightly it and a dimly lit area.

There are two ways to set the screen brightness programmatically. You can set Settings.System.SCREEN_BRIGHTNESS (range is 0 .. 255), but on versions of Android later than API level 23 this requires a
runtime permission which can only be requested dynamically.

You can also set the brightness for your app's current top-level window only using
getWindow().getAttributes().screenBrightness(range is 0.0F .. 1.0F, or -1.0F not to override the system setting).

If you just want to set the screen brightness within your app, that is the easiest solution since it requires no permissions.

Another way of achieving a similar effect, at least if your screen uses a dark background, is to reduce the opacity of all the widgets. This works nicely on an OLED screen, where only lit pixels consume power, but not so well on a backlit screen.

However it doesn't seem to be possible on Android to determine programmatically whether the display is backlit or an OLED, see this stackoverflow question

I have posted a little app
on github which you can play with to see how your device does brightness control in the various ways mentioned. It also contains code to do all of the things that I describe above, which you can copy if you need to.

ContentLicense: CC BY-SA 2.5


问:
Find column with specific name and fill the field with specific text to the last row
I need to find column named "Current" (preferred) or last column in general in the table named "YTD_input1" and fill all rows with text "Current" to the last row of the table.

My suggested code is below but does not work.

```<code> Dim pasteSheet As Worksheet: Set pasteSheet = wb.Worksheets("DPM input YTD_working")
 Dim LastRow As Long, Nxtrw As Long, lCol As Long

 LastRow = copySheet.Cells(Rows.Count, 1).End(xlUp).Row

 lCol = pasteSheet.Cells(1, Columns.Count).End(xlToLeft).Select

 pasteSheet.Range(lCol & LastRow).Value = "Current"
</code>```

Can you please give me some advice how to build the code to be working?

答:
Fill an Excel Table Column

Option Explicit

Sub FillTableColumn()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets("DPM input YTD_working")
    Dim tbl As ListObject: Set tbl = ws.ListObjects("YTD_input1")

    Dim lcl As ListColumn
    On Error Resume Next
        Set lcl = tbl.ListColumns("Current")
    On Error GoTo 0

    ' Reference the column data range (no header).
    Dim cdrg As Range

    ' Either...
    If Not lcl Is Nothing Then ' column 'Current' found
        Set cdrg = lcl.DataBodyRange
        ' Fill
        cdrg.Value = "Current"
    'Else ' column 'Current' not found - do nothing
    End If

'    ' ... or e.g.:
'    If lcl Is Nothing Then ' column 'Current' found
'        Set cdrg = lcl.DataBodyRange
'    Else ' column 'Current' not found - reference the last columnn
'        Set cdrg = tbl.DataBodyRange.Columns(tbl.DataBodyRange.Columns.Count)
'    End If
'
'    ' Fill
'    cdrg.Value = "Current"

End Sub
```

Body:
I need to find column named "Current" (preferred) or last column in general in the table named "YTD_input1" and fill all rows with text "Current" to the last row of the table.

My suggested code is below but does not work.

 Dim pasteSheet As Worksheet: Set pasteSheet = wb.Worksheets("DPM input YTD_working")
 Dim LastRow As Long, Nxtrw As Long, lCol As Long

 LastRow = copySheet.Cells(Rows.Count, 1).End(xlUp).Row

 lCol = pasteSheet.Cells(1, Columns.Count).End(xlToLeft).Select

 pasteSheet.Range(lCol & LastRow).Value = "Current"

Can you please give me some advice how to build the code to be working?


问:
how to enable comparison between Vec<_> and Vec<_,CustomAllocator>?
I am trying to use a custom allocator, using the allocator API in Rust.

It seems Rust considers Vec<u8,CustomAllocator> and Vec<u8> as two distinct types.

    let a: Vec<u8,CustomAllocator> = Vec::new_in(CustomAllocator);
    for x in [1,2,3] { a.push(x) }

    let b:Vec<u8> = vec![1,2,3];
    assert_eq!(a,b);
```
<p>It means that a simple comparison like the below won't compile:</p>
```error[E0277]: can't compare `Vec<u8, CustomAllocator>` with `Vec<u8>`
  --> src/main.rs:37:5
   |
37 |     assert_eq!(a,b);
   |     ^^^^^^^^^^^^^^^ no implementation for `Vec<u8, CustomAllocator> == Vec<u8>`
   |
   = help: the trait `PartialEq<Vec<u8>>` is not implemented for `Vec<u8, CustomAllocator>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
```

I can't implement the trait, as I don't own either Vec or PartialEq.

In reality, and in the context of my implementation, I may compare both underlying slices. But I don't see how I can achieve this with the language...

Any clue appreciated!

答:
Update:
Since GitHub pull request #93755 has been merged, comparison between Vecs with different allocators is now possible.

Original answer:

Vec uses the std::alloc::Global allocator by default, so Vec<u8> is in fact Vec<u8, Global>. Since Vec<u8, CustomAllocator> and Vec<u8, Global> are indeed distinct types, they cannot directly be compared because the PartialEq implementation is not generic for the allocator type. As @PitaJ commented, you can compare the slices instead using assert_eq!(&a[..], &b[..]) (which is also what the author of the allocator API recommends).

Body:
I am trying to use a custom allocator, using the allocator API in Rust.

It seems Rust considers Vec<u8,CustomAllocator> and Vec<u8> as two distinct types.

    let a: Vec<u8,CustomAllocator> = Vec::new_in(CustomAllocator);
    for x in [1,2,3] { a.push(x) }

    let b:Vec<u8> = vec![1,2,3];
    assert_eq!(a,b);

It means that a simple comparison like the below won't compile:

error[E0277]: can't compare `Vec<u8, CustomAllocator>` with `Vec<u8>`
  --> src/main.rs:37:5
   |
37 |     assert_eq!(a,b);
   |     ^^^^^^^^^^^^^^^ no implementation for `Vec<u8, CustomAllocator> == Vec<u8>`
   |
   = help: the trait `PartialEq<Vec<u8>>` is not implemented for `Vec<u8, CustomAllocator>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

I can't implement the trait, as I don't own either Vec or PartialEq.

In reality, and in the context of my implementation, I may compare both underlying slices. But I don't see how I can achieve this with the language...

Any clue appreciated!


问:
GCE Load Balancer Health Check Fails (Connection Refused)
My (GCE) Load Balancer health checks are failing with a connection refused error, ultimately marking my GCE Ingress as UNHEALTHY.
Now I'm wondering how to fix this issue.

For my setup I'm using a GKE Autopilot cluster. And I have teared down and restarted my setup several times, always leading to the same result.

Suppose I have a deployment configured with a pod template consisting of several containers (of which not all of them expose ports).

Side Note: For simplicity I skipped some configurations, such as config maps.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-app-deployment
spec:
  selector:
    matchLabels:
      app: some-app
  replicas: 2
  template:
    metadata:
      labels:
        app: some-app
    spec:
      restartPolicy: Always
      containers:
        - name: web-server
          image: {{some-app-image}}
          command: ['app', 'web-server']
          ports:
            - name: web-server
              containerPort: 5000
              protocol: TCP
        - name: admin-server
          image: {{some-app-image}}
          command: ['app', 'admin-server']
          ports:
            - name: admin-server
              containerPort: 5001
              protocol: TCP
        - name: worker
          image: {{some-app-image}}
          command: ['app', 'worker']
        - name: cron
          image: {{some-app-image}}
          command: ['app', 'cron']
        - name: helper
          image: {{some-app-image}}
          command: [ '/bin/bash', '-c', '--' ]
          args: [ 'while true; do sleep 30; done;' ]
```
<p>The following is the BackendConfig CRD, which supposedly defines the health check.
I chose to define the path as <code>/favicon.ico</code> because Load Balancer Health Check requires exactly <code>200 OK</code> response and the web-servers base path <code>/</code> emits a redirect <code>302</code>, hence it would faild the Health Check.
With <code>kubectl port-forward</code> I confirmed that <code>/favicon.ico</code> actually emits <code>200 OK</code> and it does.
Btw. just to exclude this from being a problem, I also tried other paths without success.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: http-hc-config
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20
</code>```

Additionally there is a custom header added to the admin endpoint.

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: x-header-config
spec:
  customRequestHeaders:
    headers:
    - "X-Client-Region:{client_region}"
```
<p>The following is the service description. It references the BackendConfig via annotations as per the documentation.
The documentation is not very specific as to how to reference the health check, so I mapped it to the relevant port.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
  name: some-app-service
  annotations:
    cloud.google.com/backend-config: '{
      "default":"http-hc-config",
      "ports":{"4001":"x-header-config"}}'
spec:
  type: NodePort
  selector:
    app: some-app
  ports:
    - name: web
      targetPort: 5000
      protocol: TCP
      port: 4000
    - name: admin
      targetPort: 5001
      protocol: TCP
      port: 4001
</code>```

I confirmed that my service is running, as I could successfully kubectl port-forward the pods and access the web-servers content.

Now the final piece of the setup is this ingress object.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: gce
spec:
  rules:
    - host: admin.example.com
      http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4001
    - http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4000
```
<p>EDIT #1 & #2:
Performing a <code>gcloud compute health-checks describe {{HEALTH_DEF_ID}}</code> I receive the following output for the health check on <code>port 4001</code>, which seems to be out-of-sync with the defined BackendConfig CRD:</p>
<pre class="lang-yaml prettyprint-override"><code>checkIntervalSec: 15
creationTimestamp: '2022-02-07T11:30:50.059-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  portSpecification: USE_SERVING_PORT
  proxyHeader: NONE
  requestPath: /
id: {{REDACTED}}
kind: compute#healthCheck
logConfig:
  enable: true
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2
</code>```

And the following for port 4000, which surprisingly contains the right path and port configuration:

checkIntervalSec: 20
creationTimestamp: '2022-02-07T12:12:59.248-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  port: 5000
  portSpecification: USE_FIXED_PORT
  proxyHeader: NONE
  requestPath: /favicon.ico
id: {{REDACTED}}
kind: compute#healthCheck
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2
```
<p>Either there's something wrong with my setup, or the BackendConfig is not equally applied for all services in the rules section of the Ingress.</p>
<p>Edit #3:</p>
<p>The Healt Check log entry for <code>port 4000</code> shows:</p>
<pre class="lang-json prettyprint-override"><code>healthCheckProbeResult: {
detailedHealthState: "TIMEOUT"
healthCheckProtocol: "HTTP"
healthState: "UNHEALTHY"
ipAddress: "10.40.129.203"
previousDetailedHealthState: "UNKNOWN"
previousHealthState: "UNHEALTHY"
probeCompletionTimestamp: "2022-02-07T20:06:10.955412154Z"
probeRequest: "/favicon.ico"
probeResultText: "HTTP response: , Error: Connection refused"
probeSourceIp: "35.191.12.114"
responseLatency: "0.000569s"
targetIp: "10.40.129.203"
targetPort: 5000
}
</code>```

EDIT #4:
I needed to adjust the BackendConfig annotation, as my case was in fact more involved compared to what my previous definitions were showing.

答:
Can you do a kubectl describe ing ingress?

I think you should see an error about an invalid wildcard.  You should leave the * out.

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: gce
spec:
  rules:
    - host: admin.example.com
      http:
        paths:
        - path: /
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4001
    - http:
        paths:
        - path: /
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4000
</code>```

Body:
My (GCE) Load Balancer health checks are failing with a connection refused error, ultimately marking my GCE Ingress as UNHEALTHY.
Now I'm wondering how to fix this issue.

For my setup I'm using a GKE Autopilot cluster. And I have teared down and restarted my setup several times, always leading to the same result.

Suppose I have a deployment configured with a pod template consisting of several containers (of which not all of them expose ports).

Side Note: For simplicity I skipped some configurations, such as config maps.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-app-deployment
spec:
  selector:
    matchLabels:
      app: some-app
  replicas: 2
  template:
    metadata:
      labels:
        app: some-app
    spec:
      restartPolicy: Always
      containers:
        - name: web-server
          image: {{some-app-image}}
          command: ['app', 'web-server']
          ports:
            - name: web-server
              containerPort: 5000
              protocol: TCP
        - name: admin-server
          image: {{some-app-image}}
          command: ['app', 'admin-server']
          ports:
            - name: admin-server
              containerPort: 5001
              protocol: TCP
        - name: worker
          image: {{some-app-image}}
          command: ['app', 'worker']
        - name: cron
          image: {{some-app-image}}
          command: ['app', 'cron']
        - name: helper
          image: {{some-app-image}}
          command: [ '/bin/bash', '-c', '--' ]
          args: [ 'while true; do sleep 30; done;' ]

The following is the BackendConfig CRD, which supposedly defines the health check.
I chose to define the path as /favicon.ico because Load Balancer Health Check requires exactly 200 OK response and the web-servers base path / emits a redirect 302, hence it would faild the Health Check.
With kubectl port-forward I confirmed that /favicon.ico actually emits 200 OK and it does.
Btw. just to exclude this from being a problem, I also tried other paths without success.

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: http-hc-config
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20

Additionally there is a custom header added to the admin endpoint.

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: x-header-config
spec:
  customRequestHeaders:
    headers:
    - "X-Client-Region:{client_region}"

The following is the service description. It references the BackendConfig via annotations as per the documentation.
The documentation is not very specific as to how to reference the health check, so I mapped it to the relevant port.

apiVersion: v1
kind: Service
metadata:
  name: some-app-service
  annotations:
    cloud.google.com/backend-config: '{
      "default":"http-hc-config",
      "ports":{"4001":"x-header-config"}}'
spec:
  type: NodePort
  selector:
    app: some-app
  ports:
    - name: web
      targetPort: 5000
      protocol: TCP
      port: 4000
    - name: admin
      targetPort: 5001
      protocol: TCP
      port: 4001

I confirmed that my service is running, as I could successfully kubectl port-forward the pods and access the web-servers content.

Now the final piece of the setup is this ingress object.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: gce
spec:
  rules:
    - host: admin.example.com
      http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4001
    - http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4000

EDIT #1 & #2:
Performing a gcloud compute health-checks describe {{HEALTH_DEF_ID}} I receive the following output for the health check on port 4001, which seems to be out-of-sync with the defined BackendConfig CRD:

checkIntervalSec: 15
creationTimestamp: '2022-02-07T11:30:50.059-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  portSpecification: USE_SERVING_PORT
  proxyHeader: NONE
  requestPath: /
id: {{REDACTED}}
kind: compute#healthCheck
logConfig:
  enable: true
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2

And the following for port 4000, which surprisingly contains the right path and port configuration:

checkIntervalSec: 20
creationTimestamp: '2022-02-07T12:12:59.248-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  port: 5000
  portSpecification: USE_FIXED_PORT
  proxyHeader: NONE
  requestPath: /favicon.ico
id: {{REDACTED}}
kind: compute#healthCheck
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2

Either there's something wrong with my setup, or the BackendConfig is not equally applied for all services in the rules section of the Ingress.

Edit #3:

The Healt Check log entry for port 4000 shows:

healthCheckProbeResult: {
detailedHealthState: "TIMEOUT"
healthCheckProtocol: "HTTP"
healthState: "UNHEALTHY"
ipAddress: "10.40.129.203"
previousDetailedHealthState: "UNKNOWN"
previousHealthState: "UNHEALTHY"
probeCompletionTimestamp: "2022-02-07T20:06:10.955412154Z"
probeRequest: "/favicon.ico"
probeResultText: "HTTP response: , Error: Connection refused"
probeSourceIp: "35.191.12.114"
responseLatency: "0.000569s"
targetIp: "10.40.129.203"
targetPort: 5000
}

EDIT #4:
I needed to adjust the BackendConfig annotation, as my case was in fact more involved compared to what my previous definitions were showing.

Body:
Can you do a kubectl describe ing ingress?

I think you should see an error about an invalid wildcard.  You should leave the * out.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: gce
spec:
  rules:
    - host: admin.example.com
      http:
        paths:
        - path: /
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4001
    - http:
        paths:
        - path: /
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4000


问:
Cannot resolve symbol 'router-outlet'
The project is based on Angular 13.

Added routing to the project.
app-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import {RouterModule, Routes} from "@angular/router";
import {HomePageComponent} from "./home-page/home-page.component";

const appRoutes: Routes =[
  { path: '', component: HomePageComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

added AppRoutingModule to the file app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {ModalModule} from "ngb-modal";
import {FormsModule} from "@angular/forms";
import { HomePageComponent } from './home-page/home-page.component';
import {AppRoutingModule} from "./app-routing.module";

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    HomePageComponent
  ],

  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

but if I try to add to the file app.component.html

```<code><router-outlet></router-outlet>
</code>```

IDEA throws an error

```<code>Cannot resolve symbol 'router-outlet'
</code>```

But if I open another project with routing in the same IDE, there is no such error.

答:
I guess you are using WebStorm as an IDE, since i also ran into that warning when i upgraded my project to Angular 13, yet i didn't it on VSC.

Apparently in order to solve it you need to upgrade WebStorm to 2021.3. I recommend using JetBrains's toolbox app, which makes it easy to update.

Title: Cannot resolve symbol 'router-outlet'

Body:
The project is based on Angular 13.

Added routing to the project.
app-routing.module.ts

import { NgModule } from '@angular/core';
import {RouterModule, Routes} from "@angular/router";
import {HomePageComponent} from "./home-page/home-page.component";

const appRoutes: Routes =[
  { path: '', component: HomePageComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

added AppRoutingModule to the file app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {ModalModule} from "ngb-modal";
import {FormsModule} from "@angular/forms";
import { HomePageComponent } from './home-page/home-page.component';
import {AppRoutingModule} from "./app-routing.module";

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    HomePageComponent
  ],

  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

but if I try to add to the file app.component.html

<router-outlet></router-outlet>

IDEA throws an error

Cannot resolve symbol 'router-outlet'

But if I open another project with routing in the same IDE, there is no such error.


问:
How to create a new column based off a number in an existing column that matches with another column's categorical value
I have a dataframe with game, category, if it's solo play or not, and with rating. I add a new column that contains the best game in terms of max rating in each category within each solo/double grouping.

```<code>category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
game <- c("Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$game <- game
df$solo <- solo
df$category <- category

df <- df  %>%
  group_by(category, solo) %>%
  mutate(best_game = max(rating, na.rm = TRUE)) %>%
  ungroup
</code>```

My question is, instead of having the highest rating (best_game) for each solo/double and category group, how can I add a column that has the game corresponding to the highest rating in best_game?

Example Output. Expected output is what I'd like to happen

```<code>rating    game    solo   category  best_game  **(expected_output)**
    5       Game1   double  Party   5            Game1
    3       Game1   double  Party   5            Game1
</code>```

答:
Just include a statment to subset the game variable with rating == max(rating)

```<code>df <- df  %>%
        group_by(category, solo) %>%
        mutate(best_game = game[rating == max(rating, na.rm = TRUE)]) %>%
        ungroup

df

# A tibble: 18 × 5
   rating game  solo   category  best_game
    <dbl> <chr> <chr>  <chr>     <chr>
 1      8 Game1 solo   Party     Game1
 2      7 Game2 solo   Adventure Game2
 3      6 Game3 solo   Puzzle    Game3
 4      5 Game1 double Party     Game1
 5      3 Game2 double Adventure Game2
 6      3 Game3 double Puzzle    Game3
 7      2 Game1 solo   Party     Game1
 8      1 Game2 solo   Adventure Game2
 9     10 Game3 solo   Puzzle    Game3
10      3 Game1 double Party     Game1
11      4 Game2 double Adventure Game2
12      5 Game3 double Puzzle    Game3
13      6 Game1 solo   Party     Game1
14      3 Game2 solo   Adventure Game2
15      2 Game3 solo   Puzzle    Game3
16      1 Game1 double Party     Game1
17      3 Game2 double Adventure Game2
18      1 Game3 double Puzzle    Game3
</code>```

Body:
I have a dataframe with game, category, if it's solo play or not, and with rating. I add a new column that contains the best game in terms of max rating in each category within each solo/double grouping.

category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
game <- c("Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$game <- game
df$solo <- solo
df$category <- category

df <- df  %>%
  group_by(category, solo) %>%
  mutate(best_game = max(rating, na.rm = TRUE)) %>%
  ungroup

My question is, instead of having the highest rating (best_game) for each solo/double and category group, how can I add a column that has the game corresponding to the highest rating in best_game?

Example Output. Expected output is what I'd like to happen

rating    game    solo   category  best_game  **(expected_output)**
    5       Game1   double  Party   5            Game1
    3       Game1   double  Party   5            Game1

Body:
Just include a statment to subset the game variable with rating == max(rating)

df <- df  %>%
        group_by(category, solo) %>%
        mutate(best_game = game[rating == max(rating, na.rm = TRUE)]) %>%
        ungroup

df

# A tibble: 18 × 5
   rating game  solo   category  best_game
    <dbl> <chr> <chr>  <chr>     <chr>
 1      8 Game1 solo   Party     Game1
 2      7 Game2 solo   Adventure Game2
 3      6 Game3 solo   Puzzle    Game3
 4      5 Game1 double Party     Game1
 5      3 Game2 double Adventure Game2
 6      3 Game3 double Puzzle    Game3
 7      2 Game1 solo   Party     Game1
 8      1 Game2 solo   Adventure Game2
 9     10 Game3 solo   Puzzle    Game3
10      3 Game1 double Party     Game1
11      4 Game2 double Adventure Game2
12      5 Game3 double Puzzle    Game3
13      6 Game1 solo   Party     Game1
14      3 Game2 solo   Adventure Game2
15      2 Game3 solo   Puzzle    Game3
16      1 Game1 double Party     Game1
17      3 Game2 double Adventure Game2
18      1 Game3 double Puzzle    Game3


问:
AWS Fargate modify /etc/hosts on startup
I am calling an external API and the only way to call is when I have a hosts file entry. So right now I ECS Exec and add it there. I want to automate it so when I autoscale I don't have to ECS Exec to add the hosts file entry on each task.

Below is part of my task definition that has Entrypoint / command. They both are empty. I believe I can use one of them to do this but not 100% sure.

```<code>  "entryPoint": null,
  "portMappings": [
    {
      "hostPort": 8000,
      "protocol": "tcp",
      "containerPort": 8000
    }
  ],
  "command": null,
</code>```

答:
Posting this for the sake of others with similar needs. There's 3 ways to  make this work.

Like the commentors have pointed out R53 private hosted zones (costs money + affects the entire VPC, not just your containers)

Create a Startup.sh which can have logic to add to hosts and add it as part of your container deployable and invoke it using the DockerFile

ADD RunStartUp.sh RunStartUp.sh
CMD["./RunStartUp.sh"]

Directly add the hosts entry using entryPoint/Command in the task definition json

"entryPoint": [
"sh",
"-c"
],
"command" : [
"/bin/sh -c "echo '122.123.423.12 google.com >> \etc\hosts ""
]

Body:
I am calling an external API and the only way to call is when I have a hosts file entry. So right now I ECS Exec and add it there. I want to automate it so when I autoscale I don't have to ECS Exec to add the hosts file entry on each task.

Below is part of my task definition that has Entrypoint / command. They both are empty. I believe I can use one of them to do this but not 100% sure.

  "entryPoint": null,
  "portMappings": [
    {
      "hostPort": 8000,
      "protocol": "tcp",
      "containerPort": 8000
    }
  ],
  "command": null,


问:
How to add a button to remove user
I currently have this code that displays users on a team and when you click on the name of a user that is on the list it passes the name that you click to a function which removes them from the team. Instead I would like a button to be next to the name and when you click the button it removes the person that the button is next to. How would I go about doing this

```<code>$(document).ready(function() {
        $("#your_teams234").change(function() {

            var team = $("#your_teams234").val();
            $.ajax({
                url: 'functions.php',
                method: 'post',
                data: 'members=' + team
            }).done(function(requests) {
                console.log(requests);
                requests = JSON.parse(requests);
                $('#teammates').empty();
                if (requests.length != 0) {
                    $("#teamContainer").css("display", "block");
                    requests.forEach(function(request) {
                        $('#teammates').append('<p class="myDivs">' + request.email + '</p>')
                    })
                }
                if (requests.length == 0) {
                    $('#teammates').append(`<p> No teammates </p>`)
                }
                $('.myDivs').click(function() {
                    $var1 = $(this).text();
                    $.ajax({
                        url: 'functions.php',
                        type: 'post',
                        data: {
                            "callFunc1": $var1,
                            "teamName": team
                        },
                        success: function(response) {
                            console.log(response);
                        }
                    });
                });
            })
        })
    })
</code>```

Here is the html code for my team container

```<code><div id="teamContainer" style="display: none;">
    <p style="font-weight: bold; font-size:18px left">Current Team Members (click name to remove)</p>
    <div id='teammates'>
    </div>
    <hr style="margin-left: 350px; margin-right: 350px">
</div>
</div>
</code>```

答:
First off, you really should be passing ID's rather than names in order to access a user. What if you have 2 users with the same name, or apostrophes/odd characters - or even the lack of a name? At any rate, you didn't show your HTML but here's how it could work.

$('.remover').click(function() {
  let $user = $(this).closest('.user-container').find('.myDivs');
  let $userid = $user.data('id');
  let $username = $user.text();
  console.log(`remove user ${$username}, id ${$userid}`);
  $(this).closest('.user-container').remove()
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='user-container'>
  <span class='myDivs' data-id='1'>John Smith</span>
  <button class='remover'>Remove user</button>
</div>

<div class='user-container'>
  <span class='myDivs' data-id='2'>Susan Sarandon</span>
  <button class='remover'>Remove user</button>
</div>

<div class='user-container'>
  <span class='myDivs' data-id='3'>Bill Nye</span>
  <button class='remover'>Remove user</button>
</div></code>```

Title: How to add a button to remove user

Body:
I currently have this code that displays users on a team and when you click on the name of a user that is on the list it passes the name that you click to a function which removes them from the team. Instead I would like a button to be next to the name and when you click the button it removes the person that the button is next to. How would I go about doing this

$(document).ready(function() {
        $("#your_teams234").change(function() {

            var team = $("#your_teams234").val();
            $.ajax({
                url: 'functions.php',
                method: 'post',
                data: 'members=' + team
            }).done(function(requests) {
                console.log(requests);
                requests = JSON.parse(requests);
                $('#teammates').empty();
                if (requests.length != 0) {
                    $("#teamContainer").css("display", "block");
                    requests.forEach(function(request) {
                        $('#teammates').append('
' + request.email + '
')
                    })
                }
                if (requests.length == 0) {
                    $('#teammates').append(`<p> No teammates </p>`)
                }
                $('.myDivs').click(function() {
                    $var1 = $(this).text();
                    $.ajax({
                        url: 'functions.php',
                        type: 'post',
                        data: {
                            "callFunc1": $var1,
                            "teamName": team
                        },
                        success: function(response) {
                            console.log(response);
                        }
                    });
                });
            })
        })
    })

Here is the html code for my team container

Current Team Members (click name to remove)

Body:
First off, you really should be passing ID's rather than names in order to access a user. What if you have 2 users with the same name, or apostrophes/odd characters - or even the lack of a name? At any rate, you didn't show your HTML but here's how it could work.

$('.remover').click(function() {
  let $user = $(this).closest('.user-container').find('.myDivs');
  let $userid = $user.data('id');
  let $username = $user.text();
  console.log(`remove user ${$username}, id ${$userid}`);
  $(this).closest('.user-container').remove()
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='user-container'>
  <span class='myDivs' data-id='1'>John Smith</span>
  <button class='remover'>Remove user</button>
</div>

<div class='user-container'>
  <span class='myDivs' data-id='2'>Susan Sarandon</span>
  <button class='remover'>Remove user</button>
</div>

<div class='user-container'>
  <span class='myDivs' data-id='3'>Bill Nye</span>
  <button class='remover'>Remove user</button>
</div>


问:
How to display eslint errors in Visual Studio 2019 Error list
Having SPA application with Angular and .net core web api, I would like to apply some typescript code style, so all of my team mates write code in same style. TSLint which is default linter shipped with angular is deprecated (as mentioned on theirs github page) so I went through tslint recomendations an try to use typescript-eslint. It was easy to add it to the project and run manually from cmd/powerShell.
Now I want to run lint after msbuild so I added after build step in csproj file

```<code><Target Name="typescript-eslint" AfterTargets="Build">
  <Exec WorkingDirectory="$(SpaRoot)" Command="npx eslint --ext .ts"/>
</Target>
</code>```

Which is works fine, but errors appeared in Error List window not helpful at all.
I wonder is there a way to output errors in same way as it will be regular .net compilation error, so I can double click on error and quickly navigate to it.

答:
TSLint is deprecated. You can do the following:

Install ESLint via npm.

Amend your build script to the following:

```<code><Target Name="RunESLint" BeforeTargets="AfterBuild">
    <Exec Command="npx eslint $(SpaRoot) --format visualstudio"></Exec>
</Target>
</code>```

The key is in the --format option.

Body:
Having SPA application with Angular and .net core web api, I would like to apply some typescript code style, so all of my team mates write code in same style. TSLint which is default linter shipped with angular is deprecated (as mentioned on theirs github page) so I went through tslint recomendations an try to use typescript-eslint. It was easy to add it to the project and run manually from cmd/powerShell.
Now I want to run lint after msbuild so I added after build step in csproj file

<Target Name="typescript-eslint" AfterTargets="Build">
  <Exec WorkingDirectory="$(SpaRoot)" Command="npx eslint --ext .ts"/>
</Target>

Which is works fine, but errors appeared in Error List window not helpful at all.
I wonder is there a way to output errors in same way as it will be regular .net compilation error, so I can double click on error and quickly navigate to it.

Body:
TSLint is deprecated. You can do the following:

Install ESLint via npm.

Amend your build script to the following:

<Target Name="RunESLint" BeforeTargets="AfterBuild">
    <Exec Command="npx eslint $(SpaRoot) --format visualstudio"></Exec>
</Target>

The key is in the --format option.