问:
How to keep my image caption grid floating correctly with different sized text content
I have an issue here where if a caption is too long, if it extends beyond one line it causes the elements following to not float correctly. I would like to have it, so that no matter on the content of the caption, the following row adjusts to the space. I have seen another site achieve something very similar.

I can't work out what else I need.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

CSS Tricks say:

The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats

Reading this, I set the container div.project-thumbnail, but no change:

```<code>.project-thumbnail {
  overflow: auto
}
</code>```

jsFiddle

EDIT

As the comment suggests, setting a height to the caption div div.thumb would enable it to float correctly. A fixed height will cut off content that becomes too big for it. Adding overflow: auto to this div will just add a scrollbar to it, this is not what I am after.

EDIT

This site here has a similar system. Items with a width are floated, no row separator, but if the content within their div extends beyond a few lines, the bottom of the div will adjust, aligning the next row neatly.

答:
First solution

This is what you are looking for,  you have to add just one rule to your css,

```<code>.row article:nth-child(3n+1){
    clear: left;
}
</code>```

.row article:nth-child(3n+1){
 clear: left;
}
body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

Second solution : inline block display

Fluid, scalable easy to grasp

I prefer this solution, using display:inline-block which is straightforward and works fine now for IE. The only downfall is the white spaces between the markup(which I've chosen to delete them here).

I've just taken liberty to modify your code so you can find what just the modifications.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 display: inline-block;
 vertical-align: top;
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

Third solution: grid layout

Very cool powerful modern CSS feature, you can get some more info here

body {
 padding: 0;
 margin: 0 auto;
}

body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}

.constraint {
 /*! padding-right: 2%; */
 /*! padding-left: 2%; */
 margin-right: auto;
 margin-left: auto;
 width: 100%;
}
.col-4 {
 /*! width: 33.33333333% */
}
.columns {
 padding-left: 25px;
 padding-right: 25px;
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto;
 display: grid;
 grid-template-columns: 1fr 1fr 1fr;
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

Body:
I have an issue here where if a caption is too long, if it extends beyond one line it causes the elements following to not float correctly. I would like to have it, so that no matter on the content of the caption, the following row adjusts to the space. I have seen another site achieve something very similar.

I can't work out what else I need.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

Box One

Item preview

Box One

Item preview with some content that makes it extend onto another line.

Box One

Item preview

Box One

Item preview

Box One

Item preview

Box One

Item preview

CSS Tricks say:

The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats

Reading this, I set the container div.project-thumbnail, but no change:

.project-thumbnail {
  overflow: auto
}

jsFiddle

EDIT

As the comment suggests, setting a height to the caption div div.thumb would enable it to float correctly. A fixed height will cut off content that becomes too big for it. Adding overflow: auto to this div will just add a scrollbar to it, this is not what I am after.

EDIT

This site here has a similar system. Items with a width are floated, no row separator, but if the content within their div extends beyond a few lines, the bottom of the div will adjust, aligning the next row neatly.

Body:
First solution

This is what you are looking for,  you have to add just one rule to your css,

.row article:nth-child(3n+1){
    clear: left;
}

.row article:nth-child(3n+1){
 clear: left;
}
body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

<div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div>

Second solution : inline block display

Fluid, scalable easy to grasp

I prefer this solution, using display:inline-block which is straightforward and works fine now for IE. The only downfall is the white spaces between the markup(which I've chosen to delete them here).

I've just taken liberty to modify your code so you can find what just the modifications.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 display: inline-block;
 vertical-align: top;
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

<div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article><article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div>

Third solution: grid layout

Very cool powerful modern CSS feature, you can get some more info here

body {
 padding: 0;
 margin: 0 auto;
}

body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}

.constraint {
 /*! padding-right: 2%; */
 /*! padding-left: 2%; */
 margin-right: auto;
 margin-left: auto;
 width: 100%;
}
.col-4 {
 /*! width: 33.33333333% */
}
.columns {
 padding-left: 25px;
 padding-right: 25px;
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto;
 display: grid;
 grid-template-columns: 1fr 1fr 1fr;
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
}

<div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div>


来源: stackexchange

问:
Pandas merge issue on key of object type containing number and string values
I have two dataframes df1 and df2 as shown below:-

```<code>df1 = pd.DataFrame({'x': [1, '3', 5,'t','m','u'],'y':[2, 4, 6, 4, 4, 8]})

df2 = pd.DataFrame({'x': [1, 3, '4','t'],'z':[2, 4, 6,7]})
</code>```

I am trying to merge(left join) the two data frames as:-

```<code>df=pd.merge(df1, df2, how='left', on='x')
</code>```

the output is:-

```<code>df
Out[25]:
   x  y    z
0  1  2  2.0
1  3  4  NaN
2  5  6  NaN
3  t  4  7.0
4  m  4  NaN
5  u  8  NaN
</code>```

Clearly for second row above i.e for x=3, I would like to have z=4 instead of NaN.Is there an option to define data type of the key during merge or any other workaround where I can change the dtype of the keys to string in both data frames and get the desired output.

答:
You can use assign to temporarily assign new dtype to the x column:

```<code>pd.merge(df1.assign(x=df1.x.astype(str)),
         df2.assign(x=df2.x.astype(str)),
         how='left', on='x')
</code>```

Output:

```<code>   x  y    z
0  1  2  2.0
1  3  4  4.0
2  5  6  NaN
3  t  4  7.0
4  m  4  NaN
5  u  8  NaN
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two dataframes df1 and df2 as shown below:-

df1 = pd.DataFrame({'x': [1, '3', 5,'t','m','u'],'y':[2, 4, 6, 4, 4, 8]})

df2 = pd.DataFrame({'x': [1, 3, '4','t'],'z':[2, 4, 6,7]})

I am trying to merge(left join) the two data frames as:-

df=pd.merge(df1, df2, how='left', on='x')

the output is:-

df
Out[25]:
   x  y    z
0  1  2  2.0
1  3  4  NaN
2  5  6  NaN
3  t  4  7.0
4  m  4  NaN
5  u  8  NaN

Clearly for second row above i.e for x=3, I would like to have z=4 instead of NaN.Is there an option to define data type of the key during merge or any other workaround where I can change the dtype of the keys to string in both data frames and get the desired output.

Body:
You can use assign to temporarily assign new dtype to the x column:

pd.merge(df1.assign(x=df1.x.astype(str)),
         df2.assign(x=df2.x.astype(str)),
         how='left', on='x')

Output:

   x  y    z
0  1  2  2.0
1  3  4  4.0
2  5  6  NaN
3  t  4  7.0
4  m  4  NaN
5  u  8  NaN


问:
SAS search multiple values in a string
I have two SAS datasets with (assume for simplicity) one char variable in each. The first dataset has a variable with company description (sometimes including city, sometimes not; a messy field) and a second dataset has a variable, where all cities are listed. I need to create variable in a first dataset saying, if any of the cities from 2nd dataset was found or not and the outcome should not contain just 0 or 1 answers, but the city itself.
Is there an easy way to do it without looping INDEXW (or similar) functions?</p>

答:
What's wrong with indexw?  Using proc sql and indexw allows a pretty straightforward solution.

Sample data:

```<code>data have_messy;
  length messy $100;
  messy = 'this is a city name: brisbane' ; output;
  messy = 'this is a city name: sydney'   ; output;
  messy = 'this is a city name: melbourne'; output;
run;

data have_city;
  length city $20;
  city = 'sydney'  ; output;
  city = 'brisbane'; output;
run;
</code>```

Example query:

```<code>proc sql noprint;
  create table want as
  select a.*,
         b.city
  from have_messy a
  left join have_city  b on indexw(a.messy, b.city)
  ;
quit;
</code>```

Results:

```<code>messy                               city
===============================     =========
this is a city name: sydney         sydney
this is a city name: brisbane       brisbane
this is a city name: melbourne
</code>```

Be careful - the above query can return multiple results per row in table a if multiple city names are found.  I suggest you run a follow up step to handle any duplicate rows depending on your requirements.

Title: SAS search multiple values in a string

Body:
What's wrong with indexw?  Using proc sql and indexw allows a pretty straightforward solution.

Sample data:

data have_messy;
  length messy $100;
  messy = 'this is a city name: brisbane' ; output;
  messy = 'this is a city name: sydney'   ; output;
  messy = 'this is a city name: melbourne'; output;
run;

data have_city;
  length city $20;
  city = 'sydney'  ; output;
  city = 'brisbane'; output;
run;

Example query:

proc sql noprint;
  create table want as
  select a.*,
         b.city
  from have_messy a
  left join have_city  b on indexw(a.messy, b.city)
  ;
quit;

Results:

messy                               city
===============================     =========
this is a city name: sydney         sydney
this is a city name: brisbane       brisbane
this is a city name: melbourne

Be careful - the above query can return multiple results per row in table a if multiple city names are found.  I suggest you run a follow up step to handle any duplicate rows depending on your requirements.


问:
Deleted database still shows in database list in PostgreSQL SQLmanager
Using PostgreSQL 9.4.12, I created a new database called new_db and before adding any table or any other object to it and probably before registering it (I don't remember if I've registered or not), I dropped it. Now, it still shows in database list in SQLmanager:

and when I attempt to drop it via following query:

```<code>drop database new_db;
</code>```

it says:

```<code>database doesn't exist
</code>```

But when I open 'database registration manager', it lists 'new_db' and shows the register check box as marked:

and when I try to remove the mark and apply the changes it displays an error that isn't relevant to the 'new_db' database.

Following query also results 0 rows:

```<code>select oid, * from pg_database where datname like
   'new_db';
</code>```

How can I remove the database from the list in SQLmanager?

答: SQL Manager creates new_db (asdefault anme) on first connection. After that it registers it. If you just drop database and don't unregister it the "alias" remains. You have to right click on new_db and "unregister database"</p>

Body:
Using PostgreSQL 9.4.12, I created a new database called new_db and before adding any table or any other object to it and probably before registering it (I don't remember if I've registered or not), I dropped it. Now, it still shows in database list in SQLmanager:

and when I attempt to drop it via following query:

drop database new_db;

it says:

database doesn't exist

But when I open 'database registration manager', it lists 'new_db' and shows the register check box as marked:

and when I try to remove the mark and apply the changes it displays an error that isn't relevant to the 'new_db' database.

Following query also results 0 rows:

select oid, * from pg_database where datname like
   'new_db';

How can I remove the database from the list in SQLmanager?


问:
C++ - structs... function parameter issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

It has the following code:

```<code>// Declare a DateStruct variable
DateStruct sToday;

// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;

// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;
}

// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);
</code>```

What is the purpose of the

DateStruct &sDate

parameter in the function signature, especially that I cannot see a use of it in the function body?

Thanks.

答: It means a reference to an existing DateStruct instance.</p>

ContentLicense: CC BY-SA 2.5

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

It has the following code:

// Declare a DateStruct variable
DateStruct sToday;

// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;

// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;
}

// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);

What is the purpose of the

DateStruct &sDate

parameter in the function signature, especially that I cannot see a use of it in the function body?

Thanks.


问:
Un-expected output from is_numeric / foreach routine
Ref: http://php.net/manual/en/function.is-numeric.php.

Example #1 is_numeric().

Why does the Example #1 routine output 1337 4 times instead of 1 time?  My expectation is the routine would ouput the other 3 numeric values that follow 1337.  Even if I re-arrange the order of the elements it still outputs 1337 4 times.  I understand hex and binary values are not allowed, but why does the routine output 1337 for those values.  Also, if I change 1337 to 01337 the ouput is 735.

Why these confusing outputs?

```<code><?php
$tests = array(
    "42", 1337, 0x539, 02471, 0b10100111001, 1238.443e2, "not numeric",
    array(), 9.1, null
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>

Output:
'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
123844.300000000002910383045673370361328125 is numeric
'not numeric' is NOT numeric
array () is NOT numeric
9.0999999999999996447286321199499070644378662109375 is numeric
NULL is NOT numeric
</code>```

答:
Base-N notation syntax

which you had to know to pull this off

Hexadecimal

A number prefixed with 0x will be interpreted as base-16

Octtal

A number prefixed with 0 will be interpreted as base-8

Binary

A number prefixed with 0b will be interpreted as base-2

Conversion to Decimal

1337 base10 (base10 value: 1337)

0x539 base16 (base10 value: 1337)

02471 base8 (base10 value: 1337)

0b10100111001 base2 (base10 value: 1337)

Numbers in strings are always shown in base-10

Converting these numbers to a string, as with var_export, will convert them to base-10, unless you use number_format.

Body:
Ref: http://php.net/manual/en/function.is-numeric.php.

Example #1 is_numeric().

Why does the Example #1 routine output 1337 4 times instead of 1 time?  My expectation is the routine would ouput the other 3 numeric values that follow 1337.  Even if I re-arrange the order of the elements it still outputs 1337 4 times.  I understand hex and binary values are not allowed, but why does the routine output 1337 for those values.  Also, if I change 1337 to 01337 the ouput is 735.

Why these confusing outputs?

<?php
$tests = array(
    "42", 1337, 0x539, 02471, 0b10100111001, 1238.443e2, "not numeric",
    array(), 9.1, null
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>

Output:
'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
123844.300000000002910383045673370361328125 is numeric
'not numeric' is NOT numeric
array () is NOT numeric
9.0999999999999996447286321199499070644378662109375 is numeric
NULL is NOT numeric


问:
org.openqa.selenium.MutableCapabilities not available?
I don't seem to have org.openqa.selenium.MutableCapabilities available in my version of Selenium. I'm using version 2.53.0.

I'm trying to use Selenium standalone server in a Grails project and the application is crashing on this line:

```<code> ChromeOptions options = new ChromeOptions()
</code>```

I have a feeling this may be the cause. Any help greatly appreciated.

答:
MutableCapabilities

MutableCapabilities was introduced for the first time with the availability of Selenium (Java Client) v3.6.0

Here is the snapshot from the Selenium (Java Client) v3.6.0 Release Notes:

All Option classes now extend MutableCapbilities
    new RemoteWebDriver(new ChromeOptions());

With the availability of Selenium (Java Client) v3.7.0 we migrated from using DesiredCapabilities to either
  MutableCapabilities or (preferably) ImmutableCapabilities.

Here is the snapshot from the Selenium (Java Client) v3.7.0 Release Notes:

Migrated from using DesiredCapabilities to either
    MutableCapabilities or (preferably) ImmutableCapabilities.

org.openqa.selenium.MutableCapabilities

Here is the JavaDoc link of org.openqa.selenium.MutableCapabilities

Body:
I don't seem to have org.openqa.selenium.MutableCapabilities available in my version of Selenium. I'm using version 2.53.0.

I'm trying to use Selenium standalone server in a Grails project and the application is crashing on this line:

 ChromeOptions options = new ChromeOptions()

I have a feeling this may be the cause. Any help greatly appreciated.


问:
Detect timestamp of position of object detected from an mp4 video using OpenCV in Python
I am trying to detect objects from an mp4 video file using OpenCV in Python. I am able to detect the objects in the video.

I would like to get the timestamp of the position at which the object was detected in the video file and write it to a text file.

Here is my code so far:

```<code>import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
    toys= my_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in toys:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        #Logic to write time stamp to file goes here
    return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    cv2.imshow('Video', canvas)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()
</code>```

I tried to use VideoCapture's method get() using property identifier like this:

```<code> video_capture.get(CV_CAP_PROP_POS_MSEC)
</code>```

but get an error name 'CV_CAP_PROP_POS_MSEC' is not defined

Seems like cv2 does not have this method or property identifier implemented.

Is there any other way in cv2 to implement what I want?

Please help.

SOLVED

This will print timestamp of the position of object everytime it is detected in the video.
Here is the working code:

```<code>import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
    toys= my_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in toys:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        print("Toy Detected at: "+str(video_capture.get(cv2.CAP_PROP_POS_MSEC)))
    return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    cv2.imshow('Video', canvas)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()
</code>```

答:
cv2 does have the property implemented, but the full name needs to be used.

This should work

```<code>import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
    toys= my_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in toys:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        #Logic to write time stamp to file goes here
    return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    print (video_capture.get(cv2.CAP_PROP_POS_MSEC))
    cv2.imshow('Video', canvas)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()
</code>```

i.e. you want the property of the instance video_capture not the generic class VideoCapture and the property name is prefixed by the class cv2.. The property name is either CAP_PROP_POS_MSECor CV_CAP_PROP_MSEC - depending on the OpenCV version (see Can't get VideoCapture property as the property identifier are not defined ).

Body:
I am trying to detect objects from an mp4 video file using OpenCV in Python. I am able to detect the objects in the video.

I would like to get the timestamp of the position at which the object was detected in the video file and write it to a text file.

Here is my code so far:

import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
    toys= my_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in toys:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        #Logic to write time stamp to file goes here
    return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    cv2.imshow('Video', canvas)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

I tried to use VideoCapture's method get() using property identifier like this:

 video_capture.get(CV_CAP_PROP_POS_MSEC)

but get an error name 'CV_CAP_PROP_POS_MSEC' is not defined

Seems like cv2 does not have this method or property identifier implemented.

Is there any other way in cv2 to implement what I want?

Please help.

SOLVED

This will print timestamp of the position of object everytime it is detected in the video.
Here is the working code:

import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
    toys= my_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in toys:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        print("Toy Detected at: "+str(video_capture.get(cv2.CAP_PROP_POS_MSEC)))
    return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    cv2.imshow('Video', canvas)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

Body:
cv2 does have the property implemented, but the full name needs to be used.

This should work

import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
    toys= my_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in toys:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        #Logic to write time stamp to file goes here
    return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    print (video_capture.get(cv2.CAP_PROP_POS_MSEC))
    cv2.imshow('Video', canvas)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

i.e. you want the property of the instance video_capture not the generic class VideoCapture and the property name is prefixed by the class cv2.. The property name is either CAP_PROP_POS_MSECor CV_CAP_PROP_MSEC - depending on the OpenCV version (see Can't get VideoCapture property as the property identifier are not defined ).


问:
Decoding H264 using random access
I want to access random frames in a H264 file and map the decoded images to a Direct3D texture. I am using the the NVIDIA VIDEO CODEC SDK. I've already found the NvDecodeD3D11 sample that was included in version 8.0 and have stripped it down to the bear essentials.

Basically I want to achieve the same idea as proposed in: decoding H264 from middle of the file.

My file can be IDR frames only, but can also include P-frames.

Easy access to the sample: Github

I understand the idea in the linked question, but I don't know where and how to implement this.

答: Great question, and I am afraid it requires a lot of work. You have to get familiar with the I and P frame format exactly. Next, you will figure out how to search for the header of frames, and form a buffer with pointers to the I frame header starts. After that, you will have to devise the system that will be used as a regular play by doing play while going from pointer that marks the current frame, or will be able to go fast forward or backwards, by rewinding the buffer pointer indices. Study this, and you will be able to find the solution. It is highly likely that there is already open source code for this, but that requires more search. You may try to put a bounty on this.</p>

Title: Decoding H264 using random access


问:
How to initialize a static variable in a multithreaded context?
I thought up a good use of the static keyword inside a function to be something like this:

```<code>void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}
</code>```

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

答:
One approach is to use a global lock to serialize the initialization paths. You'll need a portable wrapper over a SMP memory barrier however; the acquire barrier implied by the lock is not sufficient, as it, in principle, allows the compiler and/or CPU to cache the results of memory reads from before the lock acquisition. Here's an example:

```<code>Lock global_init_lock; // Should have low contention, as it's only used during startup

