问:
Sending HTML Email in php?
Here is the code.

```<code>$to = 'youraddress@example.com';

$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
</code>```

I don't follow it well. expect someone can do me a favor.

Why should I generate a random hash?

Why I must add boundary string and mime type specification to header?

Why use ob_start();?

4.

```<code>--PHP-alt-<?php echo $random_hash; ?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit
</code>```

What are those lines meaning? Could I delete them? Thank you.

答:
Generating a random hash is to avoid it colliding with your content.

A "boundary string" tells the email clients where headers start and stop and where the actual email contents start. Since you want to send HTML email, you must specifically tell the email client it will be receiving HTML, not just any content.

Otherwise the HTML and stuff will be sent directly to the browser, ie, the user viewing your site. Instead you want to store the HTML in a variable and use it instead.

Content-Type tells the email client what kind of content you are sending and how it is encoded.

Of course you cannot delete them. It would be like sending you a PDF file without saying it is a PDF and without a proper extension - you won't know what to do with it.

Note

Emails, websites, anything which has a structure (including most files) usually are laid out in a structure of "header" and "body".

The header tells the file reader what to expect in the "body". The "body" is the actual content the reader should do something with.

Title: Sending HTML Email in php?

Body:
Here is the code.

$to = 'youraddress@example.com';

$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!

This is something with HTML formatting.

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

I don't follow it well. expect someone can do me a favor.

Why should I generate a random hash?

Why I must add boundary string and mime type specification to header?

Why use ob_start();?

4.

--PHP-alt-<?php echo $random_hash; ?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit

What are those lines meaning? Could I delete them? Thank you.


来源: stackexchange

问:
A value of type 'String?' can't be returned because function has return type of 'Future<String>?'
The documentation says:

If the function has a declared return type,  then update the type to
be Future<T>, where T is the type of the value that the function
returns.

When I do that with this code, I get an error: A value of type 'String?' can't be returned from the method 'amethod' because it has a return type of Future < String>?.

Why is it giving that error and what is the correct way to return a non-void value from an async function? Thanks.

```<code>class Demo{

 Future<String>? amethod() async{
 String? variable1;

   //await ...

  return variable1;
 }
}
</code>```

答:
Your function wants to return variable1, which is of type String?.  Since the function is asynchronous, its return type must be Future<String?>, not Future<String>?.  The two are not the same:

A return type of Future<String>? means that the function returns either null or a Future.  That Future completes to a non-nullable String.  This is almost never what you want as a return type.

A return type of Future<String?> means that the function always returns a Future, never null.  That Future completes to either null or a String.

ContentLicense: CC BY-SA 4.0

Body:
The documentation says:

If the function has a declared return type,  then update the type to
be Future<T>, where T is the type of the value that the function
returns.

When I do that with this code, I get an error: A value of type 'String?' can't be returned from the method 'amethod' because it has a return type of Future < String>?.

Why is it giving that error and what is the correct way to return a non-void value from an async function? Thanks.

class Demo{

 Future<String>? amethod() async{
 String? variable1;

   //await ...

  return variable1;
 }
}


问:
Upload an image onto Imgur API - C# UWP
I've been trying to get uploading an image anonymously onto Imgur using the Imgur API to work, however I've been facing an issue with unauthorized path access.

I've tried search around other similar articles on Microsoft Docs and posts here on stack overflow but couldn't find a solution. I've even given my application "broadFileSystemAccess" as rescap capability in my Package.appxmanifest which I found from reading the Microsoft UWP documentations.

The error I receive is:

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'

The error occurs at the var filecon = File.ReadAllBytes(imgpath); line.

My File Picker code is:

```<code>public static string imgpath = "";

    public static string finalimg = "";

    private async void FileNameButton_Click(object sender, RoutedEventArgs e)
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".jpeg");
        picker.FileTypeFilter.Add(".png");

        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            imgpath = file.Path;
            var filecon = File.ReadAllBytes(imgpath); #Error drops here <---
            finalimg = Convert.ToBase64String(filecon);

            await ImgurUploadAPI();
            Debug.WriteLine("Picked Image: " + file.Name);
            uploadedimage_text.Text = "Picked Image: " + file.Name;
        }
        else
        {
            Debug.WriteLine("Image uploading has been cancelled.");
        }
    }
</code>```

And the ImgurUpload task code is:

```<code>public static string imgurlink = "";

    public async Task ImgurUploadAPI()
    {
        try
        {
            if (imgpath != null)
            {
                // Construct the HttpClient and Uri
                HttpClient httpClient = new HttpClient();
                Uri uri = new Uri("https://api.imgur.com/3/upload");

                httpClient.DefaultRequestHeaders.Add("Authorization", "Client-ID IMGUR-CLIENTIDHERE");
                //Debug.WriteLine("Request Headers: ");

                // Construct the JSON to post
                HttpStringContent content = new HttpStringContent("image=\"{finalimg}\"");
                Debug.WriteLine("Request Upload: " + content);

                // Post the JSON and wait for a response
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                imgurlink = httpResponseBody;
                Debug.WriteLine("Request Response: " + httpResponseBody);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }
</code>```

I feel like it might be something to do with the way I access and convert the image to be ready for upload. Any tips would be very appreciated as I've been stuck on this for awhile now and it's one of the last things I need to complete for my project. Cheers!

答:
Besides @Julian Silden Langlo answer. there is another option for your scenario. The reason for this behavior is that you could not directly access the file using File.ReadAllBytes(String) Method.

I noticed that you've already added the broadFileSystemAccess capability, what you need to note is that this capability only works for the Windows.Storage APIs. So you could only use it like

```<code>StorageFile file = StorageFile.GetFileFromPathAsync(filepath)
</code>```

Title: Upload an image onto Imgur API - C# UWP

Body:
I've been trying to get uploading an image anonymously onto Imgur using the Imgur API to work, however I've been facing an issue with unauthorized path access.

I've tried search around other similar articles on Microsoft Docs and posts here on stack overflow but couldn't find a solution. I've even given my application "broadFileSystemAccess" as rescap capability in my Package.appxmanifest which I found from reading the Microsoft UWP documentations.

The error I receive is:

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'

The error occurs at the var filecon = File.ReadAllBytes(imgpath); line.

My File Picker code is:

public static string imgpath = "";

    public static string finalimg = "";

    private async void FileNameButton_Click(object sender, RoutedEventArgs e)
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".jpeg");
        picker.FileTypeFilter.Add(".png");

        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            imgpath = file.Path;
            var filecon = File.ReadAllBytes(imgpath); #Error drops here <---
            finalimg = Convert.ToBase64String(filecon);

            await ImgurUploadAPI();
            Debug.WriteLine("Picked Image: " + file.Name);
            uploadedimage_text.Text = "Picked Image: " + file.Name;
        }
        else
        {
            Debug.WriteLine("Image uploading has been cancelled.");
        }
    }

And the ImgurUpload task code is:

