问:
How to make responsive table and header fixed both on same html table
Here is the code pen https://codepen.io/shaswat/pen/EbwPNK

I have made an html table responsive by making all the columns getting repeated and show the correspondent row value up when its mobile display -- so the responsive part is done

Now having trouble to make the header fixed in this html table while scrolling the tbody - so tbody can have fixed height and that time scrolling header should be fixed -- applicable only for the resolutions greater than mobile display
--need help in this

HTML

```<code><h1>Some more Header information</h1>
<h2>Some more Header information</h2>
<h3>Header</h3>

<div class='rg-container'>
    <div class='rg-content'>
        <table class='rg-table'>
            <thead>
                <tr>
                    <th class='text '>id </th>
                    <th class='text '>somcol</th>
                    <th class='text '>biggger id</th>
                    <th class='text '>another id</th>
                    <th class='text '>med col</th>
                    <th class='text '>med col</th>
                    <th class='text '>sheet</th>
                    <th class='text '>sheet</th>
                    <th class='text '>anotherbigcoloumn</th>
                    <th class='text '>small</th>
                    <th class='text '>anotherbigcoloumn</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>small col</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>averybigcolumnssssss</th>
                    <th class='text '>mediumclolumnss</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class='text' data-title='id'>id</td>
                    <td class='text' data-title='somcol'>somcol</td>
                    <td class='text' data-title='biggger id'>biggger id</td>
                    <td class='text' data-title='another id'>another id</td>
                    <td class='text' data-title='med col'>med col</td>
                    <td class='text' data-title='med col'>med col</td>
                    <td class='text' data-title='sheet'>sheet</td>
                    <td class='text' data-title='sheet'>sheet</td>
                    <td class='text' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text' data-title='small'>small</td>
                    <td class='text' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='small col'>small col</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

CSS

```<code>.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}

.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}
</code>```

答:
you r doing great but I think u missed somethings like:

you should put the whole thing in a div (container), and of course giving a fixed size to the container.

the header and the content should be at separated divs and tables.

you must put (display: flex;  flex-direction: column;height: 100%;) in the class of containing div(of the two tables,rg-container in your code)

you also must put (overflow-y: scroll;)in the class of container div of the second table.

So your code will be like this:

.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.container {
  background: tan;
  width: 100%;
  padding: 4px;
  height: 300px;
  box-sizing: border-box;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}
.rg-body{overflow-y: scroll;}
.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Some more Header information</h1>
<h2>Some more Header information</h2>
<h3>Header</h3>
<div class="container">
<div class='rg-container'>
    <div class='rg-content'>
        <table class='rg-table'>
            <thead>
                <tr>
                    <th class='text '>id </th>
                <th class='text '>somcol</th>
                <th class='text '>biggger id</th>
                <th class='text '>another id</th>
                <th class='text '>med col</th>
                <th class='text '>med col</th>
                <th class='text '>sheet</th>
                <th class='text '>sheet</th>
                <th class='text '>anotherbigcoloumn</th>
                <th class='text '>small</th>
                <th class='text '>anotherbigcoloumn</th>
                <th class='text '>dateformat</th>
                <th class='text '>dateformat</th>
                <th class='text '>small col</th>
                <th class='text '>dateformat</th>
                <th class='text '>averybigcolumnssssss</th>
                <th class='text '>mediumclolumnss</th>
                </tr>
            </thead>
            <tbody>
      </table>
  </div>
  <div class="rg-body">
    <table>
                <tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>

            </tbody>
        </table>

    </div>
</div>
  </div></code>```

Body:
Here is the code pen https://codepen.io/shaswat/pen/EbwPNK

I have made an html table responsive by making all the columns getting repeated and show the correspondent row value up when its mobile display -- so the responsive part is done

Now having trouble to make the header fixed in this html table while scrolling the tbody - so tbody can have fixed height and that time scrolling header should be fixed -- applicable only for the resolutions greater than mobile display
--need help in this

HTML

Some more Header information

Some more Header information

Header

                    id
                    somcol
                    biggger id
                    another id
                    med col
                    med col
                    sheet
                    sheet
                    anotherbigcoloumn
                    small
                    anotherbigcoloumn
                    dateformat
                    dateformat
                    small col
                    dateformat
                    averybigcolumnssssss
                    mediumclolumnss

                    id
                    somcol
                    biggger id
                    another id
                    med col
                    med col
                    sheet
                    sheet
                    another big coloumn
                    small
                    another big coloumn
                    date format
                    date format
                    small col
                    date format
                    a very big columnssssss
                    medium clolumnss

CSS

.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}

.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}

Body:
you r doing great but I think u missed somethings like:

you should put the whole thing in a div (container), and of course giving a fixed size to the container.

the header and the content should be at separated divs and tables.

you must put (display: flex;  flex-direction: column;height: 100%;) in the class of containing div(of the two tables,rg-container in your code)

you also must put (overflow-y: scroll;)in the class of container div of the second table.

So your code will be like this:

.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.container {
  background: tan;
  width: 100%;
  padding: 4px;
  height: 300px;
  box-sizing: border-box;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}
.rg-body{overflow-y: scroll;}
.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}
}

<h1>Some more Header information</h1>
<h2>Some more Header information</h2>
<h3>Header</h3>
<div class="container">
<div class='rg-container'>
    <div class='rg-content'>
        <table class='rg-table'>
            <thead>
                <tr>
                    <th class='text '>id </th>
                <th class='text '>somcol</th>
                <th class='text '>biggger id</th>
                <th class='text '>another id</th>
                <th class='text '>med col</th>
                <th class='text '>med col</th>
                <th class='text '>sheet</th>
                <th class='text '>sheet</th>
                <th class='text '>anotherbigcoloumn</th>
                <th class='text '>small</th>
                <th class='text '>anotherbigcoloumn</th>
                <th class='text '>dateformat</th>
                <th class='text '>dateformat</th>
                <th class='text '>small col</th>
                <th class='text '>dateformat</th>
                <th class='text '>averybigcolumnssssss</th>
                <th class='text '>mediumclolumnss</th>
                </tr>
            </thead>
            <tbody>
      </table>
  </div>
  <div class="rg-body">
    <table>
                <tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
<tr class=''>
                    <td class='text ' data-title='id'>id</td>
                    <td class='text ' data-title='somcol'>somcol</td>
                    <td class='text ' data-title='biggger id'>biggger id</td>
                    <td class='text ' data-title='another id'>another id</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='med col'>med col</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='sheet'>sheet</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='small'>small</td>
                    <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='small col'>small col</td>
                    <td class='text ' data-title='dateformat'>date format</td>
                    <td class='text ' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text ' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>

            </tbody>
        </table>

    </div>
</div>
  </div>


来源: stackexchange

问:
Python to check rpm is greater version
Could any one help me to check in Linux to meet rpm version

Below command I used to get package version.

```<code>  rpm -qi libstdc++6 | awk -F': ' '/Version/ {print $2}'
</code>```

using sub-process, I get below out put

```<code> 6.2.1+r239768
</code>```

Now I want to compare 6.2.1+r239768 is greater than  5.1.1

Below is results I am expected

```<code>output = 6.2.1+r239768
print "This rpm version is supported"
output = 6.3+r23
print "This rpm version is supported"
output = 7.1.1+r57678
print "This rpm version is supported"
output = 5.1.1+r23677
print "This rpm version is not supported"
output = 4.1+r56888
print "This rpm version is not supported"
</code>```

