问:
How to define a generic SwiftUI view that can accept sectioned fetch results for different entities
I need to define a generic SwiftUI view that can accept sectioned fetch results for different CoreData entities, but I'm not sure how to define the generic view.

In the example below, I have two sectioned fetch results defined for Patient and Doctor entities. I need to be able to pass them to the generic view.

```<code>@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Patient.nameSortDescriptors(), animation: .default)
private var patients: SectionedFetchResults<String, Patient>

@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Doctor.nameSortDescriptors(), animation: .default)
private var doctors: SectionedFetchResults<String, Doctor>

GenericView(items: patients)
GenericView(items: doctors)

struct GenericView: View {
    let items: ?????
}
</code>```

答:
If for example Doctor and Patient conforms to protocol Human, then it could be as follows

```<code>protocol Human {
    var name: String { get set }

    // other code here
}

class Doctor: NSManagedObject, Human {
    var name: String = ""

    // other code here
}

struct GenericView<T: NSManagedObject & Human>: View {
    let items: SectionedFetchResults<String, T>

    var body: some View {
    // other code here
    }
}
</code>```

Body:
I need to define a generic SwiftUI view that can accept sectioned fetch results for different CoreData entities, but I'm not sure how to define the generic view.

In the example below, I have two sectioned fetch results defined for Patient and Doctor entities. I need to be able to pass them to the generic view.

@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Patient.nameSortDescriptors(), animation: .default)
private var patients: SectionedFetchResults<String, Patient>

@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Doctor.nameSortDescriptors(), animation: .default)
private var doctors: SectionedFetchResults<String, Doctor>

GenericView(items: patients)
GenericView(items: doctors)

struct GenericView: View {
    let items: ?????
}

Body:
If for example Doctor and Patient conforms to protocol Human, then it could be as follows

protocol Human {
    var name: String { get set }

    // other code here
}

class Doctor: NSManagedObject, Human {
    var name: String = ""

    // other code here
}

struct GenericView<T: NSManagedObject & Human>: View {
    let items: SectionedFetchResults<String, T>

    var body: some View {
    // other code here
    }
}


来源: stackexchange

问:
Duplicate class com.google.android.flexbox - Android Admob
I am using admob and facebook for ads in my app and its done but I want to check it so i have added Mediation Test Suite depnedancy

```<code> implementation 'com.google.android.ads:mediation-test-suite:2.0.0'
</code>```

And the app could not build it shows

```<code>Duplicate class com.google.android.flexbox.AlignContent found in modules jetified-flexbox-1.1.1-runtime (com.google.android:flexbox:1.1.1) and jetified-flexbox-3.0.0-runtime (com.google.android.flexbox:flexbox:3.0.0)
Duplicate class com.google.android.flexbox.AlignItems found in modules jetified-flexbox-1.1.1-runtime (com.google.android:flexbox:1.1.1) and jetified-flexbox-3.0.0-runtime (com.google.android.flexbox:flexbox:3.0.0)
</code>```

And many more Duplicate Class of Flexbox

my admob version

```<code>implementation 'com.google.android.gms:play-services-ads:20.4.0'
</code>```

答:
Exclude the flexbox module which is causing the conflict like this...</p>
```<code>implementation ('com.google.android.ads:mediation-test-suite:2.0.0') {
   exclude group: "com.google.android.flexbox", module: "flexbox"
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using admob and facebook for ads in my app and its done but I want to check it so i have added Mediation Test Suite depnedancy

 implementation 'com.google.android.ads:mediation-test-suite:2.0.0'

And the app could not build it shows

Duplicate class com.google.android.flexbox.AlignContent found in modules jetified-flexbox-1.1.1-runtime (com.google.android:flexbox:1.1.1) and jetified-flexbox-3.0.0-runtime (com.google.android.flexbox:flexbox:3.0.0)
Duplicate class com.google.android.flexbox.AlignItems found in modules jetified-flexbox-1.1.1-runtime (com.google.android:flexbox:1.1.1) and jetified-flexbox-3.0.0-runtime (com.google.android.flexbox:flexbox:3.0.0)

And many more Duplicate Class of Flexbox

my admob version

implementation 'com.google.android.gms:play-services-ads:20.4.0'

Body:
Exclude the flexbox module which is causing the conflict like this...

implementation ('com.google.android.ads:mediation-test-suite:2.0.0') {
   exclude group: "com.google.android.flexbox", module: "flexbox"
}


问:
UIButton with custom image still shows titleLabel even though I set it to blank - Swift iOS
I'm pretty new to Swift, currently writing an AR game.
Seems like my issue is very basic, but I can't figure it out.

I added a button to an AR Scene through the storyboard and linked it to an IBAction function (which works correctly when the button is clicked).
I gave the button an image and deleted the Title.
See how the button shows up in the storyboard:
button in Xcode storyboard without Title

But when I run the app, the button image shows up with a default label (saying "Button") as shown in this image:
button in iPhone screenshot WITH label next to the button image

I can't figure out why this label is there and how to remove it.
Should I add the button programmatically instead of adding it through the storyboard?
Should the button be treated differently because it's an AR app?

I was able to remove the label by adding the same UIButton as an IBOutlet and adding the following line in viewWillAppear:

```<code>restartButton.titleLabel?.text = ""
</code>```

But this feels to me like a workaround and not a real solution.
Also, as soon as I click on the button, the label shows up again. I tried to add the same workaround line to the function when the button is clicked, but that didn't help.

I'm sure I'm missing something very simple.
Your help would be appreciated.

Thanks!

答:
In iOS-15, Xcode-13.1 we are facing the same issue, You can change the same with Interface Builder via changing the "style" state from "Plane" to "Default" and then removing the title for that button, It will work perfectly fine as shown below:-

The initial state of the button is assigned as Plane like below:-

Then change the button style property as Default and remove title text for the same like below:-

Body:
I'm pretty new to Swift, currently writing an AR game.
Seems like my issue is very basic, but I can't figure it out.

I added a button to an AR Scene through the storyboard and linked it to an IBAction function (which works correctly when the button is clicked).
I gave the button an image and deleted the Title.
See how the button shows up in the storyboard:
button in Xcode storyboard without Title

But when I run the app, the button image shows up with a default label (saying "Button") as shown in this image:
button in iPhone screenshot WITH label next to the button image

I can't figure out why this label is there and how to remove it.
Should I add the button programmatically instead of adding it through the storyboard?
Should the button be treated differently because it's an AR app?

I was able to remove the label by adding the same UIButton as an IBOutlet and adding the following line in viewWillAppear:

restartButton.titleLabel?.text = ""

But this feels to me like a workaround and not a real solution.
Also, as soon as I click on the button, the label shows up again. I tried to add the same workaround line to the function when the button is clicked, but that didn't help.

I'm sure I'm missing something very simple.
Your help would be appreciated.

Thanks!


问:
Octave Symbolic Package (macOS) - error python
Trying to run Octave on Mac with the Symbolic package
After the install I ran a test (as shown in link above) by typing:

```<code>pkg load symbolic

syms x
</code>```

However, I got an following error with syms x

```<code>octave:37> syms x
Symbolic pkg v2.9.0: sh: /usr/anaconda3/bin/python: No such file or directory
error: Cannot run the Python executable "/usr/anaconda3/bin/python"
      Try "sympref diagnose" for more information.
error: called from
      assert_have_python_and_sympy at line 61 column 7
      python_ipc_popen2 at line 79 column 5
      python_ipc_driver at line 62 column 15
      pycall_sympy__ at line 163 column 11
      valid_sym_assumptions at line 38 column 10
      assumptions at line 82 column 7
      syms at line 97 column 13
octave:37>
</code>```

I then tried sympref diagnose

```<code>octave:37> sympref diagnose

Symbolic package diagnostics
============================

Python and SymPy are needed for most features of the Symbolic package.

The Python interpreter is currently: "/usr/anaconda3/bin/python".

Computers may have more than one Python interpreter installed.  If you
need to, you can select a different one using the PYTHON environment
variable (see "help sympref").  For example, to use Python 2, try
setenv PYTHON python2
sympref reset

Attempting to run /usr/anaconda3/bin/python -c "print(\"Python says hello\")"

sh: /usr/anaconda3/bin/python: No such file or directory
status =  127
output =

Unfortunately, that command failed!
We expected to see "status = 0" and "output = Python says hello".

* Is there an error message above?

* Do you have Python installed?

* Please try using "setenv" as described above.
</code>```

I think it has to do with name of the python directory.
there are 2 same questions: error: 'python_ipc_popen2' undefined near line 62 column 15 When running Octave

Installing Octave Symbolic Package using SymPy (macOS) - Can't get SymPy to work

Thanks in advance

Also if i remove anaconda:

```<code>octave:1> pkg load symbolic
octave:2> syms x
Symbolic pkg v2.9.0: sh: /Users/usr/octave/symbolic- 2.9.0/bin/py27.exe: Permission denied
error: Cannot run the Python executable "py27.exe"
      Try "sympref diagnose" for more information.
error: called from
      assert_have_python_and_sympy at line 61 column 7
      python_ipc_popen2 at line 79 column 5
      python_ipc_driver at line 62 column 15
      pycall_sympy__ at line 163 column 11
      valid_sym_assumptions at line 38 column 10
      assumptions at line 82 column 7
      syms at line 97 column 13
octave:2> sympref diagnose

Symbolic package diagnostics
============================

Python and SymPy are needed for most features of the Symbolic package.

The Python interpreter is currently: "py27.exe".

Computers may have more than one Python interpreter installed.  If you
need to, you can select a different one using the PYTHON environment
variable (see "help sympref").  For example, to use Python 2, try
  setenv PYTHON python2
  sympref reset