public static string imgurlink = "";

    public async Task ImgurUploadAPI()
    {
        try
        {
            if (imgpath != null)
            {
                // Construct the HttpClient and Uri
                HttpClient httpClient = new HttpClient();
                Uri uri = new Uri("https://api.imgur.com/3/upload");

                httpClient.DefaultRequestHeaders.Add("Authorization", "Client-ID IMGUR-CLIENTIDHERE");
                //Debug.WriteLine("Request Headers: ");

                // Construct the JSON to post
                HttpStringContent content = new HttpStringContent("image=\"{finalimg}\"");
                Debug.WriteLine("Request Upload: " + content);

                // Post the JSON and wait for a response
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                imgurlink = httpResponseBody;
                Debug.WriteLine("Request Response: " + httpResponseBody);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }

I feel like it might be something to do with the way I access and convert the image to be ready for upload. Any tips would be very appreciated as I've been stuck on this for awhile now and it's one of the last things I need to complete for my project. Cheers!

Body:
Besides @Julian Silden Langlo answer. there is another option for your scenario. The reason for this behavior is that you could not directly access the file using File.ReadAllBytes(String) Method.

I noticed that you've already added the broadFileSystemAccess capability, what you need to note is that this capability only works for the Windows.Storage APIs. So you could only use it like

StorageFile file = StorageFile.GetFileFromPathAsync(filepath)


问:
Find_all function returning multiple strings that are separated but not delimited by a character
Background: I am pretty new to python and decided to practice by making a webscraper for https://www.marketwatch.com/tools/markets/stocks/a-z which would allow me to pull the company name, ticker, origin, and sector. I could then use this in another scraper to combine it with more complex information. The page is separated by 2 indexing methods- one to select the first letter of the company name (at the top of the page and another for the number of pages within that letter index (at the bottom of the page). These two tags have the class = "pagination" identifier but when I scrape based on that criteria, I get two separate strings but they are not a delimited list separated by a comma.

Does anyone know how to get the strings as a list? or individually? I really only care about the second.

```<code>from bs4 import BeautifulSoup
import requests

# open the source code of the website as text
source = 'https://www.marketwatch.com/tools/markets/stocks/a-z/x'

page = requests.get(source).text
soup = BeautifulSoup(page, 'lxml')

for tags in soup.find_all('ul', class_='pagination'):

    tags_text = tags.text
    print(tags_text)
</code>```

Which returns:

```<code>0-9ABCDEFGHIJKLMNOPQRSTUVWX (current)YZOther
«123»
</code>```

When I try to split on /n:

```<code>tags_text = tags.text.split('/n')
print(tags_text)
</code>```

The return is:

```<code>['\n0-9ABCDEFGHIJKLMNOPQRSTUVWX (current)YZOther']
['«123»']
</code>```

Neither seem to form a list. I have found many ways to get the first string but I really only need the second.

Also, please note that I am using the X index as my current tab. If you build it from scratch, you might have more numbers in the second string and the word (current) might be in a different place in the first list.

THANK YOU!!!!

Edit:
Cleaned old, commented out code from the source and realized I did not show the results of trying to call the second element despite the lack of a comma in the split example:

```<code>tags_text = tags.text.split('/n')[1]
print(tags_text)
</code>```

Returns:

```<code>File, "C:\.....", line 22, in <module>
tags_text = tags.text.split('/n')[1]

IndexError: list index out of range
</code>```

答: Never mind, I was using print() when I should have been using return, .apphend(), or another term to actually do something with the value...</p>

Body:
Background: I am pretty new to python and decided to practice by making a webscraper for https://www.marketwatch.com/tools/markets/stocks/a-z which would allow me to pull the company name, ticker, origin, and sector. I could then use this in another scraper to combine it with more complex information. The page is separated by 2 indexing methods- one to select the first letter of the company name (at the top of the page and another for the number of pages within that letter index (at the bottom of the page). These two tags have the class = "pagination" identifier but when I scrape based on that criteria, I get two separate strings but they are not a delimited list separated by a comma.

Does anyone know how to get the strings as a list? or individually? I really only care about the second.

from bs4 import BeautifulSoup
import requests

# open the source code of the website as text
source = 'https://www.marketwatch.com/tools/markets/stocks/a-z/x'

page = requests.get(source).text
soup = BeautifulSoup(page, 'lxml')

for tags in soup.find_all('ul', class_='pagination'):

    tags_text = tags.text
    print(tags_text)

Which returns:

0-9ABCDEFGHIJKLMNOPQRSTUVWX (current)YZOther
«123»

When I try to split on /n:

tags_text = tags.text.split('/n')
print(tags_text)

The return is:

['\n0-9ABCDEFGHIJKLMNOPQRSTUVWX (current)YZOther']
['«123»']

Neither seem to form a list. I have found many ways to get the first string but I really only need the second.

Also, please note that I am using the X index as my current tab. If you build it from scratch, you might have more numbers in the second string and the word (current) might be in a different place in the first list.

THANK YOU!!!!

Edit:
Cleaned old, commented out code from the source and realized I did not show the results of trying to call the second element despite the lack of a comma in the split example:

tags_text = tags.text.split('/n')[1]
print(tags_text)

Returns:

File, "C:\.....", line 22, in <module>
tags_text = tags.text.split('/n')[1]

IndexError: list index out of range


问:
Convert IEnumerable<Dictionary<int, string>> to List<Dictionary<int, string>>
```<code>var a = GetIEnumerableDictionary();
</code>```

a is IEnumerable<Dictionary<int, string>>.
How do I convert a to List<Dictionary<int, string>> ?

答:
You can use the List IEnumerable<T> constructor, so:

```<code>List<Dictionary<int, string>> myList = new List<Dictionary<int, string>>(a);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
var a = GetIEnumerableDictionary();

a is IEnumerable<Dictionary<int, string>>.
How do I convert a to List<Dictionary<int, string>> ?

Body:
You can use the List IEnumerable<T> constructor, so:

List<Dictionary<int, string>> myList = new List<Dictionary<int, string>>(a);


问:
Routage in Net 6, how to allow url {controller}/{action}/{id}/{string}
in the program.cs i found this line of code :

```<code>app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
</code>```

but i am not sure how to do in order to allow my website to have such a URL :
www.domain.com/mycontroller/id/title

Could you help me to make this happen?
what do i need to change?
and in the controller i need to add something?
and the link asp-action how should be?
Thanks

答:
If you want to  allow url {controller}/{action}/{id}/{string} in the controller,you can use like this:

```<code>[Route("[controller]/[action]")]
public class TestController : Controller
{
   [Route("{id}/{s}")]
   public IActionResut Test(string id,string s)
   {
       return View();
   }

}
</code>```

If you want to use  tag:

```<code><a asp-action="AddStudy" asp-route-id="xxx" asp-route-s="xxx">a</a>
</code>```

Body:
in the program.cs i found this line of code :

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

but i am not sure how to do in order to allow my website to have such a URL :
www.domain.com/mycontroller/id/title

Could you help me to make this happen?
what do i need to change?
and in the controller i need to add something?
and the link asp-action how should be?
Thanks

Body:
If you want to  allow url {controller}/{action}/{id}/{string} in the controller,you can use like this:

[Route("[controller]/[action]")]
public class TestController : Controller
{
   [Route("{id}/{s}")]
   public IActionResut Test(string id,string s)
   {
       return View();
   }

}

If you want to use <a> tag:

<a asp-action="AddStudy" asp-route-id="xxx" asp-route-s="xxx">a</a>


问:
Application Insight Custom Metrics Not available in Logs
I had loaded Custom Metrics using App Insights API to Application Insights (which is workspace-based). I want to enrich the custom metrics with tables in logs.However i am not able to see the custom logs in the Log Analytics workspace or in the custom metrics explorer.
Is there a workaround for doing this.

I can create charts using the metrics loaded in Application Insights

答:
Few of the reasons why custom metrics are not being logged were:

There can be couple of minutes or less latency in Application Insights Pipeline itself. Please check this AzureMonitorStatus Blog contains most AI Issues with their resolutions at one place (tech community category).

When new custom property or new custom metric is added, it might take for that new field to show up as a field in metadata that the charts use to build themselves, depending on timing.

If it is a new application, to display that new custom property/metric in metadata, it can take up to ~15 minutes (maximum) and sometimes less than that.

Once they are available in Metadata, might need to refresh the portal if you're already in the Metrics Explorer window for that AI resource for it to re-request metadata to see your field (normally just the "refresh" command on Metrics Explorer or an Overview blade is good enough to get that working but doing a full refresh in the browser works as last resort).


问:
Module Object not callable from beautiful soup
Just starting to build my first webscraper and I cannot figure out why my beautifulsoup module isn't able to call. Thank you for helping the beginner :(

import requests
from bs4 import BeautifulSoup

# Import your website here
html_text = requests.get(
    'https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=').text

soup = BeautifulSoup(html_text, 'lxml')

# Find the part of the webpage where your information is in
job = soup.find_all('li', class_='clearfix job-bx wht-shd-bx')
company_name = job.find('h3', class_='joblist-comp-name').text.replace(' ', '')
skills = job.find('span', class_='srp-skills').text.replace(' ', '')
published_date = job.find('span', class_='sim-posted').span.text

print(published_date)

print(f'''
Company name: {company_name}
Required Skills: {skills}

''')
```
```Traceback (most recent call last):
  File "c:\Users\GamingPC\OneDrive - University of Pittsburgh\Random Work\Desktop\Python Projects\Web scraping.py", line 12, in <module>
    company_name = job.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '')
  File "C:\Users\GamingPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bs4\element.py", line 2253, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
```

答:
```<code>job = soup.find_all('li', class_ = 'clearfix job-bx wht-shd-bx')
company_name = job.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '')
</code>```

find_all() returns a result set.  You can't call find() on a result set.

Body:
Just starting to build my first webscraper and I cannot figure out why my beautifulsoup module isn't able to call. Thank you for helping the beginner :(

import requests
from bs4 import BeautifulSoup

# Import your website here
html_text = requests.get(
    'https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=').text

soup = BeautifulSoup(html_text, 'lxml')

# Find the part of the webpage where your information is in
job = soup.find_all('li', class_='clearfix job-bx wht-shd-bx')
company_name = job.find('h3', class_='joblist-comp-name').text.replace(' ', '')
skills = job.find('span', class_='srp-skills').text.replace(' ', '')
published_date = job.find('span', class_='sim-posted').span.text

print(published_date)

print(f'''
Company name: {company_name}
Required Skills: {skills}

''')

Traceback (most recent call last):
  File "c:\Users\GamingPC\OneDrive - University of Pittsburgh\Random Work\Desktop\Python Projects\Web scraping.py", line 12, in <module>
    company_name = job.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '')
  File "C:\Users\GamingPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bs4\element.py", line 2253, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

Body:
job = soup.find_all('li', class_ = 'clearfix job-bx wht-shd-bx')
company_name = job.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '')

find_all() returns a result set.  You can't call find() on a result set.


问:
Extract numbers from a field in PostgreSQL
I have a table with a column po_number of type varchar in Postgres 8.4. It stores alphanumeric values with some special characters. I want to ignore the characters [/alpha/?/$/encoding/.] and check if the column contains a number or not. If its a number then it needs to typecast as number or else pass null, as my output field po_number_new is a number field.

Below is the example:

SQL Fiddle.

I tired this statement:

```<code>select
(case when  regexp_replace(po_number,'[^\w],.-+\?/','') then po_number::numeric
else null
end) as po_number_new from test
</code>```

