问:
django forms non_field_errors customizing
I want to have my own errors in django forms but I cant . as you can see I define my own error_messages but django is still using Its own errors.

app account / forms.py:

```<code>from django import forms

error_messages_email = {
    'required': 'please Fill-out this field',
    'invalid': 'invalid format for email',
    'max_length': 'max length is 40 chars',
}
error_messages = {
    'required': 'please Fill-out this field',
    'invalid': 'fields format is not valid',
    'max_length': 'max_length is 30 chars',
    'min_length': 'password should be at least 8 Chars',
}

class LoginForm(forms.Form):
    username = forms.CharField(error_messages=error_messages, max_length=30,
                               widget=forms.TextInput(attrs={'class': 'form-control',
                                                             'placeholder': 'Username'}))
    password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
                               widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                                 'placeholder': 'Password'}))

class SignupForm(forms.Form):
    username = forms.CharField(error_messages=error_messages, max_length=30,
                               widget=forms.TextInput(attrs={'class': 'form-control',
                                                             'placeholder': 'Username'}))

    email = forms.EmailField(error_messages=error_messages_email, max_length=40,
                             widget=forms.EmailInput(attrs={'class': 'form-control',
                                                            'placeholder': 'Email'}))

    password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
                               widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                                 'placeholder': 'Password'}))

</code>```

and this is my apps template / signup.html:

```<code>{% extends 'main.html' %}

{% block title %} Join {% endblock %}

{% block content %}

    <form action="" method="post">
        {% csrf_token %}
        {{ form.non_field_errors }}

            {{ form.username.errors }}
            <label for="{{ form.username.id_for_label }}">Username:</label>
            {{ form.username }}<br>

            {{ form.email.errors }}
            <label for="{{ form.email.id_for_label }}">E-mail:</label>
            {{ form.email }}<br>

            {{ form.password.errors }}
            <label for="{{ form.password.id_for_label }}">Password:</label>
            {{ form.password }}<br>

        <input type="submit" value="signup" class="btn btn-primary" >

    </form>

{% endblock %}
</code>```

the only problem is the errors other parts are working properly, in the browser I also change max_length to 50 and pass it a 50-char password and submit it and it works fine and shows my own error.

答:
about the answer , what I was doing wrong was that I didn't turn off templates validation so it wasn't using django validation error. simply where you defined your form template just do this:

```<code><form action="" method="post" novalidate>
</code>```

put novalidate at the end of the form tag

Body:
I want to have my own errors in django forms but I cant . as you can see I define my own error_messages but django is still using Its own errors.

app account / forms.py:

from django import forms

error_messages_email = {
    'required': 'please Fill-out this field',
    'invalid': 'invalid format for email',
    'max_length': 'max length is 40 chars',
}
error_messages = {
    'required': 'please Fill-out this field',
    'invalid': 'fields format is not valid',
    'max_length': 'max_length is 30 chars',
    'min_length': 'password should be at least 8 Chars',
}

class LoginForm(forms.Form):
    username = forms.CharField(error_messages=error_messages, max_length=30,
                               widget=forms.TextInput(attrs={'class': 'form-control',
                                                             'placeholder': 'Username'}))
    password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
                               widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                                 'placeholder': 'Password'}))

class SignupForm(forms.Form):
    username = forms.CharField(error_messages=error_messages, max_length=30,
                               widget=forms.TextInput(attrs={'class': 'form-control',
                                                             'placeholder': 'Username'}))

    email = forms.EmailField(error_messages=error_messages_email, max_length=40,
                             widget=forms.EmailInput(attrs={'class': 'form-control',
                                                            'placeholder': 'Email'}))

    password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
                               widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                                 'placeholder': 'Password'}))

and this is my apps template / signup.html:

{% extends 'main.html' %}

{% block title %} Join {% endblock %}

{% block content %}

    <form action="" method="post">
        {% csrf_token %}
        {{ form.non_field_errors }}

            {{ form.username.errors }}
            Username:
            {{ form.username }}

            {{ form.email.errors }}
            E-mail:
            {{ form.email }}

            {{ form.password.errors }}
            Password:
            {{ form.password }}

        <input type="submit" value="signup" class="btn btn-primary" >

    </form>

{% endblock %}

the only problem is the errors other parts are working properly, in the browser I also change max_length to 50 and pass it a 50-char password and submit it and it works fine and shows my own error.

Body:
about the answer , what I was doing wrong was that I didn't turn off templates validation so it wasn't using django validation error. simply where you defined your form template just do this:

<form action="" method="post" novalidate>

put novalidate at the end of the form tag


来源: stackexchange

问:
MetaMask - RPC Error: Error: [ethjs-query] while formatting outputs from RPC
I am very new to Ethereum smart contract solidity programming. Currently, I have been facing this issue when I try to pass a variable from my Node.js servlet to the smart contract I deployed using Truffle Suite, specifically with accounts provided by Ganache.

Following is the JavaScript I used to connect and call the smart contract method:

```<code>if (this.state.contract) {
            this.state.contract.methods.searchKeyword(searchToken.toString())
                .send({from: this.state.account, gas: 210000, gasPrice: 50000}, function (err, res) {
                    if (err) {
                        console.log("Error", err)
                        return
                    }
                    console.log(res)
                })
        }
</code>```

Following is the Solidity code in smart contract:

```<code>function searchKeyword (string memory searchToken) public {
        searchWord = searchToken;
    }
</code>```

Whenever I call the function and pass searchToken , the following error pops up. I have tried setting the gas and gasPrice over, within, below the gasLimit of my MetaMask wallet but I am still getting errors like Exceeds block gas limit. I have tried without setting the gas and gasPrice but I am still getting the similar issue.

Any genius please help me this noob beginner who trying so hard to debug just a small little function. Thank you guys in advance :D

答: Try reseting your metamask accounts (settings > advanced > reset account). Worked for me.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am very new to Ethereum smart contract solidity programming. Currently, I have been facing this issue when I try to pass a variable from my Node.js servlet to the smart contract I deployed using Truffle Suite, specifically with accounts provided by Ganache.

Following is the JavaScript I used to connect and call the smart contract method:

if (this.state.contract) {
            this.state.contract.methods.searchKeyword(searchToken.toString())
                .send({from: this.state.account, gas: 210000, gasPrice: 50000}, function (err, res) {
                    if (err) {
                        console.log("Error", err)
                        return
                    }
                    console.log(res)
                })
        }

Following is the Solidity code in smart contract:

function searchKeyword (string memory searchToken) public {
        searchWord = searchToken;
    }

Whenever I call the function and pass searchToken , the following error pops up. I have tried setting the gas and gasPrice over, within, below the gasLimit of my MetaMask wallet but I am still getting errors like Exceeds block gas limit. I have tried without setting the gas and gasPrice but I am still getting the similar issue.

Any genius please help me this noob beginner who trying so hard to debug just a small little function. Thank you guys in advance :D


问:
How to get pin codes without zeros in it?
Write a query to display the customer_id,customer full name ,city,pincode,and order details (order id, product class desc, product desc, subtotal(product_quantity * product_price)) for orders shipped to cities whose pin codes do not have any 0s in them. Sort the output on customer name and subtotal. (52 ROWS) [NOTE: TABLE TO BE USED - online_customer, address, order_header, order_items, product, product_class].

These are the attributes of each table:

Address- ADDRESS_ID, ADDRESS_LINE1,ADDRESS_LINE2,CITY,STATE,PINCODE,COUNTRY

ONLINE_CUSTOMER- CUSTOMER_ID, CUSTOMER_FNAME, CUSTMER_LNAME, CUSTOMER_EMAIL,CUSTOMER_PHONE, ADDRESS_ID, CUSTOMER_CREATION_DATE,CUSTOMER_USERNAME, CUSTOMER_GENDER

ORDER_HEADER- ORDER_ID, CUSTOMER_ID, ORDER_DATE, ORDER_STATUS, PAYMENT_MODE, PAYMENT_DATE, ORDER_SHIPMENT_DATE,SHIPPER_ID

ORDER_ITEMS- ORDER_ID, PRODUCT_ID, PRODUCT_QUANTITY

PRODUCT- PRODUCT_ID, PRODUCT_DESC, PRODUCT_CLASS_CODE, PRODUCT_PRICE, PRODUCT_QUANTITY_AVAIL, LEN, WIDTH, HEIGHT, WEIGHT

PRODUCT_CLASS- PRODUCT_CLASS_CODE, PRODUCT_CLASS_DESC

Can anyone help me on how to filter pincodes without any zeros in it and order status as shipped.

答:
Test if no zeros exist

where length(replace(pincode,'0','')) = length(pincode)

or

where instr(pincode,'0') = 0

or you could use regex or test valid pincodes by downloading and validating


问:
Using *ngFor to loop through an array and *ngIf to select which elements from the array to list
I'm trying to use *ngFor to loop through an array of objects. I realized I couldn't use *ngFor and an *ngIf on the same element, it would return an error. Instead, I tried to stick my *ngIf on the contents of the list item. But now, I'm getting a bunch of empty list items and they're being created and displayed on my view page.

I don't want to stick the *ngFor on my
 element because then it will create a bunch of
 elements with a single list item within each.

I'm hoping one of you will have another method of implementing this.

```<code>// AppComponent
// contacts: Contact[];  // An array of `Contact` Objects

<ul>
  <li *ngFor="#contact of contacts">
    <contact-detail *ngIf="checkList(contact) == true" [contact]="contact"></contact-detail>
  </li>
</ul>
</code>```

and...

