问:
HTML sections overlapping
I have the following simple HTML layout

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

The second and third sections are overlapping, what am I doing wrong?

答:
The problem you're suffering is that elements with a float property are taken out of the document's normal flow when their position(s) and layout are calculated by the browser.

There are two easy ways to solve this problem, the first is to set overflow: hidden; to the parent element (in this case to the
 element) in the CSS:

section {
  overflow: hidden;
}

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

Another way is to use a pseudo-element, or an added child-element, set to clear: both; which will force that element to be displayed after the floated content and, not being floated itself, this forces the browser to include that element's position in the layout; first, using an added child element:

```<code>section::after {
  /* newline character: */
  content: "\A";
  /* forcing the element/pseudo-element to
     take 100% of the width of the parent;
     this could be replaced with:
       display: inline-block;
       width: 100%;
     but that's unnecessarily verbose and
     may cause problems because of padding
     and margins */
  display: block;
  /* forcing the element/pseudo-element to
     clear the preceding floats */
  clear: both;
}
</code>```

section::after {
  content: "\A";
  display: block;
  clear: both;
}

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

However since the problem is the use of float, it's even easier to solve the problem by avoiding the problem. The following approach uses CSS flex-box to prevent the problem arising:

.section1 {
  background: red;
}

.section2 {
  background: green;
  /* initiates the flex-box layout: */
  display: flex;
  /* allows the flex-item children
     to wrap to form a multi-row/column
     layout: */
  flex-wrap: wrap;
  /* setting the flex axes, and layout,
     to be row-based: */
  flex-direction: row;
}

.section3 {
  background: yellow;
}

.section2 p {
  /* defines how much the element
     will grow relative to other
     elements in the layout; this
     sets the
 element to 100%
     width: */
  flex-grow: 100%;
  /* defines how much the element
     can shrink relative to other
     elements in the layout: */
  flex-shrink: 1;
}

.section2 article {
  flex-grow: 33%;
  flex-shrink: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

And, finally, using CSS grid layout:

.section1 {
  background: red;
}

.section2 {
  background: green;
  /* sets the grid layout, the child elements
     are automatically set to
     'display: grid-item': */
  display: grid;
  /* defines two rows, each with a 'size' of
     'min-content'; this causes the row to be
     large enough to show the content without
     the author needing to guess (or discover)
     the rendered height of the element: */
  grid-template-rows: repeat(min-content, 2);
  /* defines three columns, each the size of
     1fr (one fractional unit of the width
     available): */
  grid-template-columns: repeat(1fr, 3);
}

.section3 {
  background: yellow;
}

.section2 p {
  /* places the element in the
     first grid-row: */
  grid-row: 1;
  /* places the element in the
     first grid-column, and spans
     all three of those columns: */
  grid-column: 1 / span 3;
}

.section2 article {
  /* places the elements in the
     second grid-row; we don't define
     which of the columns the elements
     are placed in, instead leaving the
     browser to place them automatically: */
  grid-row: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

Title: HTML sections overlapping

Body:
I have the following simple HTML layout

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.

    Section 2 content

    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas.

    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex.

    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos

  Section 3 content

The second and third sections are overlapping, what am I doing wrong?

Body:
The problem you're suffering is that elements with a float property are taken out of the document's normal flow when their position(s) and layout are calculated by the browser.

There are two easy ways to solve this problem, the first is to set overflow: hidden; to the parent element (in this case to the <section> element) in the CSS:

section {
  overflow: hidden;
}

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}

<section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section>

Another way is to use a pseudo-element, or an added child-element, set to clear: both; which will force that element to be displayed after the floated content and, not being floated itself, this forces the browser to include that element's position in the layout; first, using an added child element:

section::after {
  /* newline character: */
  content: "\A";
  /* forcing the element/pseudo-element to
     take 100% of the width of the parent;
     this could be replaced with:
       display: inline-block;
       width: 100%;
     but that's unnecessarily verbose and
     may cause problems because of padding
     and margins */
  display: block;
  /* forcing the element/pseudo-element to
     clear the preceding floats */
  clear: both;
}

section::after {
  content: "\A";
  display: block;
  clear: both;
}

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}

<section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section>

However since the problem is the use of float, it's even easier to solve the problem by avoiding the problem. The following approach uses CSS flex-box to prevent the problem arising:

.section1 {
  background: red;
}

.section2 {
  background: green;
  /* initiates the flex-box layout: */
  display: flex;
  /* allows the flex-item children
     to wrap to form a multi-row/column
     layout: */
  flex-wrap: wrap;
  /* setting the flex axes, and layout,
     to be row-based: */
  flex-direction: row;
}

.section3 {
  background: yellow;
}

.section2 p {
  /* defines how much the element
     will grow relative to other
     elements in the layout; this
     sets the <p> element to 100%
     width: */
  flex-grow: 100%;
  /* defines how much the element
     can shrink relative to other
     elements in the layout: */
  flex-shrink: 1;
}

.section2 article {
  flex-grow: 33%;
  flex-shrink: 1;
}

<section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section>

And, finally, using CSS grid layout:

.section1 {
  background: red;
}

.section2 {
  background: green;
  /* sets the grid layout, the child elements
     are automatically set to
     'display: grid-item': */
  display: grid;
  /* defines two rows, each with a 'size' of
     'min-content'; this causes the row to be
     large enough to show the content without
     the author needing to guess (or discover)
     the rendered height of the element: */
  grid-template-rows: repeat(min-content, 2);
  /* defines three columns, each the size of
     1fr (one fractional unit of the width
     available): */
  grid-template-columns: repeat(1fr, 3);
}

.section3 {
  background: yellow;
}

.section2 p {
  /* places the element in the
     first grid-row: */
  grid-row: 1;
  /* places the element in the
     first grid-column, and spans
     all three of those columns: */
  grid-column: 1 / span 3;
}

.section2 article {
  /* places the elements in the
     second grid-row; we don't define
     which of the columns the elements
     are placed in, instead leaving the
     browser to place them automatically: */
  grid-row: 2;
}

<section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section>


来源: stackexchange

问:
Scrapy CLI output - CSV_DELIMITER parameter not working
I am trying to run the scrapy exporter with a custom delimiter via CLI like this:

scrapy runspider beneficiari_2016.py -o beneficiari_2016.csv -t csv -a CSV_DELIMITER="\n"

The export works perfectly, but the delimiter is still the default comma(",").

Please let me know if you have any idea how it can be fixed. Thank you!

The code:

```<code>import scrapy
from scrapy.item import Item, Field
import urllib.parse

class anmdm(Item):
    nume_beneficiar = Field()

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://www.anm.ro/sponsorizari/afisare-2016/beneficiari?
    page=1']
    def parse(self, response):
        doctor = anmdm()
        doctors = []
        for item in response.xpath('//tbody/tr'):
            doctor['nume_beneficiar'] =
        item.xpath('td[5]//text()').extract_first()
            yield doctor
        next_page =  response.xpath("//ul/li[@class='active']/following-
       sibling::li/a/@href").extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            print(next_page)
            yield response.follow(next_page, self.parse)
</code>```

答:
CSV_DELIMITER needs to be changed in settings and not like an spider argument -a.

To change settings on the command line use -s:

```<code>scrapy runspider beneficiari_2016.py -o beneficiari_2016.csv -t csv -s CSV_DELIMITER="\n"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run the scrapy exporter with a custom delimiter via CLI like this:

scrapy runspider beneficiari_2016.py -o beneficiari_2016.csv -t csv -a CSV_DELIMITER="\n"

The export works perfectly, but the delimiter is still the default comma(",").

Please let me know if you have any idea how it can be fixed. Thank you!

The code:

import scrapy
from scrapy.item import Item, Field
import urllib.parse

class anmdm(Item):
    nume_beneficiar = Field()

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://www.anm.ro/sponsorizari/afisare-2016/beneficiari?
    page=1']
    def parse(self, response):
        doctor = anmdm()
        doctors = []
        for item in response.xpath('//tbody/tr'):
            doctor['nume_beneficiar'] =
        item.xpath('td[5]//text()').extract_first()
            yield doctor
        next_page =  response.xpath("//ul/li[@class='active']/following-
       sibling::li/a/@href").extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            print(next_page)
            yield response.follow(next_page, self.parse)

Body:
CSV_DELIMITER needs to be changed in settings and not like an spider argument -a.

To change settings on the command line use -s:

scrapy runspider beneficiari_2016.py -o beneficiari_2016.csv -t csv -s CSV_DELIMITER="\n"


问:
Getting no seeders and leechers for scrape from udp tracker
I am trying to implement the scrape method for an UDP tracker but I keep getting 0 seeders/leechers as response. I am still getting a 2 as the action so no error is reported.
I have hardcoded a hash here just to show that it has no effect on the result I am getting.

```<code>    final ByteArrayOutputStream byteStream =new ByteArrayOutputStream();
    final DataOutputStream dataStream =new DataOutputStream(byteStream);
    dataStream.writeInt(connectResponse.get("connectionId0"));
    dataStream.writeInt(connectResponse.get("connectionId1"));
    dataStream.writeInt(2);
    dataStream.write(connectResponse.get("transactionId"));
    bencodeWriter.write(byteOut.toString());
    dataStream.writeChars("1D19CC96C1A4965D184E4B215942DBC0A09FF8F2");
    dataStream.close();
    final byte[] scrapeBytes= byteStream.toByteArray();
</code>```

I tried different trackers but get the same response. What might be the problem?

Edit: Added the hex dump of all the requests and responses:

Connect Request:

Connect Response:

Scrape Request:

Scrape Response:

答:
In the Scrape request;

the transaction_id=0x36 is sent as a single byte instead of 4 bytes=0x00000036

and the info_hash is sent as a 80 bytes string that is hex-encoded were every character is prepended by a zero-byte 0x00 instead of as a raw 20 bytes string.

I.E. 0x0031004400310039... instead of 0x1D19...

The Scrape response has no peers, as there is no torrents with the info_hashes sent in the request.

Body:
I am trying to implement the scrape method for an UDP tracker but I keep getting 0 seeders/leechers as response. I am still getting a 2 as the action so no error is reported.
I have hardcoded a hash here just to show that it has no effect on the result I am getting.

    final ByteArrayOutputStream byteStream =new ByteArrayOutputStream();
    final DataOutputStream dataStream =new DataOutputStream(byteStream);
    dataStream.writeInt(connectResponse.get("connectionId0"));
    dataStream.writeInt(connectResponse.get("connectionId1"));
    dataStream.writeInt(2);
    dataStream.write(connectResponse.get("transactionId"));
    bencodeWriter.write(byteOut.toString());
    dataStream.writeChars("1D19CC96C1A4965D184E4B215942DBC0A09FF8F2");
    dataStream.close();
    final byte[] scrapeBytes= byteStream.toByteArray();

I tried different trackers but get the same response. What might be the problem?

Edit: Added the hex dump of all the requests and responses:

Connect Request:

Connect Response:

Scrape Request:

Scrape Response:


问:
Is there a risk of injection using mail function
Hi
I'm developing a contact form. I'm using the mail function to email it over to the webmaster.

Is there a risk someone could inject malicious javascript and any other injection attack?

```<code>$to = (this is from config xml file)
$message = $_POST['message'];
mail($to ,'feedback',$message);
</code>```

答: Only if you set the content type to text/html

ContentLicense: CC BY-SA 2.5

Body:
Hi
I'm developing a contact form. I'm using the mail function to email it over to the webmaster.

Is there a risk someone could inject malicious javascript and any other injection attack?

$to = (this is from config xml file)
$message = $_POST['message'];
mail($to ,'feedback',$message);


问:
Android Keystore generation failure with java keytool
I ran the command prompt from the directory containing keytool.exe and ran the command line for keystore generation and after accepting all details and beggining to store keystore it ends up showing this error:

```<code>[Storing CandMKS.keystore]
keytool error: java.io.FileNotFoundException: CandMKS.keystore (Access is
denied)
java.io.FileNotFoundException: CandMKS.keystore (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at sun.security.tools.keytool.Main.doCommands(Main.java:1144)
    at sun.security.tools.keytool.Main.run(Main.java:343)
    at sun.security.tools.keytool.Main.main(Main.java:336)
</code>```

Now I think the problem is with java. Something to do with java paths because earlier I tried to build with CLI and it gave an error while debugging java with javac. Any suggestions ?

答: Ran CMD as administrator. Problem solved.</p>

Body:
I ran the command prompt from the directory containing keytool.exe and ran the command line for keystore generation and after accepting all details and beggining to store keystore it ends up showing this error:

[Storing CandMKS.keystore]
keytool error: java.io.FileNotFoundException: CandMKS.keystore (Access is
denied)
java.io.FileNotFoundException: CandMKS.keystore (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at sun.security.tools.keytool.Main.doCommands(Main.java:1144)
    at sun.security.tools.keytool.Main.run(Main.java:343)
    at sun.security.tools.keytool.Main.main(Main.java:336)

Now I think the problem is with java. Something to do with java paths because earlier I tried to build with CLI and it gave an error while debugging java with javac. Any suggestions ?


问:
change name of HTML <select> form Attribute in a for loop
In my code I create duplicate copies of a fieldset based on user input using the code in the snippet. My issue right now is that when the user submits the form the params Hash does not take into account value from different instances of the fieldset. The last value overwrites all the previous values. As an example in the current scenario below is the params Hash.

```<code> { "member"=>"2", "lte_freq1"=>"4", "ru_type"=>"RRU", "4_way_rx"=>"No"}
</code>```

However, my desired output is shown below. Here the value of member =2 so two instances of fieldset are appended:

```<code> { "member"=>"2", "lte_freq1_1"=>"6", "ru_type_1"=>"RU",
  "4_way_rx_1"=>"Yes", "lte_freq1_2"=>"4", "ru_type_2"=>"RRU",
  "4_way_rx_2"=>"No" }
</code>```

$(document).ready(function(){
$("button").click(function(){
var number = document.getElementById("member").value;
var repeat = $('fieldset');
var cloned;

for (i=1;i<number;i++){
    cloned = repeat.clone(true);
    cloned.appendTo('.sector_prop');

}

 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<br>

 <br>
 <br>

</head>
<body>
<form action="/form" method="post">
<div class="textbox">

<legend><b> RF Parameters</b></legend>
<br>
Number of Sectors (LTE)<br>
<br>
<input type="text" id="member" name="member" value="">
<br>
<br>

<button>Generate Sector Properties</button>
<br>
<br>

<div class="sector_prop">

<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS
for Band 4 and PCS for Band 2)<br>
<br>
<select name="lte_freq1">
<option value="6">850</option>
<option value="2">AWS</option>
<option value="4">PCS</option>
</select>
<br>

<br>
Radio Type (Select "RU" for Rack-mount or RRU for Remote-Radio):<br>
<br>
<select name="ru_type">
  <option value="RU">RU</option>
  <option value="RRU">RRU</option>
</select>
<br>
<br>
4 way Rx (Select "Yes" or "No"):<br>
<br>
<select name="4_way_rx">
  <option value="Yes">Yes</option>
  <option value="No">No</option>
</select>
<br>
<br>

</fieldset>

</div>

<br>

<input type="submit">
</form>
<br>
<br>
</body></code>```

答:
You are cloning the element, it won't magically update the field name. So you need to manually get the index and update the name of the new element as you clone:</p>

```<code>$(document).ready(function(){
  $("button").click(function(){
    var number = document.getElementById("member").value;
    var repeat = $('fieldset');
    var cloned;

    for (i=1;i<number;i++){
      cloned = repeat.clone(true);
      current_name = cloned.find('select').attr('name');
      cloned.find('select').prop('name', current_name + '_' + i);
      cloned.appendTo('.sector_prop');
    }
  });
});
</code>```

Body:
In my code I create duplicate copies of a fieldset based on user input using the code in the snippet. My issue right now is that when the user submits the form the params Hash does not take into account value from different instances of the fieldset. The last value overwrites all the previous values. As an example in the current scenario below is the params Hash.

 { "member"=>"2", "lte_freq1"=>"4", "ru_type"=>"RRU", "4_way_rx"=>"No"}

However, my desired output is shown below. Here the value of member =2 so two instances of fieldset are appended:

 { "member"=>"2", "lte_freq1_1"=>"6", "ru_type_1"=>"RU",
  "4_way_rx_1"=>"Yes", "lte_freq1_2"=>"4", "ru_type_2"=>"RRU",
  "4_way_rx_2"=>"No" }

$(document).ready(function(){
$("button").click(function(){
var number = document.getElementById("member").value;
var repeat = $('fieldset');
var cloned;

for (i=1;i<number;i++){
    cloned = repeat.clone(true);
    cloned.appendTo('.sector_prop');

}

 });
});

<!DOCTYPE html>

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

<legend> RF Parameters</legend>

Number of Sectors (LTE)

<input type="text" id="member" name="member" value="">

<button>Generate Sector Properties</button>

<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS
for Band 4 and PCS for Band 2)