void somefunc() {
    static void *data;
    static long init_flag = 0;
    if (!init_flag) { // fast non-atomic compare for the fast path
        global_init_lock.Lock();
        read_memory_barrier(); // make sure we re-read init_flag
        if (!init_flag)
            data = init_data();
        write_memory_barrier(); // make sure data gets committed and is visible to other procs
        init_flag = 1;
        global_init_lock.Unlock();
    }
    read_memory_barrier(); // we've seen init_flag = 1, now make sure data is visible
    // ....
}
</code>```

That said, I would recommend putting the locks with the data, not with the functions that act on the data. After all, how do you intend to synchronize readers like this? What if you want to use separate locks for separate arrays later? And what if you want to write other functions that take that lock later down the road?

Body:
I thought up a good use of the static keyword inside a function to be something like this:

void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

Body:
One approach is to use a global lock to serialize the initialization paths. You'll need a portable wrapper over a SMP memory barrier however; the acquire barrier implied by the lock is not sufficient, as it, in principle, allows the compiler and/or CPU to cache the results of memory reads from before the lock acquisition. Here's an example:

Lock global_init_lock; // Should have low contention, as it's only used during startup

void somefunc() {
    static void *data;
    static long init_flag = 0;
    if (!init_flag) { // fast non-atomic compare for the fast path
        global_init_lock.Lock();
        read_memory_barrier(); // make sure we re-read init_flag
        if (!init_flag)
            data = init_data();
        write_memory_barrier(); // make sure data gets committed and is visible to other procs
        init_flag = 1;
        global_init_lock.Unlock();
    }
    read_memory_barrier(); // we've seen init_flag = 1, now make sure data is visible
    // ....
}

That said, I would recommend putting the locks with the data, not with the functions that act on the data. After all, how do you intend to synchronize readers like this? What if you want to use separate locks for separate arrays later? And what if you want to write other functions that take that lock later down the road?


问:
/../ in PHP After ['DOCUMENT_ROOT']
I am working on Contact form , and i found a strange code.

```<code>$request_method = $_SERVER["REQUEST_METHOD"];
    if($request_method == "GET"){
      $query_vars = $_GET;
    } elseif ($request_method == "POST"){
      $query_vars = $_POST;
    }
    reset($query_vars);
    $t = date("U");

    $file = $_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t;
    $fp = fopen($file,"w");
    while (list ($key, $val) = each ($query_vars)) {
     fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
     fputs($fp,"$val\n");
     fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
     if ($key == "redirect") { $landing_page = $val;}
    }
    fclose($fp);
