问:
C# - How can i get the count of child elements using LINQ to XML
This is an extract of the XML i'm using

```<code>    <AccountNumber>
      <RecordID>A9</RecordID>
      <SegmentLength>14</SegmentLength>
      <Number>6770307103</Number>
    </AccountNumber>
    <PaymentCounter>
      <RecordID>B2</RecordID>
      <SegmentLength>14</SegmentLength>
      <History>99</History>
      <Delinq30Day>00</Delinq30Day>
      <Delinq60Day>00</Delinq60Day>
      <Delinq90PlusDay>00</Delinq90PlusDay>
      <DerogCnt>00</DerogCnt>
    </PaymentCounter>
</code>```

Here I'm trying to identify the number of child elements under AccountNumber and PaymentCounter.

I'm looking for this answer
AccountNumber count = 3
PaymentCounter count = 7

After I get the count, I will use the data to dynamically populate a table.

I tried this :
int count1 = xmlDocument.Descendants("AccountNumber").Count();

The count() in LINQ to XML will give me the number of times element "AccountNumber" is repeated in the XML, but doesnot give me the number of child elements.

Is there a way to do this?

答:
From MSDN
XDocument.Descendants
Returns a collection of the descendant elements for this document or element, in document order

if you so something like the following

var  elements =    xmlDocument.Descendants("AccountNumber").

you will get all the AccountNumber elements
you have to iterate through each element in  order to get the count of each element

```<code> foreach (var xElement in elements )
            {
                var acElt= xElement.Descendants().Count();

                     //then do your construction here
            }
</code>```

Body:
This is an extract of the XML i'm using

    <AccountNumber>
      <RecordID>A9</RecordID>
      <SegmentLength>14</SegmentLength>
      <Number>6770307103</Number>
    </AccountNumber>
    <PaymentCounter>
      <RecordID>B2</RecordID>
      <SegmentLength>14</SegmentLength>
      <History>99</History>
      <Delinq30Day>00</Delinq30Day>
      <Delinq60Day>00</Delinq60Day>
      <Delinq90PlusDay>00</Delinq90PlusDay>
      <DerogCnt>00</DerogCnt>
    </PaymentCounter>

Here I'm trying to identify the number of child elements under AccountNumber and PaymentCounter.

I'm looking for this answer
AccountNumber count = 3
PaymentCounter count = 7

After I get the count, I will use the data to dynamically populate a table.

I tried this :
int count1 = xmlDocument.Descendants("AccountNumber").Count();

The count() in LINQ to XML will give me the number of times element "AccountNumber" is repeated in the XML, but doesnot give me the number of child elements.

Is there a way to do this?

Body:
From MSDN
XDocument.Descendants
Returns a collection of the descendant elements for this document or element, in document order

if you so something like the following

var  elements =    xmlDocument.Descendants("AccountNumber").

you will get all the AccountNumber elements
you have to iterate through each element in  order to get the count of each element

 foreach (var xElement in elements )
            {
                var acElt= xElement.Descendants().Count();

                     //then do your construction here
            }


来源: stackexchange

问:
firebase cloud function won't store cookie named other than "__session"
i followed the sample of authorized-https-endpoint and only added console.log to print the req.cookies, the problem is the cookies are always empty {} I set the cookies using client JS calls and they do save but from some reason, I can't get them on the server side.

here is the full code of index.js, it's exactly the same as the sample:

```<code>'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
const app = express();

const validateFirebaseIdToken = (req, res, next) => {
  console.log(req.cookies); //// <----- issue this is empty {} why??
  next();
};

app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);
app.get('/hello', (req, res) => {
  res.send(`Hello!!`);
});

exports.app = functions.https.onRequest(app);
</code>```

store cookie:

curl http://FUNCTION_URL/hello --cookie "__session=bar" // req.cookies =
 {__session: bar}

doesn't store:

curl http://FUNCTION_URL/hello --cookie "foo=bar" // req.cookies =
 {}

答:
If you are using Firebase Hosting + Cloud Functions, __session is the only cookie you can store, by design. This is necessary for us to be able to efficiently cache content on the CDN -- we strip all cookies from the request other than __session. This should be documented but doesn't appear to be (oops!). We'll update documentation to reflect this limitation.

Also, you need to set Cache-Control Header as private

