问:
Responsive table in table - HTML email
I'm trying to make responsive email in HTML but i need to put very long table in table, which is a structure. It's not problem to make table responsive with overflow-x: auto, but it's difficult (for me) to make responsive table in table.

Here's codepen: https://codepen.io/Aventadorrre/pen/NWPeWdd
When you remove whole div table-wrapper then it works perfectly with small devices. When i have this table in table it's only scalling.

```<code><!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Simple Transactional Email</title>
    <style>
      /* -------------------------------------
          GLOBAL RESETS
      ------------------------------------- */

      /*All the styling goes here*/

      img {
        border: none;
        -ms-interpolation-mode: bicubic;
        max-width: 100%;
      }

      body {
        background-color: #f6f6f6;
        font-family: sans-serif;
        -webkit-font-smoothing: antialiased;
        font-size: 14px;
        line-height: 1.4;
        margin: 0;
        padding: 0;
        -ms-text-size-adjust: 100%;
        -webkit-text-size-adjust: 100%;
      }

      table {
        border-collapse: separate;
        mso-table-lspace: 0pt;
        mso-table-rspace: 0pt;
        width: 100%; }
        table td {
          font-family: sans-serif;
          font-size: 14px;
          vertical-align: top;
      }

      /* -------------------------------------
          BODY & CONTAINER
      ------------------------------------- */

      .body {
        background-color: #f6f6f6;
        width: 100%;
      }

      /* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
      .container {
        display: block;
        margin: 0 auto !important;
        /* makes it centered */
        max-width: 991px;
        padding: 10px;
        width: 991px;
      }

      /* This should also be a block element, so that it will fill 100% of the .container */
      .content {
        box-sizing: border-box;
        display: block;
        margin: 0 auto;
        max-width: 991px;
        padding: 10px;
      }

      /* -------------------------------------
          HEADER, FOOTER, MAIN
      ------------------------------------- */
      .locals {
        border-collapse: collapse;
        border-spacing: 0;
        width: 100%;
        border: 1px solid #ddd;
      }
      .locals td {
        text-align: center;
        padding: 8px;
      }

      .locals th {
        text-align: center;
        padding: 8px;
      }

      .table-title {
        margin-top: 35px;
      }

      .table-wrapper {
        margin-bottom: 30px;
      }

      .about-wrapper p {
        margin-bottom: 15px;
      }

      .main {
        background: #ffffff;
        border-radius: 3px;
        width: 100%;
      }

      .wrapper {
        box-sizing: border-box;
        padding: 20px;
      }

      .content-block {
        padding-bottom: 10px;
        padding-top: 10px;
      }

      .footer {
        clear: both;
        margin-top: 10px;
        text-align: center;
        width: 100%;
      }
        .footer td,
        .footer p,
        .footer span,
        .footer a {
          color: #999999;
          font-size: 12px;
          text-align: center;
      }

      /* -------------------------------------
          TYPOGRAPHY
      ------------------------------------- */
      h1,
      h2,
      h3,
      h4 {
        color: #000000;
        font-family: sans-serif;
        font-weight: 400;
        line-height: 1.4;
        margin: 0;
        margin-bottom: 30px;
      }

      h1 {
        font-size: 35px;
        font-weight: 300;
        text-align: center;
        text-transform: capitalize;
      }

      p,
      ul,
      ol {
        font-family: sans-serif;
        font-size: 14px;
        font-weight: normal;
        margin: 0;
        margin-bottom: 15px;
      }
        p li,
        ul li,
        ol li {
          list-style-position: inside;
          margin-left: 5px;
      }

      a {
        color: #3498db;
        text-decoration: underline;
      }

      /* -------------------------------------
          BUTTONS
      ------------------------------------- */
      .btn {
        box-sizing: border-box;
        width: 100%; }
        .btn > tbody > tr > td {
          padding-bottom: 15px; }
        .btn table {
          width: auto;
      }
        .btn table td {
          background-color: #ffffff;
          border-radius: 5px;
          text-align: center;
      }
        .btn a {
          background-color: #ffffff;
          border: solid 1px #3498db;
          border-radius: 5px;
          box-sizing: border-box;
          color: #3498db;
          cursor: pointer;
          display: inline-block;
          font-size: 14px;
          font-weight: bold;
          margin: 0;
          padding: 12px 25px;
          text-decoration: none;
          text-transform: capitalize;
      }

      .btn-primary table td {
        background-color: #3498db;
      }

      .btn-primary a {
        background-color: #3498db;
        border-color: #3498db;
        color: #ffffff;
      }

      /* -------------------------------------
          OTHER STYLES THAT MIGHT BE USEFUL
      ------------------------------------- */
      .last {
        margin-bottom: 0;
      }

      .first {
        margin-top: 0;
      }

      .align-center {
        text-align: center;
      }

      .align-right {
        text-align: right;
      }

      .align-left {
        text-align: left;
      }

      .clear {
        clear: both;
      }

      .mt0 {
        margin-top: 0;
      }

      .mb0 {
        margin-bottom: 0;
      }

      .preheader {
        color: transparent;
        display: none;
        height: 0;
        max-height: 0;
        max-width: 0;
        opacity: 0;
        overflow: hidden;
        mso-hide: all;
        visibility: hidden;
        width: 0;
      }

      .powered-by a {
        text-decoration: none;
      }

      hr {
        border: 0;
        border-bottom: 1px solid #f6f6f6;
        margin: 20px 0;
      }

      /* -------------------------------------
          RESPONSIVE AND MOBILE FRIENDLY STYLES
      ------------------------------------- */
      @media only screen and (max-width: 768px) {
        table[class=body] h1 {
          font-size: 28px !important;
          margin-bottom: 10px !important;
        }
        table[class=body] p,
        table[class=body] ul,
        table[class=body] ol,
        table[class=body] td,
        table[class=body] span,
        table[class=body] a {
          font-size: 16px !important;
        }
        table[class=body] .wrapper,
        table[class=body] .article {
          padding: 10px !important;
        }
        table[class=body] .content {
          padding: 0 !important;
        }
        table[class=body] .container {
          padding: 0 !important;
          width: 100% !important;
        }
        table[class=body] .main {
          border-left-width: 0 !important;
          border-radius: 0 !important;
          border-right-width: 0 !important;
        }
        table[class=body] .btn table {
          width: 100% !important;
        }
        table[class=body] .btn a {
          width: 100% !important;
        }
        table[class=body] .img-responsive {
          height: auto !important;
          max-width: 100% !important;
          width: auto !important;
        }
      }

      /* -------------------------------------
          PRESERVE THESE STYLES IN THE HEAD
      ------------------------------------- */
      @media all {
        .ExternalClass {
          width: 100%;
        }
        .ExternalClass,
        .ExternalClass p,
        .ExternalClass span,
        .ExternalClass font,
        .ExternalClass td,
        .ExternalClass div {
          line-height: 100%;
        }
        .apple-link a {
          color: inherit !important;
          font-family: inherit !important;
          font-size: inherit !important;
          font-weight: inherit !important;
          line-height: inherit !important;
          text-decoration: none !important;
        }
        #MessageViewBody a {
          color: inherit;
          text-decoration: none;
          font-size: inherit;
          font-family: inherit;
          font-weight: inherit;
          line-height: inherit;
        }
        .btn-primary table td:hover {
          background-color: #34495e !important;
        }
        .btn-primary a:hover {
          background-color: #34495e !important;
          border-color: #34495e !important;
        }
      }

    </style>
  </head>
  <body class="">
    <span class="preheader">This is preheader text. Some clients will show this text as a preview.</span>
    <table role="presentation" border="0" cellpadding="0" cellspacing="0" class="body">
      <tr>
        <td> </td>
        <td class="container">
          <div class="content">

            <!-- START CENTERED WHITE CONTAINER -->
            <table role="presentation" class="main">

              <!-- START MAIN CONTENT AREA -->
              <tr>
                <td class="wrapper">
                  <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                      <td>
                        <p>Szanowni Państwo,</p>
                        <p>Dziękuję serdecznie za zainteresowanie inwestycją Rezydencja Gubałówka. <br><br>W odpowiedzi na zapytanie, załączam kilka informacji dotyczących inwestycji.</p>
                        <p>Nasza oferta to:</p>
                        <ul>
                          <li>Rentowność do 7% w skali roku od wartości zainwestowanej kwoty</li>
                          <li>W cenie apartamentu wykończenie pod klucz w bardzo wysokim standardzie</li>
                          <li>Do 2 tygodni pobytu właścicielskiego w roku</li>
                          <li>200 m od górnej stacji Polany Szymoszkowej </li>
                          <li>Umowa najmu na 10 lat</li>
                          <li>Pierwsza wpłata 20% kolejne wraz z realizacją inwestycji</li>
                          <li>Planowany termin oddania II kwartał 2022 r.</li>
                          <li>Możliwość rozliczenia podatku VAT (w tym celu zalecamy kontakt z właściwym Urzędem Skarbowym).</li>
                        </ul>
                        <p class="table-title"><strong>Poniżej znajduje się przykładowa oferta lokali od 12 do 39 m.kw.</strong></p>
                        <div class="table-wrapper" style="overflow-x: auto;">
                          <table class="locals">
                              <tr>
                                <th>Budynek</th>
                                <th>Kondygnacja</th>
                                <th>Nr lokalu</th>
                                <th>Powierzchnia po podłodze [m²]</th>
                                <th>Pokój [m²]</th>
                                <th>Łazienka [m²]</th>
                                <th>Balkon [m²]</th>
                                <th>Antresola [m²]</th>
                                <th>Cena m² netto</th>
                                <th>Cena netto</th>
                              </tr>
                              <tr>
                                <td class="align-center">5</td>
                                <td class="align-center">-1</td>
                                <td class="align-center">5A-07</td>
                                <td class="align-center">12,63</td>
                                <td class="align-center">10,43</td>
                                <td class="align-center">2,20</td>
                                <td class="align-center">-</td>
                                <td class="align-center">-</td>
                                <td class="align-center">21 900 zł</td>
                                <td class="align-center">276 597 zł</td>
                              </tr>
                              <tr>
                                <td class="align-center">5</td>
                                <td class="align-center">-1</td>
                                <td class="align-center">5A-07</td>
                                <td class="align-center">12,63</td>
                                <td class="align-center">10,43</td>
                                <td class="align-center">2,20</td>
                                <td class="align-center">-</td>
                                <td class="align-center">-</td>
                                <td class="align-center">21 900 zł</td>
                                <td class="align-center">276 597 zł</td>
                              </tr>
                          </table>
                        </div>
                        <div class="about-wrapper">
                          <p>Do każdego lokalu istnieje możliwość zakupu miejsca postojowego w garażu podziemnym w cenie 50.000 zł netto. Kwota ta zalicza się do kwoty zainwestowanej od której naliczany jest czynsz.</p>
                          <p>Rezydencja Gubałówka to unikalny na skalę polską obiekt położony w Kościelisku na szczycie góry Gubałówka. Dzięki swojej unikalnej lokalizacji, Rezydencja Gubałówka zyskała szerokie grono klientów ceniących Zakopane za shopping i życie nocne (10 min. od Krupówek), wspaniałą naturę (Rezydencję otaczają łąki i lasy) oraz luksus (w obiekcie znajdą Państwo basen, spa, nagradzaną restaurację oraz bardzo wysoki standard wykończenia). Zapierające wdech w piersiach widoki powodują, że Rezydencję odwiedza coraz więcej turystów ceniących piękno natury i aktywną turystykę bez kompromisu.</p>
                          <p>Obiekt funkcjonuje od 2017 roku o stale rosnącej popularności (<strong>średnia ocena na <a href="#">domain.com</a> to 9,2</strong>). </p>
                          <p>Zapraszam do odwiedzenia strony naszego obiektu <a href="#">www.domain.com/</a>, <br> oraz strony naszej inwestycji <a href="#">domain.com</a></p>
                        </div>
                      </td>
                    </tr>
                  </table>
                </td>
              </tr>

            <!-- END MAIN CONTENT AREA -->
            </table>
            <!-- END CENTERED WHITE CONTAINER -->

            <!-- START FOOTER -->
            <div class="footer">
              <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                <tr>
                  <td class="content-block">
                    <span class="apple-link">Dział Sprzedaży Rezydencja Gubałówka</span>
                  </td>
                </tr>
              </table>
            </div>
            <!-- END FOOTER -->

          </div>
        </td>
        <td> </td>
      </tr>
    </table>
  </body>
</html>
</code>```

