问:
How to disable python history saving?
I am on linux (OpenSuse) machine using CPython with

```<code>22;~/.../XO/> python3 --version
Python 3.6.10
</code>```

I would like to setup saving/loading python interactive shell history separately for each working directory in which a session has been started.
I am trying to do it in /etc/pythonstart having export PYTHONSTARTUP=/etc/pythonstart

The relevant content of my /etc/pythonstart is

```<code>import os
import readline
import atexit

historyFile = ".pyhistory"
cwd         = os.getcwd()

historyPath = cwd + "/" + historyFile

def save_history():
    try:
        readline.write_history_file(historyPath)
    except:
        pass

# read history
if os.path.exists(historyPath):
    readline.set_history_length(100)
    readline.read_history_file(historyPath)

# save history
atexit.register(save_history)
</code>```

It almost works, except python also saves and reads history in ~/.python_history and it gets merged for all sessions. Is there a way to disable the later behaviour and if yes, how?

答:
This modification to the startup file does the job. It does not disable writing to ~/.python_history but ignores its content on startup.

```<code>import atexit
import os
import readline

historyFile = ".pyhistory"
startFile   = ".pystart"
cwd         = os.getcwd()

historyPath = cwd + "/" + historyFile
startPath   = cwd + "/" + startFile

def save_history(historyPath=historyPath):
    import readline
    try:
        readline.write_history_file(historyPath)
        readline.clear_history()
    except:
        pass

# ignore history loaded from the standard file
readline.clear_history()

# load history from the custom file
if os.path.exists(historyPath):
    readline.set_history_length(100)
    readline.read_history_file(historyPath)

# register handler
atexit.register(save_history)
</code>```

Title: How to disable python history saving?

Body:
I am on linux (OpenSuse) machine using CPython with

22;~/.../XO/> python3 --version
Python 3.6.10

I would like to setup saving/loading python interactive shell history separately for each working directory in which a session has been started.
I am trying to do it in /etc/pythonstart having export PYTHONSTARTUP=/etc/pythonstart

The relevant content of my /etc/pythonstart is

import os
import readline
import atexit

historyFile = ".pyhistory"
cwd         = os.getcwd()

historyPath = cwd + "/" + historyFile

def save_history():
    try:
        readline.write_history_file(historyPath)
    except:
        pass

# read history
if os.path.exists(historyPath):
    readline.set_history_length(100)
    readline.read_history_file(historyPath)

# save history
atexit.register(save_history)

It almost works, except python also saves and reads history in ~/.python_history and it gets merged for all sessions. Is there a way to disable the later behaviour and if yes, how?

Body:
This modification to the startup file does the job. It does not disable writing to ~/.python_history but ignores its content on startup.

import atexit
import os
import readline

historyFile = ".pyhistory"
startFile   = ".pystart"
cwd         = os.getcwd()

historyPath = cwd + "/" + historyFile
startPath   = cwd + "/" + startFile

def save_history(historyPath=historyPath):
    import readline
    try:
        readline.write_history_file(historyPath)
        readline.clear_history()
    except:
        pass

# ignore history loaded from the standard file
readline.clear_history()

# load history from the custom file
if os.path.exists(historyPath):
    readline.set_history_length(100)
    readline.read_history_file(historyPath)

# register handler
atexit.register(save_history)


来源: stackexchange

问:
TakeWhile fails for unapparent reason
In my following Linq query, that I run against a SQL Server 2012 instance, I attempt to read the most recent records up to the previously established MasterId marker (which is a Guid).

```<code>var cdc = crm.CdcContacts
             .Include("CdcMaster")
             .OrderByDescending(x => x.CreatedOn)
             .TakeWhile(x => x.MasterId != marker)
             .OrderBy(x => x.CreatedOn);
</code>```

However, this fails.

"Processing of the LINQ expression 'DbSet\r\n

  .OrderByDescending(x => x.CreatedOn)\r\n    .TakeWhile(x => x.Id !=
  new Guid(\"ABFF5734-F59F-EA11-80CB-005056BC5333\"))' by
  'NavigationExpandingExpressionVisitor' failed. This may indicate
  either a bug or a limitation in EF Core. See
  https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed
  information."

The link in the error message leads to the page on Client vs. Server evaluation so I'm pretty sure the TakeWhile can't be evaluated - I know the cursor logic doesn't work in the same way in older versions of SQL Server, perhaps this could be an explanation.

When I replace the TakeWhile with a simple Take(10), everything works - this evaluates neatly as SELECT TOP 10 * but I get no output of the generated SQL through the console logger factory before the exception hits.

Can someone help me understand what possible reasons might exist for this TakeWhile to not work?

答:
This exception indicates unsupported LINQ method.

I wish EF Core provided documentation with list of supported / unsupported LINQ methods (and CLR properties/methods) like EF6, but up to now they didn't, so it's trial and error.

But TakeWhile and SkipWhile definitely are one of unsupported (and I'm guess they'll never be). I'm not sure why Queryable contains them at all - probably for compatibility with Enumerable methods. But AFAIK no query provider (except LINQ to Object of course) does implement them, since they have no natural translation to SQL.

You can of course switch to Enumerable methods (with AsEnumerable() as explained in the link), but that's not good in general. You'd better express your query with other standard LINQ operators.

P.S. The database and EF Core database provider doesn't matter - the aforementioned methods are not supported by EF Core LINQ query processor.

ContentLicense: CC BY-SA 4.0

Title: TakeWhile fails for unapparent reason

Body:
In my following Linq query, that I run against a SQL Server 2012 instance, I attempt to read the most recent records up to the previously established MasterId marker (which is a Guid).

var cdc = crm.CdcContacts
             .Include("CdcMaster")
             .OrderByDescending(x => x.CreatedOn)
             .TakeWhile(x => x.MasterId != marker)
             .OrderBy(x => x.CreatedOn);

However, this fails.

"Processing of the LINQ expression 'DbSet\r\n

  .OrderByDescending(x => x.CreatedOn)\r\n    .TakeWhile(x => x.Id !=
  new Guid(\"ABFF5734-F59F-EA11-80CB-005056BC5333\"))' by
  'NavigationExpandingExpressionVisitor' failed. This may indicate
  either a bug or a limitation in EF Core. See
  https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed
  information."

The link in the error message leads to the page on Client vs. Server evaluation so I'm pretty sure the TakeWhile can't be evaluated - I know the cursor logic doesn't work in the same way in older versions of SQL Server, perhaps this could be an explanation.

When I replace the TakeWhile with a simple Take(10), everything works - this evaluates neatly as SELECT TOP 10 * but I get no output of the generated SQL through the console logger factory before the exception hits.

Can someone help me understand what possible reasons might exist for this TakeWhile to not work?


问:
unlocking the system preferences is not working
System Preferences is trying to unlock users & Groups preferences
Unable to open System preferences for the my MacOs High Sierra.

sudo commands helps to provided the access to unlock the usergroups?

答:
It’s works after doing this
Restart mac hold
Ctrl + S

It’s open OS X terminal

mount -uw /

rm /var/db/.ApplesetupDone

reboot

Then follow the instructions to setup for admin


问:
Padding missing on one side of scrollable div
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="moh">
    <div></div>
</div></code>```

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

答:
It happens because #moh is 100px and the inner div is 500px. The solution is to set them both to 500px and wrap them with a 3rd div that is limited to 100px with overflow-x.

#wrapper {
  overflow-x: auto;
  width: 100px;
}

#moh {
  background: red;
  width: 500px;
  padding: 5px; // this padding should be on all 4 sides
}

#moh div {
  width: 500px;
  height: 50px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="moh">
    <div></div>
  </div>
</div></code>```

Body:
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

Body:
It happens because #moh is 100px and the inner div is 500px. The solution is to set them both to 500px and wrap them with a 3rd div that is limited to 100px with overflow-x.

#wrapper {
  overflow-x: auto;
  width: 100px;
}

#moh {
  background: red;
  width: 500px;
  padding: 5px; // this padding should be on all 4 sides
}

#moh div {
  width: 500px;
  height: 50px;
  background: green;
}

<div id="wrapper">
  <div id="moh">
    <div></div>
  </div>
</div>


问:
How do I make the html source formatting
How do I make the html source formatting in php

Sample:

```<code><?
    ob_start();

    $mixed_output =
    "<div><div>2.</div><div>
          <div>4.</div>
             <div>4.</div>
    </div>  <div>2.</div>
      <div>2.</div>
    </div>";

    echo format_mixed_output($mixed_output);
?>
</code>```

i want to be this:

```<code><html>
    <div>
      <div>2.</div>
        <div>
          <div>4.</div>
          <div>4.</div>
        </div>
      <div>2.</div>
      <div>2.</div>
    </div>
</html>
</code>```

i can't find source in net, please help me...

答:
You can use "Tidy".

Example: http://www.php.net/manual/en/tidy.examples.basic.php

Your example would be something like this:

```<code><?php
    $mixed_output =
"<div><div>2.</div><div>
      <div>4.</div>
         <div>4.</div>
</div>  <div>2.</div>
  <div>2.</div>
</div>";

$config = array(
            'indent'         => true,
            'output-xml'     => true,
            'input-xml'     => true,
            'wrap'         => '1000');

$tidy = new tidy();
$tidy->parseString($mixed_output, $config, 'utf8');
$tidy->cleanRepair();
echo tidy_get_output($tidy);
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I make the html source formatting in php

Sample:

<?
    ob_start();

    $mixed_output =
    "

2.

4.

4.

2.

2.

";

    echo format_mixed_output($mixed_output);
?>

i want to be this:

2.

4.

4.

2.

2.

i can't find source in net, please help me...

Body:
You can use "Tidy".

Example: http://www.php.net/manual/en/tidy.examples.basic.php

Your example would be something like this:

<?php
    $mixed_output =
"<div><div>2.</div><div>
      <div>4.</div>
         <div>4.</div>
</div>  <div>2.</div>
  <div>2.</div>
</div>";

$config = array(
            'indent'         => true,
            'output-xml'     => true,
            'input-xml'     => true,
            'wrap'         => '1000');

$tidy = new tidy();
$tidy->parseString($mixed_output, $config, 'utf8');
$tidy->cleanRepair();
echo tidy_get_output($tidy);
?>


问:
Pyexcelerate: set table style format
I am using below code to export DataFrame to excel using pyexcelerate:

```<code>from pyexcelerate import Workbook
'''
    code to populate DataFrame
'''
excel = [df.columns] + list(df.values)
wb = Workbook()
wb.new_sheet('Sheet1', data=excel)
wb.save(os.path.join(os.getcwd(), folder_name, file_name))
</code>```

Everything works fine. Now, I would like to set Excel table format using Pyexcelerate. But, could not find the documentation on how to do that.

May I know how to set styles with Pyexcelerate?

I would like to stick with Pyexcelerate as project is developed with this library and also because of project constraint.

答:
Are you referring to these styles? Unfortunately table styles aren't supported because they're a rather complicated feature with a lot of edge cases and it's more flexible to set the styles directly.

You mentioned that you have millions of records, styling every other row is actually quite performant. Cache the Style object to avoid recreating it every iteration.

wb = Workbook()
ws = wb.new_sheet("sheet name")
style = Style(fill=Fill(background=Color(255,0,0,0)))
for row in range(1, len(rows) + 1, 2):
  ws.set_row_style(row, style)
wb.save("output.xlsx")
```

Even with millions of rows, this should not add much to your export time.

Title: Pyexcelerate: set table style format

Body:
I am using below code to export DataFrame to excel using pyexcelerate:

from pyexcelerate import Workbook
'''
    code to populate DataFrame
'''
excel = [df.columns] + list(df.values)
wb = Workbook()
wb.new_sheet('Sheet1', data=excel)
wb.save(os.path.join(os.getcwd(), folder_name, file_name))

Everything works fine. Now, I would like to set Excel table format using Pyexcelerate. But, could not find the documentation on how to do that.

May I know how to set styles with Pyexcelerate?

I would like to stick with Pyexcelerate as project is developed with this library and also because of project constraint.

Body:
Are you referring to these styles? Unfortunately table styles aren't supported because they're a rather complicated feature with a lot of edge cases and it's more flexible to set the styles directly.

You mentioned that you have millions of records, styling every other row is actually quite performant. Cache the Style object to avoid recreating it every iteration.

wb = Workbook()
ws = wb.new_sheet("sheet name")
style = Style(fill=Fill(background=Color(255,0,0,0)))
for row in range(1, len(rows) + 1, 2):
  ws.set_row_style(row, style)
wb.save("output.xlsx")

Even with millions of rows, this should not add much to your export time.


问:
Each row in range skips every second value
I want to loop over all rows in the active worksheet and compare the values of a column.

However, it skips every second value.

The worksheet looks like this:

Code:

```<code>Sub test()

    Dim ws As Worksheet
    Dim r As Range
    Dim total As Integer
    Dim value As String

    Set ws = ActiveSheet
    total = 0

    For Each r In ws.UsedRange.rows

        value = r.Cells(r.Row, 3).value

        If value = "Test" Then

            'Do something...
            total = total + 1

        End If

       Debug.Print ("Row: " & r.Row & " - Value: " & value)

    Next r

End Sub
</code>```

The console shows this:

```<code>Row: 1 - Value: Col2
Row: 2 - Value: JohnDoe
Row: 3 - Value: JohnDoe
Row: 4 - Value: Test
Row: 5 - Value: Blabla
Row: 6 - Value: Blabla
Row: 7 - Value:
Row: 8 - Value:
Row: 9 - Value:
Row: 10 - Value:
Row: 11 - Value:
</code>```

How do I fix this, so it does not skip every second value?

The reason I am using UsedRange instead of for i = 1 to x, is that I will not now the number of rows beforehand.

答:
Suggestions:

Avoid using UsedRange: see this question why.

Avoid looping over the Rows if you don't need to... also avoid referencing r.Cells as this will not be an absolute reference (i.e. relative to the whole sheet), but a relative reference based on r.

```<code>With ws
    Dim lastRow as Long
    lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row

    For i = 2 to lastRow
       If .Cells(i, "C").Value = "Test" Then
           ' do your stuff, though this loop is still inefficient
       End If
    Next
End With
</code>```

Body:
I want to loop over all rows in the active worksheet and compare the values of a column.

However, it skips every second value.

The worksheet looks like this:

Code:

Sub test()

    Dim ws As Worksheet
    Dim r As Range
    Dim total As Integer
    Dim value As String

    Set ws = ActiveSheet
    total = 0

    For Each r In ws.UsedRange.rows

        value = r.Cells(r.Row, 3).value

        If value = "Test" Then

            'Do something...
            total = total + 1

        End If

       Debug.Print ("Row: " & r.Row & " - Value: " & value)

    Next r

End Sub

The console shows this:

Row: 1 - Value: Col2
Row: 2 - Value: JohnDoe
Row: 3 - Value: JohnDoe
Row: 4 - Value: Test
Row: 5 - Value: Blabla
Row: 6 - Value: Blabla
Row: 7 - Value:
Row: 8 - Value:
Row: 9 - Value:
Row: 10 - Value:
Row: 11 - Value:

How do I fix this, so it does not skip every second value?

The reason I am using UsedRange instead of for i = 1 to x, is that I will not now the number of rows beforehand.

Body:
Suggestions:

Avoid using UsedRange: see this question why.

Avoid looping over the Rows if you don't need to... also avoid referencing r.Cells as this will not be an absolute reference (i.e. relative to the whole sheet), but a relative reference based on r.

With ws
    Dim lastRow as Long
    lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row

    For i = 2 to lastRow
       If .Cells(i, "C").Value = "Test" Then
           ' do your stuff, though this loop is still inefficient
       End If
    Next
End With


问:
Using Python and BeautifulSoup to scrape list from an URL
I am new to BeautifulSoup so please excuse any beginner mistakes here. I am attempting to scrape an url and want to store list of movies under one date.
Below is the code I have so far:

```<code>import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')
date = soup.find_all("h4")
ul = soup.find_all("ul")
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    mv=ul.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))
</code>```

I am getting "AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?"

Expected result in list or dataframe

```<code>29th May 2020 Romantic
29th May 2020 Sohreyan Da Pind Aa Gaya
5th June 2020 Lakshmi Bomb
and so on
</code>```

Thanks in advance for help.

答:
I think you should replace "ul" with "h1" on the 10th line. And add definition of variable "movielist" ahead.</p>

```<code>import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')
date = soup.find_all("h4")
ul = soup.find_all("ul")
# add code here
movielist = []
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    # replace ul with h1 here
    mv=h1.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))
print(movielist)
</code>```

Body:
I am new to BeautifulSoup so please excuse any beginner mistakes here. I am attempting to scrape an url and want to store list of movies under one date.
Below is the code I have so far:

import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')
date = soup.find_all("h4")
ul = soup.find_all("ul")
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    mv=ul.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))

