问:
InputText component behaves unexpectedly
To add events and formatters to the InputText component of Blazor, I have created an inherited component, InputText2.

It looks like this:

public class InputText2 : InputText
{
    [Parameter]
    public Action<string> OnBlur { get; set; }

    [Parameter]
    public Func<string, string> Formatter { get; set; }

    protected override bool TryParseValueFromString(string value, out string result, [NotNullWhen(false)] out string validationErrorMessage)
    {
        var parseResult = base.TryParseValueFromString(value, out result, out validationErrorMessage);

        OnBlur?.Invoke(value);

        return parseResult;
    }

    protected override string FormatValueAsString(string value)
    {
        var result = Formatter?.Invoke(value) ?? value;
        //CurrentValueAsString = result;

        return result;
    }
}
```

The Formatter parameter takes a Func that modifies the string in some way. In my example, I wanted postal codes in the format "12345" to be formatted "123 45". In FormatValueAsString, result gets the correct value, but this is not reflected in the UI after rendering. However, if I do set CurrentValueAsString to result, then it works. But I can't find any reason for this. And in other examples, that property is never touched either. Also, it seems to be able to create loops between FormatValueAsString and TryParseValueFromString.

Anyone seen this before?

答:
FormatValueAsString is just used by InputBase to format the CurrentValue in the getter for CurrentValueAsString.

The value that is bound to the input control and hence what you see on the page is the value of CurrentValue

So, if you want the displayed value to use the formatted value, you need to set CurrentValue to that formatted value - and this is what happens when you include the line to set CurrentValueAsString = result - the setter on CurrentValueAsString sets CurrentValue.

Body:
To add events and formatters to the InputText component of Blazor, I have created an inherited component, InputText2.

It looks like this:

public class InputText2 : InputText
{
    [Parameter]
    public Action<string> OnBlur { get; set; }

    [Parameter]
    public Func<string, string> Formatter { get; set; }

    protected override bool TryParseValueFromString(string value, out string result, [NotNullWhen(false)] out string validationErrorMessage)
    {
        var parseResult = base.TryParseValueFromString(value, out result, out validationErrorMessage);

        OnBlur?.Invoke(value);

        return parseResult;
    }

    protected override string FormatValueAsString(string value)
    {
        var result = Formatter?.Invoke(value) ?? value;
        //CurrentValueAsString = result;

        return result;
    }
}

The Formatter parameter takes a Func that modifies the string in some way. In my example, I wanted postal codes in the format "12345" to be formatted "123 45". In FormatValueAsString, result gets the correct value, but this is not reflected in the UI after rendering. However, if I do set CurrentValueAsString to result, then it works. But I can't find any reason for this. And in other examples, that property is never touched either. Also, it seems to be able to create loops between FormatValueAsString and TryParseValueFromString.

Anyone seen this before?


来源: stackexchange

问:
AWS ECS Fargate dynamically register IP to target group
I use AWS at work and I am fairly new to this.

I have multiple Services with one Task/Container running. Each Container is fundamentally the same with a few changes, it's basically for different stages/deployments. I have one target group for each, so my load balancer routes requests from specific domains to each.

For example: if host is example1.com then forward to exampleTargetGroup1 and so on.

The Problem

As you may know each time a container is updated, its IP changes, hence I have to re-register the new IP to the target group

I have found several approaches to this problem. Most of them suggest to use a Network Load Balancer for a static IP, but this doesn't work because, as I understand it, it registers the containers automatically on updates.

Another solution is to trigger a Lambda function on a cloud watch events when the Task is being updated. The function grabs the IP and updates the Route53 record. My Idea was to take this approach and deregister the old IP in the target group and register the new one.

My Questions

Is there a better solution to this or did I understand the first solutions wrong? If the last solution is optimal for my problem is there maybe a code sample so I won't need to figure it out?

EDIT:

Thanks to Mark B I now know, you should preferably use the AWS API or a tool like Terraform to create an ECS Service and associating a target group to it.

答:
"but this doesn't work because, as I understand it, it registers the
containers automatically on updates."

I think you are misunderstanding something here. Each ECS service should be associated with a load balancer Target Group. Whenever the service creates a task, the service will automatically add that task's IP to the target group. Whenever the service removes a task, it will also remove that task's IP from the target group. This works with both Network Load Balancers and Application Load Balancers.

You stated the following:

"I have multiple Services with one Task/Container running"

So you have one task per service, and one service per target group. From your description, your architecture should look like this:

```<code>One load Balancer with multiple domains pointing at it.
In the Load Balancer listener configuration, you have each domain configured to route to a different target group.
Each ECS service configured with a task count of 1

Load balancer -> domain name 1 -> target group 1 -> ECS service 1 -> ECS task 1
Load balancer -> domain name 2 -> target group 2 -> ECS service 2 -> ECS task 2
Load balancer -> domain name 3 -> target group 3 -> ECS service 3 -> ECS task 3
etc...
</code>```

In the above scenario, as long as you have each ECS service configured with the appropriate target group, each time that service redeploys a task it will automatically update the target group to point to the updated task.

In other words ECS will "dynamically register the IP to target group", exactly like you are wanting.

ContentLicense: CC BY-SA 4.0

Body:
"but this doesn't work because, as I understand it, it registers the
containers automatically on updates."

I think you are misunderstanding something here. Each ECS service should be associated with a load balancer Target Group. Whenever the service creates a task, the service will automatically add that task's IP to the target group. Whenever the service removes a task, it will also remove that task's IP from the target group. This works with both Network Load Balancers and Application Load Balancers.

You stated the following:

"I have multiple Services with one Task/Container running"

So you have one task per service, and one service per target group. From your description, your architecture should look like this:

One load Balancer with multiple domains pointing at it.
In the Load Balancer listener configuration, you have each domain configured to route to a different target group.
Each ECS service configured with a task count of 1

Load balancer -> domain name 1 -> target group 1 -> ECS service 1 -> ECS task 1
Load balancer -> domain name 2 -> target group 2 -> ECS service 2 -> ECS task 2
Load balancer -> domain name 3 -> target group 3 -> ECS service 3 -> ECS task 3
etc...

In the above scenario, as long as you have each ECS service configured with the appropriate target group, each time that service redeploys a task it will automatically update the target group to point to the updated task.

In other words ECS will "dynamically register the IP to target group", exactly like you are wanting.


问:
awk command with regex expression from variable fails
I am trying to fetch elements from array on the basis specific pattern
for example:
alllist is array contains following data:

```<code>echo "${alllist[@]}":
setup-demo1-release-0 setup-demo1-release-1 setup-demo1-release-2 setup-demo1-production-0 setup-demo1-production-1
</code>```

where type is a variable and can have values like -release-0 and -production-0 ending with hyphen and numeric number

setup-demo1 is same for all elements in array and <-release-0> and <-production-0>
so created a regex expression in which it will look for something like this:
for type=release it shall return all values

```<code>setup-demo1-release-0 setup-demo1-release-1
</code>```

for type=production it shall return all values

```<code>setup-demo1-production-0 setup-demo1-production-1
</code>```

Note: setup-demo1 can also be written as setup-release1 or setup-production1 so using grep for these words shall be ignored.

I have also tried achieving this through awk command:

```<code>endWithDigitPattern='[-0-9]'
targetNodes=($(echo "$alllist"| sed 's/[][",]//g' | tr ' ' '\n' | awk -v nTypes="release""$endWithDigitPattern" '$1~ nTypes {print $1}'))
</code>```

and it is not returning expected result while executed through script file.
and may be I am not using endWithDigitPattern variable in right way.

Let me know what's wrong with my command used.

答:
Setup:

```<code>$ alllist=(setup-demo1-release-0 setup-demo1-release-1 setup-demo1-release-2 setup-demo1-production-0 setup-demo1-production-1)
$ endWithDigitPattern='[-0-9]'
</code>```

echo "$alllist" is the same as echo "${alllist[0]}"; to display the entire contents of the array we need to use echo "${alllist[@]}"  (keeping in mind this will not work as expected if the array values contain white space), eg:

```<code>$ typeset -p alllist
declare -a alllist=([0]="setup-demo1-release-0" [1]="setup-demo1-release-1" [2]="setup-demo1-release-2" [3]="setup-demo1-production-0" [4]="setup-demo1-production-1")

$ echo "$alllist"            # references alllist[0]
setup-demo1-release-0

$ echo "${alllist[@]}"
setup-demo1-release-0 setup-demo1-release-1 setup-demo1-release-2 setup-demo1-production-0 setup-demo1-production-1
</code>```

OP's current code:

```<code>$ echo "$alllist"| sed 's/[][",]//g' | tr ' ' '\n' | awk -v nTypes="release""$endWithDigitPattern" '$1~ nTypes {print $1}'
setup-demo1-release-0
</code>```

Fix to OP's current code:

```<code>$ echo "${alllist[@]}"| sed 's/[][",]//g' |tr ' ' '\n' | awk -v nTypes="release""$endWithDigitPattern" '$1~ nTypes {print $1}'
setup-demo1-release-0
setup-demo1-release-1
setup-demo1-release-2
</code>```

Assuming we can ignore the possibility of white space within the array values, there are a few other ways to to perform the desired operation; one idea using printf|grep:

```<code>$ type=production
$ printf "%s\n" "${alllist[@]}" | grep -- "-${type}-[0-9]"
setup-demo1-production-0
setup-demo1-production-1