答:
There are three general ways of tackling responsive tables in HTML emails. Overflow-x will not work across all email clients, so it's not a solution.

Hybrid Column Approach

What you have is:

[head1] [head2] [head3]

[data1] [data2] [data3]

[data4] [data5] [data6]

But what you'll need for mobile responsiveness is a vertical table:

[head1] [data1]

[head2] [data2]

[head3] [data3]

With the second row as another table:

[head1] [data4]

[head2] [data5]

[head3] [data6]

By using the hybrid email approach and hiding the repeated headers by default (for desktop), we can achieve this.

See full write-up with code example for 4 columns here: https://medium.com/@nathankeenmelb/bulletproof-responsive-datatables-in-html-emails-64248b9e18f5

Table as image

You can save the entire table as an image; that way you enable zooming and scrolling for all email clients.

However, it comes with a large drawback in that the data is inaccessible, and requires extensive interaction by the user to read (zooming, constant moving left/right & up/down).

Cards

Does it have to be done as a table? It may be a better approach to group data into a 'card', allowing you to use multiple lines (plus it reads a whole lot better!).

See my write-up here: https://medium.com/@nathankeenmelb/responsive-datatables-through-card-ui-design-for-email-aca6f3c395a2

Title: Responsive table in table - HTML email

Body:
I'm trying to make responsive email in HTML but i need to put very long table in table, which is a structure. It's not problem to make table responsive with overflow-x: auto, but it's difficult (for me) to make responsive table in table.

Here's codepen: https://codepen.io/Aventadorrre/pen/NWPeWdd
When you remove whole div table-wrapper then it works perfectly with small devices. When i have this table in table it's only scalling.

<!doctype html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Simple Transactional Email</title>

    This is preheader text. Some clients will show this text as a preview.

Szanowni Państwo,

Dziękuję serdecznie za zainteresowanie inwestycją Rezydencja Gubałówka.

W odpowiedzi na zapytanie, załączam kilka informacji dotyczących inwestycji.

Nasza oferta to:

Rentowność do 7% w skali roku od wartości zainwestowanej kwoty

W cenie apartamentu wykończenie pod klucz w bardzo wysokim standardzie

Do 2 tygodni pobytu właścicielskiego w roku

200 m od górnej stacji Polany Szymoszkowej

Umowa najmu na 10 lat

Pierwsza wpłata 20% kolejne wraz z realizacją inwestycji

Planowany termin oddania II kwartał 2022 r.

Możliwość rozliczenia podatku VAT (w tym celu zalecamy kontakt z właściwym Urzędem Skarbowym).

Poniżej znajduje się przykładowa oferta lokali od 12 do 39 m.kw.

                                Budynek
                                Kondygnacja
                                Nr lokalu
                                Powierzchnia po podłodze [m²]
                                Pokój [m²]
                                Łazienka [m²]
                                Balkon [m²]
                                Antresola [m²]
                                Cena m² netto
                                Cena netto

                                5
                                -1
                                5A-07
                                12,63
                                10,43
                                2,20
                                -
                                -
                                21 900 zł
                                276 597 zł

                                5
                                -1
                                5A-07
                                12,63
                                10,43
                                2,20
                                -
                                -
                                21 900 zł
                                276 597 zł

Do każdego lokalu istnieje możliwość zakupu miejsca postojowego w garażu podziemnym w cenie 50.000 zł netto. Kwota ta zalicza się do kwoty zainwestowanej od której naliczany jest czynsz.

Rezydencja Gubałówka to unikalny na skalę polską obiekt położony w Kościelisku na szczycie góry Gubałówka. Dzięki swojej unikalnej lokalizacji, Rezydencja Gubałówka zyskała szerokie grono klientów ceniących Zakopane za shopping i życie nocne (10 min. od Krupówek), wspaniałą naturę (Rezydencję otaczają łąki i lasy) oraz luksus (w obiekcie znajdą Państwo basen, spa, nagradzaną restaurację oraz bardzo wysoki standard wykończenia). Zapierające wdech w piersiach widoki powodują, że Rezydencję odwiedza coraz więcej turystów ceniących piękno natury i aktywną turystykę bez kompromisu.

Obiekt funkcjonuje od 2017 roku o stale rosnącej popularności (średnia ocena na domain.com to 9,2).

Zapraszam do odwiedzenia strony naszego obiektu www.domain.com/,
 oraz strony naszej inwestycji domain.com

                    Dział Sprzedaży Rezydencja Gubałówka


来源: stackexchange

问:
Firefox not displaying :after pseudo-element
I'm using a pseudo element to display a fallback profile picture when a user does not upload his/her own. The fallback picture works well on Chrome, but not on Firefox. Any idea what causes this?

Chrome

Firefox

CSS

```<code>.agent-photo{
  width: 70px;
  height: 70px;
  border-radius: 50px;
  object-fit: cover;
  position: relative;
}

.agent-photo:before {
  background-image: url('../img/default-user-2.jpg');
  background-size: 70px 70px;
  content: '';
  display: block;
  width: 70px;
  height: 70px;
  border-radius: 50px;
  margin-bottom:3px;
}

.agent-thumbnail-container{
  position: absolute;
  top: 50%;
}

.confirmation-container{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}
</code>```

HTML

```<code><div class="agent-thumbnail-container">
    <img class="agent-photo" src="http://127.0.0.1:8000${agent.profile_pic}" alt="">
    <img class="agent-check" src="img/checkmark-green-circle.svg" alt="">
</div>

</code>```

答:
Most browsers don't support pseudo-elements on img tags.

From the spec:

Note. This specification does not fully define the interaction of
  :before and :after with replaced elements (such as IMG in HTML). This
  will be defined in more detail in a future specification.

See this answer for an explanation as to why.

ContentLicense: CC BY-SA 4.0

Body:
I'm using a pseudo element to display a fallback profile picture when a user does not upload his/her own. The fallback picture works well on Chrome, but not on Firefox. Any idea what causes this?

Chrome

Firefox

CSS

.agent-photo{
  width: 70px;
  height: 70px;
  border-radius: 50px;
  object-fit: cover;
  position: relative;
}

.agent-photo:before {
  background-image: url('../img/default-user-2.jpg');
  background-size: 70px 70px;
  content: '';
  display: block;
  width: 70px;
  height: 70px;
  border-radius: 50px;
  margin-bottom:3px;
}

.agent-thumbnail-container{
  position: absolute;
  top: 50%;
}

.confirmation-container{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}

HTML


问:
Python list contains only digits integer or string
I need to check if a list contains only digits of int or str.

ex:

[3, 34, "45", 7, "3"]

would return true

and ["3" "hello", 9]

would return false

I know that the .isdigit() function cannot be used with a list containing int

答:
```<code>your_list = [3, 34, "45", 7, "3"]
def foo(e):
    try:
        int(e)
        return True
    except ValueError:
        return False

all(map(foo, your_list))
</code>```


问:
Channel Replacement Using PIL
I am currently working on a tool where 1 image's channels are needing to be replaced with 3 other images.

for example:

```<code>I have an image "X" and the channels would be X.r, X.g and X.b respectively.
I have 3 other images ["A","B","C"]
Those 3 images needs to replace the channels in X.

So the result would be X.A, X.B and X.C.
</code>```

What is the best possible way to do so?

答:
You have split() and merge() and other methods

```<code>from PIL import Image

img = Image.open('images/image.jpg')

r,g,b = img.split()

#r = img.getchannel(0)
#g = img.getchannel(1)
#b = img.getchannel(2)

img = Image.merge('RGB', (r,g,b))

img.show()
</code>```

You can also convert to numpy array and work with array

```<code>from PIL import Image
import numpy as np

img = Image.open('images/image.jpg')

arr = np.array(img)

r = arr[:,:,0]
g = arr[:,:,1]
b = arr[:,:,2]

arr[:,:,0] = r
arr[:,:,1] = g
arr[:,:,2] = b

img = Image.fromarray(arr)

img.show()
</code>```

Example

```<code>from PIL import Image

img1 = Image.open('winter.jpg')
img2 = Image.open('spring.jpg')

r1,g1,b1 = img1.split()
r2,g2,b2 = img2.split()

new_img = Image.merge('RGB', (r1,g2,b2))

new_img.show()

new_img.save('output.jpg')
</code>```

winter.jpg

spring.jpg

output.jpg

Title: Channel Replacement Using PIL

Body:
I am currently working on a tool where 1 image's channels are needing to be replaced with 3 other images.

for example:

I have an image "X" and the channels would be X.r, X.g and X.b respectively.
I have 3 other images ["A","B","C"]
Those 3 images needs to replace the channels in X.