Attempting to run py27.exe -c "print(\"Python says hello\")"

sh: /Users/usr/octave/symbolic-2.9.0/bin/py27.exe: Permission denied
status =  126
output =

Unfortunately, that command failed!
We expected to see "status = 0" and "output = Python says hello".

 * Is there an error message above?

 * Do you have Python installed?

 * Please try using "setenv" as described above.

 * Most systems search the PATH environment when looking for commands.
</code>```

答: The problem seems disappeared if you upgrade from Octave 6.3 to a higher version of Octave in windows but I have not tested in Mac OS. However, Octave still lacks of fplot3 function for 3d curve plotting etc.</p>

Body:
Trying to run Octave on Mac with the Symbolic package
After the install I ran a test (as shown in link above) by typing:

pkg load symbolic

syms x

However, I got an following error with syms x

octave:37> syms x
Symbolic pkg v2.9.0: sh: /usr/anaconda3/bin/python: No such file or directory
error: Cannot run the Python executable "/usr/anaconda3/bin/python"
      Try "sympref diagnose" for more information.
error: called from
      assert_have_python_and_sympy at line 61 column 7
      python_ipc_popen2 at line 79 column 5
      python_ipc_driver at line 62 column 15
      pycall_sympy__ at line 163 column 11
      valid_sym_assumptions at line 38 column 10
      assumptions at line 82 column 7
      syms at line 97 column 13
octave:37>

I then tried sympref diagnose

octave:37> sympref diagnose

Symbolic package diagnostics
============================

Python and SymPy are needed for most features of the Symbolic package.

The Python interpreter is currently: "/usr/anaconda3/bin/python".

Computers may have more than one Python interpreter installed.  If you
need to, you can select a different one using the PYTHON environment
variable (see "help sympref").  For example, to use Python 2, try
setenv PYTHON python2
sympref reset

Attempting to run /usr/anaconda3/bin/python -c "print(\"Python says hello\")"

sh: /usr/anaconda3/bin/python: No such file or directory
status =  127
output =

Unfortunately, that command failed!
We expected to see "status = 0" and "output = Python says hello".

* Is there an error message above?

* Do you have Python installed?

* Please try using "setenv" as described above.

I think it has to do with name of the python directory.
there are 2 same questions: error: 'python_ipc_popen2' undefined near line 62 column 15 When running Octave

Installing Octave Symbolic Package using SymPy (macOS) - Can't get SymPy to work

Thanks in advance

Also if i remove anaconda:

octave:1> pkg load symbolic
octave:2> syms x
Symbolic pkg v2.9.0: sh: /Users/usr/octave/symbolic- 2.9.0/bin/py27.exe: Permission denied
error: Cannot run the Python executable "py27.exe"
      Try "sympref diagnose" for more information.
error: called from
      assert_have_python_and_sympy at line 61 column 7
      python_ipc_popen2 at line 79 column 5
      python_ipc_driver at line 62 column 15
      pycall_sympy__ at line 163 column 11
      valid_sym_assumptions at line 38 column 10
      assumptions at line 82 column 7
      syms at line 97 column 13
octave:2> sympref diagnose

Symbolic package diagnostics
============================

Python and SymPy are needed for most features of the Symbolic package.

The Python interpreter is currently: "py27.exe".

Computers may have more than one Python interpreter installed.  If you
need to, you can select a different one using the PYTHON environment
variable (see "help sympref").  For example, to use Python 2, try
  setenv PYTHON python2
  sympref reset

Attempting to run py27.exe -c "print(\"Python says hello\")"

sh: /Users/usr/octave/symbolic-2.9.0/bin/py27.exe: Permission denied
status =  126
output =

Unfortunately, that command failed!
We expected to see "status = 0" and "output = Python says hello".

 * Is there an error message above?

 * Do you have Python installed?

 * Please try using "setenv" as described above.

 * Most systems search the PATH environment when looking for commands.


问:
How to link a Vaadin Grid with the result of Spring Mono WebClient data
This seems to be a missing part in the documentation of Vaadin...

I call an API to get data in my UI like this:

```<code>@Override
public URI getUri(String url, PageRequest page) {
    return UriComponentsBuilder.fromUriString(url)
            .queryParam("page", page.getPageNumber())
            .queryParam("size", page.getPageSize())
            .queryParam("sort", (page.getSort().isSorted() ? page.getSort() : ""))
            .build()
            .toUri();
}

@Override
public Mono<Page<SomeDto>> getDataByPage(PageRequest pageRequest) {
    return webClient.get()
            .uri(getUri(URL_API + "/page", pageRequest))
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<>() {
            });
}
</code>```

In the Vaadin documentation (https://vaadin.com/docs/v10/flow/binding-data/tutorial-flow-data-provider), I found an example with DataProvider.fromCallbacks but this expects streams and that doesn't feel like the correct approach as I need to block on the requests to get the streams...

```<code>DataProvider<SomeDto, Void> lazyProvider = DataProvider.fromCallbacks(
     q -> service.getData(PageRequest.of(q.getOffset(), q.getLimit())).block().stream(),
     q -> service.getDataCount().block().intValue()
);
</code>```

When trying this implementation, I get the following error:

```<code>org.springframework.core.codec.CodecException: Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
grid.setItems(lazyProvider);
</code>```

答:
There are two parts to this question.

The first one is about asynchronously loading data for a DataProvider in Vaadin. This isn't supported since Vaadin has prioritized the typical case with fetching data straight through JDBC. This means that you end up blocking a thread while the data is loading. Vaadin 23 will add support for doing that blocking on a separate thread instead of keeping the UI thread blocked, but it will still be blocking.

The other half of your problem doesn't seem to be directly related to Vaadin. The exception message says that the Jackson instance used by the REST client isn't configured to support creating instances of org.springframework.data.domain.Page. I don't have direct experience with this part of the problem, so I cannot give any advice on exactly how to fix it.

Body:
This seems to be a missing part in the documentation of Vaadin...

I call an API to get data in my UI like this:

@Override
public URI getUri(String url, PageRequest page) {
    return UriComponentsBuilder.fromUriString(url)
            .queryParam("page", page.getPageNumber())
            .queryParam("size", page.getPageSize())
            .queryParam("sort", (page.getSort().isSorted() ? page.getSort() : ""))
            .build()
            .toUri();
}

@Override
public Mono<Page<SomeDto>> getDataByPage(PageRequest pageRequest) {
    return webClient.get()
            .uri(getUri(URL_API + "/page", pageRequest))
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<>() {
            });
}

In the Vaadin documentation (https://vaadin.com/docs/v10/flow/binding-data/tutorial-flow-data-provider), I found an example with DataProvider.fromCallbacks but this expects streams and that doesn't feel like the correct approach as I need to block on the requests to get the streams...

DataProvider<SomeDto, Void> lazyProvider = DataProvider.fromCallbacks(
     q -> service.getData(PageRequest.of(q.getOffset(), q.getLimit())).block().stream(),
     q -> service.getDataCount().block().intValue()
);

When trying this implementation, I get the following error:

org.springframework.core.codec.CodecException: Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
grid.setItems(lazyProvider);


问:
Sending some vars besides the file data
I'm trying to upload a file using post request but I can't append any other variables with it .
Here is the code : </p>

```<code>NSMutableURLRequest *urlRequest =
      [NSMutableURLRequest requestWithURL:url];
   [urlRequest setHTTPMethod:@"POST"];
   [urlRequest setValue:
      [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry]
      forHTTPHeaderField:@"Content-Type"];