I am getting "AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?"

Expected result in list or dataframe

29th May 2020 Romantic
29th May 2020 Sohreyan Da Pind Aa Gaya
5th June 2020 Lakshmi Bomb
and so on

Thanks in advance for help.

Body:
I think you should replace "ul" with "h1" on the 10th line. And add definition of variable "movielist" ahead.

import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')
date = soup.find_all("h4")
ul = soup.find_all("ul")
# add code here
movielist = []
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    # replace ul with h1 here
    mv=h1.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))
print(movielist)


问:
Fastest way to select multiple elements from a list to build a dataframe
I have a list that contains multiple data.frames. I want to select every nth data.frame from the list and combine them into a single data.frame which can be written to a csv.

Here is an example of the list structure:

```<code>one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                     last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                        last_name  = c('Davis', 'Proctor') )

one.list <- list()

one.list[[1]]$title <- one.title
one.list[[1]]$author <- one.author
one.list[[2]]$title <- second.title
one.list[[2]]$author <- second.author
</code>```

Here's my current solution that produces a single data frame for the 'authors' fields:

```<code>build_author_table <- function(result.l){

  list_to_df <- function(i){

  x <- result.l[[i]]$author

  return(x)
}

authors_df_l <-(lapply(1:length(result.l), FUN = list_to_df))

authors_df <- do.call("rbind", lapply(authors_df_l, as.data.frame))

return(authors_df)
}
</code>```

This produces the output I want:

```<code>    first_name last_name
1      Susan     Smith
2      Alice   Johnson
3      Sarah     Davis
4       Mary   Proctor
</code>```

But as you can probably imagine, when scaled to thousands of records with much larger text fields in the data.frame, it is painfully slow.

Can anyone suggest a faster, more efficient way to produce the final data.frame?

答:
Here's a better solution (benchmarked):

```<code>data.table::rbindlist(lapply(one.list, "[[", "author"))
</code>```

The purr solution is pretty, but not that fast. Benchmark results:

```<code>microbenchmark(build_author_table(one.list),
    data.table::rbindlist(lapply(one.list, "[[", "author")),
    map_dfr(one.list, "author"))
</code>```

```<code>Unit: microseconds
                                                    expr     min       lq      mean   median       uq        max neval cld
                            build_author_table(one.list) 170.693 190.9460  239.2987 206.4505 272.3815    494.477   100   a
 data.table::rbindlist(lapply(one.list, "[[", "author"))  69.562  88.5590  270.4926  99.1750 152.6735  15068.116   100   a
                             map_dfr(one.list, "author") 214.832 245.2825 2374.5980 281.3210 340.1270 206562.846   100   a
</code>```

Body:
I have a list that contains multiple data.frames. I want to select every nth data.frame from the list and combine them into a single data.frame which can be written to a csv.

Here is an example of the list structure:

one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                     last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                        last_name  = c('Davis', 'Proctor') )

one.list <- list()

one.list[[1]]$title <- one.title
one.list[[1]]$author <- one.author
one.list[[2]]$title <- second.title
one.list[[2]]$author <- second.author

Here's my current solution that produces a single data frame for the 'authors' fields:

build_author_table <- function(result.l){

  list_to_df <- function(i){

  x <- result.l[[i]]$author

  return(x)
}

authors_df_l <-(lapply(1:length(result.l), FUN = list_to_df))

authors_df <- do.call("rbind", lapply(authors_df_l, as.data.frame))

return(authors_df)
}

This produces the output I want:

    first_name last_name
1      Susan     Smith
2      Alice   Johnson
3      Sarah     Davis
4       Mary   Proctor

But as you can probably imagine, when scaled to thousands of records with much larger text fields in the data.frame, it is painfully slow.

Can anyone suggest a faster, more efficient way to produce the final data.frame?

Body:
Here's a better solution (benchmarked):

data.table::rbindlist(lapply(one.list, "[[", "author"))

The purr solution is pretty, but not that fast. Benchmark results:

microbenchmark(build_author_table(one.list),
    data.table::rbindlist(lapply(one.list, "[[", "author")),
    map_dfr(one.list, "author"))

Unit: microseconds
                                                    expr     min       lq      mean   median       uq        max neval cld
                            build_author_table(one.list) 170.693 190.9460  239.2987 206.4505 272.3815    494.477   100   a
 data.table::rbindlist(lapply(one.list, "[[", "author"))  69.562  88.5590  270.4926  99.1750 152.6735  15068.116   100   a
                             map_dfr(one.list, "author") 214.832 245.2825 2374.5980 281.3210 340.1270 206562.846   100   a


问:
How to change datetime values into a separately formatted value
I have a data set, which unfortunately has sporadic DateTime values, rather than int or str.

How could I go about editing the values, by iterating through the database and replacing the 2019-05-03 00:00:00 into 5-3, for example?

I have tried a few for loops but to no avail. Is there a pandas shortcut?