$ type=release
$ printf "%s\n" "${alllist[@]}" | grep -- "-${type}-[0-9]"
setup-demo1-release-0
setup-demo1-release-1
setup-demo1-release-2
</code>```

Body:
I am trying to fetch elements from array on the basis specific pattern
for example:
alllist is array contains following data:

echo "${alllist[@]}":
setup-demo1-release-0 setup-demo1-release-1 setup-demo1-release-2 setup-demo1-production-0 setup-demo1-production-1

where type is a variable and can have values like -release-0 and -production-0 ending with hyphen and numeric number

setup-demo1 is same for all elements in array and <-release-0> and <-production-0>
so created a regex expression in which it will look for something like this:
for type=release it shall return all values

setup-demo1-release-0 setup-demo1-release-1

for type=production it shall return all values

setup-demo1-production-0 setup-demo1-production-1

Note: setup-demo1 can also be written as setup-release1 or setup-production1 so using grep for these words shall be ignored.

I have also tried achieving this through awk command:

endWithDigitPattern='[-0-9]'
targetNodes=($(echo "$alllist"| sed 's/[][",]//g' | tr ' ' '\n' | awk -v nTypes="release""$endWithDigitPattern" '$1~ nTypes {print $1}'))

and it is not returning expected result while executed through script file.
and may be I am not using endWithDigitPattern variable in right way.

Let me know what's wrong with my command used.

Body:
Setup:

$ alllist=(setup-demo1-release-0 setup-demo1-release-1 setup-demo1-release-2 setup-demo1-production-0 setup-demo1-production-1)
$ endWithDigitPattern='[-0-9]'

echo "$alllist" is the same as echo "${alllist[0]}"; to display the entire contents of the array we need to use echo "${alllist[@]}"  (keeping in mind this will not work as expected if the array values contain white space), eg:

$ typeset -p alllist
declare -a alllist=([0]="setup-demo1-release-0" [1]="setup-demo1-release-1" [2]="setup-demo1-release-2" [3]="setup-demo1-production-0" [4]="setup-demo1-production-1")

$ echo "$alllist"            # references alllist[0]
setup-demo1-release-0

$ echo "${alllist[@]}"
setup-demo1-release-0 setup-demo1-release-1 setup-demo1-release-2 setup-demo1-production-0 setup-demo1-production-1

OP's current code:

$ echo "$alllist"| sed 's/[][",]//g' | tr ' ' '\n' | awk -v nTypes="release""$endWithDigitPattern" '$1~ nTypes {print $1}'
setup-demo1-release-0

Fix to OP's current code:

$ echo "${alllist[@]}"| sed 's/[][",]//g' |tr ' ' '\n' | awk -v nTypes="release""$endWithDigitPattern" '$1~ nTypes {print $1}'
setup-demo1-release-0
setup-demo1-release-1
setup-demo1-release-2

Assuming we can ignore the possibility of white space within the array values, there are a few other ways to to perform the desired operation; one idea using printf|grep:

$ type=production
$ printf "%s\n" "${alllist[@]}" | grep -- "-${type}-[0-9]"
setup-demo1-production-0
setup-demo1-production-1

$ type=release
$ printf "%s\n" "${alllist[@]}" | grep -- "-${type}-[0-9]"
setup-demo1-release-0
setup-demo1-release-1
setup-demo1-release-2


问:
Selenium: how to define css if webpage has mutiple elements with same name
I have the following HTML code:

```<code><table id="userPlaylistTable" cellspacing="0" cellpadding="0">
<div class="numCellWrapper">
<div class="listArrow up" onclick="moveRowUp($(this))"></div>
<div class="numCell"> 1 </div>
<div class="listArrow down" onclick="moveRowDown($(this))"></div>
</div>
<div class="numCellWrapper">
<div class="listArrow up" onclick="moveRowUp($(this))"></div>
<div class="numCell"> 2 </div>
<div class="listArrow down" onclick="moveRowDown($(this))"></div>
</div>
<div class="numCellWrapper">
<div class="listArrow up" onclick="moveRowUp($(this))"></div>
<div class="numCell"> 3 </div>
<div class="listArrow down" onclick="moveRowDown($(this))"></div>
</div>
</code>```

Basically, now if I define my css as:

```<code>css=table#userPlaylistTable div[class='listArrow up']
</code>```

It picks the first such element it finds. But, how would I have to define my css, so that it picks second element of this type?
So, basically how would I define my css to pick a particular element, if multiple elements of the same kind exist on the page?

Could someone please help me with this query?

Thanks.

答: add [1] which is the index into the array. usually 0 based, so [1] is the second element</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the following HTML code:

 1

 2

 3

Basically, now if I define my css as:

css=table#userPlaylistTable div[class='listArrow up']

It picks the first such element it finds. But, how would I have to define my css, so that it picks second element of this type?
So, basically how would I define my css to pick a particular element, if multiple elements of the same kind exist on the page?

Could someone please help me with this query?

Thanks.


问:
CSS Grid - move it behind the menu bar
Problem: i am building a webpage and learning to use grids with CSS.
But i am running into a problem with it, as the dropdown menu i have at the top of the page, goes BEHIND the grid-items.

i've tried using the z-index: -1; and z-index:1; on just about every block there is regarding both the menu and the grid.
But so far have been unsuccesfull.

So here i am.

How do i do this??

A fiddle to see my "problem"

Here is a FIDDLE of the problem.

it might just be me which is missing something obvious, but i am still learning :D

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  position: relative;
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu-bar">
  <li class="dropdown">
    <p>Test 1</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 2</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 3</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 4 </p>
  </li>
  <li class="dropdown">
    <p>Test 5 </p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
</ul>
<div class="grid-container">
  <div class="grid-item">
    <p> hello world </p>
  </div>
</div></code>```