But I got an error for explicit cast:

答:
Since version 12 - that's 2 years + 4 months ago at the time of writing (but after the last edit that I can see on the accepted answer), you could use a GENERATED FIELD to do this quite easily on a one-time basis rather than having to calculate it each time you wish to SELECT a new po_number.

Furthermore, you can use the TRANSLATE function to extract your digits which is less expensive than the REGEXP_REPLACE solution proposed by @ErwinBrandstetter!

I would do this as follows (all of the code below is available on the fiddle here):

```<code>CREATE TABLE s
(
  num TEXT,

  new_num INTEGER GENERATED ALWAYS AS
    (NULLIF(TRANSLATE(num, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ. ', ''), '')::INTEGER) STORED
);
</code>```

You can add to the 'ABCDEFG... string in the TRANSLATE function as appropriate - I have decimal point (.) and a space ( ) at the end - you may wish to have more characters there depending on your input!

And checking:

```<code>INSERT INTO s VALUES ('2'), (''), (NULL), (' ');
INSERT INTO t VALUES ('2'), (''), (NULL), (' ');
SELECT * FROM s;
SELECT * FROM t;
</code>```

Result (same for both):

```<code>num    new_num
  2          2
          NULL
          NULL
          NULL
</code>```

So, I wanted to check how efficient my solution was, so I ran the following test inserting 10,000 records into both tables s and t as follows (from here):

```<code>EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
INSERT INTO t
with symbols(characters) as
(
  VALUES ('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
)
select string_agg(substr(characters, (random() * length(characters) + 1) :: INTEGER, 1), '')
from symbols
join generate_series(1,10) as word(chr_idx) on 1 = 1 -- word length
join generate_series(1,10000) as words(idx) on 1 = 1 -- # of words
group by idx;
</code>```

The differences weren't that huge but the regex solution was consistently slower by about 25% - even changing the order of the tables undergoing the INSERTs.

However, where the TRANSLATE solution really shines is when doing a "raw" SELECT as follows:

```<code>EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
  NULLIF(TRANSLATE(num, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ. ', ''), '')::INTEGER
FROM s;
</code>```

and the same for the REGEXP_REPLACE solution.

The differences were very marked, the TRANSLATE taking approx. 25% of the time of the other function. Finally, in the interests of fairness, I also did this for both tables:

```<code>EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
  num, new_num
FROM t;
</code>```

Both extremely quick and identical!

Body:
I have a table with a column po_number of type varchar in Postgres 8.4. It stores alphanumeric values with some special characters. I want to ignore the characters [/alpha/?/$/encoding/.] and check if the column contains a number or not. If its a number then it needs to typecast as number or else pass null, as my output field po_number_new is a number field.

Below is the example:

SQL Fiddle.

I tired this statement:

select
(case when  regexp_replace(po_number,'[^\w],.-+\?/','') then po_number::numeric
else null
end) as po_number_new from test

But I got an error for explicit cast:

Body:
Since version 12 - that's 2 years + 4 months ago at the time of writing (but after the last edit that I can see on the accepted answer), you could use a GENERATED FIELD to do this quite easily on a one-time basis rather than having to calculate it each time you wish to SELECT a new po_number.

Furthermore, you can use the TRANSLATE function to extract your digits which is less expensive than the REGEXP_REPLACE solution proposed by @ErwinBrandstetter!

I would do this as follows (all of the code below is available on the fiddle here):