```<code>,age,menopause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quad,irradiat,Class
0,40-49,premeno,15-19,0-2,yes,3,right,left_up,no,recurrence-events
1,50-59,ge40,15-19,0-2,no,1,right,central,no,no-recurrence-events
2,50-59,ge40,35-39,0-2,no,2,left,left_low,no,recurrence-events
3,40-49,premeno,35-39,0-2,yes,3,right,left_low,yes,no-recurrence-events
4,40-49,premeno,30-34,2019-05-03 00:00:00,yes,2,left,right_up,no,recurrence-events
5,50-59,premeno,25-29,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
6,50-59,ge40,40-44,0-2,no,3,left,left_up,no,no-recurrence-events
7,40-49,premeno,2014-10-01 00:00:00,0-2,no,2,left,left_up,no,no-recurrence-events
8,40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
9,40-49,ge40,40-44,15-17,yes,2,right,left_up,yes,no-recurrence-events
10,50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
11,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
12,50-59,ge40,30-34,0-2,no,1,right,central,no,no-recurrence-events
13,50-59,ge40,25-29,0-2,no,2,right,left_up,no,no-recurrence-events
14,40-49,premeno,25-29,0-2,no,2,left,left_low,yes,recurrence-events
15,30-39,premeno,20-24,0-2,no,3,left,central,no,no-recurrence-events
16,50-59,premeno,2014-10-01 00:00:00,2019-05-03 00:00:00,no,1,right,left_up,no,no-recurrence-events
17,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
18,50-59,premeno,40-44,0-2,no,2,left,left_up,no,no-recurrence-events
19,50-59,ge40,20-24,0-2,no,3,left,left_up,no,no-recurrence-events
20,50-59,lt40,20-24,0-2,?,1,left,left_low,no,recurrence-events
21,60-69,ge40,40-44,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
22,50-59,ge40,15-19,0-2,no,2,right,left_low,no,no-recurrence-events
23,40-49,premeno,2014-10-01 00:00:00,0-2,no,1,right,left_up,no,no-recurrence-events
24,30-39,premeno,15-19,2019-08-06 00:00:00,yes,3,left,left_low,yes,recurrence-events
25,50-59,ge40,20-24,2019-05-03 00:00:00,yes,2,right,left_up,no,no-recurrence-events
</code>```

答:
```<code>import re
import datetime

s = "2014-10-01 00:00:00"

pattern = re.compile("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}")

if pattern.match(s):
  d = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
  print(f"{str(d.month).zfill(2)}-{str(d.day).zfill(2)}")

</code>```

Body:
I have a data set, which unfortunately has sporadic DateTime values, rather than int or str.

How could I go about editing the values, by iterating through the database and replacing the 2019-05-03 00:00:00 into 5-3, for example?

I have tried a few for loops but to no avail. Is there a pandas shortcut?

,age,menopause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quad,irradiat,Class
0,40-49,premeno,15-19,0-2,yes,3,right,left_up,no,recurrence-events
1,50-59,ge40,15-19,0-2,no,1,right,central,no,no-recurrence-events
2,50-59,ge40,35-39,0-2,no,2,left,left_low,no,recurrence-events
3,40-49,premeno,35-39,0-2,yes,3,right,left_low,yes,no-recurrence-events
4,40-49,premeno,30-34,2019-05-03 00:00:00,yes,2,left,right_up,no,recurrence-events
5,50-59,premeno,25-29,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
6,50-59,ge40,40-44,0-2,no,3,left,left_up,no,no-recurrence-events
7,40-49,premeno,2014-10-01 00:00:00,0-2,no,2,left,left_up,no,no-recurrence-events
8,40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
9,40-49,ge40,40-44,15-17,yes,2,right,left_up,yes,no-recurrence-events
10,50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
11,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
12,50-59,ge40,30-34,0-2,no,1,right,central,no,no-recurrence-events
13,50-59,ge40,25-29,0-2,no,2,right,left_up,no,no-recurrence-events
14,40-49,premeno,25-29,0-2,no,2,left,left_low,yes,recurrence-events
15,30-39,premeno,20-24,0-2,no,3,left,central,no,no-recurrence-events
16,50-59,premeno,2014-10-01 00:00:00,2019-05-03 00:00:00,no,1,right,left_up,no,no-recurrence-events
17,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
18,50-59,premeno,40-44,0-2,no,2,left,left_up,no,no-recurrence-events
19,50-59,ge40,20-24,0-2,no,3,left,left_up,no,no-recurrence-events
20,50-59,lt40,20-24,0-2,?,1,left,left_low,no,recurrence-events
21,60-69,ge40,40-44,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
22,50-59,ge40,15-19,0-2,no,2,right,left_low,no,no-recurrence-events
23,40-49,premeno,2014-10-01 00:00:00,0-2,no,1,right,left_up,no,no-recurrence-events
24,30-39,premeno,15-19,2019-08-06 00:00:00,yes,3,left,left_low,yes,recurrence-events
25,50-59,ge40,20-24,2019-05-03 00:00:00,yes,2,right,left_up,no,no-recurrence-events


问:
Copying Specific Outgoing Links
There are 46 links on the site: http://www.math.hmc.edu/~ajb/PCMI/problem_solve.html. I want links from 7th link to 33th link. I need them separated to a file. Can I copy the outgoing links?

答:
Grep source for

```<code><a href
</code>```

then take the result into vim and use the following command

```<code>%s/.*<a href="\(.*\)">.*/\1/g

pcmi08_b.pdf
pcmi07_b.pdf
pcmi06_b.pdf
pcmi05_a.pdf
pcmi05_b.pdf
pcmi04_b.pdf
pcmi03_b.pdf
http://www.math.hmc.edu/putnam/
pcmi_classic.pdf
pcmi_classic.tex
http://www.math.hmc.edu/putnam/seminar.shtml
pcmi_tng.tex
pss_solution.pdf
pss_solution.tex
http://www.maa.org/mathhorizons/
http://www.maa.org/pubs/mathmag.html
http://www.maa.org/pubs/cmj.html
http://www.maa.org/pubs/monthly.html
http://www.math.hmc.edu/funfacts/
http://mathforum.org/students/
http://mathworld.wolfram.com
http://www.cecm.sfu.ca/projects/ISC/
http://www.research.att.com/%7Enjas/sequences/index.html
http://ams.rice.edu/mathscinet/
http://mathforum.org/wagon/
http://math.scu.edu/putnam/index.html
http://www.unl.edu/amc/a-activities/a7-problems/putnam/
http://www.unl.edu/amc/a-activities/a7-problems/problemarchive.html
http://www.amazon.com/exec/obidos/ASIN/0387982191/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/tg/detail/-/038790803X/ref=pd_sim_books_1/t/002-7200940-4079202?v=glance&s=books
http://www.amazon.com/exec/obidos/tg/detail/-/0471135712/ref=pd_sim_books_2/t/002-7200940-4079202?v=glance&s=books
http://www.amazon.com/exec/obidos/tg/detail/-/0817641556/ref=pd_bxgy_text_1/t/002-7200940-4079202?v=glance&s=books&st=*
http://www.amazon.com/exec/obidos/ASIN/0387947434/ref=pd_pym_rvi_1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0883855194/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/tg/detail/-/0883853256/qid=1057672535/sr=8-1/ref=sr_8_1/t/002-7200940-4079202?v=glance&s=books&n=507846" style="font-style: italic;
http://www.amazon.com/exec/obidos/ASIN/088385807X/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0486694151/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0486695735/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0691023565/ref=pd_sxp_elt_l1/t/002-7200940-4079202
</code>```

OwnerDisplayName: UnixBasics

ContentLicense: CC BY-SA 2.5

Title: Copying Specific Outgoing Links

Body:
Grep source for

<a href

then take the result into vim and use the following command

%s/.*<a href="\(.*\)">.*/\1/g

pcmi08_b.pdf
pcmi07_b.pdf
pcmi06_b.pdf
pcmi05_a.pdf
pcmi05_b.pdf
pcmi04_b.pdf
pcmi03_b.pdf
http://www.math.hmc.edu/putnam/
pcmi_classic.pdf
pcmi_classic.tex
http://www.math.hmc.edu/putnam/seminar.shtml
pcmi_tng.tex
pss_solution.pdf
pss_solution.tex
http://www.maa.org/mathhorizons/
http://www.maa.org/pubs/mathmag.html
http://www.maa.org/pubs/cmj.html
http://www.maa.org/pubs/monthly.html
http://www.math.hmc.edu/funfacts/
http://mathforum.org/students/
http://mathworld.wolfram.com
http://www.cecm.sfu.ca/projects/ISC/
http://www.research.att.com/%7Enjas/sequences/index.html
http://ams.rice.edu/mathscinet/
http://mathforum.org/wagon/
http://math.scu.edu/putnam/index.html
http://www.unl.edu/amc/a-activities/a7-problems/putnam/
http://www.unl.edu/amc/a-activities/a7-problems/problemarchive.html
http://www.amazon.com/exec/obidos/ASIN/0387982191/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/tg/detail/-/038790803X/ref=pd_sim_books_1/t/002-7200940-4079202?v=glance&amp;s=books
http://www.amazon.com/exec/obidos/tg/detail/-/0471135712/ref=pd_sim_books_2/t/002-7200940-4079202?v=glance&amp;s=books
http://www.amazon.com/exec/obidos/tg/detail/-/0817641556/ref=pd_bxgy_text_1/t/002-7200940-4079202?v=glance&amp;s=books&amp;st=*
http://www.amazon.com/exec/obidos/ASIN/0387947434/ref=pd_pym_rvi_1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0883855194/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/tg/detail/-/0883853256/qid=1057672535/sr=8-1/ref=sr_8_1/t/002-7200940-4079202?v=glance&amp;s=books&amp;n=507846" style="font-style: italic;
http://www.amazon.com/exec/obidos/ASIN/088385807X/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0486694151/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0486695735/ref=pd_sxp_elt_l1/t/002-7200940-4079202
http://www.amazon.com/exec/obidos/ASIN/0691023565/ref=pd_sxp_elt_l1/t/002-7200940-4079202

OwnerDisplayName: Andrew Clark

LastEditorDisplayName: Andrew Clark


问:
C# Sorting a DataTableCollection by a common column in each table
I'm having some troubles figuring out how to sort a DataTableCollection.  The scenario is that each table in the collection would have the same schema and have a column called "JobNumber" which I want to sort on.  The data in these tables would need to be processed in that order.

Any suggestions?

答:
```<code>DataTableCollection col;

  foreach(DataTable tbl in col)
  {
    // Get the DefaultViewManager of a DataTable and sort it.
    DataTable1.DefaultView.Sort = "JobNumber";
  }
</code>```

http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx

Body:
DataTableCollection col;

  foreach(DataTable tbl in col)
  {
    // Get the DefaultViewManager of a DataTable and sort it.
    DataTable1.DefaultView.Sort = "JobNumber";
  }

http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx


问:
Upload a file in admin and then download from the website Django
I am trying to create a website, where customer can upload a file in an Admin section, and after any person can download this file from the website. Preferably any files like pdf, exe, doc (is it possible?) I am able to upload a file in Admin and it shows it on the website. It downloads the file with a correct name (saved in media) but shows a failure , file missing.

So far I have :

setting.py

```<code>STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'
</code>```

models.py

```<code>class TEACHING(models.Model):

    title = models.CharField(max_length=100)

    content = models.TextField()

    date_posted = models.DateTimeField(auto_now_add=True)

    excercise = models.FileField(upload_to="files/", default='default value')

    def __str__(self):

        return self.title
</code>```

views.py

```<code>def teaching(request):

    context = { 'teaches' : TEACHING.objects.all()}

    return render(request, 'blog/teaching.html', context)
</code>```

urls.py

```<code>if settings.DEBUG:

    urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
</code>```

teaching.html

```<code>{% for teach in teaches %}
    <a href="{{ teach.excercise }}" download>Download</a>
{% endfor %}
</code>```

答:
Hi You are not providing url in href, so please change your  with following way

```<code><a href="{{ teach.excercise.url }}" download>Download</a>
</code>```

Body:
I am trying to create a website, where customer can upload a file in an Admin section, and after any person can download this file from the website. Preferably any files like pdf, exe, doc (is it possible?) I am able to upload a file in Admin and it shows it on the website. It downloads the file with a correct name (saved in media) but shows a failure , file missing.

So far I have :

setting.py

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

models.py

class TEACHING(models.Model):

    title = models.CharField(max_length=100)

    content = models.TextField()

    date_posted = models.DateTimeField(auto_now_add=True)

    excercise = models.FileField(upload_to="files/", default='default value')

    def __str__(self):

        return self.title

views.py

def teaching(request):

    context = { 'teaches' : TEACHING.objects.all()}

    return render(request, 'blog/teaching.html', context)

urls.py

if settings.DEBUG:

    urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

teaching.html

{% for teach in teaches %}
    Download
{% endfor %}

Body:
Hi You are not providing url in href, so please change your <a> with following way

<a href="{{ teach.excercise.url }}" download>Download</a>


答:
I didn't specify a list to receive, and I changed it from 'h1' to 'text capture' instead of 'h4'.

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

page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')

movielist = []
date = soup.find_all("h4")
ul = soup.find_all("ui")
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    mv=h1.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))
</code>```

The reason the date doesn't match in the output result is that the 'date' retrieved looks like the following, so you need to fix the logic.
There are multiple titles on the same release date, so the release date and number of titles don't match up. I can't help you that much because I don't have the time. Have a good night.

```<code>29 May 2020
05 June 2020
07 June 2020
07 June 2020 Romantic
12 June 2020
12 June 2020 Sohreyan Da Pind Aa Gaya
18 June 2020
18 June 2020 Laxmmi Bomb
19 June 2020
19 June 2020 Roohi Afzana
25 June 2020
25 June 2020 Nikamma
26 June 2020
26 June 2020 Naandhi
02 July 2020
02 July 2020 Mandela
03 July 2020
03 July 2020 Medium Spicy
10 July 2020
10 July 2020 Out of the Blue
</code>```

Title: Using Python and BeautifulSoup to scrape list from an URL

Body:
I didn't specify a list to receive, and I changed it from 'h1' to 'text capture' instead of 'h4'.

import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')

movielist = []
date = soup.find_all("h4")
ul = soup.find_all("ui")
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    mv=h1.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))

The reason the date doesn't match in the output result is that the 'date' retrieved looks like the following, so you need to fix the logic.
There are multiple titles on the same release date, so the release date and number of titles don't match up. I can't help you that much because I don't have the time. Have a good night.

29 May 2020
05 June 2020
07 June 2020
07 June 2020 Romantic
12 June 2020
12 June 2020 Sohreyan Da Pind Aa Gaya
18 June 2020
18 June 2020 Laxmmi Bomb
19 June 2020
19 June 2020 Roohi Afzana
25 June 2020
25 June 2020 Nikamma
26 June 2020
26 June 2020 Naandhi
02 July 2020
02 July 2020 Mandela
03 July 2020
03 July 2020 Medium Spicy
10 July 2020
10 July 2020 Out of the Blue


问:
Which datatype should be used for currency?
Seems like Money type is discouraged as described here.

My application needs to store currency, which datatype shall I be using? Numeric, Money or FLOAT?

答:
Use BigInt to store currency as a positive integer representing the monetary value in the smallest currency unit (e.g., 100 cents to store $1.00 or 100 to store ¥100 (Japanese yen, a zero-decimal currency). This is what Stripe does--one the most important financial service companies for global ecommerce.

Source: see "Zero-decimal currencies" at https://stripe.com/docs/currencies

Eventually this will be the top answer...


问:
How to set view in matplolib FigureCanvas programmatically?
```<code>from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from PyQt5 import QtCore
from PyQt5 import QtWidgets

class MyFigure(QtCore.QObject):
    def __init__(self):
        self.widget = QtWidgets.QWidget()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.widget)
        self.axis = self.fig.add_subplot(111)
        self.toolbar = NavigationToolbar(self.canvas, self.widget)

    def plot(self, x, y):
        self.axis.plot(x, y)
        self.canvas.draw()

    def set_view(self, xmin, xmax, ymin, ymax):
        # how can I do that?

</code>```

With the NavigationToolbar I can use pan and zoom to interactively set the view to a particular region of the plot in FigureCanvas.

How can I set the FigureCanvas view programmatically to a region (xmin, xmax, ymin, ymax)?

答:
You can change view limits using matplotlib.pyplot.xlim or matplotlib.axes.Axes.set_xlim. For example:

```<code>def set_view(self, xmin, xmax, ymin, ymax):
    self.axis.set_xlim(xmin, xmax)
    self.axis.set_ylim(ymin, ymax)
</code>```

However, I don't how this interacts with FigureCanvas. Just test it.

Body:
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from PyQt5 import QtCore
from PyQt5 import QtWidgets

class MyFigure(QtCore.QObject):
    def __init__(self):
        self.widget = QtWidgets.QWidget()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.widget)
        self.axis = self.fig.add_subplot(111)
        self.toolbar = NavigationToolbar(self.canvas, self.widget)

    def plot(self, x, y):
        self.axis.plot(x, y)
        self.canvas.draw()

    def set_view(self, xmin, xmax, ymin, ymax):
        # how can I do that?

With the NavigationToolbar I can use pan and zoom to interactively set the view to a particular region of the plot in FigureCanvas.

How can I set the FigureCanvas view programmatically to a region (xmin, xmax, ymin, ymax)?

Body:
You can change view limits using matplotlib.pyplot.xlim or matplotlib.axes.Axes.set_xlim. For example:

def set_view(self, xmin, xmax, ymin, ymax):
    self.axis.set_xlim(xmin, xmax)
    self.axis.set_ylim(ymin, ymax)

However, I don't how this interacts with FigureCanvas. Just test it.


问:
Accessible drawer menu using tabs
How to enable a user to tab through an app drawer immediately once the menu opens. In a menu similar to the following example (but having the drawer on the right):

Now I want the user to be able to tab through the application and have the focus on the menu directly once it opens.

Desired outcome:

User presses tab

[Focus is on the "open menu" button]

User presses spacebar

[Menu opens]

User presses tab again

[Focus is on the "close menu" icon]

User presses tab again

[Focus is on the first menu item] (yay!)

Actual outcome:

User presses tab

[Focus is on the "open menu" button]

User presses spacebar

[Menu opens]

User presses tab again

[Focus is on the first button ("this is some button") in the page] (Oh no :(. it should instead be going to the navigation in the drawer)

Code example

For this code example I am following the steps as described on "Navigation Menu Button Example" from w3.org.

/* this JS code is arbitrary and for demonstration purpose. */
/* It is most likely a HTML solution */
const buttonOpenMenu = document.getElementById('open-menu');
const buttonCloseMenu = document.getElementById('close-menu');
const drawer = document.getElementById('drawer');

buttonOpenMenu.onclick = function () {
 drawer.classList.add('open');
    drawer.setAttribute("aria-expanded", true);
}

buttonCloseMenu.onclick = function () {
 drawer.classList.remove('open');
    drawer.setAttribute("aria-expanded", false);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* CSS also arbitrary */
main {
  flex-grow: 1;
  width: 100%;
}

#drawer {
  width: 240px;
  flex: 0 0 auto;
  top: 0;
  height: 100%;
  position: fixed;
  left: auto;
  right: -240px;
}

#drawer.open {
  right: 0;
}</code>```

    <button
      id="open-menu"
      aria-haspopup="true"
      aria-controls="drawer"
    >
      open menu
    </button>

    Title

    <button>
      this is some button
    </button>

Some body content

    <button>
      another button
    </button>

   <button id="close-menu">
     close menu
  </button>

Menu item 1

Menu item 2