答:
you have to add 'z-index: -1;' to '.dropdown::before'
and remove position: relative from .grid-item:

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}
.dropdown::before {
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu-bar">
  <li class="dropdown">
    <p>Test 1</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 2</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 3</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 4 </p>
  </li>
  <li class="dropdown">
    <p>Test 5 </p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
</ul>
<div class="grid-container">
  <div class="grid-item">
    <p> hello world </p>
  </div>
</div></code>```

I hope this solution helps

Title: CSS Grid - move it behind the menu bar

Body:
Problem: i am building a webpage and learning to use grids with CSS.
But i am running into a problem with it, as the dropdown menu i have at the top of the page, goes BEHIND the grid-items.

i've tried using the z-index: -1; and z-index:1; on just about every block there is regarding both the menu and the grid.
But so far have been unsuccesfull.

So here i am.

How do i do this??

A fiddle to see my "problem"

Here is a FIDDLE of the problem.

it might just be me which is missing something obvious, but i am still learning :D

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  position: relative;
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}

Test 1

 test 1

 test 2

 test 3

 test 4

Test 2

 test 1

 test 2

 test 3

 test 4

Test 3

 test 1

 test 2

 test 3

 test 4

Test 4

Test 5

 test 1

 test 2

 test 3

 test 4

 hello world

Body:
you have to add 'z-index: -1;' to '.dropdown::before'
and remove position: relative from .grid-item:

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}
.dropdown::before {
  z-index: -1;
}

<ul class="menu-bar">
  <li class="dropdown">
    <p>Test 1</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 2</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 3</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 4 </p>
  </li>
  <li class="dropdown">
    <p>Test 5 </p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
</ul>
<div class="grid-container">
  <div class="grid-item">
    <p> hello world </p>
  </div>
</div>

I hope this solution helps


问:
Angular - How to test if an error was thrown from an observable error function
I have this nested subscription in a function:

```<code>myFunc() {
    this.userService.isLoggedIn().subscribe(isLoggedIn => {
        if (isLoggedIn) {
            this.otherService.post({}).subscribe({
                next: response => {
                    // do stuff
                },
                error: err => {
                    // do stuff
                    throw new UserException(err)
                },
            })
        }
    }
}
</code>```

I would like to write a unit test that expects myFunc to throw UserException if otherService.post responds with an error.
I am trying with this:

```<code>it('should rethrow error', () => {
    const thrownError = new HttpErrorResponse({})
    mockUserService.isLoggedIn.and.returnValue(of(true))
    mockOtherService.post.and.returnValue(throwError(() => thrownError))
    fixture.detectChanges()

    // clicking on the UI to call component.myFunc

    expect(mockOtherService.post).toHaveBeenCalledWith({})
    expect(() => component.myFunc()).toThrow(new UserException(thrownError))
}
</code>```

But it fails because myFunc does not throw an exception. Why is that?

答:
Nested Functions

Consider the following code and notice that even though there's an error thrown "inside" function one, function one will never throw an error on its own.

function one(){
  console.log("ONE");

  const two = () => {
    console.log("TWO");
    throw "This is an error";
  }

  return two;
}

console.log("Calling function one");
one();
console.log("Done with function one");
```
<p>The error is only ever seen later when that internal function is actually called:</p>
<pre class="lang-ts prettyprint-override"><code>const two = one();
// the following throws an error:
two();
</code>```

myFunc doesn't throw an error:

That's how asynchronous code works. It defines some code (like two above) that doesn't get called right away, it gets called sometime later.

By the time either next or error is called from {next: /*...*/, error: /*...*/}, the function that returned the next and error functions (myFunc) has already run and been popped off of the call stack.

So, in this case, your test is correct to note that myFunc doesn't throw an error (because it doesn't).

I'm not sure delving into the various testing libraries and harnesses for RxJS is in scope for such an answer (maybe somebody else will take on that task?).

An Aside: Refactoring RxJS

In general, you shouldn't nest subscriptions. Avoiding nested callbacks is one of the core features of both Promises and Observables for asynchronous workflows.

Here's how I might write myFunc instead:

myFunc() {

  this.userService.isLoggedIn().pipe(

    filter(isLoggedIn => !!isLoggedIn),
    mergeMap(_ => this.otherService.post({}))

  ).subscribe({
    next: response => { /* do stuff */ },
    error: err => {
        // do stuff
        throw new UserException(err);
    }
  })

}
```

Body:
I have this nested subscription in a function:

myFunc() {
    this.userService.isLoggedIn().subscribe(isLoggedIn => {
        if (isLoggedIn) {
            this.otherService.post({}).subscribe({
                next: response => {
                    // do stuff
                },
                error: err => {
                    // do stuff
                    throw new UserException(err)
                },
            })
        }
    }
}

I would like to write a unit test that expects myFunc to throw UserException if otherService.post responds with an error.
I am trying with this:

it('should rethrow error', () => {
    const thrownError = new HttpErrorResponse({})
    mockUserService.isLoggedIn.and.returnValue(of(true))
    mockOtherService.post.and.returnValue(throwError(() => thrownError))
    fixture.detectChanges()

    // clicking on the UI to call component.myFunc

    expect(mockOtherService.post).toHaveBeenCalledWith({})
    expect(() => component.myFunc()).toThrow(new UserException(thrownError))
}

But it fails because myFunc does not throw an exception. Why is that?

Body:
Nested Functions

Consider the following code and notice that even though there's an error thrown "inside" function one, function one will never throw an error on its own.

function one(){
  console.log("ONE");

  const two = () => {
    console.log("TWO");
    throw "This is an error";
  }

  return two;
}

console.log("Calling function one");
one();
console.log("Done with function one");

The error is only ever seen later when that internal function is actually called:

const two = one();
// the following throws an error:
two();

myFunc doesn't throw an error:

That's how asynchronous code works. It defines some code (like two above) that doesn't get called right away, it gets called sometime later.

By the time either next or error is called from {next: /*...*/, error: /*...*/}, the function that returned the next and error functions (myFunc) has already run and been popped off of the call stack.

So, in this case, your test is correct to note that myFunc doesn't throw an error (because it doesn't).

I'm not sure delving into the various testing libraries and harnesses for RxJS is in scope for such an answer (maybe somebody else will take on that task?).

An Aside: Refactoring RxJS

In general, you shouldn't nest subscriptions. Avoiding nested callbacks is one of the core features of both Promises and Observables for asynchronous workflows.

Here's how I might write myFunc instead:

myFunc() {

  this.userService.isLoggedIn().pipe(

    filter(isLoggedIn => !!isLoggedIn),
    mergeMap(_ => this.otherService.post({}))

  ).subscribe({
    next: response => { /* do stuff */ },
    error: err => {
        // do stuff
        throw new UserException(err);
    }
  })

}


问:
CSS email input :valid placeholder issue
I am making a login page with email and password input boxes. I have added a placeholder using a span element. When the input box is clicked it will move the placeholder to the top of the input box and make the font-size a lot smaller. The placeholder stays in this position if the input box is still focused or if text is entered into the input.

This works perfectly for text inputs and the password input because it detects that the inputs are valid when they contain text, but it doesn't work for email input until you type in a email that is the correct format. So for example, if you just type 'test' into the email box it not see this as valid and the placeholder text will go back to its original position and overlap the text.

Can anyone help me with this please?

```<code><form name="login" action="" method="post"><input type="hidden" name="formid" value="4f5e2c860e789bc1df1ea953c167d39e">
    <!-- Email -->
    <div class="input-box login-input">
        <input type="email" name="email_address" class="text-input" autocomplete="email" autocorrect="off" autocapitalize="off" spellcheck="false" required="">
        <span class="input-placeholder">Email</span>
    </div>
    <!-- Password -->
    <div class="input-box login-input">
        <input type="password" name="keywords" maxlength="40" class="text-input" autocomplete="current-password" autocorrect="off" autocapitalize="off" spellcheck="false" required="">
        <span class="input-placeholder">Password</span>
    </div>
    <button type="submit" name="login" class="page-control-btn red-btn">Sign In</button>
</form>
</code>```

CSS:

```<code>.login-input {
    padding: 0;
}
.login-input .text-input {
    width: 100%;
    letter-spacing: normal;
    padding-left: 20px;
    position: relative;
}
/*NB search input palceholder */
.input-placeholder {
    position: absolute;
    font-size: 16px;
    color: rgb(255, 255, 255, 0.7);
    left: 19px;
    top: 10px;
    letter-spacing: 0.1rem;
    text-transform: capitalize;
    pointer-events: none;
    transition: 0.2s ease all;
}
.login-input .text-input,
.login-input .input-placeholder {
    color: #595959 !important;
}
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:focus) ~ .input-placeholder {
    color: rgb(0, 0, 0, 0.8) !important;
}
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:focus):valid ~ .input-placeholder {
    top: 4px;
    bottom: 10px;
    left: 19px;
    font-size: 9px;
    opacity: 1;
    letter-spacing: normal;
}
</code>```

答:
Instead of .text-input:not(:focus):valid use .text-input:not(:placeholder-shown).

Use :placeholder-shown pseudo class to detect if the input contains text or has value without checking its validity. Though this requires a placeholder attribute on the inputs with a single space value.

.login-input {
    padding: 0;
}
.login-input .text-input {
    width: 100%;
    letter-spacing: normal;
    padding-left: 20px;
    position: relative;
}
/*NB search input palceholder */
.input-placeholder {
    position: absolute;
    font-size: 16px;
    color: rgb(255, 255, 255, 0.7);
    left: 19px;
    top: 10px;
    letter-spacing: 0.1rem;
    text-transform: capitalize;
    pointer-events: none;
    transition: 0.2s ease all;
}
.login-input .text-input,
.login-input .input-placeholder {
    color: #595959 !important;
}
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:focus) ~ .input-placeholder {
    color: rgb(0, 0, 0, 0.8) !important;
}

/*edited*/
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:placeholder-shown) ~ .input-placeholder {
    top: 4px;
    bottom: 10px;
    left: 19px;
    font-size: 9px;
    opacity: 1;
    letter-spacing: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="login" action="" method="post"><input type="hidden" name="formid" value="4f5e2c860e789bc1df1ea953c167d39e">
    <!-- Email -->
    <div class="input-box login-input">
        <!--inserted placeholder=" " -->
        <input type="email" name="email_address" class="text-input" autocomplete="email" autocorrect="off" autocapitalize="off" spellcheck="false" required="" placeholder=" ">
        <span class="input-placeholder">Email</span>
    </div>
    <!-- Password -->
    <div class="input-box login-input">
        <!--inserted placeholder=" " -->
        <input type="password" name="keywords" maxlength="40" class="text-input" autocomplete="current-password" autocorrect="off" autocapitalize="off" spellcheck="false" required="" placeholder=" ">
        <span class="input-placeholder">Password</span>
    </div>
    <button type="submit" name="login" class="page-control-btn red-btn">Sign In</button>
</form></code>```

Note: These particular custom placeholders will not go back into their original places if the value of the input fields contain only spaces / blank character. So look after that.

Body:
I am making a login page with email and password input boxes. I have added a placeholder using a span element. When the input box is clicked it will move the placeholder to the top of the input box and make the font-size a lot smaller. The placeholder stays in this position if the input box is still focused or if text is entered into the input.

This works perfectly for text inputs and the password input because it detects that the inputs are valid when they contain text, but it doesn't work for email input until you type in a email that is the correct format. So for example, if you just type 'test' into the email box it not see this as valid and the placeholder text will go back to its original position and overlap the text.

Can anyone help me with this please?

<form name="login" action="" method="post"><input type="hidden" name="formid" value="4f5e2c860e789bc1df1ea953c167d39e">

        <input type="email" name="email_address" class="text-input" autocomplete="email" autocorrect="off" autocapitalize="off" spellcheck="false" required="">
        Email

        <input type="password" name="keywords" maxlength="40" class="text-input" autocomplete="current-password" autocorrect="off" autocapitalize="off" spellcheck="false" required="">
        Password

    <button type="submit" name="login" class="page-control-btn red-btn">Sign In</button>
</form>

CSS:

.login-input {
    padding: 0;
}
.login-input .text-input {
    width: 100%;
    letter-spacing: normal;
    padding-left: 20px;
    position: relative;
}
/*NB search input palceholder */
.input-placeholder {
    position: absolute;
    font-size: 16px;
    color: rgb(255, 255, 255, 0.7);
    left: 19px;
    top: 10px;
    letter-spacing: 0.1rem;
    text-transform: capitalize;
    pointer-events: none;
    transition: 0.2s ease all;
}
.login-input .text-input,
.login-input .input-placeholder {
    color: #595959 !important;
}
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:focus) ~ .input-placeholder {
    color: rgb(0, 0, 0, 0.8) !important;
}
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:focus):valid ~ .input-placeholder {
    top: 4px;
    bottom: 10px;
    left: 19px;
    font-size: 9px;
    opacity: 1;
    letter-spacing: normal;
}

Body:
Instead of .text-input:not(:focus):valid use .text-input:not(:placeholder-shown).

Use :placeholder-shown pseudo class to detect if the input contains text or has value without checking its validity. Though this requires a placeholder attribute on the inputs with a single space value.

.login-input {
    padding: 0;
}
.login-input .text-input {
    width: 100%;
    letter-spacing: normal;
    padding-left: 20px;
    position: relative;
}
/*NB search input palceholder */
.input-placeholder {
    position: absolute;
    font-size: 16px;
    color: rgb(255, 255, 255, 0.7);
    left: 19px;
    top: 10px;
    letter-spacing: 0.1rem;
    text-transform: capitalize;
    pointer-events: none;
    transition: 0.2s ease all;
}
.login-input .text-input,
.login-input .input-placeholder {
    color: #595959 !important;
}
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:focus) ~ .input-placeholder {
    color: rgb(0, 0, 0, 0.8) !important;
}

/*edited*/
.login-input .text-input:focus ~ .input-placeholder,
.login-input .text-input:not(:placeholder-shown) ~ .input-placeholder {
    top: 4px;
    bottom: 10px;
    left: 19px;
    font-size: 9px;
    opacity: 1;
    letter-spacing: normal;
}

<form name="login" action="" method="post"><input type="hidden" name="formid" value="4f5e2c860e789bc1df1ea953c167d39e">
    <!-- Email -->
    <div class="input-box login-input">
        <!--inserted placeholder=" " -->
        <input type="email" name="email_address" class="text-input" autocomplete="email" autocorrect="off" autocapitalize="off" spellcheck="false" required="" placeholder=" ">
        <span class="input-placeholder">Email</span>
    </div>
    <!-- Password -->
    <div class="input-box login-input">
        <!--inserted placeholder=" " -->
        <input type="password" name="keywords" maxlength="40" class="text-input" autocomplete="current-password" autocorrect="off" autocapitalize="off" spellcheck="false" required="" placeholder=" ">
        <span class="input-placeholder">Password</span>
    </div>
    <button type="submit" name="login" class="page-control-btn red-btn">Sign In</button>
</form>

Note: These particular custom placeholders will not go back into their original places if the value of the input fields contain only spaces / blank character. So look after that.


问:
Is there a way to solve EPERM: operation not permitted, copyfile
I am facing this problem and I have tried a lot of solutions to fix it yet nothing seem to work: yarn cache clean and I deleted yarn and reinstalled it again then tried to reinstall nodejs and npm.

Yarn Error: When I run yarn install this error pops out:

error An unexpected error occurred: "EPERM: operation not permitted, copyfile 'C:\Users\MYCOM\AppData\Local\Yarn\Cache\v6\npm-request-2.88.2-d73c918731cb5a87da047e207234146f664d12b3-integrity\node_modules\request\lib\cookies.js' -> 'D:\v-location\v-location-server\node_modules\request\lib\cookies.js'".

Yet when I run npm install every thing works fine and all dependencies are installed can anyone help me fix it or at least till me the reason of this error?

This is what notepad++ gives me when I open any coockies.js file available in my pc

答:
Set the yarn cache directory to other disk, such as:</p>
```<code>yarn config set cache-folder 'D:/yarn-cache'
</code>```

Body:
Set the yarn cache directory to other disk, such as:

yarn config set cache-folder 'D:/yarn-cache'


问:
memset sets some elements to *almost* zero or nan
I have the line memset(C, 0, N*M);, where C is a matrix of doubles. (I am using WSL.)

However if I look in gdb, certain elements in the matrix are set to either -nan(0xffffffffffff8) and others are set to for example 9.0096750001652956e-314.

The first one doesn't give any errors but a += doesn't seem to change anything (or at the very least doesn't seem to make the nan thing disappear), while the second is an issue if the element is not changed or only has += 0, as the comparison if (0 == C[i][j]) then fails.

If I set the values to 0 manually, then these issues do not arise at all.

Is this a WSL thing, or is there something about memset that I do not understand?

答: The M*N is the number of items (doubles) but memset expects the number of bytes. For an array double C[M][N], you need to do memset(C, 0, sizeof(C));.


问:
Where are the best explanations of memory management for iPhone?
I am looking for good explanations out there. I have a 1000 pages book about objective-c, but unfortunately the part about memory management, retain counting, is described pretty bad and hard to understand.</p>

答: A quick explaination: Anything you alloc, new, retain or copy you must also release.  Also, anything you DON'T alloc or copy you should retain if you plan on holding on to it beyond the current message loop (or you risk it being autoreleased and becoming an invalid reference).

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Eric P


问:
Sharepoint Web performance optimization
We are running on SSL on following server topology:

 1 ISA (SSL Terminate/cache/proxy+AD authentication)

  1 Sharepoint

 1 IBM DB2 Database as enterprise/corporate DB

 1 MS SQL Server as local DB

We have recently optimized the caching, compression, minification, and other ASP.net best practices such as viewstate and cookie sizes, minimizing round trips, parallel connections/domain sharding and a lot more....

Now we are not convinced that the we are in an optimized position as the network resources i.e. bandwidth and especially latency are out of our control!!

The client/browser to server/sharepoint is trans-Atlantic i.e. (ASIA, USA, EUROPE).

As of my understanding the only ways to improve the network (latency) are: - TCP/SSL optimization - hardware/software? - CDNs - cloud or our own ?

答:
Well Hertzel there are many factors that can impact performance, you need to have cache for your database but standalone cache is not the solution for true benefits you have to have some distributed cache.

To the best of my knowledge StorageEdge is the best suitable solution for such issues as it can optimize storage to its best plus on it also has distributed cache which can improve the network (latency).

You can download its free copy from http://www.alachisoft.com/storageedge/index.html

Title: Sharepoint Web performance optimization


问:
How to directly open the new google sheet created from script?
I have been using the following code (after some edits and help from the community here) to create a duplicate sheet from a template sheet. However, the number of sheets have increased now. Is there a way to make some edits in this code such that the newly created sheet shows up directly so I can right away edit without horizontally scrolling through to find the new sheet that was created from the script? .

Edited question for giving better clarity on the issue.

```<code>function duplicateSheetWithProtections() {
      var ui = SpreadsheetApp.getUi();
      var oldSheetName = ui.prompt('Sheet to Copy?');
      var newSheetName = ui.prompt('New Sheet Name?');
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      sheet = ss.getSheetByName(oldSheetName.getResponseText());
      sheet2 = sheet.copyTo(ss).setName(newSheetName.getResponseText());
      var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
      for (var i = 0; i < protections.length; i++) {
        var p = protections[i];
        var rangeNotation = p.getRange().getA1Notation();
        var p2 = sheet2.getRange(rangeNotation).protect();
        p2.setDescription(p.getDescription());
        p2.setWarningOnly(p.isWarningOnly());
        if (!p.isWarningOnly()) {
          p2.removeEditors(p2.getEditors());
          p2.addEditors(p.getEditors());
          // p2.setDomainEdit(p.canDomainEdit()); //  only if using an Apps domain

            /* Make the new sheet active */
      ss.setActiveSheet(sheet);
       }
      }
    }
</code>```

答:
Try

```<code>sheet2.moveActiveSheet(0)
</code>```

this will be the simplest and most effective solution

Body:
I have been using the following code (after some edits and help from the community here) to create a duplicate sheet from a template sheet. However, the number of sheets have increased now. Is there a way to make some edits in this code such that the newly created sheet shows up directly so I can right away edit without horizontally scrolling through to find the new sheet that was created from the script? .

Edited question for giving better clarity on the issue.

function duplicateSheetWithProtections() {
      var ui = SpreadsheetApp.getUi();
      var oldSheetName = ui.prompt('Sheet to Copy?');
      var newSheetName = ui.prompt('New Sheet Name?');
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      sheet = ss.getSheetByName(oldSheetName.getResponseText());
      sheet2 = sheet.copyTo(ss).setName(newSheetName.getResponseText());
      var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
      for (var i = 0; i < protections.length; i++) {
        var p = protections[i];
        var rangeNotation = p.getRange().getA1Notation();
        var p2 = sheet2.getRange(rangeNotation).protect();
        p2.setDescription(p.getDescription());
        p2.setWarningOnly(p.isWarningOnly());
        if (!p.isWarningOnly()) {
          p2.removeEditors(p2.getEditors());
          p2.addEditors(p.getEditors());
          // p2.setDomainEdit(p.canDomainEdit()); //  only if using an Apps domain

            /* Make the new sheet active */
      ss.setActiveSheet(sheet);
       }
      }
    }

Body:
Try

sheet2.moveActiveSheet(0)

this will be the simplest and most effective solution


问:
In Visual Studio code version 1.64, MarkdownString with 4 leading spaces is displayed as blank in Hover
Our Visual Studio Code Extension uses the HoverProvider API to show custom hovers on the editor.  We are using MarkdownString for the hover content with 4 leading spaces for each line to enable syntax coloring. Till version 1.63, this was working fine. But on using vscode version 1.64, hover shows empty tooltips.

Turns out that the issue is resolved once the leading spaces are removed. But the syntax coloring does not show up if there are no leading spaces. Is there a change in the behavior of MarkdownString, or is there a different way to enable syntax coloring for the data type?

答:
I think the preferred way is to use this:

const markdownString = new vscode.MarkdownString();

const codeBlock = `const a = 12;
if (a) return;`;    // any preceding tabs will be rendered in a template literal, so flush left

// const codeBlock2 = `const c = 12;\nif (c) return;`;  // works, alternate form with newline

markdownString.appendCodeblock(codeBlock, "javascript");

markdownString.isTrusted = true;

return new vscode.Hover(markdownString, new vscode.Range(position, position));
```
<hr />
<p>Also the <code>``` and  tags are supported in markdownString's:

content.appendMarkdown(`<p><b> Some label: <code>${value}</code></b></p>`);
```

Body:
I think the preferred way is to use this:

const markdownString = new vscode.MarkdownString();

const codeBlock = `const a = 12;
if (a) return;`;    // any preceding tabs will be rendered in a template literal, so flush left

// const codeBlock2 = `const c = 12;\nif (c) return;`;  // works, alternate form with newline

markdownString.appendCodeblock(codeBlock, "javascript");

markdownString.isTrusted = true;

return new vscode.Hover(markdownString, new vscode.Range(position, position));

Also the <pre> and <code> tags are supported in markdownString's:

content.appendMarkdown(`<p><b> Some label: <code>${value}</code></b></p>`);


问:
How to make an app.route() in Flask only functional if you are coming from a specific URL?
I'm creating a project to learn how to use Stripe and work together with a registration template. My integration with Stripe is working, I can successfully make a payment and after the payment is done, I'm redirected to my registration template.

The problem is, you should only get access to the registration template after going through the Stripe integration, but what is happening is anyone who access the '/register' URL manually can by pass the payment stage and register himself in the registration template.

The route I'm using in the process is:

```<code>@app.route('/stripe_pay')
def stripe_pay():
    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'price': '{{ PRICE ID }}',
            'quantity': 1,
        }],
        mode='subscription',
        success_url=url_for('register', _external=True),
        cancel_url=url_for('signup', _external=True),
    )
    return {
        'checkout_session_id': session['id'],
        'checkout_public_key': app.config['STRIPE_PUBLIC_KEY'],
    }
</code>```

The '/register' route performs user data collection and then writes down all the information in a database. All is working fine with the process.

```<code>@app.route('/register')
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        todb = c_personal_info( first_name = form.first_name.data,
                            last_name = form.last_name.data,
                            email = form.email.data,
                            password = form.password.data,
                            subscription='M')
        with db.session.begin():
            db.session.add(todb)
        flash('Thanks for registering! You can now login!', category="success")
        return redirect(url_for('login'))
    return render_template('register.html', form = form)
</code>```

The session is not authenticated, as the '/register' template is actually where you would create your credentials to log in.

My question is how do I make the '/register' end point only accessible when you are coming from the '/stripe_pay' end point? I also would love to hear your ideas and different aproaches to this.

答:
I solved my issue by using the "@login_required" decorator, in conjunction with the "current_user" module from "Flask-Login".

1 - As a last step, before routing to the route I want to protect, I logged in with an "admin" user. I created that user for that and for other priviledged accesses.

2 - I decorated the target route with "@login_required", so I blocked non logged users, then I used "current_user" with a condition to allow only the "admin" user to proceed. Any other logged in user is redirected to a different URL.

Body:
I'm creating a project to learn how to use Stripe and work together with a registration template. My integration with Stripe is working, I can successfully make a payment and after the payment is done, I'm redirected to my registration template.

The problem is, you should only get access to the registration template after going through the Stripe integration, but what is happening is anyone who access the '/register' URL manually can by pass the payment stage and register himself in the registration template.

The route I'm using in the process is:

@app.route('/stripe_pay')
def stripe_pay():
    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'price': '{{ PRICE ID }}',
            'quantity': 1,
        }],
        mode='subscription',
        success_url=url_for('register', _external=True),
        cancel_url=url_for('signup', _external=True),
    )
    return {
        'checkout_session_id': session['id'],
        'checkout_public_key': app.config['STRIPE_PUBLIC_KEY'],
    }