答:
The python rpm library gives you a way to compare a EVR (Epoch, Version, Release), but doesn't seem to give you the code to split a string into those parts. It's trivial, though. Here's a little working program.</p>

```<code>#! /usr/bin/env python

import re
import sys

import rpm

evr_re = re.compile(r'^(?:([^:]*):)?([^-]+)(?:-(.*))?$')

def str_to_evr(s):
    mo = evr_re.match(s)
    if not mo:
        raise ValueError("not a valid version string")
    return mo.groups()

def main():
    if len(sys.argv) != 3:
        raise SystemExit("usage: vercmp VER1 VER2")
    try:
        evr_a = str_to_evr(sys.argv[1].strip())
        evr_b = str_to_evr(sys.argv[2].strip())
        result = rpm.labelCompare(evr_a, evr_b)
    except Exception as exc:
        raise SystemExit("Problem converting or comparing versions: %s %s" % (
            type(exc).__name__, exc))
    print (result)

if __name__ == "__main__":
    main()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python to check rpm is greater version

Body:
Could any one help me to check in Linux to meet rpm version

Below command I used to get package version.

  rpm -qi libstdc++6 | awk -F': ' '/Version/ {print $2}'

using sub-process, I get below out put

 6.2.1+r239768

Now I want to compare 6.2.1+r239768 is greater than  5.1.1

Below is results I am expected

output = 6.2.1+r239768
print "This rpm version is supported"
output = 6.3+r23
print "This rpm version is supported"
output = 7.1.1+r57678
print "This rpm version is supported"
output = 5.1.1+r23677
print "This rpm version is not supported"
output = 4.1+r56888
print "This rpm version is not supported"

Body:
The python rpm library gives you a way to compare a EVR (Epoch, Version, Release), but doesn't seem to give you the code to split a string into those parts. It's trivial, though. Here's a little working program.

#! /usr/bin/env python

import re
import sys

import rpm

evr_re = re.compile(r'^(?:([^:]*):)?([^-]+)(?:-(.*))?$')

def str_to_evr(s):
    mo = evr_re.match(s)
    if not mo:
        raise ValueError("not a valid version string")
    return mo.groups()

def main():
    if len(sys.argv) != 3:
        raise SystemExit("usage: vercmp VER1 VER2")
    try:
        evr_a = str_to_evr(sys.argv[1].strip())
        evr_b = str_to_evr(sys.argv[2].strip())
        result = rpm.labelCompare(evr_a, evr_b)
    except Exception as exc:
        raise SystemExit("Problem converting or comparing versions: %s %s" % (
            type(exc).__name__, exc))
    print (result)

if __name__ == "__main__":
    main()


问:
Azure app service: Cannot find the certificate in X509Store(StoreName.My, StoreLocation.CurrentUser)
I have written a program that needs a certificate for signing and some other things.

I have uploaded my pfx file as private certificate in SSL certificates of my app service.

Then I've tried to see installed certificates on my app service as it has been described in here by using power shell.

But my current user doesn't have any certificates.

I've also checked my local machine, but it wasn't there either.

I cannot also find it using my c# code:

```<code> X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        certStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false);
        if (certCollection.Count == 0)
            throw new Exception("Certificate not found");
</code>```

答:
We could get the answer from this blog.

Adding an app setting named WEBSITE_LOAD_CERTIFICATES with its value set to the thumbprint of the certificate will make it accessible to your web application.

You can have multiple comma-separated thumbprint values or can set this value to "*" (without quotes) in which case all your certificates will be loaded to your web applications personal certificate store.

Body:
I have written a program that needs a certificate for signing and some other things.

I have uploaded my pfx file as private certificate in SSL certificates of my app service.

Then I've tried to see installed certificates on my app service as it has been described in here by using power shell.

But my current user doesn't have any certificates.

I've also checked my local machine, but it wasn't there either.

I cannot also find it using my c# code:

 X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        certStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false);
        if (certCollection.Count == 0)
            throw new Exception("Certificate not found");


问:
How to get Sql Temp Table Join with column values that are not in table, replaced by 0
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

```<code>#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4
</code>```

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

答:
First if you have these 5 temp tables that probably means there is a much much much better way of doing this at the source table level!  But because you asked you most significant problem with combining them is that not 1 of the tables hold a combination of every month_year and prod_id.  So you have to create it.  The way I choose to do this for completeness sake is to:

Create a Tally table (as a common table expression [CTE]) for use in
generating a month_year table

Create a Products CTE by unioning all distinct prod_ids from your temp tables

Create a MonthYearInputs CTE to be able to determine the Max and Min month_years represented

Generate a MonthYear CTE to house every possible month_year combination between the MIN & MAX years represented in your data

Then a cartisean (CROSS) join between the MonthYear & Product ctes give you all of the combinations to LEFT JOIN the other tables to.

Simply put a where statement in to remove the rows that have no values in ALL of the tables and use ISNULL() or COALESCE() to make the null values 0.

Here is a working example: http://rextester.com/MCEO96178

```<code>;WITH cteTen AS (
    SELECT n FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n)
)

, cteTally AS (
    SELECT
       n = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       cteTen t1
       CROSS JOIN cteTen t2 --hundreds
       CROSS JOIN cteTen t3 --thousands
       --keep cross joining if need more than 1000 month
)

, cteProducts AS (
    SELECT DISTINCT prod_id FROM #tmp_spoilt_good_job_amt
    UNION
    SELECT DISTINCT prod_id FROM #tmp_received_qty
    UNION
    SELECT DISTINCT prod_id FROM #tmp_purchase_qty
    UNION
    SELECT DISTINCT prod_id FROM #tmp_opening_balance
    UNION
    SELECT DISTINCT prod_id FROM #tmp_closing_balance
)

, cteInputMonthYears AS (
    SELECT DISTINCT month_year FROM #tmp_spoilt_good_job_amt
    UNION
    SELECT DISTINCT month_year FROM #tmp_received_qty
    UNION
    SELECT DISTINCT month_year FROM #tmp_purchase_qty
    UNION
    SELECT DISTINCT month_year FROM #tmp_opening_balance
    UNION
    SELECT DISTINCT month_year FROM #tmp_closing_balance
)

, cteMaxMinMonthYears AS (
    SELECT
       MinMonthYear =  CAST(STUFF(MIN(month_year),3,0,'-01') AS DATETIME)
       ,MonthsDiff = DATEDIFF(MONTH,CAST(STUFF(MIN(month_year),3,0,'-01') AS DATETIME),CAST(STUFF(MAX(month_year),3,0,'-01') AS DATETIME)) + 1
    FROM
       cteInputMonthYears
)

, cteMonthYears AS (
    SELECT
       month_year = FORMAT(DATEADD(MONTH, t.n - 1, m.MinMonthYear),'MM-yyyy')
    FROM
       cteMaxMinMonthYears m
       INNER JOIN cteTally t
       ON m.MonthsDiff >= t.n
)

SELECT
    my.month_year
    ,job_amt = ISNULL(ja.job_amt,0)
    ,spoil = ISNULL(ja.spoil,0)
    ,good = ISNULL(ja.good,0)
    ,p.prod_id
    ,received_qty = ISNULL(r.received_qty,0)
    ,purchase_qty = ISNULL(pur.purchase_qty,0)
    ,opening_balance = ISNULL(o.opening_balance,0)
    ,closing_balance = ISNULL(c.closing_balance,0)