CREATE TABLE s
(
  num TEXT,

  new_num INTEGER GENERATED ALWAYS AS
    (NULLIF(TRANSLATE(num, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ. ', ''), '')::INTEGER) STORED
);

You can add to the 'ABCDEFG... string in the TRANSLATE function as appropriate - I have decimal point (.) and a space ( ) at the end - you may wish to have more characters there depending on your input!

And checking:

INSERT INTO s VALUES ('2'), (''), (NULL), (' ');
INSERT INTO t VALUES ('2'), (''), (NULL), (' ');
SELECT * FROM s;
SELECT * FROM t;

Result (same for both):

num    new_num
  2          2
          NULL
          NULL
          NULL

So, I wanted to check how efficient my solution was, so I ran the following test inserting 10,000 records into both tables s and t as follows (from here):

EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
INSERT INTO t
with symbols(characters) as
(
  VALUES ('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
)
select string_agg(substr(characters, (random() * length(characters) + 1) :: INTEGER, 1), '')
from symbols
join generate_series(1,10) as word(chr_idx) on 1 = 1 -- word length
join generate_series(1,10000) as words(idx) on 1 = 1 -- # of words
group by idx;

The differences weren't that huge but the regex solution was consistently slower by about 25% - even changing the order of the tables undergoing the INSERTs.

However, where the TRANSLATE solution really shines is when doing a "raw" SELECT as follows:

EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
  NULLIF(TRANSLATE(num, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ. ', ''), '')::INTEGER
FROM s;

and the same for the REGEXP_REPLACE solution.

The differences were very marked, the TRANSLATE taking approx. 25% of the time of the other function. Finally, in the interests of fairness, I also did this for both tables:

EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
  num, new_num
FROM t;

Both extremely quick and identical!


问:
How do I loop a piece of code (have tried for, doesn't seem to work for me)
I'm looking for a way to loop the code below... so that it'll go through and print the first sentence, then the second sentence over and over until one entity's health drops to zero.

From my research (bearing in mind I'm a knucklehead) the 'for' function seems to only work with single words/numbers... but perhaps I'm wrong.

CODE:

```<code>if sentence == 1:
  print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 0

if sentence == 0:
  print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 1

#And then repeat and repeat over and over :)
</code>```

答:
Since you want the loop to happen while a particular condition is true, rather than for each item in a list/range/etc, you want a while loop:

```<code>while enemy_1_health > 0:
    print(f"The {enemy_1} {random.choice(attack_verb)} {main_character}  with its {random.choice(enemy_1_weapon)}")
    enemy_1_health -= 20
    print(enemy_1_health)

    print(f"{main_character} {random.choice(attack_verb)} the {enemy_1} with his {random.choice(main_character_weapon)}")
    enemy_1_health -= 20
    print(enemy_1_health)
</code>```

Note that you don't need the if sentence stuff because you're always setting sentence in such a way as to make it equivalent to if True, at which point you can dispense with the whole thing.

Here's an example of how you could use a for loop to iterate over the different attack scenarios:

```<code>while enemy_1_health > 0:
    for attacker, attacker_pronoun, victim, weapons in [
        (f"The {enemy_1}", "its", main_character, enemy_1_weapon),
        (main_character, "his", f"the {enemy_1}", main_character_weapon),
    ]:
        print(f"{attacker} {random.choice(attack_verb)} {victim} with {attacker_pronoun} {random.choice(weapons)}")
        enemy_1_health -= 20
        print(enemy_1_health)
</code>```

Body:
I'm looking for a way to loop the code below... so that it'll go through and print the first sentence, then the second sentence over and over until one entity's health drops to zero.

From my research (bearing in mind I'm a knucklehead) the 'for' function seems to only work with single words/numbers... but perhaps I'm wrong.

CODE:

if sentence == 1:
  print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 0

if sentence == 0:
  print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 1

#And then repeat and repeat over and over :)

Body:
Since you want the loop to happen while a particular condition is true, rather than for each item in a list/range/etc, you want a while loop:

while enemy_1_health > 0:
    print(f"The {enemy_1} {random.choice(attack_verb)} {main_character}  with its {random.choice(enemy_1_weapon)}")
    enemy_1_health -= 20
    print(enemy_1_health)

    print(f"{main_character} {random.choice(attack_verb)} the {enemy_1} with his {random.choice(main_character_weapon)}")
    enemy_1_health -= 20
    print(enemy_1_health)

Note that you don't need the if sentence stuff because you're always setting sentence in such a way as to make it equivalent to if True, at which point you can dispense with the whole thing.

Here's an example of how you could use a for loop to iterate over the different attack scenarios:

while enemy_1_health > 0:
    for attacker, attacker_pronoun, victim, weapons in [
        (f"The {enemy_1}", "its", main_character, enemy_1_weapon),
        (main_character, "his", f"the {enemy_1}", main_character_weapon),
    ]:
        print(f"{attacker} {random.choice(attack_verb)} {victim} with {attacker_pronoun} {random.choice(weapons)}")
        enemy_1_health -= 20
        print(enemy_1_health)


问:
VS Code - open a file using the same window and keeping the workspace
I want a way to open/create files from the terminal - using the same VS Code Window.

If I try to give the following command using the terminal, it'll close the current window and open a new one.

```<code>code . nameofthefile.js -r --reuse-window
</code>```

Then, if I'm running npm start - the previous command will kill it. On top of this - it'll reload my workspace removing all the folders that were in the Explorer on the left bar.

If I use only ..

```<code>code . nomeofthefile.js
</code>```

this will open a new window. That's not what I want as well.

Is it possible to open a new file without closing the current with a terminal command in VS Code?

答:
Open a folder in current vs code window while you are using the vs code terminal to change the directory:-
code -r .

Body:
I want a way to open/create files from the terminal - using the same VS Code Window.

If I try to give the following command using the terminal, it'll close the current window and open a new one.

code . nameofthefile.js -r --reuse-window

Then, if I'm running npm start - the previous command will kill it. On top of this - it'll reload my workspace removing all the folders that were in the Explorer on the left bar.

If I use only ..

code . nomeofthefile.js

this will open a new window. That's not what I want as well.

Is it possible to open a new file without closing the current with a terminal command in VS Code?


问:
Storing list elements in brackets
I have a list and I'm trying to fill it with bracketed elements. In it's simplest form, my issue is that I want example=([]) to become example=([('a','b'),('c','d')]).

More explicitly, I'm trying to turn the runnable snippet of code below into a function. But I can't get the list called text to fill properly. Here is the code working:

```<code># import prompt toolkit
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.styles import Style
# My palette
my_palette = {"my_pink": '#ff1493', "my_blue": '#0000ff',}
# The text.
text = FormattedText([('class:my_pink', 'Hello '),('class:my_blue', 'World')])
# Style sheet
style = Style.from_dict(my_palette)
# Print
print_formatted_text(text, style=style)
</code>```

This my attempt at creating a function, that at one point turns *args into list elements:

```<code>def col(*args):
    """Should take `col['word', 'colour']` and return the word in that colour."""
    text = FormattedText([])
    for a in args:
        text_template = ("class:" + str(a[1]) + "', '" + str(a[0]))
        text_template = text_template.replace("'", "")
        text.append(text_template)
    print(text) # Shows what is going on in the `text` variable (nothing good).
    style = Style.from_dict(my_palette)
    print_formatted_text(text, style=style)
</code>```

The function would be run with something like this:

```<code>col(["Hello", 'my_pink'], ["World", 'my_blue'])
</code>```

The text variable should look like the first example of text, but brackets are missing and the commas are in strings so it looks like this:

```<code>text = FormattedText([('class:my_pink, Hello ', 'class:my_blue', 'World'])
</code>```

Rather than like this:

```<code>text = FormattedText([('class:my_pink', 'Hello '), ('class:my_blue', 'World')])
</code>```

I tried further manipulation, using variations of the following:

```<code>text = format(', '.join('({})'.format(i) for i in text))
</code>```

But honestly I cant understand how I making such a pigs ear of a simple problem. I have tried a lot of 'jammy' solutions but none work and I would like a pythonic one.

答:
You can use list comprehension and f-string:

def col(*args):
    """Should take `col['word', 'colour']` and return the word in that colour."""
    text = FormattedText([(f"class:{a[1]}", str(a[0])) for a in args])
    print(text) # Shows what is going on in the `text` variable (nothing good).
    style = Style.from_dict(my_palette)
    print_formatted_text(text, style=style)
```

Title: Storing list elements in brackets

Body:
I have a list and I'm trying to fill it with bracketed elements. In it's simplest form, my issue is that I want example=([]) to become example=([('a','b'),('c','d')]).

More explicitly, I'm trying to turn the runnable snippet of code below into a function. But I can't get the list called text to fill properly. Here is the code working:

# import prompt toolkit
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.styles import Style
# My palette
my_palette = {"my_pink": '#ff1493', "my_blue": '#0000ff',}
# The text.
text = FormattedText([('class:my_pink', 'Hello '),('class:my_blue', 'World')])
# Style sheet
style = Style.from_dict(my_palette)
# Print
print_formatted_text(text, style=style)

This my attempt at creating a function, that at one point turns *args into list elements:

def col(*args):
    """Should take `col['word', 'colour']` and return the word in that colour."""
    text = FormattedText([])
    for a in args:
        text_template = ("class:" + str(a[1]) + "', '" + str(a[0]))
        text_template = text_template.replace("'", "")
        text.append(text_template)
    print(text) # Shows what is going on in the `text` variable (nothing good).
    style = Style.from_dict(my_palette)
    print_formatted_text(text, style=style)

The function would be run with something like this:

col(["Hello", 'my_pink'], ["World", 'my_blue'])

The text variable should look like the first example of text, but brackets are missing and the commas are in strings so it looks like this:

text = FormattedText([('class:my_pink, Hello ', 'class:my_blue', 'World'])

Rather than like this:

text = FormattedText([('class:my_pink', 'Hello '), ('class:my_blue', 'World')])

I tried further manipulation, using variations of the following:

text = format(', '.join('({})'.format(i) for i in text))

But honestly I cant understand how I making such a pigs ear of a simple problem. I have tried a lot of 'jammy' solutions but none work and I would like a pythonic one.


问:
Show/hide floating div by click on right side of the screen
I need to make a floating div that appears to be almost hidden and if I click in the tab it appears to the left. Floating over the rest of the site. I don't know if I made myself clear, so I put here two images, how it should look hidden and visible. But I couldn't figure it out yet how to make it. Any help will be appreciated.

I work with VueJS.

答:
This is a vanilla js implementation that uses fixed position, the css transition property for animation, and a class that is toggled when the handle is clicked to change the position.

const slideout = document.querySelector('.slideout')

const handle = slideout.querySelector('.handle')

handle.onclick = function() {
  slideout.classList.toggle('active');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slideout {
  position: fixed;
  width: 80%;
  height: 80%;
  left: 100%;
  top: 10%;
  transition: left .3s ease-out;
}

.slideout.active {
  left: 10%;
}

.handle {
  position: absolute;
  top: 10px;
  left: -20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: darkred;
  cursor: pointer;
}

.body {
  position: absolute;
  background: red;
  width: 100%;
  height: 100%;
  border-radius: 8px;
}</code>```

```

Body:
This is a vanilla js implementation that uses fixed position, the css transition property for animation, and a class that is toggled when the handle is clicked to change the position.

const slideout = document.querySelector('.slideout')

const handle = slideout.querySelector('.handle')

handle.onclick = function() {
  slideout.classList.toggle('active');
}

.slideout {
  position: fixed;
  width: 80%;
  height: 80%;
  left: 100%;
  top: 10%;
  transition: left .3s ease-out;
}

.slideout.active {
  left: 10%;
}

.handle {
  position: absolute;
  top: 10px;
  left: -20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: darkred;
  cursor: pointer;
}

.body {
  position: absolute;
  background: red;
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

<div class="slideout">
  <div class="handle"></div>
  <div class="body"></div>
</div>


问:
Why is my code not printing in the debug console?
I am new to coding and to Visual Studio Code so I am trying to teach myself how to use the program. I primarily want to code in Java and I have it set up correctly. The problem is that every time I try to run a basic program, it prints in the terminal but in the tutorial videos it prints in debug console. Has anyone had this problem and can anyone help me fix this?

/**
 * Hello
 */
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
```

答:
Go to your settings (ctrl + , | apple-key + , | by clicking on the Wheel Icon on the bottom left -> "Settings" | ctrl+p -> type in "settings")

Search for "java.debug.settings.console".

Change your default console to "internalConsole".


问:
ModuleNotFoundError despite declairing install_requires in setup.py
I wrote create a package uploaded to PyPI for testing, but I keep getting a ModuleNotFoundError for pandas when I try to import it to a virtual environment. I import pandas in a file in the package and therefore, declared it in setup.py under install_requires = ['pandas']. Before that, I had a setup.cfg and declared it in pyproject.toml\

```<code>[build-system]
requires = [
    "setuptools>=42",
    "pandas",
    "wheel"
]
build-backend = "setuptools.build_meta"
</code>```

but neither worked. Am I declaring pandas at the wrong place? Are there some other files/folder-structure which I should share for solving this problem? Any help is welcome

答: Ok, so it did actually work as soon as I uploaded it to the "real" PyPl. I have no clue why it wouldn't work for Test PyPl, if you do know, feel free to enlighten us in the comments, I'll update the answer.</p>

Body:
I wrote create a package uploaded to PyPI for testing, but I keep getting a ModuleNotFoundError for pandas when I try to import it to a virtual environment. I import pandas in a file in the package and therefore, declared it in setup.py under install_requires = ['pandas']. Before that, I had a setup.cfg and declared it in pyproject.toml\

[build-system]
requires = [
    "setuptools>=42",
    "pandas",
    "wheel"
]
build-backend = "setuptools.build_meta"

but neither worked. Am I declaring pandas at the wrong place? Are there some other files/folder-structure which I should share for solving this problem? Any help is welcome


问:
Not able to access a customfield in Jira Rest Api
I need to get the timestamp of the duration an issue was made the transition into "Waiting-for-Input" state. I tried to get this using custom_fields using this URL <{jira-base-url}/rest/api/2/field>
I found out there is a custom_field for it which is as follows

```<code>{
        "id": "customfield_13225",
        "name": 'Days in "Waiting-for-Input"',
        "custom": True,
        "orderable": True,
        "navigable": True,
        "searchable": True,
        "clauseNames": ["cf[13225]", 'Days in "Waiting-for-Input"'],
        "schema": {
            "type": "string",
            "custom": "com.onresolve.jira.groovy.groovyrunner:scripted-field",
            "customId": 13225,
        },
}
</code>```

But when I try to access this customfield I get an error like

AttributeError: 'PropertyHolder' object has no attribute
'customfield_13225'

The code which I am trying is

```<code>issue = jira.issue('ABC-1')
print(issue.fields.customfield_13225)
</code>```

Need help to access this customfield.

I am using JIRA Rest API and using python 3.7

答: This customfield was blocked by my administrator. Had to request them to allow access to this customfield after which I was able to access this field.</p>

Body:
I need to get the timestamp of the duration an issue was made the transition into "Waiting-for-Input" state. I tried to get this using custom_fields using this URL <{jira-base-url}/rest/api/2/field>
I found out there is a custom_field for it which is as follows

{
        "id": "customfield_13225",
        "name": 'Days in "Waiting-for-Input"',
        "custom": True,
        "orderable": True,
        "navigable": True,
        "searchable": True,
        "clauseNames": ["cf[13225]", 'Days in "Waiting-for-Input"'],
        "schema": {
            "type": "string",
            "custom": "com.onresolve.jira.groovy.groovyrunner:scripted-field",
            "customId": 13225,
        },
}

But when I try to access this customfield I get an error like

AttributeError: 'PropertyHolder' object has no attribute
'customfield_13225'

The code which I am trying is

issue = jira.issue('ABC-1')
print(issue.fields.customfield_13225)

Need help to access this customfield.

I am using JIRA Rest API and using python 3.7


问:
How to make external dependencies on a shared items project in VS?
I am in need of sharing some header files between two different projects. So I created a shared items project, and now I can't figure out how to add external dependencies to it, so I could use includes from the WDK 10 shared folder. Did anyone run into this problem before? I can still add external dependencies on a library project, but somehow not on shared items.</p>

答:
As the article says

These “shared items” projects don’t participate in build but they can
contain any number of C++ headers and sources.

And you need to add the dependencies to the actual build project.


问:
Custom resolver to select a field from a DictConfig
```<code>nodes:
  node1: 1
  node2: 2
  node3: 3

selected_node: ${subfield:${nodes},node1}
</code>```

Can I make a subfield resolver that returns nodes["node1"] and stores it in selected_node?

My attempts so far result in this error:

```<code>omegaconf.errors.GrammarParseError: token recognition error at: '{'
    full_key: selected_node
    object_type=dict
</code>```

答:
from omegaconf import OmegaConf
s = """
nodes:
  node1: 1
  node2: 2
  node3: 3

selected: ${subfield:${nodes},node1}
"""

def _subfield(node, field):
    return node[field]

OmegaConf.register_new_resolver("subfield", _subfield)
a = OmegaConf.create(s)
print(a.selected) # -> 1
```

Body:
nodes:
  node1: 1
  node2: 2
  node3: 3

selected_node: ${subfield:${nodes},node1}

Can I make a subfield resolver that returns nodes["node1"] and stores it in selected_node?

My attempts so far result in this error:

omegaconf.errors.GrammarParseError: token recognition error at: '{'
    full_key: selected_node
    object_type=dict


问:
sorting some data
I am trying to sort some data in bash. Data looks like below.

```<code>    20110724.gz   1347
    20110724.gz   2128
    20110725.gz   1315
    20110725.gz   2334
    20110726.gz   808
    20110726.gz   1088
    -bash-3.2$
</code>```

After sorting, it should look like

```<code>    20110724.gz 3475
    20110725.gz 3649
    20110726.gz 1896
</code>```

Basically, for a given date, the data are summed up. Can somebody help? Thanks.

hmm, hopefully I figure it out in a few days.

答:
You don't need perl for doing that. Some shell trickery will help :)

```<code>sort -n -k1,8 <file | while true ; do
    if ! read line ; then
        test -n "$accfile" && echo $accfile $value
        break
    fi
    line=$(echo $line | tr -s ' ' )
    curfile=$(echo $line | cut -d\  -f1)
    curvalue=$(echo $line | cut -d\  -f2)
    if [ $curfile != "$accfile" ] ; then
        # new file, output the last if not empty
        test -n "$accfile" && echo $accfile $value
        accfile=$curfile
        value=$curvalue
    else
        value=$(expr $value \+ $curvalue)
    fi
done
</code>```

The k parameter tells sort what characters use to sort. As dates are put in number-ordered format, a number sort (-n) works.

Title: sorting some data

Body:
I am trying to sort some data in bash. Data looks like below.

    20110724.gz   1347
    20110724.gz   2128
    20110725.gz   1315
    20110725.gz   2334
    20110726.gz   808
    20110726.gz   1088
    -bash-3.2$

After sorting, it should look like

    20110724.gz 3475
    20110725.gz 3649
    20110726.gz 1896

Basically, for a given date, the data are summed up. Can somebody help? Thanks.

hmm, hopefully I figure it out in a few days.

Body:
You don't need perl for doing that. Some shell trickery will help :)

sort -n -k1,8 <file | while true ; do
    if ! read line ; then
        test -n "$accfile" && echo $accfile $value
        break
    fi
    line=$(echo $line | tr -s ' ' )
    curfile=$(echo $line | cut -d\  -f1)
    curvalue=$(echo $line | cut -d\  -f2)
    if [ $curfile != "$accfile" ] ; then
        # new file, output the last if not empty
        test -n "$accfile" && echo $accfile $value
        accfile=$curfile
        value=$curvalue
    else
        value=$(expr $value \+ $curvalue)
    fi
done

The k parameter tells sort what characters use to sort. As dates are put in number-ordered format, a number sort (-n) works.


问:
Xamarin Forms BLE Plugin Scan Issue Android 12
I have written a xamarin forms app which uses the Plugin.BLE NuGet package to scan and connect to ble devices. It was working/debugging flawlessly on my phone until it(my phone) updated to Android 12.0 - API 31. I am using the basic vanilla implementation from the plugin:

```<code>adapter.DeviceDiscovered += (s,a) => deviceList.Add(a.Device);
await adapter.StartScanningForDevicesAsync();
</code>```

I have found that Android 12 requires different runtime permissions ([https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#declare-android11-or-lower][1]) and I have tried to accomodate them in the manifest file:

```<code>    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
    <application android:label="Rep_001.Android" android:theme="@style/MainTheme"></application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#declare-android11-or-lower
</code>```

but alas I am having no luck. I am thinking that I need to ask the user for scan and connect privileges at runtime but I am not sure how to do that as Xamarin.Essentials does not have bluetooth permissions requests.

答:
The BLUETOOTH_ADVERTISE, BLUETOOTH_CONNECT, and BLUETOOTH_SCAN permissions are runtime permissions.

Therefore, you must explicitly request user approval in your app before you can look for Bluetooth devices, make a device discoverable to other devices, or communicate with already-paired Bluetooth devices.

When your app requests at least one of these permissions, the system prompts the user to allow your app to access Nearby devices.

Body:
I have written a xamarin forms app which uses the Plugin.BLE NuGet package to scan and connect to ble devices. It was working/debugging flawlessly on my phone until it(my phone) updated to Android 12.0 - API 31. I am using the basic vanilla implementation from the plugin:

adapter.DeviceDiscovered += (s,a) => deviceList.Add(a.Device);
await adapter.StartScanningForDevicesAsync();

I have found that Android 12 requires different runtime permissions ([https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#declare-android11-or-lower][1]) and I have tried to accomodate them in the manifest file:

    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
    <application android:label="Rep_001.Android" android:theme="@style/MainTheme"></application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#declare-android11-or-lower

but alas I am having no luck. I am thinking that I need to ask the user for scan and connect privileges at runtime but I am not sure how to do that as Xamarin.Essentials does not have bluetooth permissions requests.


问:
Is there a way to read mouse wheel data inside while loop without locking while loop in ubuntu in C?
Hello the masters of C and C++.
I am trying to get mouse wheel data in while loop using read function.

I am in Ubuntu 20.04 and using C language.

Here's brief code I did so far.
the "read" function keeps blocking the while loop and waits for the input.
I want to process the while loop when there is no input.

Is there any way that I could achieve this? or is there any library that I could use of? It doesn't have to be read function if there's any other way.

Thank you all

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <linux/input.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
  int fd;
  struct input_event event_data;

  if ((fd = open("/dev/input/event19", O_RDONLY)) == -1) {  // mice mouse0 event19
    perror("opening device");
    exit(EXIT_FAILURE);
  }

  // wheel data: 8 2 +-1 11 2 +-120

  while (1) {
    read(fd, &event_data, sizeof(event_data));
    if (((event_data.code == 8) || (event_data.code == 6)) && (event_data.type == 2) &&
        ((event_data.value == 1) || (event_data.value == -1))) {
        printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
            event_data.value);
    } else if (event_data.code != 0) {
        printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
            event_data.value);
    }
    printf("\nCheck while\n");
  }

  return 0;
}
</code>```

答:
I think we have 2 method:

1st is use multithread  : one thread for reading input and another for main logic. ex https://www.geeksforgeeks.org/multithreading-c-2/

2nd use nonblocking flag like this

```<code>int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
while (1)
{

    if (-1 != read(fd, &event_data, sizeof(event_data)))
    {
        if (((event_data.code == 8) || (event_data.code == 6)) && (event_data.type == 2) &&
            ((event_data.value == 1) || (event_data.value == -1)))
        {
            printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
                   event_data.value);
        }
        else if (event_data.code != 0)
        {
            printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
                   event_data.value);
        }
    }

    printf("\nCheck while\n");
}
</code>```

The code snippet above will configure such a descriptor for non-blocking access. If data is not available when you call read, then the system call will fail with a return value of -1 and errno is set to EAGAIN. See the fnctl man pages for more information

refer : Non-blocking call for reading descriptor

Body:
Hello the masters of C and C++.
I am trying to get mouse wheel data in while loop using read function.

I am in Ubuntu 20.04 and using C language.

Here's brief code I did so far.
the "read" function keeps blocking the while loop and waits for the input.
I want to process the while loop when there is no input.

Is there any way that I could achieve this? or is there any library that I could use of? It doesn't have to be read function if there's any other way.

Thank you all

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

#include <linux/input.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
  int fd;
  struct input_event event_data;

  if ((fd = open("/dev/input/event19", O_RDONLY)) == -1) {  // mice mouse0 event19
    perror("opening device");
    exit(EXIT_FAILURE);
  }

  // wheel data: 8 2 +-1 11 2 +-120

  while (1) {
    read(fd, &event_data, sizeof(event_data));
    if (((event_data.code == 8) || (event_data.code == 6)) && (event_data.type == 2) &&
        ((event_data.value == 1) || (event_data.value == -1))) {
        printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
            event_data.value);
    } else if (event_data.code != 0) {
        printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
            event_data.value);
    }
    printf("\nCheck while\n");
  }

  return 0;
}

Body:
I think we have 2 method:

1st is use multithread  : one thread for reading input and another for main logic. ex https://www.geeksforgeeks.org/multithreading-c-2/

2nd use nonblocking flag like this

int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
while (1)
{

    if (-1 != read(fd, &event_data, sizeof(event_data)))
    {
        if (((event_data.code == 8) || (event_data.code == 6)) && (event_data.type == 2) &&
            ((event_data.value == 1) || (event_data.value == -1)))
        {
            printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
                   event_data.value);
        }
        else if (event_data.code != 0)
        {
            printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
                   event_data.value);
        }
    }

    printf("\nCheck while\n");
}

The code snippet above will configure such a descriptor for non-blocking access. If data is not available when you call read, then the system call will fail with a return value of -1 and errno is set to EAGAIN. See the fnctl man pages for more information

refer : Non-blocking call for reading descriptor


问:
Docker container and FIPS mode enabled
We're trying to get a SAP HanaExpress container running on a VM that has FIPS mode enabled, but it will not start up due to a FATAL FIPS SELFTEST FAILURE error. The VM is running CentOS 7, though I'm not sure that matters. I've read several articles/posts and it appears the running container does recognize that FIPS mode is enabled, but the service still doesn't work. Both of these checks work:

cat /proc/sys/crypto/fips_enabled

sysctl crypto.fips_enabled

The container is running in privileged mode and the /etc/system-fips file is mounted into the container as well. Is there anything else I need to check to make this work or at least debug the issue? I have a feeling there's something small, and not HanaExpress specific, that I'm missing, but I just haven't found it yet.

Edit1: It looks like the issue is Docker and not the container. I finally found info that fips mode should be reported as active when you run the docker info command, but it wasn't showing up. CentOS 7 installs the 1.13.1 version, which appears to be too old, so I downloaded and installed 20.10.9. However, even following the instructions provided by docker, it's not reporting fips mode as active. If anyone else has had this issue and solved it, any advice would be great.

答:
/proc/... files are READ-only files

If you don't need FIPS enabled, then try this and see if it goes away. https://www.thegeekdiary.com/how-to-disable-fips-mode-on-centos-rhel-7/
then test if fips is enabled or not by running sysctl -a 2>/dev/null | grep fips_enabled and see if sudo yum list installed | grep "dracut.fips" shows dracut-fips is installed or not.

I believe that if the HOST OS where you are running Docker container has this disabled, then you may not see this error

Title: Docker container and FIPS mode enabled


问:
Refresh a view when the children of an object are changed in SwiftUI
I am working on a CoreData application with two entities MyList and MyListItem. MyList can have many MyListItem (one to many). When the app is launched, I can see all the lists. I can tap on a list to go to the list items. On that screen, I tap a button to add an item to the selected list. After, adding the item when I go back to the all lists screen I cannot see the number of items reflected in the count. The reason is that MyListsView is not rendered again since the number of lists have not changed.

The complete code is shown below:

```<code>import SwiftUI
import CoreData

extension MyList {

    static var all: NSFetchRequest<MyList> {
        let request = MyList.fetchRequest()
        request.sortDescriptors = []
        return request
    }
}

struct DetailView: View {

    @Environment(\.managedObjectContext) var viewContext
    let myList: MyList

    var body: some View {
        VStack {
            Text("Detail View")
            Button("Add List Item") {

                let myListP = viewContext.object(with: myList.objectID) as! MyList

                let myListItem = MyListItem(context: viewContext)
                myListItem.name = randomString()
                myListItem.myList = myListP

                try? viewContext.save()

            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}

class ViewModel: NSObject, ObservableObject {

    @Published var myLists: [MyList] = []

    private var fetchedResultsController: NSFetchedResultsController<MyList>
    private(set) var context: NSManagedObjectContext

    override init() {
        self.context = CoreDataManager.shared.context

        fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        super.init()
        fetchedResultsController.delegate = self

        do {
            try fetchedResultsController.performFetch()
            guard let myLists = fetchedResultsController.fetchedObjects else { return }
            self.myLists = myLists

        }  catch {
            print(error)
        }
    }
}

extension ViewModel: NSFetchedResultsControllerDelegate {
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        guard let myLists = controller.fetchedObjects as? [MyList] else { return }
        self.myLists = myLists
    }
}

struct MyListsView: View {

    let myLists: [MyList]

    var body: some View {
        List(myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                HStack {
                    Text(myList.name ?? "")
                    Spacer()

                    Text("\((myList.items ?? []).count)")
                }
            }
        }
    }
}

struct ContentView: View {

    @StateObject private var vm = ViewModel()
    @Environment(\.managedObjectContext) var viewContext

    var body: some View {
        NavigationView {
            VStack {

                // when adding an item to the list the MyListView view is
                // not re-rendered
                MyListsView(myLists: vm.myLists)

                Button("Change List") {

                }
            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}
</code>```

Inside ContentView there is a view called "MyListsView". That view is not rendered when the items are added. Since, according to that view nothing changed since the number of lists are still the same.

How do you solve this problem?

UPDATE:

What happens if I add one more level of views like for ListCellView as shown below:

```<code>struct MyListCellView: View {

    @StateObject var vm: ListCellViewModel

    init(vm: ListCellViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        HStack {
            Text(vm.name)
            Spacer()

            Text("\((vm.items).count)")
        }
    }
}

@MainActor
class ListCellViewModel: ObservableObject {

    let myList: MyList

    init(myList: MyList) {
        self.myList = myList
        self.name = myList.name ?? ""
        self.items = myList.items!.allObjects as! [MyListItem]
        print(self.items.count)
    }

    @Published var name: String = ""
    @Published var items: [MyListItem] = []
}

struct MyListsView: View {

    @StateObject var vm: ViewModel

    init(vm: ViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        let _ = Self._printChanges()
        List(vm.myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                MyListCellView(vm: ListCellViewModel(myList: myList))
            }
        }
    }
}
</code>```

Now the count is again not being updated.

答:
Your ViewModel is an ObserveableObject, but you are not observing it in MyListsView. When you initialized MyListsView, you set a let constant. Of course that won't update. Do this instead:

```<code>struct MyListsView: View {

    @ObservedObject var vm: ViewModel

    init(viewModel: ViewModel) {
        self.vm = viewModel
    }

    var body: some View {
        List(vm.myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                HStack {
                    Text(myList.name ?? "")
                    Spacer()

                    Text("\((myList.items ?? []).count)")
                }
            }
        }
    }
}
</code>```

Now the @Published in ViewModel will cause MyListView to change when it does, and that includes adding a related entity.

Body:
I am working on a CoreData application with two entities MyList and MyListItem. MyList can have many MyListItem (one to many). When the app is launched, I can see all the lists. I can tap on a list to go to the list items. On that screen, I tap a button to add an item to the selected list. After, adding the item when I go back to the all lists screen I cannot see the number of items reflected in the count. The reason is that MyListsView is not rendered again since the number of lists have not changed.

The complete code is shown below:

import SwiftUI
import CoreData

extension MyList {

    static var all: NSFetchRequest<MyList> {
        let request = MyList.fetchRequest()
        request.sortDescriptors = []
        return request
    }
}

struct DetailView: View {

    @Environment(\.managedObjectContext) var viewContext
    let myList: MyList

    var body: some View {
        VStack {
            Text("Detail View")
            Button("Add List Item") {

                let myListP = viewContext.object(with: myList.objectID) as! MyList

                let myListItem = MyListItem(context: viewContext)
                myListItem.name = randomString()
                myListItem.myList = myListP

                try? viewContext.save()

            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}

class ViewModel: NSObject, ObservableObject {

    @Published var myLists: [MyList] = []

    private var fetchedResultsController: NSFetchedResultsController<MyList>
    private(set) var context: NSManagedObjectContext

    override init() {
        self.context = CoreDataManager.shared.context

        fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        super.init()
        fetchedResultsController.delegate = self

        do {
            try fetchedResultsController.performFetch()
            guard let myLists = fetchedResultsController.fetchedObjects else { return }
            self.myLists = myLists

        }  catch {
            print(error)
        }
    }
}

extension ViewModel: NSFetchedResultsControllerDelegate {
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        guard let myLists = controller.fetchedObjects as? [MyList] else { return }
        self.myLists = myLists
    }
}

struct MyListsView: View {

    let myLists: [MyList]

    var body: some View {
        List(myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                HStack {
                    Text(myList.name ?? "")
                    Spacer()

                    Text("\((myList.items ?? []).count)")
                }
            }
        }
    }
}

struct ContentView: View {

    @StateObject private var vm = ViewModel()
    @Environment(\.managedObjectContext) var viewContext

    var body: some View {
        NavigationView {
            VStack {

                // when adding an item to the list the MyListView view is
                // not re-rendered
                MyListsView(myLists: vm.myLists)

                Button("Change List") {

                }
            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}

Inside ContentView there is a view called "MyListsView". That view is not rendered when the items are added. Since, according to that view nothing changed since the number of lists are still the same.

How do you solve this problem?

UPDATE:

What happens if I add one more level of views like for ListCellView as shown below:

struct MyListCellView: View {

    @StateObject var vm: ListCellViewModel

    init(vm: ListCellViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        HStack {
            Text(vm.name)
            Spacer()

            Text("\((vm.items).count)")
        }
    }
}

@MainActor
class ListCellViewModel: ObservableObject {

    let myList: MyList

    init(myList: MyList) {
        self.myList = myList
        self.name = myList.name ?? ""
        self.items = myList.items!.allObjects as! [MyListItem]
        print(self.items.count)
    }

    @Published var name: String = ""
    @Published var items: [MyListItem] = []
}

struct MyListsView: View {

    @StateObject var vm: ViewModel

    init(vm: ViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        let _ = Self._printChanges()
        List(vm.myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                MyListCellView(vm: ListCellViewModel(myList: myList))
            }
        }
    }
}

Now the count is again not being updated.

Body:
Your ViewModel is an ObserveableObject, but you are not observing it in MyListsView. When you initialized MyListsView, you set a let constant. Of course that won't update. Do this instead:

struct MyListsView: View {

    @ObservedObject var vm: ViewModel

    init(viewModel: ViewModel) {
        self.vm = viewModel
    }

    var body: some View {
        List(vm.myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                HStack {
                    Text(myList.name ?? "")
                    Spacer()

                    Text("\((myList.items ?? []).count)")
                }
            }
        }
    }
}

Now the @Published in ViewModel will cause MyListView to change when it does, and that includes adding a related entity.


问:
How to remove duplicate words removing duplicates not case sensetive
I have a string

```<code>str1='This Python is good Good python'
</code>```

I want the output removing duplicates keeping in the first word irrespective of case, for eg. good and Good are considered same as Python python. The output should be

```<code>output='This Python is good'
</code>```

答:
One approach might be to use regular expressions to remove any word for which we can find a duplicate.  The catch is that regex engines move from start to end of a string.  Since you want to retain the first occurrence, we can reverse the string, and then do the cleanup.

str1 = 'This Python is good Good python'
str1_reverse = ' '.join(reversed(str1.split(' ' )))
str1_reverse = re.sub(r'\s*(\w+)\s*(?=.*\b\1\b)', ' ', str1_reverse, flags=re.I)
str1 = ' '.join(reversed(str1_reverse.strip().split(' ' )))
print(str1)  # This Python is good
```

Body:
I have a string

str1='This Python is good Good python'

I want the output removing duplicates keeping in the first word irrespective of case, for eg. good and Good are considered same as Python python. The output should be

output='This Python is good'


问:
Django update_or_create using foreying key objects
My app have two models, PortfolioAsset and Transction.

I am trying to use update_or_create in the transaction to find if the object PortfolioAsset exist with the selected parameters. If it exist to update, if not to create.

But i am getting this error:

Cannot assign "(<PortfolioAsset: PortfolioAsset object (11)>, False)": "Transaction.portfolio_asset" must be a "PortfolioAsset" instance.

This was the exisiting object that i would like to update in this example.

PortfolioAsset

```<code>class PortfolioAsset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0)

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.\
                filter(portfolio=self.portfolio, asset=self.asset).\
                exists():
            raise ValidationError(
                message='This asset already exists in this portfolio.',
                code='unique_together',
            )

</code>```

and Transactions:

```<code>class Transaction(models.Model):
    OrderChoices = (
        ('Buy', 'Buy'),
        ('Sell', 'Sell'),
    )
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, default=1)
    portfolio_asset = models.ForeignKey(PortfolioAsset, on_delete=models.CASCADE, editable=False)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0)
    order = models.CharField(max_length = 8, choices = OrderChoices)

    def save(self, *args, **kwargs):
        self.portfolio_asset = PortfolioAsset.objects.update_or_create(portfolio=self.portfolio, asset=self.asset)
        if self.order == 'Buy':
            self.portfolio_asset.shares_amount += self.shares_amount
        if self.order == 'Sell':
            self.portfolio_asset.shares_amount -= self.shares_amount
        self.portfolio_asset.save()
        super(Transaction, self).save(*args, **kwargs)
</code>```

What am i doing wrong? Thanks

答:
update_or_create..[Django-doc] returns a tuple: the object, and a flag that indicates whether or not it was created.

So you will have to capture the object first like this:

self.portfolio_asset, created = PortfolioAsset.objects.update_or_create(portfolio=self.portfolio, asset=self.asset)
                      # ^^^ Add this
```

Body:
My app have two models, PortfolioAsset and Transction.

I am trying to use update_or_create in the transaction to find if the object PortfolioAsset exist with the selected parameters. If it exist to update, if not to create.

But i am getting this error:

Cannot assign "(<PortfolioAsset: PortfolioAsset object (11)>, False)": "Transaction.portfolio_asset" must be a "PortfolioAsset" instance.

This was the exisiting object that i would like to update in this example.

PortfolioAsset

class PortfolioAsset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0)

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.\
                filter(portfolio=self.portfolio, asset=self.asset).\
                exists():
            raise ValidationError(
                message='This asset already exists in this portfolio.',
                code='unique_together',
            )

and Transactions:

class Transaction(models.Model):
    OrderChoices = (
        ('Buy', 'Buy'),
        ('Sell', 'Sell'),
    )
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, default=1)
    portfolio_asset = models.ForeignKey(PortfolioAsset, on_delete=models.CASCADE, editable=False)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0)
    order = models.CharField(max_length = 8, choices = OrderChoices)

    def save(self, *args, **kwargs):
        self.portfolio_asset = PortfolioAsset.objects.update_or_create(portfolio=self.portfolio, asset=self.asset)
        if self.order == 'Buy':
            self.portfolio_asset.shares_amount += self.shares_amount
        if self.order == 'Sell':
            self.portfolio_asset.shares_amount -= self.shares_amount
        self.portfolio_asset.save()
        super(Transaction, self).save(*args, **kwargs)