</code>```

The line

```<code>$file = $_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t;
</code>```

Confused me where should i go to get a gdform.php file , and to pass a new filed variable.

Looking forward for your inputs.

Thanks

答:
if you directory structure is as follows:

```<code>html
..data
..webroot
</code>```

$_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t; will take you to the data directory. So, it means one level up

Title: /../ in PHP After ['DOCUMENT_ROOT']

Body:
I am working on Contact form , and i found a strange code.

$request_method = $_SERVER["REQUEST_METHOD"];
    if($request_method == "GET"){
      $query_vars = $_GET;
    } elseif ($request_method == "POST"){
      $query_vars = $_POST;
    }
    reset($query_vars);
    $t = date("U");

    $file = $_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t;
    $fp = fopen($file,"w");
    while (list ($key, $val) = each ($query_vars)) {
     fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
     fputs($fp,"$val\n");
     fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
     if ($key == "redirect") { $landing_page = $val;}
    }
    fclose($fp);

The line

$file = $_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t;

Confused me where should i go to get a gdform.php file , and to pass a new filed variable.

Looking forward for your inputs.

Thanks

Body:
if you directory structure is as follows:

html
..data
..webroot

$_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t; will take you to the data directory. So, it means one level up


问:
Adding a navigation drawer to an existing project
I'm a beginner in Android. I have a project with multiple activities and I need to add a navigation drawer to this project instead of a normal menu. I added a new navigation drawer activity, but it doesn't show in my previous activities.

Should I add something to my existing activities?

All the tutorials I have watch use fragment while I use AppCompatActivity.

So I don't know how can I add it to my project.

Can you help me, please?

答: to do that, you have to use fragments instead of activities. fragments are easier to work with navigation drawers than activities. 1st you have to create a main activity for navigation drawer. Change your other activities to fragments. Then you can have navigation drawer in all the fragments. Refer below video it has everything you want. if there is any problem ask. https://www.youtube.com/watch?v=-SUvA1fXaKw</p>


问:
Adding Skype for Business scope to v2.0 Azure app
I am creating a v2.0 application via the new Microsoft Application Registration Portal (apps.dev.microsoft.com) and I can't find where to add scopes for other non-Graph APIs. Specifically Skype for Business.

In the classic Azure portal, i had access to this screen which allowed me to add scopes for other APIs:

In the new Application Registration Portal, the only place I see to add scopes is here:

and Skype for Business is not an option there.

How do I add the Skype for Business scope to v2.0 apps?

答:
The Skype for Business APIs (Web SDK, UCMA, UCWA, etc.) currently do not support the v2 Endpoint.

At the moment the majority of Microsoft APIs do not support the v2 Endpoint. Given the enormous legacy of APIs Microsoft supports, there unfortunately isn't an exhaustive list. Generally, unless the API documentation expressly states support for the v2 Endpoint or Converged Authentication it means you'll need to use the v1 Endpoint.

One aside on permissions with the v2 Endpoint. With the v1 Endpoint you requests access by "resource" and pre-defined the permissions you required within the Azure Portal. The v2 Endpoint no longer uses resources however; it now uses "scopes" that are dynamically defined during the authentication workflow. For more details see Scopes, not resources.

I'd recommend adding this request to the UserVoice site. This will help ensure this remains on product teams radar going forward.


问:
Page refreshing after the parameter selection in SSRS report
I have couple of parameters in my SSRS report. some are multivalued and some are regular with drop down list. each time while selecting a different parameter value the page is getting refreshed. Is there any way to avoid this  page refreshment on each parameter selection.

Thanks in advance.
Maria

答:
For me this was resolved by disabling X-Content-Type-Options: nosniff custom header in the web.config.

<customHeaders>
   <add name="X-Frame-Options" value="SAMEORIGIN" />

    <add name="X-XSS-Protection" value="1; mode=block" />
</customHeaders>```

OwnerDisplayName: san

Body:
For me this was resolved by disabling X-Content-Type-Options: nosniff custom header in the web.config.

<customHeaders>
   <add name="X-Frame-Options" value="SAMEORIGIN" />
   <!--
   <add name="X-Content-Type-Options" value="nosniff" />
 THIS BREAKS SSRS REPORTS, causes clickable controls to immediately reload page
 -->
    <add name="X-XSS-Protection" value="1; mode=block" />
</customHeaders>


问:
Parsing UFW logs for IP and port numbers
I want to write a script to go through my UFW firewall logs for blocked connections, and pull out the source IP and port they were trying to connect to. I have managed to put together scripts to pull these out individually, and am having difficulty in getting the script now to output the IP and port on one line. Below is a sample of the firewall logs I have and the script. Currently it output all IPs, followed by all port numbers. What I want on each line is the source IP address and corresponding destination port from each log entry.

The ultimate aim is to see what ports each IP address is trying to connect to. My plan was to use uniq -c, once I can output each IP and port from the logs.

input

```<code>Nov 26 06:25:11 vps123456 kernel: [620802.845897] [UFW BLOCK] IN=ens3 OUT= MAC=fa:16:3e:9f:c7:5d:11:22:33:44:55:66:77:88 SRC=85.93.20.253 DST=10.20.30.40 LEN=40 TOS=0x00 PREC=0x00 TTL=245 ID=5830 PROTO=TCP SPT=51639 DPT=735 WINDOW=1024 RES=0x00 SYN URGP=0
Nov 26 06:27:44 vps123456 kernel: [620955.012996] [UFW BLOCK] IN=ens3 OUT= MAC=fa:16:3e:9f:c7:5d:11:22:33:44:55:66:77:88 SRC=51.15.51.140 DST=10.20.30.40 LEN=433 TOS=0x00 PREC=0x00 TTL=50 ID=42044 DF PROTO=UDP SPT=5088 DPT=5062 LEN=413
</code>```

./script

```<code>file="input"
for line in $file; do
    addr=$(awk '{match($0,/SRC=[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART,RLENGTH); print ip}' $file)
    port=$(awk '{match($0,/DPT=[0-9]{0,5}/); port = substr($0,RSTART,RLENGTH); print port}' $file)
    echo $addr, $src >> output
done
</code>```

output

```<code>SRC=85.93.20.253 SRC=51.15.51.140, DPT=735 DPT=5062
</code>```

答:
A quick php solution for you problem, that will print on each line the source ip address and the corresponding destination port. The script reads your input logfile line by line and process each row. Match ip address and port number into variables using regex.

```<code><?php

$infile = $argv[1];

$handle = fopen($infile, "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        preg_match('/.*SRC=(?<ip>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*DPT=)(?<port>[0-9]+).*/', $line, $m);
        if ($m) {
            print $m['ip'] . ' ' . $m['port'] . "\n";
        }
    }
    fclose($handle);
} else {
    exit("Unable to open file ($finfile)");
}
</code>```

After saving the above script into a file (ie.: get-uwf-ip-port.php), you can run in the following way:

```<code>php get-uwf-ip-port.php your_logfile
</code>```

The output (source file was your two example lines):