<select name="lte_freq1">
<option value="6">850</option>
<option value="2">AWS</option>
<option value="4">PCS</option>
</select>

Radio Type (Select "RU" for Rack-mount or RRU for Remote-Radio):

<select name="ru_type">
  <option value="RU">RU</option>
  <option value="RRU">RRU</option>
</select>

4 way Rx (Select "Yes" or "No"):

<select name="4_way_rx">
  <option value="Yes">Yes</option>
  <option value="No">No</option>
</select>

</fieldset>

<input type="submit">
</form>

Body:
You are cloning the element, it won't magically update the field name. So you need to manually get the index and update the name of the new element as you clone:

$(document).ready(function(){
  $("button").click(function(){
    var number = document.getElementById("member").value;
    var repeat = $('fieldset');
    var cloned;

    for (i=1;i<number;i++){
      cloned = repeat.clone(true);
      current_name = cloned.find('select').attr('name');
      cloned.find('select').prop('name', current_name + '_' + i);
      cloned.appendTo('.sector_prop');
    }
  });
});


问:
.htaccess to secure admin directory in mvc architecture
I am trying to make a site with mvc structure. I have this :

www/

blog/

app/

admin/

controller/

model/

view/

config/

front/

controller/

model/

view/

assets/

images/

libs/

portfolio /

I have a first .htaccess at the root (www/) for Gzip compression and stuff.
I have a second .htaccess for my blog (in www/blog/) with my very basic redirection system :

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#QSA permet de garder les paramètres GET et les ajouter à la suite
RewriteRule (.*) index.php?p=$1 [QSA]
</code>```

The file index.php in www/blog/ parses the url and uses the right controllers like this :

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

include_once(APP_f.controller/controller.class.php');
$controlF = new ControleurF();

include_once(APP_b.'controleur/controleur.class.php');
$controlB = new ControleurB();

if (isset($_GET['p'])&&(substr($_GET['p'],0,4)== 'admin')) {
//on est dans l'admin
    $lapage=explode('/',$_GET['p']);
    if (!empty($lapage[1])) {$pp = $lapage[1];} else {$pp="index";}

    if (!isset($pp) OR $pp == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$pp);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlB->load($ctrl);
    include_once($c);

}else{
//on est en front
    if (!isset($_GET['p']) OR $_GET['p'] == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$_GET['p']);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlF->load($ctrl);
    include_once($c);
}

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

Everything works fine but i am having trouble understanding how i could secure my admin folder with .htaccess/.htpasswd
Is there a way to do something like that in www/blog/.htaccess :

```<code><Directory admin>
AuthUserFile "/home/foobar/www/blog/.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin"
AuthType Basic
Require valid-user
</Directory>
</code>```

答:
I find a way : use sessions with php
http://www.apprendre-php.com/tutoriels/tutoriel-14-les-sessions.html</p>

Body:
I am trying to make a site with mvc structure. I have this :

www/

blog/

app/

admin/

controller/

model/

view/

config/

front/

controller/

model/

view/

assets/

images/

libs/

portfolio /

I have a first .htaccess at the root (www/) for Gzip compression and stuff.
I have a second .htaccess for my blog (in www/blog/) with my very basic redirection system :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#QSA permet de garder les paramètres GET et les ajouter à la suite
RewriteRule (.*) index.php?p=$1 [QSA]

The file index.php in www/blog/ parses the url and uses the right controllers like this :

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

include_once(APP_f.controller/controller.class.php');
$controlF = new ControleurF();

include_once(APP_b.'controleur/controleur.class.php');
$controlB = new ControleurB();

if (isset($_GET['p'])&&(substr($_GET['p'],0,4)== 'admin')) {
//on est dans l'admin
    $lapage=explode('/',$_GET['p']);
    if (!empty($lapage[1])) {$pp = $lapage[1];} else {$pp="index";}

    if (!isset($pp) OR $pp == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$pp);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlB->load($ctrl);
    include_once($c);

}else{
//on est en front
    if (!isset($_GET['p']) OR $_GET['p'] == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$_GET['p']);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlF->load($ctrl);
    include_once($c);
}

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

Everything works fine but i am having trouble understanding how i could secure my admin folder with .htaccess/.htpasswd
Is there a way to do something like that in www/blog/.htaccess :

<Directory admin>
AuthUserFile "/home/foobar/www/blog/.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin"
AuthType Basic
Require valid-user
</Directory>


问:
utf8.offset: how to specify starting positions?
How can I use utf8.offset(s, n, i) to find the offset of the character at n starting from specific byte and character positions? The i parameter is documented as:

Returns the position (in bytes) where the encoding of the n-th character of s (counting from position i) starts...

I got i is what I need, but I can't understand if it's byte position or character position. How can I use it?

答: All string offsets in the Lua manual are in bytes, unless the manual specifically says otherwise. So i is a byte offset, as is utf8.offset's return value.


问:
How do you create a table in python from a text file
i have been trying to create a table from a text file like this:

```<code>MemberID  Surname  Year joined  Membership status  Nights booked  Pointsbalance
Jim123    jimmy     2017        gold               10              15000
</code>```

and the text file is like this:

```<code>jim123,jimmy,2017,gold,10,15000
</code>```

how would i do this?
as simple as possible please

答:
You can read in the data and put it in a dictionary:</p>

```<code>f = open('filename.txt').readlines()