What am i doing wrong? Thanks


问:
How to create reusable dropdown component using material ui or mui in react?
Any solution to create reusable dropdown component using material ui or mui in react ?</p>

答:
I think you can use Material UI - Autocomplete component to create the reusable dropdown component.

Here is the documentation and code example inside:

https://mui.com/components/autocomplete/#main-content


问:
Returning many-to-one composite in SQL in one row
I have the following tables

```<code>User
---------------------------
UserID, FirstName, LastName

Role
---------------------------
RoleID, UserID, RoleName
</code>```

Assuming a many to one relationship between Role and User what is the best way I can return in one query a user along with all the roles they might be in, in a single row?

Previously I have always loaded the Roles (or similar data) in a separate query but the problem is that if your data grows this technique becomes too slow.

答: Getting your data into a single row with more columns isn't inherently more efficient than returning multiple rows with fewer columns. Creating and destroying the connection is probably the most expensive operation your doing, so you might consider creating a stored procedure that wraps both queries and then accessing the results using NextResult</p>

Body:
I have the following tables

User
---------------------------
UserID, FirstName, LastName

Role
---------------------------
RoleID, UserID, RoleName

Assuming a many to one relationship between Role and User what is the best way I can return in one query a user along with all the roles they might be in, in a single row?

Previously I have always loaded the Roles (or similar data) in a separate query but the problem is that if your data grows this technique becomes too slow.