The '/register' route performs user data collection and then writes down all the information in a database. All is working fine with the process.

@app.route('/register')
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        todb = c_personal_info( first_name = form.first_name.data,
                            last_name = form.last_name.data,
                            email = form.email.data,
                            password = form.password.data,
                            subscription='M')
        with db.session.begin():
            db.session.add(todb)
        flash('Thanks for registering! You can now login!', category="success")
        return redirect(url_for('login'))
    return render_template('register.html', form = form)

The session is not authenticated, as the '/register' template is actually where you would create your credentials to log in.

My question is how do I make the '/register' end point only accessible when you are coming from the '/stripe_pay' end point? I also would love to hear your ideas and different aproaches to this.


问:
How to center scrollable content with header?
I'm trying to center some content. The content is larger than the parent and therefore requires scrolling. There is also a header at top. For some reason, the scroll height clips the scrollable content. Thoughts on how I should fix the issue?

Here's the fiddle: https://jsfiddle.net/xgsqyu45/

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

答:
Simplest solution - replace the margin of your .content element to this:

```<code>.content {
  margin:auto 12px;
}
</code>```

Updated jsfiddle:
https://jsfiddle.net/odjnL09g/

Explanation: Essentially what is required is that margin-top:auto and margin-bottom: auto are set - this is explicit to children of flexbox elements. This keeps the element vertically centered when it's smaller than the parent container, but when it's larger it scrolls properly. If you need the 12px vertical spacing, you should place a child element inside .content and transfer any styling to that and add a padding property to the .content.