So the result would be X.A, X.B and X.C.

What is the best possible way to do so?

Body:
You have split() and merge() and other methods

from PIL import Image

img = Image.open('images/image.jpg')

r,g,b = img.split()

#r = img.getchannel(0)
#g = img.getchannel(1)
#b = img.getchannel(2)

img = Image.merge('RGB', (r,g,b))

img.show()

You can also convert to numpy array and work with array

from PIL import Image
import numpy as np

img = Image.open('images/image.jpg')

arr = np.array(img)

r = arr[:,:,0]
g = arr[:,:,1]
b = arr[:,:,2]

arr[:,:,0] = r
arr[:,:,1] = g
arr[:,:,2] = b

img = Image.fromarray(arr)

img.show()

Example

from PIL import Image

img1 = Image.open('winter.jpg')
img2 = Image.open('spring.jpg')

r1,g1,b1 = img1.split()
r2,g2,b2 = img2.split()

new_img = Image.merge('RGB', (r1,g2,b2))

new_img.show()

new_img.save('output.jpg')

winter.jpg

spring.jpg

output.jpg


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答: I'd use the Builder pattern here instead of Factory. No big difference but find it a bit easier when the parameters vary like it seems to do in his example.</p>

OwnerDisplayName: BloodParrot

ContentLicense: CC BY-SA 2.5

Title: Array of Strings to an Array of Objects

OwnerDisplayName: willcodejavaforfood


问:
Creating a custom android UI
does anyone know how I would get started creating a custom android UI?
it wouldn't be an app. Once you install it, it would change the appearance of your UI until you uninstall it.

I've done some research but it doesn't seem to be possible/available yet??

If anyone could help or link me to a site on how to to get started that'd be awesome, thx!

I program using eclipse, btw.

This is basically what i want to do, but i want to design it myself http://www.intomobile.com/2011/02/09/sentio-ui-android-home-replacement-app/
How would I get started?

答: maybe you should read the document about this site,i think i will help you.most of the ui element can create by xml file,or coding. if you want to know more about that,to read this site: http://developer.android.com/guide/topics/ui/index.html</p>

ContentLicense: CC BY-SA 3.0

Title: Creating a custom android UI


问:
Access VBA - Problems looping through fields in Access last record and exporting to Word bookmarks?
Thanks for looking at this.

I have a recordset with 60 fields and I want to export the last record for each field into a Microsoft Word file with 60 bookmarks called g1 to g60.

Of course I would like to loop through these but can't make it work.

Essentially what I want is this:

```<code>Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

wDoc.Bookmarks("g1").Range.Text = Nz(rs!PlanQ, "")
wDoc.Bookmarks("g2").Range.Text = Nz(rs!PlanQMin, "")
wDoc.Bookmarks("g3").Range.Text = Nz(rs!PlanUnsat, "")
wDoc.Bookmarks("g4").Range.Text = Nz(rs!BriefQ, "")
wDoc.Bookmarks("g5").Range.Text = Nz(rs!BriefQmin, "")
wDoc.Bookmarks("g6").Range.Text = Nz(rs!BriefUnsat, "")
' and so on up to 60
wDoct.Save
wApp.Quit
</code>```

This works but needs to be looped of course - I tried this, but it errors out:

```<code>Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

intI = 1

With rs
Do Until .EOF
For Each fld in rs.Fields
wDoc.Bookmarks("g" & "intI").Range.Text = Nz(rs!fld.Name, "")

Next fld
intI = intI + 1
loop
End With

wDoct.save
Wapp.quit
</code>```

Any ideas will be very much welcome, otherwise I have a lot of typing ahead of me. :-)

Thank you for your time!

Peter

This is the current code that fail like mentioned below:
UPDATE This is the exact copy paste.

```<code>Public Sub Looptest()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim rs As DAO.Recordset
Dim index As Integer
Dim item As Variant

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

For Each item In rs.Fields
    index = index + 1

    Dim bookmarkName As String
    bookmarkName = "g" & index

    Dim bookmarkValue As Variant
    bookmarkValue = Nz(rs(item.Name).Value, "")

    Debug.Print "Try set bookmark '" & bookmarkName & "' to '" & bookmarkValue & "' now."

    Dim bookmarkRange As Word.Range
    Set bookmarkRange = wDoc.Bookmarks(bookmarkName).Range

    bookmarkRange.Text = bookmarkValue

    Set bookmarkRange = Nothing
    Next item

wApp.DisplayAlerts = False
wDoc.SaveAs2 "C:\Users\Peter\Documents\" & rs!ID & "_gradesheet.docm"
wDoc.Close
wApp.Quit
</code>```

答:
Your code tries to match numbered bookmarks to table fields, based only on their order. Even if you get it to work now, this will be very hard to maintain, every change will cause new troubles.

It is much easier to name the bookmarks identical to their matching table field names, i.e. PlanQ etc.

Then your code becomes simpler and maintainable.

And if a table field (e.g. ID) doesn't exist as bookmark in the document, you can simply ignore it.

```<code>For Each fld In rs.Fields

    Dim bookmarkName As String
    bookmarkName = fld.Name

    Dim bookmarkValue As String  ' since you are using Nz(), you don't need Variant
    bookmarkValue = Nz(fld.Value, "")

    If wDoc.Bookmarks.Exists(bookmarkName) Then
        wDoc.Bookmarks(bookmarkName).Range.Text = bookmarkValue
    Else
        Debug.Print "Ignored table field <" & bookmarkName & "> - no matching bookmark found in word document."
    End If

Next item
</code>```

Body:
Thanks for looking at this.

I have a recordset with 60 fields and I want to export the last record for each field into a Microsoft Word file with 60 bookmarks called g1 to g60.

Of course I would like to loop through these but can't make it work.

Essentially what I want is this:

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

wDoc.Bookmarks("g1").Range.Text = Nz(rs!PlanQ, "")
wDoc.Bookmarks("g2").Range.Text = Nz(rs!PlanQMin, "")
wDoc.Bookmarks("g3").Range.Text = Nz(rs!PlanUnsat, "")
wDoc.Bookmarks("g4").Range.Text = Nz(rs!BriefQ, "")
wDoc.Bookmarks("g5").Range.Text = Nz(rs!BriefQmin, "")
wDoc.Bookmarks("g6").Range.Text = Nz(rs!BriefUnsat, "")
' and so on up to 60
wDoct.Save
wApp.Quit

This works but needs to be looped of course - I tried this, but it errors out:

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

intI = 1

With rs
Do Until .EOF
For Each fld in rs.Fields
wDoc.Bookmarks("g" & "intI").Range.Text = Nz(rs!fld.Name, "")

Next fld
intI = intI + 1
loop
End With

wDoct.save
Wapp.quit

Any ideas will be very much welcome, otherwise I have a lot of typing ahead of me. :-)

Thank you for your time!

Peter

This is the current code that fail like mentioned below:
UPDATE This is the exact copy paste.

Public Sub Looptest()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim rs As DAO.Recordset
Dim index As Integer
Dim item As Variant

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

For Each item In rs.Fields
    index = index + 1

    Dim bookmarkName As String
    bookmarkName = "g" & index

    Dim bookmarkValue As Variant
    bookmarkValue = Nz(rs(item.Name).Value, "")

    Debug.Print "Try set bookmark '" & bookmarkName & "' to '" & bookmarkValue & "' now."

    Dim bookmarkRange As Word.Range
    Set bookmarkRange = wDoc.Bookmarks(bookmarkName).Range

    bookmarkRange.Text = bookmarkValue

    Set bookmarkRange = Nothing
    Next item

wApp.DisplayAlerts = False
wDoc.SaveAs2 "C:\Users\Peter\Documents\" & rs!ID & "_gradesheet.docm"
wDoc.Close
wApp.Quit

Body:
Your code tries to match numbered bookmarks to table fields, based only on their order. Even if you get it to work now, this will be very hard to maintain, every change will cause new troubles.

It is much easier to name the bookmarks identical to their matching table field names, i.e. PlanQ etc.

Then your code becomes simpler and maintainable.

And if a table field (e.g. ID) doesn't exist as bookmark in the document, you can simply ignore it.

For Each fld In rs.Fields

    Dim bookmarkName As String
    bookmarkName = fld.Name

    Dim bookmarkValue As String  ' since you are using Nz(), you don't need Variant
    bookmarkValue = Nz(fld.Value, "")

    If wDoc.Bookmarks.Exists(bookmarkName) Then
        wDoc.Bookmarks(bookmarkName).Range.Text = bookmarkValue
    Else
        Debug.Print "Ignored table field <" & bookmarkName & "> - no matching bookmark found in word document."
    End If

Next item


问:
Get id that starts with string using xpath
I am using python 3.7 and I want to print all divs with id's that start with "def". I don't undestand why my example code is not working:

```<code>import xml.etree.ElementTree as ET
html = '<div> <div id="abc 123"></div> <div id="def hhh"></div> <div id="ghi test"></div> </div>'
root = ET.fromstring(html)
print( root.findall("//div[starts-with(@id, 'def')]") )
</code>```

Result:

```<code>SyntaxError: cannot use absolute path on element
</code>```

I really don't undestand why this is not working. If that would work the next step would be to loop through it and get the id names using .get("id").

What am I doing wrong?

答:
There are 2 distinct issues here, both handled by other questions.

First:

```<code>import xml.etree.ElementTree as ET
html = '<div> <div id="abc 123"></div> <div id="def hhh"></div> <div id="ghi test"></div> </div>'
root = ET.fromstring(html)

try:
    print( root.findall("//div[starts-with(@id, 'def')]") )
except SyntaxError as e:
    print e
</code>```

See live: https://ideone.com/PfpjYz
Error is "cannot use absolute path on element" - this is handled by Python - ElementTree- cannot use absolute path on element

Second issue, when using relative elements, you get a different error:

```<code>import xml.etree.ElementTree as ET
html = '<div> <div id="abc 123"></div> <div id="def hhh"></div> <div id="ghi test"></div> </div>'
root = ET.fromstring(html)
try:
    print( root.findall(".//div[starts-with(@id, 'def')]") )
except SyntaxError as e:
    print e
</code>```

See live: https://ideone.com/BNc7My

Error has changed "invalid predicate" - see xpath-support - starts-with is not there

See: Python XPath SyntaxError: invalid predicate for possible solutions.

Finally, you can use a different xml library, or work around the limitations of this one.

```<code>import lxml.etree
root = lxml.etree.fromstring(html)

print root.xpath(".//div[starts-with(@id, 'def')]")[0].attrib
</code>```