```<code>// ContactDetailComponent
<img />
<span>{{contact.name}}</span>
<span>{{contact.email}}</span>
</code>```

What is happening:

```<code><ul>
  <li>
    <!--template bindings={}-->  // ngIf conditional returned true
    <img />
    <span>Name1</span>
    <span>Email1</span>
  </li>
  <li>
    <!--template bindings={}-->   // ngIf conditional returned false
  </li>
  <li>
    <!--template bindings={}-->  // false
  </li>
  <li>
    <!--template bindings={}-->  // true
    <img />
    <span>Name1</span>
    <span>Email1</span>
  </li>
</ul>
</code>```

I'm using Material Design Lite, so all these elements will have some css properties. Empty
 just return an empty space of a certain height.

Also, if other information is needed, please let me know.

答:
Sasxa's answer didn't work for me at 2022. You can use ng-template instead of template to get the same result.</p>
```<code><ul>
    <ng-template ngFor let-item [ngForOf]="calcService.myDataArray">
        <li *ngIf="item.esTarifa === true">
            {{item.id}}
        </li>
    </ng-template>
</ul>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use *ngFor to loop through an array of objects. I realized I couldn't use *ngFor and an *ngIf on the same element, it would return an error. Instead, I tried to stick my *ngIf on the contents of the list item. But now, I'm getting a bunch of empty list items and they're being created and displayed on my view page.

I don't want to stick the *ngFor on my
 element because then it will create a bunch of
 elements with a single list item within each.

I'm hoping one of you will have another method of implementing this.

// AppComponent
// contacts: Contact[];  // An array of `Contact` Objects

    <contact-detail *ngIf="checkList(contact) == true" [contact]="contact"></contact-detail>

and...

// ContactDetailComponent

{{contact.name}}
{{contact.email}}

What is happening:

      // ngIf conditional returned true

    Name1
    Email1

       // ngIf conditional returned false

      // false

      // true

    Name1
    Email1

I'm using Material Design Lite, so all these elements will have some css properties. Empty
 just return an empty space of a certain height.

Also, if other information is needed, please let me know.

Body:
Sasxa's answer didn't work for me at 2022. You can use ng-template instead of template to get the same result.

<ul>
    <ng-template ngFor let-item [ngForOf]="calcService.myDataArray">
        <li *ngIf="item.esTarifa === true">
            {{item.id}}
        </li>
    </ng-template>
</ul>


问:
Creating an object array in foreach
i am struggeling to create an object array from two input-groups,
each group has 3 inputs with data-side = left/right
each input has class "elm" and data-pos = a/b/c

```<code><input class="elm-left elm" name="l1" data-pos="a" data-side="left"/>
<input class="elm-left elm" name="l2" data-pos="b" data-side="left"/>
<input class="elm-left elm" name="l3" data-pos="c" data-side="left"/>

<input class="elm-right elm" name="r1" data-pos="a" data-side="right"/>
<input class="elm-right elm" name="r2" data-pos="b" data-side="right"/>
<input class="elm-right elm" name="r3" data-pos="c" data-side="right"/>
</code>```

desired output is:

```<code>[
 {
  "name":"title1",
  "data":[
   {
    "left" :{"A":10,"B":10,"C":10},
    "right":{"A":20,"B":20,"C":20}
   }
  ]
 }
]
</code>```

my output is:

```<code>...,"data":[
 {
  "left":{"A":20,"B":20,"C":20},
  "right":{"A":20,"B":20,"C":20}
 }
]
</code>```
```<code>var sides = {};
var info  = {};
$(".elm").each(function () {

  var pos   = $(this).data('pos').toUpperCase(); //a,b,c
  var side  = $(this).data('side'); //left, right
  var val   = $(this).val();

  info[[pos]] = val;

  sides[side] = info;
});

data.push(sides);
</code>```

答:
You need to initialise a new object for info[side] before you can use info[side][pos]

```<code>info[side] = info[side] || {}
</code>```

this is a common pattern to either use the existing value if there is one or create a new one object if needed.

You can then use this object directly without the need for the info variable which was getting re-used for different sets of values.

var sides = {};

$(".elm").each(function () {

  var pos   = $(this).data('pos').toUpperCase(); //a,b,c
  var side  = $(this).data('side'); //left, right
  var val   = $(this).val();

  sides[side] = sides[side] || {};
  sides[side][pos] = val;
});

var output = { name: "title1", data: [] };
output.data.push(sides);

console.log(JSON.stringify(output))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="elm-left elm" name="l1" data-pos="a" data-side="left" value="20"/>
<input class="elm-left elm" name="l2" data-pos="b" data-side="left" value="20"/>
<input class="elm-left elm" name="l3" data-pos="c" data-side="left" value="20"/>

<input class="elm-right elm" name="r1" data-pos="a" data-side="right" value="20"/>
<input class="elm-right elm" name="r2" data-pos="b" data-side="right" value="20"/>
<input class="elm-right elm" name="r3" data-pos="c" data-side="right" value="20"/></code>```

Title: Creating an object array in foreach

Body:
i am struggeling to create an object array from two input-groups,
each group has 3 inputs with data-side = left/right
each input has class "elm" and data-pos = a/b/c

<input class="elm-left elm" name="l1" data-pos="a" data-side="left"/>
<input class="elm-left elm" name="l2" data-pos="b" data-side="left"/>
<input class="elm-left elm" name="l3" data-pos="c" data-side="left"/>

<input class="elm-right elm" name="r1" data-pos="a" data-side="right"/>
<input class="elm-right elm" name="r2" data-pos="b" data-side="right"/>
<input class="elm-right elm" name="r3" data-pos="c" data-side="right"/>

desired output is:

[
 {
  "name":"title1",
  "data":[
   {
    "left" :{"A":10,"B":10,"C":10},
    "right":{"A":20,"B":20,"C":20}
   }
  ]
 }
]

my output is:

...,"data":[
 {
  "left":{"A":20,"B":20,"C":20},
  "right":{"A":20,"B":20,"C":20}
 }
]

var sides = {};
var info  = {};
$(".elm").each(function () {

  var pos   = $(this).data('pos').toUpperCase(); //a,b,c
  var side  = $(this).data('side'); //left, right
  var val   = $(this).val();

  info[[pos]] = val;

  sides[side] = info;
});

data.push(sides);

Body:
You need to initialise a new object for info[side] before you can use info[side][pos]

info[side] = info[side] || {}

this is a common pattern to either use the existing value if there is one or create a new one object if needed.

You can then use this object directly without the need for the info variable which was getting re-used for different sets of values.

var sides = {};

$(".elm").each(function () {

  var pos   = $(this).data('pos').toUpperCase(); //a,b,c
  var side  = $(this).data('side'); //left, right
  var val   = $(this).val();

  sides[side] = sides[side] || {};
  sides[side][pos] = val;
});

var output = { name: "title1", data: [] };
output.data.push(sides);

console.log(JSON.stringify(output))

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="elm-left elm" name="l1" data-pos="a" data-side="left" value="20"/>
<input class="elm-left elm" name="l2" data-pos="b" data-side="left" value="20"/>
<input class="elm-left elm" name="l3" data-pos="c" data-side="left" value="20"/>

<input class="elm-right elm" name="r1" data-pos="a" data-side="right" value="20"/>
<input class="elm-right elm" name="r2" data-pos="b" data-side="right" value="20"/>
<input class="elm-right elm" name="r3" data-pos="c" data-side="right" value="20"/>


问:
Auto advance input fields (multi-part serial number)
I'm trying to build a 4-part serial number input that auto-advances for each chunk of the serial number.

e.g. 1-384-3884-39

Also, how would I add the strings together into one string on submit?

答:
I found this codepen quite impressive:
It has support for:

digit-only input or mixed input (letters+digits)

(uncomment code if you need)

copy-pasting serial code

checking the whole serial code for input errors

(e.g. no only last box filled)

It has no getter code provided - here is on possible implementation of me:

```<code><button onclick="evalResults(event)"> evalResults </button>

<script>
function evalResults(e) {
    e.preventDefault();

let serial = '';
for(let i = 0; ++i <= valueLen / inputLen;) {
    let serial_fragment = document.querySelector('.def-txt-input[name="chars[' + i + ']"]');
    serial_fragment = serial_fragment.value.toString();
    if (serial_fragment.length != inputLen) {
      // invalid input - too few letters/digits
      serial = undefined;
      break;
    }
    serial += serial_fragment;
}

// serial: string if valid input
//         undefined if invalid input
if (serial !== undefined) // valid input
    alert('The serial is: ' + serial);
else // serial === undefined
    alert('Invalid serial code');

}
</script>
</code>```

The code from codepen.io:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-12">
      <p>Paste the following in the first input or type</p>
      <p>9847FG28RT038L71EE7U</p>
    </div>
    <div class="col-xs-12">
      <form class="form">
          <div class="form-group">
            <div class="col-xs-12">
              <label>Serial Number: </label>
            </div>

            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[1]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[2]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[3]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[4]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[5]"> </div>
        </div>
    </div>
  </div>
</div>
</code>```
```<code>var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
var valueLen = 20;
var inputLen = 4;

// Autotab replaces all the old code below
// https://github.com/Mathachew/jquery-autotab
$inputs.autotab({ format: 'alphanumeric', uppercase: true });

// Prevents user from manually entering non-digits.
/*
$inputs.on("input.fromManual", function(){
    if(!intRegex.test($(this).val())){
        $(this).val("");
    }
});
*/

// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
/*
$inputs.on("paste", function() {
    var $this = $(this);
    var originalValue = $this.val();

    $this.val("");

    $this.one("input.fromPaste", function(){
        $currentInputBox = $(this);

        var pastedValue = $currentInputBox.val();

        if (pastedValue.length == valueLen && intRegex.test(pastedValue)) {
            pasteValues(pastedValue);
        }
        else {
            $this.val(originalValue);
        }

        $inputs.attr("maxlength", inputLen);
    });

    $inputs.attr("maxlength", valueLen);
});

*/
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
  // we split the original value in parts of inputLen length
    var re = new RegExp('.{1,'+inputLen+'}','g');
    var values = element.match(re);

    $(values).each(function(index) {
        var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
        $inputBox.val(values[index])
    });
};
</code>```

It has following dependencies (you may want to use it without the stylesheet):

```<code><link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery-autotab/1.9.2/js/jquery.autotab.min.js'></script>
</code>```

Body:
I found this codepen quite impressive:
It has support for:

digit-only input or mixed input (letters+digits)

(uncomment code if you need)

copy-pasting serial code

checking the whole serial code for input errors

(e.g. no only last box filled)

It has no getter code provided - here is on possible implementation of me:

<button onclick="evalResults(event)"> evalResults </button>

<script>
function evalResults(e) {
    e.preventDefault();

let serial = '';
for(let i = 0; ++i <= valueLen / inputLen;) {
    let serial_fragment = document.querySelector('.def-txt-input[name="chars[' + i + ']"]');
    serial_fragment = serial_fragment.value.toString();
    if (serial_fragment.length != inputLen) {
      // invalid input - too few letters/digits
      serial = undefined;
      break;
    }
    serial += serial_fragment;
}

// serial: string if valid input
//         undefined if invalid input
if (serial !== undefined) // valid input
    alert('The serial is: ' + serial);
else // serial === undefined
    alert('Invalid serial code');

}
</script>

The code from codepen.io:

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <p>Paste the following in the first input or type</p>
      <p>9847FG28RT038L71EE7U</p>
    </div>
    <div class="col-xs-12">
      <form class="form">
          <div class="form-group">
            <div class="col-xs-12">
              <label>Serial Number: </label>
            </div>

            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[1]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[2]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[3]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[4]"> </div>
            <div class="col-xs-2"><input type="text" maxlength="4" class="def-txt-input form-control" name="chars[5]"> </div>
        </div>
    </div>
  </div>
</div>

var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
var valueLen = 20;
var inputLen = 4;

// Autotab replaces all the old code below
// https://github.com/Mathachew/jquery-autotab
$inputs.autotab({ format: 'alphanumeric', uppercase: true });

// Prevents user from manually entering non-digits.
/*
$inputs.on("input.fromManual", function(){
    if(!intRegex.test($(this).val())){
        $(this).val("");
    }
});
*/

// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
/*
$inputs.on("paste", function() {
    var $this = $(this);
    var originalValue = $this.val();

    $this.val("");

    $this.one("input.fromPaste", function(){
        $currentInputBox = $(this);

        var pastedValue = $currentInputBox.val();

        if (pastedValue.length == valueLen && intRegex.test(pastedValue)) {
            pasteValues(pastedValue);
        }
        else {
            $this.val(originalValue);
        }

        $inputs.attr("maxlength", inputLen);
    });

    $inputs.attr("maxlength", valueLen);
});

*/
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
  // we split the original value in parts of inputLen length
    var re = new RegExp('.{1,'+inputLen+'}','g');
    var values = element.match(re);

    $(values).each(function(index) {
        var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
        $inputBox.val(values[index])
    });
};

It has following dependencies (you may want to use it without the stylesheet):

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery-autotab/1.9.2/js/jquery.autotab.min.js'></script>


问:
Perform same task on multiple objects in the environment using for loop
I have these data:

```<code>u1 <- 'www.link1.com'
u2 <- 'www.link2.com'
u3 <- 'www.link3.com'
u4 <- 'www.link4.com'
</code>```

I want to do some work on them, how can I use for-loop to do this?!

```<code>for (i in u1 : ur4)
{
  texti <- gettxt(i)
}
</code>```

答:
You can use a sapply with get to obtain the value of the object.

The first argument of sapply depends on how many urls do you have.

```<code>sapply(1:4, function(x) gettext(get(paste0("u", x))))
[1] "www.link1.com" "www.link2.com" "www.link3.com" "www.link4.com"
</code>```

Updated

If you wish to export the gettxt results to individual vectors, you can use the following (note that lapply is used here instead of sapply):

```<code>setNames(lapply(1:4, function(x) gettxt(get(paste0("u", x)))), paste0("u", 1:4, "_txt")) %>%
  list2env(envir = globalenv())
</code>```

Where it'll output four vectors with the names as u1_txt to u4_txt

```<code>grep("^u", ls(), value = T)
[1] "u1"     "u1_txt" "u2"     "u2_txt" "u3"     "u3_txt" "u4"
[8] "u4_txt"
</code>```

Example

I've used some dummy sites to test the codes.

```<code>u1 <- "https://CRAN.R-project.org/package=htm2txt"
u2 <- "https://CRAN.R-project.org/package=dplyr"
u3 <- "https://CRAN.R-project.org/package=tidyverse"
u4 <- "https://CRAN.R-project.org/package=tidyr"

setNames(lapply(1:4, function(x) gettxt(get(paste0("u", x)))), paste0("u", 1:4, "_txt")) %>%
  list2env(envir = globalenv())

grep("^u", ls(), value = T)
[1] "u1"     "u1_txt" "u2"     "u2_txt" "u3"     "u3_txt" "u4"
[8] "u4_txt"

u1_txt
[1] "htm2txt: Convert Html into Text\n\nConvert a html document to simple plain texts by removing all html tags. This package utilizes regular expressions to strip off html tags. It also offers gettxt() and browse() function, which enables you to get or browse texts at a certain web page.\n\nVersion: 2.1.1\n\nDepends: R (≥ 3.0.0)\n\nPublished: 2017-10-19\n\nAuthor: Sangchul Park [aut, cre]\n\nMaintainer: Sangchul Park <mail at sangchul.com>\n\nBugReports: https://github.com/sangchulpark/htm2txt/issues\n\nLicense: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]\n\nURL: https://github.com/sangchulpark\n\nNeedsCompilation: no\n\nIn views: WebTechnologies\n\nCRAN checks: htm2txt results\n\nDocumentation:\n\nReference manual: htm2txt.pdf\n\nDownloads:\n\nPackage source: htm2txt_2.1.1.tar.gz\n\nWindows binaries: r-devel: htm2txt_2.1.1.zip, r-release: htm2txt_2.1.1.zip, r-oldrel: htm2txt_2.1.1.zip\n\nmacOS binaries: r-release (arm64): htm2txt_2.1.1.tgz, r-release (x86_64): htm2txt_2.1.1.tgz, r-oldrel: htm2txt_2.1.1.tgz\n\nOld sources: htm2txt archive\n\nReverse dependencies:\n\nReverse imports: getDEE2\n\nLinking:\n\nPlease use the canonical form https://CRAN.R-project.org/package=htm2txt to link to this page."
</code>```

Body:
I have these data:

u1 <- 'www.link1.com'
u2 <- 'www.link2.com'
u3 <- 'www.link3.com'
u4 <- 'www.link4.com'

I want to do some work on them, how can I use for-loop to do this?!

for (i in u1 : ur4)
{
  texti <- gettxt(i)
}

Body:
You can use a sapply with get to obtain the value of the object.

The first argument of sapply depends on how many urls do you have.

sapply(1:4, function(x) gettext(get(paste0("u", x))))
[1] "www.link1.com" "www.link2.com" "www.link3.com" "www.link4.com"

Updated

If you wish to export the gettxt results to individual vectors, you can use the following (note that lapply is used here instead of sapply):

setNames(lapply(1:4, function(x) gettxt(get(paste0("u", x)))), paste0("u", 1:4, "_txt")) %>%
  list2env(envir = globalenv())

Where it'll output four vectors with the names as u1_txt to u4_txt

grep("^u", ls(), value = T)
[1] "u1"     "u1_txt" "u2"     "u2_txt" "u3"     "u3_txt" "u4"
[8] "u4_txt"

Example

I've used some dummy sites to test the codes.

u1 <- "https://CRAN.R-project.org/package=htm2txt"
u2 <- "https://CRAN.R-project.org/package=dplyr"
u3 <- "https://CRAN.R-project.org/package=tidyverse"
u4 <- "https://CRAN.R-project.org/package=tidyr"

setNames(lapply(1:4, function(x) gettxt(get(paste0("u", x)))), paste0("u", 1:4, "_txt")) %>%
  list2env(envir = globalenv())

grep("^u", ls(), value = T)
[1] "u1"     "u1_txt" "u2"     "u2_txt" "u3"     "u3_txt" "u4"
[8] "u4_txt"

u1_txt
[1] "htm2txt: Convert Html into Text\n\nConvert a html document to simple plain texts by removing all html tags. This package utilizes regular expressions to strip off html tags. It also offers gettxt() and browse() function, which enables you to get or browse texts at a certain web page.\n\nVersion: 2.1.1\n\nDepends: R (≥ 3.0.0)\n\nPublished: 2017-10-19\n\nAuthor: Sangchul Park [aut, cre]\n\nMaintainer: Sangchul Park <mail at sangchul.com>\n\nBugReports: https://github.com/sangchulpark/htm2txt/issues\n\nLicense: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]\n\nURL: https://github.com/sangchulpark\n\nNeedsCompilation: no\n\nIn views: WebTechnologies\n\nCRAN checks: htm2txt results\n\nDocumentation:\n\nReference manual: htm2txt.pdf\n\nDownloads:\n\nPackage source: htm2txt_2.1.1.tar.gz\n\nWindows binaries: r-devel: htm2txt_2.1.1.zip, r-release: htm2txt_2.1.1.zip, r-oldrel: htm2txt_2.1.1.zip\n\nmacOS binaries: r-release (arm64): htm2txt_2.1.1.tgz, r-release (x86_64): htm2txt_2.1.1.tgz, r-oldrel: htm2txt_2.1.1.tgz\n\nOld sources: htm2txt archive\n\nReverse dependencies:\n\nReverse imports: getDEE2\n\nLinking:\n\nPlease use the canonical form https://CRAN.R-project.org/package=htm2txt to link to this page."


问:
Order by best match of string column in EF Core
I am implementing a search feature for the users in our api. The search will query our db to fetch the first N users matching the search term. I want to order the user after "best match" so the most relevant user is on top.

What I'd like to do is something like:

```<code>var users = await _dbContext.Users
   .IncludeUserData()
   .Where(u => u.Name.Contains(searchTerm))
   .OrderBy(u => u.Name.IndexOf(searchTerm)) <- This row is not possible
   .ToListAsync();