f = [i.strip('\n').split(',') for i in f]

final_data = {i[0]:i[1:] for i in f}
</code>```

Body:
i have been trying to create a table from a text file like this:

MemberID  Surname  Year joined  Membership status  Nights booked  Pointsbalance
Jim123    jimmy     2017        gold               10              15000

and the text file is like this:

jim123,jimmy,2017,gold,10,15000

how would i do this?
as simple as possible please

Body:
You can read in the data and put it in a dictionary:

f = open('filename.txt').readlines()

f = [i.strip('\n').split(',') for i in f]

final_data = {i[0]:i[1:] for i in f}


问:
Spring MVC using hibernate Sequence doesn't exist
UserBean Class

```<code>@Entity
@Table(name="users")
public class UserBean {

    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    @Column(name="ID")
    private Integer id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "AGE")
    private int age;

    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserBean [id=").append(id).append(", name=")
                .append(name).append(", email=").append(email).append(", age=")
                .append(age).append("]");
        return builder.toString();
    }

}
</code>```

I am getting  ORA:02289 Sequence doesn't exist

Here is hibernate.cfg.xml

```<code><hibernate-configuration>
    <session-factory>
        <mapping class="com.abc.bean.UserBean" />
    </session-factory>
</hibernate-configuration>
</code>```

Dispatcher package scan

```<code><context:component-scan base-package="com.abc.controller" />
<context:component-scan base-package="com.abc.dao.impl" />
<mvc:annotation-driven />
</code>```

I have tried the same thing in another laptop and it worked, what is causing the problem? Earlier, I tried to generate a sequence but it didn't worked well

Sql command executed:
create table users(id int primary key,name varchar(20),email varchar(20),age int);

答: Which version of Oracle you using? As per my knowledge Auto increment not supported in 11g but supports in 12c..</p>

Body:
UserBean Class

@Entity
@Table(name="users")
public class UserBean {

    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    @Column(name="ID")
    private Integer id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "AGE")
    private int age;

    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserBean [id=").append(id).append(", name=")
                .append(name).append(", email=").append(email).append(", age=")
                .append(age).append("]");
        return builder.toString();
    }

}

I am getting  ORA:02289 Sequence doesn't exist

Here is hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <mapping class="com.abc.bean.UserBean" />
    </session-factory>
</hibernate-configuration>

Dispatcher package scan

<context:component-scan base-package="com.abc.controller" />
<context:component-scan base-package="com.abc.dao.impl" />
<mvc:annotation-driven />

I have tried the same thing in another laptop and it worked, what is causing the problem? Earlier, I tried to generate a sequence but it didn't worked well

Sql command executed:
create table users(id int primary key,name varchar(20),email varchar(20),age int);


问:
Amazon EC2 instance through public ip is not working
The instance is running fine. I am using linux os and apache-tomcat-8.0.33 server. I can access from private ip using putty  But when i am trying to access the same through the public ip, it is not accessible. I have seen the security configurations all ports are enabled.

Can anyone help me how to reslove this issue

 inbound image

答:
Regardless of the number of ports open in your security group, if you must access your ec2 instance using it's public IP, over the internet, you must assign an internet gateway (IGW) to the subnet your ec2 instance belongs to

http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Internet_Gateway.html


问:
How can I expand my program to make it used on multiple devices and give them access to the old database without losing data?
I built a software for a farm using C#, the program was meant to keep track of the inventory and the financial exchanges related to the farms work.

The software was built to be installed on the manager's computer who then entered the farms data and retrieved reports and so. While the accountant used the same PC to use the financial part of the program with a different account.

Now the farm's business grew and more users need to use the system, can I move the database with the old data to a server so users can log in the system from different PC's at the time and continue the old tasks?

If I can - what do I change in my code?

P.S. the database was done in MS Access.

答:
Not a lot of information to go on here.  I can tell you that Access is a file based database system, and so whilst you could put the database files on a server or a NAS device with no problem with multiple users you should expect to run into the usual problems of Windows file sharing - VERY SLOW performance as a minimum.

It is also possible that the database may have been limited to a single user at a time, and without any more information impossible to know whether the developers have allowed for multi-user at all or whether you could have a situation where if several people do open the file at once one person may be overwriting another's data leading to corruption.

The short answer is that if the original developers are no longer around and you cannot ask the question of them then you probably need a new dedicated application to do the work which would mean either a complete rewrite or an alternative commercial application.

For multi-user Microsoft SQL Server, MySql, or even Firebird or another dedicated database back end would be the way to go.  The front end could be anything - Winforms, WPF, even a web application if that is what you want, but it would have to be written.

I hope that this is helpful.


问:
"{\"error\":\"Invalid command.\"}" How to fix this error? With JSON in R
```<code>library(httr)
library(jsonlite)
library(lubridate)

command = "currencyPair"

url <- paste("https://poloniex.com/public?command=", command, sep = "")

raw.result <- GET(url = url)

# names(raw.result)
# [1] "url"         "status_code" "headers"     "all_headers" "cookies" "content"     "date"        "times"
# [9] "request"     "handle"

# head(raw.result$content)
# [1] 7b 22 65 72 72 6f

this.raw.content <- rawToChar(raw.result$content)

# this.raw.content
# [1] "{\"error\":\"Invalid command.\"}"
</code>```

I would like to get the above command into Character form so that I can create a Data.frame. What can I do to fix the error line?

答:
Try looking into using the multiple arugment. For instance,

```<code>rawToChar(raw.result$content, multiple = TRUE)
 [1] "{" "\"" "e" "r" "r" "o" "r" "\"" ":" "\"" "I" "n" "v" "a" "l"