Edit: Updating the answer to reflect what the OP wanted, centering, both vertically and horizontally.

It required that the .content has margin:auto applied and remove the justify-content:center from the parent flexbox container to avoid a nasty clipping bug.

```<code>.scroll {
  // justify-content:center; // This is commented out to avoid clipping bug
}

.content {
  margin:auto;
}
</code>```

Here is the fiddle to the final working code:
https://jsfiddle.net/c9foy54q/

Body:
Simplest solution - replace the margin of your .content element to this:

.content {
  margin:auto 12px;
}

Updated jsfiddle:
https://jsfiddle.net/odjnL09g/

Explanation: Essentially what is required is that margin-top:auto and margin-bottom: auto are set - this is explicit to children of flexbox elements. This keeps the element vertically centered when it's smaller than the parent container, but when it's larger it scrolls properly. If you need the 12px vertical spacing, you should place a child element inside .content and transfer any styling to that and add a padding property to the .content.

Edit: Updating the answer to reflect what the OP wanted, centering, both vertically and horizontally.

It required that the .content has margin:auto applied and remove the justify-content:center from the parent flexbox container to avoid a nasty clipping bug.

.scroll {
  // justify-content:center; // This is commented out to avoid clipping bug
}

.content {
  margin:auto;
}

Here is the fiddle to the final working code:
https://jsfiddle.net/c9foy54q/