See online: https://ideone.com/Ie1j8F

Note: this is still a duplicate question, and should be closed as such, but this is to long to fit into an comment.

Body:
I am using python 3.7 and I want to print all divs with id's that start with "def". I don't undestand why my example code is not working:

import xml.etree.ElementTree as ET
html = '

'
root = ET.fromstring(html)
print( root.findall("//div[starts-with(@id, 'def')]") )

Result:

SyntaxError: cannot use absolute path on element

I really don't undestand why this is not working. If that would work the next step would be to loop through it and get the id names using .get("id").

What am I doing wrong?

Body:
There are 2 distinct issues here, both handled by other questions.

First:

import xml.etree.ElementTree as ET
html = '<div> <div id="abc 123"></div> <div id="def hhh"></div> <div id="ghi test"></div> </div>'
root = ET.fromstring(html)

try:
    print( root.findall("//div[starts-with(@id, 'def')]") )
except SyntaxError as e:
    print e

See live: https://ideone.com/PfpjYz
Error is "cannot use absolute path on element" - this is handled by Python - ElementTree- cannot use absolute path on element

Second issue, when using relative elements, you get a different error:

import xml.etree.ElementTree as ET
html = '<div> <div id="abc 123"></div> <div id="def hhh"></div> <div id="ghi test"></div> </div>'
root = ET.fromstring(html)
try:
    print( root.findall(".//div[starts-with(@id, 'def')]") )
except SyntaxError as e:
    print e

See live: https://ideone.com/BNc7My

Error has changed "invalid predicate" - see xpath-support - starts-with is not there

See: Python XPath SyntaxError: invalid predicate for possible solutions.

Finally, you can use a different xml library, or work around the limitations of this one.

import lxml.etree
root = lxml.etree.fromstring(html)

print root.xpath(".//div[starts-with(@id, 'def')]")[0].attrib

See online: https://ideone.com/Ie1j8F

Note: this is still a duplicate question, and should be closed as such, but this is to long to fit into an comment.


问:
Why Precaching with fixed urls in manifest?
I was reading about precaching with service workers and i ended up with this precaching.

I cant understand why it uses fixed urls with hashes. They must be created dynamically every time a file changes.

So whats the point of putting them manually and setting revision to null?

答:
If you are talking about the way Workbox tags the file hash value to the URL then I can answer this one.

The hash is a calculation of the file contents. Which stays the same until you change anything in the file. Then the file has a different hash. So Workbox generates a manifest each time you run the script to generate the service worker.

Then when the service worker is installed it will only fetch updates for network assets that have been updated. It can also do a hash check to verify the file is what is expects.

Another way I have been accomplishing this without a manifest file and a build step to maintain is to make HEAD requests to the network assets. The server should return a last updated header value you can check against a value in the cache of when the file was created.

I have not quite perfected this technique, but when I get it stable I will probably create an article about the method.

But the ultimate goal is to eliminate as many round trips as possible and reduce the data burden on the server and the client.


问:
Retrieving different aggregated fields with mongoose
I am trying to wrap my head around the query which I am trying to make with mongoose on Node JS. Here is my dataset:

```<code>{"_id":{"$oid":"5e49c389e3c23a1da881c1c9"},"name":"New York","good_incidents":{"$numberInt":"50"},"salary":{"$numberInt":"50000"},"bad_incidents":"30"}
{"_id":{"$oid":"5e49c3bbe3c23a1da881c1ca"},"name":"Cairo","bad_incidents":{"$numberInt":"59"},"salary":{"$numberInt":"15000"}}
{"_id":{"$oid":"5e49c42de3c23a1da881c1cb"},"name":"Berlin","incidents":{"$numberInt":"30"},"bad_incidents":"15","salary":{"$numberInt":"55000"}}
{"_id":{"$oid":"5e49c58ee3c23a1da881c1cc"},"name":"New York","good_incidents":{"$numberInt":"15"},"salary":{"$numberInt":"56500"}}
</code>```

What I am trying to do is get these values:

The most repeated city in collection

The average of bad_incidents

The maximum value of good_incidents

Maximum salary where there are no bad_incidents

I am trying to wrap my head around how I can do this in one query, because I only need one value per field. I would be glad if somebody would lead me on the right track. No need for full solution

Regards!

答:
You may perform MongoDB aggregation with $facet operator which allows compute several aggregation at once.

```<code>db.collection.aggregate([
  {
    $facet: {
      repeated_city: [
        {
          $group: {
            _id: "$name",
            name: {
              $first: "$name"
            },
            count: {
              $sum: 1
            }
          }
        },
        {
          $match: {
            count: {
              $gt: 1
            }
          }
        },
        {
          $sort: {
            count: -1
          }
        },
        {
          $limit: 1
        }
      ],
      bad_incidents: [
        {
          $group: {
            _id: null,
            avg_bad_incidents: {
              $avg: {
                $toInt: "$bad_incidents"
              }
            }
          }
        }
      ],
      good_incidents: [
        {
          $group: {
            _id: null,
            max_good_incidents: {
              $max: {
                $toInt: "$good_incidents"
              }
            }
          }
        }
      ],
      max_salary: [
        {
          $match: {
            bad_incidents: {
              $exists: false
            }
          }
        },
        {
          $group: {
            _id: null,
            max_salary: {
              $max: {
                $toInt: "$salary"
              }
            }
          }
        }
      ]
    }
  },
  {
    $replaceWith: {
      $mergeObjects: [
        {
          $arrayElemAt: [
            "$repeated_city",
            0
          ]
        },
        {
          $arrayElemAt: [
            "$bad_incidents",
            0
          ]
        },
        {
          $arrayElemAt: [
            "$good_incidents",
            0
          ]
        },
        {
          $arrayElemAt: [
            "$max_salary",
            0
          ]
        }
      ]
    }
  }
])
</code>```

MongoPlayground

```<code>[
  {
    "_id": null,
    "avg_bad_incidents": 34.666666666666664,
    "count": 2,
    "max_good_incidents": 50,
    "max_salary": 56500,
    "name": "New York"
  }
]
</code>```

Body:
I am trying to wrap my head around the query which I am trying to make with mongoose on Node JS. Here is my dataset:

{"_id":{"$oid":"5e49c389e3c23a1da881c1c9"},"name":"New York","good_incidents":{"$numberInt":"50"},"salary":{"$numberInt":"50000"},"bad_incidents":"30"}
{"_id":{"$oid":"5e49c3bbe3c23a1da881c1ca"},"name":"Cairo","bad_incidents":{"$numberInt":"59"},"salary":{"$numberInt":"15000"}}
{"_id":{"$oid":"5e49c42de3c23a1da881c1cb"},"name":"Berlin","incidents":{"$numberInt":"30"},"bad_incidents":"15","salary":{"$numberInt":"55000"}}
{"_id":{"$oid":"5e49c58ee3c23a1da881c1cc"},"name":"New York","good_incidents":{"$numberInt":"15"},"salary":{"$numberInt":"56500"}}

What I am trying to do is get these values:

The most repeated city in collection

The average of bad_incidents

The maximum value of good_incidents

Maximum salary where there are no bad_incidents

I am trying to wrap my head around how I can do this in one query, because I only need one value per field. I would be glad if somebody would lead me on the right track. No need for full solution

Regards!

Body:
You may perform MongoDB aggregation with $facet operator which allows compute several aggregation at once.

db.collection.aggregate([
  {
    $facet: {
      repeated_city: [
        {
          $group: {
            _id: "$name",
            name: {
              $first: "$name"
            },
            count: {
              $sum: 1
            }
          }
        },
        {
          $match: {
            count: {
              $gt: 1
            }
          }
        },
        {
          $sort: {
            count: -1
          }
        },
        {
          $limit: 1
        }
      ],
      bad_incidents: [
        {
          $group: {
            _id: null,
            avg_bad_incidents: {
              $avg: {
                $toInt: "$bad_incidents"
              }
            }
          }
        }
      ],
      good_incidents: [
        {
          $group: {
            _id: null,
            max_good_incidents: {
              $max: {
                $toInt: "$good_incidents"
              }
            }
          }
        }
      ],
      max_salary: [
        {
          $match: {
            bad_incidents: {
              $exists: false
            }
          }
        },
        {
          $group: {
            _id: null,
            max_salary: {
              $max: {
                $toInt: "$salary"
              }
            }
          }
        }
      ]
    }
  },
  {
    $replaceWith: {
      $mergeObjects: [
        {
          $arrayElemAt: [
            "$repeated_city",
            0
          ]
        },
        {
          $arrayElemAt: [
            "$bad_incidents",
            0
          ]
        },
        {
          $arrayElemAt: [
            "$good_incidents",
            0
          ]
        },
        {
          $arrayElemAt: [
            "$max_salary",
            0
          ]
        }
      ]
    }
  }
])

MongoPlayground

[
  {
    "_id": null,
    "avg_bad_incidents": 34.666666666666664,
    "count": 2,
    "max_good_incidents": 50,
    "max_salary": 56500,
    "name": "New York"
  }
]


问:
Imbed matplotlib figure into iPython HTML
I want to dynamically write and display HTML with a code cell in Jupyter Notebook.  The objective is to generate the HTML to display table, div, img tags in some way I choose.  I want to capture img data and place it where I want in this auto generated HTML.

So far I've figured out that I can do the following:

```<code>from IPython.core.display import HTML

HTML("<h1>Hello</h1>")
</code>```

and get:

Hello

That's great.  However, I want to be able to do this:

```<code>HTML("<h1>Hello</h1><hr/><img src='somestring'/>")
</code>```

and get something similar to a Hello with a horizontal line and an image below it, where the image is the same one as below.

```<code>import pandas as pd
import numpy as np

np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

df.plot.scatter(0, 1)
</code>```

The result should look like this:

Question

What do I replace 'something' with in order to implement this?  And more to the point, how do I get it via python?

I would have imagined there was an attribute on a figure object that would hold an serialized version of the image but I can't find it.

答:
I'm going to build on what was answered by others (piRSquared) because it didn't work for me with Jupyter and Python 3. I wrote the following function, which will take any plot function I define and call it, and capture the outputs without displaying them in Jupyter. I personally use this in to build custom HTML machine learning reports based on many model iterations I execute using Livy and Spark.

from IPython.core.display import HTML
import binascii
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import base64

def capturePlotHTML(plotFunction):
    # open IO object
    sio3 = BytesIO()
    plotFunction()
    plt.savefig(sio3)
    sio3.seek(0)
    data_uri = base64.b64encode(sio3.read()).decode('ascii')
    html_out = ''
    html_out += ''.format(data_uri)
    html_out += ''
    #prevents plot from showing in output
    plt.close()
    return (HTML(html_out))