```

答:
The reason that your tab order isn't working the way you want is because it doesn't reflect the DOM order. Elements will receive focus in the order that they appear in the markup, unless you set the focus.

You can fix this by setting focus when the menu opens by using HTMLElement.focus().

HTML:

Add an id and tabindex attributes to the nav element.

```<code><nav id="nav" aria-labelledby="open-menu" role="menu" tabindex="0">
</code>```

JAVASCRIPT:

Set the focus on the nav element using document.getElementById.

```<code>buttonOpenMenu.onclick = function () {
    drawer.classList.add('open');
    drawer.setAttribute("aria-expanded", true);
    document.getElementById("nav").focus();
}
</code>```

See a working example here: https://jsfiddle.net/25nzpo76/

Title: Accessible drawer menu using tabs

Body:
How to enable a user to tab through an app drawer immediately once the menu opens. In a menu similar to the following example (but having the drawer on the right):

Now I want the user to be able to tab through the application and have the focus on the menu directly once it opens.

Desired outcome:

User presses tab

[Focus is on the "open menu" button]

User presses spacebar

[Menu opens]

User presses tab again

[Focus is on the "close menu" icon]

User presses tab again

[Focus is on the first menu item] (yay!)

Actual outcome:

User presses tab

[Focus is on the "open menu" button]

User presses spacebar

[Menu opens]

User presses tab again

[Focus is on the first button ("this is some button") in the page] (Oh no :(. it should instead be going to the navigation in the drawer)

Code example

For this code example I am following the steps as described on "Navigation Menu Button Example" from w3.org.

/* this JS code is arbitrary and for demonstration purpose. */
/* It is most likely a HTML solution */
const buttonOpenMenu = document.getElementById('open-menu');
const buttonCloseMenu = document.getElementById('close-menu');
const drawer = document.getElementById('drawer');

buttonOpenMenu.onclick = function () {
 drawer.classList.add('open');
    drawer.setAttribute("aria-expanded", true);
}

buttonCloseMenu.onclick = function () {
 drawer.classList.remove('open');
    drawer.setAttribute("aria-expanded", false);
}

/* CSS also arbitrary */
main {
  flex-grow: 1;
  width: 100%;
}

#drawer {
  width: 240px;
  flex: 0 0 auto;
  top: 0;
  height: 100%;
  position: fixed;
  left: auto;
  right: -240px;
}

#drawer.open {
  right: 0;
}

    <button
      id="open-menu"
      aria-haspopup="true"
      aria-controls="drawer"
    >
      open menu
    </button>

    Title

    <button>
      this is some button
    </button>

Some body content

    <button>
      another button
    </button>

   <button id="close-menu">
     close menu
  </button>

Menu item 1

Menu item 2

Body:
The reason that your tab order isn't working the way you want is because it doesn't reflect the DOM order. Elements will receive focus in the order that they appear in the markup, unless you set the focus.

You can fix this by setting focus when the menu opens by using HTMLElement.focus().

HTML:

Add an id and tabindex attributes to the nav element.

<nav id="nav" aria-labelledby="open-menu" role="menu" tabindex="0">

JAVASCRIPT:

Set the focus on the nav element using document.getElementById.

buttonOpenMenu.onclick = function () {
    drawer.classList.add('open');
    drawer.setAttribute("aria-expanded", true);
    document.getElementById("nav").focus();
}

See a working example here: https://jsfiddle.net/25nzpo76/


问:
Training Computer Vision OCR
I setup the Azure Computer Vision Service and used in my app.  When I tried performing OCR on some images, it didn't recognize all the text (i.e. leaving out "S" in "cups").
Can it be trained/retrained in OCR when text isn't recognized correctly?</p>

答:
Based on the image and info you provided, I quickly checked the output of Computer Vision API which has several operations for text processing:

OCR: the original one, synchronous

Recognize Text: the 2nd one, asynchronous, which will be deprecated for the last one

Batch Read (2.0 & 2.1) > Read (3.0): the latest one, asynchronous also.

In terms of results quality, Read operation is better, especially for rotated items and other cases.

Here is a sample of the output of each one with your image (https://moderatorsampleimages.blob.core.windows.net/samples/sample2.jpg), generated with Cognitive Workbench website, an open-source demo of Cognitive Services.

OCR

You can see some errors:

there is a "*" after "CAPABLE"

"OURSELVE" is missing the "S"

The last period is a comma

Recognize Text

Here the only issue is the missing period at the end

Batch Read

Here the only issue is the missing period at the end

Conclusion: use Read 3.0 which is now Generally Available. API Link: https://westeurope.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-ga/operations/5d986960601faab4bf452005

Title: Training Computer Vision OCR


问:
How to get the text inside a h2 tag in selenium python
how to get the text inside the html tag and assert if it is present on the page.

html-

```<code><h2>  You are suggested the Low Fat Vegan Diet </h2>
</code>```

i tried-

```<code>message = driver.find_elements_by_tag_name('h2').Text()
</code>```

AttributeError: 'list' object has no attribute 'Text'

```<code> message = driver.find_elements_by_tag_name('h2').getText()
</code>```

AttributeError: 'list' object has no attribute 'getText'

how do i get the text and assert it is present in the page?

答:
the method name is  find_elements_by_tag_name so it returns a list of elements.
if your target element is the first item in elements you can try this:

```<code>message = driver.find_elements_by_tag_name('h2')[0].text
</code>```

i recommend you to use Beautifulsoup to get better search in elements.

Body:
how to get the text inside the html tag and assert if it is present on the page.

html-

  You are suggested the Low Fat Vegan Diet

i tried-

message = driver.find_elements_by_tag_name('h2').Text()

AttributeError: 'list' object has no attribute 'Text'

 message = driver.find_elements_by_tag_name('h2').getText()

AttributeError: 'list' object has no attribute 'getText'

how do i get the text and assert it is present in the page?

Body:
the method name is  find_elements_by_tag_name so it returns a list of elements.
if your target element is the first item in elements you can try this:

message = driver.find_elements_by_tag_name('h2')[0].text

i recommend you to use Beautifulsoup to get better search in elements.


问:
PyMongo aggregation Not working with $max operator
My query is working fine on the mongo shell. But when running through pymongo is giving error. Can someone help me with this one.

```<code>db.collectioname.aggregate([
     {   "$match": { "$and": [
                        { "organization_id": int(organization_id) },
                        { "resulttime":{
                                "$gte":stdate,
                                "$lte":enddate
                            }
                        }
                    ]
            }
    },
    { "$skip" : int(offset) },
    { "$limit" : int(limit) },
    { "$group": {
        "_id": "$userid",
        "max_temperature": { "$max": "$temperature" },
        "min_temperature": { "$min": "$temperature" }
    }}
     ])
</code>```

However, I am getting an error as

```<code>pymongo.errors.OperationFailure: unknown operator: $max
</code>```

答:
I tried it; it works fine for me. Can you confirm this sample code works. If not print a full stack trace.</p>

```<code>import pymongo
import datetime

offset = 0
limit = 1
organization_id = 1
stdate = datetime.datetime(2020, 1, 1, 0, 0)
enddate = datetime.datetime(2021, 1, 1, 0, 0)

db = pymongo.MongoClient()['mydatabase']
db.collectioname.insert_one({'organization_id': organization_id, 'resulttime': datetime.datetime.now(), 'temperature': 37.4})

records = db.collectioname.aggregate([
    {"$match": {"$and": [
        {"organization_id": int(organization_id)},
        {"resulttime": {
            "$gte": stdate,
            "$lte": enddate
        }}]}
    },
    {"$skip": int(offset)},
    {"$limit": int(limit)},
    {"$group": {
        "_id": "$userid",
        "max_temperature": {"$max": "$temperature"},
        "min_temperature": {"$min": "$temperature"}
    }}
])

print(list(records))
</code>```

Body:
My query is working fine on the mongo shell. But when running through pymongo is giving error. Can someone help me with this one.

db.collectioname.aggregate([
     {   "$match": { "$and": [
                        { "organization_id": int(organization_id) },
                        { "resulttime":{
                                "$gte":stdate,
                                "$lte":enddate
                            }
                        }
                    ]
            }
    },
    { "$skip" : int(offset) },
    { "$limit" : int(limit) },
    { "$group": {
        "_id": "$userid",
        "max_temperature": { "$max": "$temperature" },
        "min_temperature": { "$min": "$temperature" }
    }}
     ])

However, I am getting an error as

pymongo.errors.OperationFailure: unknown operator: $max

Body:
I tried it; it works fine for me. Can you confirm this sample code works. If not print a full stack trace.

import pymongo
import datetime

offset = 0
limit = 1
organization_id = 1
stdate = datetime.datetime(2020, 1, 1, 0, 0)
enddate = datetime.datetime(2021, 1, 1, 0, 0)

db = pymongo.MongoClient()['mydatabase']
db.collectioname.insert_one({'organization_id': organization_id, 'resulttime': datetime.datetime.now(), 'temperature': 37.4})

records = db.collectioname.aggregate([
    {"$match": {"$and": [
        {"organization_id": int(organization_id)},
        {"resulttime": {
            "$gte": stdate,
            "$lte": enddate
        }}]}
    },
    {"$skip": int(offset)},
    {"$limit": int(limit)},
    {"$group": {
        "_id": "$userid",
        "max_temperature": {"$max": "$temperature"},
        "min_temperature": {"$min": "$temperature"}
    }}
])

print(list(records))


问:
How to check whether the values are in Float using jUnit assertion?
I am trying to automate an API. In response, I am getting float value for one of the keys. The value is dynamic so the only thing I want to assert is to check whether the value is a float number or not. How can we assert that via jUnit5 library?</p>

答:
You could just try to read the value as a float using Float.valueOf(), if it can't be interpreted as a float the function will throw an exception and the test will fail. Something like this:

```<code>@Test
public void isFloat() {
    // this will throw an exception
    Float.valueOf("definitely_not_a_float");
}
</code>```

Body:
You could just try to read the value as a float using Float.valueOf(), if it can't be interpreted as a float the function will throw an exception and the test will fail. Something like this:

@Test
public void isFloat() {
    // this will throw an exception
    Float.valueOf("definitely_not_a_float");
}


问:
Importing a pdf image in R markdown
I am trying to import a pdf file into R Markdown.

The pdf file name is "question7.pdf".

I am trying to import the image using knitr::include_graphics() but I have no idea on how to use the code properly.

Could someone help me?

Tks !

答:
Just running

knitr::include_graphics("question7.pdf")
```

inside an R code chunk in your RMarkdown file should work. Assuming that question7.pdf is in the same folder as your Rmd file.

Title: Importing a pdf image in R markdown

Body:
Just running

knitr::include_graphics("question7.pdf")

inside an R code chunk in your RMarkdown file should work. Assuming that question7.pdf is in the same folder as your Rmd file.


问:
Refresh multiple div-[unique_ID]'s with jQuery and .load()?
I am working on modifying a plugin to allow users to vote on posts. My page looks something like this (though this is simplified of course):

```<code><div class="vote vote1">
//voting buttons
</div>

<div class="vote vote2">
//voting buttons
</div>

<div class="vote vote3">
//voting buttons
</div>

<div class="vote vote4">
//voting buttons
</div>
</code>```

As you can see, each voting div has a unique class associated with it, vote[id]. My trouble is that after submitting the vote to my vote.php file I need to refresh this unique voting div with the new data. I have been able to do this without trouble when I hardcode a particular voting div's unique id into .load(), but I cannot seem to get this to work dynamically for all voting divs using a single script. Would somebody be able to help me out in refreshing the unique voting div that has been clicked?

```<code><script type="text/javascript">
jQuery(document).ready(function(){
$(".vote a.can-vote").click(
    function() {
        var some = jQuery(this).parent();
        var thepost = jQuery(this).attr("post");
        var theuser = jQuery(this).attr("user");
        var updown = jQuery(this).attr("up-down");
        var is_update = jQuery(this).attr("update");
        var votebox = ".vote"+thepost+" span";

        jQuery.ajax({
            type: "POST",
            url: "<?php bloginfo('template_url'); ?>/vote.php",
            data: {user: theuser, post: thepost, up_down: updown, update: is_update},
            cache: false,
            success: function( data ){
                jQuery(some).load('http://mydomain.com div.vote[ID]');
            }
        });
        return false;
    });
});
</script>
</code>```

I'm sorry if this is a simple question but I've been trying my best to figure it out for two days with no luck; thank you in advance for any help.

答:
If I understood well:
 you can do an 'offline' trick.

Just increment the vote number with jQuery, something like in this Ex:

```<code>var voted = 0;
$('.vote').attr('value', function() {
voted++;
return voted;
});
</code>```

The change will happen in the browser.
Than always on page refresh you'll get back the real state from the DB.

Body:
I am working on modifying a plugin to allow users to vote on posts. My page looks something like this (though this is simplified of course):

//voting buttons

//voting buttons

//voting buttons

//voting buttons