```<code>res.setHeader('Cache-Control', 'private');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i followed the sample of authorized-https-endpoint and only added console.log to print the req.cookies, the problem is the cookies are always empty {} I set the cookies using client JS calls and they do save but from some reason, I can't get them on the server side.

here is the full code of index.js, it's exactly the same as the sample:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
const app = express();

const validateFirebaseIdToken = (req, res, next) => {
  console.log(req.cookies); //// <----- issue this is empty {} why??
  next();
};

app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);
app.get('/hello', (req, res) => {
  res.send(`Hello!!`);
});

exports.app = functions.https.onRequest(app);

store cookie:

curl http://FUNCTION_URL/hello --cookie "__session=bar" // req.cookies =
 {__session: bar}

doesn't store:

curl http://FUNCTION_URL/hello --cookie "foo=bar" // req.cookies =
 {}

Body:
If you are using Firebase Hosting + Cloud Functions, __session is the only cookie you can store, by design. This is necessary for us to be able to efficiently cache content on the CDN -- we strip all cookies from the request other than __session. This should be documented but doesn't appear to be (oops!). We'll update documentation to reflect this limitation.

Also, you need to set Cache-Control Header as private

res.setHeader('Cache-Control', 'private');


问:
use response write to make a link
I have a urlcolumn and a title column and i want the link to be automatically made in asp</p>

```<code> <td><%response.write(<a href="rs.fields.item("urlcolumn")target=_"blank">rs.fields.item("titlecolumn")</a>)%></td>
</code>```

答:
At the minimum, you will need to quote the output value for Response.Write to work, i.e.

```<code><td><%Response.Write("<a href='" + rs.fields.item("urlcolumn") + "' target='_blank'>" + rs.fields.item("titlecolumn") + "</a>")%></td>
</code>```

EDIT (updated my code sample).

EDIT #2 - Make sure to clean any input going into these links.  Creating links this way makes you very vulnerable to a XSS attack (especially since the href attribute can actually execute Javascript).

ContentLicense: CC BY-SA 2.5

Title: use response write to make a link

Body:
I have a urlcolumn and a title column and i want the link to be automatically made in asp

 <%response.write(rs.fields.item("titlecolumn"))%>

Body:
At the minimum, you will need to quote the output value for Response.Write to work, i.e.

<td><%Response.Write("<a href='" + rs.fields.item("urlcolumn") + "' target='_blank'>" + rs.fields.item("titlecolumn") + "</a>")%></td>

EDIT (updated my code sample).

EDIT #2 - Make sure to clean any input going into these links.  Creating links this way makes you very vulnerable to a XSS attack (especially since the href attribute can actually execute Javascript).


问:
How do paging and filter work well?
I have a table with paging and filter. I set the limit to 5 and it work's well when the page is loaded, but when I use a filter to fetch the data, its shows me more than 5 rows. I hope it can keep limit 5 and paging.

```<code>@foreach($products as $item)
    <tr name='items'>
        <td><a href="#" name='type' data-pk='{{$item->id}}'>{{$item->type_id}}</a></td>
        <td><input class = 'imgInp btn btn-default' type="file" name="icon" data-input="false">
            <img />
            <button class='btn btn-primary' style='display:none'>upload</button>
            <button class='btn btn-danger' style='display:none'>cancel</button>
        </td>
        <td><a href="#" name='name' data-pk='{{$item->id}}' class="editable">{{$item->name}}</a></td>
        <td><a href="#" name='pricing' data-pk='{{$item->id}}' class="editable">{{$item->pricing}}</a></td>
        <td><a href="#" name='short_description' data-pk='{{$item->id}}' class="editable">{{$item->short_description}}</a></td>
        <td><a href='#' class="fa fa-trash fa-lg" aria-hidden="true" data-pk='{{$item->id}}' name='delete'></a></td>
    </tr>
@endforeach
</code>```

here is my code

  $('#search').keyup(function(){
  var input, filter, table, tr, td, i;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  table = document.getElementById("product_table");
  tr = $("tr[name=items]");
  for (i = 0; i
 -1 ||
          td_1.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_2.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_3.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_4.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   .thumb {
   height: 100px;
   border: 1px solid #000;
   margin: 10px 5px 0 0;
   }
   .paging-nav {
   text-align: right;
   padding-top: 2px;
   }
   .paging-nav a {
   margin: auto 1px;
   text-decoration: none;
   display: inline-block;
   padding: 1px 7px;
   background: #91b9e6;
   color: white;
   border-radius: 3px;
   }
   .paging-nav .selected-page {
   background: #187ed5;
   font-weight: bold;
   }
   #search_product{
    float: right;
    padding-bottom: 10px;
   }</code>```

<link href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" rel="stylesheet"/>

                 search
                 <input type="text" id="search" class="form-control" placeholder="  ">

               type
               icon
               name
               pricing
               note
               delete

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

<<123>>

```

Fiddle

答:
Simply add a counter:

```<code>$('#search').keyup(function(){
  var input, filter, table, tr, td, i, count = 0;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  table = document.getElementById("product_table");
  tr = $("tr[name=items]");
  for (i = 0; i < tr.length && count < 5; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    td_1 = tr[i].getElementsByTagName("td")[1];
    td_2 = tr[i].getElementsByTagName("td")[2];
    td_3 = tr[i].getElementsByTagName("td")[3];
    td_4 = tr[i].getElementsByTagName("td")[4];
    if (td || td_1 || td_2 || td_3 || td_4) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_1.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_2.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_3.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_4.innerHTML.toUpperCase().indexOf(filter) > -1) {
        count++;
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
  });
</code>```

Also, you may want to get rid of all of your magic numbers and use jQuery a little more effectively. If I were to rewrite your code, I'd do it as follows:

```<code>$('#search').keyup(function () {
  const maxNums = 5;
  var filter = $(this).val().toUpperCase(),
      count  = 0;

  $('tr[name="items"]').each(function () {
    if (count >= maxNums) return;

    var possible = true;
    $('td', this).each(function () {
      if ($(this).html().toUpperCase().indexOf(filter) < 0) {
        possible = false;
      }
    })

    if (possible) {
      if (count++ < maxNums) {
        $(this).css('display', 'block');
      }
    } else {
      $(this).css('display', 'none');
    }
  });
});
</code>```

I'm sure there are many on this site who could perform this even better than I. :)

Title: How do paging and filter work well?

Body:
I have a table with paging and filter. I set the limit to 5 and it work's well when the page is loaded, but when I use a filter to fetch the data, its shows me more than 5 rows. I hope it can keep limit 5 and paging.

@foreach($products as $item)

        id}}'>{{$item->type_id}}
        <input class = 'imgInp btn btn-default' type="file" name="icon" data-input="false">

            <button class='btn btn-primary' style='display:none'>upload</button>
            <button class='btn btn-danger' style='display:none'>cancel</button>

        id}}' class="editable">{{$item->name}}
        id}}' class="editable">{{$item->pricing}}
        id}}' class="editable">{{$item->short_description}}
        id}}' name='delete'>

@endforeach

here is my code

  $('#search').keyup(function(){
  var input, filter, table, tr, td, i;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  table = document.getElementById("product_table");
  tr = $("tr[name=items]");
  for (i = 0; i
 -1 ||
          td_1.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_2.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_3.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_4.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
  });

   .thumb {
   height: 100px;
   border: 1px solid #000;
   margin: 10px 5px 0 0;
   }
   .paging-nav {
   text-align: right;
   padding-top: 2px;
   }
   .paging-nav a {
   margin: auto 1px;
   text-decoration: none;
   display: inline-block;
   padding: 1px 7px;
   background: #91b9e6;
   color: white;
   border-radius: 3px;
   }
   .paging-nav .selected-page {
   background: #187ed5;
   font-weight: bold;
   }
   #search_product{
    float: right;
    padding-bottom: 10px;
   }

<link href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" rel="stylesheet"/>

                 search
                 <input type="text" id="search" class="form-control" placeholder="  ">

               type
               icon
               name
               pricing
               note
               delete

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               10
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

               0
               <input class="imgInp btn btn-default" type="file" name="icon" data-input="false">

                  <button class="btn btn-primary" style="display:none">upload</button>
                  <button class="btn btn-danger" style="display:none">cancel</button>

               name
               20
               note

<<123>>

Fiddle

Body:
Simply add a counter:

$('#search').keyup(function(){
  var input, filter, table, tr, td, i, count = 0;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  table = document.getElementById("product_table");
  tr = $("tr[name=items]");
  for (i = 0; i < tr.length && count < 5; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    td_1 = tr[i].getElementsByTagName("td")[1];
    td_2 = tr[i].getElementsByTagName("td")[2];
    td_3 = tr[i].getElementsByTagName("td")[3];
    td_4 = tr[i].getElementsByTagName("td")[4];
    if (td || td_1 || td_2 || td_3 || td_4) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_1.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_2.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_3.innerHTML.toUpperCase().indexOf(filter) > -1 ||
          td_4.innerHTML.toUpperCase().indexOf(filter) > -1) {
        count++;
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
  });

Also, you may want to get rid of all of your magic numbers and use jQuery a little more effectively. If I were to rewrite your code, I'd do it as follows:

$('#search').keyup(function () {
  const maxNums = 5;
  var filter = $(this).val().toUpperCase(),
      count  = 0;

  $('tr[name="items"]').each(function () {
    if (count >= maxNums) return;

    var possible = true;
    $('td', this).each(function () {
      if ($(this).html().toUpperCase().indexOf(filter) < 0) {
        possible = false;
      }
    })

    if (possible) {
      if (count++ < maxNums) {
        $(this).css('display', 'block');
      }
    } else {
      $(this).css('display', 'none');
    }
  });
});

I'm sure there are many on this site who could perform this even better than I. :)


问:
Problems reading binary file
I'm trying to read the first 6 bytes of a file, but it's giving me weird results, and I can't seem to figure out what I'm doing wrong.

My code:

```<code>struct Block {
    char fileSize[3];
    char initialDataBlockId[3];
};

int main(int c, char **a) {

    ifstream file("C\\main_file_cache.idx0", ios::binary);

    Block block;

    file.get((char*)&block, sizeof(block));

    printf("File Size: %i\n", block.fileSize);
    printf("Initial Data Block ID: %i\n", block.initialDataBlockId);

    file.close();

    system("pause");
    return 0;
}
</code>```

Before I ran the code, I opened the file in a binary editor,
and it showed me this hex code:

```<code>    00 00 00 00-00 00 05 af-4b 00 00 01-26 df cd 00
    00 6f 03 3f-ed 00 03 61-05 08 35 00-04 8b 01 61
    59 00 08 39-03 23 0a 00-05 6c 00 35-d0 00 06 fe
    03 69 d8 00-07 19
</code>```

There are a total of 54 bytes. The first 6 bytes are just zero.

So, I expected my program to produce the following output:

```<code>File Size: 0
Initial Data Block ID: 0
</code>```

Instead, the outputs is as follows:

```<code>File Size: 10419128
Initial Data Block ID: 10419131
</code>```

This result makes no sense. Maybe there is something wrong with my code?

答:
You should use type unsigned char in your Block structure.

You should use file.read() to read binary data instead of file.get().

You are printing the addresses of the arrays in the Block structure, not their contents, furthermore the specifier %i expects an int, not a char *, so the behavior in undefined and you get some weird integer value but anything culd have happened, including program termination. Increasing the warning level is advisable so the compiler warns about such silly mistakes.

If the file format is little endian, you could convert these 3 byte arrays to numbers this way:

```<code>int block_fileSize =  (unsigned char)block.fileSize[0] +
                     ((unsigned char)block.fileSize[1] << 8) +
                     ((unsigned char)block.fileSize[2] << 16);
int block_initialDataBlockId =  (unsigned char)block.initialDataBlockId[0] +
                               ((unsigned char)block.initialDataBlockId[1] << 8) +
                               ((unsigned char)block.initialDataBlockId[2] << 16);
printf("File Size: %i\n", block_fileSize);
printf("Initial Data Block ID: %i\n", block_initialDataBlockId);
</code>```

Title: Problems reading binary file

Body:
I'm trying to read the first 6 bytes of a file, but it's giving me weird results, and I can't seem to figure out what I'm doing wrong.

My code:

struct Block {
    char fileSize[3];
    char initialDataBlockId[3];
};

int main(int c, char **a) {

    ifstream file("C\\main_file_cache.idx0", ios::binary);

    Block block;

    file.get((char*)&block, sizeof(block));

    printf("File Size: %i\n", block.fileSize);
    printf("Initial Data Block ID: %i\n", block.initialDataBlockId);

    file.close();

    system("pause");
    return 0;
}

Before I ran the code, I opened the file in a binary editor,
and it showed me this hex code:

    00 00 00 00-00 00 05 af-4b 00 00 01-26 df cd 00
    00 6f 03 3f-ed 00 03 61-05 08 35 00-04 8b 01 61
    59 00 08 39-03 23 0a 00-05 6c 00 35-d0 00 06 fe
    03 69 d8 00-07 19

There are a total of 54 bytes. The first 6 bytes are just zero.

So, I expected my program to produce the following output:

File Size: 0
Initial Data Block ID: 0

Instead, the outputs is as follows:

File Size: 10419128
Initial Data Block ID: 10419131

This result makes no sense. Maybe there is something wrong with my code?

Body:
You should use type unsigned char in your Block structure.

You should use file.read() to read binary data instead of file.get().

You are printing the addresses of the arrays in the Block structure, not their contents, furthermore the specifier %i expects an int, not a char *, so the behavior in undefined and you get some weird integer value but anything culd have happened, including program termination. Increasing the warning level is advisable so the compiler warns about such silly mistakes.

If the file format is little endian, you could convert these 3 byte arrays to numbers this way:

int block_fileSize =  (unsigned char)block.fileSize[0] +
                     ((unsigned char)block.fileSize[1] << 8) +
                     ((unsigned char)block.fileSize[2] << 16);
int block_initialDataBlockId =  (unsigned char)block.initialDataBlockId[0] +
                               ((unsigned char)block.initialDataBlockId[1] << 8) +
                               ((unsigned char)block.initialDataBlockId[2] << 16);
printf("File Size: %i\n", block_fileSize);
printf("Initial Data Block ID: %i\n", block_initialDataBlockId);


问:
How to search a folder of text files to see if a specific string exists and then extract a string between two words using Python?
Currently, I'm just trying to figure out why this code won't work.

EDIT: wrote some new code

EDIT 2: SOLVED (reading through comments reminded me to encode the with.open() so it looks like this now,

EDIT 3: New code for pulling the "string" (date) I need between two words.

```<code>import os
items=os.listdir("C:/output")

for names in items:
  if names.endswith(".txt"):
    with open('C:/output/' + names, encoding="utf8") as currentFile:
      text = currentFile.read()
      if ('Date Released' in text):
           a = 'Released'
           b = 'Description'
           startpos = text.find(a) + len(a)
           endpos = text.find(b, startpos)
           print('Date Released ' + text[startpos:endpos] + names + '\n')
           #print ('Found in ' + names[:-4] + '\n')
      else:
          print ('Not in ' + names[:-4] + '\n')
</code>```

I'm now getting the output:

```<code>Date Released :  12/14/2016

1393-004IP_ B_ C2  filename

Date Released :  4/11/2017

1476-002 IP, filename

Date Released :  9/25/2015

1987-XXX IP filename
</code>```

Is there a way to get the Date Released : #/##/#### line on the same line as the file name? Also, some output I get when I run this right now is garbage. I'm assuming it could be from checking for Date Released more than once or a possible flaw with the if condition?

答: if you are working with windows try using double "\" instead of  single"/" in path names</p>

Body:
Currently, I'm just trying to figure out why this code won't work.

EDIT: wrote some new code

EDIT 2: SOLVED (reading through comments reminded me to encode the with.open() so it looks like this now,

EDIT 3: New code for pulling the "string" (date) I need between two words.

import os
items=os.listdir("C:/output")

for names in items:
  if names.endswith(".txt"):
    with open('C:/output/' + names, encoding="utf8") as currentFile:
      text = currentFile.read()
      if ('Date Released' in text):
           a = 'Released'
           b = 'Description'
           startpos = text.find(a) + len(a)
           endpos = text.find(b, startpos)
           print('Date Released ' + text[startpos:endpos] + names + '\n')
           #print ('Found in ' + names[:-4] + '\n')
      else:
          print ('Not in ' + names[:-4] + '\n')

I'm now getting the output:

Date Released :  12/14/2016

1393-004IP_ B_ C2  filename

Date Released :  4/11/2017

1476-002 IP, filename

Date Released :  9/25/2015

1987-XXX IP filename

Is there a way to get the Date Released : #/##/#### line on the same line as the file name? Also, some output I get when I run this right now is garbage. I'm assuming it could be from checking for Date Released more than once or a possible flaw with the if condition?


问:
Error: Cannot find control with path: 'x ' angular 2
I am trying to make a specific form field in my overall form dynamic so that x amount of objects can be added to the array of that field.
However, every time the page inits I get a

Error: Cannot find control with path: 'media -> '

This is my form.ts

```<code>this.cardForm = new FormGroup({
  'title': new FormControl(cardTitle),
  media: this._fb.array([
    this.initMedia(),
  ]),
  'links': new FormGroup({
    'news': new FormControl(news),
  }),

  initMedia() {
   return this._fb.group({
   type: new FormControl(),
   raw: new FormControl(),
   primary: new FormControl(),
   thumbs: this._fb.group({
    default: new FormControl()
  })
})
}

addMedia(){
 const control = <FormArray>this.cardForm.controls['media'];
 control.push(this._fb.control(['']));
}
removeMedia(i: number){
 const control = <FormArray>this.cardForm.controls['media'];
 control.removeAt(i);
}
</code>```

this is my form.html:

```<code><div class="row">
  <div class="col-xs-12">
    <form [formGroup]="cardForm" (ngSubmit)="onSubmit(cardForm.value)">
      <div class="row">
        <div class="col-xs-12">
          <button
            type="submit"
            class="btn btn-success">
            Update Card</button>
          <button
            type="button"
            class="btn btn-danger"
            (click)="onCancel()">
            Cancel</button>
        </div>
      </div>

    <div formArrayName="media">
      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <div *ngFor= "let media of cardForm.controls.media.controls; let i=index">
              <span>Media {{i + 1}}</span>
              <span *ngIf="cardForm.controls.media.controls.length > 1" (click)="removeMedia(i)"></span>
          </div>
          <div [formGroupName]="i">
            <div>
              <label>Url</label>
                <md-input-container class="mdcontainer">
                  <input mdInput placeholder="Media Url" type="text" formControlName="raw">
                </md-input-container>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</code>```

And the media[] looks like this:

```<code>media: [
        {
          raw:'string',
          primary: boolean,
          type: 'string',
          thumb: {
                 default: 'string'
                 {
        }
      ]
</code>```

What am I missing/doing wrong here for that error to come up?
Any help/tips/suggestions would be much appreciated.

答:
You could try the get method instead. I think it is a bit more user-friendly:

```<code>cardForm.get('media')
</code>```

Check it out in the docs here: https://angular.io/guide/reactive-forms#inspect-formcontrol-properties

Body:
I am trying to make a specific form field in my overall form dynamic so that x amount of objects can be added to the array of that field.
However, every time the page inits I get a

Error: Cannot find control with path: 'media -> '

This is my form.ts

this.cardForm = new FormGroup({
  'title': new FormControl(cardTitle),
  media: this._fb.array([
    this.initMedia(),
  ]),
  'links': new FormGroup({
    'news': new FormControl(news),
  }),

  initMedia() {
   return this._fb.group({
   type: new FormControl(),
   raw: new FormControl(),
   primary: new FormControl(),
   thumbs: this._fb.group({
    default: new FormControl()
  })
})
}

addMedia(){
 const control = <FormArray>this.cardForm.controls['media'];
 control.push(this._fb.control(['']));
}
removeMedia(i: number){
 const control = <FormArray>this.cardForm.controls['media'];
 control.removeAt(i);
}

this is my form.html:

    <form [formGroup]="cardForm" (ngSubmit)="onSubmit(cardForm.value)">

          <button
            type="submit"
            class="btn btn-success">
            Update Card</button>
          <button
            type="button"
            class="btn btn-danger"
            (click)="onCancel()">
            Cancel</button>

              Media {{i + 1}}
               1" (click)="removeMedia(i)">

              Url
                <md-input-container class="mdcontainer">
                  <input mdInput placeholder="Media Url" type="text" formControlName="raw">
                </md-input-container>

And the media[] looks like this:

media: [
        {
          raw:'string',
          primary: boolean,
          type: 'string',
          thumb: {
                 default: 'string'
                 {
        }
      ]

What am I missing/doing wrong here for that error to come up?
Any help/tips/suggestions would be much appreciated.

Body:
You could try the get method instead. I think it is a bit more user-friendly:

cardForm.get('media')

Check it out in the docs here: https://angular.io/guide/reactive-forms#inspect-formcontrol-properties


问:
Cant print a hash on a perl module
I have a .pm Package Test file which contains:

```<code>sub new{
my $hash = shift;
my $self = {};
bless($self,$class);
$self->{hash} = %hash;
return $self;}
</code>```

and

```<code>sub printer{
my $self = shift;
print("Test: ",$self->{hash},"\n");
return;}
</code>```

On my main.pl I use:

```<code>$test = Test->new(%myhash);
</code>```

I don't know if explained it properly but the problem is that I can't print my hash using my printer function.
I really appreciatte some help about it and if more information about it is needed I can paste all the files here.

答:
The first argument to ->new is the class name. The arguments to the constructor come next. Not hardwiring the class name also makes inheritance possible.

Do you understand the difference between a hash and a hash reference? %hash is a hash, \%hash is a hash reference. If $test->{hash} contains a hash reference, you can dereference it (i.e. retrieve the hash from it) with %{ $test->{hash} }. Hash values must be scalars, which means you can't make a hash a value of a hash - but you can make a hash reference the value.

I'd also recommend to indent the code properly.

```<code>#! /usr/bin/perl
use warnings;
use strict;

{
    package Test;

    sub new {
        my ($class, %hash) = @_;
        bless { hash => \%hash }, $class;
    }

    sub printer {
        my $self = shift;
        print "Test: ", %{ $self->{hash} }, "\n";
    }
}

my %hash = ( a => 11, b => 12 );
my $t = 'Test'->new(%hash);
$t->printer;  # a11b12 or b12a11
</code>```

Title: Cant print a hash on a perl module

Body:
I have a .pm Package Test file which contains:

sub new{
my $hash = shift;
my $self = {};
bless($self,$class);
$self->{hash} = %hash;
return $self;}

and

sub printer{
my $self = shift;
print("Test: ",$self->{hash},"\n");
return;}

On my main.pl I use:

$test = Test->new(%myhash);

I don't know if explained it properly but the problem is that I can't print my hash using my printer function.
I really appreciatte some help about it and if more information about it is needed I can paste all the files here.

Body:
The first argument to ->new is the class name. The arguments to the constructor come next. Not hardwiring the class name also makes inheritance possible.

Do you understand the difference between a hash and a hash reference? %hash is a hash, \%hash is a hash reference. If $test->{hash} contains a hash reference, you can dereference it (i.e. retrieve the hash from it) with %{ $test->{hash} }. Hash values must be scalars, which means you can't make a hash a value of a hash - but you can make a hash reference the value.

I'd also recommend to indent the code properly.

#! /usr/bin/perl
use warnings;
use strict;

{
    package Test;

    sub new {
        my ($class, %hash) = @_;
        bless { hash => \%hash }, $class;
    }

    sub printer {
        my $self = shift;
        print "Test: ", %{ $self->{hash} }, "\n";
    }
}

my %hash = ( a => 11, b => 12 );
my $t = 'Test'->new(%hash);
$t->printer;  # a11b12 or b12a11


问:
Why does this happen IEnumerable versus List
I have the following BL method

```<code>public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

```<code>public void Save()
{
   group.SomeProp = true;
}
</code>```

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

```<code>public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

答:
Running a LINQ query does not store the results.

Instead, it will re-execute the query each time you enumerate it.

After calling Save(), the query will be empty, since none of the items meet the where clause.

Change it to

```<code>var unsaved = group.Where(g => !g.SomeProp).ToList();
</code>```

Calling ToList() will store the results in a List<T>; this avoids re-executing the query.

Body:
I have the following BL method

public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

public void Save()
{
   group.SomeProp = true;
}

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

Body:
Running a LINQ query does not store the results.

Instead, it will re-execute the query each time you enumerate it.

After calling Save(), the query will be empty, since none of the items meet the where clause.

Change it to

var unsaved = group.Where(g => !g.SomeProp).ToList();

Calling ToList() will store the results in a List<T>; this avoids re-executing the query.


问:
Element type "firstname" must not be declared more than once?
This is the error i get while generating DTD for this XML document

```<code>Element type "firstname" must not be declared more than once line no. 21
</code>```

Question: This is the given XML Document

```<code><?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE order SYSTEM "order.dtd">

<order number="1">

<shipto>

    <reference customer="C001"></reference>

</shipto>

<contact>Tom</contact>

<date>

    <day>14</day>

    <month>06</month>

    <year>2017</year>

</date>

<item>

    <book>

        <isbn>1547895</isbn>

        <title>Introduction to XML</title>

        <price>1490</price>

        <author>

            <firstname>Ivan</firstname>

            <lastname>charles</lastname>

        </author>

    </book>

    <quantity>4</quantity>

    <discount>5</discount>

</item>

<item>

    <book>

        <isbn>1547885</isbn>

        <title>Java Programming</title>

        <price>2000</price>

        <author>

            <firstname>James</firstname>

        </author>

    </book>

    <quantity>4</quantity>

    <discount>5</discount>

</item>

<person id="C001">

    <firstname>Tom</firstname>

    <lastname>Richard</lastname>

    <address>

        <company>ABC</company>

        <city>Bangalore</city>

        <addressline>Electronic city</addressline>

    </address>

</person>

</order>
</code>```

Code: This is the code I have implemented for generating DTD from the XML document given above

```<code><?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT order (shipto,contact,date,item+,person)>
<!ELEMENT shipto (reference)>
<!ELEMENT reference (#PCDATA)>
<!ELEMENT contact (#PCDATA)>
<!ELEMENT date (day,month,year)>
<!ELEMENT day (#PCDATA)>
<!ELEMENT month (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT item (book+,quantity+,discount+)>
<!ELEMENT book (isbn+,title+,price+,author+)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT author (firstname+,lastname*)>
<!ELEMENT firstname (#PCDATA)>                       \\line number 21
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT quantity (#PCDATA)>
<!ELEMENT discount (#PCDATA)>
<!ELEMENT person (firstname,lastname,address)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT address (company,city,addressline)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT addressline (#PCDATA)>
<!ATTLIST order number ID #REQUIRED>
<!ATTLIST reference customer CDATA #REQUIRED>
<!ATTLIST person id ID #REQUIRED>
</code>```

答:
Like the error says, you can only declare an element once.

In your DTD, you have declared firstname and lastname twice.

Even though both author and person allow firstname/lastname in their content models, you can only declare them once. If you remove one firstname declaration and one lastname declaration your DTD will be valid.

Also, in your XML, the number attribute value on the order element is invalid because it starts with a number.

Body:
This is the error i get while generating DTD for this XML document

Element type "firstname" must not be declared more than once line no. 21

Question: This is the given XML Document

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE order SYSTEM "order.dtd">

<order number="1">

<shipto>

    <reference customer="C001"></reference>

</shipto>

<contact>Tom</contact>

<date>

    <day>14</day>

    <month>06</month>

    <year>2017</year>

</date>

<item>

    <book>

        <isbn>1547895</isbn>

        <title>Introduction to XML</title>

        <price>1490</price>

        <author>

            <firstname>Ivan</firstname>

            <lastname>charles</lastname>

        </author>

    </book>

    <quantity>4</quantity>

    <discount>5</discount>

</item>

<item>

    <book>

        <isbn>1547885</isbn>

        <title>Java Programming</title>

        <price>2000</price>

        <author>

            <firstname>James</firstname>

        </author>

    </book>

    <quantity>4</quantity>

    <discount>5</discount>

</item>

<person id="C001">

    <firstname>Tom</firstname>

    <lastname>Richard</lastname>

    <address>

        <company>ABC</company>

        <city>Bangalore</city>

        <addressline>Electronic city</addressline>

    </address>

</person>

</order>

Code: This is the code I have implemented for generating DTD from the XML document given above

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT order (shipto,contact,date,item+,person)>
<!ELEMENT shipto (reference)>
<!ELEMENT reference (#PCDATA)>
<!ELEMENT contact (#PCDATA)>
<!ELEMENT date (day,month,year)>
<!ELEMENT day (#PCDATA)>
<!ELEMENT month (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT item (book+,quantity+,discount+)>
<!ELEMENT book (isbn+,title+,price+,author+)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT author (firstname+,lastname*)>
<!ELEMENT firstname (#PCDATA)>                       \\line number 21
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT quantity (#PCDATA)>
<!ELEMENT discount (#PCDATA)>
<!ELEMENT person (firstname,lastname,address)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT address (company,city,addressline)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT addressline (#PCDATA)>
<!ATTLIST order number ID #REQUIRED>
<!ATTLIST reference customer CDATA #REQUIRED>
<!ATTLIST person id ID #REQUIRED>


问:
BOOST::ASIO. Making sure io_service.run() is invoked only after async_receive(...) is called?
I have a problem where two threads are called like this, one after another.

new boost::thread( &SERVER::start_receive, this);

new boost::thread( &SERVER::run_io_service, this);

Where the first thread calls this function.

```<code>void start_receive()
{
    udp_socket.async_receive(....);
}
</code>```

and the second thread calls,

```<code>void run_io_service()
{
    io_service.run();
}
</code>```

and sometimes the io_service thread ends up finishing before the start_receive() thread and then the server cannot receive packets.

I thought about putting a sleep function between the two threads to wait a while for the start_receive() to complete and that works but I wondered if there was another sure fire way to make this happen?

答:
When you call io_service.run(), the thread will block, dispatching posted handlers until either:

There are no io_service::work objects associated with the io_service, or

io_service.stop() is called.

If either of these happens, the io_service enters the stopped state and will refuse to dispatch any more handlers in future until its reset() method is called.

Every time you initiate an asynchronous operation on an io object associated with the io_service, an io_service::work object is embedded in the asynchronous handler.

For this reason, point (1) above cannot happen until the asynchronous handler has run.

this code therefore will guarantee that the async process completes and that the asserts pass:

```<code>asio::io_service ios;    // ios is not in stopped state
assert(!ios.stopped());
auto obj = some_io_object(ios);
bool completed = false;
obj.async_something(..., [&](auto const& ec) { completed = true; });
// nothing will happen yet. There is now 1 work object associated with ios
assert(!completed);

auto ran = ios.run();
assert(completed);
assert(ran == 1);    // only 1 async op waiting for completion.
assert(ios.stopped());  // io_service is exhausted and no work remaining

ios.reset();
assert(!ios.stopped());  // io_service is ready to run again
</code>```

Body:
I have a problem where two threads are called like this, one after another.

new boost::thread( &SERVER::start_receive, this);

new boost::thread( &SERVER::run_io_service, this);

Where the first thread calls this function.

void start_receive()
{
    udp_socket.async_receive(....);
}

and the second thread calls,

void run_io_service()
{
    io_service.run();
}

and sometimes the io_service thread ends up finishing before the start_receive() thread and then the server cannot receive packets.

I thought about putting a sleep function between the two threads to wait a while for the start_receive() to complete and that works but I wondered if there was another sure fire way to make this happen?

Body:
When you call io_service.run(), the thread will block, dispatching posted handlers until either:

There are no io_service::work objects associated with the io_service, or

io_service.stop() is called.

If either of these happens, the io_service enters the stopped state and will refuse to dispatch any more handlers in future until its reset() method is called.

Every time you initiate an asynchronous operation on an io object associated with the io_service, an io_service::work object is embedded in the asynchronous handler.

For this reason, point (1) above cannot happen until the asynchronous handler has run.

this code therefore will guarantee that the async process completes and that the asserts pass:

asio::io_service ios;    // ios is not in stopped state
assert(!ios.stopped());
auto obj = some_io_object(ios);
bool completed = false;
obj.async_something(..., [&](auto const& ec) { completed = true; });
// nothing will happen yet. There is now 1 work object associated with ios
assert(!completed);

auto ran = ios.run();
assert(completed);
assert(ran == 1);    // only 1 async op waiting for completion.
assert(ios.stopped());  // io_service is exhausted and no work remaining

ios.reset();
assert(!ios.stopped());  // io_service is ready to run again


问:
Celluloid resize pool
I have the following program structure.

```<code>client = Client.new
params = client.get_params
pool = client.pool(size: params.size)

futures = params.map do |p|
    pool.future(:perform_work, p)
end

futures.map(&:value)
</code>```

Client is Celluloid-enabled class using include Celluloid. This works great until I try to execute the program in a loop. I need to dynamically resize pool of workers based on number of parameters I receive from external data-feed.

```<code>client = Client.new
pool = client.pool(size: 1)

loop do
   params = client.get_params

   ....
   **? pool.resize(size: params.size) ?**
   ....

   futures = params.map do |p|
      pool.future(:perform_work, p)
   end

   futures.map(&:value)
   sleep 1
end
</code>```

I tried include pool creation into the loop with subsequent pool.terminate but it's spamming threads and leads to actor crash.

答:
Setting pool.size explicitly did the trick it seems</p>

```<code>client = Client.new
pool = client.pool(size: 1)

loop do
   params = client.get_params
   pool.size = params.size

   futures = params.map do |p|
      pool.future(:perform_work, p)
   end

   futures.map(&:value)
   sleep 1
end
</code>```

Title: Celluloid resize pool

Body:
I have the following program structure.

client = Client.new
params = client.get_params
pool = client.pool(size: params.size)

futures = params.map do |p|
    pool.future(:perform_work, p)
end

futures.map(&:value)

Client is Celluloid-enabled class using include Celluloid. This works great until I try to execute the program in a loop. I need to dynamically resize pool of workers based on number of parameters I receive from external data-feed.

client = Client.new
pool = client.pool(size: 1)

loop do
   params = client.get_params

   ....
   **? pool.resize(size: params.size) ?**
   ....

   futures = params.map do |p|
      pool.future(:perform_work, p)
   end

   futures.map(&:value)
   sleep 1
end

I tried include pool creation into the loop with subsequent pool.terminate but it's spamming threads and leads to actor crash.

Body:
Setting pool.size explicitly did the trick it seems

client = Client.new
pool = client.pool(size: 1)

loop do
   params = client.get_params
   pool.size = params.size

   futures = params.map do |p|
      pool.future(:perform_work, p)
   end

   futures.map(&:value)
   sleep 1
end


问:
Getting wrong date for Javascript Date() function
I am trying to use the "new Date()" function but my dates are not coming out correctly.

This date & time is correct if I use:

```<code>new Date(); //outputs Wed Jul 05 2017 13:16:31 GMT-0700 (Pacific Daylight Time)
</code>```

When I try to change the date, it comes out incorrect:

```<code>new Date(2017,07,03,12,01,36); //outputs Thu Aug 03 2017 12:01:36 GMT-0700 (Pacific Daylight Time)
</code>```

I'm not sure why it says "Aug" when it should be "Jul".

Thanks In Advance!

答: It is because months start from zero. So, if you want July, you have to set month to 06</p>

Body:
I am trying to use the "new Date()" function but my dates are not coming out correctly.

This date & time is correct if I use:

new Date(); //outputs Wed Jul 05 2017 13:16:31 GMT-0700 (Pacific Daylight Time)

When I try to change the date, it comes out incorrect:

new Date(2017,07,03,12,01,36); //outputs Thu Aug 03 2017 12:01:36 GMT-0700 (Pacific Daylight Time)

I'm not sure why it says "Aug" when it should be "Jul".

Thanks In Advance!


答:
month is 0-based

Date - JavaScript | MDN

```<code>new Date(2017,06,03,12,01,36) // Mon Jul 03 2017 12:01:36 GMT-0700 (PDT)
</code>```

Similar questions

javascript is creating date wrong month

why is the javascript date month index 0-based

Why does the month argument range from 0 to 11 in JavaScript's Date constructor?

Title: Getting wrong date for Javascript Date() function

Body:
month is 0-based

Date - JavaScript | MDN

new Date(2017,06,03,12,01,36) // Mon Jul 03 2017 12:01:36 GMT-0700 (PDT)

Similar questions

javascript is creating date wrong month

why is the javascript date month index 0-based

Why does the month argument range from 0 to 11 in JavaScript's Date constructor?


问:
Strange issues when adding/deleting items to an array on click
I got a modal with a list of items.

Clicking the item div adds the item to the list, and also updates the cart total price.

Clicking the selected item removes the item from the list, and also updates the cart total price.

And it works great, when clicking slowly, but when I click like a maniac (add/delete many items in a short time period) I get strange results like: the selected value doesn't go back to 0, or some items are still in the 'itemsInBuyCart' array despite none of them being actually selected.

```<code>app.addItemToBuyCart = function(item, price, div) {
        if (app.addClicking) return;
        app.addClicking = 1;
        if (app.itemsInBuyCart.indexOf(item.toString()) == -1) {
            app.itemsInBuyCart.push(item.toString());
            div.children().addClass("selected");
              app.buySelectedValue += price;
        } else {
            app.itemsInBuyCart.splice(app.itemsInBuyCart.indexOf(item));
            div.children().removeClass("selected");
             app.buySelectedValue -= price;
        }
     $('#buySelectedValue').text(app.buySelectedValue);
        app.addClicking = 0;
    }
</code>```

The clickable divs for each item are generated like this:

```<code>$("#buyCartModal").append('<div style="cursor:pointer" onClick="app.addItemToBuyCart(' + item.id + ', '+item.price+', $(this));"
</code>```

答:
There's a lot of logic with DOM manipulation that goes on here. This can be just taxing enough on performance, meaning rapid clicks aren't always registered because the previous function is still running (or weird behaviors like you've described come about).

So what can you do about it?

Without seeing your full code I can't make very helpful optimization recommendations, but as a general suggestion, set a boolean varaible that must be true in order for the function to be called via onClick. Set the boolean variable to true at the very end of addItemToBuyCart() and false at the very beginning. That's a little vague but I think you get the idea, and this ensures that you are only calling your function when the browser is ready to handle the request.

Body:
I got a modal with a list of items.

Clicking the item div adds the item to the list, and also updates the cart total price.

Clicking the selected item removes the item from the list, and also updates the cart total price.

And it works great, when clicking slowly, but when I click like a maniac (add/delete many items in a short time period) I get strange results like: the selected value doesn't go back to 0, or some items are still in the 'itemsInBuyCart' array despite none of them being actually selected.

app.addItemToBuyCart = function(item, price, div) {
        if (app.addClicking) return;
        app.addClicking = 1;
        if (app.itemsInBuyCart.indexOf(item.toString()) == -1) {
            app.itemsInBuyCart.push(item.toString());
            div.children().addClass("selected");
              app.buySelectedValue += price;
        } else {
            app.itemsInBuyCart.splice(app.itemsInBuyCart.indexOf(item));
            div.children().removeClass("selected");
             app.buySelectedValue -= price;
        }
     $('#buySelectedValue').text(app.buySelectedValue);
        app.addClicking = 0;
    }

The clickable divs for each item are generated like this:

$("#buyCartModal").append('<div style="cursor:pointer" onClick="app.addItemToBuyCart(' + item.id + ', '+item.price+', $(this));"


问:
Detect empty directory with Perl
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

```<code>#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}
</code>```

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

```<code>sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }
</code>```

答:
A little verbose for clarity, but:

```<code>sub is_folder_empty {
    my $dirname = shift;
    opendir(my $dh, $dirname) or die "Not a directory";
    return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
}
</code>```

Then you can do:

```<code>if (is_folder_empty($your_dir)) {
    ....
}
</code>```

Title: Detect empty directory with Perl

Body:
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }

Body:
A little verbose for clarity, but:

sub is_folder_empty {
    my $dirname = shift;
    opendir(my $dh, $dirname) or die "Not a directory";
    return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
}

Then you can do:

if (is_folder_empty($your_dir)) {
    ....
}


问:
Enable and disable onkeydown event?
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

```<code>var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};
</code>```

Kind Regards

答:
To do this, I would change your disable handler to this:

```<code>$(".open-project").click(function(){
  $(document).on('keydown', function(e) { e.preventDefault(); });
});
</code>```

And for the re-enable handler do this:

```<code>$("#project_close").click(function(){
  $(document).off('keydown');
});
</code>```

The on() function binds the keydown event to basically stop the event from occurring, and the off() function restores the default keydown functionality. You can refer to the jQuery documentation for those functions here:

http://api.jquery.com/on/

http://api.jquery.com/off/

Title: Enable and disable onkeydown event?

Body:
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};

Kind Regards

Body:
To do this, I would change your disable handler to this:

$(".open-project").click(function(){
  $(document).on('keydown', function(e) { e.preventDefault(); });
});

And for the re-enable handler do this:

$("#project_close").click(function(){
  $(document).off('keydown');
});

The on() function binds the keydown event to basically stop the event from occurring, and the off() function restores the default keydown functionality. You can refer to the jQuery documentation for those functions here:

http://api.jquery.com/on/

http://api.jquery.com/off/


问:
TypeError: list indices must be integers or slices, not str - get from json
I try to get all lattitudes and longtitudes from this json.

Code:

```<code>import urllib.parse
import requests

raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid='
print()

userid = 735890904669618176
#userid = input('UserID: ')

url = raw_json + urllib.parse.urlencode({'userid=': userid}) + '&page_size=1000'
print(url)

json_data = requests.get(url).json()
print()

for coordinates in json_data['data']['video_info']:
    print(coordinates['lat'], coordinates['lnt'])
    print()
</code>```

Error:

```<code>/usr/bin/python3.6 /media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates

http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000

Traceback (most recent call last):
  File "/media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates", line 17, in <module>
    for coordinates in json_data['data']['video_info']:
TypeError: list indices must be integers or slices, not str

Process finished with exit code 1
</code>```

Where do I go wrong?

In advance, thanks for your help and time.

I just post some of the json to show what it looks like.
The json looks like this:

```<code>{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1499275646",
    "video_info": [
      {
        "vid": "14992026438883533757",
        "watchnumber": "38",
        "topicid": "0",
        "topic": "",
        "vtime": "1499202678",
        "title": "happy 4th of july",
        "userid": "735890904669618176",
        "online": "0",
        "addr": "",
        "isaddr": "2",
        "lnt": "-80.1282576",
        "lat": "26.2810628",
        "area": "A_US",
        "countryCode": "US",
        "chatSystem": "1",
        },
</code>```

Full json: https://pastebin.com/qJywTqa1

答:
According to your posted json, you have problem in this statement-

print(coordinates['lat'], coordinates['lnt'])

Here coordinates is a list having only one item which is dictionary. So your statement should be-

print(coordinates[0]['lat'], coordinates[0]['lnt'])

Body:
I try to get all lattitudes and longtitudes from this json.

Code:

import urllib.parse
import requests

raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid='
print()

userid = 735890904669618176
#userid = input('UserID: ')

url = raw_json + urllib.parse.urlencode({'userid=': userid}) + '&page_size=1000'
print(url)

json_data = requests.get(url).json()
print()

for coordinates in json_data['data']['video_info']:
    print(coordinates['lat'], coordinates['lnt'])
    print()

Error:

/usr/bin/python3.6 /media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates

http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000

Traceback (most recent call last):
  File "/media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates", line 17, in <module>
    for coordinates in json_data['data']['video_info']:
TypeError: list indices must be integers or slices, not str

Process finished with exit code 1

Where do I go wrong?

In advance, thanks for your help and time.

I just post some of the json to show what it looks like.
The json looks like this:

{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1499275646",
    "video_info": [
      {
        "vid": "14992026438883533757",
        "watchnumber": "38",
        "topicid": "0",
        "topic": "",
        "vtime": "1499202678",
        "title": "happy 4th of july",
        "userid": "735890904669618176",
        "online": "0",
        "addr": "",
        "isaddr": "2",
        "lnt": "-80.1282576",
        "lat": "26.2810628",
        "area": "A_US",
        "countryCode": "US",
        "chatSystem": "1",
        },

Full json: https://pastebin.com/qJywTqa1


问:
How do I remove an item from the Intellij default changelist?
Somehow or other a file in the .idea folder has landed on the default changelist and every time I make a commit Intellij is asking me if if I want to include the file in the commit.

I can't figure out why Intellij insists on trying to version control this file or how I can change its mind.

答:
From bash console write git status this action will display all files modifieds/new, now identify the file of .idea folder, if the file is untracked then you just delete that file with the following command:

```<code>git clean -f .idea/file_to_include.xml
</code>```

But if the file has changes git can undo the change with the following command:

```<code>git checkout --  .idea/file_to_include.xml
</code>```

In spite of the proposed solution, it is advisable to avoid tracking that folder as well as some files like *.iws, *.iml, *.ipr, for to do that, you can create a .gitignore file in the main folder of your project and add this:

```<code>.idea
*.iws
*.iml
*.ipr
</code>```

save the file and add it to your repo:

```<code>git add .gitignore
git commit -m "Excluded files and folders"
</code>```

Body:
From bash console write git status this action will display all files modifieds/new, now identify the file of .idea folder, if the file is untracked then you just delete that file with the following command:

git clean -f .idea/file_to_include.xml

But if the file has changes git can undo the change with the following command:

git checkout --  .idea/file_to_include.xml

In spite of the proposed solution, it is advisable to avoid tracking that folder as well as some files like *.iws, *.iml, *.ipr, for to do that, you can create a .gitignore file in the main folder of your project and add this:

.idea
*.iws
*.iml
*.ipr

save the file and add it to your repo:

git add .gitignore
git commit -m "Excluded files and folders"


问:
Issue with clicking link on selenium java
I tried everything. By xpath , by css-selector , by class name too.

```<code>//*[@id="opbox-listing"]/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a
thats look xpath , but don't work
</code>```

on selenium i tried thats way:

```<code>        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).submit();

        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).click();
</code>```

what i do wrong? someone have any ideas?

答:
Your xpath is broken: opening apostrophe is missing for an id value:

```<code>"//*[@id='opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a"
</code>```

Body:
I tried everything. By xpath , by css-selector , by class name too.

//*[@id="opbox-listing"]/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a
thats look xpath , but don't work

on selenium i tried thats way:

        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).submit();

        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).click();

what i do wrong? someone have any ideas?

Body:
Your xpath is broken: opening apostrophe is missing for an id value:

"//*[@id='opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a"


答:
Your problem lies in Lazy Evalution of LINQ. In first example, the LINQ query is actualy run TWICE. First for enumerating for calling your Save() method, and second to get Any().

As general rule while working with LINQ, put ToList() after each and every query.

Title: Why does this happen IEnumerable versus List

Body:
I have the following BL method

public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

public void Save()
{
   group.SomeProp = true;
}

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks


问:
Aws API Gate Way doesn't create Amazon CloudFront distribution
I am following the link to setup, it says in the doc "For every API you create, API Gateway sets up an Amazon CloudFront distribution for the API", I have created 4 API's and deployed them, but when I goto cloudFront, I don't see anything, it says Create Distribution. Not sure, What I am missing exactly, any help would be appreciated.

答: The cloudfront distributions are not exposed to the public. API Gateway internally setups up a cloudfront distribution for every api.</p>


问:
Do not open Website
I use open-cart to build e-commerce web. When I enter url: http://supersmartstyles.com/ it will take too much time and it is not open.

when I put http_server on "config.php" page it not open when i remove that then its open with error

Notice: Use of undefined constant HTTP_SERVER - assumed 'HTTP_SERVER' in /home/stylesmart/public_html/index.php on line 63

Notice: Use of undefined constant HTTPS_SERVER - assumed 'HTTPS_SERVER' in /home/stylesmart/public_html/index.php on line 64

If anybody have any idea about this, please let me know.

Thanks

答: It can be database slowdown, but can also be a misconfiguring Apache or Nginx.</p>

Title: Do not open Website


问:
Mongoose self nesting
I'd like to store the following:

```<code>var TestSchema = new Schema({
    name: {
        type: String
    },
    regions: [RegionSchema]
}

var RegionSchema = new Schema({
    name: {
        type: String
    },
    minX: {
        type: Number
    },
    minY: {
        type: Number
    },
    minZ: {
        type: Number
    },
    maxX: {
        type: Number
    },
    maxY: {
        type: Number
    },
    maxZ: {
        type: Number
    },
    children: [this]
});
</code>```

So as you can see I'm trying to make a region object, able to contain region objects, however this fails to save without exception, presumably the [this] in the schema gets stuck in some endless loop or something.

How can I make this to work for nesting regions?

The json payload I could expect to send to this schema:

```<code>name: "test123",
regions: [
        {
            name: "TestRegion",
            minX: 0,
            minY: 0,
            minZ: 0,
            maxX: 100,
            maxY: 255,
            maxZ: 100,
            children: [
                {
                    name: "TestRegionChild",
                    minX: 3,
                    minY: 3,
                    minZ: 3,
                    maxX: 97,
                    maxY: 252,
                    maxZ: 97,
                    children: []
                }
            ]
        }
    ]
</code>```

I appreciate any help, thank you.

答:
If your other regions are saved first, you can save the children as a list of objectIds like this:

```<code>children: [{
     type: Schema.ObjectId,
     ref: 'Region'
}]
</code>```

Another option is to redesign your Schema and have a 'parent' on your Region and delete the 'children' field. Then when you need to get all the children you can query easily and not have big nested objects.

```<code>var RegionSchema = new Schema({
     --- other fields omitted ---

     parent: {
        type: Schema.ObjectId,
        ref: 'Region'
    }
});
</code>```

Title: Mongoose self nesting

Body:
I'd like to store the following:

var TestSchema = new Schema({
    name: {
        type: String
    },
    regions: [RegionSchema]
}

var RegionSchema = new Schema({
    name: {
        type: String
    },
    minX: {
        type: Number
    },
    minY: {
        type: Number
    },
    minZ: {
        type: Number
    },
    maxX: {
        type: Number
    },
    maxY: {
        type: Number
    },
    maxZ: {
        type: Number
    },
    children: [this]
});

So as you can see I'm trying to make a region object, able to contain region objects, however this fails to save without exception, presumably the [this] in the schema gets stuck in some endless loop or something.

How can I make this to work for nesting regions?

The json payload I could expect to send to this schema:

name: "test123",
regions: [
        {
            name: "TestRegion",
            minX: 0,
            minY: 0,
            minZ: 0,
            maxX: 100,
            maxY: 255,
            maxZ: 100,
            children: [
                {
                    name: "TestRegionChild",
                    minX: 3,
                    minY: 3,
                    minZ: 3,
                    maxX: 97,
                    maxY: 252,
                    maxZ: 97,
                    children: []
                }
            ]
        }
    ]

I appreciate any help, thank you.

Body:
If your other regions are saved first, you can save the children as a list of objectIds like this:

children: [{
     type: Schema.ObjectId,
     ref: 'Region'
}]

Another option is to redesign your Schema and have a 'parent' on your Region and delete the 'children' field. Then when you need to get all the children you can query easily and not have big nested objects.

var RegionSchema = new Schema({
     --- other fields omitted ---

     parent: {
        type: Schema.ObjectId,
        ref: 'Region'
    }
});


问:
Is it possible to link to a 360 YouTube video with ReactVR?
In the documentation for ReactVR for VideoPano

it demonstrates pointing to a video in the code base.

Is it possible to link to an external link (aka Youtube)?

So instead of video.mp4, it would link to https://www.youtube.com/watch?v=hkgYIr_LWPw&index=1&list=PL-BE7kqSgbEj44peyt5BmLK63kbDp7Rhu

```<code>let videoUrl = 'video.webm';
const supportedFormats = NativeModules.VideoModule.supportedFormats;
for (let i = 0; i < supportedFormats.length; i++) {
  if (supportedFormats[i] === 'mp4') {
    videoUrl = 'video.mp4';
  }
}
</code>```

the rest of the code looks like this.

```<code>class WelcomeToVR extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      playerState: new MediaPlayerState({autoPlay: true, muted: true}), // init with muted, autoPlay
    };
  }
  render() {
    return (
           <View>
           <VideoPano
    playerState={this.state.playerState}
  source={asset(videoUrl, {layout: 'SPHERE'})}
         />
         <VideoControl
  style={{
  height: 0.2,
          width: 4,
                 layoutOrigin: [0.5, 0.5, 0],
  transform: [{translate: [0, 0, -4]}],
}}
playerState={this.state.playerState}
</code>```

答:
YouTube intentionally chooses to obfuscate the direct links to their video files. Linking the embedded player isn't a solution since that thing's a mini web app with streaming logic, not an actual video file.

There's a pretty good write-up on how you could get around that here How do all of these “Save video from YouTube” services work? (probably against their Terms and Conditions though).

It is possible, however, to link to an external video URL, here's how:

Pick a random 3D 360 YouTube video, like this one

Download it, I used savefrom.net but there are many others and host it somewhere http://YOURDOMAIN/YOURVIDEO.mp4

Render a <VideoPano /> in your scene/view

```<code><VideoPano source={{
  uri: 'http://YOURDOMAIN/YOURVIDEO.mp4',
  stereo: 'BOTTOM_TOP_3D' // this is specific to YouTube 3D videos
}} />
</code>```

https://facebook.github.io/react-vr/docs/videopano.html

Body:
In the documentation for ReactVR for VideoPano

it demonstrates pointing to a video in the code base.

Is it possible to link to an external link (aka Youtube)?

So instead of video.mp4, it would link to https://www.youtube.com/watch?v=hkgYIr_LWPw&index=1&list=PL-BE7kqSgbEj44peyt5BmLK63kbDp7Rhu

let videoUrl = 'video.webm';
const supportedFormats = NativeModules.VideoModule.supportedFormats;
for (let i = 0; i < supportedFormats.length; i++) {
  if (supportedFormats[i] === 'mp4') {
    videoUrl = 'video.mp4';
  }
}

the rest of the code looks like this.

class WelcomeToVR extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      playerState: new MediaPlayerState({autoPlay: true, muted: true}), // init with muted, autoPlay
    };
  }
  render() {
    return (
           <View>
           <VideoPano
    playerState={this.state.playerState}
  source={asset(videoUrl, {layout: 'SPHERE'})}
         />
         <VideoControl
  style={{
  height: 0.2,
          width: 4,
                 layoutOrigin: [0.5, 0.5, 0],
  transform: [{translate: [0, 0, -4]}],
}}
playerState={this.state.playerState}

Body:
YouTube intentionally chooses to obfuscate the direct links to their video files. Linking the embedded player isn't a solution since that thing's a mini web app with streaming logic, not an actual video file.

There's a pretty good write-up on how you could get around that here How do all of these “Save video from YouTube” services work? (probably against their Terms and Conditions though).

It is possible, however, to link to an external video URL, here's how:

Pick a random 3D 360 YouTube video, like this one

Download it, I used savefrom.net but there are many others and host it somewhere http://YOURDOMAIN/YOURVIDEO.mp4

Render a <VideoPano /> in your scene/view

<VideoPano source={{
  uri: 'http://YOURDOMAIN/YOURVIDEO.mp4',
  stereo: 'BOTTOM_TOP_3D' // this is specific to YouTube 3D videos
}} />

https://facebook.github.io/react-vr/docs/videopano.html


问:
Why must accessor functions be const? Where is the vulnerability?
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

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

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}
</code>```

答:
Function with keyword const guarantee that use her, don't change object which was given. So if you want give to print object to some function or especially to operator<< outside class you should use only method with keyword const.

```<code>std::ostream &operator<<(std::ostream& str, const Object& obj)
{
    return str << obj.someFunctionConst() << std::endl;
}
</code>```

function with error (compile error)

```<code>std::ostream &operator<<(std::ostream& str, const Object& obj)
{
     return str << obj.someFunctionWithoutConst() << std::endl;
}
</code>```

Body:
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}

Body:
Function with keyword const guarantee that use her, don't change object which was given. So if you want give to print object to some function or especially to operator<< outside class you should use only method with keyword const.

std::ostream &operator<<(std::ostream& str, const Object& obj)
{
    return str << obj.someFunctionConst() << std::endl;
}

function with error (compile error)

std::ostream &operator<<(std::ostream& str, const Object& obj)
{
     return str << obj.someFunctionWithoutConst() << std::endl;
}


问:
windows directory contents being "." and ".."
I'm trying to search through the contents of a directory. Inside of the directory is other directories, which should always be in the same order. When I make an array of the directory contents, I have to reserve the first two spots for "." and "..". Can anyone tell me why this is?

And is this present on mac as well? My script won't run properly on mac because the array isn't lining up with where the directories should be. I think its because these "." and ".." spots don't exist on mac or something. I'm just looking for some answers. Not sure if it will help, but here is my code.

```<code>print "Enter the SMD day folder to generate summary. (Ex: a folder named 06132017)\n";
chomp($smddirectory = <STDIN>);
print "\n";
print "Output will be in the SGE folder.\n";
opendir ($DIR, $smddirectory) ;
my @directories = readdir $DIR;
closedir $DIR;

@directories = map{$smddirectory . '/' . $_} @directories;

$mydir = @directories[14];
$mydirs = @directories[2];
$mydirb = @directories[3];
$mydirbs = @directories[4];
$mydirc = @directories[5];
$mydircs = @directories[6];
$JSHDirectory = @directories[7];
$JSHsDirectory = @directories[8];
$JSHBDirectory = @directories[9];
$JSHBsDirectory = @directories[10];
$JSHCDirectory = @directories[11];
$JSHCsDirectory = @directories[12];
$SGEDirectory = @directories[13];
</code>```

答:
Actually, you won't always get . and ... You'll only get them if they exist in the directory,[1] and the reason you get them is because they exist in the directory.[2] Just filter them out if you're not interested in them.

```<code>my @directories =
    map { "$smddirectory/$_" }
       grep { !/^\.\.?\z/ }
          readdir($DIR);
</code>```

Furthermore, there's no guarantee about the order in which readdir will return the directory entries. You should not rely on them being in any particular order.

They root of physical drives don't have . or .. in Windows.

```<code>>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" C:\
0

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" C:\Users
2
</code>```

It varies for other type of drives.

```<code>>subst Z: C:\

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" Z:\
0

>subst /d Z:

>subst Z: C:\Users

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" Z:\
2

>subst /d Z:
</code>```

These and other files starting with . are normally kept hidden from users in unix systems (incl OS/X), but ls -a will show them. . is a link to the current directory, and .. is a link to the parent directory.

Body:
I'm trying to search through the contents of a directory. Inside of the directory is other directories, which should always be in the same order. When I make an array of the directory contents, I have to reserve the first two spots for "." and "..". Can anyone tell me why this is?

And is this present on mac as well? My script won't run properly on mac because the array isn't lining up with where the directories should be. I think its because these "." and ".." spots don't exist on mac or something. I'm just looking for some answers. Not sure if it will help, but here is my code.

print "Enter the SMD day folder to generate summary. (Ex: a folder named 06132017)\n";
chomp($smddirectory = <STDIN>);
print "\n";
print "Output will be in the SGE folder.\n";
opendir ($DIR, $smddirectory) ;
my @directories = readdir $DIR;
closedir $DIR;

@directories = map{$smddirectory . '/' . $_} @directories;

$mydir = @directories[14];
$mydirs = @directories[2];
$mydirb = @directories[3];
$mydirbs = @directories[4];
$mydirc = @directories[5];
$mydircs = @directories[6];
$JSHDirectory = @directories[7];
$JSHsDirectory = @directories[8];
$JSHBDirectory = @directories[9];
$JSHBsDirectory = @directories[10];
$JSHCDirectory = @directories[11];
$JSHCsDirectory = @directories[12];
$SGEDirectory = @directories[13];

Body:
Actually, you won't always get . and ... You'll only get them if they exist in the directory,[1] and the reason you get them is because they exist in the directory.[2] Just filter them out if you're not interested in them.

my @directories =
    map { "$smddirectory/$_" }
       grep { !/^\.\.?\z/ }
          readdir($DIR);

Furthermore, there's no guarantee about the order in which readdir will return the directory entries. You should not rely on them being in any particular order.

They root of physical drives don't have . or .. in Windows.

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" C:\
0

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" C:\Users
2

It varies for other type of drives.

>subst Z: C:\

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" Z:\
0

>subst /d Z:

>subst Z: C:\Users

>perl -E"opendir($dh, $ARGV[0]) or die $!; say 0+grep /^\./, readdir($dh)" Z:\
2

>subst /d Z:

These and other files starting with . are normally kept hidden from users in unix systems (incl OS/X), but ls -a will show them. . is a link to the current directory, and .. is a link to the parent directory.


问:
PrimeFaces DataTable doesn't update when filtered
I'm new to PrimeFaces and to JSF.

I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.

Have you got any suggestions?

I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table

Thank you, any help will be appreciated

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form>
        <p:dataTable var="car" value="#{dtCar.cars}" widgetVar="carsTable"
            emptyMessage="No cars found with given criteria"
            filteredValue="#{dtCar.filteredCars}">

            <p:column filterBy="#{car.model}" headerText="Model"
                footerText="contains" filterMatchMode="contains">
                <h:outputText value="#{car.model}" />
            </p:column>
            <p:column filterBy="#{car.color}" headerText="Color"
                footerText="contains" filterMatchMode="contains">
                <h:outputText value="#{car.color}" />
            </p:column>

        </p:dataTable>
        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>
</html>
</code>```

Here is the CarBean.java

```<code>package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private List<Car> cars;

  private List<Car> filteredCars;

  public CarBean() {
    setCars(new ArrayList<Car>());
    getCars().add(new Car("myModel", "blu"));
    getCars().add(new Car("punto", "blu"));
    getCars().add(new Car("doblo", "grigio"));
    getCars().add(new Car("smart", "blu"));
    getCars().add(new Car("twingo", "rosso"));
    getCars().add(new Car("twingo", "bianco"));
    getCars().add(new Car("doblo", "blu"));
    // add more cars
  }

  // getter setter
  public List<Car> getCars() {
    return cars;
  }

  public void setCars(List<Car> cars) {
    this.cars = cars;
  }

  public List<Car> getFilteredCars() {
    return filteredCars;
  }

  public void setFilteredCars(List<Car> filteredCars) {
    this.filteredCars = filteredCars;
  }

  public String loadNewCars() {
    if (getCars().get(0).getModel().equals("myModel")) {
      getCars().clear();
      getCars().add(new Car("gt", "giallo"));
      getCars().add(new Car("scirocco", "azzurro"));
      getCars().add(new Car("duna", "giallo"));
      getCars().add(new Car("diablo", "griggio"));
      getCars().add(new Car("cayenne", "rosso"));
      getCars().add(new Car("aygo", "azzurro"));
      setFilteredCars(null);
    }
    else {
      getCars().clear();
      getCars().add(new Car("myModel", "blu"));
      getCars().add(new Car("punto", "blu"));
      getCars().add(new Car("doblo", "grigio"));
      getCars().add(new Car("smart", "blu"));
      getCars().add(new Car("twingo", "rosso"));
      getCars().add(new Car("twingo", "bianco"));
      getCars().add(new Car("doblo", "blu"));
      setFilteredCars(null);
    }
    return null;
  }
}
</code>```

And here is the Car.java

```<code>package it.caditech.testtable;
public class Car {
  private String model;

  private String color;

  public Car(String m, String c) {
    model = m;
    color = c;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}
</code>```

答:
Try this:</p>

```<code><p:dataTable id="yourDataTable" var="car"...
<p:poll interval="3" update="yourDataTable" />
</code>```

Body:
I'm new to PrimeFaces and to JSF.

I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.

Have you got any suggestions?

I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table

Thank you, any help will be appreciated

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form>

                <h:outputText value="#{car.model}" />

                <h:outputText value="#{car.color}" />

        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>

Here is the CarBean.java

package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private List<Car> cars;

  private List<Car> filteredCars;

  public CarBean() {
    setCars(new ArrayList<Car>());
    getCars().add(new Car("myModel", "blu"));
    getCars().add(new Car("punto", "blu"));
    getCars().add(new Car("doblo", "grigio"));
    getCars().add(new Car("smart", "blu"));
    getCars().add(new Car("twingo", "rosso"));
    getCars().add(new Car("twingo", "bianco"));
    getCars().add(new Car("doblo", "blu"));
    // add more cars
  }

  // getter setter
  public List<Car> getCars() {
    return cars;
  }

  public void setCars(List<Car> cars) {
    this.cars = cars;
  }

  public List<Car> getFilteredCars() {
    return filteredCars;
  }

  public void setFilteredCars(List<Car> filteredCars) {
    this.filteredCars = filteredCars;
  }

  public String loadNewCars() {
    if (getCars().get(0).getModel().equals("myModel")) {
      getCars().clear();
      getCars().add(new Car("gt", "giallo"));
      getCars().add(new Car("scirocco", "azzurro"));
      getCars().add(new Car("duna", "giallo"));
      getCars().add(new Car("diablo", "griggio"));
      getCars().add(new Car("cayenne", "rosso"));
      getCars().add(new Car("aygo", "azzurro"));
      setFilteredCars(null);
    }
    else {
      getCars().clear();
      getCars().add(new Car("myModel", "blu"));
      getCars().add(new Car("punto", "blu"));
      getCars().add(new Car("doblo", "grigio"));
      getCars().add(new Car("smart", "blu"));
      getCars().add(new Car("twingo", "rosso"));
      getCars().add(new Car("twingo", "bianco"));
      getCars().add(new Car("doblo", "blu"));
      setFilteredCars(null);
    }
    return null;
  }
}

And here is the Car.java

package it.caditech.testtable;
public class Car {
  private String model;

  private String color;

  public Car(String m, String c) {
    model = m;
    color = c;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}

Body:
Try this:

<p:dataTable id="yourDataTable" var="car"...
<p:poll interval="3" update="yourDataTable" />