FROM
    cteMonthYears my
    CROSS JOIN cteProducts p
    LEFT JOIN #tmp_spoilt_good_job_amt ja
    ON my.month_year = ja.month_year
    AND p.prod_id = ja.prod_id
    LEFT JOIN #tmp_received_qty r
    ON my.month_year = r.month_year
    AND p.prod_id = r.prod_id
    LEFT JOIN #tmp_purchase_qty pur
    ON my.month_year = pur.month_year
    AND p.prod_id = pur.prod_id
    LEFT JOIN #tmp_opening_balance o
    ON my.month_year = o.month_year
    AND p.prod_id = o.prod_id
    LEFT JOIN #tmp_closing_balance c
    ON my.month_year = c.month_year
    AND p.prod_id = c.prod_id
WHERE
    NOT(ja.month_year IS NULL
       AND r.month_year IS NULL
       AND pur.month_year IS NULL
       AND o.month_year IS NULL
       AND o.month_year IS NULL
       AND c.month_year IS NULL)
ORDER BY
    my.month_year
    ,p.prod_id
</code>```

Body:
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

Body:
First if you have these 5 temp tables that probably means there is a much much much better way of doing this at the source table level!  But because you asked you most significant problem with combining them is that not 1 of the tables hold a combination of every month_year and prod_id.  So you have to create it.  The way I choose to do this for completeness sake is to:

Create a Tally table (as a common table expression [CTE]) for use in
generating a month_year table

Create a Products CTE by unioning all distinct prod_ids from your temp tables

Create a MonthYearInputs CTE to be able to determine the Max and Min month_years represented

Generate a MonthYear CTE to house every possible month_year combination between the MIN & MAX years represented in your data

Then a cartisean (CROSS) join between the MonthYear & Product ctes give you all of the combinations to LEFT JOIN the other tables to.

Simply put a where statement in to remove the rows that have no values in ALL of the tables and use ISNULL() or COALESCE() to make the null values 0.

Here is a working example: http://rextester.com/MCEO96178

;WITH cteTen AS (
    SELECT n FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n)
)

, cteTally AS (
    SELECT
       n = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       cteTen t1
       CROSS JOIN cteTen t2 --hundreds
       CROSS JOIN cteTen t3 --thousands
       --keep cross joining if need more than 1000 month
)

, cteProducts AS (
    SELECT DISTINCT prod_id FROM #tmp_spoilt_good_job_amt
    UNION
    SELECT DISTINCT prod_id FROM #tmp_received_qty
    UNION
    SELECT DISTINCT prod_id FROM #tmp_purchase_qty
    UNION
    SELECT DISTINCT prod_id FROM #tmp_opening_balance
    UNION
    SELECT DISTINCT prod_id FROM #tmp_closing_balance
)

, cteInputMonthYears AS (
    SELECT DISTINCT month_year FROM #tmp_spoilt_good_job_amt
    UNION
    SELECT DISTINCT month_year FROM #tmp_received_qty
    UNION
    SELECT DISTINCT month_year FROM #tmp_purchase_qty
    UNION
    SELECT DISTINCT month_year FROM #tmp_opening_balance
    UNION
    SELECT DISTINCT month_year FROM #tmp_closing_balance
)

, cteMaxMinMonthYears AS (
    SELECT
       MinMonthYear =  CAST(STUFF(MIN(month_year),3,0,'-01') AS DATETIME)
       ,MonthsDiff = DATEDIFF(MONTH,CAST(STUFF(MIN(month_year),3,0,'-01') AS DATETIME),CAST(STUFF(MAX(month_year),3,0,'-01') AS DATETIME)) + 1
    FROM
       cteInputMonthYears
)

, cteMonthYears AS (
    SELECT
       month_year = FORMAT(DATEADD(MONTH, t.n - 1, m.MinMonthYear),'MM-yyyy')
    FROM
       cteMaxMinMonthYears m
       INNER JOIN cteTally t
       ON m.MonthsDiff >= t.n
)

SELECT
    my.month_year
    ,job_amt = ISNULL(ja.job_amt,0)
    ,spoil = ISNULL(ja.spoil,0)
    ,good = ISNULL(ja.good,0)
    ,p.prod_id
    ,received_qty = ISNULL(r.received_qty,0)
    ,purchase_qty = ISNULL(pur.purchase_qty,0)
    ,opening_balance = ISNULL(o.opening_balance,0)
    ,closing_balance = ISNULL(c.closing_balance,0)
FROM
    cteMonthYears my
    CROSS JOIN cteProducts p
    LEFT JOIN #tmp_spoilt_good_job_amt ja
    ON my.month_year = ja.month_year
    AND p.prod_id = ja.prod_id
    LEFT JOIN #tmp_received_qty r
    ON my.month_year = r.month_year
    AND p.prod_id = r.prod_id
    LEFT JOIN #tmp_purchase_qty pur
    ON my.month_year = pur.month_year
    AND p.prod_id = pur.prod_id
    LEFT JOIN #tmp_opening_balance o
    ON my.month_year = o.month_year
    AND p.prod_id = o.prod_id
    LEFT JOIN #tmp_closing_balance c
    ON my.month_year = c.month_year
    AND p.prod_id = c.prod_id
WHERE
    NOT(ja.month_year IS NULL
       AND r.month_year IS NULL
       AND pur.month_year IS NULL
       AND o.month_year IS NULL
       AND o.month_year IS NULL
       AND c.month_year IS NULL)
ORDER BY
    my.month_year
    ,p.prod_id


问:
Using Cassandra Prepared Statement using Cassandra Operations Spring Boot
I need Prepared Statement / instead of Query Builder using  Cassandra Operations Interface and session
Any Example or recent docs. for Cassandra using java</p>

答:
Use spring-data-cassandra and that will do all magic for you.

App sample https://github.com/valchkou-app/spring-boot-cassandra-simple

```<code>@Repository
interface ISensorMeasureRepository extends CassandraRepository<SensorMeasureEntity> {

  @Query('select * from sensor_measures_simple where sensor_id=?0 and measure_time>=?1 and measure_time<=?2')
  List<SensorMeasureEntity> getBySensorAndDateRange(int sensorId, Date start, Date end)