问:
After comparing two columns, how can I remove unique values in one column with its values in other different columns in R
I have 3 columns in an excel file.
Note: my DCL anc CL columns are not the same lenght. I have extra values in CL and also my values in CL have numeric values in ic50. Exactly I remove both those extra values which are in CL and ic50.  (DCL, CL and ic50 are my columns' names)

```<code>DCL         CL          ic50
COLO-684    COLO-684    1,853021
COLO-792    COLO-792    1,673109
COLO-824    COLO-824    24,194019
COLO-829    COLO-829    125,288504
COR-L105    COR-L105    1,324301
COR-L23     COR-L23     13,645992
CPC-N       COR-L311    3,807295
CTV-1       CP66-MEL    7,974192
CW-2        CPC-N       4,701374
D-263MG     CTV-1       0,252652
D-283MED    CW-2        6,857369
            D-263MG     17,863089
            D-283MED    0,279165
</code>```

I want to remove unique values in colum CL with its values of column ic50. Finally, I want to have the values in both in DCL and CL with the numeric values of CL in ic50. So, I will have the same length in all columns.

Expected file:

```<code>DCL         CL          ic50
COLO-684    COLO-684    1,853021
COLO-792    COLO-792    1,673109
COLO-824    COLO-824    24,194019
COLO-829    COLO-829    125,288504
COR-L105    COR-L105    1,324301
COR-L23     COR-L23     13,645992
CPC-N       CPC-N       4,701374
CTV-1       CTV-1       0,252652
CW-2        CW-2        6,857369
D-263MG     D-263MG     17,863089
D-283MED    D-283MED    0,279165
</code>```

Body:
I have 3 columns in an excel file.
Note: my DCL anc CL columns are not the same lenght. I have extra values in CL and also my values in CL have numeric values in ic50. Exactly I remove both those extra values which are in CL and ic50.  (DCL, CL and ic50 are my columns' names)

DCL         CL          ic50
COLO-684    COLO-684    1,853021
COLO-792    COLO-792    1,673109
COLO-824    COLO-824    24,194019
COLO-829    COLO-829    125,288504
COR-L105    COR-L105    1,324301
COR-L23     COR-L23     13,645992
CPC-N       COR-L311    3,807295
CTV-1       CP66-MEL    7,974192
CW-2        CPC-N       4,701374
D-263MG     CTV-1       0,252652
D-283MED    CW-2        6,857369
            D-263MG     17,863089
            D-283MED    0,279165

I want to remove unique values in colum CL with its values of column ic50. Finally, I want to have the values in both in DCL and CL with the numeric values of CL in ic50. So, I will have the same length in all columns.

Expected file:

DCL         CL          ic50
COLO-684    COLO-684    1,853021
COLO-792    COLO-792    1,673109
COLO-824    COLO-824    24,194019
COLO-829    COLO-829    125,288504
COR-L105    COR-L105    1,324301
COR-L23     COR-L23     13,645992
CPC-N       CPC-N       4,701374
CTV-1       CTV-1       0,252652
CW-2        CW-2        6,857369
D-263MG     D-263MG     17,863089
D-283MED    D-283MED    0,279165

Body:
How about this:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
dat <- tibble::tribble(~DCL,         ~CL,          ~ic50,
"COLO-684",   "COLO-684",   1.853021,
"COLO-792",    "COLO-792",     1.673109,
"COLO-824",   "COLO-824",   24.194019,
"COLO-829",    "COLO-829",     125.288504,
"COR-L105",   "COR-L105",   1.324301,
"COR-L23",     "COR-L23",      13.645992,
"CPC-N",     "COR-L311",   3.807295,
"CTV-1",       "CP66-MEL",     7.974192,
"CW-2",       "CPC-N",      4.701374,
"D-263MG",     "CTV-1",        0.252652,
"D-283MED",   "CW-2",       6.857369,
NA_character_,"D-263MG",     17.863089,
NA_character_,"D-283MED",    0.279165)

left_join(dat %>% select(DCL), dat %>% select(-DCL) %>% mutate(DCL = CL)) %>% na.omit()
#> Joining, by = "DCL"
#> # A tibble: 11 × 3
#>    DCL      CL          ic50
#>    <chr>    <chr>      <dbl>
#>  1 COLO-684 COLO-684   1.85
#>  2 COLO-792 COLO-792   1.67
#>  3 COLO-824 COLO-824  24.2
#>  4 COLO-829 COLO-829 125.
#>  5 COR-L105 COR-L105   1.32
#>  6 COR-L23  COR-L23   13.6
#>  7 CPC-N    CPC-N      4.70
#>  8 CTV-1    CTV-1      0.253
#>  9 CW-2     CW-2       6.86
#> 10 D-263MG  D-263MG   17.9
#> 11 D-283MED D-283MED   0.279

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
C# WIN UI 3: I have combobox with custom-typed observable collection as itemssource. Need help getting selected item
very new to C# WPF/WIN UI. My combobox displays my collection perfectly. But now when I want to do something with what the user selected I can't find the correct syntax in my 'SelectionChanged' event handler. I want to get the 'Market_ID' somehow.  (FYI, I am not using MVVM yet as I don't understand how to implement, but I will learn. (really liking c#))

```<code>    <ComboBox x:Name="cmbMarketID" PlaceholderText="Select Market ID" Width="500" Margin="5,5,0,0" RelativePanel.RightOf="border1" RelativePanel.Below="cmbState" ItemsSource="{x:Bind marketIdent}" SelectionChanged="cmbMarketID_SelectionChanged" SelectedItem="{Binding Market_ID}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="cmbo_market_ID" Text="{Binding Market_ID}" Width="15" TextAlignment="Right"/>
                    <TextBlock Text="{Binding Product}" Width="145" Margin="10,0,10,0" FontWeight="SemiBold"/>
                    <TextBlock Text="{Binding Company}" Width="70" Margin="10,0,10,0"/>
                    <TextBlock Text="{Binding System}" Margin="10,0,10,0"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</code>```

Here is the event handler: (I used a simple string first, and that worked, but now I need to use a typed-collection)

```<code>    private void cmbMarketID_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (cmbMarketID.SelectedIndex == -1)
        {
            // Do not execute event
        }
        else
        {
            //string mktid = cmbMarketID.SelectedItem.ToString().Substring(0, 2).TrimEnd();
            //string mktid = cmbMarketID.SelectedItem;
            int mktid = (int)cmbMarketID.SelectedItem(); <-------what should the correct syntax be here?
            //v_metric_mktid = mktid;
        }
    }
</code>```

答:
Cast the SelectedItem property to your type.

For example, if marketIdent is an IEnumerable<YourClass>:

```<code>var item = cmbMarketID.SelectedItem as YourClass;
</code>```

Or if marketIdent is an IEnumerable<int>:

```<code>if (mbMarketID.SelectedItem != null)
{
     var mktid = (int)mbMarketID.SelectedItem;
}
</code>```

Body:
very new to C# WPF/WIN UI. My combobox displays my collection perfectly. But now when I want to do something with what the user selected I can't find the correct syntax in my 'SelectionChanged' event handler. I want to get the 'Market_ID' somehow.  (FYI, I am not using MVVM yet as I don't understand how to implement, but I will learn. (really liking c#))

    <ComboBox x:Name="cmbMarketID" PlaceholderText="Select Market ID" Width="500" Margin="5,5,0,0" RelativePanel.RightOf="border1" RelativePanel.Below="cmbState" ItemsSource="{x:Bind marketIdent}" SelectionChanged="cmbMarketID_SelectionChanged" SelectedItem="{Binding Market_ID}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="cmbo_market_ID" Text="{Binding Market_ID}" Width="15" TextAlignment="Right"/>
                    <TextBlock Text="{Binding Product}" Width="145" Margin="10,0,10,0" FontWeight="SemiBold"/>
                    <TextBlock Text="{Binding Company}" Width="70" Margin="10,0,10,0"/>
                    <TextBlock Text="{Binding System}" Margin="10,0,10,0"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

Here is the event handler: (I used a simple string first, and that worked, but now I need to use a typed-collection)

    private void cmbMarketID_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (cmbMarketID.SelectedIndex == -1)
        {
            // Do not execute event
        }
        else
        {
            //string mktid = cmbMarketID.SelectedItem.ToString().Substring(0, 2).TrimEnd();
            //string mktid = cmbMarketID.SelectedItem;
            int mktid = (int)cmbMarketID.SelectedItem(); <-------what should the correct syntax be here?
            //v_metric_mktid = mktid;
        }
    }

Body:
Cast the SelectedItem property to your type.

For example, if marketIdent is an IEnumerable<YourClass>:

var item = cmbMarketID.SelectedItem as YourClass;

Or if marketIdent is an IEnumerable<int>:

if (mbMarketID.SelectedItem != null)
{
     var mktid = (int)mbMarketID.SelectedItem;
}


问:
Chrome renders page twice while Safari works as expected
Ruby on Rails 6.0 (RC1) renders with Bootstrap 4.3.1 correctly on Safari but seems to render the page on Chrome twice (so it appears), first without using the Bootstrap CSS information, then applies the Bootstrap formatting. For a fraction of a second I can see the page in it's "raw" format before it gets reformatted.

Chrome on Windows: same result, renders twice / flickers
Edge: works correctly
Firefox on Windows: misbehaves like Chrome does

With working correctly I mean it does not flicker when rendering the page.

Here is what I did.

Create a new RoR application

```<code>  rails new test600
</code>```

Create a controller

```<code>  cd test600
  rails g controller main index
</code>```

Install Bootstrap, JQuery and Popper

```<code>  yarn add bootstrap@4.3.1 jquery popper.js
</code>```

Edit config/webpack/environment.js so it reads:

```<code>const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)

module.exports = environment
</code>```

Edit app/javascript/packs/application.js and add

```<code>require('jquery')
require('bootstrap/dist/js/bootstrap.js')
require('bootstrap/dist/css/bootstrap.css')
</code>```

Edit app/views/layouts/application.html to

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Test600WithBootstrap</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
    <div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
      <h5 class="my-0 mr-md-auto font-weight-normal">Company name</h5>
      <nav class="my-2 my-md-0 mr-md-3">
        <a class="p-2 text-dark" href="#">Features</a>
        <a class="p-2 text-dark" href="#">Pricing</a>
      </nav>
      <a class="btn btn-outline-primary" href="#">Sign up</a>
    </div>
    <%= yield %>
  </body>
</html>
</code>```

Start the application, either rails s or puma, both give the same result.

答:
What didn't work:

Doing it this way had the flash of unstyled content.

// app/javascript/styles/application.js
import("bootstrap/dist/css/bootstrap");
```
<h3>What <strong>did</strong> work:</h3>
<pre class="lang-js prettyprint-override"><code>// app/javascript/styles/application.js
import 'styles/site'
</code>```
```<code>// app/javascript/styles/site.scss
@import "bootstrap/dist/css/bootstrap";
</code>```

in config/webpacker.yml

```<code> extract_css: true
</code>```

Reference

This took a little trial and error.

@DiegoStiehl's answer was helpful

This answer to a related problem says to create at least one css file and import it, so I tried that (the bootstrap file, but presumably you could use any)

This article showed me how to do that

Body:
Ruby on Rails 6.0 (RC1) renders with Bootstrap 4.3.1 correctly on Safari but seems to render the page on Chrome twice (so it appears), first without using the Bootstrap CSS information, then applies the Bootstrap formatting. For a fraction of a second I can see the page in it's "raw" format before it gets reformatted.

Chrome on Windows: same result, renders twice / flickers
Edge: works correctly
Firefox on Windows: misbehaves like Chrome does

With working correctly I mean it does not flicker when rendering the page.

Here is what I did.

Create a new RoR application

  rails new test600

Create a controller

  cd test600
  rails g controller main index

Install Bootstrap, JQuery and Popper

  yarn add bootstrap@4.3.1 jquery popper.js

Edit config/webpack/environment.js so it reads:

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)

module.exports = environment

Edit app/javascript/packs/application.js and add

require('jquery')
require('bootstrap/dist/js/bootstrap.js')
require('bootstrap/dist/css/bootstrap.css')

Edit app/views/layouts/application.html to

<!DOCTYPE html>

    <title>Test600WithBootstrap</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

Company name

        Features
        Pricing

      Sign up

    <%= yield %>

Start the application, either rails s or puma, both give the same result.

Body:
What didn't work:

Doing it this way had the flash of unstyled content.

// app/javascript/styles/application.js
import("bootstrap/dist/css/bootstrap");

What did work:

// app/javascript/styles/application.js
import 'styles/site'

// app/javascript/styles/site.scss
@import "bootstrap/dist/css/bootstrap";

in config/webpacker.yml

 extract_css: true

Reference

This took a little trial and error.

@DiegoStiehl's answer was helpful

This answer to a related problem says to create at least one css file and import it, so I tried that (the bootstrap file, but presumably you could use any)

This article showed me how to do that


问:
How do I make a mailto that goes to link with email inside of it
I want to make a mailto, but the mailto has to href to "mailto:{item.email}" but ofcourse that is not possible, how can I do this?</p>
```<code>{data?.entry.people.map(item => (
            <div key={item.id}>
              <BigText>
                {item.firstName} {item.lastName}
              </BigText>
              <Paragraph>{item.job}</Paragraph>
              <Paragraph>{item.phone}</Paragraph>
              <Paragraph>
                <Link href="mailto:{item.email}">{item.email}</Link>
              </Paragraph>
              <Link href={item.linkedin} target="_blank" rel="nofollow">
                Linkedin
              </Link>
            </div>
          ))}
</code>```

答:
You can do it with template literals es6</p>
```<code><Link href={`mailto:${item.email}`}>{item.email}</Link>
</code>```

Body:
I want to make a mailto, but the mailto has to href to "mailto:{item.email}" but ofcourse that is not possible, how can I do this?

{data?.entry.people.map(item => (

              <BigText>
                {item.firstName} {item.lastName}
              </BigText>
              <Paragraph>{item.job}</Paragraph>
              <Paragraph>{item.phone}</Paragraph>
              <Paragraph>
                <Link href="mailto:{item.email}">{item.email}</Link>
              </Paragraph>
              <Link href={item.linkedin} target="_blank" rel="nofollow">
                Linkedin
              </Link>

          ))}

Body:
You can do it with template literals es6

<Link href={`mailto:${item.email}`}>{item.email}</Link>


问:
School timetabling with Optapy - allow to choose teacher from a list for a lesson
I am trying to use Optapy with the school timetabling example as a base.
For any given of subject I have a list of teachers that potentially can teach this subject and each teacher can potentially teach 1 to 3 subjects. I want to optimize the teacher allocation to the lessons, such that, each student group can only have one teacher for any given subject and each student group supposed to get few lessons for any subject (i.e. 4 times math lesson for the student group A given by teacher B)

For that I tried to the add this problem fact:

```<code>@problem_fact
class Teacher:
    def __init__(self, id, name, subject, subject2, subject3):
        self.id = id
        self.name = name
        self.subject = subject
        self.subject2 = subject2
        self.subject3 = subject3

    @planning_id
    def get_id(self):
        return self.id

    def __str__(self):
        return (
                f"Teacher("
                f"id={self.id}, "
                f"name={self.name}, "
                f"subject={self.subject}, "
                f"subject2={self.subject2}, "
                f"subject3={self.subject3})"
        )
</code>```

and I added planning variable to the planning entity:

```<code>@planning_variable(Teacher, ["teacherRange"])
def get_teacher(self):
    return self.teacher

def set_teacher(self, new_teacher):
    self.teacher = new_teacher
</code>```

But I don’t know how to continue make the algorithm to chose a teacher from a list and  how to add the constraints of one teacher for one student group for any subject. Any help?

答:
In order to make the algorithm to chose a teacher from a list, the list must be returned from a method on the @planning_solution class annotated with the appropriate @value_range_provider:

```<code>@planning_solution
class TimeTable:
    def __init__(self, teacher_list, ..., score=None):
        self.teacher_list = teacher_list
        # ...
        self.score = score

    @problem_fact_collection_property(Teacher)
    @value_range_provider("teacherRange")
    def get_teacher_list(self):
        return self.teacher_list
    # rest of the class
</code>```

For the constraint "one teacher for one student group for any subject.", I would rephrase it "consistent teacher for subject on student group" (i.e. if a lesson has the same student group and subject, it must also have the same teacher). Which would be written like this:

```<code>def consistent_teacher_for_subject_and_student_group(constraint_factory: ConstraintFactory):
    return constraint_factory \
        .forEach(LessonClass) \
        .join(LessonClass,
              [
                  # ... the same student group ...
                  Joiners.equal(lambda lesson: lesson.student_group),
                  # ... the same subject ...
                  Joiners.equal(lambda lesson: lesson.subject),
                  # form unique pairs
                  Joiners.lessThan(lambda lesson: lesson.id)
              ]) \
        .filter(lambda lesson1, lesson2: lesson1.teacher != lesson2.teacher) \
        .penalize("Different teacher for the same student group and subject", HardSoftScore.ONE_HARD)
</code>```

For the constraint "teacher must be able to teach subject", you can use a filter:

```<code>def teacher_must_be_able_to_teach_subject(constraint_factory: ConstraintFactory):
    return constraint_factory \
        .forEach(LessonClass) \
        .filter(lambda lesson: lesson.subject not in {lesson.teacher.subject, lesson.teacher.subject2, lesson.teacher.subject3}) \
        .penalize("Teacher cannot teach subject", HardSoftScore.ONE_HARD)
</code>```

Body:
I am trying to use Optapy with the school timetabling example as a base.
For any given of subject I have a list of teachers that potentially can teach this subject and each teacher can potentially teach 1 to 3 subjects. I want to optimize the teacher allocation to the lessons, such that, each student group can only have one teacher for any given subject and each student group supposed to get few lessons for any subject (i.e. 4 times math lesson for the student group A given by teacher B)

For that I tried to the add this problem fact:

@problem_fact
class Teacher:
    def __init__(self, id, name, subject, subject2, subject3):
        self.id = id
        self.name = name
        self.subject = subject
        self.subject2 = subject2
        self.subject3 = subject3

    @planning_id
    def get_id(self):
        return self.id

    def __str__(self):
        return (
                f"Teacher("
                f"id={self.id}, "
                f"name={self.name}, "
                f"subject={self.subject}, "
                f"subject2={self.subject2}, "
                f"subject3={self.subject3})"
        )

and I added planning variable to the planning entity:

@planning_variable(Teacher, ["teacherRange"])
def get_teacher(self):
    return self.teacher

def set_teacher(self, new_teacher):
    self.teacher = new_teacher

But I don’t know how to continue make the algorithm to chose a teacher from a list and  how to add the constraints of one teacher for one student group for any subject. Any help?

Body:
In order to make the algorithm to chose a teacher from a list, the list must be returned from a method on the @planning_solution class annotated with the appropriate @value_range_provider:

@planning_solution
class TimeTable:
    def __init__(self, teacher_list, ..., score=None):
        self.teacher_list = teacher_list
        # ...
        self.score = score

    @problem_fact_collection_property(Teacher)
    @value_range_provider("teacherRange")
    def get_teacher_list(self):
        return self.teacher_list
    # rest of the class

For the constraint "one teacher for one student group for any subject.", I would rephrase it "consistent teacher for subject on student group" (i.e. if a lesson has the same student group and subject, it must also have the same teacher). Which would be written like this:

def consistent_teacher_for_subject_and_student_group(constraint_factory: ConstraintFactory):
    return constraint_factory \
        .forEach(LessonClass) \
        .join(LessonClass,
              [
                  # ... the same student group ...
                  Joiners.equal(lambda lesson: lesson.student_group),
                  # ... the same subject ...
                  Joiners.equal(lambda lesson: lesson.subject),
                  # form unique pairs
                  Joiners.lessThan(lambda lesson: lesson.id)
              ]) \
        .filter(lambda lesson1, lesson2: lesson1.teacher != lesson2.teacher) \
        .penalize("Different teacher for the same student group and subject", HardSoftScore.ONE_HARD)

For the constraint "teacher must be able to teach subject", you can use a filter:

def teacher_must_be_able_to_teach_subject(constraint_factory: ConstraintFactory):
    return constraint_factory \
        .forEach(LessonClass) \
        .filter(lambda lesson: lesson.subject not in {lesson.teacher.subject, lesson.teacher.subject2, lesson.teacher.subject3}) \
        .penalize("Teacher cannot teach subject", HardSoftScore.ONE_HARD)


答:
Try this :</p>
```<code><Link href={`mailto:${item.email}`>{item.email}</Link>
</code>```

Title: How do I make a mailto that goes to link with email inside of it

Body:
Try this :

<Link href={`mailto:${item.email}`>{item.email}</Link>


问:
Github Desktop not fit in the screen windows
I just installed GitHub desktop on my Windows 10 64bit. The software functions OK but the window of it won't fit in the window. Once I click on maximize button, the right side of the window just go out of the screen. Here is a screen shot, how can I fix it?

Thanks a lot for your help!

Jason

答:
I have the same problem and i solved it by click to the Alt button

now you can see the topBar and you can resize it

and you can use Alt + Space


问:
how to resolve socket timeout while creating react app
PS C:\Users\HP\Desktop> npx create-react-app enda_react

Creating a new React app in C:\Users\HP\Desktop\enda_react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! request to https://registry.npmjs.org/bfj failed, reason: Socket timeout

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HP\AppData\Local\npm-cache_logs\2021-03-10T03_17_13_731Z-debug.log

Aborting installation.
npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... package.json
Deleting enda_react/ from C:\Users\HP\Desktop
Done.

i tried different methods such as

- increase timeout,
-upadate npm versions,
-unistalled previeous create app and installed new one,
-cleared cache,

all these methods doesnt worked for me,someone please help

答:
I had the same problem, then I decided to install react js with this command:</p>
```<code> npm init react-app app-name
</code>```

Body:
I had the same problem, then I decided to install react js with this command:

 npm init react-app app-name


问:
Find max time difference between consecutive user transactions
I have a user transactions table that look like the following:

```<code>USER_ID    TRANSACTION_ID     TIMESTAMP
user1      id1                2022-01-19 15:21:27.000
user1      id2                2022-01-20 15:21:27.000
user1      id3                2022-01-25 15:21:27.000
user2      id1                2022-01-18 15:21:27.000
user2      id2                2022-01-28 15:21:27.000
user2      id3                2022-01-29 15:21:27.000
</code>```

I'd like to write a query that could find the max time difference between each user's transaction times (days is preferred but anything else would do it as well). For the above the desired output would be:

```<code>USER_ID     MAX_DIFF
user1       5 (time diff between id2 and id3)
user2       10 (time diff between id1 and id2)
</code>```

I have thought about ordering rows based on TIMESTAMP then use an approach similar to one posted here:

```<code>SELECT
    t1.ts,
    t1.number,
    t1.number - COALESCE(t2.number, t1.number) AS diff
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t1.id = t2.id + 1
ORDER BY
    t1.ts;
</code>```

Problem is that transaction ids in my table are random uuids and can not be used in such a fashion. Any help is much appreciated.

答:
The query can use LAG() to peek at the previous row (according to any ordering) and compute the time difference. Then it can use MAX to find the maximum difference between rows:

For example:

```<code>  SELECT user_id, MAX(diff) AS max_diff
  FROM (
    SELECT *,
      TIMESTAMPDIFF(second, LAG(ts)
        OVER(PARTITION BY user_id ORDER BY ts), ts) AS diff,
      LAG(transaction_id) OVER(PARTITION BY user_id ORDER BY ts) AS prev_tx_id
    FROM t
  )
  GROUP BY user_id
  HAVING max_diff IS NOT NULL
</code>```

Body:
I have a user transactions table that look like the following:

USER_ID    TRANSACTION_ID     TIMESTAMP
user1      id1                2022-01-19 15:21:27.000
user1      id2                2022-01-20 15:21:27.000
user1      id3                2022-01-25 15:21:27.000
user2      id1                2022-01-18 15:21:27.000
user2      id2                2022-01-28 15:21:27.000
user2      id3                2022-01-29 15:21:27.000

I'd like to write a query that could find the max time difference between each user's transaction times (days is preferred but anything else would do it as well). For the above the desired output would be:

USER_ID     MAX_DIFF
user1       5 (time diff between id2 and id3)
user2       10 (time diff between id1 and id2)

I have thought about ordering rows based on TIMESTAMP then use an approach similar to one posted here:

SELECT
    t1.ts,
    t1.number,
    t1.number - COALESCE(t2.number, t1.number) AS diff
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t1.id = t2.id + 1
ORDER BY
    t1.ts;

Problem is that transaction ids in my table are random uuids and can not be used in such a fashion. Any help is much appreciated.

Body:
The query can use LAG() to peek at the previous row (according to any ordering) and compute the time difference. Then it can use MAX to find the maximum difference between rows:

For example:

  SELECT user_id, MAX(diff) AS max_diff
  FROM (
    SELECT *,
      TIMESTAMPDIFF(second, LAG(ts)
        OVER(PARTITION BY user_id ORDER BY ts), ts) AS diff,
      LAG(transaction_id) OVER(PARTITION BY user_id ORDER BY ts) AS prev_tx_id
    FROM t
  )
  GROUP BY user_id
  HAVING max_diff IS NOT NULL


问:
GPIO IRQ on ARM based Embedded Linux
I'm trying to program an GPIO IRQ on AT91SAM9M10-EKES evaluation board.
I successfully registered the IRQ, and the IRQ is working.
However, some interrupts are missed. I'm sending 26, and I get only 22.

The code:

```<code>static irqreturn_t wiegand_interrupt(int irq, void *dev_id){
  atomic_inc(&counter);
  printk(KERN_WARNING "IRQ recieved, counting... %d\n",atomic_read(&counter));
  return 0;
}
irq1 = gpio_to_irq(AT91_PIN_PA21);
if (irq1 < 0) {
    err = irq1;
    printk("Unable to get irq number for GPIO %d, error %d\n",AT91_PIN_PA21, err);
    goto fail;
}

err = request_irq(irq1,wiegand_interrupt,0 ,"wiegand",NULL);

irq2 = gpio_to_irq(AT91_PIN_PA20);
if (irq2 < 0) {
    err = irq2;
    printk("Unable to get irq number for GPIO %d, error %d\n",AT91_PIN_PA21, err);
    goto fail;
}

err = request_irq(irq2,wiegand_interrupt,0 ,"wiegand",NULL);
</code>```

This is not the whole driver, but this is the actual part that deals with the IRQ.
If someone see a problem in the code, or can suggest a way to know why I lose 4 interrupts, please reply. I'm stuck on this for hours... :(

Thanks.
Ramon.

答:
I assume you are triggering your interrupts with an external system (maybe a microcontroller or something that can toggle the GPIOS). Since I do not see a real ack of the interrupt, I assume the external system does not wait for the interrupt to be handled to maybe trigger a new one.

printk is a very slow function and that's why you can miss some interrupts: a new one can be triggered while you are still handling the previous one.

So I would advise not to use printk in the handler. If you want to achieve something like this, it would be better to use a tasklet or a workqueue as the bottom half of the interrupt handler.

I can only recommend the reading of the Chapter 10 of Linux Device Drivers.

Oh and by the way, your IRQ handler should not return 0 but IRQ_HANDLED.

Title: GPIO IRQ on ARM based Embedded Linux

Body:
I'm trying to program an GPIO IRQ on AT91SAM9M10-EKES evaluation board.
I successfully registered the IRQ, and the IRQ is working.
However, some interrupts are missed. I'm sending 26, and I get only 22.

The code:

static irqreturn_t wiegand_interrupt(int irq, void *dev_id){
  atomic_inc(&counter);
  printk(KERN_WARNING "IRQ recieved, counting... %d\n",atomic_read(&counter));
  return 0;
}
irq1 = gpio_to_irq(AT91_PIN_PA21);
if (irq1 < 0) {
    err = irq1;
    printk("Unable to get irq number for GPIO %d, error %d\n",AT91_PIN_PA21, err);
    goto fail;
}

err = request_irq(irq1,wiegand_interrupt,0 ,"wiegand",NULL);

irq2 = gpio_to_irq(AT91_PIN_PA20);
if (irq2 < 0) {
    err = irq2;
    printk("Unable to get irq number for GPIO %d, error %d\n",AT91_PIN_PA21, err);
    goto fail;
}

err = request_irq(irq2,wiegand_interrupt,0 ,"wiegand",NULL);

This is not the whole driver, but this is the actual part that deals with the IRQ.
If someone see a problem in the code, or can suggest a way to know why I lose 4 interrupts, please reply. I'm stuck on this for hours... :(

Thanks.
Ramon.


问:
kong cache invalidation throws error : key must be a string
In a custom plugin I need to invalidate a Kong cache entry.
When I use

```<code>kong.cache.invalidate_local("thisisastring")
</code>```

I get error

key must be a string
 stack traceback:
    [C]: in function 'error'
    /usr/local/share/lua/5.1/kong/cache/init.lua:226: in function 'invalidate_local'
```

I'm using Kong 2.7.0.

https://github.com/Kong/kong/blob/2.7.0/kong/cache/init.lua#L226

What is wrong?

答:
You should use : not .

```<code>      kong.cache:invalidate_local("your string")
</code>```

More info about difference between : and .

Body:
In a custom plugin I need to invalidate a Kong cache entry.
When I use

kong.cache.invalidate_local("thisisastring")

I get error

key must be a string
 stack traceback:
    [C]: in function 'error'
    /usr/local/share/lua/5.1/kong/cache/init.lua:226: in function 'invalidate_local'

I'm using Kong 2.7.0.

https://github.com/Kong/kong/blob/2.7.0/kong/cache/init.lua#L226

What is wrong?

Body:
You should use : not .

      kong.cache:invalidate_local("your string")

More info about difference between : and .


问:
how to write $or query in node
This is how I write Mongo queries in Node.

query["serviceProvider.type"] = "prepaid";

but I need to write this query in my Node code which works only in MongoDB CLI. How can I achieve this i.e. I need to query same keys with two different values.

```<code>db = db.getSiblingDB("test");
db.getCollection("transactions").find(
    {

                $or : [
                    {
                        "serviceProvider.type" : "prepaid"
                    },
                    {
                        "serviceProvider.type" : "dth"
                    }
                ]

    }
);

</code>```
```<code>{
    "_id" : ObjectId("5d8b057e3a22472facdb89a4"),
    "customer" : {
        "isCustomerPaid" : true,
        "customerID" : "",
        "customer" : ""
    },
    "transaction" : {
        "transStatus" : false,
        "transID" : "15693919985540280",
        "number" : "8332900803",
        "amount" : NumberInt(5),
        "error" : "Something went wrong. Please try again after sometime."
    },
    "couponSurvey" : {
        "status" : false,
        "isEligible" : false
    },
    "status" : true,
    "advisor" : {
        "advisorID" : "BAA0280",
        "name" : "John BA",
        "phoneNumber" : 8005301205.0
    },
    "serviceProvider" : {
        "type" : "dth",
        "providerID" : "5bbb42e7a28b1daee826d7ec",
        "providerName" : "Sun Direct"
    },
    "provider" : {
        "refId" : "00",
        "status" : "fail",
        "startTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "endTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "message" : "Invalid Denomination"
    },
    "extras" : {
        "imei" : "865300302225654",
        "latitude" : "99.9385189",
        "longitude" : "11.5827393"
    },
    "createdAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "updatedAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "__v" : NumberInt(0)
}
</code>```

This is the sample data in database. Please let me know how I can query the parameters I require.

答:
One thing, your query has a type, there is an space after the second serviceProvider so the value dth is not found.

Also, to create an $or query you can simply use the same style:

let findQuery = {}
const q1 = {"serviceProvider.type" : "prepaid"}
const q2 = {"serviceProvider. type" : "dth"}
findQuery['$or'] = [q1,q2]

console.log(findQuery)```
</div>
</div>
</p>
<p>Or even if you have your values in an array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const values = ["prepaid","dth"]
let findQuery = {
'$or': values.map(m => {return {"serviceProvider.type":m}} )
}

console.log(findQuery)</code>```

Or, even... you can use $regex to find into that two values:

const values = ["prepaid","dth"]
let findQuery = {
  "serviceProvider.type":{
    '$regex':values.join('|')
  }
}

console.log(findQuery)```

Example here

Title: how to write $or query in node

Body:
This is how I write Mongo queries in Node.

query["serviceProvider.type"] = "prepaid";

but I need to write this query in my Node code which works only in MongoDB CLI. How can I achieve this i.e. I need to query same keys with two different values.

db = db.getSiblingDB("test");
db.getCollection("transactions").find(
    {

                $or : [
                    {
                        "serviceProvider.type" : "prepaid"
                    },
                    {
                        "serviceProvider.type" : "dth"
                    }
                ]

    }
);

{
    "_id" : ObjectId("5d8b057e3a22472facdb89a4"),
    "customer" : {
        "isCustomerPaid" : true,
        "customerID" : "",
        "customer" : ""
    },
    "transaction" : {
        "transStatus" : false,
        "transID" : "15693919985540280",
        "number" : "8332900803",
        "amount" : NumberInt(5),
        "error" : "Something went wrong. Please try again after sometime."
    },
    "couponSurvey" : {
        "status" : false,
        "isEligible" : false
    },
    "status" : true,
    "advisor" : {
        "advisorID" : "BAA0280",
        "name" : "John BA",
        "phoneNumber" : 8005301205.0
    },
    "serviceProvider" : {
        "type" : "dth",
        "providerID" : "5bbb42e7a28b1daee826d7ec",
        "providerName" : "Sun Direct"
    },
    "provider" : {
        "refId" : "00",
        "status" : "fail",
        "startTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "endTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "message" : "Invalid Denomination"
    },
    "extras" : {
        "imei" : "865300302225654",
        "latitude" : "99.9385189",
        "longitude" : "11.5827393"
    },
    "createdAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "updatedAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "__v" : NumberInt(0)
}

This is the sample data in database. Please let me know how I can query the parameters I require.

Body:
One thing, your query has a type, there is an space after the second serviceProvider so the value dth is not found.

Also, to create an $or query you can simply use the same style:

let findQuery = {}
const q1 = {"serviceProvider.type" : "prepaid"}
const q2 = {"serviceProvider. type" : "dth"}
findQuery['$or'] = [q1,q2]

console.log(findQuery)

Or even if you have your values in an array:

const values = ["prepaid","dth"]
let findQuery = {
'$or': values.map(m => {return {"serviceProvider.type":m}} )
}

console.log(findQuery)

Or, even... you can use $regex to find into that two values:

const values = ["prepaid","dth"]
let findQuery = {
  "serviceProvider.type":{
    '$regex':values.join('|')
  }
}

console.log(findQuery)

Example here