[16] "i" "d" " " "c" "o" "m" "m" "a" "n" "" "." "\"" "}"
</code>```

Body:
library(httr)
library(jsonlite)
library(lubridate)

command = "currencyPair"

url <- paste("https://poloniex.com/public?command=", command, sep = "")

raw.result <- GET(url = url)

# names(raw.result)
# [1] "url"         "status_code" "headers"     "all_headers" "cookies" "content"     "date"        "times"
# [9] "request"     "handle"

# head(raw.result$content)
# [1] 7b 22 65 72 72 6f

this.raw.content <- rawToChar(raw.result$content)

# this.raw.content
# [1] "{\"error\":\"Invalid command.\"}"

I would like to get the above command into Character form so that I can create a Data.frame. What can I do to fix the error line?

Body:
Try looking into using the multiple arugment. For instance,

rawToChar(raw.result$content, multiple = TRUE)
 [1] "{" "\"" "e" "r" "r" "o" "r" "\"" ":" "\"" "I" "n" "v" "a" "l"
[16] "i" "d" " " "c" "o" "m" "m" "a" "n" "" "." "\"" "}"


问:
Bootstrap - setting Column heights
I'm creating a Bootstrap (version 3.3) website, which has a smallish sized carousel, and I want to create 3 boxes immediately on its right-hand side; (refer image for an idea of what I'm trying to do).

As obviously I want it all responsive, I've placed the Carousel within a column (of width 8 for medium & large screens) + 1 for offset, while the boxes would be the width of 2 + 1 offset.
I then also created another row (and columns) within the 2 column - so that all boxes would move below the Carousel on a xs screen size at the same time.

I've used row-eq-height to make the Carousel column and the column with the boxes the same height, but I'm not sure as to how to make 2 boxes 33% of the height of the Carousel & 1 box 34% of the Carousel height.  (Obviously, I want the boxes displayed below each other, with no gutter between them).

My Code so far on Bootply;
https://www.bootply.com/RQfetegi0e

Otherwise the HTML Code so far;

```<code><div class="container" style="padding-top:100px;">
  <div class="row no-gutter">
    <div class="col-md-offset-1 col-md-8 col-sm-8 col-xs-12 row-eq-height">
      <div id="myCarousel" class="carousel slide">
        <ol class="carousel-indicators">
          <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
          <li data-target="#myCarousel" data-slide-to="1"></li>
          <li data-target="#myCarousel" data-slide-to="2"></li>
          <li data-target="#myCarousel" data-slide-to="3"></li>
          <li data-target="#myCarousel" data-slide-to="4"></li>
        </ol>
        <!-- Carousel items -->
        <div class="carousel-inner img-responsive center-block">
          <div class="active item">
            <img src="images/carousel/coming-events.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/play-group.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/learn-skills.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/kids-xmas.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/backyard-sports.jpg" alt="">
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-2 col-sm-3 col-xs-12 no-padding">
      <div class="row">
        <div class="col-xs-12" style="margin-bottom:-20px; margin-top:-20px; height:33%;">
          <h3 style="text-align:center; color: white; background-color:red; height:33%;">Text Here</h3>
        </div>
        <div class="col-xs-12" style="margin-top:-25px; margin-bottom-25px; height:34%;">
          <h3 style="text-align:center; color: white; background-color:green; height:34%;">Text Here</h3>

        </div>
        <div class="col-xs-12" style="margin-top:-25px; margin-bottom:-25px; height:33%;">
          <h3 style="text-align:center; color: white; background-color:blue; height:33%;">Text Here</h3>
        </div>
      </div>
  </div>
  </div>
</div>
</code>```

CSS Code:

```<code>.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
</code>```

答:
The way I'm handling heights is with inherit and then add some paddings.

h3 {
    height: inherit;
    padding: 3% 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-xs-12">
          <h3 style="text-align:center; color: white; background-color:red;">Text Here</h3>
        </div>
        <div class="col-xs-12">
          <h3 style="text-align:center; color: white; background-color:green;">Text Here</h3>

        </div>
        <div class="col-xs-12">
          <h3 style="text-align:center; color: white; background-color:blue;">Text Here</h3>
        </div></code>```

Title: Bootstrap - setting Column heights

Body:
I'm creating a Bootstrap (version 3.3) website, which has a smallish sized carousel, and I want to create 3 boxes immediately on its right-hand side; (refer image for an idea of what I'm trying to do).

As obviously I want it all responsive, I've placed the Carousel within a column (of width 8 for medium & large screens) + 1 for offset, while the boxes would be the width of 2 + 1 offset.
I then also created another row (and columns) within the 2 column - so that all boxes would move below the Carousel on a xs screen size at the same time.

I've used row-eq-height to make the Carousel column and the column with the boxes the same height, but I'm not sure as to how to make 2 boxes 33% of the height of the Carousel & 1 box 34% of the Carousel height.  (Obviously, I want the boxes displayed below each other, with no gutter between them).

My Code so far on Bootply;
https://www.bootply.com/RQfetegi0e

Otherwise the HTML Code so far;

Text Here

Text Here

Text Here

CSS Code:

.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}

Body:
The way I'm handling heights is with inherit and then add some paddings.

h3 {
    height: inherit;
    padding: 3% 0;
}

<div class="col-xs-12">
          <h3 style="text-align:center; color: white; background-color:red;">Text Here</h3>
        </div>
        <div class="col-xs-12">
          <h3 style="text-align:center; color: white; background-color:green;">Text Here</h3>

        </div>
        <div class="col-xs-12">
          <h3 style="text-align:center; color: white; background-color:blue;">Text Here</h3>
        </div>


问:
Why one function are giving diffrent errors in Python
This is an assignment in Udacity linear algebra refresher course and I have solved it in my way although there is a solution available for this assignment I am trying to solve it in my way.  But I am getting error while finding angle between 2 vector  that is vectore v1 and v2 .

There is 2 problems  asked 2 solve to this program. But even if there  is same. but  to programs is giving to diffrent out put  even if there "angle" function is same.

```<code>import math
from decimal import Decimal,getcontext
getcontext().prec = 30
class Vector(object):
    def __init__(self,coordinates):
        try:
            if not coordinates:
                raise ValueError
                #if coordinates is not passed then it will rise Value Error
            self.coordinates = tuple([Decimal(x)for x in coordinates])
            #Outside Class :-Vector.coordinates will give print vectors in tuple form
            #Inside Class :- self.coordinates will print vectors in tuple form
            self.dimension = len(coordinates)
            #Outside Class :-Vector.dimension will print vectors dimension/size
            #Inside Class :- self.dimension will print vectors dimension/size
        except ValueError:
            raise ValueError('The coordinates must be non empty')
        except TypeError:
            raise TypeError('The coordinates must be itterable')
    def __str__(self):
        return 'Vector:{}'.format(self,coordinates)
    def __eq__(self,v):
        return self.coordinates == v.coordinates
    def add (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]+v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def mul(self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]*v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def sub (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]-v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def scal_mul(self,s):
        coordinates=[]
        for i in self.coordinates:
            i=i*Decimal(s)
            coordinates.append(i)
        return coordinates
    def magnitude(self):
        mag = 0
        for i in self.coordinates:
            i=i*i
            mag =mag+i
        return math.sqrt(mag)

    def magnitude1(self):
        mag = 0
        coordinate_squre=[i*i for i in self.coordinates]
        return math.sqrt(sum(coordinate_squre))

#     def normalize(self):
#         try:
#             recip = Decimal(1)/self.magnitude()
#             return Vector(self.scal_mul(recip))
#         except ZeroDivisionError:
#             raise Exception("Can not Normalize Zero Vector")

    def normalize(self):
        try:
            recip = 1/self.magnitude()
            return self.scal_mul(recip)
        except ZeroDivisionError:
            raise Exception("Can not Normalize Zero Vector")

    def dot_product(self,v):
        mul = self.mul(v)
        return sum(mul)

    def dot_product2(self,v):
        self.mul = [x*y for x,y in zip(self.coordinates,v.coordinates)]
        return sum(self.mul)
    #-----------------angle functionn is giving wrong answer-------------
    def angle_rad(self,v):
        norm = self.normalize()
        angle = 1/ math.cos(norm.dot_product2(v))
        return angle

    def angle(self,v,in_degree=False):
        nrm_self = self.normalize()
        nrm_v = v.normalize()
        angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
        if in_degree:
            angle_in_degree = angle_rad * 180./math.pi
            return angle_in_degree
        else:
            return angle_rad

v1 = Vector([7.887,4.138])
v2 = Vector([-8.802,6.776])
print(v1.angle(v2))
v1 = Vector([-7.579,-7.88])
v2 = Vector([22.737,23.64])
v2.angle(v1)
</code>```

This Code is giving Error as following

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-44-2087e4f0ca26> in <module>()
    101 v1 = Vector([7.887,4.138])
    102 v2 = Vector([-8.802,6.776])
--> 103 print(v1.angle(v2))
    104 v1 = Vector([-7.579,-7.88])
    105 v2 = Vector([22.737,23.64])

<ipython-input-44-2087e4f0ca26> in angle(self, v, in_degree)
     92         nrm_self = self.normalize()
     93         nrm_v = v.normalize()