问:
React testing library getting element
I have a simple test as I am learning react testing library. I basically took this off of the website. Here is my test:

```<code>    import React from 'react';
    import {render, screen, fireEvent} from '@testing-library/react'

    import DateInput from '../dateInput';

test('calls onChange event is fired', () => {
    const onChange = jest.fn()
    const {getByLabelText} = render(<DateInput ariaLabel='test-date' onChange={onChange}/>);
    const element = getByLabelText('test-date');
    fireEvent.change(element, {target: {value: '2020-05-24'}});
    expect(onChange).toHaveBeenCalledTimes(1)
  })
</code>```

DateInput is a simple component that allows the user to enter a date value. The component boils down to

```<code>  <div>
    <input
      class="form-control"
      type="date"
      value=""
    />
  </div>
</code>```

So there is an HTML input that I am assuming has a role of 'input'. The test is failing because TestingLibraryElementError: Unable to find an element with the role "input". I am not sure how to get access to this element?

答:
The most efficient and productive way to get an element is through aria-label. It's both good for accessibility (for example screen readers) and easy to target the element.

You could do something like such

Component

```<code> <input
    class="form-control"
    type="date"
    value=""
    ariaLabel="Departure Date" //Example
 />
</code>```

Test

```<code>test('calls onChange prop when clicked', () => {
    const onChange = jest.fn()
    const {getByLabelText} = render(<DateInput onChange={onChange}/>);
    const element = getByLabelText("Departure Date");
    fireEvent.change(element, {target: {value: '2020-05-24'}});
    expect(onChange).toHaveBeenCalledTimes(1)
})
</code>```