  @Query('select * from sensor_measures_simple where sensor_id=?0 ALLOW FILTERING')
  Stream<SensorMeasureEntity> getAllBySensor(int sensorId)
}
</code>```

Body:
Use spring-data-cassandra and that will do all magic for you.

App sample https://github.com/valchkou-app/spring-boot-cassandra-simple

@Repository
interface ISensorMeasureRepository extends CassandraRepository<SensorMeasureEntity> {

  @Query('select * from sensor_measures_simple where sensor_id=?0 and measure_time>=?1 and measure_time<=?2')
  List<SensorMeasureEntity> getBySensorAndDateRange(int sensorId, Date start, Date end)

  @Query('select * from sensor_measures_simple where sensor_id=?0 ALLOW FILTERING')
  Stream<SensorMeasureEntity> getAllBySensor(int sensorId)
}

ContentLicense: CC BY-SA 4.0


问:
How to determine if stdin is empty
I have a little project to do for school. We have a program that generate a maze.
We can put arguments to generate a different maze or even get it as a picture.

We call it like that :

./test

or

./test --arg1 val --arg2 val --etc

We have been asked to parse the argument into a file that we put in stdin like that :

./test  < args.txt

Now I must be able to call the program with every one of the lines above. The line with the arguments work, the mine with the program in stdin works, but the line without anything doesnt work anymore.

So i should check if the user as sent some file in stdin i call the program with a file, else i call it the normal way. I tried with feof but it can't work since stdin won't have anything in not even eof.
When i call the program without arguments or file it waits for the user to write something, which it shouldnt.

Basically my code should look like that

```<code>int main()
{
    int v;
    if (stdin!=NULL)) { //if a file has been passed "./test <test.txt"
        scanf("%d",&v);
    }
    else {  //if no files has been passed "./test "
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50) {
        printf("you drive slow\n");
    }
    else {
        printf("you drive fast\n");
    }
    return 0;
}
</code>```

But obviously (stdin != NULL) doesn't work. So is there a way to check if stdin has something in?
I asked my classmate, one of them told me something about useing fgetc to get the first char and then put it back if there is really a char but when i try to use fgetc, if there is no char it waits for me to put a char in.

So how could I check if stdin is empty or if there is a file into it (without using new libraries)?

Thanks you in advance
have a good day

If i am not completely clear please tell it to me i am not a native speaker and i have a bit of difficulties since it's a technical question

答:
It sounds like you want to run your program based on arguments either provided on the command line or piped into it from a file. If so, you should check whether the arguments have been provided on the command line first:

```<code>if (argc > 1) {
  //parse argv
}
</code>```

Then, check whether stdin is empty, and if not read the arguments in from stdin:

```<code>else if ((fseek(stdin, 0, SEEK_END), ftell(stdin)) > 0)
{
  rewind(stdin);
  char buffer[1024];
  fgets(buffer, 1024 , stdin);
  //parse args read in from stdin
}
else
{
  //no redirection
}
</code>```

Title: How to determine if stdin is empty

Body:
I have a little project to do for school. We have a program that generate a maze.
We can put arguments to generate a different maze or even get it as a picture.

We call it like that :

./test

or

./test --arg1 val --arg2 val --etc

We have been asked to parse the argument into a file that we put in stdin like that :

./test  < args.txt

Now I must be able to call the program with every one of the lines above. The line with the arguments work, the mine with the program in stdin works, but the line without anything doesnt work anymore.

So i should check if the user as sent some file in stdin i call the program with a file, else i call it the normal way. I tried with feof but it can't work since stdin won't have anything in not even eof.
When i call the program without arguments or file it waits for the user to write something, which it shouldnt.

Basically my code should look like that

int main()
{
    int v;
    if (stdin!=NULL)) { //if a file has been passed "./test <test.txt"
        scanf("%d",&v);
    }
    else {  //if no files has been passed "./test "
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50) {
        printf("you drive slow\n");
    }
    else {
        printf("you drive fast\n");
    }
    return 0;
}

But obviously (stdin != NULL) doesn't work. So is there a way to check if stdin has something in?
I asked my classmate, one of them told me something about useing fgetc to get the first char and then put it back if there is really a char but when i try to use fgetc, if there is no char it waits for me to put a char in.

So how could I check if stdin is empty or if there is a file into it (without using new libraries)?

Thanks you in advance
have a good day

If i am not completely clear please tell it to me i am not a native speaker and i have a bit of difficulties since it's a technical question

Body:
It sounds like you want to run your program based on arguments either provided on the command line or piped into it from a file. If so, you should check whether the arguments have been provided on the command line first:

if (argc > 1) {
  //parse argv
}

Then, check whether stdin is empty, and if not read the arguments in from stdin:

else if ((fseek(stdin, 0, SEEK_END), ftell(stdin)) > 0)
{
  rewind(stdin);
  char buffer[1024];
  fgets(buffer, 1024 , stdin);
  //parse args read in from stdin
}
else
{
  //no redirection
}


问:
How to Calculate R^2 in Tensorflow
I am trying to do regression in Tensorflow. I'm not positive I am calculating R^2 correctly as Tensorflow gives me a different answer than sklearn.metrics.r2_score Can someone please look at my below code and let me know if I implemented the pictured equation correctly. Thanks

```<code>total_error = tf.square(tf.sub(y, tf.reduce_mean(y)))
unexplained_error = tf.square(tf.sub(y, prediction))
R_squared = tf.reduce_mean(tf.sub(tf.div(unexplained_error, total_error), 1.0))
R = tf.mul(tf.sign(R_squared),tf.sqrt(tf.abs(R_squared)))
</code>```

答:
I think it should be like this:</p>

```<code>total_error = tf.reduce_sum(tf.square(tf.sub(y, tf.reduce_mean(y))))
unexplained_error = tf.reduce_sum(tf.square(tf.sub(y, prediction)))
R_squared = tf.sub(1, tf.div(unexplained_error, total_error))
</code>```

Title: How to Calculate R^2 in Tensorflow

Body:
I am trying to do regression in Tensorflow. I'm not positive I am calculating R^2 correctly as Tensorflow gives me a different answer than sklearn.metrics.r2_score Can someone please look at my below code and let me know if I implemented the pictured equation correctly. Thanks

total_error = tf.square(tf.sub(y, tf.reduce_mean(y)))
unexplained_error = tf.square(tf.sub(y, prediction))
R_squared = tf.reduce_mean(tf.sub(tf.div(unexplained_error, total_error), 1.0))
R = tf.mul(tf.sign(R_squared),tf.sqrt(tf.abs(R_squared)))

Body:
I think it should be like this:

total_error = tf.reduce_sum(tf.square(tf.sub(y, tf.reduce_mean(y))))
unexplained_error = tf.reduce_sum(tf.square(tf.sub(y, prediction)))
R_squared = tf.sub(1, tf.div(unexplained_error, total_error))


问:
How do I make saving calculator like this?
Can some please help me with making a similar saving calculator just like this one at the bottom right corner of this page http://www.clickitrealtyinc.com/

I need to install something like this on my website and have no idea where to start.

答:
Very, very basic implementation. The user interface is pretty different ugly, but there you go.

The magic is the following formula:

```<code>output = (input - 599) * 0.03
</code>```

That's going to be the heart of your app, no matter how you build it.

ContentLicense: CC BY-SA 2.5

Body:
Very, very basic implementation. The user interface is pretty different ugly, but there you go.

The magic is the following formula:

output = (input - 599) * 0.03

That's going to be the heart of your app, no matter how you build it.


问:
UnhandledPromiseRejectionWarning: Callback was already called (Loopback remote method)
I'm getting an error that says

```<code>(node:27301) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.
</code>```

From what I understand about rejecting promises in await's and per the Mozilla description:

If the Promise is rejected, the await expression throws the rejected value.

I reject the error in the callback that's wrapped around my Promise like so:

```<code>Airport.nearbyAirports = async (location, cb) => {
  let airports
  try {
    airports = await new Promise((resolve, reject) => {
      Airport.find({
        // code
      }, (err, results) => {
        if (err)
          reject(err) // Reject here
        else
          resolve(results)
      })
    })
  } catch (err) { // Catch here
    cb(err, null)
    return
  }
  if (!airports.empty)
    cb(null, airports)
  }