```<code>85.93.20.253 735
51.15.51.140 5062
</code>```

UPDATE:

And here is a native bash solution. The main idea here is to read the file line by line, read each line into a shell variable, extract the ip and the port number using shell parameter expansion.

```<code>#!/bin/bash

infile="$1"
while read line; do
  ip="${line##*SRC=}"
  ip="${ip%% *}"
  port="${line##*DPT=}"
  port="${port%% *}"
  echo $ip $port
done < "$infile"
</code>```

I slightly modified your awk code, putting the ip and port matching together it will produce the same result as above:

```<code>awk '{match($0,/SRC=[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART+4,RLENGTH-4); match($0,/DPT=[0-9]{0,5}/); port = substr($0,RSTART+4,RLENGTH-4); print ip,port}' your_logfile
</code>```

Body:
I want to write a script to go through my UFW firewall logs for blocked connections, and pull out the source IP and port they were trying to connect to. I have managed to put together scripts to pull these out individually, and am having difficulty in getting the script now to output the IP and port on one line. Below is a sample of the firewall logs I have and the script. Currently it output all IPs, followed by all port numbers. What I want on each line is the source IP address and corresponding destination port from each log entry.

The ultimate aim is to see what ports each IP address is trying to connect to. My plan was to use uniq -c, once I can output each IP and port from the logs.

input

Nov 26 06:25:11 vps123456 kernel: [620802.845897] [UFW BLOCK] IN=ens3 OUT= MAC=fa:16:3e:9f:c7:5d:11:22:33:44:55:66:77:88 SRC=85.93.20.253 DST=10.20.30.40 LEN=40 TOS=0x00 PREC=0x00 TTL=245 ID=5830 PROTO=TCP SPT=51639 DPT=735 WINDOW=1024 RES=0x00 SYN URGP=0
Nov 26 06:27:44 vps123456 kernel: [620955.012996] [UFW BLOCK] IN=ens3 OUT= MAC=fa:16:3e:9f:c7:5d:11:22:33:44:55:66:77:88 SRC=51.15.51.140 DST=10.20.30.40 LEN=433 TOS=0x00 PREC=0x00 TTL=50 ID=42044 DF PROTO=UDP SPT=5088 DPT=5062 LEN=413

./script

file="input"
for line in $file; do
    addr=$(awk '{match($0,/SRC=[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART,RLENGTH); print ip}' $file)
    port=$(awk '{match($0,/DPT=[0-9]{0,5}/); port = substr($0,RSTART,RLENGTH); print port}' $file)
    echo $addr, $src >> output
done

output

SRC=85.93.20.253 SRC=51.15.51.140, DPT=735 DPT=5062

Body:
A quick php solution for you problem, that will print on each line the source ip address and the corresponding destination port. The script reads your input logfile line by line and process each row. Match ip address and port number into variables using regex.

<?php

$infile = $argv[1];

$handle = fopen($infile, "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        preg_match('/.*SRC=(?<ip>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*DPT=)(?<port>[0-9]+).*/', $line, $m);
        if ($m) {
            print $m['ip'] . ' ' . $m['port'] . "\n";
        }
    }
    fclose($handle);
} else {
    exit("Unable to open file ($finfile)");
}

After saving the above script into a file (ie.: get-uwf-ip-port.php), you can run in the following way:

php get-uwf-ip-port.php your_logfile

The output (source file was your two example lines):

85.93.20.253 735
51.15.51.140 5062

UPDATE:

And here is a native bash solution. The main idea here is to read the file line by line, read each line into a shell variable, extract the ip and the port number using shell parameter expansion.

#!/bin/bash

infile="$1"
while read line; do
  ip="${line##*SRC=}"
  ip="${ip%% *}"
  port="${line##*DPT=}"
  port="${port%% *}"
  echo $ip $port
done < "$infile"

I slightly modified your awk code, putting the ip and port matching together it will produce the same result as above:

awk '{match($0,/SRC=[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART+4,RLENGTH-4); match($0,/DPT=[0-9]{0,5}/); port = substr($0,RSTART+4,RLENGTH-4); print ip,port}' your_logfile


问:
GWT : Internet Explorer transparency issue
This post concerns only IE.
The last line of the following code is causing the issue.

```<code>    int width = 200;
    int height = 200;
    int overHeight = 40;

    AbsolutePanel absPanel = new AbsolutePanel();
    absPanel.setSize(width + "px", height + "px");

    SimplePanel underPanel = new SimplePanel();
    underPanel.setWidth(width + "px");
    underPanel.setHeight(height + "px");
    underPanel.getElement().getStyle().setBackgroundColor("red");

    SimplePanel overPanel = new SimplePanel();
    overPanel.setWidth(width + "px");
    overPanel.setHeight(overHeight + "px");
    overPanel.getElement().getStyle().setBackgroundColor("black");
    //Setting the IE opacity to 20% on the black element in order to obtain the see through effect.
    overPanel.getElement().getStyle().setProperty("filter", "alpha(opacity=20)");

    absPanel.add(underPanel, 0, 0);
    absPanel.add(overPanel, 0, 0);

    RootPanel.get("test").add(absPanel);

    //The next line causes the problem.
    absPanel.getElement().getStyle().setProperty("filter", "alpha(opacity=100)");
</code>```

So basically this code should display a red square of 200px by 200px (see underPanel in the code) and on top of it a black rectangle of 200px by 40px (see overPanel in the code). However the black rectangle is partially see through since its transparency is set to 20%, therefore it should appear in red, but of a darker red than the rectangle sitting under since it is actually a faded black item.

Some rendering problem occurs because of the last line of code that sets the opacity of the containing AbsolutePanel to 100% (which in theory should not affect the visual result). Indeed in that case the panel lying over remains still see through but straight through the background colour of the page! It's like if the panel sitting under was not there at all...

Any ideas?

This is under GWT 2.0 and IE7.