Also side note, try to refrain from using getByRole as there is a huge perfordifference using that versus other queries.

Title: React testing library getting element

Body:
I have a simple test as I am learning react testing library. I basically took this off of the website. Here is my test:

    import React from 'react';
    import {render, screen, fireEvent} from '@testing-library/react'

    import DateInput from '../dateInput';

test('calls onChange event is fired', () => {
    const onChange = jest.fn()
    const {getByLabelText} = render(<DateInput ariaLabel='test-date' onChange={onChange}/>);
    const element = getByLabelText('test-date');
    fireEvent.change(element, {target: {value: '2020-05-24'}});
    expect(onChange).toHaveBeenCalledTimes(1)
  })

DateInput is a simple component that allows the user to enter a date value. The component boils down to

    <input
      class="form-control"
      type="date"
      value=""
    />

So there is an HTML input that I am assuming has a role of 'input'. The test is failing because TestingLibraryElementError: Unable to find an element with the role "input". I am not sure how to get access to this element?

Body:
The most efficient and productive way to get an element is through aria-label. It's both good for accessibility (for example screen readers) and easy to target the element.

You could do something like such

Component

 <input
    class="form-control"
    type="date"
    value=""
    ariaLabel="Departure Date" //Example
 />

Test

test('calls onChange prop when clicked', () => {
    const onChange = jest.fn()
    const {getByLabelText} = render(<DateInput onChange={onChange}/>);
    const element = getByLabelText("Departure Date");
    fireEvent.change(element, {target: {value: '2020-05-24'}});
    expect(onChange).toHaveBeenCalledTimes(1)
})