---> 94         angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
     95         if in_degree:
     96             angle_in_degree = angle_rad * 180./math.pi

AttributeError: 'list' object has no attribute 'dot_product2'
</code>```

And another program with exactly same angle function is

```<code>import math
class Vector(object):
    def __init__(self,coordinates):
        try:
            if not coordinates:
                raise ValueError
                #if coordinates is not passed then it will rise Value Error
            self.coordinates = tuple(coordinates)
            #Outside Class :-Vector.coordinates will give print vectors in tuple form
            #Inside Class :- self.coordinates will print vectors in tuple form
            self.dimension = len(coordinates)
            #Outside Class :-Vector.dimension will print vectors dimension/size
            #Inside Class :- self.dimension will print vectors dimension/size
        except ValueError:
            raise ValueError('The coordinates must be non empty')
        except TypeError:
            raise TypeError('The coordinates must be itterable')
    def __str__(self):
        return 'Vector:{}'.format(self,coordinates)
    def __eq__(self,v):
        return self.coordinates == v.coordinates
    def add (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]+v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def mul(self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]*v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def sub (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]-v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def scal_mul(self,s):
        coordinates=[]
        for i in self.coordinates:
            i=i*s
            coordinates.append(i)
        return coordinates
    def magnitude(self):
        mag = 0
        for i in self.coordinates:
            i=i*i
            mag =mag+i
        return math.sqrt(mag)

    def magnitude1(self):
        mag = 0
        coordinate_squre=[i*i for i in self.coordinates]
        return math.sqrt(sum(coordinate_squre))

    def normalize(self):
        try:
            recip = 1/self.magnitude()
            return Vector(self.scal_mul(recip))
        except ZeroDivisionError:
            raise Exception("Can not Normalize Zero Vector")

    def dot_product(self,v):
        mul = self.mul(v)
        return sum(mul)

    def dot_product2(self,v):
        self.mul = [x*y for x,y in zip(self.coordinates,v.coordinates)]
        return sum(self.mul)
    #-----------------angle functionn is giving wrong answer-------------
    def angle_rad(self,v):
        norm = self.normalize()
        angle = 1/ math.cos(norm.dot_product2(v))
        return angle

    def angle(self,v,in_degree=False):
        nrm_self = self.normalize()
        nrm_v = v.normalize()
        angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
        if in_degree:
            angle_in_degree = angle_rad * 180./math.pi
            return angle_in_degree
        else:
            return angle_rad

v1 = Vector([7.887,4.138])
v2 = Vector([-8.802,6.776])
print(v1.angle(v2))
v1 = Vector([-7.579,-7.88])
v2 = Vector([22.737,23.64])
v2.angle(v1)
</code>```

it is giving Error as following

```<code>2.0023426999774925

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-214-2e3bee12967a> in <module>()
     95 v1 = Vector([-7.579,-7.88])
     96 v2 = Vector([22.737,23.64])
---> 97 v2.angle(v1)
     98

<ipython-input-214-2e3bee12967a> in angle(self, v, in_degree)
     82         nrm_self = self.normalize()
     83         nrm_v = v.normalize()
---> 84         angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
     85         if in_degree:
     86             angle_in_degree = angle_rad * 180./math.pi