</code>```

My question is

Why does it still consider my promise rejection unhandled? I thought the catch statement should silent this error.

Why does it consider my callback already called? I have a return statement in my catch, so both should never be called.

答:
If Airport.find() throws an exception, then execution will jump to your catch block and your Promise will never be resolved or rejected. Perhaps you need to wrap it in its own try/catch:

```<code>Airport.nearbyAirports = async (location, cb) => {
  let airports
  try {
    airports = await new Promise((resolve, reject) => {
      try {
        Airport.find({
          // code
        }, (err, results) => {
          if (err)
            reject(err) // Reject here
          else
            resolve(results)
        })
      } catch (err) {
        reject(err) // Reject here too
        cb(err, null)
      }
    })
  } catch (err) { // Catch here
    cb(err, null)
    return
  }
  if (!airports.empty)
    cb(null, airports)
  }
</code>```

Body:
I'm getting an error that says

(node:27301) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.

From what I understand about rejecting promises in await's and per the Mozilla description:

If the Promise is rejected, the await expression throws the rejected value.

I reject the error in the callback that's wrapped around my Promise like so:

Airport.nearbyAirports = async (location, cb) => {
  let airports
  try {
    airports = await new Promise((resolve, reject) => {
      Airport.find({
        // code
      }, (err, results) => {
        if (err)
          reject(err) // Reject here
        else
          resolve(results)
      })
    })
  } catch (err) { // Catch here
    cb(err, null)
    return
  }
  if (!airports.empty)
    cb(null, airports)
  }

My question is

Why does it still consider my promise rejection unhandled? I thought the catch statement should silent this error.

Why does it consider my callback already called? I have a return statement in my catch, so both should never be called.

Body:
If Airport.find() throws an exception, then execution will jump to your catch block and your Promise will never be resolved or rejected. Perhaps you need to wrap it in its own try/catch:

Airport.nearbyAirports = async (location, cb) => {
  let airports
  try {
    airports = await new Promise((resolve, reject) => {
      try {
        Airport.find({
          // code
        }, (err, results) => {
          if (err)
            reject(err) // Reject here
          else
            resolve(results)
        })
      } catch (err) {
        reject(err) // Reject here too
        cb(err, null)
      }
    })
  } catch (err) { // Catch here
    cb(err, null)
    return
  }
  if (!airports.empty)
    cb(null, airports)
  }


问:
Can a stream contain some fix huffman compressed block and some dynamic huffman compressed blocks
Is it possible to compress a stream with some blocks compressed with static Huffman encoding, and some blocks compressed with dynamic Huffman encoding? If yes, is it decompressible ?</p>

答: Yes, and yes. A stream can contain a mix of all three block types, with the third type being stored.</p>


问:
Problem installing Heroku with Rails3, Ruby 1.9.2
I am using Ubuntu 10.10, RVM and Ruby 1.9.2 and trying to install Heroku for the first time. Ruby 1.9.2 is the default for RVM and the only version I have been using.

The gem install heroku worked but trying to run heroku leads to "command not found" error. The executables folder /home/mike/.rvm/gems/ruby-1.9.2-p0/bin is already in the PATH. However, I see that Heroku was installed in /var/lib/gems/1.8/gems. gem list heroku does not show any installed gem. Simply creating symbolic links in .../ruby-1.9.2-p0 did not solve the problem, though it gives a different error:

```<code>/usr/lib/ruby/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem heroku (>= 0) (Gem::LoadError)
  from /usr/lib/ruby/1.8/rubygems.rb:214:in `activate'
  from /usr/lib/ruby/1.8/rubygems.rb:1082:in `gem'
  from /home/mike/.rvm/gems/ruby-1.9.2-p0/bin/heroku:18
</code>```

I don't understand gem and rvm well enough to know what to try next. I read in another question that Heroku supports Ruby 1.9.1 but not 1.9.2 but don't know if that is still true. If so, how does one use Rails and Ruby 1.9.x with Heroku?

答: Had the exact same problem on Mac OSX 10.6.5.  Reinstalling without sudo worked in this case also.  Thanks for the explanation... being a nube, I would have never figured it out.</p>

Body:
I am using Ubuntu 10.10, RVM and Ruby 1.9.2 and trying to install Heroku for the first time. Ruby 1.9.2 is the default for RVM and the only version I have been using.

The gem install heroku worked but trying to run heroku leads to "command not found" error. The executables folder /home/mike/.rvm/gems/ruby-1.9.2-p0/bin is already in the PATH. However, I see that Heroku was installed in /var/lib/gems/1.8/gems. gem list heroku does not show any installed gem. Simply creating symbolic links in .../ruby-1.9.2-p0 did not solve the problem, though it gives a different error:

/usr/lib/ruby/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem heroku (>= 0) (Gem::LoadError)
  from /usr/lib/ruby/1.8/rubygems.rb:214:in `activate'
  from /usr/lib/ruby/1.8/rubygems.rb:1082:in `gem'
  from /home/mike/.rvm/gems/ruby-1.9.2-p0/bin/heroku:18

I don't understand gem and rvm well enough to know what to try next. I read in another question that Heroku supports Ruby 1.9.1 but not 1.9.2 but don't know if that is still true. If so, how does one use Rails and Ruby 1.9.x with Heroku?


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
Well, if ch has a single bit set, then the count of 1 bits in ch-1 is the index of that bit.  Ideally, you'd want to find that without looping or branching, since branches are expensive, so I'd write that something like this:

```<code>int index = ((unsigned char)ch)-1;
index = ((index & 0xAA)>>1)+(index & 0x55);  //sums of pairs of bits
index = ((index & 0xCC)>>2)+(index & 0x33);  //sums of 4s of bits
index = ((index & 0xF0)>>4)+(index & 0x0F);  //sum of 8 bits
</code>```

There is also an extremely clever answer using fewer operations at the cost of a multiplication and a lookup:

```<code>int index = indexMap[((((int)(unsigned char)ch)*DEBRUIJN)>>16)&7];
</code>```

The bits in DEBRUIJN must be a De Bruijn sequence (https://en.wikipedia.org/wiki/De_Bruijn_sequence), ensuring that lookup index will be different for every value of ch.  indexMap maps those lookup indexes to the results you want.

Note also that, following @rici's comment, indexMap is so small that you can pack it into a single int.

Body:
Well, if ch has a single bit set, then the count of 1 bits in ch-1 is the index of that bit.  Ideally, you'd want to find that without looping or branching, since branches are expensive, so I'd write that something like this:

int index = ((unsigned char)ch)-1;
index = ((index & 0xAA)>>1)+(index & 0x55);  //sums of pairs of bits
index = ((index & 0xCC)>>2)+(index & 0x33);  //sums of 4s of bits
index = ((index & 0xF0)>>4)+(index & 0x0F);  //sum of 8 bits

There is also an extremely clever answer using fewer operations at the cost of a multiplication and a lookup:

int index = indexMap[((((int)(unsigned char)ch)*DEBRUIJN)>>16)&7];

The bits in DEBRUIJN must be a De Bruijn sequence (https://en.wikipedia.org/wiki/De_Bruijn_sequence), ensuring that lookup index will be different for every value of ch.  indexMap maps those lookup indexes to the results you want.

Note also that, following @rici's comment, indexMap is so small that you can pack it into a single int.


问:
Android: Same Image needs to be added in all drawable folders?
I am directly adding images in drawable folders and it is coming fine with ImageView tag android:src="@drawable/image_name" but I wonder what to do with the other drawable folders as shown below.

Do I need to add same image in all drawable folders or my way of adding images in drawable folders is wrong?

Please help me!

答:
The image is same, but the size should be different for each folders.
If you add the image only in drawable folder, same image will be loaded for all screen resolutions. So for eg: if the image size is small, this may result in bad image quality.

You can find a similar question here

I use Android studio plugin Android Drawable Importer


问:
sjplot sjt.corr doesn't appear to play nice in a loop in R
Amateur user of R and just having difficulties with simplifying some code. I have a list of dataframes of test results and I would like run the sjt.corr function across these dataframes for quality assurance.

Edit

A small reproducible example:

```<code>library(sjplot)
list <- list()
list$a <- as.data.frame(cbind(c(1,2,3,4,5,6,7,8),c(1,2,3,4,5,7,6,8)))
list$b <- as.data.frame(cbind(c(1,2,3,4,5,7,6,8),c(7,6,8,5,4,3,2,1)))
list$c <- as.data.frame(cbind(c(7,6,8,5,4,3,2,1),c(1,2,3,4,5,6,7,8)))
</code>```

I am not sure where my loop fails me. If you can see the error please let me know:

```<code>for (i in seq_along(list)) {
  sjt.corr(
    list[[i]],
    na.deletion = "pairwise",
    corr.method = "spearman",
    file = paste("consensus", i, "html", sep = ".")
  )
}
</code>```

Appears to work silently, but does not save anything.

This works:

```<code>sjt.corr(
  list[[1]],
  na.deletion = "pairwise",
  corr.method = "spearman",
  file = paste("consensus", 1, "html", sep = ".")
)
</code>```

答:
So a solution from my friend is to just use lapply.

```<code>i <- 0