As you can see, each voting div has a unique class associated with it, vote[id]. My trouble is that after submitting the vote to my vote.php file I need to refresh this unique voting div with the new data. I have been able to do this without trouble when I hardcode a particular voting div's unique id into .load(), but I cannot seem to get this to work dynamically for all voting divs using a single script. Would somebody be able to help me out in refreshing the unique voting div that has been clicked?

I'm sorry if this is a simple question but I've been trying my best to figure it out for two days with no luck; thank you in advance for any help.

Body:
If I understood well:
 you can do an 'offline' trick.

Just increment the vote number with jQuery, something like in this Ex:

var voted = 0;
$('.vote').attr('value', function() {
voted++;
return voted;
});

The change will happen in the browser.
Than always on page refresh you'll get back the real state from the DB.


问:
How do you connect two (pipe stdin and stdout) Deno subprocesses?
Judging by the API docs, a Deno subprocess (an instance of Deno.Process) can receive one of four stdin types, the same goes for stdout. However, there's no mention in the documentation as to how to pipe the output from one subprocess to the input of another. What I'm trying to achieve is akin to the basic UNIX pipe (oneProcess | another) and then read the output of the second process in the pipeline. Simply running

```<code>const someProcess = Deno.run({
  cmd: ["oneProcess firstParameter | another 2ndParameter"]
});
</code>```

fails with an error of:

error: Uncaught NotFound: No such file or directory (os error 2)

because the first argument (string) is expected to be an executable.

How would one achieve this is Deno then, are we required to perhaps set "piped" as both the output and input to the subprocesses (respectively) and then manually read and write data from one to another?

答:
You're getting NotFound: no such file or directory because the value passed to cmd must be a path to the binary.

the first element needs to be a path to the binary

And onProcess | another is not a binary.

To use a unix pipe | you can run bash and then write to stdin.

```<code>const p = Deno.run({
  cmd: ["bash"],
  stdout: "piped",
  stdin: "piped"
});

const encoder = new TextEncoder();
const decoder = new TextDecoder();

const command = "echo -n yes | md5sum";
await p.stdin.write(encoder.encode(command));

await p.stdin.close();
const output = await p.output()
p.close();

console.log(decoder.decode(output)); // a6105c0a611b41b08f1209506350279e
</code>```

Body:
Judging by the API docs, a Deno subprocess (an instance of Deno.Process) can receive one of four stdin types, the same goes for stdout. However, there's no mention in the documentation as to how to pipe the output from one subprocess to the input of another. What I'm trying to achieve is akin to the basic UNIX pipe (oneProcess | another) and then read the output of the second process in the pipeline. Simply running

const someProcess = Deno.run({
  cmd: ["oneProcess firstParameter | another 2ndParameter"]
});

fails with an error of:

error: Uncaught NotFound: No such file or directory (os error 2)

because the first argument (string) is expected to be an executable.

How would one achieve this is Deno then, are we required to perhaps set "piped" as both the output and input to the subprocesses (respectively) and then manually read and write data from one to another?

Body:
You're getting NotFound: no such file or directory because the value passed to cmd must be a path to the binary.

the first element needs to be a path to the binary

And onProcess | another is not a binary.

To use a unix pipe | you can run bash and then write to stdin.

const p = Deno.run({
  cmd: ["bash"],
  stdout: "piped",
  stdin: "piped"
});

const encoder = new TextEncoder();
const decoder = new TextDecoder();

const command = "echo -n yes | md5sum";
await p.stdin.write(encoder.encode(command));

await p.stdin.close();
const output = await p.output()
p.close();

console.log(decoder.decode(output)); // a6105c0a611b41b08f1209506350279e


问:
how to stop overwriting an index number in python list which is already written once?
I have a list with index number 0 to 5. I am telling user to input position where they want to mark ('X') into the list and then printing the list each time the user input's a index number. I want the user to input only once in a index number of the list and if user try to overwrite the written value in a list I want to give a message to user as a input 'you can't go there please try again in different position'. I want to keep running the input until the user enters a value in non-written position in the list.

I tried to do it in OOP as I am practicing OOP. I make a board then display the board with print_Board() method. In method input_Value() I tried to make it run under a while loop and break the loop when all positions are filled... also used a try catch error... which will check if the input value must have the index number from 1 to 6 only.

```<code>class Overwrite:

    list = ['.', '.', '.', '.', '.', '.']

    def print_Board(self):
        print(self.list[0:3])
        print(self.list[3:6])

    def input_Value(self):
        while True:
            try:
                self.position = input('enter a number between 1 to 6:')     # input a value
                if self.position not in ['1', '2', '3', '4', '5', '6']: # checking if the number is in range(1 to 6) or not
                    print('please try again a number between 1 to 6')
                    continue
                self.position = int(self.position) - 1  # putting -1 so that user input is different than
                self.list[self.position] = 'X'
                self.print_Board()
            except IndexError:
                print('please try again a number between 1 to 6:')
            except ValueError:
                print('please try again a number between 1 to 6:')
            else:
                if '.' not in self.list:  # it will stop the program when all the positions are filled
                    break

    def gameplay(self):
        self.print_Board()
        self.input_Value()
</code>```

答:
The simplest way that I can think to do this is to include another selection statement:

```<code>if self.list[self.position] == 'X':
    print("you can't go there please try again in different position")
    continue
</code>```

This will check if the selected index was already mutated to 'X', if it has, it will restart the while loop. Otherwise, it will continue through your code to change the position to 'X'

Although for general practice, be careful of using pythons keywords as variable names (self.list)

Body:
I have a list with index number 0 to 5. I am telling user to input position where they want to mark ('X') into the list and then printing the list each time the user input's a index number. I want the user to input only once in a index number of the list and if user try to overwrite the written value in a list I want to give a message to user as a input 'you can't go there please try again in different position'. I want to keep running the input until the user enters a value in non-written position in the list.

I tried to do it in OOP as I am practicing OOP. I make a board then display the board with print_Board() method. In method input_Value() I tried to make it run under a while loop and break the loop when all positions are filled... also used a try catch error... which will check if the input value must have the index number from 1 to 6 only.

class Overwrite:

    list = ['.', '.', '.', '.', '.', '.']

    def print_Board(self):
        print(self.list[0:3])
        print(self.list[3:6])

    def input_Value(self):
        while True:
            try:
                self.position = input('enter a number between 1 to 6:')     # input a value
                if self.position not in ['1', '2', '3', '4', '5', '6']: # checking if the number is in range(1 to 6) or not
                    print('please try again a number between 1 to 6')
                    continue
                self.position = int(self.position) - 1  # putting -1 so that user input is different than
                self.list[self.position] = 'X'
                self.print_Board()
            except IndexError:
                print('please try again a number between 1 to 6:')
            except ValueError:
                print('please try again a number between 1 to 6:')
            else:
                if '.' not in self.list:  # it will stop the program when all the positions are filled
                    break

    def gameplay(self):
        self.print_Board()
        self.input_Value()

Body:
The simplest way that I can think to do this is to include another selection statement:

if self.list[self.position] == 'X':
    print("you can't go there please try again in different position")
    continue

This will check if the selected index was already mutated to 'X', if it has, it will restart the while loop. Otherwise, it will continue through your code to change the position to 'X'

Although for general practice, be careful of using pythons keywords as variable names (self.list)


问:
How to add an object as a child of an object java
i'm stuck since hrs to a problem that regards adding an object as a child of another object: i have this class "Snapo" which contains the object Snapo, it is an array that contains the first index (m) which is an integer, and it's followed by a list Snapo --> [m (s1 s2 ... sn)]. Now i wrote the code to add a child which has only the "m" attribute to the main Snapo, but i can't understand how to add a Snapo to the main Snapo, like:
[8 ([5 ([7] [6])] [1 ([4] [3] [2])])] --> where "8" , "5" and "1" are the "m" and the other numbers are the list of Snapo

declaration of variables:

```<code>private final static int SIZE = 100;
private int m;
public int[] arr = new int[SIZE];
private int top=0;

Snapo (int m) {
    this.m = m;
    arr[0] = this.m;
}
</code>```

This is the constructor of the class ^

```<code>public void addChild (Snapo s) {
    top++;
    for (int i = top; i > 1; i--) {
        arr[i] = arr[i - 1];
    }
    arr[1] = s.arr[0];
}
</code>```

This is the addChild method that adds a single number to the main Snapo ^ (top is initialized as a private int = 0)

My program works with inputs like:

```<code>Snapo s1 = new Snapo(1);

s1.addChild(new Snapo(2));
s1.addChild(new Snapo(3));
</code>```

But it obviously doesn't with inputs like:

```<code>Snapo s3 = new Snapo(8);
s3.addChild(s1);
s3.addChild(s2);
</code>```

答:
Maybe this example could be useful

```<code>import java.util.ArrayList;
import java.util.List;
class TestAddC
{
    public static void main(String args[])
    {
        TestAddC t= new TestAddC();
        Snapo s1 = t.new Snapo("s1");
        s1.addChild(t.new Snapo("s2"));
        Snapo s3 = t.new Snapo("s3");
        s1.addChild(s3);
        Snapo s4 = t.new Snapo("s4");
        s3.addChild(s4);

        System.out.println(s1);
        System.out.println(s3);

    }
    class Snapo
    {
        List<Snapo> listC= new ArrayList<Snapo>();
        String name;
        Snapo(String name)
        {
            this.name = name;
        }
        public void addChild(Snapo obj)
        {
            listC.add(obj);
        }
        public String toString()
        {
            StringBuffer sb = new StringBuffer();
            sb.append("parent="+this.name+"\n");
            //only first level
            listC.forEach(t->sb.append("child="+t.name+"\n"));
            return sb.toString();
        }
    }
}
</code>```

Output

```<code>parent=s1
child=s2
child=s3

parent=s3
child=s4
</code>```

Version 2 : with arrays

```<code>class TestAddC
{
    public static void main(String args[])
    {
        TestAddC t= new TestAddC();
        Snapo s1 = t.new Snapo("s1");
        s1.addChild(t.new Snapo("s2"));
        Snapo s3 = t.new Snapo("s3");
        s1.addChild(s3);
        Snapo s4 = t.new Snapo("s4");
        s3.addChild(s4);
        s3.addChild(s4);
        s3.addChild(s4);
        s3.addChild(s4);
        s3.addChild(s1);

        System.out.println(s1);
        System.out.println(s3);
    }
    class Snapo
    {

        //add here up to how many children
        Snapo[] listArr = new Snapo[3];
        int counter = 0;
        String name;
        Snapo(String name)
        {
            this.name = name;
        }
        private int getNext()
        {
            System.out.println(counter);
            return (counter<listArr.length)? counter++ :(listArr.length -1);
        }
        public void addChild(Snapo obj)
        {
            listArr[getNext()] = obj;
        }
        public String toString()
        {
            StringBuffer sb = new StringBuffer();
            sb.append("parent="+this.name+"\n");
            //only first level
            for(int i=0;i<listArr.length;i++)
            {
                if(listArr[i] instanceof Snapo )
                {
                    sb.append("child="+listArr[i].name+"\n");
                }
            }
            return sb.toString();
        }
    }
}
</code>```