ValueError: math domain error
</code>```

We can see they are having same angle function

答:
The problem with your first program is that the normalize method returns a list of coordinates, return self.scal_mul(recip) but doesn't convert that list into a Vector object like the second program, which instead return Vector(self.scal_mul(recip)). When you call nrm_self.dot_product2(nrm_v), the object nrm_self is a list, not a Vector, and it doesn't have a dot_product2 method. You need to add an explicit call to the constructor Vector(), like in the second program, to be able to invoke methods from the norm_self object.

The math domain error is being thrown because dot_product2 is returning a value larger than 1 (unfortunately, 1.0000000000000002), and the inverse cosine acos(x) is only defined for values between -1 and 1. This is due to numerical error in the normalization, and can be corrected by always rounding the reciprocal slightly up.

Body:
This is an assignment in Udacity linear algebra refresher course and I have solved it in my way although there is a solution available for this assignment I am trying to solve it in my way.  But I am getting error while finding angle between 2 vector  that is vectore v1 and v2 .

There is 2 problems  asked 2 solve to this program. But even if there  is same. but  to programs is giving to diffrent out put  even if there "angle" function is same.

import math
from decimal import Decimal,getcontext
getcontext().prec = 30
class Vector(object):
    def __init__(self,coordinates):
        try:
            if not coordinates:
                raise ValueError
                #if coordinates is not passed then it will rise Value Error
            self.coordinates = tuple([Decimal(x)for x in coordinates])
            #Outside Class :-Vector.coordinates will give print vectors in tuple form
            #Inside Class :- self.coordinates will print vectors in tuple form
            self.dimension = len(coordinates)
            #Outside Class :-Vector.dimension will print vectors dimension/size
            #Inside Class :- self.dimension will print vectors dimension/size
        except ValueError:
            raise ValueError('The coordinates must be non empty')
        except TypeError:
            raise TypeError('The coordinates must be itterable')
    def __str__(self):
        return 'Vector:{}'.format(self,coordinates)
    def __eq__(self,v):
        return self.coordinates == v.coordinates
    def add (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]+v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def mul(self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]*v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def sub (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]-v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def scal_mul(self,s):
        coordinates=[]
        for i in self.coordinates:
            i=i*Decimal(s)
            coordinates.append(i)
        return coordinates
    def magnitude(self):
        mag = 0
        for i in self.coordinates:
            i=i*i
            mag =mag+i
        return math.sqrt(mag)

    def magnitude1(self):
        mag = 0
        coordinate_squre=[i*i for i in self.coordinates]
        return math.sqrt(sum(coordinate_squre))

#     def normalize(self):
#         try:
#             recip = Decimal(1)/self.magnitude()
#             return Vector(self.scal_mul(recip))
#         except ZeroDivisionError:
#             raise Exception("Can not Normalize Zero Vector")

    def normalize(self):
        try:
            recip = 1/self.magnitude()
            return self.scal_mul(recip)
        except ZeroDivisionError:
            raise Exception("Can not Normalize Zero Vector")

    def dot_product(self,v):
        mul = self.mul(v)
        return sum(mul)

    def dot_product2(self,v):
        self.mul = [x*y for x,y in zip(self.coordinates,v.coordinates)]
        return sum(self.mul)
    #-----------------angle functionn is giving wrong answer-------------
    def angle_rad(self,v):
        norm = self.normalize()
        angle = 1/ math.cos(norm.dot_product2(v))
        return angle

    def angle(self,v,in_degree=False):
        nrm_self = self.normalize()
        nrm_v = v.normalize()
        angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
        if in_degree:
            angle_in_degree = angle_rad * 180./math.pi
            return angle_in_degree
        else:
            return angle_rad

v1 = Vector([7.887,4.138])
v2 = Vector([-8.802,6.776])
print(v1.angle(v2))
v1 = Vector([-7.579,-7.88])
v2 = Vector([22.737,23.64])
v2.angle(v1)

This Code is giving Error as following

AttributeError                            Traceback (most recent call last)
<ipython-input-44-2087e4f0ca26> in <module>()
    101 v1 = Vector([7.887,4.138])
    102 v2 = Vector([-8.802,6.776])
--> 103 print(v1.angle(v2))
    104 v1 = Vector([-7.579,-7.88])
    105 v2 = Vector([22.737,23.64])

<ipython-input-44-2087e4f0ca26> in angle(self, v, in_degree)
     92         nrm_self = self.normalize()
     93         nrm_v = v.normalize()
---> 94         angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
     95         if in_degree:
     96             angle_in_degree = angle_rad * 180./math.pi

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

And another program with exactly same angle function is

import math
class Vector(object):
    def __init__(self,coordinates):
        try:
            if not coordinates:
                raise ValueError
                #if coordinates is not passed then it will rise Value Error
            self.coordinates = tuple(coordinates)
            #Outside Class :-Vector.coordinates will give print vectors in tuple form
            #Inside Class :- self.coordinates will print vectors in tuple form
            self.dimension = len(coordinates)
            #Outside Class :-Vector.dimension will print vectors dimension/size
            #Inside Class :- self.dimension will print vectors dimension/size
        except ValueError:
            raise ValueError('The coordinates must be non empty')
        except TypeError:
            raise TypeError('The coordinates must be itterable')
    def __str__(self):
        return 'Vector:{}'.format(self,coordinates)
    def __eq__(self,v):
        return self.coordinates == v.coordinates
    def add (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]+v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def mul(self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]*v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def sub (self,v):
        coordinates=[]
        for i in range(0,self.dimension):
            i=self.coordinates[i]-v.coordinates[i]
            coordinates.append(i)
        return coordinates

    def scal_mul(self,s):
        coordinates=[]
        for i in self.coordinates:
            i=i*s
            coordinates.append(i)
        return coordinates
    def magnitude(self):
        mag = 0
        for i in self.coordinates:
            i=i*i
            mag =mag+i
        return math.sqrt(mag)

    def magnitude1(self):
        mag = 0
        coordinate_squre=[i*i for i in self.coordinates]
        return math.sqrt(sum(coordinate_squre))

    def normalize(self):
        try:
            recip = 1/self.magnitude()
            return Vector(self.scal_mul(recip))
        except ZeroDivisionError:
            raise Exception("Can not Normalize Zero Vector")

    def dot_product(self,v):
        mul = self.mul(v)
        return sum(mul)

    def dot_product2(self,v):
        self.mul = [x*y for x,y in zip(self.coordinates,v.coordinates)]
        return sum(self.mul)
    #-----------------angle functionn is giving wrong answer-------------
    def angle_rad(self,v):
        norm = self.normalize()
        angle = 1/ math.cos(norm.dot_product2(v))
        return angle

    def angle(self,v,in_degree=False):
        nrm_self = self.normalize()
        nrm_v = v.normalize()
        angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
        if in_degree:
            angle_in_degree = angle_rad * 180./math.pi
            return angle_in_degree
        else:
            return angle_rad

v1 = Vector([7.887,4.138])
v2 = Vector([-8.802,6.776])
print(v1.angle(v2))
v1 = Vector([-7.579,-7.88])
v2 = Vector([22.737,23.64])
v2.angle(v1)

it is giving Error as following

2.0023426999774925

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-214-2e3bee12967a> in <module>()
     95 v1 = Vector([-7.579,-7.88])
     96 v2 = Vector([22.737,23.64])
---> 97 v2.angle(v1)
     98

<ipython-input-214-2e3bee12967a> in angle(self, v, in_degree)
     82         nrm_self = self.normalize()
     83         nrm_v = v.normalize()
---> 84         angle_rad = math.acos(nrm_self.dot_product2(nrm_v))
     85         if in_degree:
     86             angle_in_degree = angle_rad * 180./math.pi

ValueError: math domain error

We can see they are having same angle function


问:
is there any builtin javascript string hash function in newest browsers?
Everytime a new versions of browsers show up I hear about new stuff being added, like say webGL and other technologies that no one really knows if they catch up.

But I wonder if someone ever thought about such basic stuff in JS like hashing functions (MD5,SHA1 and the like).

By newest browsers I mean today's development versions too like Opera 12, Chrome 17 or Firefox 10.

Looking now for solution I found this comment on another thread here: https://stackoverflow.com/questions/7204097/short-hashing-function-for-javascript (Do you know that javascript objects already are hashtables ?). So what are these 'hashtables' ? Does it mean that I can make any string into a hash, but not an established one like md5 or sha1 but some JS build in specific ?

basically what I need to do is:

```<code>var txt="Hello world!";
var hash = txt.toSha1();
</code>```

答:
For anybody still looking for this information. There is a WebCrypto API which appears to have been finalised at the beginning of 2017.

To use it in a browser, you can find it at window.crypto.subtle which contains methods for encryption, digests etc. Documentation on the available functions here.

Body:
Everytime a new versions of browsers show up I hear about new stuff being added, like say webGL and other technologies that no one really knows if they catch up.

But I wonder if someone ever thought about such basic stuff in JS like hashing functions (MD5,SHA1 and the like).

By newest browsers I mean today's development versions too like Opera 12, Chrome 17 or Firefox 10.

Looking now for solution I found this comment on another thread here: https://stackoverflow.com/questions/7204097/short-hashing-function-for-javascript (Do you know that javascript objects already are hashtables ?). So what are these 'hashtables' ? Does it mean that I can make any string into a hash, but not an established one like md5 or sha1 but some JS build in specific ?

basically what I need to do is:

var txt="Hello world!";
var hash = txt.toSha1();


问:
How does one yank a function call in vim?
Suppose a line of text reads:

```
$x = ( frobnicate( foo( bar( $x, $y )[ 1 ]))[ 1 ]);
```

The cursor is on the 'f' of 'frobnicate' and I want to yank the text which includes the call to frobnicate.  (That is, everything up to the 3rd closing parenthesis.  I can certainly do:

```
y3f)
```

or do it interactively with

```
vf);;y
```

but neither of these is appealing.  (I don't want to have to count the '3' manually, nor do the repeated find until I hit the end point.)  Is there an easy way to accomplish the move from 'f' to the matching closing paren?  I'm thinking something like the v_i 'inner word' motion command.

答:
You could try yel% to position the cursor to the opening parentheses and then jump to the closing one with %, but it does not look much more efficient than your current solution.

The only advantage is that you don't have to count anything, and it works with nested call.

Edit :
as pointed by Peter, y% works and is a superior solution (even if I don't quite understand why it works. Vim is amazing!)

Body:
Suppose a line of text reads:

$x = ( frobnicate( foo( bar( $x, $y )[ 1 ]))[ 1 ]);

The cursor is on the 'f' of 'frobnicate' and I want to yank the text which includes the call to frobnicate.  (That is, everything up to the 3rd closing parenthesis.  I can certainly do:

y3f)

or do it interactively with

vf);;y

but neither of these is appealing.  (I don't want to have to count the '3' manually, nor do the repeated find until I hit the end point.)  Is there an easy way to accomplish the move from 'f' to the matching closing paren?  I'm thinking something like the v_i 'inner word' motion command.


问:
Apach Nifi revert flowfile attribute
In my Nifi 1.3.0 dataflow the FetchElasticsearchHttp processor changes the filename attribute to its corresponding ID in the database. I was wondering if there was a way of changing it back using some of Nifi's in house processors.

I have thought about simply writing my own script to correct this but there seems to be no way of knowing what file it is so I can't just grab its name.

答: if I understood you correctly, you can use UpdateAttribute to copy the filename attribute to another property. There's no way to stop the processor from writing its properties, but you can surely stash it away yourself. The trick is to copy/rename before invoking the fetch processor.</p>

Title: Apach Nifi revert flowfile attribute


问:
Why does adding a comment change compiled code (object) and executable in C++
I've started to add some doxygen comments to my code but I see that some comments change object code and also the linked executable in Visual C++.

I used objdump to catch the differences. I expect date and checksum differences but no more. However, adding a comment line to a doxygen style comment on a method changes object code and the executable.

Do you have any idea what can be the cause of this weird behaviour or is there another method that I can verify no changes in executable after adding those comments?

Cheers,
Burak

答: If you are compiling with debugging symbols, then the comments will cause the line references to move around.  </p>


问:
Clear Chrome browser logs in Selenium/Python
I have a large application and I am using Headless Chrome, Selenium and Python to test each module. I want to go through each module and get all the JS console errors produced while inside that specific module.

However, since each module is inside a different test case and each case executes in a separate session, the script first has to login on every test. The login process itself produces a number of errors that show up in the console. When testing each module I don't want the unrelated login errors to appear in the log.

Basically, clear anything that is in the logs right now -> go to the module and do something -> get logs that have been added to the console.

Is this not possible? I tried doing driver.execute_script("console.clear()") but the messages in the console were not removed and the login-related messages were still showing after doing something and printing the logs.

答:
State in 2017 and late 2018

The logging API is not part of the official Webdriver specification yet.

In fact, it's requested to be defined for the level 2 specification. In mid 2017 only the Chromedriver has an undocumented non-standard implementation of that command.

In the sources there's no trace of a method for clearing logs:

The public API Webdriver.get_log()

which references internal Command names

which translate to acutal requests in RemoteConnection

Possible Workaround

The returned (raw) data structure is a dictionary that looks like this:

```<code>{
    u'source': u'console-api',
    u'message': u'http://localhost:7071/console.html 8:9 "error"',
    u'timestamp': 1499611688822,
    u'level': u'SEVERE'
}
</code>```

It contains a timestamp that can be remembered so that subsequent calls to get_log() may filter for newer timestamps.

Facade

```<code>class WebdriverLogFacade(object):

    last_timestamp = 0

    def __init__(self, webdriver):
        self._webdriver = webdriver

    def get_log(self):
        last_timestamp = self.last_timestamp
        entries = self._webdriver.get_log("browser")
        filtered = []

        for entry in entries:
            # check the logged timestamp against the
            # stored timestamp
            if entry["timestamp"] > self.last_timestamp:
                filtered.append(entry)

                # save the last timestamp only if newer
                # in this set of logs
                if entry["timestamp"] > last_timestamp:
                    last_timestamp = entry["timestamp"]

        # store the very last timestamp
        self.last_timestamp = last_timestamp

        return filtered