lapply(list, function(x) {
  i <<- i + 1
  sjt.corr(
    x,
    na.deletion = "pairwise",
    corr.method = "spearman",
    file = paste("consensus", i, "html", sep = "."))
})
</code>```

Which works great! Still unsure why the original for loop does not work. Any reference to another similar scenario would be great.

Body:
Amateur user of R and just having difficulties with simplifying some code. I have a list of dataframes of test results and I would like run the sjt.corr function across these dataframes for quality assurance.

Edit

A small reproducible example:

library(sjplot)
list <- list()
list$a <- as.data.frame(cbind(c(1,2,3,4,5,6,7,8),c(1,2,3,4,5,7,6,8)))
list$b <- as.data.frame(cbind(c(1,2,3,4,5,7,6,8),c(7,6,8,5,4,3,2,1)))
list$c <- as.data.frame(cbind(c(7,6,8,5,4,3,2,1),c(1,2,3,4,5,6,7,8)))

I am not sure where my loop fails me. If you can see the error please let me know:

for (i in seq_along(list)) {
  sjt.corr(
    list[[i]],
    na.deletion = "pairwise",
    corr.method = "spearman",
    file = paste("consensus", i, "html", sep = ".")
  )
}

Appears to work silently, but does not save anything.

This works:

sjt.corr(
  list[[1]],
  na.deletion = "pairwise",
  corr.method = "spearman",
  file = paste("consensus", 1, "html", sep = ".")
)

Body:
So a solution from my friend is to just use lapply.

i <- 0

lapply(list, function(x) {
  i <<- i + 1
  sjt.corr(
    x,
    na.deletion = "pairwise",
    corr.method = "spearman",
    file = paste("consensus", i, "html", sep = "."))
})

Which works great! Still unsure why the original for loop does not work. Any reference to another similar scenario would be great.


问:
Built in function for searching sorted array in C
Is there a built in function in C for searching an integer array that has been sorted?

I can easily implement it but it seems like such a common thing - would be weird if there is no library/built in C function.

答:
There is bsearch() for binary search in sorted array https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm

Example:

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

int cmp_int(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return (a > b) - (a < b);
}

int values[] = { 5, 20, 29, 32, 63 };

int main () {
    int *item;
    int key = 32;

    /* using bsearch() to find value 32 in the array */
    item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
    if( item != NULL ) {
        printf("Found item = %d\n", *item);
    } else {
        printf("Item = %d could not be found\n", *item);
    }

    return(0);
}
</code>```

UPD
Added proper comparer by @jonathan-leffler

Body:
There is bsearch() for binary search in sorted array https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm

Example:

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

int cmp_int(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return (a > b) - (a < b);
}

int values[] = { 5, 20, 29, 32, 63 };

int main () {
    int *item;
    int key = 32;

    /* using bsearch() to find value 32 in the array */
    item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
    if( item != NULL ) {
        printf("Found item = %d\n", *item);
    } else {
        printf("Item = %d could not be found\n", *item);
    }

    return(0);
}

UPD
Added proper comparer by @jonathan-leffler


问:
How to use foreach to verify value in a 3-dimensional array without having duplicated output in php?
Hi my question is a little tricky, I got a 3-dimensional array and try to verify the 3rd level value and echo both 1st and 3rd level values.
The following is the code example, and my failed approaches.

```<code>$myArray=array(
"mySub0" => arrary(
  0 => array("mySubSub0" => "1","mySubSub1" => "a"),
  1 => array("mySubSub0" => "2","mySubSub1" => "b"),
  2 => array("mySubSub0" => "3","mySubSub1" => "b"),
 ),
 "mySub1" => arrary(
  0 => array("mySubSub0" => "4","mySubSub1" => "a"),
  1 => array("mySubSub0" => "5","mySubSub1" => "a"),
  2 => array("mySubSub0" => "6","mySubSub1" => "a"),
 ),
 "mySub2" => arrary(
  0 => array("mySubSub0" => "7","mySubSub1" => "a"),
  1 => array("mySubSub0" => "8","mySubSub1" => "b"),
  2 => array("mySubSub0" => "9","mySubSub1" => "a"),
 ),
),
</code>```

I want to check if the value of "mySubSub1" is b. if yes, echo the value of "mySubSub0" and the related key in first-level of the array. It should be like this:

```<code>mySub0
2
3
mySub2
8
</code>```

My failed approach is

```<code> foreach ($myArray as $a => $b)
 {
 foreach ($b as $c)
 if($c[mySubSub1]=="b")
    {
        echo $a
        echo $c[mySubSub0];
    }
 else {
    }
 }
</code>```

The result will have one duplicate mySub0

```<code> mySub0
 2
 mySub0
 3
 mySub2
 8
</code>```

if I move the "echo $a" out of the "if"

```<code>foreach ($myArray as $a => $b)
 {
 echo $a
 foreach ($b as $c)
 if($c[mySubSub1]=="b")
        {
        echo $c[mySubSub0];
    }
 else {
    }
 }
</code>```

the result would be

```<code> mySub0
 2
 3
 mySub1
 mySub2
 8
</code>```

one unwanted "mySub1" because there is no place to verify if there is a value b.

It has bothered my a lot today. I tried to Google but haven't found the right answer.
 Really hope someone can help me. Thank you in advance

答:
Here's something that should work:

```<code>function find_value($arr, $key, $value, $sibling)
{
    foreach ($arr as $k => $v)
    {
        $results = _find_value($v, $key, $value, $sibling);
        if (count($results) > 0) {
            echo $k;
            foreach ($results as $result) {
                echo $result;
            }
        }
    }
}

function _find_value($arr, $key, $value, $sibling)
{
    $out = array();
    foreach ($arr as $k => $v)
    {
        if ($v[$key] == $value)
            $out[] = $v[$sibling];
    }
    return $out;
}

find_value($myArray, "mySubSub1", "b", "mySubSub0");
</code>```

Basically, the main function loops over items in the outer array, calling the inner function to get a list of the "sibling" keys where the main key matches the value you're looking for. If a non-zero number of results are obtained in the inner function, echo and loop.

Hopefully this does the trick for you.

Body:
Hi my question is a little tricky, I got a 3-dimensional array and try to verify the 3rd level value and echo both 1st and 3rd level values.
The following is the code example, and my failed approaches.

$myArray=array(
"mySub0" => arrary(
  0 => array("mySubSub0" => "1","mySubSub1" => "a"),
  1 => array("mySubSub0" => "2","mySubSub1" => "b"),
  2 => array("mySubSub0" => "3","mySubSub1" => "b"),
 ),
 "mySub1" => arrary(
  0 => array("mySubSub0" => "4","mySubSub1" => "a"),
  1 => array("mySubSub0" => "5","mySubSub1" => "a"),
  2 => array("mySubSub0" => "6","mySubSub1" => "a"),
 ),
 "mySub2" => arrary(
  0 => array("mySubSub0" => "7","mySubSub1" => "a"),
  1 => array("mySubSub0" => "8","mySubSub1" => "b"),
  2 => array("mySubSub0" => "9","mySubSub1" => "a"),
 ),
),

I want to check if the value of "mySubSub1" is b. if yes, echo the value of "mySubSub0" and the related key in first-level of the array. It should be like this:

mySub0
2
3
mySub2
8

My failed approach is

 foreach ($myArray as $a => $b)
 {
 foreach ($b as $c)
 if($c[mySubSub1]=="b")
    {
        echo $a
        echo $c[mySubSub0];
    }
 else {
    }
 }

The result will have one duplicate mySub0

 mySub0
 2
 mySub0
 3
 mySub2
 8

if I move the "echo $a" out of the "if"

foreach ($myArray as $a => $b)
 {
 echo $a
 foreach ($b as $c)
 if($c[mySubSub1]=="b")
        {
        echo $c[mySubSub0];
    }
 else {
    }
 }

the result would be

 mySub0
 2
 3
 mySub1
 mySub2
 8

one unwanted "mySub1" because there is no place to verify if there is a value b.

It has bothered my a lot today. I tried to Google but haven't found the right answer.
 Really hope someone can help me. Thank you in advance

Body:
Here's something that should work:

function find_value($arr, $key, $value, $sibling)
{
    foreach ($arr as $k => $v)
    {
        $results = _find_value($v, $key, $value, $sibling);
        if (count($results) > 0) {
            echo $k;
            foreach ($results as $result) {
                echo $result;
            }
        }
    }
}

function _find_value($arr, $key, $value, $sibling)
{
    $out = array();
    foreach ($arr as $k => $v)
    {
        if ($v[$key] == $value)
            $out[] = $v[$sibling];
    }
    return $out;
}

find_value($myArray, "mySubSub1", "b", "mySubSub0");

Basically, the main function loops over items in the outer array, calling the inner function to get a list of the "sibling" keys where the main key matches the value you're looking for. If a non-zero number of results are obtained in the inner function, echo and loop.

Hopefully this does the trick for you.


问:
Python 3.6 connection to MS SQL Server for large dataframe
I am a new Python coder and also a new data scientist so please forgive any foolish sounding things here. I'll keep the details out unless anyone's curious but basically I need to connect to Microsoft SQL Server and upload a Pandas DF that is relatively large (~500k rows) and I need to do this almost every day as the project currently stands.

It doesn't have to be a Pandas DF - I've read about using odo for csv files but I haven't been able to get anything to work. The issue I'm having is that I can't bulk insert the DF because the file isn't on the same machine as the SQL Server instance. I'm consistently getting errors like the following:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL
  Server Driver][SQL Server]Incorrect syntax near the keyword 'IF'.
  (156) (SQLExecDirectW)")

As I've attempted different SQL statements you can replace IF with whatever has been the first COL_NAME in the CREATE statement. I'm using SQLAlchemy to create the engine and connect to the database. This may go without saying but the pd.to_sql() method is just way too slow for how much data I'm moving so that's why I need something faster.

I'm using Python 3.6 by the way. I've put down here most of the things that I've tried that haven't been successful.

```<code>import pandas as pd
from sqlalchemy import create_engine
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('test_col'))
address = 'mssql+pyodbc://uid:pw@server/path/database?driver=SQL Server'
engine = create_engine(address)
connection = engine.raw_connection()
cursor = connection.cursor()
# Attempt 1 <- This failed to even create a table at the cursor_execute statement so my issues could be way in the beginning here but I know that I have a connection to the SQL Server because I can use pd.to_sql() to create tables successfully (just incredibly slowly for my tables of interest)
create_statement = """
DROP TABLE test_table
CREATE TABLE test_table (test_col)
"""
cursor.execute(create_statement)
test_insert = '''
INSERT INTO test_table
(test_col)
values ('abs');
'''
cursor.execute(test_insert)

Attempt 2 <- From iabdb WordPress blog I came across
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
records = [str(tuple(x)) for x in take_rates.values]

insert_ = """
INSERT INTO test_table
("A")
VALUES
"""

for batch in chunker(records, 2): # This would be set to 1000 in practice I hope
    print(batch)
    rows = str(batch).strip('[]')
    print(rows)
    insert_rows = insert_ + rows
    print(insert_rows)
    cursor.execute(insert_rows)
    #conn.commit() # don't know when I would need to commit

conn.close()

# Attempt 3 # From a related Stack Exchange Post
 create the table but first drop if it already exists
command = """DROP TABLE IF EXISTS test_table
CREATE TABLE test_table # these columns are from my real dataset
"Serial Number" serial primary key,
"Dealer Code" text,
"FSHIP_DT" timestamp without time zone,
;"""
cursor.execute(command)
connection.commit()

# stream the data using 'to_csv' and StringIO(); then use sql's 'copy_from' function
output = io.StringIO()
# ignore the index
take_rates.to_csv(output, sep='~', header=False, index=False)
# jump to start of stream
output.seek(0)
contents = output.getvalue()
cur = connection.cursor()
# null values become ''
cur.copy_from(output, 'Config_Take_Rates_TEST', null="")
connection.commit()
cur.close()
</code>```

It seems to me that MS SQL Server is just not a nice Database to play around with...
I want to apologize for the rough formatting - I've been at this script for weeks now but just finally decided to try to organize something for StackOverflow. Thank you very much for any help anyone can offer!

答:
If you only need to replace the existing table, truncate it and use bcp utility to upload the table.  It's much faster.

```<code>from subprocess import call

command = "TRUNCATE TABLE test_table"
take_rates.to_csv('take_rates.csv', sep='\t', index=False)
call('bcp {t} in {f} -S {s} -U {u} -P {p} -d {db} -c -t "{sep}" -r "{nl}" -e {e}'.format(t='test_table', f='take_rates.csv', s=server, u=user, p=password, db=database, sep='\t', nl='\n')
</code>```