</code>```

Where basically a name that contains the search term early is ordered before a user whose name contains the term late.

E.g.
Simon Carlsson should come before Carl Simonsson if the searchTerm is "Simon"

Using SQL Server as the DB provider

How would I achieve an order by query where users with names better matching the searchTerm are sorted higher up in the list?

答:
After some more searching this method of importing functions from the DB provider was found:

```<code>[DbFunction("CHARINDEX", IsBuiltIn = true)]
public static long CHARINDEX(string substring, string str)
{
    throw new NotImplementedException();
}
</code>```

Put this in user dbContext class. It will bind to the CHARINDEX function in SQL Server.
https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping

Then use it to sort the query:

```<code>.sortBy(u => DbContext.CHARINDEX(searchTerm, u.name))
</code>```

Body:
I am implementing a search feature for the users in our api. The search will query our db to fetch the first N users matching the search term. I want to order the user after "best match" so the most relevant user is on top.

What I'd like to do is something like:

var users = await _dbContext.Users
   .IncludeUserData()
   .Where(u => u.Name.Contains(searchTerm))
   .OrderBy(u => u.Name.IndexOf(searchTerm)) <- This row is not possible
   .ToListAsync();

Where basically a name that contains the search term early is ordered before a user whose name contains the term late.

E.g.
Simon Carlsson should come before Carl Simonsson if the searchTerm is "Simon"

Using SQL Server as the DB provider

How would I achieve an order by query where users with names better matching the searchTerm are sorted higher up in the list?

Body:
After some more searching this method of importing functions from the DB provider was found:

[DbFunction("CHARINDEX", IsBuiltIn = true)]
public static long CHARINDEX(string substring, string str)
{
    throw new NotImplementedException();
}

Put this in user dbContext class. It will bind to the CHARINDEX function in SQL Server.
https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping

Then use it to sort the query:

.sortBy(u => DbContext.CHARINDEX(searchTerm, u.name))


问:
How to avoid primary key clashes when merging two identical tables with a view
I have a central database and a unique database for a project I am working on.  The central database allows me to provide users with default options and data.

The unique database matches the central database structure to allow users own customized data.  I have views that union each identical table pair.

The "primary key" field in each view is set as a primary key in the dbml I am using (Linq-to-sql).  I then add associations to other tables in the dbml.

This means that I cannot set both tables to auto-increment with a base of 0, because the primary keys are used as "foreign keys" in unique db tables (I know they're not strictly foreign keys in this instance).

Therefore in the view, I need all records from each table pair to have a unique primary key.

I have thought about setting the unique database pk base number at 1000000 or something, but this eventually may backfire on me when the global database (0 base) caught up.

I also though about prefixing each with a number in the view, e.g.

Global: 11, 12, 13, 14, 15, 16, 17, 18, 19, 110 ,111
Unique: 21, 22, 23, 24, 25, 26, 27, 28, 29, 210, 211

I am worried how this may affect performance when querying,  this has to be as efficient as possible.

Not sure of the best method?

答:
Just actually had another idea:

I could set the unique to base 1 increment 2 and the global base 2 increment 2.  This way, there is no crazy hack and the pk's will never clash


问:
Sending mails everyday using schedulers in Laravel
I am not receiving any email. Please help me out. I have changed the environment properly.

```<code>use App\User;
use App\Mail\NotifyEmail;

class Notify extends Command
{
    protected $signature = 'notify:email';
    protected $description = 'Send an email to all the users everyday';
    public function handle()
    {
        $emails = User::pluck('email')->toArray();
        $data = ['title' => 'programming' , 'body' => 'php'];
        foreach($emails as $email){
            Mail::To($email) ->send(new NotifyEmail($data));
        }
    }
}

</code>```

My kernel.php has :

```<code>$schedule->command('notify:email') ->daily();
</code>```

App\Mail\NotifyEmail.php :

```<code>class NotifyEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $details;
    public function __construct($data)
    {
        $this -> details = $data;
    }

    public function build()
    {
        return $this->view('mail', compact(varname: 'details'));
    }
}
</code>```

mail.blade.php contains {{$details['title']}} and {{$details['body']}}.

答:
have you setup the cron job in crontab? if not nothing would run

read https://laravel.com/docs/8.x/scheduling#running-the-scheduler

Body:
I am not receiving any email. Please help me out. I have changed the environment properly.

use App\User;
use App\Mail\NotifyEmail;

class Notify extends Command
{
    protected $signature = 'notify:email';
    protected $description = 'Send an email to all the users everyday';
    public function handle()
    {
        $emails = User::pluck('email')->toArray();
        $data = ['title' => 'programming' , 'body' => 'php'];
        foreach($emails as $email){
            Mail::To($email) ->send(new NotifyEmail($data));
        }
    }
}

My kernel.php has :

$schedule->command('notify:email') ->daily();

App\Mail\NotifyEmail.php :

class NotifyEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $details;
    public function __construct($data)
    {
        $this -> details = $data;
    }

    public function build()
    {
        return $this->view('mail', compact(varname: 'details'));
    }
}

mail.blade.php contains {{$details['title']}} and {{$details['body']}}.


问:
Reverse looping a triangle problem deleting string character
```<code>for (let i = "#"; i.length < 10; i+="#"){
  console.log(i);

}
for (let y = "*********"; y.length >0; y-="*"){
    console.log(y);
}
</code>```

The first part is  Eloquent JavaScript exercise. I wanted to make another loop starts from end of the first loop. The first loops ends with "########" and my other loop will start same amount of "#" but with "" and it should decrease until it has one "". So it would be reverse triangle like this:

```<code>#
##
**
*
</code>```

I wanted to make it as simple as first loop. My question is can we make it like the first loop? And why "-=" is not working?

答:
You can not modify a string using -= operator. Use y = y.slice(0, -1) instead:

for (let i = "#"; i.length < 10; i += "#") {
  console.log(i);

}
for (let y = "*********"; y.length > 0; y = y.slice(0, -1)) {
  console.log(y);
}```

More info here!

Body:
for (let i = "#"; i.length < 10; i+="#"){
  console.log(i);

}
for (let y = "*********"; y.length >0; y-="*"){
    console.log(y);
}

The first part is  Eloquent JavaScript exercise. I wanted to make another loop starts from end of the first loop. The first loops ends with "########" and my other loop will start same amount of "#" but with "" and it should decrease until it has one "". So it would be reverse triangle like this:

#
##
**
*

I wanted to make it as simple as first loop. My question is can we make it like the first loop? And why "-=" is not working?

Body:
You can not modify a string using -= operator. Use y = y.slice(0, -1) instead:

for (let i = "#"; i.length < 10; i += "#") {
  console.log(i);

}
for (let y = "*********"; y.length > 0; y = y.slice(0, -1)) {
  console.log(y);
}

More info here!


问:
Python: function that exclude negative values from list and give back new list
I have list of numbers.
I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me.
Could you please suggest something.

This is the code which is working but it's loop:

```<code>new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

</code>```

This function does not work. It gives me None.

```<code>
data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)
</code>```

答:
Use a simple comprehension:

```<code>data3 = [i for i in data2 if i > 0]
print(data3)

# Output
[10, 32, 454, 31, 53, 31314, 53, 10]
</code>```

For your function, data.append return nothing so you return None:

```<code>def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            new_list.append(i)
    return new_list  # <- HERE
</code>```

Usage:

```<code>data3 = preprocessing(data2)
print(data3)

# Output
[10, 32, 454, 31, 53, 31314, 53, 10]
</code>```

Body:
I have list of numbers.
I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me.
Could you please suggest something.

This is the code which is working but it's loop:

new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

This function does not work. It gives me None.

data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)

Body:
Use a simple comprehension:

data3 = [i for i in data2 if i > 0]
print(data3)

# Output
[10, 32, 454, 31, 53, 31314, 53, 10]

For your function, data.append return nothing so you return None:

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            new_list.append(i)
    return new_list  # <- HERE

Usage:

data3 = preprocessing(data2)
print(data3)

# Output
[10, 32, 454, 31, 53, 31314, 53, 10]


问:
Streaming video of my WPF application
I have a simple digital signage solution with a presentation application in WPF. I would like to "monitor" it from my remote machine. I would like to send a stream of the content the application is showing now (images, video, userControls, etc.).

How to do this, do i need to manually take a screenshot and send it in a video stream to my monitor - how to encode it into a stream the monitoring application can playback (that one is also WPF).