</code>```

Usage

```<code>log_facade = WebdriverLogFacade(driver)
logs = log_facade.get_log()

# more logs will be generated

logs = log_facade.get_log()
# newest log returned only
</code>```

Body:
State in 2017 and late 2018

The logging API is not part of the official Webdriver specification yet.

In fact, it's requested to be defined for the level 2 specification. In mid 2017 only the Chromedriver has an undocumented non-standard implementation of that command.

In the sources there's no trace of a method for clearing logs:

The public API Webdriver.get_log()

which references internal Command names

which translate to acutal requests in RemoteConnection

Possible Workaround

The returned (raw) data structure is a dictionary that looks like this:

{
    u'source': u'console-api',
    u'message': u'http://localhost:7071/console.html 8:9 "error"',
    u'timestamp': 1499611688822,
    u'level': u'SEVERE'
}

It contains a timestamp that can be remembered so that subsequent calls to get_log() may filter for newer timestamps.

Facade

class WebdriverLogFacade(object):

    last_timestamp = 0

    def __init__(self, webdriver):
        self._webdriver = webdriver

    def get_log(self):
        last_timestamp = self.last_timestamp
        entries = self._webdriver.get_log("browser")
        filtered = []

        for entry in entries:
            # check the logged timestamp against the
            # stored timestamp
            if entry["timestamp"] > self.last_timestamp:
                filtered.append(entry)

                # save the last timestamp only if newer
                # in this set of logs
                if entry["timestamp"] > last_timestamp:
                    last_timestamp = entry["timestamp"]

        # store the very last timestamp
        self.last_timestamp = last_timestamp

        return filtered

Usage

log_facade = WebdriverLogFacade(driver)
logs = log_facade.get_log()

# more logs will be generated

logs = log_facade.get_log()
# newest log returned only

ContentLicense: CC BY-SA 4.0


问:
Sklearn syntax error?
I am learning by this site(https://pythonprogramming.net/training-testing-machine-learning-tutorial/), part 4. This is my code(copied, with Quandl having lowercase q as is correct in newer version and model_selection instead of cross_validation for same reason).

```<code>import quandl, math
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import model_selection
from sklearn import svm
from sklearn.linear_model import LinearRegression

df = quandl.get("WIKI/GOOGL")
print(df.head())
print(df.tail())
df = df[['Adj. Open',  'Adj. High',  'Adj. Low',  'Adj.
             Close', 'Adj. Volume']]

df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) /
df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /
    df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj.
   Volume']]
print(df.head())
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
df.dropna(inplace=True)
X = np.array(df.drop(['label'], 1))
y = np.array(df['label'])
X = preprocessing.scale(X)
y = np.array(df['label'])
X_train, X_test, y_train, y_test =
    model_selection.train_test_split(X, y, test_size=0.2)

clf = svm.SVR()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
print(confidence)
</code>```

Error is:

```<code>Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\PycharmProjects\learn_python_the_hard_way\scipy.py", line 1
    from scip
            ^
SyntaxError: invalid syntax
</code>```

I don't have any idea how to solve this, any help will be greatly appreciated!

UPDATE:
I had scipy.py file created for doing scipy exercises in same file as is the one I'm practicing right now and now deleted it. Error is:

```<code>Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name 'NUMPY_MKL'
</code>```

I checked, numpy is installed and working!

答: SOLVED: altought numpy was install I had to specificaly install wheel for numpy+mkl</p>

Title: Sklearn syntax error?

Body:
I am learning by this site(https://pythonprogramming.net/training-testing-machine-learning-tutorial/), part 4. This is my code(copied, with Quandl having lowercase q as is correct in newer version and model_selection instead of cross_validation for same reason).

import quandl, math
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import model_selection
from sklearn import svm
from sklearn.linear_model import LinearRegression

df = quandl.get("WIKI/GOOGL")
print(df.head())
print(df.tail())
df = df[['Adj. Open',  'Adj. High',  'Adj. Low',  'Adj.
             Close', 'Adj. Volume']]

df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) /
df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /
    df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj.
   Volume']]
print(df.head())
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
df.dropna(inplace=True)
X = np.array(df.drop(['label'], 1))
y = np.array(df['label'])
X = preprocessing.scale(X)
y = np.array(df['label'])
X_train, X_test, y_train, y_test =
    model_selection.train_test_split(X, y, test_size=0.2)

clf = svm.SVR()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
print(confidence)

Error is:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\PycharmProjects\learn_python_the_hard_way\scipy.py", line 1
    from scip
            ^
SyntaxError: invalid syntax

I don't have any idea how to solve this, any help will be greatly appreciated!

UPDATE:
I had scipy.py file created for doing scipy exercises in same file as is the one I'm practicing right now and now deleted it. Error is:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name 'NUMPY_MKL'

I checked, numpy is installed and working!