Output

```<code>parent=s1
child=s2
child=s3

//only 3 since arrsize is 3 (added 4, always last one have the last child)
parent=s3
child=s4
child=s4
child=s1
</code>```

Body:
i'm stuck since hrs to a problem that regards adding an object as a child of another object: i have this class "Snapo" which contains the object Snapo, it is an array that contains the first index (m) which is an integer, and it's followed by a list Snapo --> [m (s1 s2 ... sn)]. Now i wrote the code to add a child which has only the "m" attribute to the main Snapo, but i can't understand how to add a Snapo to the main Snapo, like:
[8 ([5 ([7] [6])] [1 ([4] [3] [2])])] --> where "8" , "5" and "1" are the "m" and the other numbers are the list of Snapo

declaration of variables:

private final static int SIZE = 100;
private int m;
public int[] arr = new int[SIZE];
private int top=0;

Snapo (int m) {
    this.m = m;
    arr[0] = this.m;
}

This is the constructor of the class ^

public void addChild (Snapo s) {
    top++;
    for (int i = top; i > 1; i--) {
        arr[i] = arr[i - 1];
    }
    arr[1] = s.arr[0];
}

This is the addChild method that adds a single number to the main Snapo ^ (top is initialized as a private int = 0)

My program works with inputs like:

Snapo s1 = new Snapo(1);

s1.addChild(new Snapo(2));
s1.addChild(new Snapo(3));

But it obviously doesn't with inputs like:

Snapo s3 = new Snapo(8);
s3.addChild(s1);
s3.addChild(s2);

Body:
Maybe this example could be useful

import java.util.ArrayList;
import java.util.List;
class TestAddC
{
    public static void main(String args[])
    {
        TestAddC t= new TestAddC();
        Snapo s1 = t.new Snapo("s1");
        s1.addChild(t.new Snapo("s2"));
        Snapo s3 = t.new Snapo("s3");
        s1.addChild(s3);
        Snapo s4 = t.new Snapo("s4");
        s3.addChild(s4);

        System.out.println(s1);
        System.out.println(s3);

    }
    class Snapo
    {
        List<Snapo> listC= new ArrayList<Snapo>();
        String name;
        Snapo(String name)
        {
            this.name = name;
        }
        public void addChild(Snapo obj)
        {
            listC.add(obj);
        }
        public String toString()
        {
            StringBuffer sb = new StringBuffer();
            sb.append("parent="+this.name+"\n");
            //only first level
            listC.forEach(t->sb.append("child="+t.name+"\n"));
            return sb.toString();
        }
    }
}

Output

parent=s1
child=s2
child=s3

parent=s3
child=s4

Version 2 : with arrays

class TestAddC
{
    public static void main(String args[])
    {
        TestAddC t= new TestAddC();
        Snapo s1 = t.new Snapo("s1");
        s1.addChild(t.new Snapo("s2"));
        Snapo s3 = t.new Snapo("s3");
        s1.addChild(s3);
        Snapo s4 = t.new Snapo("s4");
        s3.addChild(s4);
        s3.addChild(s4);
        s3.addChild(s4);
        s3.addChild(s4);
        s3.addChild(s1);

        System.out.println(s1);
        System.out.println(s3);
    }
    class Snapo
    {

        //add here up to how many children
        Snapo[] listArr = new Snapo[3];
        int counter = 0;
        String name;
        Snapo(String name)
        {
            this.name = name;
        }
        private int getNext()
        {
            System.out.println(counter);
            return (counter<listArr.length)? counter++ :(listArr.length -1);
        }
        public void addChild(Snapo obj)
        {
            listArr[getNext()] = obj;
        }
        public String toString()
        {
            StringBuffer sb = new StringBuffer();
            sb.append("parent="+this.name+"\n");
            //only first level
            for(int i=0;i<listArr.length;i++)
            {
                if(listArr[i] instanceof Snapo )
                {
                    sb.append("child="+listArr[i].name+"\n");
                }
            }
            return sb.toString();
        }
    }
}

Output

parent=s1
child=s2
child=s3

//only 3 since arrsize is 3 (added 4, always last one have the last child)
parent=s3
child=s4
child=s4
child=s1


问:
Each row in range skips every second value
I want to loop over all rows in the active worksheet and compare the values of a column.

However, it skips every second value.

The worksheet looks like this:

Code:

```<code>Sub test()

    Dim ws As Worksheet
    Dim r As Range
    Dim total As Integer
    Dim value As String

    Set ws = ActiveSheet
    total = 0

    For Each r In ws.UsedRange.rows

        value = r.Cells(r.Row, 3).value

        If value = "Test" Then

            'Do something...
            total = total + 1

        End If

       Debug.Print ("Row: " & r.Row & " - Value: " & value)

    Next r

End Sub
</code>```

The console shows this:

```<code>Row: 1 - Value: Col2
Row: 2 - Value: JohnDoe
Row: 3 - Value: JohnDoe
Row: 4 - Value: Test
Row: 5 - Value: Blabla
Row: 6 - Value: Blabla
Row: 7 - Value:
Row: 8 - Value:
Row: 9 - Value:
Row: 10 - Value:
Row: 11 - Value:
</code>```

How do I fix this, so it does not skip every second value?

The reason I am using UsedRange instead of for i = 1 to x, is that I will not now the number of rows beforehand.

答:
The solution, thanks to @BigBen

```<code>Sub test_solution()

    'Variables
    Dim ws As Worksheet
    Dim r As Range
    Dim total As Integer
    Dim value As String
    Dim lastRow
    Dim i As Integer
    Set ws = ActiveSheet
    total = 0

    With ws
        lastRow = Range("C" & .rows.Count).End(xlUp).Row
    End With

    For i = 1 To lastRow

        value = Cells(i, 3).value

        If value = "Test" Then

            'Do something

            total = total + 1

        End If

       Debug.Print ("Row: " & i & " - Value: " & value)

    Next i

End Sub
</code>```

Gives correct output:

```<code>Row: 1 - Value: Col2
Row: 2 - Value: Test
Row: 3 - Value: JohnDoe
Row: 4 - Value: Test
Row: 5 - Value: JohnDoe
Row: 6 - Value: JohnDoe
Row: 7 - Value: Test
Row: 8 - Value: Blabla
Row: 9 - Value: Blabla
Row: 10 - Value: Test
Row: 11 - Value: Blabla
</code>```

Body:
I want to loop over all rows in the active worksheet and compare the values of a column.

However, it skips every second value.

The worksheet looks like this:

Code:

Sub test()

    Dim ws As Worksheet
    Dim r As Range
    Dim total As Integer
    Dim value As String

    Set ws = ActiveSheet
    total = 0

    For Each r In ws.UsedRange.rows

        value = r.Cells(r.Row, 3).value

        If value = "Test" Then

            'Do something...
            total = total + 1

        End If

       Debug.Print ("Row: " & r.Row & " - Value: " & value)

    Next r

End Sub

The console shows this:

Row: 1 - Value: Col2
Row: 2 - Value: JohnDoe
Row: 3 - Value: JohnDoe
Row: 4 - Value: Test
Row: 5 - Value: Blabla
Row: 6 - Value: Blabla
Row: 7 - Value:
Row: 8 - Value:
Row: 9 - Value:
Row: 10 - Value:
Row: 11 - Value:

How do I fix this, so it does not skip every second value?

The reason I am using UsedRange instead of for i = 1 to x, is that I will not now the number of rows beforehand.

Body:
The solution, thanks to @BigBen

Sub test_solution()

    'Variables
    Dim ws As Worksheet
    Dim r As Range
    Dim total As Integer
    Dim value As String
    Dim lastRow
    Dim i As Integer
    Set ws = ActiveSheet
    total = 0

    With ws
        lastRow = Range("C" & .rows.Count).End(xlUp).Row
    End With

    For i = 1 To lastRow

        value = Cells(i, 3).value

        If value = "Test" Then

            'Do something

            total = total + 1

        End If

       Debug.Print ("Row: " & i & " - Value: " & value)

    Next i

End Sub

Gives correct output:

Row: 1 - Value: Col2
Row: 2 - Value: Test
Row: 3 - Value: JohnDoe
Row: 4 - Value: Test
Row: 5 - Value: JohnDoe
Row: 6 - Value: JohnDoe
Row: 7 - Value: Test
Row: 8 - Value: Blabla
Row: 9 - Value: Blabla
Row: 10 - Value: Test
Row: 11 - Value: Blabla


问:
Glide - ImageView height is 0dp for first load
I send images to server via Retrofit. When sending process is completed my FeedFragment is opening and last sent image must be shown at the top of RecyclerView (first position). But imageView is invisible at first load. Only if I scroll down and scroll up it's becoming visible. Glide Code (in RecyclerView Adapter):

```<code>                           Glide.with(context)
                            .asBitmap()
                            .load(ApiClient.Base_URL + imagesList.get(0).getImage())
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .dontAnimate()
                            .dontTransform()
                            .thumbnail(0.1f)
                            .into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                                    progressBar.setVisibility(View.GONE);
                                    //for dynamic image height:
                                    targetImageHeight = (resource.getHeight() * deviceHeight) / resource.getWidth();

                                    if (targetImageHeight >= deviceHeight) {
                                        targetImageHeight = deviceHeight;
                                    }
                                    imageView.getLayoutParams().height = targetImageHeight;
                                    imageView.setImageBitmap(resource);
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                    Glide.with(context).clear(imageView);
                                    progressBar.setVisibility(View.GONE);
                                }
                            });
</code>```

xml:

```<code> <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ProgressBar
                android:id="@+id/progressBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:visibility="gone" />

            <uk.co.senab.photoview.PhotoView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="400dp" />

        </RelativeLayout>
</code>```

答:
Please try below code:-</p>

```<code>void load(final ImageView imageView) {
if (imageView.getHeight() == 0) {
    imageView.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
        @Override public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            load(imageView);
            return true; // == allow drawing
        }
    });
} else {
    Glide
            .with(imageView.getContext())
            .load("whatever")
            .fitCenter()
            .override(Target.SIZE_ORIGINAL, imageView.getHeight())
            .into(imageView);
   }
 }
</code>```

Body:
I send images to server via Retrofit. When sending process is completed my FeedFragment is opening and last sent image must be shown at the top of RecyclerView (first position). But imageView is invisible at first load. Only if I scroll down and scroll up it's becoming visible. Glide Code (in RecyclerView Adapter):

                           Glide.with(context)
                            .asBitmap()
                            .load(ApiClient.Base_URL + imagesList.get(0).getImage())
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .dontAnimate()
                            .dontTransform()
                            .thumbnail(0.1f)
                            .into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                                    progressBar.setVisibility(View.GONE);
                                    //for dynamic image height:
                                    targetImageHeight = (resource.getHeight() * deviceHeight) / resource.getWidth();

                                    if (targetImageHeight >= deviceHeight) {
                                        targetImageHeight = deviceHeight;
                                    }
                                    imageView.getLayoutParams().height = targetImageHeight;
                                    imageView.setImageBitmap(resource);
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                    Glide.with(context).clear(imageView);
                                    progressBar.setVisibility(View.GONE);
                                }
                            });