答:
Ok, if snapshots are ok then I've done this before. The way I did it was to take a "screenshot" of the app (using code you can find here: http://www.grumpydev.com/2009/01/03/taking-wpf-screenshots/ ) then have the signage app spin up a webservice (HttpListener, WCF or SelfHosted Nancy) that returns the current screen whenever a request is made to a particular url. You monitor app then polls that url however often you need to.

This was done to monitor an interactive game for a Surface device, and didn't seem to cause any perf issues, so should be fine for your needs.

Title: Streaming video of my WPF application


问:
Inserting variable into string, not working
So i am trying to put value inside this text

```<code>fp = str("""```yaml\nThe floor price is {floor_price} ETH.```""")
</code>```

i tried the f string but it gives error

edit: i fixed with f string after trying for long

答:
You can do it with the plus sign(+)</p>
```<code>fp = "yaml\nThe floor price is " + str(floor_price) + " ETH."
</code>```

Body:
So i am trying to put value inside this text

fp = str("""```yaml\nThe floor price is {floor_price} ETH.```""")

i tried the f string but it gives error

edit: i fixed with f string after trying for long

Body:
You can do it with the plus sign(+)

fp = "yaml\nThe floor price is " + str(floor_price) + " ETH."


Title: creating frequency table for labelled data

Body:
I am trying to create a table for multiple response database but its not showing the all output.
its showing only total frequency.

library(expss)
data<-data.frame(
  gender = c(1,2,1,2,1,2,1,2,2,2,2,1,1,2,2,2,2,1,1,1,1,1,2,1,2,1,2,2,2,1,2,1,2,1,2,1,2,2,2),
  sector = c(3,3,1,2,5,4,4,4,4,3,3,4,3,4,2,1,4,2,3,4,4,4,3,1,2,1,5,5,4,3,1,4,5,2,3,4,5,1,4),
  col1=c(1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,0,0,0,1,0,0,0,0,1,0,1),
  col2=c(1,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0,0),
  col3=c(1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0,1,1,1,1,1,0,0,1),
  col4=c(1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  col5=c(1,2,1,1,1,2,1,2,2,1,2,1,1,1,2,2,2,1,1,1,2,1,2,1,1,1,2,2,2,1,1,2,2,1,1,1,2,2,2)
)

data$gender<-factor(data$gender, levels=c(1,2), labels=c("Male","female"))
data$sector<-factor(data$sector, levels=c(1,2,3,4,5), labels=c("TX","CA","NY","LA","WA"))
data$col1<-factor(data$col1, levels=1, labels="Sales")
data$col2<-factor(data$col2, levels=1, labels="OPS")
data$col3<-factor(data$col3, levels=1, labels="Management")
data$col4<-factor(data$col4, levels=1, labels="HR")
data$col5<-factor(data$col5, levels=c(1,2), labels=c("National","Overseas"))

data$gender1 <- ifelse(data$gender == "Male",1,0)
data$total <- ifelse(data$col5 == "National",1,0)

data <- data
var_list <- c("col1","col2","col3")
my_fre <- function(curr_var) setNames(expss::fre(curr_var)[, 1:3],
                                      c("row_labels", "Count N", "Valid percent"))

cross_fun_df(data, list(as.category(col1 %to% col3)),lst, fun = my_fre)

Body:
Do you want something like this?

library(tidyverse)

data <- data.frame(
  gender = c(1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2),
  sector = c(3, 3, 1, 2, 5, 4, 4, 4, 4, 3, 3, 4, 3, 4, 2, 1, 4, 2, 3, 4, 4, 4, 3, 1, 2, 1, 5, 5, 4, 3, 1, 4, 5, 2, 3, 4, 5, 1, 4),
  col1 = c(1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1),
  col2 = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0),
  col3 = c(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1),
  col4 = c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
  col5 = c(1, 2, 1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2)
)

data$gender <- factor(data$gender, levels = c(1, 2), labels = c("Male", "female"))
data$sector <- factor(data$sector, levels = c(1, 2, 3, 4, 5), labels = c("TX", "CA", "NY", "LA", "WA"))
data$col1 <- factor(data$col1, levels = 1, labels = "Sales")
data$col2 <- factor(data$col2, levels = 1, labels = "OPS")
data$col3 <- factor(data$col3, levels = 1, labels = "Management")
data$col4 <- factor(data$col4, levels = 1, labels = "HR")
data$col5 <- factor(data$col5, levels = c(1, 2), labels = c("National", "Overseas"))

data$gender1 <- ifelse(data$gender == "Male", 1, 0)
data$total <- ifelse(data$col5 == "National", 1, 0)

data %>%
  mutate(across(everything(), as.character)) %>%
  pivot_longer(everything()) %>%
  count(name, value) %>%
  group_by(name) %>%
  mutate(perc = n / sum(n) * 100)
#> # A tibble: 21 x 4
#> # Groups:   name [9]
#>    name  value          n  perc
#>    <chr> <chr>      <int> <dbl>
#>  1 col1  Sales         12 30.8
#>  2 col1  <NA>          27 69.2
#>  3 col2  OPS           25 64.1
#>  4 col2  <NA>          14 35.9
#>  5 col3  Management    14 35.9
#>  6 col3  <NA>          25 64.1
#>  7 col4  HR             3  7.69
#>  8 col4  <NA>          36 92.3
#>  9 col5  National      21 53.8
#> 10 col5  Overseas      18 46.2
#> # … with 11 more rows

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


问:
Automate AWS SSM document execution
I have an AWS SSM document shared from another account, to install a software on an EC2 instance. Since there are auto-scaled EC2 instances, depending on the demand, new instances spin up.

Requirement is to automate this document execution on all the SSM Managed EC2 instances every day at a specified time, so that no EC2 instance will be left out without the required software.

What are the ways I can use here? I tried using the Run Command feature, but the name of document does not show up in the list.

答:
You can use SSM State Manager to automate the execution of that SSM document
https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-state.html</p>

Title: Automate AWS SSM document execution


问:
EDIT: How to import MP3 files in React app
UPDATE
The problem lied with my lack of knowledge in the environment I was working on but the answers given below should be useful for others with similar problems.

EDIT: As it seems the problem is that there's something funky going on with trying to import my mp3 to my React app/component.
The current issues is that when I try to use:

 import soundfile from "../neure-resources/test.mp3"

I end up with an error of:

"Cannot find module "../neure-resources/test.mp3"

Solving this issue for any other import of an component would be to make sure that the component that is being imported has also been defined to be exportable but how would one go about doing this to an MP3-file?

So to start with I'm not sure if my problem has to do with importing/linking my mp3 file OR with how to play audio clips in React (or something else). I will edit the title once we figure out what my issue exactly is.

So I have an app where I have a button on the web page that the user can push to play a mp3-file. Simple stuff but I'm running constantly into the following error:

HTTP load failed with status 404. Load of media resource "..." failed.

Now while I am not super proficient in file paths etc. I'd figure by looking at guides and examples I could figure it out, but I haven't been able to.

My abbreviated file structure is something like (check bottom of post for more detailed description):

student/src/components

and under components I have my actual app in a folder and another folder under components where I planned to store my "resources" so:

components/my-app-folder/my-actual-app.tsx

components/my-resources/my.mp3

For the filepath as I understood

".."

signifies for the path to start from one folder above the current location which would be my

"/components" -folder

and my resources folder is under the component folder so I figured that should be fine.
I looked up a few other SO questions about playing audio in React and found a question that suggested roughly the following:

Inside my

render()

```<code>let path = "../my-resources/test.mp3";
let audio = new Audio(path);
</code>```

And then for the JSX part:

```<code>audioPlayer = (
            <div className="count-number-equivelance-audioPlayer">
                <button id="equivalence-audio-button" onClick={() => audio.play()}>Soundclip!</button>
            </div>
        );
</code>```

I've tried:

    let path = "../my-resources/test.mp3";

and

    let path = "../../my-resources/test.mp3";

as I wasn't sure if one ".." pointed to the folder the actual app was nested in and required another ".." to actual point at the "components" folder but both of them produce the same error. I also tried using the whole path and moving the mp3 around to the same folder as the app itself but got the same result.

So I am thoroughly confused as to if I just suck at using external resources in my app or is my actual code and/or knowledge of React to blame here. The error I receive would lead me to believe that the resource isn't being located properly but I'm not sure if that's just a side effect of faulty code.

EDIT: I'm also working in a virtual environment, running my own stack locally if that makes some difference to the situation.

Also for reference a picture of the file tree:

The files opened in the picture contain the app in question and the resource it's trying to use:

The path leading up to components is the following (pic would be really big if I tried to grab the whole path in one picture).

/Users/"name of user"/arvio/client/student/src/components

答:
Inside the src/react-app-env.d.ts add this:

```<code>/// <reference types="react-scripts" />
declare module '*.mp3'; // '*.wav' if you're using wav format
</code>```

Now you can use it like this:

```<code>import beep from './assets/beep.mp3';

const alarm = new Audio(beep);
</code>```

By default, TypeScript won't allow you to import an audio file, so you need to declare it yourself.

This file react-app-env.d.ts references TypeScript types declarations that are specific to projects started with Create React App. By default, it only adds support for importing bmp, gif, jpeg, jpg, png, webp, and svg.

Body:
UPDATE
The problem lied with my lack of knowledge in the environment I was working on but the answers given below should be useful for others with similar problems.

EDIT: As it seems the problem is that there's something funky going on with trying to import my mp3 to my React app/component.
The current issues is that when I try to use:

 import soundfile from "../neure-resources/test.mp3"

I end up with an error of:

"Cannot find module "../neure-resources/test.mp3"

Solving this issue for any other import of an component would be to make sure that the component that is being imported has also been defined to be exportable but how would one go about doing this to an MP3-file?

So to start with I'm not sure if my problem has to do with importing/linking my mp3 file OR with how to play audio clips in React (or something else). I will edit the title once we figure out what my issue exactly is.

So I have an app where I have a button on the web page that the user can push to play a mp3-file. Simple stuff but I'm running constantly into the following error:

HTTP load failed with status 404. Load of media resource "..." failed.

Now while I am not super proficient in file paths etc. I'd figure by looking at guides and examples I could figure it out, but I haven't been able to.

My abbreviated file structure is something like (check bottom of post for more detailed description):

student/src/components

and under components I have my actual app in a folder and another folder under components where I planned to store my "resources" so:

components/my-app-folder/my-actual-app.tsx

components/my-resources/my.mp3

For the filepath as I understood

".."

signifies for the path to start from one folder above the current location which would be my

"/components" -folder

and my resources folder is under the component folder so I figured that should be fine.
I looked up a few other SO questions about playing audio in React and found a question that suggested roughly the following:

Inside my

render()

let path = "../my-resources/test.mp3";
let audio = new Audio(path);

And then for the JSX part:

audioPlayer = (

                <button id="equivalence-audio-button" onClick={() => audio.play()}>Soundclip!</button>

        );

I've tried:

    let path = "../my-resources/test.mp3";

and

    let path = "../../my-resources/test.mp3";

as I wasn't sure if one ".." pointed to the folder the actual app was nested in and required another ".." to actual point at the "components" folder but both of them produce the same error. I also tried using the whole path and moving the mp3 around to the same folder as the app itself but got the same result.

So I am thoroughly confused as to if I just suck at using external resources in my app or is my actual code and/or knowledge of React to blame here. The error I receive would lead me to believe that the resource isn't being located properly but I'm not sure if that's just a side effect of faulty code.

EDIT: I'm also working in a virtual environment, running my own stack locally if that makes some difference to the situation.

Also for reference a picture of the file tree:

The files opened in the picture contain the app in question and the resource it's trying to use:

The path leading up to components is the following (pic would be really big if I tried to grab the whole path in one picture).

/Users/"name of user"/arvio/client/student/src/components

Body:
Inside the src/react-app-env.d.ts add this:

/// <reference types="react-scripts" />
declare module '*.mp3'; // '*.wav' if you're using wav format

Now you can use it like this:

import beep from './assets/beep.mp3';

const alarm = new Audio(beep);

By default, TypeScript won't allow you to import an audio file, so you need to declare it yourself.

This file react-app-env.d.ts references TypeScript types declarations that are specific to projects started with Create React App. By default, it only adds support for importing bmp, gif, jpeg, jpg, png, webp, and svg.


问:
MySQL: How to allow remote connection to mysql
I have installed MySQL Community Edition 5.5 on my local machine and I want to allow remote connections so that I can connect from external source.

How can I do that?

答:
Check remote server grant permission to Wildcard access to port 3306:

sudo lsof -i -P -n | grep LISTEN

It should NOT be same like this:

mysqld    23083       mysql   21u  IPv4 145900142      0t0  TCP
127.0.0.1:3306 (LISTEN)

In this case, we need to update /etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/mariadb.conf.d/50-server.cnf with:

bind-address            = 127.0.0.1 --> 0.0.0.0

And then restart mysql "sudo service mysql restart"

In order to test mySQL connection from a client:

nc -vz <host_address> 3306


问:
How to print values of tuples using my own Tuple Class in C++
Hi everyone I am new to programming and especially OOP. I am given this *.h file, which contains a Tuple class

```<code>/*  * Tuple.h  *
 *
 *             */
#ifndef TUPLE_H_
#define TUPLE_H_
#include <string>
class Tuple
{
 public:
 Tuple ( );
 Tuple (int n, std::string s);
 virtual ~Tuple ( );
 bool setTup (int n, std::string s);
  std::string getTup(int n);
 private:
 int n;
 std::string s;
};
#endif /* TUPLE_H_ */

</code>```

I am asked to:

create two objects called Tup1 and Tup2

the private variables n and s should only bet set if n>0 and s!=" ",
otherwise they are set to n = 0 and s= " "

Tup1 should use default constructor

Tup2 should use the explicit constructor with the arguments
(2,"second")

Tup1 should then be intialized using the setTup method with the
arguments (1,"first")

Finally I should print the content of Tup1 and Tup2 by using the
getTup method and the tuples should only be printed if the function argument n in getTup is equal to the obj variable n.

I assume I should make the control that the private variables are only set in the setTup method (like this) or is this wrong?..when I compile it seems to be doing the right thing:

```<code>bool Tuple::setTup(int n, std::string s)
{

    if (n > 0 && s != " ") {
        this->n = n;
        this->s = s;
        return true;
    }

    else {
        this -> n = 0;
        this -> s = " ";

    }

    return false;
}
</code>```

I make sure that

Tup1 should use default constructor

Tup2 should use the explicit constructor with the arguments (2,"second")

Tup1 should then be intialized using the setTup method with the
arguments (1,"first")

In the main.cpp like this:

```<code>int main()
{
    Tuple Tup2(2, "Second"); //Tup2 using explicit constructor with given arguments
    Tuple Tup1; // Tup1 using default constructor
    Tup1.setTup(1,"First "); //using setTup to set Tup1 with given arguments

</code>```

However I am completley lost on how to print the values of the Tuples using the getTup method

The method takes an int argument n, but what should it return so that I can print the values of Tup1 and Tup2?

and how am i supposed to make sure that values of Tup1 and Tup2 are only printed if  the method argument n in getTup isequal to the object-variable n? ..I assume what is being asked  is to check that getTup(n) of Tup1(n,"s") the two n's should be equal...but I still have not idea how to do this

Thanks in advance!

答:
The signature in the header file already tells you what the function returns:

```<code>std::string getTup(int n);
^^return value
            ^^function name
                   ^^parameter type
                        ^^parameter name
</code>```

For the other part:

You already know how to use if. And you know how to access the objects private members.

So your code should look like this:

```<code>std::string getTup(int n){
  // check if parameter n matches private member n
    // if yes (true), then return the private member s;
    // if not, return an empty string, so nothing gets printed.
}
</code>```

Body:
Hi everyone I am new to programming and especially OOP. I am given this *.h file, which contains a Tuple class

/*  * Tuple.h  *
 *
 *             */
#ifndef TUPLE_H_
#define TUPLE_H_
#include <string>
class Tuple
{
 public:
 Tuple ( );
 Tuple (int n, std::string s);
 virtual ~Tuple ( );
 bool setTup (int n, std::string s);
  std::string getTup(int n);
 private:
 int n;
 std::string s;
};
#endif /* TUPLE_H_ */

I am asked to:

create two objects called Tup1 and Tup2

the private variables n and s should only bet set if n>0 and s!=" ",
otherwise they are set to n = 0 and s= " "

Tup1 should use default constructor

Tup2 should use the explicit constructor with the arguments
(2,"second")

Tup1 should then be intialized using the setTup method with the
arguments (1,"first")

Finally I should print the content of Tup1 and Tup2 by using the
getTup method and the tuples should only be printed if the function argument n in getTup is equal to the obj variable n.

I assume I should make the control that the private variables are only set in the setTup method (like this) or is this wrong?..when I compile it seems to be doing the right thing:

bool Tuple::setTup(int n, std::string s)
{

    if (n > 0 && s != " ") {
        this->n = n;
        this->s = s;
        return true;
    }

    else {
        this -> n = 0;
        this -> s = " ";

    }

    return false;
}

I make sure that

Tup1 should use default constructor

Tup2 should use the explicit constructor with the arguments (2,"second")

Tup1 should then be intialized using the setTup method with the
arguments (1,"first")

In the main.cpp like this:

int main()
{
    Tuple Tup2(2, "Second"); //Tup2 using explicit constructor with given arguments
    Tuple Tup1; // Tup1 using default constructor
    Tup1.setTup(1,"First "); //using setTup to set Tup1 with given arguments

However I am completley lost on how to print the values of the Tuples using the getTup method

The method takes an int argument n, but what should it return so that I can print the values of Tup1 and Tup2?

and how am i supposed to make sure that values of Tup1 and Tup2 are only printed if  the method argument n in getTup isequal to the object-variable n? ..I assume what is being asked  is to check that getTup(n) of Tup1(n,"s") the two n's should be equal...but I still have not idea how to do this

Thanks in advance!

Body:
The signature in the header file already tells you what the function returns:

std::string getTup(int n);
^^return value
            ^^function name
                   ^^parameter type
                        ^^parameter name

For the other part:

You already know how to use if. And you know how to access the objects private members.

So your code should look like this:

std::string getTup(int n){
  // check if parameter n matches private member n
    // if yes (true), then return the private member s;
    // if not, return an empty string, so nothing gets printed.
}


问:
React change only clicked button text [Looped]
When I click the button run a function called AddWait but it adds wait text to all buttons. I tried with useRef but things got messy.
Image;

I did something similar to this with jquery ;

for (let index = 0; index <= 10; index++) {
  $("#app").append(`Hello ${index}
  ===><button class=click-me>button ${index} </button>

`);
}

$(".click-me").on("click", function (event) {
  var $this = $(this);
  console.log($this.text());

  $this.text($this.text() + "hi");
  //(... rest of your JS code)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

You can check react app;

So how can I change only clicked button text?

答:
What you should do is save the div with the button into a separate component and then react will change the button text just for that particular component:</p>
```<code>import { useState } from "react";
import "./styles.css";

const CustomBtn = props => {
  const { item, index } = props;
  console.log(item)
  const [waitText, setWaitText] = useState('');
  const waitThreeSeconds = () => {
    setWaitText("wait");
    setTimeout(() => setWaitText(''), 3000)
  };

  return (
    <div>
      <span>Hello {index} </span>
      <button onClick={waitThreeSeconds}>
        button {index} {waitText}
      </button>
      <br />
      <br />
    </div>
  )
}

export default function App() {

  return (
    <div className="App">
      {[...Array(10)].map((item, index) => (
        <CustomBtn item={item} key={index} index={index} />
      ))}
    </div>
  );
}
</code>```

Body:
When I click the button run a function called AddWait but it adds wait text to all buttons. I tried with useRef but things got messy.
Image;

I did something similar to this with jquery ;

for (let index = 0; index <= 10; index++) {
  $("#app").append(`Hello ${index}
  ===><button class=click-me>button ${index} </button>

`);
}

$(".click-me").on("click", function (event) {
  var $this = $(this);
  console.log($this.text());

  $this.text($this.text() + "hi");
  //(... rest of your JS code)
});

You can check react app;

So how can I change only clicked button text?

Body:
What you should do is save the div with the button into a separate component and then react will change the button text just for that particular component:

import { useState } from "react";
import "./styles.css";

const CustomBtn = props => {
  const { item, index } = props;
  console.log(item)
  const [waitText, setWaitText] = useState('');
  const waitThreeSeconds = () => {
    setWaitText("wait");
    setTimeout(() => setWaitText(''), 3000)
  };

  return (
    <div>
      <span>Hello {index} </span>
      <button onClick={waitThreeSeconds}>
        button {index} {waitText}
      </button>
      <br />
      <br />
    </div>
  )
}

export default function App() {

  return (
    <div className="App">
      {[...Array(10)].map((item, index) => (
        <CustomBtn item={item} key={index} index={index} />
      ))}
    </div>
  );
}


问:
Git project permission denied
I ran

```<code>git clone git@github.com:{username}/{project}.git
</code>```

fatal: Could not rerad from remote repository.
Please make sure you have the correct access rights and the repository exists.

so:

```<code>ssh-add ~/.ssh/id_rsa
</code>```

No such file or directory,
hmm...

```<code>mkdir ~/.ssh/id_rsa
</code>```

WARNIG: UNPORTECTED PRIVATE KEY FILE!
Permissions 0775 for .... are too open.

答:
To complemet the comments and the steps to follow, keep in mind ssh-add is only needed if you have created a private key protected with a passphrase.

If you use

```<code>cd ~
mkdir .ssh
chmod 700 .ssh
cd .ssh
ssh-keygen -t rsa -P ""
</code>```

That will create id_rsa and id_rsa.pub, the latter (public key) is to be registered in your GitHub profile settings.

Test the access with ssh -Tv git@github.com to ensure yu are correctly authenticated.

Title: Git project permission denied

Body:
I ran

git clone git@github.com:{username}/{project}.git

fatal: Could not rerad from remote repository.
Please make sure you have the correct access rights and the repository exists.

so:

ssh-add ~/.ssh/id_rsa

No such file or directory,
hmm...

mkdir ~/.ssh/id_rsa

WARNIG: UNPORTECTED PRIVATE KEY FILE!
Permissions 0775 for .... are too open.

Body:
To complemet the comments and the steps to follow, keep in mind ssh-add is only needed if you have created a private key protected with a passphrase.

If you use

cd ~
mkdir .ssh
chmod 700 .ssh
cd .ssh
ssh-keygen -t rsa -P ""

That will create id_rsa and id_rsa.pub, the latter (public key) is to be registered in your GitHub profile settings.

Test the access with ssh -Tv git@github.com to ensure yu are correctly authenticated.


问:
UINavigationController and back button action
I have an two controllers 1st is self and 2nd is maincontroller, where I'm pushing maincontroller in stack, so the back button is automatically coming.

Here I need to make an alert when the user presses the back button.

How can I do this?

答:
```<code>extension ViewController: UINavigationControllerDelegate {
// when the self != viewcontroller ,it's mean back
     func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
          if self != viewController {
             // your code
           }
}}
</code>```


问:
Why is state variable remaining same after updating it using setState function of useState hook in React?
I was trying to create a list of movies like in Netflix, in which left arrow appears when i slide it to the right. And left arrow disappears when list gets back to original position.

Why is the value of slideNumber remaining same even after i update it using setSlideNumber?

Image of the lists i am trying to make

```<code>function List() {
    const [slideNumber, setSlideNumber] = useState(0);    //USE STATE HOOK
    const [isMoved, setIsMoved] = useState(false);

    const listRef = useRef();

    const handleClick = (direction) => {
        setIsMoved(true);
        let distance = listRef.current.getBoundingClientRect().x -50;
        if(direction === "right" && slideNumber<5){
            setSlideNumber(slideNumber+1);
            listRef.current.style.transform = `translateX(${distance - 230}px)`
        }
        if(direction === "left" && slideNumber>0){
            console.log(slideNumber);          //THIS LINE
            setSlideNumber(slideNumber-1);
            console.log(slideNumber);           //AND THIS LINE GIVES SAME OUTPUT
            if(slideNumber===1){
                setIsMoved(false);
            }

            listRef.current.style.transform = `translateX(${distance + 230}px)`
        }
    }

    return (
        <div className='list'>
            <span className="listTitle">Continue Watching</span>
            <div className="wrapper">
                <ArrowBackIosOutlinedIcon
                className='sliderArrow left'
                onClick = {()=>handleClick("left")}
                style={{display: !isMoved && "none"}}
                />
                <div className="container" ref={listRef}>
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                </div>
                <ArrowForwardIosOutlinedIcon className='sliderArrow right' onClick = {()=>handleClick("right")}/>
            </div>
        </div>
    );
}
</code>```

答:
React will batch all your state change and will update the state only once
to avoid any unnecessary render. As such, you will get an updated state only during the next render, not in the same stack you are currently executing.

In your case it will wait for your handleClick function to finish its execution before updating the state, hence the second console.log with the same output.

For your following condition to work you should use an intermediary variable:

if(direction === "left" && slideNumber > 0){
  const newSlideNuber = slideNumber - 1
  setSlideNumber(newSlideNumber);

  if(newSlideNumber === 1){
    setIsMoved(false);
  }

  listRef.current.style.transform = `translateX(${distance + 230}px)`
}
```

You can find more information about the batching behaviour in React in this github discussion

Body:
I was trying to create a list of movies like in Netflix, in which left arrow appears when i slide it to the right. And left arrow disappears when list gets back to original position.

Why is the value of slideNumber remaining same even after i update it using setSlideNumber?

Image of the lists i am trying to make

function List() {
    const [slideNumber, setSlideNumber] = useState(0);    //USE STATE HOOK
    const [isMoved, setIsMoved] = useState(false);

    const listRef = useRef();

    const handleClick = (direction) => {
        setIsMoved(true);
        let distance = listRef.current.getBoundingClientRect().x -50;
        if(direction === "right" && slideNumber<5){
            setSlideNumber(slideNumber+1);
            listRef.current.style.transform = `translateX(${distance - 230}px)`
        }
        if(direction === "left" && slideNumber>0){
            console.log(slideNumber);          //THIS LINE
            setSlideNumber(slideNumber-1);
            console.log(slideNumber);           //AND THIS LINE GIVES SAME OUTPUT
            if(slideNumber===1){
                setIsMoved(false);
            }

            listRef.current.style.transform = `translateX(${distance + 230}px)`
        }
    }

    return (

            Continue Watching

                <ArrowBackIosOutlinedIcon
                className='sliderArrow left'
                onClick = {()=>handleClick("left")}
                style={{display: !isMoved && "none"}}
                />

                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />
                    <ListItem />

                <ArrowForwardIosOutlinedIcon className='sliderArrow right' onClick = {()=>handleClick("right")}/>

    );
}

Body:
React will batch all your state change and will update the state only once
to avoid any unnecessary render. As such, you will get an updated state only during the next render, not in the same stack you are currently executing.

In your case it will wait for your handleClick function to finish its execution before updating the state, hence the second console.log with the same output.

For your following condition to work you should use an intermediary variable:

if(direction === "left" && slideNumber > 0){
  const newSlideNuber = slideNumber - 1
  setSlideNumber(newSlideNumber);

  if(newSlideNumber === 1){
    setIsMoved(false);
  }

  listRef.current.style.transform = `translateX(${distance + 230}px)`
}

You can find more information about the batching behaviour in React in this github discussion


问:
Improve use of processor during training of ML model
I am using a new pc with intel i5 11th generation processor for machine learning.

Usually when I train a model, I open the default 'task manager' by windows to check how processor and memory are used like in the picture.

as you can see here 30% of processor power is used(between 25% and 30% in all training phase).

But in my older pc with processor inter i7 6th generation, the 30% used to be at least 80% when training.

The models I train take at least few minutes to train, so it is not a running time of few seconds.

I am totally not into hardware. I Hope someone is able to explain why that difference occurs. And if it is healthy to have 30% or 80% of processor power used during training.

答:
You are limited by something else than the CPU (common would be GPU or RAM). The same 80% you saw on your old CPU just stresses the new one less because its more powerful.

Healthy has nothing to do with load, what could be unhealthy are CPU temperatures, you should aim to have them below 80°C, if they are higher youd do good in investing into a better cooler.


问:
Unable to Authenticate client using self-created token (asp.net C#)
I have a windows application that contains a web browser control. This app create a HTTPWebRequest (with "Put" method) that post an authentication token into my asp.net server. The server would verify the authenticity of the token in the login.aspx and then redirect the user to the Default.aspx. Unfortunately, FormsAuthentication.RedirectFromLoginPage does not redirect to the Default.aspx. My guess is the HTTPWebrequest doesn't support the redirection back to the browser before it redirected to the Default.aspx. Any ideas how to solve this problem??

The other problem is I need to use the web browser control in the apps to show the Default.aspx.Therefore, I need to write the Default.aspx to the Response.OutputStream and send it back to the windows app.

When the windows app receive the response, it will call the following code to show the Default.aspx:

webBrowser.DocumentStream = Response.GetResponseStream();

Really Appreciate your responses. Thanks

答:
HttpWebRequest supports redirection - I guess the support exists for authentication purposes. See HttpWebRequest.AllowAutoRedirect property - by default, it's true so you should get back the default.aspx from your web request object. The HttpWebRequest object is a stand-alone component and does not have any integration with WebBrowser control so you will not see the redirected page into the browser control automatically. At the most, you can capture the response (using GetResponse method) then use the response to load the content  into web browser control.

I will suggest that you use tool such as Fiddler to capture the HTTP request/response between your application and web server to understand the issue.


问:
What is the advantage of a single-function-class over a function?
I have often encountered classes with the following structure:

```<code>class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};
</code>```

So classes with only one public member function that are also only run once.
Is there any advantage in any case over a single free function foo(A a, B b)?
The latter option is easier to call, potentially has less header dependencies and also has  much less boilerplate in the header.

答:
An object has state that can be set up at object construction time. Then the single member function can be called at a later time, without knowing anything about how the object was set up, and the function can refer to the state that was set up earlier. A standalone function cannot do that. Any state must be passed to it as arguments, or be global/static (global/static data is best avoided for a variety of reasons).

An hands-on example is worth a thousand abstract explanations, so here is an exercise. Consider a simple object:

```<code>struct Obj {
   std::array<std::string, 42> attributes;
};
</code>```

How would you sort a vector of such objects, comparing only the attribute number K (K being a run-time parameter in the range 0..41)? Use std::sort and do not use any global or static data. Note how std::sort compares two objects: it calls a user-provided comparator, and passes it two objects to be compared, but it knows nothing about the parameter K and cannot pass it along to the comparator.

Body:
I have often encountered classes with the following structure:

class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};

So classes with only one public member function that are also only run once.
Is there any advantage in any case over a single free function foo(A a, B b)?
The latter option is easier to call, potentially has less header dependencies and also has  much less boilerplate in the header.

Body:
An object has state that can be set up at object construction time. Then the single member function can be called at a later time, without knowing anything about how the object was set up, and the function can refer to the state that was set up earlier. A standalone function cannot do that. Any state must be passed to it as arguments, or be global/static (global/static data is best avoided for a variety of reasons).

An hands-on example is worth a thousand abstract explanations, so here is an exercise. Consider a simple object:

struct Obj {
   std::array<std::string, 42> attributes;
};

How would you sort a vector of such objects, comparing only the attribute number K (K being a run-time parameter in the range 0..41)? Use std::sort and do not use any global or static data. Note how std::sort compares two objects: it calls a user-provided comparator, and passes it two objects to be compared, but it knows nothing about the parameter K and cannot pass it along to the comparator.


问:
Understanding C program that checks string for equal occurrences of characters
This program is meant to take a string, and return 0 if there is not an equal occurrence of letters within the string, and 1 if there are an equal occurrence of letters. My question is how this program is able to do this? I understand that the first for loop initializes counts as an array of 26 0's, but around the second for loop is where I start to lose understanding. I know the [s[i] - 'a'] is meant to turn characters into indexes, but im not sure of the purpose of the max variable and how the comparisons at the final for loop are able to determine whether a string has equal occurrences or not. Thank you in advance, and I am happy to answer any questions I can!</p>
```<code>int areEqualOccurrences( char phrase[] )
{
  int counts[26];
  int max;
  int i;

  for(i = 0; i < 26; i++){
      counts[i] = 0; }

  for(i = 0; i < strlen(phrase); i++){
      counts[phrase[i] - 'a']++;
      max = counts[phrase[i] - 'a'];
     }

  for(i = 0; i < 26; i++){
      if (counts[i] != 0 && counts[i] != max)
        return 0;
  }
    return 1;
}
</code>```

答:
The second for loop counts the characters in the array and initialises max to the count value of the last character in the phrase.
Then the third loop checks that all occurrance counts of characters in the whole phrase matches that of the occurrance count of the last character.

```<code>aabb => 2 times a, 2 times b, max=2 => 1
aaab => 3 times a, 1 times b, max=1 => 0
abcd => everything once, max=1 => 1
abaa => 3 times a, 1 times b, max=3 => 0
aaabbbcccdddeeefffggggggg => max=6 (number of 'g's) => 0
</code>```

Alternatively, you could initialise max to the first non-0 value in the array inside the third loop, but that requires an additional conditional check there (if(max==0) max=counts[i];) and requires you to initialise max up front (int max=0;)

Body:
This program is meant to take a string, and return 0 if there is not an equal occurrence of letters within the string, and 1 if there are an equal occurrence of letters. My question is how this program is able to do this? I understand that the first for loop initializes counts as an array of 26 0's, but around the second for loop is where I start to lose understanding. I know the [s[i] - 'a'] is meant to turn characters into indexes, but im not sure of the purpose of the max variable and how the comparisons at the final for loop are able to determine whether a string has equal occurrences or not. Thank you in advance, and I am happy to answer any questions I can!

int areEqualOccurrences( char phrase[] )
{
  int counts[26];
  int max;
  int i;

  for(i = 0; i < 26; i++){
      counts[i] = 0; }

  for(i = 0; i < strlen(phrase); i++){
      counts[phrase[i] - 'a']++;
      max = counts[phrase[i] - 'a'];
     }

  for(i = 0; i < 26; i++){
      if (counts[i] != 0 && counts[i] != max)
        return 0;
  }
    return 1;
}

Body:
The second for loop counts the characters in the array and initialises max to the count value of the last character in the phrase.
Then the third loop checks that all occurrance counts of characters in the whole phrase matches that of the occurrance count of the last character.

aabb => 2 times a, 2 times b, max=2 => 1
aaab => 3 times a, 1 times b, max=1 => 0
abcd => everything once, max=1 => 1
abaa => 3 times a, 1 times b, max=3 => 0
aaabbbcccdddeeefffggggggg => max=6 (number of 'g's) => 0

Alternatively, you could initialise max to the first non-0 value in the array inside the third loop, but that requires an additional conditional check there (if(max==0) max=counts[i];) and requires you to initialise max up front (int max=0;)


问:
JuMP nonlinear optimization constraints broken to O(1e-9)
I'm running nonlinear optimization using the Ipopt optimizer in JuMP. My objective/cost function relies on the constraints being adhered to strictly. However on some iterations the constraint are being broken.

Specifically, my constraints are s.t. the values should be between 0 and 1/0.6 = 1.6666666....

However, in some iterations, the variables have values like:

-7.761358324221462e-9 or
1.6666666718748067

crashing the program.

Is this a bug? Is it a problem with JuMP or Ipopt? Is there a workaround?

Code:

```<code>using JuMP
using Ipopt

model = Model(Ipopt.Optimizer)
@variable(model, 0.0 <= ξ[1:6] <= 1.0/0.6)
set_start_value.(ξ, ξ₀)

@constraint(model, dot(ξ, T) == 1)

register(model, :objtv, 6, MyNonLinearObjectiveFn; autodiff=true)
@NLobjective(model, Min, objtv(ξ...))

optimize!(model)
</code>```

答:
To add to the answer of Przemyslaw and repeat what Miles said in the Julia discourse, setting the bound_relax_factor to 0 should help to ensure variable value are almost always within or at bounds.

"almost" because Ipopt may choose to relax variable bounds (or constraint sides) during solve again. There is a message "Slack too small, adjusting variable bound" in the log that indicates that this happened.
So you want to handle this case in your code and not just "crash".

Body:
I'm running nonlinear optimization using the Ipopt optimizer in JuMP. My objective/cost function relies on the constraints being adhered to strictly. However on some iterations the constraint are being broken.

Specifically, my constraints are s.t. the values should be between 0 and 1/0.6 = 1.6666666....

However, in some iterations, the variables have values like:

-7.761358324221462e-9 or
1.6666666718748067

crashing the program.

Is this a bug? Is it a problem with JuMP or Ipopt? Is there a workaround?

Code:

using JuMP
using Ipopt

model = Model(Ipopt.Optimizer)
@variable(model, 0.0 <= ξ[1:6] <= 1.0/0.6)
set_start_value.(ξ, ξ₀)

@constraint(model, dot(ξ, T) == 1)

register(model, :objtv, 6, MyNonLinearObjectiveFn; autodiff=true)
@NLobjective(model, Min, objtv(ξ...))

optimize!(model)


问:
VS Code search in workspace is only looking in the opened files in editor
I used to be able to search for a text in any files in the workspace in the editor in VS Code. Now it only looks for the keyword in the opened files. I don't know how to restore the old settings back. I want to be able to find the keyword in closed files as well as opened files. Does anyone know how to fix this?

I am getting this message, "No results found in open editors. Review your settings for configured exclusions and check your gitignore files - Open Settings - Learn More"

screenshot

答: There is a setting in files options, under the "replace all" button. Disable the open book icon and you'll be able to search closed files as well.