# Plot Wrappers

# Advanced Wrapper for more complex visualizations (seaborn, etc)
class plotRegline:
    def __init__(self):
    #// could also pass in name as arg like this #def __init__(self, name):
        reg_line_prepped_pdf = pandas_input_pdf
        sns.lmplot(x='predicted',y='actual',data=reg_line_prepped_pdf,fit_reg=True, height=3, aspect=2).fig.suptitle("Regression Line")

# Basic Wrapper for simple matplotlib visualizations
def plotTsPred():
        ts_plot_prepped_pdf = pandas_input_pdf
        ts_plot_prepped_pdf.index = pd.to_datetime(ts_plot_prepped_pdf.DAYDATECOLUMN)
        ts_plot_prepped_pdf = ts_plot_prepped_pdf.drop(columns=["DAYDATECOLUMN"])
        ts_plot_prepped_pdf.plot(title="Predicted Vs Actual -- Timeseries Plot -- Days", figsize=(25,6))

#building the plots and capturing the outputs
regline_html = capturePlotHTML(plotRegline)
ts_plot_day_html = capturePlotHTML(plotTsPred)

# could be any list number of html objects
html_plots =  [regline_html, ts_plot_day_html]
combined_html_plots = display_html(*html_plots)
# the following can be run in this code block or another display the results
combined_html_plotes

```

Body:
I want to dynamically write and display HTML with a code cell in Jupyter Notebook.  The objective is to generate the HTML to display table, div, img tags in some way I choose.  I want to capture img data and place it where I want in this auto generated HTML.

So far I've figured out that I can do the following:

from IPython.core.display import HTML

HTML("
Hello
")

and get:

Hello

That's great.  However, I want to be able to do this:

HTML("
Hello

")

and get something similar to a Hello with a horizontal line and an image below it, where the image is the same one as below.

import pandas as pd
import numpy as np

np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

df.plot.scatter(0, 1)

The result should look like this:

Question

What do I replace 'something' with in order to implement this?  And more to the point, how do I get it via python?

I would have imagined there was an attribute on a figure object that would hold an serialized version of the image but I can't find it.

Body:
I'm going to build on what was answered by others (piRSquared) because it didn't work for me with Jupyter and Python 3. I wrote the following function, which will take any plot function I define and call it, and capture the outputs without displaying them in Jupyter. I personally use this in to build custom HTML machine learning reports based on many model iterations I execute using Livy and Spark.

from IPython.core.display import HTML
import binascii
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import base64

def capturePlotHTML(plotFunction):
    # open IO object
    sio3 = BytesIO()
    plotFunction()
    plt.savefig(sio3)
    sio3.seek(0)
    data_uri = base64.b64encode(sio3.read()).decode('ascii')
    html_out = '<html><head></head><body>'
    html_out += '<img src="data:image/png;base64,{0}" align="left">'.format(data_uri)
    html_out += '</body></html>'
    #prevents plot from showing in output
    plt.close()
    return (HTML(html_out))

# Plot Wrappers

# Advanced Wrapper for more complex visualizations (seaborn, etc)
class plotRegline:
    def __init__(self):
    #// could also pass in name as arg like this #def __init__(self, name):
        reg_line_prepped_pdf = pandas_input_pdf
        sns.lmplot(x='predicted',y='actual',data=reg_line_prepped_pdf,fit_reg=True, height=3, aspect=2).fig.suptitle("Regression Line")

# Basic Wrapper for simple matplotlib visualizations
def plotTsPred():
        ts_plot_prepped_pdf = pandas_input_pdf
        ts_plot_prepped_pdf.index = pd.to_datetime(ts_plot_prepped_pdf.DAYDATECOLUMN)
        ts_plot_prepped_pdf = ts_plot_prepped_pdf.drop(columns=["DAYDATECOLUMN"])
        ts_plot_prepped_pdf.plot(title="Predicted Vs Actual -- Timeseries Plot -- Days", figsize=(25,6))

#building the plots and capturing the outputs
regline_html = capturePlotHTML(plotRegline)
ts_plot_day_html = capturePlotHTML(plotTsPred)

# could be any list number of html objects
html_plots =  [regline_html, ts_plot_day_html]
combined_html_plots = display_html(*html_plots)
# the following can be run in this code block or another display the results
combined_html_plotes


问:
Countif date includes year, month or day
I have a column containing dates in a Google sheet. How can I count the number of dates that include a specific year, month or day?

I have tried the following: =COUNTIF(G:G, YEAR(2000)) which just returns a zero, although there are multiple dates in the year 2000 in that column.

All the best!

答:
year:

```<code>=INDEX(COUNTIF(YEAR(G:G), 2000))
</code>```

month:

```<code>=INDEX(COUNTIF(MONTH(G:G), 11))