xml:

 <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ProgressBar
                android:id="@+id/progressBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:visibility="gone" />

            <uk.co.senab.photoview.PhotoView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="400dp" />

        </RelativeLayout>

Body:
Please try below code:-

void load(final ImageView imageView) {
if (imageView.getHeight() == 0) {
    imageView.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
        @Override public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            load(imageView);
            return true; // == allow drawing
        }
    });
} else {
    Glide
            .with(imageView.getContext())
            .load("whatever")
            .fitCenter()
            .override(Target.SIZE_ORIGINAL, imageView.getHeight())
            .into(imageView);
   }
 }


问:
How to deal with a merge conflict caused by files moved in the target branch
I am very new to git, but I have some changes that I would like to make and there are some merge conflicts. These conflicts come from some files that have been moved in the target branch. How do I deal with these conflicts? The files have only been moved, so the changes that I made still hold, it just tells me that the file was deleted in the target branch. Should I make a new branch off of the updated target branch, and make the changes again?</p>

答:
It may help to know that in git, there is no such thing as "moving" a file.

Let's say you move /my/path/file.txt into a different directory, /my/other/path. The whole path is the name of the file. So what git knows is that there are two files in this story, one named  /my/path/file.txt and another named /my/other/path/file.txt. They are not somehow magically associated with one another, as they are in your mind. You call it moved. To git, the first file was deleted and the second file was created.

Now, it is true that sometimes when /my/path/file.txt is deleted and my/other/path/file.txt is created, git is able to combine that into the idea of "renaming" the file — that is, a file that was in one directory has its pathname changed by now appearing in another directory — but for that to work, they must be identically "the same" file, that is, their contents must be the same.

Otherwise, and in general, when you "move" a file, what git sees is that one file was deleted and another was created. And changing the contents of a file and moving it, after one commit but before another, is likely to result in git seeing one file simply disappear (delete) and another as appearing (create).

So, you have in your head a human notion that "The files have only been moved, so the changes that I made still hold", but that is not how git thinks. Git is a computer. What it sees are that in one branch the file named /my/path/file.txt vanished (because it was "moved", as you suppose). But in the other branch the file named /my/path/file.txt stayed where it was and was edited!

Well, those are two different changes on the same file: delete vs. modify. Now git doesn't know what to do.

(Meanwhile, git also sees that in the first branch a file named /my/other/path/file.txt was created, but it does not in any way associate this with either of the two files we just talked about.)

In the end, you have to decide what you want done here. I have to admit that, even as a human, it is unclear to me what you think the resolution should be. The situation seems to be that you've really got two files now, the file at /my/other/path/file.txt created in the first branch, and the file at /my/path/file.txt deleted in the first branch but edited in the second branch. I cannot imagine how you expect to proceed at this point. You surely do not want both of these files going forward. But where do you want the edited file? Even I don't know the answer to that one.

So you need to answer that question. You probably want it in the new location. So in that case your best bet, it seems to me, is to abort the merge, move  /my/path/file.txt to /my/other/path/file.txt in the second branch, and start the merge again.

I would also like to add that conflicts are not, of themselves, a bad thing! All they mean is that git cannot completely generate a merge commit automatically; it doesn't know what you intend. Presumably you do, so you just tell it (by making that part of the merge commit yourself, manually). On the whole, the language of "merge conflict" and "resolve the conflict" is completely misleading; we should think entirely in terms of the positive activity "create (or prepare to create) a merge commit", which either git can do automatically or you and git can do together, cooperatively.


问:
I'm having trouble using ggplot2 to reproduce a violin plot
My data includes a combination of mutations for several genes per sample, the counts, and the MIC (these are discrete) for the antibiotic the bacteria was screened on.

Here is toy data:

```<code>structure(list(count = c(4L, 26L, 96L, 93L, 2L, 22L), combo = structure(c(22L,
19L, 2L, 2L, 20L, 19L), .Label = c("HFALSEAIVTANGGAL", "HFALSEAIVTANGGAP",
"HFALSEAIVTANGGTP", "HFALSEAIVTANSGAP", "HFALSEAIVTAYGGTP", "HFALSEAIVTTNSGAP",
"HFALSEAIVTVNGGAL", "HFALSEAIVTVNGGAS", "HFALSEAIVTVNSGAP", "HFALSEAMTTAYGSAA",
"HFALSEAMTTAYGSAP", "HFALSEAMTTAYGSTP", "HTRUEAIVSANGGAP", "HTRUEAIVTANGGAP",
"HTRUEAIVTANSGAP", "HTRUEAIVTTNSGAP", "HTRUEAMTTAYGSAP", "YFALSEAIVTANGGAL",
"YFALSEAIVTANGGAP", "YFALSEAIVTANGGAS", "YFALSEAIVTANSGAP", "YFALSEAIVTTNGGAL",
"YFALSEAIVTTNGGAP", "YFALSEAIVTTNSGAP", "YFALSEAIVTVNGGAL", "YFALSEAMTTANGGAP",
"YFALSEAMTTANGGTP", "YFALSEAMTTAYGSAA", "YFALSEAMTTAYGSAP", "YFALSEAMTTAYGSAS",
"YFALSEAMTTAYGSTP", "YFALSENFNFNFNFNFNFNFNFNFNF", "YTRUEAIVTANGGAL",
"YTRUEAIVTANGGAP", "YTRUEAMTTAYGSAP"), class = "factor")), row.names = c(NA,
6L), class = "data.frame")
</code>```

This goes on and on for each MIC category (there are 8 on a log2 scale).

I am attempting to create a violin plot like this (source: https://www.thelancet.com/journals/laninf/article/PIIS1473-3099(18)30225-1/fulltext
):

I attempted to write some code but didn't get very far:

```<code>p <- ggplot(mydata, aes(factor(combo), y=mic)) +
  geom_violin() +
  geom_boxplot(width=.01, outlier.size=0, fill="grey50") +
  stat_summary(fun.y=median, geom="point", fill="white", shape=21, size=4)
p
</code>```

Here is what that plot looks like:

I can easily create a count table but I was hoping to have some visual like the image produced below. Can someone steer me in the right direction?

```<code>p <- ggplot(mydata, aes(x = combo, y=mic))
p + geom_violin()  + geom_jitter(height = 0, width = 0.1, aes(color=factor(combo)))
</code>```

答:
A long time has passed, and now there is an R package called ggupset which makes charts similar to those linked in The Lancet.

https://github.com/const-ae/ggupset

Plot a combination matrix instead of the standard x-axis and create UpSet plots with ggplot2.

Body:
My data includes a combination of mutations for several genes per sample, the counts, and the MIC (these are discrete) for the antibiotic the bacteria was screened on.

Here is toy data:

structure(list(count = c(4L, 26L, 96L, 93L, 2L, 22L), combo = structure(c(22L,
19L, 2L, 2L, 20L, 19L), .Label = c("HFALSEAIVTANGGAL", "HFALSEAIVTANGGAP",
"HFALSEAIVTANGGTP", "HFALSEAIVTANSGAP", "HFALSEAIVTAYGGTP", "HFALSEAIVTTNSGAP",
"HFALSEAIVTVNGGAL", "HFALSEAIVTVNGGAS", "HFALSEAIVTVNSGAP", "HFALSEAMTTAYGSAA",
"HFALSEAMTTAYGSAP", "HFALSEAMTTAYGSTP", "HTRUEAIVSANGGAP", "HTRUEAIVTANGGAP",
"HTRUEAIVTANSGAP", "HTRUEAIVTTNSGAP", "HTRUEAMTTAYGSAP", "YFALSEAIVTANGGAL",
"YFALSEAIVTANGGAP", "YFALSEAIVTANGGAS", "YFALSEAIVTANSGAP", "YFALSEAIVTTNGGAL",
"YFALSEAIVTTNGGAP", "YFALSEAIVTTNSGAP", "YFALSEAIVTVNGGAL", "YFALSEAMTTANGGAP",
"YFALSEAMTTANGGTP", "YFALSEAMTTAYGSAA", "YFALSEAMTTAYGSAP", "YFALSEAMTTAYGSAS",
"YFALSEAMTTAYGSTP", "YFALSENFNFNFNFNFNFNFNFNFNF", "YTRUEAIVTANGGAL",
"YTRUEAIVTANGGAP", "YTRUEAMTTAYGSAP"), class = "factor")), row.names = c(NA,
6L), class = "data.frame")

This goes on and on for each MIC category (there are 8 on a log2 scale).

I am attempting to create a violin plot like this (source: https://www.thelancet.com/journals/laninf/article/PIIS1473-3099(18)30225-1/fulltext
):

I attempted to write some code but didn't get very far:

p <- ggplot(mydata, aes(factor(combo), y=mic)) +
  geom_violin() +
  geom_boxplot(width=.01, outlier.size=0, fill="grey50") +
  stat_summary(fun.y=median, geom="point", fill="white", shape=21, size=4)
p

Here is what that plot looks like:

I can easily create a count table but I was hoping to have some visual like the image produced below. Can someone steer me in the right direction?

p <- ggplot(mydata, aes(x = combo, y=mic))
p + geom_violin()  + geom_jitter(height = 0, width = 0.1, aes(color=factor(combo)))


问:
SSRS Page break on Tablix with Rownumber ,just one row group and no group expression given by default
I have created a report with one tablix and it has one RowGroup (which automatically came) when I dragged and dropped my report fields. [It doesnot have any group by expression defined]

Now my requirement is to create page breaks based on the row number.

I clicked on the RowGroup properties and give Group on expression
=Floor(RowNumber(Nothing)-1/2000)

And page break "Between each instance of group "

Now page is breaking,but the problem is its breaking for every row in my tablix.

How can I overcome the same and break only at 2000 rows.

This is to avoid Excel export exception on large data.

What am I doing wrong with the tablix/group settings.

答:
I haven't done this before but try adding another group outside you current group with this expression. Then set the page break in it.

Edit: I just re read you question. I think you expression is incorrect. I think it should be:

```<code>=Floor((RowNumber(Nothing)-1)/2000)
</code>```

I couldn't understand how you could set that as the group expression and it would stil group correctly. So you will still need 2 groups:

An outside group with this expression and the pagebreak.

A details group with what you are actual displaying on each row.

Body:
I haven't done this before but try adding another group outside you current group with this expression. Then set the page break in it.

Edit: I just re read you question. I think you expression is incorrect. I think it should be:

=Floor((RowNumber(Nothing)-1)/2000)

I couldn't understand how you could set that as the group expression and it would stil group correctly. So you will still need 2 groups:

An outside group with this expression and the pagebreak.

A details group with what you are actual displaying on each row.