答: You could also include IE9.js (http://code.google.com/p/ie7-js/) from Dean Edwards, it allows you to use the opacity property for your css classes (and many more cool things, e.g. use of pseudo selectors!). I have successfully used it in several GWT based projects. Also I would set a CSS class (setStyleName()) instead of setting the inline style of the UI element.</p>

Body:
This post concerns only IE.
The last line of the following code is causing the issue.

    int width = 200;
    int height = 200;
    int overHeight = 40;

    AbsolutePanel absPanel = new AbsolutePanel();
    absPanel.setSize(width + "px", height + "px");

    SimplePanel underPanel = new SimplePanel();
    underPanel.setWidth(width + "px");
    underPanel.setHeight(height + "px");
    underPanel.getElement().getStyle().setBackgroundColor("red");

    SimplePanel overPanel = new SimplePanel();
    overPanel.setWidth(width + "px");
    overPanel.setHeight(overHeight + "px");
    overPanel.getElement().getStyle().setBackgroundColor("black");
    //Setting the IE opacity to 20% on the black element in order to obtain the see through effect.
    overPanel.getElement().getStyle().setProperty("filter", "alpha(opacity=20)");

    absPanel.add(underPanel, 0, 0);
    absPanel.add(overPanel, 0, 0);

    RootPanel.get("test").add(absPanel);

    //The next line causes the problem.
    absPanel.getElement().getStyle().setProperty("filter", "alpha(opacity=100)");

So basically this code should display a red square of 200px by 200px (see underPanel in the code) and on top of it a black rectangle of 200px by 40px (see overPanel in the code). However the black rectangle is partially see through since its transparency is set to 20%, therefore it should appear in red, but of a darker red than the rectangle sitting under since it is actually a faded black item.

Some rendering problem occurs because of the last line of code that sets the opacity of the containing AbsolutePanel to 100% (which in theory should not affect the visual result). Indeed in that case the panel lying over remains still see through but straight through the background colour of the page! It's like if the panel sitting under was not there at all...

Any ideas?

This is under GWT 2.0 and IE7.


问:
Compile a c++ program on PC to communicate with DJI phantom 4 pro
I am trying to receive on my PC(linux mint), a streaming from the camera of a DJI phantom 4 using OpenCV.
The example I am following is : https://developer.dji.com/guidance-sdk/documentation/tutorials/index.html  (I am following the linux part)
I copied the Copy libDJI_guidance.so in /usr/local/lib and I checked, it is there.
The makefile is :

```<code>#define a compiler
CXX     = g++
#define target name
TARGET  = main
#define dependencies of target
OBJECTS = main.o DJI_utility.o
#define the Include and Library path
CFLAGS  = -g -Wall -I/usr/local/include -I../../../include
LDFLAGS = -Wl,-rpath,./ -lpthread -lrt -L./ -L/usr/local/lib/ -lDJI_guidance -lusb-1.0 `pkg-config --cflags --libs opencv`

$(TARGET) : $(OBJECTS)
    $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS)
main.o : main.cpp DJI_utility.h
    $(CXX) $(CFLAGS) -c main.cpp DJI_utility.h
DJI_utility.o : DJI_utility.cpp DJI_utility.h
    $(CXX) $(CFLAGS) -c DJI_utility.cpp DJI_utility.h
clean:
    rm -rf *.o *.gch *.avi $(TARGET)
</code>```

But when i excute a make in the command line i get:

```<code>g++ -o main main.o DJI_utility.o -Wl,-rpath,./ -lpthread -lrt -L./ -L/usr/local/lib/ -lDJI_guidance -lusb-1.0 `pkg-config --cflags --libs opencv`
/usr/bin/ld: skipping incompatible /usr/local/lib//libDJI_guidance.so when searching for -lDJI_guidance
/usr/bin/ld: skipping incompatible /usr/local/lib/libDJI_guidance.so when searching for -lDJI_guidance
/usr/bin/ld: skipping incompatible //usr/local/lib/libDJI_guidance.so when searching for -lDJI_guidance
/usr/bin/ld: cannot find -lDJI_guidance
/usr/bin/ld: cannot find -lusb-1.0
collect2: error: ld returned 1 exit status
Makefile:12: recipe for target 'main' failed
make: *** [main] Error 1
</code>```

The project is located in:

```<code> ~/Documents/studies_SRT/SRT5/TX_drone/Guidance-SDK/demo/guidance_track
</code>```

The output of an ls is:
DJI_guidance.h  DJI_utility.cpp  DJI_utility.h  DJI_utility.h.gch  DJI_utility.o  main.cpp  main.o  Makefile

Thank you.

答: You seem to have downloaded library files for the wrong architecture. If you're on a 64-bit system, download the 64-bit version of the libraries.</p>

Body:
I am trying to receive on my PC(linux mint), a streaming from the camera of a DJI phantom 4 using OpenCV.
The example I am following is : https://developer.dji.com/guidance-sdk/documentation/tutorials/index.html  (I am following the linux part)
I copied the Copy libDJI_guidance.so in /usr/local/lib and I checked, it is there.
The makefile is :

#define a compiler
CXX     = g++
#define target name
TARGET  = main
#define dependencies of target
OBJECTS = main.o DJI_utility.o
#define the Include and Library path
CFLAGS  = -g -Wall -I/usr/local/include -I../../../include
LDFLAGS = -Wl,-rpath,./ -lpthread -lrt -L./ -L/usr/local/lib/ -lDJI_guidance -lusb-1.0 `pkg-config --cflags --libs opencv`

$(TARGET) : $(OBJECTS)
    $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS)
main.o : main.cpp DJI_utility.h
    $(CXX) $(CFLAGS) -c main.cpp DJI_utility.h
DJI_utility.o : DJI_utility.cpp DJI_utility.h
    $(CXX) $(CFLAGS) -c DJI_utility.cpp DJI_utility.h
clean:
    rm -rf *.o *.gch *.avi $(TARGET)

But when i excute a make in the command line i get:

g++ -o main main.o DJI_utility.o -Wl,-rpath,./ -lpthread -lrt -L./ -L/usr/local/lib/ -lDJI_guidance -lusb-1.0 `pkg-config --cflags --libs opencv`
/usr/bin/ld: skipping incompatible /usr/local/lib//libDJI_guidance.so when searching for -lDJI_guidance
/usr/bin/ld: skipping incompatible /usr/local/lib/libDJI_guidance.so when searching for -lDJI_guidance
/usr/bin/ld: skipping incompatible //usr/local/lib/libDJI_guidance.so when searching for -lDJI_guidance
/usr/bin/ld: cannot find -lDJI_guidance
/usr/bin/ld: cannot find -lusb-1.0
collect2: error: ld returned 1 exit status
Makefile:12: recipe for target 'main' failed
make: *** [main] Error 1

The project is located in:

 ~/Documents/studies_SRT/SRT5/TX_drone/Guidance-SDK/demo/guidance_track

The output of an ls is:
DJI_guidance.h  DJI_utility.cpp  DJI_utility.h  DJI_utility.h.gch  DJI_utility.o  main.cpp  main.o  Makefile

Thank you.


问:
String Filtering .. Any one..Contains only either of the selected characters or both
I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334

I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is

```<code>import java.util.*;
</code>```

import static java.lang.System.*;
public class numb {

```<code>public static void main(String[] args) {
    int num,c,cum;
    int i;
     Scanner in = new Scanner(System.in);
     out.println(3/10);

    out.println("How many elements u need to put in this array?");
    num=in.nextInt();
    int[] ray1 = new int[num];
    List<String> l1 = new LinkedList<String>();
    for (c=0;c<num;c++)
    {

        ray1[c]=c;
    }

            for(i=1;i<num;i++)
            {
         boolean baabu=true;
                do {
                    cum=ray1[i];
                    int lastdig = cum%10;
                    if(lastdig!=3||lastdig!=4)
                    {
                        baabu=false;
                    }
                    cum=cum/10;
                }
                while(cum>0&&baabu);
                if(baabu)
                {
                    String ad = String.valueOf(ray1[i]);
                    l1.add(ad);
                }

            }
            printme(l1);

}

public static void print (int[] array)
{
    for(int xc:array)
        out.println(xc);
}
public static void printme (List<String> l1)
{
    for(String yc:l1)
        out.println(yc);
}
</code>```

}

答:
Since you're treating the numbers as Strings already, the simplest way to find {3,4} strings is by matching the Regex "^[34]+$"

```<code>Pattern threeFourStrings = Pattern.compile("^[34]+$");
...
if (threeFourStrings.matcher(ad).matches()) {
    l1.add(ad);
}
</code>```

However, since you want all {3,4} strings up to 10000 (i.e. up to 4 digits), it would be far more efficient to construct them.  You might start looking here: How to get all possible n-digit numbers that can be formed using given digits?