Also side note, try to refrain from using getByRole as there is a huge perfordifference using that versus other queries.


问:
Module Object not callable from beautiful soup
Just starting to build my first webscraper and I cannot figure out why my beautifulsoup module isn't able to call. Thank you for helping the beginner :(

import requests
from bs4 import BeautifulSoup

# Import your website here
html_text = requests.get(
    'https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=').text

soup = BeautifulSoup(html_text, 'lxml')

# Find the part of the webpage where your information is in
job = soup.find_all('li', class_='clearfix job-bx wht-shd-bx')
company_name = job.find('h3', class_='joblist-comp-name').text.replace(' ', '')
skills = job.find('span', class_='srp-skills').text.replace(' ', '')
published_date = job.find('span', class_='sim-posted').span.text

print(published_date)

print(f'''
Company name: {company_name}
Required Skills: {skills}

''')
```
```Traceback (most recent call last):
  File "c:\Users\GamingPC\OneDrive - University of Pittsburgh\Random Work\Desktop\Python Projects\Web scraping.py", line 12, in <module>
    company_name = job.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '')
  File "C:\Users\GamingPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bs4\element.py", line 2253, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
```

答:
As John Gordon says, you can't call find() on a result set, so you need to iterate over the variable job, something like this would work:

```<code>import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
job = soup.find_all('li', class_ = 'clearfix job-bx wht-shd-bx')

for item in job:
    company_name = item.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '').strip()
    skills = item.find('span', class_ = 'srp-skills').text.replace(' ', '').strip()
    published_date = item.find('span', class_ = 'sim-posted').span.text

    print(published_date)

    print(f'''
    Company name: {company_name}
    Required Skills: {skills}

    ''')
</code>```

Body:
Just starting to build my first webscraper and I cannot figure out why my beautifulsoup module isn't able to call. Thank you for helping the beginner :(

import requests
from bs4 import BeautifulSoup

# Import your website here
html_text = requests.get(
    'https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=').text

soup = BeautifulSoup(html_text, 'lxml')

# Find the part of the webpage where your information is in
job = soup.find_all('li', class_='clearfix job-bx wht-shd-bx')
company_name = job.find('h3', class_='joblist-comp-name').text.replace(' ', '')
skills = job.find('span', class_='srp-skills').text.replace(' ', '')
published_date = job.find('span', class_='sim-posted').span.text

print(published_date)

print(f'''
Company name: {company_name}
Required Skills: {skills}

''')

Traceback (most recent call last):
  File "c:\Users\GamingPC\OneDrive - University of Pittsburgh\Random Work\Desktop\Python Projects\Web scraping.py", line 12, in <module>
    company_name = job.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '')
  File "C:\Users\GamingPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bs4\element.py", line 2253, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

Body:
As John Gordon says, you can't call find() on a result set, so you need to iterate over the variable job, something like this would work:

import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
job = soup.find_all('li', class_ = 'clearfix job-bx wht-shd-bx')

for item in job:
    company_name = item.find('h3', class_ = 'joblist-comp-name').text.replace(' ', '').strip()
    skills = item.find('span', class_ = 'srp-skills').text.replace(' ', '').strip()
    published_date = item.find('span', class_ = 'sim-posted').span.text

    print(published_date)

    print(f'''
    Company name: {company_name}
    Required Skills: {skills}

    ''')


问:
(Javascript) i want to reduce every duplicate values in 2 Dimensional Array but i don't know how
my English is not good but i really need your help.

I want to reduce all same values in this 2 Dimensional Array but it doesn't work.

```<code>let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

 function removeDup(edge) {
      for (let i = 0; i < edge.length; i++) {
        if (edge.some((item) => item > 1)) {
          edge.splice(i, 1);
        }
      }
      return edge;
    }
</code>```

i want to change array like this.

```<code> [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]
</code>```

答:
Use the the filter() array method with the every() array method as shown below:

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

function removeDup(edge) {
    return edge.filter(
        (cur,i) => edge.slice(0,i).every(
            prev => !prev.every(elm => cur.includes(elm))
        )
    );
}

console.log( removeDup(edge) );
//output: [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4]]```
</div>
</div>
</p>
<p>If your goal is to remove all elements that are repeated, you would need to use the whole array, <code>edge</code>, instead of <code>edge.slice(0,i)</code> and, avoid comparing an element with itself - <code>i !== j</code> - as shown below:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

function removeDup(edge) {
    return edge.filter(
        (cur,i) => edge.every(
            (prev,j) => !prev.every(elm => i !== j && cur.includes(elm))
        )
    );
}

console.log( removeDup(edge) );
//output: [[0,1,4],[1,2,4],[2,3,4],[3,0,4]]</code>```

Another approach would be:

To convert each element array to a single value by first sorting the elements and joining them

Then use filter() to only return the element array that return a frequency of 1

Use an inner filter() to count how many times each converted element appears in the array.

[...cur] ensures original elements are not sorted, since arrays are passed by reference.

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

function removeDup(edge) {
    const nedge = edge.map(cur => [...cur].sort().join(''));
    return edge.filter(
        cur => nedge.filter(
            n => n === [...cur].sort().join('')
        ).length === 1
    );
}

console.log( removeDup(edge) );
//output: [[0,1,4],[1,2,4],[2,3,4],[3,0,4]]```

Body:
my English is not good but i really need your help.

I want to reduce all same values in this 2 Dimensional Array but it doesn't work.

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

 function removeDup(edge) {
      for (let i = 0; i < edge.length; i++) {
        if (edge.some((item) => item > 1)) {
          edge.splice(i, 1);
        }
      }
      return edge;
    }

i want to change array like this.

 [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]

Body:
Use the the filter() array method with the every() array method as shown below:

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

function removeDup(edge) {
    return edge.filter(
        (cur,i) => edge.slice(0,i).every(
            prev => !prev.every(elm => cur.includes(elm))
        )
    );
}

console.log( removeDup(edge) );
//output: [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4]]

If your goal is to remove all elements that are repeated, you would need to use the whole array, edge, instead of edge.slice(0,i) and, avoid comparing an element with itself - i !== j - as shown below:

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

function removeDup(edge) {
    return edge.filter(
        (cur,i) => edge.every(
            (prev,j) => !prev.every(elm => i !== j && cur.includes(elm))
        )
    );
}

console.log( removeDup(edge) );
//output: [[0,1,4],[1,2,4],[2,3,4],[3,0,4]]

Another approach would be:

To convert each element array to a single value by first sorting the elements and joining them

Then use filter() to only return the element array that return a frequency of 1

Use an inner filter() to count how many times each converted element appears in the array.

[...cur] ensures original elements are not sorted, since arrays are passed by reference.

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

function removeDup(edge) {
    const nedge = edge.map(cur => [...cur].sort().join(''));
    return edge.filter(
        cur => nedge.filter(
            n => n === [...cur].sort().join('')
        ).length === 1
    );
}

console.log( removeDup(edge) );
//output: [[0,1,4],[1,2,4],[2,3,4],[3,0,4]]