=INDEX(COUNTIFS(MONTH(G:G), 12, G:G, "<>"))
</code>```

day:

```<code>=INDEX(COUNTIF(DAY(G:G), 27))
</code>```

weekday:

```<code>=INDEX(COUNTIF(WEEKDAY(G:G, 1), 7))
</code>```

Body:
year:

=INDEX(COUNTIF(YEAR(G:G), 2000))

month:

=INDEX(COUNTIF(MONTH(G:G), 11))

=INDEX(COUNTIFS(MONTH(G:G), 12, G:G, "<>"))

day:

=INDEX(COUNTIF(DAY(G:G), 27))

weekday:

=INDEX(COUNTIF(WEEKDAY(G:G, 1), 7))


问:
How does PokeCord do the green bar at the side?
I am trying to write a discord bot, and i  am curious on how to make the green bar that pokecord and some other bots have.

example

答:
This called embed.
In discord.py you can read about it in documentation.
In discord.js you can read about it and see some examples here.</p>


问:
Reverse Order of a Nested Dictionary Python
I have a two-layered dictionary and would like a simple command or function (if possible) to reverse the order of the dictionary, but only the outer layer, not the inner. For instance, if my dictionary were as follows:

```<code>{'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}
</code>```

and I wanted to instead make it the following:

```<code>{'dictC': {'key_3', 'value_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}
</code>```

How would I do this? I have tried methods like invertdict() and inv_map = {v: k for k, v in my_map.items()}, but I had no success with either.

Any help is appreciated!

答:
Reverse the items:</p>

```<code>>>> dict(reversed(d.items()))
{'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}
</code>```

Body:
I have a two-layered dictionary and would like a simple command or function (if possible) to reverse the order of the dictionary, but only the outer layer, not the inner. For instance, if my dictionary were as follows:

{'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

and I wanted to instead make it the following:

{'dictC': {'key_3', 'value_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

How would I do this? I have tried methods like invertdict() and inv_map = {v: k for k, v in my_map.items()}, but I had no success with either.

Any help is appreciated!

Body:
Reverse the items:

>>> dict(reversed(d.items()))
{'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}


答:
Following code would do the trick:

dict(reversed(current_dct.items()))

Title: Reverse Order of a Nested Dictionary Python


问:
Removing underline style of autocomplete in react material ui component
I want to remove the underline style and change the of the color of it when the text field gets focus in the autocomplete component of react material ui.

I can't seem to find the style to override.

Thanks in advance.

答:
Minor update to @Liem's response. Just putting the InputProps directly overwrites the InputProps it would use by default, which breaks the component. By merging the disableUnderline with the other InputProps, it should work.

```<code><Autocomplete
   renderInput={
     params =>
       <TextField
         {...params}
         InputProps={{...params.InputProps, disableUnderline: true}}
       />
   }
 />
</code>```

Body:
Minor update to @Liem's response. Just putting the InputProps directly overwrites the InputProps it would use by default, which breaks the component. By merging the disableUnderline with the other InputProps, it should work.

<Autocomplete
   renderInput={
     params =>
       <TextField
         {...params}
         InputProps={{...params.InputProps, disableUnderline: true}}
       />
   }
 />


问:
Rails - Entered Data Not Displaying
This is most likely a newbie question...
I'm currently working on my first rails project and have a couple issues to solve.

Here is the video as well as the Github link.

How do I display the entry once it’s entered on the page?
How do I get the list of entries to show up?

Currently it’s throwing the following error, but I’ve checked my spelling/pluralizations and don't see an issue.

```<code>undefined local variable or method `comicbook' for #<#<Class:0x00007fb1d23d3728>:0x00007fb1d23d18b0>
Did you mean?  comicbooks
---
        <th>Squad</th>
    </tr>
    <% render partial: 'comicbooks/comicbook', locals: {comicbook: comicbook }%>
</table>

</code>```

comicbooks_controller.rb

```<code>class ComicbooksController < ApplicationController
  def index
    @comicbooks = Comicbook.all
  end

  def create
    @comicbook = Comicbook.new(comicbook_params)
    if @comicbook.save
      redirect_to comicbooks_url
    else
      @errors = @comicbook.errors.full_messages
      render :new
    end
  end

  def new
    @comicbook = Comicbook.new
    @comicbook.person = Person.new
    @comicbook.squad = Squad.new
  end

  def edit
    unless @comicbook = Comicbook.find_by_id(params[:id])
      @error = ['Comicbook Not Found']
      redirect_to comicbooks_url
    end
  end

  def update
  end

  def comicbook_params
    params.require(:comicbook).permit(:title, :person_attributes => [:name], :squad_attributes => [:name])
  end
end
</code>```

答:
There is no variable created in your _all_comicbooks.html.erb view which is my assumption for this error.  You need to loop through the data to get this like in the index file.  So, in your index file, you have this line

```<code><% @comicbooks.each do |comicbook| %>
   <% render partial: 'comicbook', locals: {comicbook: comicbook }%>
<% end %>
</code>```

So there is a variable @comicbooks which is being looped through, and the individual variables for each item are being set to |comicbook|.  See how that works?

Without creating the loop and setting what the variable is you are just calling a variable that doesn't exist.

After looking it looks like you are sending a variable to the partial called comicbooks which is all the persons, or squads, comicbooks, so loop through that and create the comicbook variable.

So my guess is you want this in the _all_comicbooks.html.erb view

```<code><table>
  <tr>
    <th>Comicbook</th>
    <th>Hero</th>
    <th>Squad</th>
  </tr>
  <% comicbooks.each do |comicbook| %>
    <%= render partial: 'comicbooks/comicbook', locals: {comicbook: comicbook }%>
  <% end %>
</table>
</code>```

Title: Rails - Entered Data Not Displaying

Body:
This is most likely a newbie question...
I'm currently working on my first rails project and have a couple issues to solve.

Here is the video as well as the Github link.

How do I display the entry once it’s entered on the page?
How do I get the list of entries to show up?

Currently it’s throwing the following error, but I’ve checked my spelling/pluralizations and don't see an issue.

undefined local variable or method `comicbook' for #<#<Class:0x00007fb1d23d3728>:0x00007fb1d23d18b0>
Did you mean?  comicbooks
---
        Squad

    <% render partial: 'comicbooks/comicbook', locals: {comicbook: comicbook }%>

comicbooks_controller.rb

class ComicbooksController < ApplicationController
  def index
    @comicbooks = Comicbook.all
  end

  def create
    @comicbook = Comicbook.new(comicbook_params)
    if @comicbook.save
      redirect_to comicbooks_url
    else
      @errors = @comicbook.errors.full_messages
      render :new
    end
  end

  def new
    @comicbook = Comicbook.new
    @comicbook.person = Person.new
    @comicbook.squad = Squad.new
  end

  def edit
    unless @comicbook = Comicbook.find_by_id(params[:id])
      @error = ['Comicbook Not Found']
      redirect_to comicbooks_url
    end
  end

  def update
  end

  def comicbook_params
    params.require(:comicbook).permit(:title, :person_attributes => [:name], :squad_attributes => [:name])
  end
end

Body:
There is no variable created in your _all_comicbooks.html.erb view which is my assumption for this error.  You need to loop through the data to get this like in the index file.  So, in your index file, you have this line

<% @comicbooks.each do |comicbook| %>
   <% render partial: 'comicbook', locals: {comicbook: comicbook }%>
<% end %>

So there is a variable @comicbooks which is being looped through, and the individual variables for each item are being set to |comicbook|.  See how that works?

Without creating the loop and setting what the variable is you are just calling a variable that doesn't exist.

After looking it looks like you are sending a variable to the partial called comicbooks which is all the persons, or squads, comicbooks, so loop through that and create the comicbook variable.

So my guess is you want this in the _all_comicbooks.html.erb view

<table>
  <tr>
    <th>Comicbook</th>
    <th>Hero</th>
    <th>Squad</th>
  </tr>
  <% comicbooks.each do |comicbook| %>
    <%= render partial: 'comicbooks/comicbook', locals: {comicbook: comicbook }%>
  <% end %>
</table>


问:
Safe to std:move a member?
Have found comparable questions but not exactly with such a case.
Take the following code for example:

```<code>#include <iostream>
#include <string>
#include <vector>

struct Inner
{
    int a, b;
};

struct Outer
{
    Inner inner;
};

std::vector<Inner> vec;

int main()
{
    Outer * an_outer = new Outer;

    vec.push_back(std::move(an_outer->inner));

    delete an_outer;
}
</code>```

Is this safe? Even if those were polymorphic classes or ones with custom destructors?

My concern regards the instance of "Outer" which has a member variable "inner" moved away. From what I learned, moved things should not be touched anymore. However does that include the delete call that is applied to outer and would technically call delete on inner as well (and thus "touch" it)?

答:
Neither std::move, nor move semantics more generally, have any effect on the object model. They don't stop objects from existing, nor prevent you from using those objects in the future.

What they do is ask to borrow encapsulated resources from the thing you're "moving from". For example, a vector, which directly only stores a pointer some dynamically-allocated data: the concept of ownership of that data can be "stolen" by simply copying that pointer then telling the vector to null the pointer and never have anything to do with that data again. It's yielded. The data belongs to you now. You have the last pointer to it that exists in the universe.

All of this is achieved simply by a bunch of hacks. The first is std::move, which just casts your vector expression to vector&&, so when you pass the result of it to a construction or assignment operation, the version that takes vector&& (the move constructor, or move-assignment operator) is triggered instead of the one that takes const vector&, and that version performs the steps necessary to do what I described in the previous paragraph.

(For other types that we make, we traditionally keep following that pattern, because that's how we can have nice things and persuade people to use our libraries.)

But then you can still use the vector! You can "touch" it. What exactly you can do with it is discoverable from the documentation for vector, and this extends to any other moveable type: the constraints emplaced on your usage of a moved-from object depend entirely on its type, and on the decisions made by the person who designed that type.

None of this has any impact on the lifetime of the vector. It still exists, it still takes memory, and it will still be destructed when the time comes. (In this particular example you can actually .clear() it and start again adding data to a new buffer.)

So, even if ints had any sort of concept of this (they don't; they encapsulate no indirectly-stored data, and own no resources; they have no constructors, so they also have no constructors taking int&&), the delete "touch"ing them would be entirely safe. And, more generally, none of this depends on whether the thing you've moved from is a member or not.

More generally, if you had a type T, and an object of that type, and you moved from it, and one of the constraints for T was that you couldn't delete it after moving from it, that would be a bug in T. That would be a serious mistake by the author of T. Your objects all need to be destructible. The mistake could manifest as a compilation failure or, more likely, undefined behaviour, depending on what exactly the bug was.

tl;dr: Yes, this is safe, for several reasons.

Title: Safe to std:move a member?

Body:
Have found comparable questions but not exactly with such a case.
Take the following code for example:

#include <iostream>
#include <string>
#include <vector>

struct Inner
{
    int a, b;
};

struct Outer
{
    Inner inner;
};

std::vector<Inner> vec;

int main()
{
    Outer * an_outer = new Outer;

    vec.push_back(std::move(an_outer->inner));

    delete an_outer;
}

Is this safe? Even if those were polymorphic classes or ones with custom destructors?

My concern regards the instance of "Outer" which has a member variable "inner" moved away. From what I learned, moved things should not be touched anymore. However does that include the delete call that is applied to outer and would technically call delete on inner as well (and thus "touch" it)?


问:
Specifying an email address and non-default folder name if I have more than one email address in Outlook
The following code is working, but I have a few questions.

I have more than one email address in Outlook. I would like to specify the email address in Excel. Let's say in "Control" tab, cell "b1" is an email address. How can I specify it?

I want to specify a non-default folder name (not Inbox, Sent, Drafts or Delete) by name in Excel. Let’s say in the "Control" tab, cell "c1" is a folder name. How can I specify it?

Sub GetFromInbox()

    Dim olApp As Outlook.Application
    Dim olNs As Namespace
    Dim Fldr As MAPIFolder
    Dim olMail As Variant
    Dim i, ij As Integer
    Dim tt As Date

    Set olApp = New Outlook.Application
    Set olNs = olApp.GetNamespace("MAPI")
    Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
    i = 1
    ij = 0
    x = Date

    ' Now. the following "For each next " code starts to look in the oldest email!
    ' So how can I change the code if the code starts from the newest?
    For Each olMail In Fldr.Items
        ij = ij + 1
        'If IsNumeric((Format(olMail.ReceivedTime, "dd/mm/yy"))) Then
            Sheets("test").Range("a1").Select
            Sheets("test").Range("I1").Clear
            Sheets("test").Range("I2") = ij
            Sheets("test").Range("I1").Value = (Format(olMail.ReceivedTime, "dd/mm/yy"))
            Sheets("test").Range("I1").NumberFormat = "dd/mm/yy"
            tt = Sheets("test").Range("I1")
            ' MsgBox ("Y-tt=" & tt & " receivedtime=" & olMail.ReceivedTime)
        'Else
            'tt = 0
            'MsgBox ("N-tt=" & tt & " receivedtime=" & olMail.ReceivedTime)
        'End If
        ' tt = CDate(Format(olMail.ReceivedTime, "dd/mm/yy"))
        If tt >= Range("H1") Then
            'If InStr(olMail.Subject, "others") > 0 And tt >= Range("h1") Then
            If InStr(olMail.Subject, "others") > 0 Then
                ActiveSheet.Range("h2") = "y"
                ActiveSheet.Cells(i, 1).Value = olMail.Subject
                ActiveSheet.Cells(i, 2).Value = olMail.ReceivedTime
                ActiveSheet.Cells(i, 3).Value = olMail.SenderName
                tt = CDate(Format(olMail.ReceivedTime, "dd/mm/yy"))
                ActiveSheet.Cells(i, 4).Value = CDate(Format(olMail.ReceivedTime, "dd/mm/yy"))
                ' tt = ActiveSheet.Cells(i, 4).Value
                ActiveSheet.Cells(i, 5).Value = (Format(olMail.ReceivedTime, "hh:mm"))
                MsgBox ("tt=" & tt)
                i = i + 1
            End If
        Else
            Sheets("test").Range("h2") = "N"
        End If
    Next olMail

    Set Fldr = Nothing
    Set olNs = Nothing
    Set olApp = Nothing
    'tt = ""

End Sub
```

答:
This describes how to walk from folder to folder.

https://stackoverflow.com/a/35657225/1571407

Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration

Sub GetFromAdditionalInbox()

    ' Early binding. Set reference to Microsoft Outlook XX.X Object Library
    Dim olApp As Outlook.Application
    Dim olNs As Namespace
    Dim Fldr As Outlook.folder

    Set olApp = New Outlook.Application
    Set olNs = olApp.GetNamespace("MAPI")

    ' Where folders are in the navigation pane
    '
    ' In "Main" tab
    '  - cell (A2) is email address.
    '  - cell (B2) is "Inbox"
    '  - cell (C2) is "subfolder directly under Inbox"
    '  - cell (D2) is "subsubfolder directly under subfolder"
    '
    With ThisWorkbook.Worksheets("Main")

        ' https://stackoverflow.com/questions/9076634/get-reference-to-additional-inbox
        Set Fldr = olNs.Folders(.Range("A2").Value)
        Set Fldr = Fldr.Folders(.Range("B2").Value)
        'Set Fldr = Fldr.Folders(.Range("C2").Value)
        'Set Fldr = Fldr.Folders(.Range("D2").Value)

        ' If the tree goes much further, investigate GetFolder
        '  https://stackoverflow.com/questions/17049546/get-mapi-folder-in-outlook-from-folder-path

    End With

    Debug.Print Fldr

End Sub
```


问:
How does the called function interprets the address of an array when using called by reference?
In the example, adapted from a book, I want to fully understand how passing and array by reference really works. From playing with the below code in Code Blocks and some reading here and there, I get that passing by value doesn't change the initial variable's value ( the example_pass_by_value). As for the other two variables whose adresses are passed by reference to the change function, I only understood the  example_pass_by_reference case like this : when calling the function like this "change (&example_pass_by_reference), you actually put and "=" sign between the formal parameter "by_reference" ( this being declared as pointer in the change function definition) and the address of "example_pass_by_reference" variable whic is passed to the change function ( ex: by_reference = 0x6644fe, or better by_reference = &example_pass_by_reference); The thing i don't understand is how the "=" is put between the address of array in the calling of function "change(array, ....) and the formal parameter "int arr[]" from definition of the function "change(int arr[], ...)", since int arr[] is an array, not a pointer, to be able to receive the address of variable "array".( like int arr[] = array, or int arr[] = 0x7856ff, for example);
Thank you in advance and sorry for the subsequent errors in my code or language.</p>

```<code>#include <stdio.h>
#include <string.h>

main()
{
    int array[3] = {1,2,3};
    int example_pass_by_value = 5;
    int example_pass_by_reference = 6;

    change(array, example_pass_by_value, &example_pass_by_reference);

    printf("Back in main(), the array[1] is now %d.\n", array[1]);
    printf("Back in main(), the example_pass_by_value is now %d.\n, unchanged", example_pass_by_value);
    printf("Back in main(), the example_pass_by_reference is now %d.\n", example_pass_by_reference);
    return(0);
}

/******************************************************************/

change(int arr[], int by_value, int *by_reference)
{
    // Changes made to all three variables;
      arr[1] = 10;
      by_value = 100;
      *by_reference = 1000;
      return;
}
</code>```

答:
For starters a typical mistake of whose who do not know C is the statement like that

C does not pass anything by reference, it doesn't have references

C does not have references in the sense as C++ has but it has a mechanism of passing by reference.

You shall not mix the terminology and notions of different languages and shall use the terminology defined in the concrete language.

In C pointers play the role of references. From the C Standard

— A pointer type may be derived from a function type or an object
  type, called the referenced type. A pointer type describes an object
  whose value provides a reference to an entity of the referenced
  type. A pointer type derived from the referenced type T is sometimes
  called ‘‘pointer to T’’. The construction of a pointer type from a
  referenced type is called ‘‘pointer type derivation’’. A pointer type
  is a complete object type.

So to pass by reference in C means passing an object through a pointer to the object.

As for your question then arrays used in expressions (with rare exceptions as for example using in the sizeof operator) are implicitly converted to pointers to their first elements.

You can imagine the following function call

```<code>void f( int a[] );

//...
int a[] = { 1, 2, 3, 4, 6 };

f( a );
</code>```

like

```<code>void f( int a[] );

//...
int a[] = { 1, 2, 3, 4, 6 };

int *tmp = a;
f( tmp );
</code>```

or that is the same

```<code>void f( int a[] );

//...
int a[] = { 1, 2, 3, 4, 6 };

int *tmp = &a[0];
f( tmp );
</code>```

On the other hand, a function parameter having an array type is implicitly adjusted by the compiler to pointer to the type of element of the array.

So for example these two function declarations are equivalent and declare the same one function

```<code>void f( int a[] );
void f( int *a );
</code>```

So passing an array to a function you are passing  pointer to its first element. It means that in fact all elements of the array are passed by reference. Using the pointer arithmetic you can change any element of the array pointed to by the pointer.

For example this statement

```<code>arr[1] = 10;
</code>```

is evaluated by the compiler like

```<code>*( arr + 1 ) = 10;
</code>```

where arr is a pointer to the first element of an array.

Body:
In the example, adapted from a book, I want to fully understand how passing and array by reference really works. From playing with the below code in Code Blocks and some reading here and there, I get that passing by value doesn't change the initial variable's value ( the example_pass_by_value). As for the other two variables whose adresses are passed by reference to the change function, I only understood the  example_pass_by_reference case like this : when calling the function like this "change (&example_pass_by_reference), you actually put and "=" sign between the formal parameter "by_reference" ( this being declared as pointer in the change function definition) and the address of "example_pass_by_reference" variable whic is passed to the change function ( ex: by_reference = 0x6644fe, or better by_reference = &example_pass_by_reference); The thing i don't understand is how the "=" is put between the address of array in the calling of function "change(array, ....) and the formal parameter "int arr[]" from definition of the function "change(int arr[], ...)", since int arr[] is an array, not a pointer, to be able to receive the address of variable "array".( like int arr[] = array, or int arr[] = 0x7856ff, for example);
Thank you in advance and sorry for the subsequent errors in my code or language.

#include <stdio.h>
#include <string.h>

main()
{
    int array[3] = {1,2,3};
    int example_pass_by_value = 5;
    int example_pass_by_reference = 6;

    change(array, example_pass_by_value, &example_pass_by_reference);

    printf("Back in main(), the array[1] is now %d.\n", array[1]);
    printf("Back in main(), the example_pass_by_value is now %d.\n, unchanged", example_pass_by_value);
    printf("Back in main(), the example_pass_by_reference is now %d.\n", example_pass_by_reference);
    return(0);
}

/******************************************************************/

change(int arr[], int by_value, int *by_reference)
{
    // Changes made to all three variables;
      arr[1] = 10;
      by_value = 100;
      *by_reference = 1000;
      return;
}

Body:
For starters a typical mistake of whose who do not know C is the statement like that

C does not pass anything by reference, it doesn't have references

C does not have references in the sense as C++ has but it has a mechanism of passing by reference.

You shall not mix the terminology and notions of different languages and shall use the terminology defined in the concrete language.

In C pointers play the role of references. From the C Standard

— A pointer type may be derived from a function type or an object
  type, called the referenced type. A pointer type describes an object
  whose value provides a reference to an entity of the referenced
  type. A pointer type derived from the referenced type T is sometimes
  called ‘‘pointer to T’’. The construction of a pointer type from a
  referenced type is called ‘‘pointer type derivation’’. A pointer type
  is a complete object type.

So to pass by reference in C means passing an object through a pointer to the object.

As for your question then arrays used in expressions (with rare exceptions as for example using in the sizeof operator) are implicitly converted to pointers to their first elements.

You can imagine the following function call

void f( int a[] );

//...
int a[] = { 1, 2, 3, 4, 6 };

f( a );

like

void f( int a[] );

//...
int a[] = { 1, 2, 3, 4, 6 };

int *tmp = a;
f( tmp );

or that is the same

void f( int a[] );

//...
int a[] = { 1, 2, 3, 4, 6 };

int *tmp = &a[0];
f( tmp );

On the other hand, a function parameter having an array type is implicitly adjusted by the compiler to pointer to the type of element of the array.

So for example these two function declarations are equivalent and declare the same one function

void f( int a[] );
void f( int *a );

So passing an array to a function you are passing  pointer to its first element. It means that in fact all elements of the array are passed by reference. Using the pointer arithmetic you can change any element of the array pointed to by the pointer.

For example this statement

arr[1] = 10;

is evaluated by the compiler like

*( arr + 1 ) = 10;

where arr is a pointer to the first element of an array.


答:
If your using Python 3.6 or lower, dictionary order is not maintained or guaranteed. What you could do is use a collections.OrderedDict() and apply reversed() to reverse the dictionary:

```<code>>>> from collections import OrderedDict
>>> d = {'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}
>>> OrderedDict(reversed(list(d.items())))
OrderedDict([('dictC', {'value_3', 'key_3'}), ('dictB', {'key_2': 'value_2'}), ('dictA', {'key_1': 'value_1'})])
</code>```

OrderedDict() is a subclass of dict, so it works like a normal dictionary.

However, if you are using a newer version of Python, then dictionary insertion order is maintained. So you could just do the following:

```<code>>>> dict(reversed(list(d.items())))
{'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}
</code>```

Note: For safety reasons, its probably better to cast list() to d.items, since older versions pre Python 3.8 don't allow reversing of type dict_items. You will raise a TypeError: 'dict_items' is not reversible error otherwise.

Body:
If your using Python 3.6 or lower, dictionary order is not maintained or guaranteed. What you could do is use a collections.OrderedDict() and apply reversed() to reverse the dictionary:

>>> from collections import OrderedDict
>>> d = {'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}
>>> OrderedDict(reversed(list(d.items())))
OrderedDict([('dictC', {'value_3', 'key_3'}), ('dictB', {'key_2': 'value_2'}), ('dictA', {'key_1': 'value_1'})])

OrderedDict() is a subclass of dict, so it works like a normal dictionary.

However, if you are using a newer version of Python, then dictionary insertion order is maintained. So you could just do the following:

>>> dict(reversed(list(d.items())))
{'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

Note: For safety reasons, its probably better to cast list() to d.items, since older versions pre Python 3.8 don't allow reversing of type dict_items. You will raise a TypeError: 'dict_items' is not reversible error otherwise.


问:
Akka Typed Actors and AKka Http - cannot find ActorRefFactory
I am trying to work with typed actors version 2.6.3 and akka http version 10.1.11
while all worked fine in non typed actors , now I am getting compilation error

```<code>object Main extends App {

   def createServer(implicit system: ActorSystem[IdentityCalculated]) = {

implicit val materializer = ActorMaterializer()

 }
 def apply(): Behavior[IdentityCalculated] = {
Behaviors.setup { context =>

  val identityManager = context.spawn(IdentityManager(), "identity-manager")

  implicit val timeout = Timeout(10, TimeUnit.SECONDS)
  implicit val scheduler = context.system.scheduler

  identityManager.tell(CalculateIdentity(context.self))

  Behaviors.receiveMessage{
    case IdentityCalculated(_,_,_) =>
      println("got response")
      Behaviors.same
  }
}

}
ActorSystem(Main(), "credentials-manager")

}
</code>```

what am I missing?
I want to create http server when I get the message that the identity was calculated how ever i am getting compilation error in the materializer
creation

Main.scala:19:50: implicit ActorRefFactory required: if outside of an Actor you need an implicit ActorSystem, inside of an actor this should be the implicit ActorContext
  [error]     implicit val materializer = ActorMaterializer()
  [error]                                                  ^
  [error] one error found

thanks

答:
You can use classic streams (which are typed, despite running on an untyped ActorSystem) by replacing:

```<code>implicit val materializer = ActorMaterializer()
</code>```

with

```<code>implicit val materializer = system.classicSystem
</code>```

Body:
I am trying to work with typed actors version 2.6.3 and akka http version 10.1.11
while all worked fine in non typed actors , now I am getting compilation error

object Main extends App {

   def createServer(implicit system: ActorSystem[IdentityCalculated]) = {

implicit val materializer = ActorMaterializer()

 }
 def apply(): Behavior[IdentityCalculated] = {
Behaviors.setup { context =>

  val identityManager = context.spawn(IdentityManager(), "identity-manager")

  implicit val timeout = Timeout(10, TimeUnit.SECONDS)
  implicit val scheduler = context.system.scheduler

  identityManager.tell(CalculateIdentity(context.self))

  Behaviors.receiveMessage{
    case IdentityCalculated(_,_,_) =>
      println("got response")
      Behaviors.same
  }
}

}
ActorSystem(Main(), "credentials-manager")

}

what am I missing?
I want to create http server when I get the message that the identity was calculated how ever i am getting compilation error in the materializer
creation

Main.scala:19:50: implicit ActorRefFactory required: if outside of an Actor you need an implicit ActorSystem, inside of an actor this should be the implicit ActorContext
  [error]     implicit val materializer = ActorMaterializer()
  [error]                                                  ^
  [error] one error found

thanks

Body:
You can use classic streams (which are typed, despite running on an untyped ActorSystem) by replacing:

implicit val materializer = ActorMaterializer()

with

implicit val materializer = system.classicSystem


问:
Python WEBDRIVER - I can't select an element from a listbox and submit my answer
I would like to select an element from a listbox and then submit my answer so that my browser opens a new page with the elements i chose. I was able to select the argument but when I press the button "Search", it doesnt take into account my selections. Here are the html of the listbox :

```<code><select size="10" name="lbSources" id="lbSources" class="form" onkeypress="return OnKeyPressEnterSubmit('btnSearch', event);" style="width:250px;">
    <option value="UK_P">01 net</option>
    <option value="UKA_P">01 net - Hors-série</option>
    <option value="QAA_P">2 Rives, Les (Sorel-Tracy, QC)</option>
    <option value="WV_P">24 Heures (Suisse)</option>
    <option value="FJ_P">Abitibi Express Rouyn-Noranda/Abitibi-Ouest</option>
   (...)
</code>```

and the html of the search button :

```<code> <input type="image" name="btnSearch" id="btnSearch" src="/images/interface/buttons/SearchFR_on.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSearch", "", true, "", "", false, false))">
</code>```

And here is how my Python code looks like:

```<code>selectBox = browser.find_element_by_name("lbSources")
selectBox.send_keys("UK_P")
browser.find_element_by_name("btnSearch").click()
</code>```

So it first selects a box but then... Nothing..

答:
Use Select class to click from dropdown:</p>

```<code>select = Select(driver.find_element_by_id('lbSources'))

# select by visible text
select.select_by_visible_text('UK_P')

# select by value
select.select_by_value('1')
</code>```

Body:
I would like to select an element from a listbox and then submit my answer so that my browser opens a new page with the elements i chose. I was able to select the argument but when I press the button "Search", it doesnt take into account my selections. Here are the html of the listbox :

<select size="10" name="lbSources" id="lbSources" class="form" onkeypress="return OnKeyPressEnterSubmit('btnSearch', event);" style="width:250px;">
    <option value="UK_P">01 net</option>
    <option value="UKA_P">01 net - Hors-série</option>
    <option value="QAA_P">2 Rives, Les (Sorel-Tracy, QC)</option>
    <option value="WV_P">24 Heures (Suisse)</option>
    <option value="FJ_P">Abitibi Express Rouyn-Noranda/Abitibi-Ouest</option>
   (...)

and the html of the search button :

 <input type="image" name="btnSearch" id="btnSearch" src="/images/interface/buttons/SearchFR_on.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSearch", "", true, "", "", false, false))">

And here is how my Python code looks like:

selectBox = browser.find_element_by_name("lbSources")
selectBox.send_keys("UK_P")
browser.find_element_by_name("btnSearch").click()

So it first selects a box but then... Nothing..

Body:
Use Select class to click from dropdown:

select = Select(driver.find_element_by_id('lbSources'))

# select by visible text
select.select_by_visible_text('UK_P')

# select by value
select.select_by_value('1')


问:
Using cropper with ng-file-upload
I'm using ng-file-upload to preview and upload an image. Before I upload the image I'd like to have the user crop the image. I tried using ng-img-crop, but that didn't have the features I wanted (aspect ratio customization), but cropper did (https://github.com/fengyuanchen/cropper/). My only problem now is how can I crop a preview of an image using cropper. The image src ends up being a blob ie "blob:XYZ". Has anyone successfully used cropper in this way? Is it possible?</p>

答:
Save the blob you get from this.cropper.getCroppedCanvas().toBlob() by attaching it to the state.

Pass the saved blob to the File constructor within the save() function by pushing it to the first parameter fileBits

Handle the upload on the backend with a help of multer

Component

import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { default as Cropper } from 'cropperjs';
import { FileItem, FileUploader } from 'ng2-file-upload';
import { UserService } from '../services/user.service';
import { User } from '../models/core';

@Component({
  selector: 'app-image-cropper',
  templateUrl: './image-cropper.component.html',
  styleUrls: ['./image-cropper.component.scss']
})
export class ImageCropperComponent implements OnInit, AfterViewInit, OnDestroy {

  @ViewChild('imageElement', {static: false})
  public imageElement: ElementRef;

  @Input()
  public imageSource: string;

  public imageBlob: Blob;
  public uploader: FileUploader;
  private cropper: Cropper;

  public constructor(private userService: UserService) {}

  public ngAfterViewInit() {
    this.cropper = new Cropper(this.imageElement.nativeElement, {
      zoomable: false,
      scalable: false,
      responsive: true,
      autoCropArea: 1,
      aspectRatio: 1,
      viewMode: 1,
      crop: (event) => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          this.imageBlob = blob;
          console.log('Crop saved as a Blob');
        });
      }
    });
  }

  public save() {
    const date: number = new Date().getTime();
    // Put the blob into the fileBits array of the File constructor
    const file = new File([this.imageBlob], 'photo', {type: 'image/png', lastModified: date});
    const fileItem = new FileItem(this.uploader, file, {});
    this.uploader.queue.push(fileItem);
    fileItem.upload();
  }

  ngOnInit() {
    this.userService.user$.subscribe((user: User) => {
      this.uploader = new FileUploader({url: '/api/profile/' + user.username + '/avatar', itemAlias: 'photo'});
      this.uploader.onAfterAddingFile = (file) => {
        file.withCredentials = false;
      };
      this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
        console.log(response);
      };
    });
  }

  ngOnDestroy(): void {
    this.imageBlob = undefined;
    this.imageSource = '';
  }

}

```
<h2>Component template</h2>
<pre class="lang-html prettyprint-override"><code><div class="modal-content">
  <div class="modal-header">
    <p class="modal-title font-weight-bold" id="crop-modal-title"><i></i>Crop</p>
    <button type="button" class="close" data-dismiss="modal"
            (click)="activeModal.close('Close click')">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">

    <div class="img-container">
      <img #imageElement [src]="imageSource" crossorigin>
    </div>
    <button type="button" class="button button-primary"
            (click)="save()">
    </button>
  </div>
</div>

</code>```

Node Controller

import { Request, Response, Router } from 'express';
import * as util from 'util';
import * as fs from 'fs';
import * as multer from 'multer';

Router.post('/profile/:username/avatar/', upload.single('photo'), async (req: Request, resp: Response) => {
    try {
        console.log(req.file);
        // Do something with the uploaded file here
        const fsUnlinkPromisified = (util as any).promisify(fs.unlink);
        await fsUnlinkPromisified(req.file.path);
    } catch (error) {
        console.log(error);
        return resp.send({
            msg: 'Upload failed',
            status: 400
        });
    }
});
```

Title: Using cropper with ng-file-upload

Body:
Save the blob you get from this.cropper.getCroppedCanvas().toBlob() by attaching it to the state.

Pass the saved blob to the File constructor within the save() function by pushing it to the first parameter fileBits

Handle the upload on the backend with a help of multer

Component

import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { default as Cropper } from 'cropperjs';
import { FileItem, FileUploader } from 'ng2-file-upload';
import { UserService } from '../services/user.service';
import { User } from '../models/core';

@Component({
  selector: 'app-image-cropper',
  templateUrl: './image-cropper.component.html',
  styleUrls: ['./image-cropper.component.scss']
})
export class ImageCropperComponent implements OnInit, AfterViewInit, OnDestroy {

  @ViewChild('imageElement', {static: false})
  public imageElement: ElementRef;

  @Input()
  public imageSource: string;

  public imageBlob: Blob;
  public uploader: FileUploader;
  private cropper: Cropper;

  public constructor(private userService: UserService) {}

  public ngAfterViewInit() {
    this.cropper = new Cropper(this.imageElement.nativeElement, {
      zoomable: false,
      scalable: false,
      responsive: true,
      autoCropArea: 1,
      aspectRatio: 1,
      viewMode: 1,
      crop: (event) => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          this.imageBlob = blob;
          console.log('Crop saved as a Blob');
        });
      }
    });
  }

  public save() {
    const date: number = new Date().getTime();
    // Put the blob into the fileBits array of the File constructor
    const file = new File([this.imageBlob], 'photo', {type: 'image/png', lastModified: date});
    const fileItem = new FileItem(this.uploader, file, {});
    this.uploader.queue.push(fileItem);
    fileItem.upload();
  }

  ngOnInit() {
    this.userService.user$.subscribe((user: User) => {
      this.uploader = new FileUploader({url: '/api/profile/' + user.username + '/avatar', itemAlias: 'photo'});
      this.uploader.onAfterAddingFile = (file) => {
        file.withCredentials = false;
      };
      this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
        console.log(response);
      };
    });
  }

  ngOnDestroy(): void {
    this.imageBlob = undefined;
    this.imageSource = '';
  }

}

Component template

<div class="modal-content">
  <div class="modal-header">
    <p class="modal-title font-weight-bold" id="crop-modal-title"><i></i>Crop</p>
    <button type="button" class="close" data-dismiss="modal"
            (click)="activeModal.close('Close click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">

    <div class="img-container">
      <img #imageElement [src]="imageSource" crossorigin>
    </div>
    <button type="button" class="button button-primary"
            (click)="save()">
    </button>
  </div>
</div>

Node Controller

import { Request, Response, Router } from 'express';
import * as util from 'util';
import * as fs from 'fs';
import * as multer from 'multer';

Router.post('/profile/:username/avatar/', upload.single('photo'), async (req: Request, resp: Response) => {
    try {
        console.log(req.file);
        // Do something with the uploaded file here
        const fsUnlinkPromisified = (util as any).promisify(fs.unlink);
        await fsUnlinkPromisified(req.file.path);
    } catch (error) {
        console.log(error);
        return resp.send({
            msg: 'Upload failed',
            status: 400
        });
    }
});