(Of course since you only have 2 digits, "3" and "4", it might be even more efficient to just list the binary numbers from 0 to 1111 and transpose "0" to "3" and "1" to "4".)

Body:
I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334

I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is

import java.util.*;

import static java.lang.System.*;
public class numb {

public static void main(String[] args) {
    int num,c,cum;
    int i;
     Scanner in = new Scanner(System.in);
     out.println(3/10);

    out.println("How many elements u need to put in this array?");
    num=in.nextInt();
    int[] ray1 = new int[num];
    List<String> l1 = new LinkedList<String>();
    for (c=0;c<num;c++)
    {

        ray1[c]=c;
    }

            for(i=1;i<num;i++)
            {
         boolean baabu=true;
                do {
                    cum=ray1[i];
                    int lastdig = cum%10;
                    if(lastdig!=3||lastdig!=4)
                    {
                        baabu=false;
                    }
                    cum=cum/10;
                }
                while(cum>0&&baabu);
                if(baabu)
                {
                    String ad = String.valueOf(ray1[i]);
                    l1.add(ad);
                }

            }
            printme(l1);

}

public static void print (int[] array)
{
    for(int xc:array)
        out.println(xc);
}
public static void printme (List<String> l1)
{
    for(String yc:l1)
        out.println(yc);
}

}

Body:
Since you're treating the numbers as Strings already, the simplest way to find {3,4} strings is by matching the Regex "^[34]+$"

Pattern threeFourStrings = Pattern.compile("^[34]+$");
...
if (threeFourStrings.matcher(ad).matches()) {
    l1.add(ad);
}

However, since you want all {3,4} strings up to 10000 (i.e. up to 4 digits), it would be far more efficient to construct them.  You might start looking here: How to get all possible n-digit numbers that can be formed using given digits?

(Of course since you only have 2 digits, "3" and "4", it might be even more efficient to just list the binary numbers from 0 to 1111 and transpose "0" to "3" and "1" to "4".)


问:
Why the database didn't update anything although terminal shows "Completed 200" for Rails?
My controller code is like these:

```<code>def edit
  @user = User.find params[:id]
end

def update
  @user = User.find params[:id]
  if @user.update_attributes(params[:user])
    flash[:notice] = "success!"
  else
    flash[:notice] = "fail!"
  end
end

attr_accessor :username, :introduction, :first_name, :last_name

private

def user_params
  params.require(:user).permit(:username, :introduction, :first_name, :last_name)
end
</code>```

View:

```<code><%= form_for @user, :url =>edit_path(@user), :method => :PUT do |f| %>
<%= f.label :username %><br>
<%= f.text_field :username %>
<br>
<%= f.label :Introduction %><br>
<%= f.text_area :introduction %>
<br>
<%= f.label :FirstName %><br>
<%= f.text_field :first_name %>
<br>
<%= f.label :LastName %><br>
<%= f.text_field :last_name %>
<br>
<%= f.submit "Save changes"%><% end %>
</code>```

And the terminal is:

```

    Started PUT "/profile/1/edit" for 127.0.0.1 at 2017-12-06 04:30:05 -0500
    Processing by ProfileController#edit as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"eBvvAG892DTOFzYuFTKPCgbOuSQXB8BVOub7A8CgaPHLW2vaBFMpUGNHhgYZednfd5pqICCy1DykIarD7QYtIg==", "user"=>{"username"=>"aaa", "introduction"=>"aaaaa", "first_name"=>"a", "last_name"=>"a"}, "commit"=>"Save changes", "id"=>"1"}
      User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
      Notification Load (0.1ms)  SELECT "notifications".* FROM "notifications"
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."sender_id" = ? LIMIT 1  [["sender_id", 1]]
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."recip_id" = ? LIMIT 1  [["recip_id", 1]]
      User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
      CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
      Rendered profile/edit.html.erb within layouts/game (1.5ms)
      User Load (0.2ms)  SELECT "users".* FROM "users"
    Completed 200 OK in 32ms (Views: 28.5ms | ActiveRecord: 0.5ms)

```

But database is not updating:

1|du.1@osu.edu|$2a$11$2WHUjqQHU1gtlzw3ObXgVeE7dGG1qby2tLmATeoUyMnh1cg5wXv86||||3|2017-12-06 08:43:44.469588|2017-12-06 05:32:19.252680|127.0.0.1|127.0.0.1|2017-12-05 17:04:39.689636|2017-12-06 08:43:44.470487||1970-1-1|||This guy is lazy. Without an Introduction.|

答:
Something is definitely askew. Look here:

```<code>Started PUT "/profile/1/edit" for 127.0.0.1 at 2017-12-06 04:30:05 -0500
</code>```

You're doing a PUT to /profile/1/edit. Conventionally, you would do a GET to /profile/1/edit which would map to the edit action of your ProfileController. So, perhaps you have your routes mis-configured because I would normally expect that to throw an error. Instead (if your console output is correct), PUT "/profile/1/edit" is mapping to the edit action of your ProfileController, as you can see here:

```<code>Processing by ProfileController#edit as HTML
</code>```

And, naturally, edit doesn't do any updating:

```<code>def edit
  @user = User.find params[:id]
end
</code>```

So, no changes to your database.

By the way, are you using Devise or something like that? As you can see, you're loading your user twice:

```<code>  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  ...
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
</code>```

So I wonder if, in edit,

```<code>def edit
  @user = User.find params[:id]
end
</code>```

@user = User.find params[:id] is even needed.

Body:
My controller code is like these:

def edit
  @user = User.find params[:id]
end

def update
  @user = User.find params[:id]
  if @user.update_attributes(params[:user])
    flash[:notice] = "success!"
  else
    flash[:notice] = "fail!"
  end
end

attr_accessor :username, :introduction, :first_name, :last_name

private

def user_params
  params.require(:user).permit(:username, :introduction, :first_name, :last_name)
end

View:

<%= form_for @user, :url =>edit_path(@user), :method => :PUT do |f| %>
<%= f.label :username %>

<%= f.text_field :username %>

<%= f.label :Introduction %>

<%= f.text_area :introduction %>

<%= f.label :FirstName %>

<%= f.text_field :first_name %>

<%= f.label :LastName %>

<%= f.text_field :last_name %>

<%= f.submit "Save changes"%><% end %>

And the terminal is:

    Started PUT "/profile/1/edit" for 127.0.0.1 at 2017-12-06 04:30:05 -0500
    Processing by ProfileController#edit as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"eBvvAG892DTOFzYuFTKPCgbOuSQXB8BVOub7A8CgaPHLW2vaBFMpUGNHhgYZednfd5pqICCy1DykIarD7QYtIg==", "user"=>{"username"=>"aaa", "introduction"=>"aaaaa", "first_name"=>"a", "last_name"=>"a"}, "commit"=>"Save changes", "id"=>"1"}
      User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
      Notification Load (0.1ms)  SELECT "notifications".* FROM "notifications"
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."sender_id" = ? LIMIT 1  [["sender_id", 1]]
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."recip_id" = ? LIMIT 1  [["recip_id", 1]]
      User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
      CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
      Rendered profile/edit.html.erb within layouts/game (1.5ms)
      User Load (0.2ms)  SELECT "users".* FROM "users"
    Completed 200 OK in 32ms (Views: 28.5ms | ActiveRecord: 0.5ms)

But database is not updating:

1|du.1@osu.edu|$2a$11$2WHUjqQHU1gtlzw3ObXgVeE7dGG1qby2tLmATeoUyMnh1cg5wXv86||||3|2017-12-06 08:43:44.469588|2017-12-06 05:32:19.252680|127.0.0.1|127.0.0.1|2017-12-05 17:04:39.689636|2017-12-06 08:43:44.470487||1970-1-1|||This guy is lazy. Without an Introduction.|

Body:
Something is definitely askew. Look here:

Started PUT "/profile/1/edit" for 127.0.0.1 at 2017-12-06 04:30:05 -0500

You're doing a PUT to /profile/1/edit. Conventionally, you would do a GET to /profile/1/edit which would map to the edit action of your ProfileController. So, perhaps you have your routes mis-configured because I would normally expect that to throw an error. Instead (if your console output is correct), PUT "/profile/1/edit" is mapping to the edit action of your ProfileController, as you can see here:

Processing by ProfileController#edit as HTML

And, naturally, edit doesn't do any updating:

def edit
  @user = User.find params[:id]
end

So, no changes to your database.

By the way, are you using Devise or something like that? As you can see, you're loading your user twice:

  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  ...
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]

So I wonder if, in edit,

def edit
  @user = User.find params[:id]
end

@user = User.find params[:id] is even needed.


问:
Awk code explanation: changing order of fields
I have a file a .txt file that has 14 columns. The head of it would look like this:

```<code>name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi rsid
SNP1  A  T 0.05   1       5  56 7    8    9    11  12  rs1
SNP2  T  A 0.05   1       6  55 7    8    9    11  12  rs2
</code>```

I want to put the last column in the first position. I wasn't sure what was the most efficient way of doing this, but I came across this, inspiring myself from other posts:

```<code>awk '{$0=$NF FS$0; $14=""}1' file.txt | head
</code>```

I obtained this, which I think works:

```<code>rsid    name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi
rs1     SNP1  A  T 0.05   1       5  56 7    8    9    11  12
rs2     SNP2  T  A 0.05   1       6  55 7    8    9    11  12
</code>```

I am struggling though to understand what exactly the code does.

I know that NF is the field count of the line being processed

I know that FS is the field seperator

So how can my code work exactly? I just don't really understand how saying that $0 (the whole line) is equal to NF and saying FS$0 (not sure what this means) ends up with the last field now being first. I do realise that $14="" is not written, you end up with 2 rsid columns, one at the start and one at the end.

I'm quite new to using awk so if there is an easier way to achieve this, I would happily go for it.

Thanks

答:
might be easier with sed

```<code>sed -E 's/(.*)\s(\S+)$/\2 \1/' file
</code>```

match the last field and the rest of the line, print it reverse order.

\s is shorthand for whitespace character, equivalent to [ \t\r\n\f].
\S is the negation of \s, for non-whitespace.  POSIX equivalent of \s is [:space:].  If your sed doesn't support the shorthand notation or you want full portability you may need to use one of the equivalent forms.

Body:
I have a file a .txt file that has 14 columns. The head of it would look like this:

name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi rsid
SNP1  A  T 0.05   1       5  56 7    8    9    11  12  rs1
SNP2  T  A 0.05   1       6  55 7    8    9    11  12  rs2

I want to put the last column in the first position. I wasn't sure what was the most efficient way of doing this, but I came across this, inspiring myself from other posts:

awk '{$0=$NF FS$0; $14=""}1' file.txt | head

I obtained this, which I think works:

rsid    name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi
rs1     SNP1  A  T 0.05   1       5  56 7    8    9    11  12
rs2     SNP2  T  A 0.05   1       6  55 7    8    9    11  12

I am struggling though to understand what exactly the code does.

I know that NF is the field count of the line being processed

I know that FS is the field seperator

So how can my code work exactly? I just don't really understand how saying that $0 (the whole line) is equal to NF and saying FS$0 (not sure what this means) ends up with the last field now being first. I do realise that $14="" is not written, you end up with 2 rsid columns, one at the start and one at the end.

I'm quite new to using awk so if there is an easier way to achieve this, I would happily go for it.

Thanks

Body:
might be easier with sed

sed -E 's/(.*)\s(\S+)$/\2 \1/' file

match the last field and the rest of the line, print it reverse order.

\s is shorthand for whitespace character, equivalent to [ \t\r\n\f].
\S is the negation of \s, for non-whitespace.  POSIX equivalent of \s is [:space:].  If your sed doesn't support the shorthand notation or you want full portability you may need to use one of the equivalent forms.


问:
Docker Compose keep container running
I want to start a service with docker-compose and keep the container running so I can get its IP-address via 'docker inspect'. However, the container always exits right after starting up.

I tried to add "command: ["sleep", "60"]" and other things to the docker-compose.yml but whenever I add the line with "command:..." I cant call "docker-compose up" as I will get the message "Cannot start container ..... System error: invalid character 'k' looking for beginning of value"

I also tried adding "CMD sleep 60" and whatnot to the Dockerfile itself but these commands do not seem to be executed.

Is there an easy way to keep the container alive or to fix one of my problems?

EDIT:
Here is the Compose file I want to run:

```<code>version: '2'
services:
  my-test:
    image: ubuntu
    command: bash -c "while true; do echo hello; sleep 2; done"
</code>```

It's working fine If I start this with docker-compose under OS X, but if I try the same under Ubuntu 16.04 it gives me above error message.

If I try the approach with the Dockerfile, the Dockerfile looks like this:

```<code>FROM ubuntu:latest
CMD ["sleep", "60"]
</code>```

Which does not seem to do anything

EDIT 2:
I have to correct myself, turned out it was the same problem with the Dockerfile and the docker-compose.yml:
Each time I add either "CMD ..." to the Dockerfile OR add "command ..." to the compose file, I get above error with the invalid character. If I remove both commands, it works flawlessly.

答:
In the Dockerfile you can use the command:</p>

```<code>{CMD sleep infinity}
</code>```

Title: Docker Compose keep container running

Body:
I want to start a service with docker-compose and keep the container running so I can get its IP-address via 'docker inspect'. However, the container always exits right after starting up.

I tried to add "command: ["sleep", "60"]" and other things to the docker-compose.yml but whenever I add the line with "command:..." I cant call "docker-compose up" as I will get the message "Cannot start container ..... System error: invalid character 'k' looking for beginning of value"

I also tried adding "CMD sleep 60" and whatnot to the Dockerfile itself but these commands do not seem to be executed.

Is there an easy way to keep the container alive or to fix one of my problems?

EDIT:
Here is the Compose file I want to run:

version: '2'
services:
  my-test:
    image: ubuntu
    command: bash -c "while true; do echo hello; sleep 2; done"

It's working fine If I start this with docker-compose under OS X, but if I try the same under Ubuntu 16.04 it gives me above error message.

If I try the approach with the Dockerfile, the Dockerfile looks like this:

FROM ubuntu:latest
CMD ["sleep", "60"]

Which does not seem to do anything

EDIT 2:
I have to correct myself, turned out it was the same problem with the Dockerfile and the docker-compose.yml:
Each time I add either "CMD ..." to the Dockerfile OR add "command ..." to the compose file, I get above error with the invalid character. If I remove both commands, it works flawlessly.

Body:
In the Dockerfile you can use the command:

{CMD sleep infinity}