NSString *post = @"key1=val1&key2=val2";
NSData *postVars = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

   NSMutableData *postData =
      [NSMutableData dataWithCapacity:[data length]+[postVars length] + 512];
    [postData appendData:postVars];
   [postData appendData:
      [[NSString stringWithFormat:@"--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];
   [postData appendData:
      [[NSString stringWithFormat:
        @"Content-Disposition: form-data; name=\"%@\"; filename=\"test.bin\"\r\n\r\n", FORM_FLE_INPUT]
       dataUsingEncoding:NSUTF8StringEncoding]];
   [postData appendData:data];
   [postData appendData:
      [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];

   [urlRequest setHTTPBody:postData];
</code>```

答:
It may be useful to you.</p>

```<code>NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sending some vars besides the file data

Body:
I'm trying to upload a file using post request but I can't append any other variables with it .
Here is the code :

NSMutableURLRequest *urlRequest =
      [NSMutableURLRequest requestWithURL:url];
   [urlRequest setHTTPMethod:@"POST"];
   [urlRequest setValue:
      [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry]
      forHTTPHeaderField:@"Content-Type"];

NSString *post = @"key1=val1&key2=val2";
NSData *postVars = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

   NSMutableData *postData =
      [NSMutableData dataWithCapacity:[data length]+[postVars length] + 512];
    [postData appendData:postVars];
   [postData appendData:
      [[NSString stringWithFormat:@"--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];
   [postData appendData:
      [[NSString stringWithFormat:
        @"Content-Disposition: form-data; name=\"%@\"; filename=\"test.bin\"\r\n\r\n", FORM_FLE_INPUT]
       dataUsingEncoding:NSUTF8StringEncoding]];
   [postData appendData:data];
   [postData appendData:
      [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];

   [urlRequest setHTTPBody:postData];

Body:
It may be useful to you.

NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];


问:
Prime ng Calendar year range changes when clicking arrows to year outside of range
I have a p-calendar element that is working correctly, but it has an annoying ui bug that allows the user to click to a year outside of the yearRange. They cannot selected a day in a year outside of the yearRange, as expected, but when they click on the year dropdown from a date outside of the yearRange, the yearRange in the dropdown is different. (e.g. if the original yearRange is 2016:2022 and the user selects Dec 2022 then clicks arrow to Jan 2023, when they click the year drop down they will now see 2022-2028)

```<code>      <p-calendar
                name="arrivedate"
                [showIcon]="true"
                [monthNavigator]="true"
                [yearNavigator]="true"
                yearRange="2016:2022"
                formControlName="arrivedateCtrl"
                dateFormat="yy/mm/dd"
                placeholder="{{requireText}}"
                readonlyInput="readonlyInput"
                [locale]="calLanObj">
      </p-calendar>
</code>```

I'm trying to find a way to either not allow the user to click the arrows to a year outside the yearRange, or that when they click the year dropdown from a date outside of the range they will see the original yearRange in the dropdown.

Any ideas?

Thanks

答:
There is no intended way to do this. So your options are:

Make a request to the devs in the github issues: https://github.com/primefaces/primeng/issues

Grab the source code from the github and modify it to what you want - you might even be able to merge it into the main product since primeng is open source: https://github.com/primefaces/primeng/tree/master/src/app/components/calendar

Use this janky hack:

We'll add event listeners for onYearChange and onMonthChange. Also, a template id so we can use ViewChild to do some questionable stuff.

```
<p>I've removed the deprecated property <code>yearRange</code> and use <code>minDate</code> and <code>maxDate</code> instead.</p>
<p>Then we'll add a function to check the year is within our bounds when the user changes it. We'll use <code>@ViewChild</code> to access all the functions and variables that we're <em>not supposed to</em>. Through trial and error, I found that calling the <code>onModelTouched()</code> function and then resetting our date value will update the date in the calendar.</p>
<pre class="lang-js prettyprint-override"><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { Calendar } from 'primeng/calendar';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
  @ViewChild('calendar') calendar?: Calendar;
  minDate = new Date(1451624400000); //Jan 1 2016
  maxDate = new Date(1672462800000); //Dec 31 2022
  date = new Date();
  constructor() {}

  ngOnInit(): void {}

  checkYear(date: { month: number; year: number }) {
    if (this.calendar) {
      if (date.year < 2016) {
        this.calendar.onModelTouched();
        this.date = new Date(this.minDate);
      }
      if (date.year > 2022) {
        this.calendar.onModelTouched();
        this.date = new Date(this.maxDate);
      }
    }
  }
}
</code>```

If the user picks a date not within our range, we set it to the minimum or maximum value. We need to make sure to set the date using new Date() to ensure change detection will trigger every time.

Keep in mind this is using the component in an unintentional way, so there's no guarantee it won't break in future versions.

Stackblitz: https://stackblitz.com/edit/angular-ivy-emw3ge?file=src/app/test/test.component.ts

Body:
I have a p-calendar element that is working correctly, but it has an annoying ui bug that allows the user to click to a year outside of the yearRange. They cannot selected a day in a year outside of the yearRange, as expected, but when they click on the year dropdown from a date outside of the yearRange, the yearRange in the dropdown is different. (e.g. if the original yearRange is 2016:2022 and the user selects Dec 2022 then clicks arrow to Jan 2023, when they click the year drop down they will now see 2022-2028)

I'm trying to find a way to either not allow the user to click the arrows to a year outside the yearRange, or that when they click the year dropdown from a date outside of the range they will see the original yearRange in the dropdown.

Any ideas?

Thanks

Body:
There is no intended way to do this. So your options are:

Make a request to the devs in the github issues: https://github.com/primefaces/primeng/issues

Grab the source code from the github and modify it to what you want - you might even be able to merge it into the main product since primeng is open source: https://github.com/primefaces/primeng/tree/master/src/app/components/calendar

Use this janky hack:

We'll add event listeners for onYearChange and onMonthChange. Also, a template id so we can use ViewChild to do some questionable stuff.

<p-calendar
  #calendar
  [(ngModel)]="date"
  [showIcon]="true"
  [minDate]="minDate"
  [maxDate]="maxDate"
  (onYearChange)="checkYear($event)"
  (onMonthChange)="checkYear($event)"
>
</p-calendar>

I've removed the deprecated property yearRange and use minDate and maxDate instead.

Then we'll add a function to check the year is within our bounds when the user changes it. We'll use @ViewChild to access all the functions and variables that we're not supposed to. Through trial and error, I found that calling the onModelTouched() function and then resetting our date value will update the date in the calendar.

import { Component, OnInit, ViewChild } from '@angular/core';
import { Calendar } from 'primeng/calendar';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
  @ViewChild('calendar') calendar?: Calendar;
  minDate = new Date(1451624400000); //Jan 1 2016
  maxDate = new Date(1672462800000); //Dec 31 2022
  date = new Date();
  constructor() {}

  ngOnInit(): void {}

  checkYear(date: { month: number; year: number }) {
    if (this.calendar) {
      if (date.year < 2016) {
        this.calendar.onModelTouched();
        this.date = new Date(this.minDate);
      }
      if (date.year > 2022) {
        this.calendar.onModelTouched();
        this.date = new Date(this.maxDate);
      }
    }
  }
}

If the user picks a date not within our range, we set it to the minimum or maximum value. We need to make sure to set the date using new Date() to ensure change detection will trigger every time.

Keep in mind this is using the component in an unintentional way, so there's no guarantee it won't break in future versions.

Stackblitz: https://stackblitz.com/edit/angular-ivy-emw3ge?file=src/app/test/test.component.ts


问:
Kubernetes Nginx Ingress Connection Refused on External IP Address (Bare Metal)
I've setup an ingress resource to route requests to single service.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    #kubernetes.io/ingress.class: nginx
    #ingress.kubernetes.io/rewrite-target: /

spec:
  defaultBackend:
    service:
      name: dashboard
      port:
        number: 80
```
<pre class="lang-sh prettyprint-override"><code>$ kubectl get ing
NAME              CLASS    HOSTS   ADDRESS         PORTS   AGE
example-ingress   <none>   *       102.16.50.202   80      3m28s
</code>```

The nginx-controller:

$ kubectl get pods -n ingress-nginx
NAME                                        READY   STATUS      RESTARTS      AGE
ingress-nginx-admission-create--1-gl59f     0/1     Completed   0             15h
ingress-nginx-admission-patch--1-9kbz6      0/1     Completed   0             15h
ingress-nginx-controller-54d8b558d4-2ss8f   1/1     Running     1 (13h ago)   15h

$ kubectl get svc -n ingress-nginx
NAME                                 TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)                      AGE
ingress-nginx-controller             LoadBalancer   10.233.48.242   102.16.50.202   80:31690/TCP,443:32666/TCP   15h
ingress-nginx-controller-admission   ClusterIP      10.233.17.68    <none>          443/TCP                      15h
```
<p>I'm able to reach and get response from the service via the controller's cluster IP:</p>
<pre class="lang-sh prettyprint-override"><code>$ curl -i 10.233.48.242
HTTP/1.1 200 OK
Date: Tue, 08 Feb 2022 04:50:44 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 2306
Connection: keep-alive
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Tue, 25 Jan 2022 09:35:14 GMT
ETag: W/"902-17e9096e050"
...
</code>```

But not on its (nginx-controller's) external IP address:

$ curl -i 102.16.50.202
curl: (7) Failed to connect to 102.16.50.202 port 80: Connection refused

$ curl -i http://102.16.50.202
curl: (7) Failed to connect to 102.16.50.202 port 80: Connection refused

$ curl -i http://102.16.50.202/
curl: (7) Failed to connect to 102.16.50.202 port 80: Connection refused
```
<p>I tried creating a new path (prefix), changed service type to NodePort, disabled the firewall, with no success; same issue.</p>
<p>Any observation or input would help a lot. Thanks.</p>
<h5>Edit-1:</h5>
<p>The nginx ingress controller is installed (<code>kubectl apply</code>) without modifying the default configuration:</p>
<pre class="lang-yaml prettyprint-override"><code>#file: ingress-controller-deploy.yml
...
apiVersion: v1
kind: Service
metadata:
  annotations:
  labels:
    helm.sh/chart: ingress-nginx-4.0.15
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/version: 1.1.1
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/component: controller
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ipFamilyPolicy: SingleStack
  ipFamilies:
    - IPv4
  ports:
    - name: http
      port: 80
      protocol: TCP
      targetPort: http
      appProtocol: http
    - name: https
      port: 443
      protocol: TCP
      targetPort: https
      appProtocol: https
  selector:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/component: controller
</code>```

The externalTrafficPolicy:Local seems to be ok if I'm using a load balancer, which in my case is MetalLB .

#file: ingress-controller-deploy.yml
apiVersion: apps/v1
kind: Deployment
...
          securityContext:
            capabilities:
              drop:
                - ALL
              add:
                - NET_BIND_SERVICE
            runAsUser: 101
            allowPrivilegeEscalation: true
```

The securityContext section seems ok too.

答:
The ingress object is not your issue. You have to concentrate on the ingress-controller setup. Also, which load-balancing mechanism are you using? If you are on Bare Metal, you need to deploy something like MetalLB, which you probably already have (otherwise the service of type LoadBalancer stays in pending state).

Good documentation around this topic can be found at https://kubernetes.github.io/ingress-nginx/deploy/baremetal/

Body:
I've setup an ingress resource to route requests to single service.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    #kubernetes.io/ingress.class: nginx
    #ingress.kubernetes.io/rewrite-target: /

spec:
  defaultBackend:
    service:
      name: dashboard
      port:
        number: 80

$ kubectl get ing
NAME              CLASS    HOSTS   ADDRESS         PORTS   AGE
example-ingress   <none>   *       102.16.50.202   80      3m28s

The nginx-controller:

$ kubectl get pods -n ingress-nginx
NAME                                        READY   STATUS      RESTARTS      AGE
ingress-nginx-admission-create--1-gl59f     0/1     Completed   0             15h
ingress-nginx-admission-patch--1-9kbz6      0/1     Completed   0             15h
ingress-nginx-controller-54d8b558d4-2ss8f   1/1     Running     1 (13h ago)   15h

$ kubectl get svc -n ingress-nginx
NAME                                 TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)                      AGE
ingress-nginx-controller             LoadBalancer   10.233.48.242   102.16.50.202   80:31690/TCP,443:32666/TCP   15h
ingress-nginx-controller-admission   ClusterIP      10.233.17.68    <none>          443/TCP                      15h

I'm able to reach and get response from the service via the controller's cluster IP:

$ curl -i 10.233.48.242
HTTP/1.1 200 OK
Date: Tue, 08 Feb 2022 04:50:44 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 2306
Connection: keep-alive
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Tue, 25 Jan 2022 09:35:14 GMT
ETag: W/"902-17e9096e050"
...

But not on its (nginx-controller's) external IP address:

$ curl -i 102.16.50.202
curl: (7) Failed to connect to 102.16.50.202 port 80: Connection refused

$ curl -i http://102.16.50.202
curl: (7) Failed to connect to 102.16.50.202 port 80: Connection refused

$ curl -i http://102.16.50.202/
curl: (7) Failed to connect to 102.16.50.202 port 80: Connection refused

I tried creating a new path (prefix), changed service type to NodePort, disabled the firewall, with no success; same issue.

Any observation or input would help a lot. Thanks.

Edit-1:

The nginx ingress controller is installed (kubectl apply) without modifying the default configuration:

#file: ingress-controller-deploy.yml
...
apiVersion: v1
kind: Service
metadata:
  annotations:
  labels:
    helm.sh/chart: ingress-nginx-4.0.15
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/version: 1.1.1
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/component: controller
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ipFamilyPolicy: SingleStack
  ipFamilies:
    - IPv4
  ports:
    - name: http
      port: 80
      protocol: TCP
      targetPort: http
      appProtocol: http
    - name: https
      port: 443
      protocol: TCP
      targetPort: https
      appProtocol: https
  selector:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/component: controller

The externalTrafficPolicy:Local seems to be ok if I'm using a load balancer, which in my case is MetalLB .

#file: ingress-controller-deploy.yml
apiVersion: apps/v1
kind: Deployment
...
          securityContext:
            capabilities:
              drop:
                - ALL
              add:
                - NET_BIND_SERVICE
            runAsUser: 101
            allowPrivilegeEscalation: true

The securityContext section seems ok too.


问:
Interacting like a Mealy machine in sequential VHDL
We're working on testing a circuit that writes to memory, so the test bench needs to read bytes from memory.  However the memory is intended to be read by a Mealy machine. The protocol for the reader is this:

It requests a read by setting oReadRequest high and setting the address bus.

It waits until the next clock period.

If before the end of that next clock period, the request has been acknowledged by iReading being high, then the reader can find the result on the data bus, and has the option of setting oReadRequest to low, or putting a new address on the address bus.

If by the end of that next clock period the request has not been acknowledged, the reader keeps the address the same and oReadRequest high and then it's back to step 2.

This is easy enough to implement in concurrent VHDL with a Mealy machine. But for the test benches I'd like to have a procedure that can read a byte, which means using only sequential statements.

Here is what we have. And it works. (At least it works in pre-synthesis testing.)  But it seems wrong somehow to have a wait based on time.  Our clock period is 10ns.  The 3 ns seems completely arbitrary.

```<code>    procedure readByte(
        signal iReading : in std_ulogic;
        signal iData : in NineBitByte;
        address : in ByteAddress;
        signal oReadRequest : out std_ulogic;
        signal oReadAddress : out ByteAddress;
        result : out NineBitByte) is
    begin

        loop
            -- Request a byte.
            oReadAddress <= address;
            oReadRequest <= '1';

            wait until rising_edge( clock );

            -- Wait for a little while
            -- to give the memory arbiter time to react
            -- to the request.
            wait for 3 ns;

            -- Is it acknowledged?
            exit when iReading = '1';
        end loop;

        result := iData;
        -- Tentatively reset the request line.
        -- A subsequent read in this cycle might
        -- overturn this assignment.
        oReadRequest <= '0';
    end procedure;
</code>```

We are using VHDL-93 in case that makes a difference.

So the specific question is whether there is a way to write the procedure without putting in arbitrary time delays.

The more general question is whether there is a way to write sequential VHDL to emulate a Mealy machine without knowing how fast the other process will react.  With concurrent assignments, an input such as iReading that might change partway trough a clock cycle can be continuously monitored and changes reacted to at any time in the clock cycle. In the code I have above, I picked a specific time in each clock cycle to observe this input.

答:
Reading again your specifications and your code I think that we could reformulate as "assert oReadRequest high, wait until the next rising edge of the clock, and then, if iReading is not already asserted high, wait until it is".

The second wait can last 0 time if iReading is already asserted high, or less than one clock period if it is asserted high before the next rising edge of the clock or more, it does not make any difference, the behaviour is the same: just stop waiting when iReading is asserted high.

So, if I am right, you could replace the body of your procedure by:

```<code>begin
    -- Request a byte.
    oReadAddress <= address;
    oReadRequest <= '1';
    -- wait next rising edge of clock
    wait until rising_edge(clock);
    -- if not acknowledged
    if iReading /= '1' then
        -- wait until acknowledge
        wait until iReading = '1';
    end if;

    result := iData;
    oReadRequest <= '0';
end procedure;
</code>```

In case you know for sure that iReading will be 0 after the first rising edge of the clock, we can reformulate as "assert oReadRequest high, wait until the next rising edge of the clock, and then, wait until iReading is asserted high":

```<code>begin
    -- Request a byte.
    oReadAddress <= address;
    oReadRequest <= '1';
    -- wait next rising edge of clock
    wait until rising_edge(clock);
    -- wait until acknowledge
    wait until iReading = '1';

    result := iData;
    oReadRequest <= '0';
end procedure;
</code>```

In both cases, when returning from your procedure call, you can call it again with a different address and this will chain consecutive requests without delay.

Finally, if none of these interpretations is correct I think you are facing another kind of issue: after having sent your request you don't know what to wait for, that signals its acknowledgement. And this is not a VHDL problem, it is a specification problem.

Body:
We're working on testing a circuit that writes to memory, so the test bench needs to read bytes from memory.  However the memory is intended to be read by a Mealy machine. The protocol for the reader is this:

It requests a read by setting oReadRequest high and setting the address bus.

It waits until the next clock period.

If before the end of that next clock period, the request has been acknowledged by iReading being high, then the reader can find the result on the data bus, and has the option of setting oReadRequest to low, or putting a new address on the address bus.

If by the end of that next clock period the request has not been acknowledged, the reader keeps the address the same and oReadRequest high and then it's back to step 2.

This is easy enough to implement in concurrent VHDL with a Mealy machine. But for the test benches I'd like to have a procedure that can read a byte, which means using only sequential statements.

Here is what we have. And it works. (At least it works in pre-synthesis testing.)  But it seems wrong somehow to have a wait based on time.  Our clock period is 10ns.  The 3 ns seems completely arbitrary.

    procedure readByte(
        signal iReading : in std_ulogic;
        signal iData : in NineBitByte;
        address : in ByteAddress;
        signal oReadRequest : out std_ulogic;
        signal oReadAddress : out ByteAddress;
        result : out NineBitByte) is
    begin

        loop
            -- Request a byte.
            oReadAddress <= address;
            oReadRequest <= '1';

            wait until rising_edge( clock );

            -- Wait for a little while
            -- to give the memory arbiter time to react
            -- to the request.
            wait for 3 ns;

            -- Is it acknowledged?
            exit when iReading = '1';
        end loop;

        result := iData;
        -- Tentatively reset the request line.
        -- A subsequent read in this cycle might
        -- overturn this assignment.
        oReadRequest <= '0';
    end procedure;

We are using VHDL-93 in case that makes a difference.

So the specific question is whether there is a way to write the procedure without putting in arbitrary time delays.

The more general question is whether there is a way to write sequential VHDL to emulate a Mealy machine without knowing how fast the other process will react.  With concurrent assignments, an input such as iReading that might change partway trough a clock cycle can be continuously monitored and changes reacted to at any time in the clock cycle. In the code I have above, I picked a specific time in each clock cycle to observe this input.

Body:
Reading again your specifications and your code I think that we could reformulate as "assert oReadRequest high, wait until the next rising edge of the clock, and then, if iReading is not already asserted high, wait until it is".

The second wait can last 0 time if iReading is already asserted high, or less than one clock period if it is asserted high before the next rising edge of the clock or more, it does not make any difference, the behaviour is the same: just stop waiting when iReading is asserted high.

So, if I am right, you could replace the body of your procedure by:

begin
    -- Request a byte.
    oReadAddress <= address;
    oReadRequest <= '1';
    -- wait next rising edge of clock
    wait until rising_edge(clock);
    -- if not acknowledged
    if iReading /= '1' then
        -- wait until acknowledge
        wait until iReading = '1';
    end if;

    result := iData;
    oReadRequest <= '0';
end procedure;

In case you know for sure that iReading will be 0 after the first rising edge of the clock, we can reformulate as "assert oReadRequest high, wait until the next rising edge of the clock, and then, wait until iReading is asserted high":

begin
    -- Request a byte.
    oReadAddress <= address;
    oReadRequest <= '1';
    -- wait next rising edge of clock
    wait until rising_edge(clock);
    -- wait until acknowledge
    wait until iReading = '1';

    result := iData;
    oReadRequest <= '0';
end procedure;

In both cases, when returning from your procedure call, you can call it again with a different address and this will chain consecutive requests without delay.

Finally, if none of these interpretations is correct I think you are facing another kind of issue: after having sent your request you don't know what to wait for, that signals its acknowledgement. And this is not a VHDL problem, it is a specification problem.


问:
Function to validate an input type button max value 9 and min value 1, not working
I have a challenge that make a table depending on what's on the inputs.

function createTable(){
    let table = document.getElementById('table')
    let row = document.getElementById('input-row').value
    let column = document.getElementById('input-column').value

     for(let rowIndex = 0; rowIndex < row; rowIndex++){
        let tr = document.createElement('tr')

        for(let colIndex = 0; colIndex < column; colIndex++){
            let td = document.createElement('td')
            tr.appendChild(td)
        }

        table.appendChild(tr)

        document.getElementById('input-row').value = " "
        document.getElementById('input-column').value = " "

        if(row == " ") {
            alert('Number of rows cannot be empty')
            return false
        }

        if(row > 9) {
            alert('Number of rows cannot be greater than 9')
            return false
        }

        if(row <= 0) {
            alert('Number of rows cannot be less than 1')
            return false
        }

    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="inputs-container">
            <div class="inputs-container_rows">
                <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
                <h3>Rows</h3>
            </div>
            <div class="inputs-container_columns">
                <input type="number" class="inputs" max=9 min=0 id="input-column">
                <h3>Columns</h3>
            </div>
 </div>
 <div class="btn-container">
            <button id="btn" onclick="createTable()">Create Table</button>
        </div>
        <div class="table-container">
            <table border="1" id="table">

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

for the validation only the if(row > 9) is working the other ones not.

Also, I want to erase the table when again I press the button, I don't know how to do it.

答:
If you have anything that requires user interaction, you'll need to listen for events (unless you are using prompt() but that's just plain awful). The "click" event is the goto event but there are far better ones you could use especially if you use a <form>. One event in particular is exclusively for the form:

submit: When user is focused in a field and hits
Enter/Return key or a <button>,
<input type="submit">, or
<input type="image"> is clicked the form will:

validate itself if there is any [required], [pattern], [min], [max], etc. attributes or any validation methods hooked in,

gather all values from any fields with a [name] attribute,

then send it to a server, and will return a response.

If it doesn't have a server to send it to, it will return a blank page. The example below will do everything when a "submit" event is fired, but it will not send data to a server. You should read the following:

Events

Event Delegation

Inline Event Handlers are Garbage

Forms and Form Controls (aka Fields)

Details are commented in the example below

/***********
    ** Creates a given element and appends them.
    * @param   {String}     tag     tagName of element to be
    *                               created
    * @param   {DOM Object} parent  DOM object to append to
    * @param   {Number}     times   number of times tag is
    *                               created
    * @param   {String}     content string in
    *                               each cell (Default is empty)
    * @returns {DOM Object|Array} DOM object or an array of DOM
    *                             objects
    */
    const setDOM = (tag, parent, times, content = '') => {
      let nodeList = [];
      for (let i = 0; i < times; i++) {
        let node = document.createElement(tag);
        parent.appendChild(node);
        node.insertAdjacentHTML('beforeEnd', content);
        nodeList.push(node);
      }
      return times > 1 ? nodeList : times === 1 ? nodeList.pop() : null;
    }

    /** Event handler passes an Event Object (e) **/
    const buildTable = e => {

      /** Event Properties/Methods
      -Stop normal behavior of form submits
      -(io) is all form controls (fieldset, legend, input,
      button)
      */
      e.preventDefault();
      const io = e.currentTarget.elements;

      /** Form Data
      -(r) number of rows
      -(c) number of columns
      -(cnt) text if any from #edit
      */
      let r = parseInt(io.rows.value);
      let c = parseInt(io.cols.value);
      let cnt = io.edit.innerHTML;

      /** Create the Table
      -Clear #box
      -Create
 in #box
      -Create
 in table
      */
      io.box.replaceChildren();
      const table = setDOM('table', io.box, 1);
      const tB = setDOM('tbody', table, 1);

      /** Create Rows & Columns
      -Create all

      -if an array is returned...
        ...Use .forEach() to create the  for each
...
        ...Otherwise just run setDOM() once to create the
      */
      const allRows = setDOM('tr', tB, r);
      if (Array.isArray(allRows)) {
        allRows.forEach((row, idx) => setDOM('td', allRows[idx], c, cnt));
      } else {
        setDOM('td', allRows, c, cnt);
      }

      /** Create tHead
      -if #head is checked...
        ...Create
...
        ...Create
...
        ...Create all
      */
      if (io.head.checked) {
        let tH = table.createTHead();
        let hRow = setDOM('tr', tH, 1);
        setDOM('th', hRow, c, cnt);
      }

      /** Create tFoot
      -if #foot is checked...
        ...Create
...
        ...Create
...
        ...Create all
      */
      if (io.foot.checked) {
        let tF = table.createTFoot();
        let fRow = setDOM('tr', tF, 1);
        setDOM('td', fRow, c, cnt);
      }
    };

    // Reference the form and listen for the submit event
    const UI = document.forms[0];
    UI.onsubmit = buildTable;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*, *::before {box-sizing: border-box;}:root {font: 1ch/1.25 'Segoe UI';}body {font-size: 4ch;}.box {width: 100%;max-width: max-content;background: lightgrey;}.box:empty {border: 0;background: transparent;}.edit {width: 100%;min-width: 50vw;min-height: 50px;overflow-wrap: break-word;word-break: break-word;border: 0;outline: 0;padding: 0;}.group {display: flex;flex-flow: row wrap;justify-content: flex-start;align-items: center;}fieldset, button, input {border-radius: 4px;}input {display: inline-block;font-size: 100%;font-family: Consolas;}label {display: flex;align-items: center;margin-right: 2rem;margin-top: 4px;font-size: 100%;}label b {font-weight: 400;}button {display: block;float: right;width: 80px;margin: 4px 0;font-size: 100%;cursor: pointer;}.num {width: 5ch;}.chx {width: 15px;height: 15px;margin-bottom: -1px;cursor: pointer;}table {table-layout: fixed;border-collapse: collapse;width: 100%;}table, td, th {border: 1px solid #000;}th {background: lime;}tbody td {background: cyan;}tfoot td {background: tomato;}</code>```

    <form id='UI'>
      <fieldset>
        <fieldset class='group'>
          <legend>Rows & Columns</legend>
          Rows:......(max. 99)
          <input id='rows' class='num' type='number' min='1' max='99' maxlegnth='3' required>
          Columns:.(max. 20)
          <input id='cols' class='num' type='number' min='1' max='20' maxlegnth='3' required>
        </fieldset>
        <fieldset>
          <legend>Optional text </legend>
          <fieldset id='edit' class='edit' contenteditable></fieldset>
        </fieldset>
        <fieldset class='group'>
          <legend>Optional Sections</legend>
          Table Head: <input id='head' class='chx' type='checkbox'>
          Table Foot: <input id='foot' class='chx' type='checkbox'>
        </fieldset>
        <button>GO</button>
        <fieldset id='box' class='box'></fieldset>
      </fieldset>
    </form>
  ```

Body:
I have a challenge that make a table depending on what's on the inputs.

function createTable(){
    let table = document.getElementById('table')
    let row = document.getElementById('input-row').value
    let column = document.getElementById('input-column').value

     for(let rowIndex = 0; rowIndex < row; rowIndex++){
        let tr = document.createElement('tr')

        for(let colIndex = 0; colIndex < column; colIndex++){
            let td = document.createElement('td')
            tr.appendChild(td)
        }

        table.appendChild(tr)

        document.getElementById('input-row').value = " "
        document.getElementById('input-column').value = " "

        if(row == " ") {
            alert('Number of rows cannot be empty')
            return false
        }

        if(row > 9) {
            alert('Number of rows cannot be greater than 9')
            return false
        }

        if(row <= 0) {
            alert('Number of rows cannot be less than 1')
            return false
        }

    }
}

                <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">

Rows

                <input type="number" class="inputs" max=9 min=0 id="input-column">

Columns

            <button id="btn" onclick="createTable()">Create Table</button>

for the validation only the if(row > 9) is working the other ones not.

Also, I want to erase the table when again I press the button, I don't know how to do it.

Body:
If you have anything that requires user interaction, you'll need to listen for events (unless you are using prompt() but that's just plain awful). The "click" event is the goto event but there are far better ones you could use especially if you use a <form>. One event in particular is exclusively for the form:

submit: When user is focused in a field and hits
Enter/Return key or a <button>,
<input type="submit">, or
<input type="image"> is clicked the form will:

validate itself if there is any [required], [pattern], [min], [max], etc. attributes or any validation methods hooked in,

gather all values from any fields with a [name] attribute,

then send it to a server, and will return a response.

If it doesn't have a server to send it to, it will return a blank page. The example below will do everything when a "submit" event is fired, but it will not send data to a server. You should read the following:

Events

Event Delegation

Inline Event Handlers are Garbage

Forms and Form Controls (aka Fields)

Details are commented in the example below

/***********
    ** Creates a given element and appends them.
    * @param   {String}     tag     tagName of element to be
    *                               created
    * @param   {DOM Object} parent  DOM object to append to
    * @param   {Number}     times   number of times tag is
    *                               created
    * @param   {String}     content string in
    *                               each cell (Default is empty)
    * @returns {DOM Object|Array} DOM object or an array of DOM
    *                             objects
    */
    const setDOM = (tag, parent, times, content = '') => {
      let nodeList = [];
      for (let i = 0; i < times; i++) {
        let node = document.createElement(tag);
        parent.appendChild(node);
        node.insertAdjacentHTML('beforeEnd', content);
        nodeList.push(node);
      }
      return times > 1 ? nodeList : times === 1 ? nodeList.pop() : null;
    }

    /** Event handler passes an Event Object (e) **/
    const buildTable = e => {

      /** Event Properties/Methods
      -Stop normal behavior of form submits
      -(io) is all form controls (fieldset, legend, input,
      button)
      */
      e.preventDefault();
      const io = e.currentTarget.elements;

      /** Form Data
      -(r) number of rows
      -(c) number of columns
      -(cnt) text if any from #edit
      */
      let r = parseInt(io.rows.value);
      let c = parseInt(io.cols.value);
      let cnt = io.edit.innerHTML;

      /** Create the Table
      -Clear #box
      -Create <table> in #box
      -Create <tbody> in table
      */
      io.box.replaceChildren();
      const table = setDOM('table', io.box, 1);
      const tB = setDOM('tbody', table, 1);

      /** Create Rows & Columns
      -Create all <tr>
      -if an array is returned...
        ...Use .forEach() to create the <td> for each <tr>...
        ...Otherwise just run setDOM() once to create the <td>
      */
      const allRows = setDOM('tr', tB, r);
      if (Array.isArray(allRows)) {
        allRows.forEach((row, idx) => setDOM('td', allRows[idx], c, cnt));
      } else {
        setDOM('td', allRows, c, cnt);
      }

      /** Create tHead
      -if #head is checked...
        ...Create <thead>...
        ...Create <tr>...
        ...Create all <th>
      */
      if (io.head.checked) {
        let tH = table.createTHead();
        let hRow = setDOM('tr', tH, 1);
        setDOM('th', hRow, c, cnt);
      }

      /** Create tFoot
      -if #foot is checked...
        ...Create <tfoot>...
        ...Create <tr>...
        ...Create all <td>
      */
      if (io.foot.checked) {
        let tF = table.createTFoot();
        let fRow = setDOM('tr', tF, 1);
        setDOM('td', fRow, c, cnt);
      }
    };

    // Reference the form and listen for the submit event
    const UI = document.forms[0];
    UI.onsubmit = buildTable;

*, *::before {box-sizing: border-box;}:root {font: 1ch/1.25 'Segoe UI';}body {font-size: 4ch;}.box {width: 100%;max-width: max-content;background: lightgrey;}.box:empty {border: 0;background: transparent;}.edit {width: 100%;min-width: 50vw;min-height: 50px;overflow-wrap: break-word;word-break: break-word;border: 0;outline: 0;padding: 0;}.group {display: flex;flex-flow: row wrap;justify-content: flex-start;align-items: center;}fieldset, button, input {border-radius: 4px;}input {display: inline-block;font-size: 100%;font-family: Consolas;}label {display: flex;align-items: center;margin-right: 2rem;margin-top: 4px;font-size: 100%;}label b {font-weight: 400;}button {display: block;float: right;width: 80px;margin: 4px 0;font-size: 100%;cursor: pointer;}.num {width: 5ch;}.chx {width: 15px;height: 15px;margin-bottom: -1px;cursor: pointer;}table {table-layout: fixed;border-collapse: collapse;width: 100%;}table, td, th {border: 1px solid #000;}th {background: lime;}tbody td {background: cyan;}tfoot td {background: tomato;}

<main>
    <form id='UI'>
      <fieldset>
        <fieldset class='group'>
          <legend>Rows &amp; Columns</legend>
          <label>Rows:......<sup>(max. 99)</sup>&nbsp;
          <input id='rows' class='num' type='number' min='1' max='99' maxlegnth='3' required></label>
          <label>Columns:.<sup>(max. 20)</sup>&nbsp;
          <input id='cols' class='num' type='number' min='1' max='20' maxlegnth='3' required></label>
        </fieldset>
        <fieldset>
          <legend>Optional text </legend>
          <fieldset id='edit' class='edit' contenteditable></fieldset>
        </fieldset>
        <fieldset class='group'>
          <legend>Optional Sections</legend>
          <label><b>Table Head:</b>&nbsp;<input id='head' class='chx' type='checkbox'></label>
          <label><b>Table Foot:</b>&nbsp;<input id='foot' class='chx' type='checkbox'></label>
        </fieldset>
        <button>GO</button>
        <fieldset id='box' class='box'></fieldset>
      </fieldset>
    </form>
  </main>


问:
Is it possible to perform 128-bit / 64-bit division without branching, in terms of 64-bit division?
I'm working with the Algorand contract code which has a very limited scope of possible operations in their assembly code - e.g., it is not possible to control flow of the code. Basic 64 bit arithmetic operations are available.

What I need to do is to divide two 64-bit segments (as a whole 128-bit number) of a certain 128-bit integer by another 64-bit integer knowing that the result will fit within 64-bit integer. Is it possible without controlling flow of the code and only with 64-bit arithmetics?

答:
Not answering the main question, but solving the underlying issue.

Algorand smart contracts now support such large division directly using the opcode divmodw: https://developer.algorand.org/docs/get-details/dapps/avm/teal/opcodes/#divmodw

They also support division of up to 512-bit numbers: https://developer.algorand.org/docs/get-details/dapps/avm/teal/specification/#arithmetic-logic-and-cryptographic-operations


问:
How to install the Bumblebee 2021.1.1 Android Studio Patch?
When I open Android Studio I receive a notification saying that an update is available:

```<code>The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes
</code>```

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.

答:
As written in the issuetracker (217880288):

Workaround: delete manually only the "C:\Program Files\Android\Android Studio"-folder and then install AS again. All your preferences will be restored because they are saved in your profile folder.

This worked for me.
However I for my part only renamed the old Android Studio folder and will keep it for a few Versions just to be have it in case of problems - but I didn't notice any problems yet.

P.S.: I readded the folder as exclusion from Antivirus, even if I do not remember well if this is still helping performance.

P.P.S.: Before I also tried the JetBrains Toolbox way to update AS, it said it installed the patch - however I still got the messages afterwards and it was still using old gradle.

Body:
When I open Android Studio I receive a notification saying that an update is available:

The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.


问:
laravel jetstream photo profile section doesnt apear
eh been trying to make the section of upload photo appear in the update section, but it does not appear unless I remove the if and I do not understand why I already modify the jetstream.php the .env and I do not know what else to do
enter image description here
that if I do not know what it does but it is what does not allow the image to be displayed
enter image description here
the photo section does not appear :(</p>

答:
If profile photo section still doesn't appear after enabling profile photos

Try clearing the cache by running:

```<code>php artisan optimize
</code>```

then refresh the browser.

Body:
If profile photo section still doesn't appear after enabling profile photos

Try clearing the cache by running:

php artisan optimize

then refresh the browser.


问:
Unconstrained Optimization using Gradient and (sparse) Hessian
I'm looking for a C++ optimization package that can do multivariate unconstrained optimization using gradient and Hessian information.  I'm doing it now in Matlab using fminunc with the 'GradObj', 'Hessian', and 'HessPattern' options.  My Hessian is very sparse so a package that takes that into account would be preferable.

Are there any alternatives to Matlab for this?  Open-source or closed-source are both fine.  C++ is preferable but I'm flexible.

答: You could just ditch the Hessian and use a BFGS approach, like libLBFGS. These quasi-Newton methods are usually pretty good.</p>

OwnerDisplayName: eglaser


问:
asyncio and GET: Unexpected UTF-8 BOM

Update

My asyncio powered GET requestor is giving me issues today, but only for certain workItem requests that it makes.

It is not a particular workItem that is causing the issue. I can retrieve a single workItem and then run the same function again and get rejected with the error:

Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)

The line that triggers the error is: workItem = await resp.json() in this function:

```<code>async def getWorkItem(self, session, url):
    async with session.get(url, headers=headers) as resp:
        workItem = await resp.json()  <----------------- the problem
        workItem = pd.json_normalize(workItem['value'])
        workItem.columns = workItem.columns.str.replace(
            'fields.', '', regex=False)
        return workItem
</code>```

How might I try to solve this decoding issue?

答:
You could remove BOM before decode json, a minimal example:

test.py:

```<code>import aiohttp
import asyncio
import json

async def main():
    async with aiohttp.ClientSession() as session:
        # async with session.get('http://127.0.0.1:9989/data.json') as resp:
        async with session.get('http://127.0.0.1:9989/with_bom.json') as resp:
            raw_text = await resp.text()
            text_without_bom = raw_text.encode().decode('utf-8-sig')
            work_items = json.loads(text_without_bom)
            print(type(work_items))
            print(work_items)

asyncio.run(main())
</code>```

Explanation:

Use text() to replace json() to get the raw text.

Remove BOM using utf-8-sig decode.

Use json.loads() to transform str to dict.

Above code works both for response with BOM or without BOM.

Title: asyncio and GET: Unexpected UTF-8 BOM

Body:
Update

My asyncio powered GET requestor is giving me issues today, but only for certain workItem requests that it makes.

It is not a particular workItem that is causing the issue. I can retrieve a single workItem and then run the same function again and get rejected with the error:

Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)

The line that triggers the error is: workItem = await resp.json() in this function:

async def getWorkItem(self, session, url):
    async with session.get(url, headers=headers) as resp:
        workItem = await resp.json()  <----------------- the problem
        workItem = pd.json_normalize(workItem['value'])
        workItem.columns = workItem.columns.str.replace(
            'fields.', '', regex=False)
        return workItem

How might I try to solve this decoding issue?

Body:
You could remove BOM before decode json, a minimal example:

test.py:

import aiohttp
import asyncio
import json

async def main():
    async with aiohttp.ClientSession() as session:
        # async with session.get('http://127.0.0.1:9989/data.json') as resp:
        async with session.get('http://127.0.0.1:9989/with_bom.json') as resp:
            raw_text = await resp.text()
            text_without_bom = raw_text.encode().decode('utf-8-sig')
            work_items = json.loads(text_without_bom)
            print(type(work_items))
            print(work_items)

asyncio.run(main())

Explanation:

Use text() to replace json() to get the raw text.

Remove BOM using utf-8-sig decode.

Use json.loads() to transform str to dict.

Above code works both for response with BOM or without BOM.


问:
ninja: build stopped: subcommand failed when building llvm10 on Fedora 35
I have been trying to build llvm10 from source. I downloaded the source from llvm's github and have been trying for the past few days to complete the build but each and everytime towards the end of the ninja process, the error pops up -ninja: build stopped: subcommand failed

I am using the following commands to build:

```<code>cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/home/llvm -DLLVM_ENABLE_PROJECTS=clang -DLLVM_LIBDIR_SUFFIX=64 -DLLVM_TARGETS_TO_BUILD="AMDGPU" -DLLVM_OPTIMIZED_TABLEGEN=ON -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_PARALLEL_LINK_JOBS=1
</code>```

Since multiple of my attempts failed, I also tried running by setting the parallel jobs to 1 as many threads recommended. Also did ninja -j1 but none of this helps.

I remember having done this successfully on Fedora 34, so, I reinstalled Fedora 34, but, it too gives me the same error.

This is the portion where the error pops up:

```<code>[1/17] Building CXX object utils/bench.../benchmark.dir/benchmark_register.cc.o
FAILED: utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o
/bin/c++ -DHAVE_POSIX_REGEX -DHAVE_STD_REGEX -DHAVE_STEADY_CLOCK -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/build/utils/benchmark/src -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src -I/usr/include/libxml2 -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/build/include -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/include -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/include -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/../include -fPIC -fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wno-comment -fdiagnostics-color -ffunction-sections -fdata-sections  -std=c++11  -Wall  -Wextra  -Wshadow  -pedantic  -pedantic-errors  -Wfloat-equal  -fstrict-aliasing  -fno-exceptions  -Wstrict-aliasing -O3 -DNDEBUG -std=c++14 -MD -MT utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o -MF utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o.d -o utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o -c /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.cc
In file included from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.cc:15:
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h: In function ‘void AddRange(std::vector<T>*, T, T, int)’:
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:17:30: error: ‘numeric_limits’ is not a member of ‘std’
   17 |   static const T kmax = std::numeric_limits<T>::max();
      |                              ^~~~~~~~~~~~~~
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:17:46: error: expected primary-expression before ‘>’ token
   17 |   static const T kmax = std::numeric_limits<T>::max();
      |                                              ^
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:17:49: error: ‘::max’ has not been declared; did you mean ‘std::max’?
   17 |   static const T kmax = std::numeric_limits<T>::max();
      |                                                 ^~~
      |                                                 std::max
In file included from /usr/include/c++/11/algorithm:62,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/include/benchmark/benchmark.h:175,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/internal_macros.h:4,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/check.h:8,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:6,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.cc:15:
/usr/include/c++/11/bits/stl_algo.h:3467:5: note: ‘std::max’ declared here
 3467 |     max(initializer_list<_Tp> __l, _Compare __comp)
      |     ^~~
ninja: build stopped: subcommand failed.
</code>```

Any help is appreciated.

答: The header include was missed at that time. You may want to add it by yourself (https://github.com/llvm/llvm-project/commit/b498303066a63a203d24f739b2d2e0e56dca70d1) or use newer version of LLVM ;)</p>

Body:
I have been trying to build llvm10 from source. I downloaded the source from llvm's github and have been trying for the past few days to complete the build but each and everytime towards the end of the ninja process, the error pops up -ninja: build stopped: subcommand failed

I am using the following commands to build:

cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/home/llvm -DLLVM_ENABLE_PROJECTS=clang -DLLVM_LIBDIR_SUFFIX=64 -DLLVM_TARGETS_TO_BUILD="AMDGPU" -DLLVM_OPTIMIZED_TABLEGEN=ON -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_PARALLEL_LINK_JOBS=1

Since multiple of my attempts failed, I also tried running by setting the parallel jobs to 1 as many threads recommended. Also did ninja -j1 but none of this helps.

I remember having done this successfully on Fedora 34, so, I reinstalled Fedora 34, but, it too gives me the same error.

This is the portion where the error pops up:

[1/17] Building CXX object utils/bench.../benchmark.dir/benchmark_register.cc.o
FAILED: utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o
/bin/c++ -DHAVE_POSIX_REGEX -DHAVE_STD_REGEX -DHAVE_STEADY_CLOCK -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/build/utils/benchmark/src -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src -I/usr/include/libxml2 -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/build/include -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/include -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/include -I/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/../include -fPIC -fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wno-comment -fdiagnostics-color -ffunction-sections -fdata-sections  -std=c++11  -Wall  -Wextra  -Wshadow  -pedantic  -pedantic-errors  -Wfloat-equal  -fstrict-aliasing  -fno-exceptions  -Wstrict-aliasing -O3 -DNDEBUG -std=c++14 -MD -MT utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o -MF utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o.d -o utils/benchmark/src/CMakeFiles/benchmark.dir/benchmark_register.cc.o -c /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.cc
In file included from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.cc:15:
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h: In function ‘void AddRange(std::vector<T>*, T, T, int)’:
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:17:30: error: ‘numeric_limits’ is not a member of ‘std’
   17 |   static const T kmax = std::numeric_limits<T>::max();
      |                              ^~~~~~~~~~~~~~
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:17:46: error: expected primary-expression before ‘>’ token
   17 |   static const T kmax = std::numeric_limits<T>::max();
      |                                              ^
/home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:17:49: error: ‘::max’ has not been declared; did you mean ‘std::max’?
   17 |   static const T kmax = std::numeric_limits<T>::max();
      |                                                 ^~~
      |                                                 std::max
In file included from /usr/include/c++/11/algorithm:62,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/include/benchmark/benchmark.h:175,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/internal_macros.h:4,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/check.h:8,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.h:6,
                 from /home/test/Desktop/llvm-project-llvmorg-10.0.0/llvm/utils/benchmark/src/benchmark_register.cc:15:
/usr/include/c++/11/bits/stl_algo.h:3467:5: note: ‘std::max’ declared here
 3467 |     max(initializer_list<_Tp> __l, _Compare __comp)
      |     ^~~
ninja: build stopped: subcommand failed.

Any help is appreciated.


问:
How to open a link in a new Tab in NextJS?
How can i open a link in a new Tab in NextJS ? i tried this :

```<code>      <Link href="https://twitter.com/" passHref>
        <a target="_blank">
          <div className={`${dark ? styles.iconTwitterWhite : styles.iconTwitter} mr-3`} />
        </a>
      </Link>
</code>```

It opens the link in a new Tab but i have an ESLint message saying :

```<code>ESLint: The href attribute is required for an anchor to be keyboard accessible. Provide a valid, navigable address as the href value. If you cannot provide an href, but still need the element to resemble a link, use a button and change it with appropriate styles.
</code>```

Is there another way to do it ?

答:
I've heard there are cases where you want to stick with Link (i18n stuff that Link helps with) so you can use passHref (which just passes the href to the immediate child) like so:

```<code><Link href="/" passHref>
  <a target="_blank" rel="noopener noreferrer">
    Foo
  </a>
</Link>
</code>```

Body:
How can i open a link in a new Tab in NextJS ? i tried this :

      <Link href="https://twitter.com/" passHref>

          <div className={`${dark ? styles.iconTwitterWhite : styles.iconTwitter} mr-3`} />

      </Link>

It opens the link in a new Tab but i have an ESLint message saying :

ESLint: The href attribute is required for an anchor to be keyboard accessible. Provide a valid, navigable address as the href value. If you cannot provide an href, but still need the element to resemble a link, use a button and change it with appropriate styles.

Is there another way to do it ?

Body:
I've heard there are cases where you want to stick with Link (i18n stuff that Link helps with) so you can use passHref (which just passes the href to the immediate child) like so:

<Link href="/" passHref>
  <a target="_blank" rel="noopener noreferrer">
    Foo
  </a>
</Link>


问:
Randomization in Silenium
im using selenium and lets say I wanted to choose a random element right in a  specific class right. How would I do that. Here is an example of my code

```<code>answer_click = driver.find_element_by_xpath('//*[@class="item"]').click()
</code>```

there are multiple items in this class and I want to choose a random one, how would I do so. Sorry if this makes it complicated

答:
This example looks for all the answers, then finds all the visible elements, and eventually gets a random item.

Visibility checking can be removed, but commonly some not visible elements might be found, so the random will be invisible, and click will cause an exception.

import random

all_answers = driver.find_elements_by_xpath('//*[@class="item"]')
visible_answers = filter(lambda x: x.is_displayed(), all_answers)
answer_to_click = random.choice(visible_answers)
answer_to_click.click()
```

Title: Randomization in Silenium

Body:
im using selenium and lets say I wanted to choose a random element right in a  specific class right. How would I do that. Here is an example of my code

answer_click = driver.find_element_by_xpath('//*[@class="item"]').click()

there are multiple items in this class and I want to choose a random one, how would I do so. Sorry if this makes it complicated


问:
I want to put text in an input field by pressing a button
I have a button called suggestion that the script is attached. I have an input field for the user to input their name. If they click the button I want a to populate the input field with a random suggestion. I know how to do the random part, but can not find an example of how to put that string into the input field where they could edit it or except it.</p>
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RandomChar : MonoBehaviour
{
    public Text ourName;
    public string rndName = "bob";
    public void SetText(string textOurName)
    {
        textOurName = rndName;
        ourName.text = textOurName;
    }
}
</code>```

答:
If it is an actual InputField then you should not go through the Text component but rather directly through the InputField.text

```<code>public InputField ourName;

public void SetText()
{
    ourName.text = GetRandomName ();
}
</code>```

Body:
I have a button called suggestion that the script is attached. I have an input field for the user to input their name. If they click the button I want a to populate the input field with a random suggestion. I know how to do the random part, but can not find an example of how to put that string into the input field where they could edit it or except it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RandomChar : MonoBehaviour
{
    public Text ourName;
    public string rndName = "bob";
    public void SetText(string textOurName)
    {
        textOurName = rndName;
        ourName.text = textOurName;
    }
}

Body:
If it is an actual InputField then you should not go through the Text component but rather directly through the InputField.text

public InputField ourName;

public void SetText()
{
    ourName.text = GetRandomName ();
}


问:
How do I automatically create service principals or MSIs with Terraform for use in Azure Pipelines to manage AKS resources?
I'm following the official docs to create Azure Kubernetes clusters. The docs state that I need to create a service principal first, manually, and provide the client_id and client_secret.

Doing it manually is not an option.

Here is the code for my service principal. It's decorated with links to the most recent Terraform docs for reference.

```<code>data "azurerm_subscription" "current" {}
data "azuread_client_config" "current" {}

resource "random_id" "current" {
  byte_length = 8
  prefix      = "ExternalDnsTf"
}

# Create Azure AD App.
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application
resource "azuread_application" "current" {
  display_name = random_id.current.hex
  owners       = [data.azuread_client_config.current.object_id]

}

# Create Service Principal associated with the Azure AD App
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal
resource "azuread_service_principal" "current" {
  application_id               = azuread_application.current.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.current.object_id]
}

# Create Service Principal password
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application_password
resource "azuread_application_password" "current" {
  application_object_id = azuread_application.current.object_id
}

# Create role assignment for service principal
# https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/role_assignment
resource "azurerm_role_assignment" "current" {
  scope                = data.azurerm_subscription.current.id
  role_definition_name = "Contributor"

 # When assigning to a SP, use the object_id, not the appId
 # see: https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-cli
  principal_id = azuread_service_principal.current.object_id
}
</code>```

I keep getting the following error in my pipeline: (note, I am the owner of my subscription)

```<code>ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData
│ error: Authorization_RequestDenied: Insufficient privileges to complete the
│ operation.

</code>```

What I'm trying to do is to eliminate the manual steps to setup supporting services. Take ExternalDNS for example. The Azure docs state that I need to use az ad sp create-for-rbac -n ExternalDnsServicePrincipal; az role assignment create --role "Reader" --assignee <appId GUID> --scope <resource group resource id>; az role assignment create --role "Contributor" --assignee <appId GUID> --scope <dns zone resource id>

Ultimately, I'm trying to create the terraform version of the azure cli commands.

Support for create-for-rbac was a feature request on github. That used to work great, but so much has changed, it's not applicable to current API versions. Also, with AAD Graph being deprecated in favor Microsoft Graph API, I wonder if I'm getting snagged on that.

The ExternalDNS docs also suggested Managed Service Identities (MSI). Service principals, MSI, MSGraph API integration, honestly, I don't care which one is used. Whatever is current best-practices is fine so long as I do not have to log into the portal to manually create or give permissions, or manually run az cli commands.

EDIT: Permissions clarification

I'm using Terraform, of course, to provision resources. If I do all of this without terraform (manually or with a bash script), I use azure cli I start setting permissions by doing the following:

az login

az account set -s <my-subscription-id>

I am the owner of my subscription. I can run all commands, create SPs, MSIs, assign roles, etc, with no problem.

In the pipelines, I am using the charleszipp az pipelines terraform plugin. In the logs, I see:

az login --service-principal -t <my-tenant-id> -u *** -p ***

az account set -s <my-subscription-id>

I'm not sure if that makes a difference. I interpret that as ultimately, commands are executed after signing in and setting the account subscription, like I do manually.

Technically, I'm not using a service connection in several of these tasks. However, where one is required, I have created a Service connection and defined its Scope to the subscription level. It's of type Azure Resource Manager.

However, if I click "manage service principal, it takes me to the portal where there are no permissions defined.

While I am the owner of my subscription, I am not the root management group. I'm owned / provisioned by someone else. Ultimately, they have control of Active Directory. I cannot add or edit permissions. If I try to add any under permissions API and select Microsoft Graph, it says that authorization is required. Grant Admin Consent for <parent organization is greyed out.

But why would that be important if I'm the owner of my subscription? If I can do whatever I want via the az cli command line, what's preventing me from doing the same in the pipeline?

答:
I am using user-managed identity for that, it seemed most straightforward and worked fine for me.</p>
```<code>resource "azurerm_user_managed_identity", "mi" {
    resource_group_name = "rg"
    name = "mi"
    location = "eastus"
}

resource "azurerm_role_assignment" "ra" {
    scope = azurerm_subnet.sn.id  // subnet I created earlier
    role_definition_name = "Network Contributor"  // required with kubenet
    principal_id = azurerm_user_managed_identity.mi.principal_id
}

resource "azurerm_kubernetes_cluster" "aks" {
    name = "aks"
    identity {
        type = "UserAssigned"
        user_assigned_identity_id = azurerm_user_managed_identity.mi.id
    }
    <...remaining attributes...>
    depends_on = [azurerm_role_assignment.ra] // just to be safe
}
</code>```

Body:
I'm following the official docs to create Azure Kubernetes clusters. The docs state that I need to create a service principal first, manually, and provide the client_id and client_secret.

Doing it manually is not an option.

Here is the code for my service principal. It's decorated with links to the most recent Terraform docs for reference.

data "azurerm_subscription" "current" {}
data "azuread_client_config" "current" {}

resource "random_id" "current" {
  byte_length = 8
  prefix      = "ExternalDnsTf"
}

# Create Azure AD App.
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application
resource "azuread_application" "current" {
  display_name = random_id.current.hex
  owners       = [data.azuread_client_config.current.object_id]

}

# Create Service Principal associated with the Azure AD App
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal
resource "azuread_service_principal" "current" {
  application_id               = azuread_application.current.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.current.object_id]
}

# Create Service Principal password
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application_password
resource "azuread_application_password" "current" {
  application_object_id = azuread_application.current.object_id
}

# Create role assignment for service principal
# https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/role_assignment
resource "azurerm_role_assignment" "current" {
  scope                = data.azurerm_subscription.current.id
  role_definition_name = "Contributor"

 # When assigning to a SP, use the object_id, not the appId
 # see: https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-cli
  principal_id = azuread_service_principal.current.object_id
}

I keep getting the following error in my pipeline: (note, I am the owner of my subscription)

ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData
│ error: Authorization_RequestDenied: Insufficient privileges to complete the
│ operation.

What I'm trying to do is to eliminate the manual steps to setup supporting services. Take ExternalDNS for example. The Azure docs state that I need to use az ad sp create-for-rbac -n ExternalDnsServicePrincipal; az role assignment create --role "Reader" --assignee <appId GUID> --scope <resource group resource id>; az role assignment create --role "Contributor" --assignee <appId GUID> --scope <dns zone resource id>

Ultimately, I'm trying to create the terraform version of the azure cli commands.

Support for create-for-rbac was a feature request on github. That used to work great, but so much has changed, it's not applicable to current API versions. Also, with AAD Graph being deprecated in favor Microsoft Graph API, I wonder if I'm getting snagged on that.

The ExternalDNS docs also suggested Managed Service Identities (MSI). Service principals, MSI, MSGraph API integration, honestly, I don't care which one is used. Whatever is current best-practices is fine so long as I do not have to log into the portal to manually create or give permissions, or manually run az cli commands.

EDIT: Permissions clarification

I'm using Terraform, of course, to provision resources. If I do all of this without terraform (manually or with a bash script), I use azure cli I start setting permissions by doing the following:

az login

az account set -s <my-subscription-id>

I am the owner of my subscription. I can run all commands, create SPs, MSIs, assign roles, etc, with no problem.

In the pipelines, I am using the charleszipp az pipelines terraform plugin. In the logs, I see:

az login --service-principal -t <my-tenant-id> -u *** -p ***

az account set -s <my-subscription-id>

I'm not sure if that makes a difference. I interpret that as ultimately, commands are executed after signing in and setting the account subscription, like I do manually.

Technically, I'm not using a service connection in several of these tasks. However, where one is required, I have created a Service connection and defined its Scope to the subscription level. It's of type Azure Resource Manager.

However, if I click "manage service principal, it takes me to the portal where there are no permissions defined.

While I am the owner of my subscription, I am not the root management group. I'm owned / provisioned by someone else. Ultimately, they have control of Active Directory. I cannot add or edit permissions. If I try to add any under permissions API and select Microsoft Graph, it says that authorization is required. Grant Admin Consent for <parent organization is greyed out.

But why would that be important if I'm the owner of my subscription? If I can do whatever I want via the az cli command line, what's preventing me from doing the same in the pipeline?

Body:
I am using user-managed identity for that, it seemed most straightforward and worked fine for me.

resource "azurerm_user_managed_identity", "mi" {
    resource_group_name = "rg"
    name = "mi"
    location = "eastus"
}

resource "azurerm_role_assignment" "ra" {
    scope = azurerm_subnet.sn.id  // subnet I created earlier
    role_definition_name = "Network Contributor"  // required with kubenet
    principal_id = azurerm_user_managed_identity.mi.principal_id
}

resource "azurerm_kubernetes_cluster" "aks" {
    name = "aks"
    identity {
        type = "UserAssigned"
        user_assigned_identity_id = azurerm_user_managed_identity.mi.id
    }
    <...remaining attributes...>
    depends_on = [azurerm_role_assignment.ra] // just to be safe
}