You will need to install bcp utility (yum install mssql-tools on CentOS/RedHat).

Body:
I am a new Python coder and also a new data scientist so please forgive any foolish sounding things here. I'll keep the details out unless anyone's curious but basically I need to connect to Microsoft SQL Server and upload a Pandas DF that is relatively large (~500k rows) and I need to do this almost every day as the project currently stands.

It doesn't have to be a Pandas DF - I've read about using odo for csv files but I haven't been able to get anything to work. The issue I'm having is that I can't bulk insert the DF because the file isn't on the same machine as the SQL Server instance. I'm consistently getting errors like the following:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL
  Server Driver][SQL Server]Incorrect syntax near the keyword 'IF'.
  (156) (SQLExecDirectW)")

As I've attempted different SQL statements you can replace IF with whatever has been the first COL_NAME in the CREATE statement. I'm using SQLAlchemy to create the engine and connect to the database. This may go without saying but the pd.to_sql() method is just way too slow for how much data I'm moving so that's why I need something faster.

I'm using Python 3.6 by the way. I've put down here most of the things that I've tried that haven't been successful.

import pandas as pd
from sqlalchemy import create_engine
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('test_col'))
address = 'mssql+pyodbc://uid:pw@server/path/database?driver=SQL Server'
engine = create_engine(address)
connection = engine.raw_connection()
cursor = connection.cursor()
# Attempt 1 <- This failed to even create a table at the cursor_execute statement so my issues could be way in the beginning here but I know that I have a connection to the SQL Server because I can use pd.to_sql() to create tables successfully (just incredibly slowly for my tables of interest)
create_statement = """
DROP TABLE test_table
CREATE TABLE test_table (test_col)
"""
cursor.execute(create_statement)
test_insert = '''
INSERT INTO test_table
(test_col)
values ('abs');
'''
cursor.execute(test_insert)

Attempt 2 <- From iabdb WordPress blog I came across
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
records = [str(tuple(x)) for x in take_rates.values]

insert_ = """
INSERT INTO test_table
("A")
VALUES
"""

for batch in chunker(records, 2): # This would be set to 1000 in practice I hope
    print(batch)
    rows = str(batch).strip('[]')
    print(rows)
    insert_rows = insert_ + rows
    print(insert_rows)
    cursor.execute(insert_rows)
    #conn.commit() # don't know when I would need to commit

conn.close()

# Attempt 3 # From a related Stack Exchange Post
 create the table but first drop if it already exists
command = """DROP TABLE IF EXISTS test_table
CREATE TABLE test_table # these columns are from my real dataset
"Serial Number" serial primary key,
"Dealer Code" text,
"FSHIP_DT" timestamp without time zone,
;"""
cursor.execute(command)
connection.commit()

# stream the data using 'to_csv' and StringIO(); then use sql's 'copy_from' function
output = io.StringIO()
# ignore the index
take_rates.to_csv(output, sep='~', header=False, index=False)
# jump to start of stream
output.seek(0)
contents = output.getvalue()
cur = connection.cursor()
# null values become ''
cur.copy_from(output, 'Config_Take_Rates_TEST', null="")
connection.commit()
cur.close()

It seems to me that MS SQL Server is just not a nice Database to play around with...
I want to apologize for the rough formatting - I've been at this script for weeks now but just finally decided to try to organize something for StackOverflow. Thank you very much for any help anyone can offer!

Body:
If you only need to replace the existing table, truncate it and use bcp utility to upload the table.  It's much faster.

from subprocess import call

command = "TRUNCATE TABLE test_table"
take_rates.to_csv('take_rates.csv', sep='\t', index=False)
call('bcp {t} in {f} -S {s} -U {u} -P {p} -d {db} -c -t "{sep}" -r "{nl}" -e {e}'.format(t='test_table', f='take_rates.csv', s=server, u=user, p=password, db=database, sep='\t', nl='\n')

You will need to install bcp utility (yum install mssql-tools on CentOS/RedHat).


问:
Remove
 tags from the beginning and end of a string
How would I, given a string like this (for example), remove all break (
,
, and any other form) tags from only the beginning and end of the string?

Original string:

```<code><br>Hello, World! https://www.youtube.com/watch?v=NU7W7qe2R0A<br><br>
</code>```

Output:

```<code>Hello, World! https://www.youtube.com/watch?v=NU7W7qe2R0A
</code>```

If the original string has
 tags in the middle of the string, i.e.:

```<code><br>Hello, World!<br><br>https://www.youtube.com/watch?v=NU7W7qe2R0A<br><br>
</code>```

It should output:

```<code>Hello, World!<br><br>https://www.youtube.com/watch?v=NU7W7qe2R0A
</code>```

How would I achieve this results?

答:
This is what I use in my projects :</p>

```<code>Code below will handle : <br>, <br >, <br   >, <br/>, <br />, <br   />

$data = "<br><br ><br/><br />test1<br><br  ><br />test2<br><br ><br/><br />";
$str = preg_replace('/^(<br\s*?\/?>)+|(<br\s*\/?>)+$/', '', $data);
echo $str;
</code>```

Title: Remove <br> tags from the beginning and end of a string

Body:
How would I, given a string like this (for example), remove all break (
,
, and any other form) tags from only the beginning and end of the string?

Original string:

Hello, World! https://www.youtube.com/watch?v=NU7W7qe2R0A

Output:

Hello, World! https://www.youtube.com/watch?v=NU7W7qe2R0A

If the original string has
 tags in the middle of the string, i.e.:

Hello, World!

https://www.youtube.com/watch?v=NU7W7qe2R0A

It should output:

Hello, World!

https://www.youtube.com/watch?v=NU7W7qe2R0A

How would I achieve this results?

Body:
This is what I use in my projects :

Code below will handle : <br>, <br >, <br   >, <br/>, <br />, <br   />

$data = "<br><br ><br/><br />test1<br><br  ><br />test2<br><br ><br/><br />";
$str = preg_replace('/^(<br\s*?\/?>)+|(<br\s*\/?>)+$/', '', $data);
echo $str;


问:
javascript three dots syntax
I'm using Vuetify for a vue app, in this file I saw a very strange syntax which I can't find what it is

on line 38:

```<code>const data = {
    attrs: { disabled: this.disabled },
    class: this.classes,
    props: {},
    directives: [{
      name: 'ripple',
      value: this.ripple || false
    }],
    on: {
      ...(this.$listeners || {}),  // <<<---- here
      click: this.click
    }
  }
</code>```

can anyone tell what is that three dots? any articles about this would be nice

thanks

答:
That's the spread operator! It grabs all the properties from the object. </p>

<p>In that example, it'll copy the object without mutating it. </p>

Title: javascript three dots syntax

Body:
I'm using Vuetify for a vue app, in this file I saw a very strange syntax which I can't find what it is

on line 38:

const data = {
    attrs: { disabled: this.disabled },
    class: this.classes,
    props: {},
    directives: [{
      name: 'ripple',
      value: this.ripple || false
    }],
    on: {
      ...(this.$listeners || {}),  // <<<---- here
      click: this.click
    }
  }

can anyone tell what is that three dots? any articles about this would be nice

thanks

Body:
That's the spread operator! It grabs all the properties from the object.

In that example, it'll copy the object without mutating it.