问:
Create a custom drop down menu and place dataset value in input
I'm trying to create a custom drop down menu, using HTML, CSS and Vanilla Javascript.

I've managed to get the menu to appear when the user clicks on the the "from" input field, however when I try and click on an option, it wont let you add the value stored in the "code" dataset.

I did get it to work by using setTimeout method, however it is a bit hit and miss sometimes and doesn't seem like a good solution.

Is there an alternative way to get it to work?

function app() {

  var messages = document.querySelector(".messages");

  var inputFrom = document.querySelector(".input-from");

  var inputTo = document.querySelector(".input-to");

  var nearestContainer = document.querySelector(".nearest-container");

  inputFrom.addEventListener("focus", inputToFocusIn, false);

  function inputToFocusIn(e) {

    messages.innerHTML = "focusin event triggered on input-from";

    // add class
    inputFrom.classList.add("input-from--focusin");
    nearestContainer.classList.add("nearest-container--active");

    // remove class
    inputFrom.classList.remove("input-from--focusout");
    nearestContainer.classList.remove("nearest-container--hidden");

  }

  inputFrom.addEventListener("focusout", inputToFocusOut, false);

  function inputToFocusOut(e) {

    messages.innerHTML = "focusout event triggered on input-from";

      // add class
      inputFrom.classList.remove("input-from--focusin");
      nearestContainer.classList.remove("nearest-container--active");

      // remove class
      inputFrom.classList.add("input-from--focusout");
      nearestContainer.classList.add("nearest-container--hidden");

  }

  var nearestStations = document.querySelectorAll(".nearest-station");

  // add event listener to buttons
  for(var nearestStation of nearestStations) {

    nearestStation.addEventListener("click", addToInputFrom, false);

  }

  function addToInputFrom(e) {

    inputFrom.classList.add("input-from--focusout");
    nearestContainer.classList.add("nearest-container--hidden");

    inputFrom.classList.remove("input-from--focusin")
    nearestContainer.classList.remove("nearest-container--active")

    var targetDataset = e.currentTarget.dataset.code;

    messages.innerHTML = "station added to input from field"

    inputFrom.value = "";
    inputFrom.value = targetDataset;

  }

  var switchButton = document.querySelector(".button-switch");

  switchButton.addEventListener("click", clickSwitch, false);

  function clickSwitch(e) {

    var inputFromValue = inputFrom.value;
    var inputToValue = inputTo.value;

    inputFrom.value = inputToValue;
    inputTo.value = inputFromValue;

  }

}

window.onload = app();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* stylesheet */

body {
 font-family: "GRAPHIK";
 font-style: normal;
 font-weight: 400;
 font-size: 16px;
 color: #242424;
}

* {
 box-sizing: border-box;
 outline: none;
}

.container {
 display: flex;
 flex-direction: column;
 justify-content: center;
 align-items: center;
 width: 100vw;
 height: 100vh;
 background-color: #FF4136;
}

.search-container {
 display: flex;
 flex-direction: column;
 flex-shrink: 0;
 width: 300px;
 padding: 10px;
 background-color: #FFF;
 border-radius: 10px;
}

.form-container {
 display: flex;
 flex-direction: row;
 width: 100%;
}

.input-container {
 width: 100%;
}

.input {
 width: 100%;
 border: none;
 border-radius: 10px;
 background-color: #f1f1f1;
 padding: 10px;
}

.input-from {
 margin-bottom: 5px;
}

.input-from--focusout {
 border-radius: 10px;
}

.input-from--focusin {
 border-radius: 10px 10px 0 0;
}

.input-to {
 margin-bottom: 5px;
}

.switch-container {
  margin-bottom: 5px;
}

.button {
 border: none;
 background-color: transparent;
}

.button-switch {
 height: 100%;
 width: 38px;
 margin-left: 5px;
 background-color: #f1f1f1;
 border-radius: 10px;
 background-image: url(../assets/images/switch.svg);
 background-position: center;
 background-size: 20px;
 background-repeat: no-repeat;
}

.button-switch:hover {
 background-image: url(../assets/images/switch-hover.svg);
}

.button-search {
 padding: 10px;
 background-color: #2ECC40;
 color: #FFF;
 border-radius: 10px;
 width: 100%;
 transition: background-color 0.5s ease;
}

.button-search:hover {
 background-color: #33e147;
}

.input-container-to {
  position: relative;

}

.nearest-container {
 position: absolute;
 top: 38px;
 background-color: #f1f1f1;
 padding: 5px;
 border-radius: 0 0 10px 10px;
 width: 100%;
 z-index: 100;
}

.messages {
 width: 300px;
 background-color: #FFF;
 padding: 5px;
 border-radius: 10px;
 text-align: center;
 margin-bottom: 5px;
 font-size: 10px;
}

.finding, .show-more {
 width: 100%;
 font-size: 10px;
 font-style: italic;
 margin: 0;
 padding: 5px;
}

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

.nearest-station {
 font-size: 10px;
 padding: 5px;
 border-radius: 10px;
}

.nearest-container--hidden {
 display: none;
}

.nearest-station--active {
 display: flex;
}

.nearest-station:hover {
 background-color: #FFF;
 cursor: pointer;
}

.logo {
 margin-right: 5px;
}

.nr-logo {
 width: 15px;
}

.station-distance {
 font-style: italic;
 float: right;
}</code>```

messages here

      <input type="text" class="input input-from" placeholder="From">

Finding stations closest to you...

         Leigh-on-Sea
         0.6km

         Chalkwell
         1.5km

         Westcliff
         2.7km

         Southend Central
         3.6km

         Southend Victoria
         3.8km

      <input type="text" class="input input-to" placeholder="To">

     <input type="button" class="button button-switch">

    <input type="button" class="button button-search" value="Search">

```

答:
Using setTimeout in the inputToFocusOut() function is indeed the correct way to obtain the desired effect: hiding of the menu must be delayed so that a click on a menu item will register and its callback will fire. There should be nothing hit and miss about it, just set the delay at a reasonable value, say 300ms, and remove the hiding of the menu from the addToInputFrom() callback. Actually, you can remove all of the latter function's class-toggling calls, as they are redundant there and may interfere. The menu will be shown/hidden by virtue of inputFrom gaining/losing focus.

BTW, why are you using focusout and not blur?

Body:
I'm trying to create a custom drop down menu, using HTML, CSS and Vanilla Javascript.

I've managed to get the menu to appear when the user clicks on the the "from" input field, however when I try and click on an option, it wont let you add the value stored in the "code" dataset.

I did get it to work by using setTimeout method, however it is a bit hit and miss sometimes and doesn't seem like a good solution.

Is there an alternative way to get it to work?

function app() {

  var messages = document.querySelector(".messages");

  var inputFrom = document.querySelector(".input-from");

  var inputTo = document.querySelector(".input-to");

  var nearestContainer = document.querySelector(".nearest-container");

  inputFrom.addEventListener("focus", inputToFocusIn, false);

  function inputToFocusIn(e) {

    messages.innerHTML = "focusin event triggered on input-from";

    // add class
    inputFrom.classList.add("input-from--focusin");
    nearestContainer.classList.add("nearest-container--active");

    // remove class
    inputFrom.classList.remove("input-from--focusout");
    nearestContainer.classList.remove("nearest-container--hidden");

  }

  inputFrom.addEventListener("focusout", inputToFocusOut, false);

  function inputToFocusOut(e) {

    messages.innerHTML = "focusout event triggered on input-from";

      // add class
      inputFrom.classList.remove("input-from--focusin");
      nearestContainer.classList.remove("nearest-container--active");

      // remove class
      inputFrom.classList.add("input-from--focusout");
      nearestContainer.classList.add("nearest-container--hidden");

  }

  var nearestStations = document.querySelectorAll(".nearest-station");

  // add event listener to buttons
  for(var nearestStation of nearestStations) {

    nearestStation.addEventListener("click", addToInputFrom, false);

  }

  function addToInputFrom(e) {

    inputFrom.classList.add("input-from--focusout");
    nearestContainer.classList.add("nearest-container--hidden");

    inputFrom.classList.remove("input-from--focusin")
    nearestContainer.classList.remove("nearest-container--active")

    var targetDataset = e.currentTarget.dataset.code;

    messages.innerHTML = "station added to input from field"

    inputFrom.value = "";
    inputFrom.value = targetDataset;

  }

  var switchButton = document.querySelector(".button-switch");

  switchButton.addEventListener("click", clickSwitch, false);

  function clickSwitch(e) {

    var inputFromValue = inputFrom.value;
    var inputToValue = inputTo.value;

    inputFrom.value = inputToValue;
    inputTo.value = inputFromValue;

  }

}

window.onload = app();

/* stylesheet */

body {
 font-family: "GRAPHIK";
 font-style: normal;
 font-weight: 400;
 font-size: 16px;
 color: #242424;
}

* {
 box-sizing: border-box;
 outline: none;
}

.container {
 display: flex;
 flex-direction: column;
 justify-content: center;
 align-items: center;
 width: 100vw;
 height: 100vh;
 background-color: #FF4136;
}

.search-container {
 display: flex;
 flex-direction: column;
 flex-shrink: 0;
 width: 300px;
 padding: 10px;
 background-color: #FFF;
 border-radius: 10px;
}

.form-container {
 display: flex;
 flex-direction: row;
 width: 100%;
}

.input-container {
 width: 100%;
}

.input {
 width: 100%;
 border: none;
 border-radius: 10px;
 background-color: #f1f1f1;
 padding: 10px;
}

.input-from {
 margin-bottom: 5px;
}

.input-from--focusout {
 border-radius: 10px;
}

.input-from--focusin {
 border-radius: 10px 10px 0 0;
}

.input-to {
 margin-bottom: 5px;
}

.switch-container {
  margin-bottom: 5px;
}

.button {
 border: none;
 background-color: transparent;
}

.button-switch {
 height: 100%;
 width: 38px;
 margin-left: 5px;
 background-color: #f1f1f1;
 border-radius: 10px;
 background-image: url(../assets/images/switch.svg);
 background-position: center;
 background-size: 20px;
 background-repeat: no-repeat;
}

.button-switch:hover {
 background-image: url(../assets/images/switch-hover.svg);
}

.button-search {
 padding: 10px;
 background-color: #2ECC40;
 color: #FFF;
 border-radius: 10px;
 width: 100%;
 transition: background-color 0.5s ease;
}

.button-search:hover {
 background-color: #33e147;
}

.input-container-to {
  position: relative;

}

.nearest-container {
 position: absolute;
 top: 38px;
 background-color: #f1f1f1;
 padding: 5px;
 border-radius: 0 0 10px 10px;
 width: 100%;
 z-index: 100;
}

.messages {
 width: 300px;
 background-color: #FFF;
 padding: 5px;
 border-radius: 10px;
 text-align: center;
 margin-bottom: 5px;
 font-size: 10px;
}

.finding, .show-more {
 width: 100%;
 font-size: 10px;
 font-style: italic;
 margin: 0;
 padding: 5px;
}

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

.nearest-station {
 font-size: 10px;
 padding: 5px;
 border-radius: 10px;
}

.nearest-container--hidden {
 display: none;
}

.nearest-station--active {
 display: flex;
}

.nearest-station:hover {
 background-color: #FFF;
 cursor: pointer;
}

.logo {
 margin-right: 5px;
}

.nr-logo {
 width: 15px;
}

.station-distance {
 font-style: italic;
 float: right;
}

messages here

      <input type="text" class="input input-from" placeholder="From">

Finding stations closest to you...

         Leigh-on-Sea
         0.6km

         Chalkwell
         1.5km

         Westcliff
         2.7km

         Southend Central
         3.6km

         Southend Victoria
         3.8km

      <input type="text" class="input input-to" placeholder="To">

     <input type="button" class="button button-switch">

    <input type="button" class="button button-search" value="Search">


来源: stackexchange

问:
Set selected value of a dropdown in Razor view
I am trying to set the selected value in a dropdown in a razor view.

```<code>       <select id="drpStatus" name="status">
               <option value="A">Active</option>
               <option value="S">Suspended</option>
               <option value="T">Terminated</option>
               <option value="D">Deleted</option>
       </select>

//I am trying with the below code, based on the value in Model, I want to set the  particular option as selected
<option selected=@{if(@Model!=null && @Model.Status=='A'){'selected'}} value="A">Active</option>
</code>```

Above code is not working, please let me know if I am working in a right direction or is there any other/better way to achieve it.

答:
@{
    List<SelectListItem> lstOrderTypes = new List<SelectListItem>();
    lstOrderTypes.Add(new SelectListItem {Value = "1", Text = "plan1" });
    lstOrderTypes.Add(new SelectListItem {Value = "2", Text = "plan2" });
}
@functions {
    public static string GetString(IHtmlContent content)
    {
        var writer = new System.IO.StringWriter();
        content.WriteTo(writer, HtmlEncoder.Default);
        return writer.ToString();
    }
}

@{
    var x = GetString(Html.DisplayFor(model => model.OrderType));
}

<select>
  @foreach (SelectListItem option in lstOrderTypes)
  {
      <option value="@option.Value" selected="@(option.Value == x)">@option.Text</option>
  }
</select>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set the selected value in a dropdown in a razor view.

       <select id="drpStatus" name="status">
               <option value="A">Active</option>
               <option value="S">Suspended</option>
               <option value="T">Terminated</option>
               <option value="D">Deleted</option>
       </select>

//I am trying with the below code, based on the value in Model, I want to set the  particular option as selected
<option selected=@{if(@Model!=null && @Model.Status=='A'){'selected'}} value="A">Active</option>

Above code is not working, please let me know if I am working in a right direction or is there any other/better way to achieve it.


问:
Regarding p2p connection and c#
i just want to know how two application interact with each other across the internet. how one send some message to other one because when IP is not fixed. please give me some coding tips by which a p2p apps connect other one across the internet when IP is not known.

please help me in detail.

答:
As Spender pointed out, you can't do this without using a server as a go-between. Would you expect to be able to visit a friend if you didn't know their address?

In other words, each of the two machines intending to establish a P2P conection would contact a known server to exchange connection information. After that they could in theory talk to each other.

However, it is likely that they are behind routers using NAT and therefore can't receive incoming packets without either opening ports on the router or resorting to some kind of technique to get around NAT.

ContentLicense: CC BY-SA 2.5

Title: Regarding p2p connection and c#


问:
Insert the contents of a file as the first lines of a file; In bash (GNU)
The specific task is to use the header of a KML file and insert it into hundreds of split up KML data files that do not have the header.

The KML header is multiple lines and specific spacing. I've found I can use Sed with the 'r' readfile option to grab the contents of a file containing the header. However when I insert the data with '1r' the header is placed in the file starting on the second line. sed doesn't seem to let me address 'line 0' to insert before. Insert mode would work, but I wouldn't be able to just grab the header format that is saved in a file and would need to script the entire header.

```<code>#!/bin/bash
for i in ./Split/*;
        do sed -i '1r KML_Header.txt' $i
done
</code>```

The KML Header Looks like this:

```<code><?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
</code>```

The end result with the header will look something like this:

```<code><?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <when>2017-11-16T11:47:52Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>
</code>```

However, this is what my current best command gets me:

```<code><when>2017-11-16T11:47:52Z</when>
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>
</code>```

答:
I suggest trying awk.  With GNU awk:

```<code>awk -i inplace 'FNR==NR{hdr=hdr "\n" $0; next} FNR==1{print substr(hdr,2)} 1' inplace=0 header inplace=1 ./Split/*
</code>```

How it works:

-i inplace

This tells awk to change files in-place.

FNR==NR{hdr=hdr "\n" $0; next}

This tells awk that, when reading the first file (header), it should save the contents in the variable hdr, skip the rest of the commands, and jump to the next line.

FNR==1{print substr(hdr,2)}

This tells that, when it starts a new file, it should first print the header (minus the unneeded initial newline in variable hdr).

1

This is awks cryptic shorthand for print-the-current-line.

Example

```<code>$ cat >header
1
2
3
$ cat >file1
4
5
6
$ cat >file2
44
55
66
</code>```

Using our command to change the files in-place:

```<code>$ awk -i inplace 'FNR==NR{hdr=hdr "\n" $0; next} FNR==1{print substr(hdr,2)} 1' inplace=0 header inplace=1 file*
$ cat file1
1
2
3
4
5
6
$ cat file2
1
2
3
44
55
66
</code>```

Hat tip to Barmar.

Body:
The specific task is to use the header of a KML file and insert it into hundreds of split up KML data files that do not have the header.

The KML header is multiple lines and specific spacing. I've found I can use Sed with the 'r' readfile option to grab the contents of a file containing the header. However when I insert the data with '1r' the header is placed in the file starting on the second line. sed doesn't seem to let me address 'line 0' to insert before. Insert mode would work, but I wouldn't be able to just grab the header format that is saved in a file and would need to script the entire header.

#!/bin/bash
for i in ./Split/*;
        do sed -i '1r KML_Header.txt' $i
done

The KML Header Looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>

The end result with the header will look something like this:

<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <when>2017-11-16T11:47:52Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>

However, this is what my current best command gets me:

<when>2017-11-16T11:47:52Z</when>
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>

Body:
I suggest trying awk.  With GNU awk:

awk -i inplace 'FNR==NR{hdr=hdr "\n" $0; next} FNR==1{print substr(hdr,2)} 1' inplace=0 header inplace=1 ./Split/*

How it works:

-i inplace

This tells awk to change files in-place.

FNR==NR{hdr=hdr "\n" $0; next}

This tells awk that, when reading the first file (header), it should save the contents in the variable hdr, skip the rest of the commands, and jump to the next line.

FNR==1{print substr(hdr,2)}

This tells that, when it starts a new file, it should first print the header (minus the unneeded initial newline in variable hdr).

1

This is awks cryptic shorthand for print-the-current-line.

Example

$ cat >header
1
2
3
$ cat >file1
4
5
6
$ cat >file2
44
55
66

Using our command to change the files in-place:

$ awk -i inplace 'FNR==NR{hdr=hdr "\n" $0; next} FNR==1{print substr(hdr,2)} 1' inplace=0 header inplace=1 file*
$ cat file1
1
2
3
4
5
6
$ cat file2
1
2
3
44
55
66

Hat tip to Barmar.


问:
Using shared_ptr for unique ownership (kind of) - is this good practice?
this is quite hard to explain but I'll try my best. So, I have a RenderComponent, EventManager and RenderSystem. In my RenderComponents constructor, I raise a renderComponentCreated event which the RenderSystem subscribes to. Using an event args object, I pass a RenderNode as data which contains the information the renderSystem needs to draw the thing (drawable, position and type).

So far so good. Now, when the renderComponent is deleted, I want the RenderNode to be removed from the RenderSystem automatically while still leaving the option to remove it manually e.g. as a reaction to some event. This could be done using a RenderComponentRemoveNodeEvent which again the RenderSystem subscribes to.

Now the 'problem'. From my understanding (and from what I want) the renderNode should be something uniquely owned by the RenderComponent (hence unique_ptr). However, this would require me to either copy (and implement a comparison operator for the renderNode --> to be able to find it when I want to remove it) or pass a reference / raw pointer to the renderNode. However, (If I'm correct) there is no way to know whether a reference still refers to a valid object which would mean that automatic removal could not be implemented.

My solution was to make the RenderNode (that is uniquely owned by the RenderComponent) shared and pass weak pointers to the event. The RenderSystem also now maintains a list of weak pointers that it checks for whether they are still pointing to a valid object and automatically removes them if not. So essentially what I would have wanted is creating a weak pointer from a unique one. However, the way it is now, someone could just create a shared pointer from the weak pointer and keep the RenderNode alive longer than it should. Since the managed object itself (RenderNode) contains references to other objects that will not exist longer than the RenderComponent this may cause serious issues.

My question now: can this be considered good design or have I missed something?

PS: Sorry if this explanation reads a bit clunky (English is not my native) and thanks for your help!

答:
There's certainly nothing wrong with using std::weak_ptr to grant access to an object that might be destroyed, that's what it was invented for. But it does necessitate that the object itself be held by a std::shared_ptr. Not only does this mask your intent to have the object lifetime controlled by its parent, it forces dynamic allocation of the object and precludes it from being a member variable of the parent.

An alternate approach is to keep track of the pointer through a handle, and have a handle manager that tracks whether the object is alive or dead. The safest way to implement this is to make the manager a base class of the object you're tracking, that way RAII ensures it is always up to date. Here's a sample implementation of that concept. Note: untested.

```<code>template<class Derived>
class HandleBased
{
public:
    typedef uint64_t handle_t;

    HandleBased() : m_Handle(NextHandle())
    {
        Map()[m_Handle] = this;
    }

    ~HandleBased()
    {
        auto it = Map().find(m_Handle);
        Map().erase(it);
    }

    handle_t ThisHandle()
    {
        return m_Handle;
    }

    static Derived* FindPtr(handle_t h)
    {
        auto it = Map().find(h);
        if (it == Map().end())
            return null_ptr;
        return static_cast<Derived*>(it->second);
    }

private:
    static handle_t NextHandle()
    {
        static handle_t next = 0;
        return next++;
    }

    static std::unordered_map<handle_t, HandleBased*>& Map()
    {
        static std::unordered_map<handle_t, HandleBased*> the_map;
        return the_map;
    }

    handle_t m_Handle;
};
</code>```

And here's an example of how you'd use it:

```<code>class RenderNode : public HandleBased<RenderNode>
{
};

class RenderComponent
{
    std::unique_ptr<RenderNode> node1;
    RenderNode node2;

public:
    void Setup(RenderSystem& rs)
    {
        node1 = new RenderNode;
        rs.nodes.push_back(node1->ThisHandle());
        rs.nodes.push_back(node2.ThisHandle());
    }
};

class RenderSystem
{
public:
    std::list<RenderNode::Handle> nodes;

    void DoRender()
    {
        for (auto it = nodes.begin(); it != nodes.end(); )
        {
            RenderNode* p = RenderNode::FindPtr(*it);
            if (p == NULL)
                it = nodes.erase(it);
            else
            {
                p->DoSomething();
                ++it;
            }
        }
    }
};
</code>```

Body:
There's certainly nothing wrong with using std::weak_ptr to grant access to an object that might be destroyed, that's what it was invented for. But it does necessitate that the object itself be held by a std::shared_ptr. Not only does this mask your intent to have the object lifetime controlled by its parent, it forces dynamic allocation of the object and precludes it from being a member variable of the parent.

An alternate approach is to keep track of the pointer through a handle, and have a handle manager that tracks whether the object is alive or dead. The safest way to implement this is to make the manager a base class of the object you're tracking, that way RAII ensures it is always up to date. Here's a sample implementation of that concept. Note: untested.

template<class Derived>
class HandleBased
{
public:
    typedef uint64_t handle_t;

    HandleBased() : m_Handle(NextHandle())
    {
        Map()[m_Handle] = this;
    }

    ~HandleBased()
    {
        auto it = Map().find(m_Handle);
        Map().erase(it);
    }

    handle_t ThisHandle()
    {
        return m_Handle;
    }

    static Derived* FindPtr(handle_t h)
    {
        auto it = Map().find(h);
        if (it == Map().end())
            return null_ptr;
        return static_cast<Derived*>(it->second);
    }

private:
    static handle_t NextHandle()
    {
        static handle_t next = 0;
        return next++;
    }

    static std::unordered_map<handle_t, HandleBased*>& Map()
    {
        static std::unordered_map<handle_t, HandleBased*> the_map;
        return the_map;
    }

    handle_t m_Handle;
};

And here's an example of how you'd use it:

class RenderNode : public HandleBased<RenderNode>
{
};

class RenderComponent
{
    std::unique_ptr<RenderNode> node1;
    RenderNode node2;

public:
    void Setup(RenderSystem& rs)
    {
        node1 = new RenderNode;
        rs.nodes.push_back(node1->ThisHandle());
        rs.nodes.push_back(node2.ThisHandle());
    }
};

class RenderSystem
{
public:
    std::list<RenderNode::Handle> nodes;

    void DoRender()
    {
        for (auto it = nodes.begin(); it != nodes.end(); )
        {
            RenderNode* p = RenderNode::FindPtr(*it);
            if (p == NULL)
                it = nodes.erase(it);
            else
            {
                p->DoSomething();
                ++it;
            }
        }
    }
};


问:
How to make Min-plus matrix multiplication in python faster?
So I have two matrices, A and B, and I want to compute the min-plus product as given here: Min-plus matrix multiplication. For that I've implemented the following:

```<code>def min_plus_product(A,B):
    B = np.transpose(B)
    Y = np.zeros((len(B),len(A)))
    for i in range(len(B)):
         Y[i] = (A + B[i]).min(1)
    return np.transpose(Y)
</code>```

This works fine, but is slow for big matrices, is there a way to make it faster? I've heard that implemeting in C or using the GPU might be good options.

答:
Here is an algo that saves a bit if the middle dimension is large enough and entries are uniformly distributed. It exploits the fact that the smallest sum typically will be from two small terms.

```<code>import numpy as np

def min_plus_product(A,B):
    B = np.transpose(B)
    Y = np.zeros((len(B),len(A)))
    for i in range(len(B)):
         Y[i] = (A + B[i]).min(1)
    return np.transpose(Y)

def min_plus_product_opt(A,B, chop=None):
    if chop is None:
        # not sure this is optimal
        chop = int(np.ceil(np.sqrt(A.shape[1])))
    B = np.transpose(B)
    Amin = A.min(1)
    Y = np.zeros((len(B),len(A)))
    for i in range(len(B)):
        o = np.argsort(B[i])
        Y[i] = (A[:, o[:chop]] + B[i, o[:chop]]).min(1)
        if chop < len(o):
            idx = np.where(Amin + B[i, o[chop]] < Y[i])[0]
            for j in range(chop, len(o), chop):
                if len(idx) == 0:
                    break
                x, y = np.ix_(idx, o[j : j + chop])
                slmin = (A[x, y] + B[i, o[j : j + chop]]).min(1)
                slmin = np.minimum(Y[i, idx], slmin)
                Y[i, idx] = slmin
                nidx = np.where(Amin[idx] + B[i, o[j + chop]] < Y[i, idx])[0]
                idx = idx[nidx]
    return np.transpose(Y)

A = np.random.random(size=(1000,1000))
B = np.random.random(size=(1000,2000))

print(np.allclose(min_plus_product(A,B), min_plus_product_opt(A,B)))

import time
t = time.time();min_plus_product(A,B);print('naive {}sec'.format(time.time()-t))
t = time.time();min_plus_product_opt(A,B);print('opt {}sec'.format(time.time()-t))
</code>```

Sample output:

```<code>True
naive 7.794037580490112sec
opt 1.65810227394104sec
</code>```

Body:
So I have two matrices, A and B, and I want to compute the min-plus product as given here: Min-plus matrix multiplication. For that I've implemented the following:

def min_plus_product(A,B):
    B = np.transpose(B)
    Y = np.zeros((len(B),len(A)))
    for i in range(len(B)):
         Y[i] = (A + B[i]).min(1)
    return np.transpose(Y)

This works fine, but is slow for big matrices, is there a way to make it faster? I've heard that implemeting in C or using the GPU might be good options.

Body:
Here is an algo that saves a bit if the middle dimension is large enough and entries are uniformly distributed. It exploits the fact that the smallest sum typically will be from two small terms.

import numpy as np

def min_plus_product(A,B):
    B = np.transpose(B)
    Y = np.zeros((len(B),len(A)))
    for i in range(len(B)):
         Y[i] = (A + B[i]).min(1)
    return np.transpose(Y)

def min_plus_product_opt(A,B, chop=None):
    if chop is None:
        # not sure this is optimal
        chop = int(np.ceil(np.sqrt(A.shape[1])))
    B = np.transpose(B)
    Amin = A.min(1)
    Y = np.zeros((len(B),len(A)))
    for i in range(len(B)):
        o = np.argsort(B[i])
        Y[i] = (A[:, o[:chop]] + B[i, o[:chop]]).min(1)
        if chop < len(o):
            idx = np.where(Amin + B[i, o[chop]] < Y[i])[0]
            for j in range(chop, len(o), chop):
                if len(idx) == 0:
                    break
                x, y = np.ix_(idx, o[j : j + chop])
                slmin = (A[x, y] + B[i, o[j : j + chop]]).min(1)
                slmin = np.minimum(Y[i, idx], slmin)
                Y[i, idx] = slmin
                nidx = np.where(Amin[idx] + B[i, o[j + chop]] < Y[i, idx])[0]
                idx = idx[nidx]
    return np.transpose(Y)

A = np.random.random(size=(1000,1000))
B = np.random.random(size=(1000,2000))

print(np.allclose(min_plus_product(A,B), min_plus_product_opt(A,B)))

import time
t = time.time();min_plus_product(A,B);print('naive {}sec'.format(time.time()-t))
t = time.time();min_plus_product_opt(A,B);print('opt {}sec'.format(time.time()-t))

Sample output:

True
naive 7.794037580490112sec
opt 1.65810227394104sec


问:
Newtonsoft deserialize multiple JSON files with cross references
I have two JSON files (that I can't change the format for) in the following format:

Main file -

```<code>[
   {
      "Name":"XYZ",
      "UnitReferenceId":1
   },
   {
      "Name":"ABC",
      "UnitReferenceId":2
   }
]
</code>```

The lookup/reference JSON file -

```<code>[
   {
      "UnitReferenceId":1,
      "Units":[
         {
            "Unit":"mg",
            "Scale":1
         },
         {
            "Unit":"gm",
            "Scale":1000
         },
         {
            "Unit":"kg",
            "Scale":1000000
         }
      ]
   },
   {
      "UnitReferenceId":2,
      "Units":[
         {
            "Unit":"mm",
            "Scale":1
         },
         {
            "Unit":"m",
            "Scale":1000
         },
         {
            "Unit":"km",
            "Scale":1000000
         }
      ]
   }
]
</code>```

How would I go about deserializing that into C# classes using Newtonsoft JSON into something like:

```<code>public class Widget
{
    public string Name {get; set;}
    public UnitReference UnitReference { get; set; }
}

public class UnitReference
{
    public long UnitReferenceId { get; set; }
    public List<Unit> Units { get; set; }
}
public class Unit
{
    [JsonProperty("Unit")]
    public string UnitValue { get; set; }
    public long Scale { get; set; }
}
</code>```

Any help would be greatly appreciated!

答: I use json2csharp for creating my classes quickly.  If you have to implement it in code, see JSON C# Class Generator Project.</p>

Body:
I have two JSON files (that I can't change the format for) in the following format:

Main file -

[
   {
      "Name":"XYZ",
      "UnitReferenceId":1
   },
   {
      "Name":"ABC",
      "UnitReferenceId":2
   }
]

The lookup/reference JSON file -

[
   {
      "UnitReferenceId":1,
      "Units":[
         {
            "Unit":"mg",
            "Scale":1
         },
         {
            "Unit":"gm",
            "Scale":1000
         },
         {
            "Unit":"kg",
            "Scale":1000000
         }
      ]
   },
   {
      "UnitReferenceId":2,
      "Units":[
         {
            "Unit":"mm",
            "Scale":1
         },
         {
            "Unit":"m",
            "Scale":1000
         },
         {
            "Unit":"km",
            "Scale":1000000
         }
      ]
   }
]

How would I go about deserializing that into C# classes using Newtonsoft JSON into something like:

public class Widget
{
    public string Name {get; set;}
    public UnitReference UnitReference { get; set; }
}

public class UnitReference
{
    public long UnitReferenceId { get; set; }
    public List<Unit> Units { get; set; }
}
public class Unit
{
    [JsonProperty("Unit")]
    public string UnitValue { get; set; }
    public long Scale { get; set; }
}

Any help would be greatly appreciated!


问:
quickly inspect OCR text layer on PDF file
Is there any program that will allow me to superimpose the text (OCR) layer of a PDF on top of the PDF rendering?

I want to quickly see if the text layer has errors or not.

It would be more convenient if that can be done with a program, if not, some cli command or script would also work.

答:
Superimpose?  It implies you'd like to add text while I believe you'd like to have access to the text for detection and possibly further analysis of the OCRed text quality.  Perhaps need further clarification.

Our developers worked for some time on algorithms to detect the presence of text in PDFs and then evaluate its quality.  There are many cases that can trick a basic algorithm - Bates number or imprinter added into image-only PDF makes it seem like PDF has high-quality text while it has no actual text.  Some copiers produce "searchable PDFs" while using very low-quality OCR that contains many errors, but not necessarily on the first page that is typically some kind of title page with large fonts, thus the first line of the text encountered by an algorithm seems high quality.  Or the first page may have text while other pages do not, yet algorithm may believe the whole PDF has text.

In our commercial high-volume server-based OCR software (used by service bureaus, SaaS platforms,  libraries, backlog conversions, etc.) we now have advanced detection of PDFs with existing text layer and "smart decisions" which can filter out many of these false positive situations.  Our OCR can skip re-OCRing PDFs with high-quality text in PDFs.  If you are looking for a high-quality inexpensive OCR platform, such detection is a feature in it, but it can't be used separately without our OCR.  OCR workflow is used as a part of that filter.  Our developers wrote and integrated these algorithms without external tools.

I am with www.wisetrend.com where we provide software solutions and consulting for various OCR projects.


问:
UITabBarItem title overwritten by UIViewController title?
I have setup a UITabBarController with two separate UIViewControllers. In the init for the second UIViewController I am setting the UITabBarItem so it displays the tab correctly:

```<code>UITabBarItem *tabBar = [self tabBarItem];
[tabBar setTitle:@"DATA"];
[tabBar setImage:[UIImage imageNamed:@"DATA.png"]];
</code>```

This works fine, the tab shows the title "DATA" and displays the correct icon image. In the same controller inside loadView I am setting the UIViewController title:

```<code>[self setTitle:@"Data Table"];
</code>```

My question is when I run the application my 2nd tab reads "DATA" however when I click on the tab and loadView is called (I have a UITableView in there) and I set the UNViewControllers title property to "Data Table" my 2nd tab also changes to read "Data Table". Is there a way to fix/avoid this?

答:
Are you sure you want just two UIViewControllers not UINavigationControllers? Usually you create a UIViewController, then create UINavigationController with that view controller, and then put these navigation controllers into UITabBarController.

This way your UIViewController will actually have 'title' which you can change.

Body:
I have setup a UITabBarController with two separate UIViewControllers. In the init for the second UIViewController I am setting the UITabBarItem so it displays the tab correctly:

UITabBarItem *tabBar = [self tabBarItem];
[tabBar setTitle:@"DATA"];
[tabBar setImage:[UIImage imageNamed:@"DATA.png"]];

This works fine, the tab shows the title "DATA" and displays the correct icon image. In the same controller inside loadView I am setting the UIViewController title:

[self setTitle:@"Data Table"];

My question is when I run the application my 2nd tab reads "DATA" however when I click on the tab and loadView is called (I have a UITableView in there) and I set the UNViewControllers title property to "Data Table" my 2nd tab also changes to read "Data Table". Is there a way to fix/avoid this?


问:
Java - How to populate 2d array with nested while loops?
I need to populate a double array with user input by using nested while loops only. This is what I have so far:</p>

```<code>public static double[][] score() {
        int col = 3;
        int row = 3;
        int size = 0;
        Scanner in = new Scanner(System.in);
        double[][] scores = new double[row][col];
        System.out.println("Enter your scores: ");
        while (in.hasNextDouble() && size < scores.length) {
            while (size < scores[size].length) {
                scores[][] = in.hasNextDouble();
                size++;
            }
            return scores;
        }
</code>```

答:
The most common way to do this is through for loops since they allow you to specify the index counters you need in a concise way:

```<code>for(int i = 0; i < scores.length; i++){
    for(int j = 0; j < scores[i].length; j++){
        scores[i][j] = in.nextDouble();
    }
}
</code>```

If you specifically need to use while loops you can do pretty much the same thing, its just broken up into multiple lines:

```<code>int i = 0;
while(i < scores.length){
    int j = 0;
    while(j < scores[i].length){
        scores[i][j] = in.nextDouble();
        j++;
    }
    i++;
}
</code>```

Body:
I need to populate a double array with user input by using nested while loops only. This is what I have so far:

public static double[][] score() {
        int col = 3;
        int row = 3;
        int size = 0;
        Scanner in = new Scanner(System.in);
        double[][] scores = new double[row][col];
        System.out.println("Enter your scores: ");
        while (in.hasNextDouble() && size < scores.length) {
            while (size < scores[size].length) {
                scores[][] = in.hasNextDouble();
                size++;
            }
            return scores;
        }

Body:
The most common way to do this is through for loops since they allow you to specify the index counters you need in a concise way:

for(int i = 0; i < scores.length; i++){
    for(int j = 0; j < scores[i].length; j++){
        scores[i][j] = in.nextDouble();
    }
}

If you specifically need to use while loops you can do pretty much the same thing, its just broken up into multiple lines:

int i = 0;
while(i < scores.length){
    int j = 0;
    while(j < scores[i].length){
        scores[i][j] = in.nextDouble();
        j++;
    }
    i++;
}


问:
MySql - Getting total number from two groups of records from one table
I am on Mysql version 5.5. I have two tables - product, ordr.

```<code>CREATE TABLE `product` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `ordr` (
  `id` int(11) NOT NULL,
  `product_id` varchar(45) DEFAULT NULL,
  `status` varchar(45) DEFAULT NULL,
  `qty` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

Here is how they are populated -

```<code>insert into product values (20, 'pen');

insert into ordr values (100, 20, 'queue', 5);
insert into ordr values (110, 20, 'queue', 5);
insert into ordr values (120, 20, 'pending', 10);
insert into ordr values (130, 20, 'pending', 10);
insert into ordr values (140, 20, 'pending', 10);
</code>```

I want to get the total quantity of products that are in two different statuses. For the test data above data, I want to see 10 for queue quantity and 30 for pending quantity.

When I run

```<code>select p.name, sum(o.qty) as queue_qty, sum(o2.qty) as pending_qty
from product p
left outer join ordr o on o.product_id = p.id and o.status = 'queue'
left outer join ordr o2 on o2.product_id = p.id and o2.status = 'pending'
where p.id = 20;
</code>```

I get

```<code>name - pen
queue_qty - 30
pending_qty - 60
</code>```

Can someone help me fix this SQL?

答:
You need to aggregate the information before it's joined. Since you have two 1-n relationships, your join logic is duplicating information.</p>

```<code>select
  p.name
  , o.qty as qty_queue
  , o2.qty as qty_pending
from
  product p
  join (
    select
      product_id
      , sum(qty) as qty
    from
      ordr
    where
      ordr.status = 'queue'
    group by
      product_id
  ) o
    on p.id = o.product_id
  join (
    select
      product_id
      , sum(qty) as qty
    from
      ordr
    where
      ordr.status = 'pending'
    group by
      product_id
  ) o2
    on p.id = o2.product_id
group by
  p.name
</code>```

Body:
I am on Mysql version 5.5. I have two tables - product, ordr.

CREATE TABLE `product` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `ordr` (
  `id` int(11) NOT NULL,
  `product_id` varchar(45) DEFAULT NULL,
  `status` varchar(45) DEFAULT NULL,
  `qty` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Here is how they are populated -

insert into product values (20, 'pen');

insert into ordr values (100, 20, 'queue', 5);
insert into ordr values (110, 20, 'queue', 5);
insert into ordr values (120, 20, 'pending', 10);
insert into ordr values (130, 20, 'pending', 10);
insert into ordr values (140, 20, 'pending', 10);

I want to get the total quantity of products that are in two different statuses. For the test data above data, I want to see 10 for queue quantity and 30 for pending quantity.

When I run

select p.name, sum(o.qty) as queue_qty, sum(o2.qty) as pending_qty
from product p
left outer join ordr o on o.product_id = p.id and o.status = 'queue'
left outer join ordr o2 on o2.product_id = p.id and o2.status = 'pending'
where p.id = 20;

I get

name - pen
queue_qty - 30
pending_qty - 60

Can someone help me fix this SQL?

Body:
You need to aggregate the information before it's joined. Since you have two 1-n relationships, your join logic is duplicating information.

select
  p.name
  , o.qty as qty_queue
  , o2.qty as qty_pending
from
  product p
  join (
    select
      product_id
      , sum(qty) as qty
    from
      ordr
    where
      ordr.status = 'queue'
    group by
      product_id
  ) o
    on p.id = o.product_id
  join (
    select
      product_id
      , sum(qty) as qty
    from
      ordr
    where
      ordr.status = 'pending'
    group by
      product_id
  ) o2
    on p.id = o2.product_id
group by
  p.name


问:
Is A* algorithm suitable in starting and ending positions composed of multiple neighbouring cells
Can the A* algorithm be efficiently applied to a NxM rectangular grid with varying travel cost involved while moving to any cell and starting location is not a single cell but is composed of multiple closed cells; say a cluster of neighbouring cells where a neighbour of a cell is any of the eight cells surrounding it? (The ending cell is similar to that.)
If so, then can anyone please show the way and if not what can be a good procedure to tackle the problem?</p>

答:
Can the A* algorithm be efficiently applied to a NxM rectangular grid with varying travel cost [...]

Yes, A* works on Graphs of any type as long as edge costs are positive. Instead of phrasing the graph as a grid with regular neighbours, construct it so that grid cells which are connected have edges between them.

Edge costs can also be arbitrary as long as they are non-negative (positive or zero).

Make sure that your heuristic remains admissible.

and starting location is not a single cell but is composed of multiple closed cells;

Yes, this should be possible.

Decide on an initial cost for each of the cells. Zero as costs for all of them would be easiest.

Instead of adding just the single start vertex into the priority queue, add all the multiple cells into the priority queue.

say a cluster of neighbouring cells where a neighbour of a cell is any of the eight cells surrounding it? (The ending cell is similar to that.)

The goal can also be composed of multiple cells.

Just make it such that reaching any of the goal cells terminates the search.

Make sure you to compute the heuristic as the minimum of the individual heuristics to each goal cell. (I.e. compute heuristic for each goal cell, then take minimal value.)


问:
checking invariants in C++
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

```<code>template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}
</code>```

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

```<code>#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};
</code>```

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?

答:
Question #0: I suppose there is no way to declare an unnamed local variable? :)

You can usually whip up something using macros and __LINE__, but if you just pick a strange enough name, it should already do, since you shouldn't have more than one (directly) in the same scope. This

```<code>class invariants_checker {};

template<class T>
class invariants_checker_impl : public invariants_checker {
public:
    invariants_checker_impl(T* that) : that_(that) {that_->check_invariants();}
    ~invariants_checker_impl()                     {that_->check_invariants();}
private:
    T* that_;
};

template<class T>
inline invariants_checker_impl<T> get_invariant_checker(T* that)
{return invariants_checker_impl<T>(that);}

#define CHECK_INVARIANTS const invariants_checker&
   my_fancy_invariants_checker_object_ = get_invariant_checker(this)
</code>```

works for me.

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

I'm not sure whether it invokes UB technical. In practice it would certainly be safe to do so - where it not for the fact that, in practice, a class member that has to be declared at a specific position in relation to other class members is going to be a problem sooner or later.

Question #2: Do you see any other problems with this approach? Can you improve it?

See #2. Take a moderately sized class, add half a decade of extending and bug-fixing by two dozen developers, and I consider the chances to mess this up at at least once at about 98%.

You can somewhat mitigate this by adding a shouting comment to the data member. Still.

Question #3: Is this approach new or well-known? Are there better solutions available?

I hadn't seen this approach, but given your description of before() and after() I immediately thought of the same solution.

I think Stroustrup had an article many (~15?) years ago, where he described a handle class overloading operator->() to return a proxy. This could then, in its ctor and dtor, perform before- and after-actions while being oblivious to the methods being invoked through it.

Edit: I see that Frerich has added an answer fleshing this out. Of course, unless your class already needs to be used through such a handle, this is a burden onto your class' users. (IOW: It won't work.)

Title: checking invariants in C++

Body:
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?

Body:
Question #0: I suppose there is no way to declare an unnamed local variable? :)

You can usually whip up something using macros and __LINE__, but if you just pick a strange enough name, it should already do, since you shouldn't have more than one (directly) in the same scope. This

class invariants_checker {};

template<class T>
class invariants_checker_impl : public invariants_checker {
public:
    invariants_checker_impl(T* that) : that_(that) {that_->check_invariants();}
    ~invariants_checker_impl()                     {that_->check_invariants();}
private:
    T* that_;
};

template<class T>
inline invariants_checker_impl<T> get_invariant_checker(T* that)
{return invariants_checker_impl<T>(that);}

#define CHECK_INVARIANTS const invariants_checker&
   my_fancy_invariants_checker_object_ = get_invariant_checker(this)

works for me.

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

I'm not sure whether it invokes UB technical. In practice it would certainly be safe to do so - where it not for the fact that, in practice, a class member that has to be declared at a specific position in relation to other class members is going to be a problem sooner or later.

Question #2: Do you see any other problems with this approach? Can you improve it?

See #2. Take a moderately sized class, add half a decade of extending and bug-fixing by two dozen developers, and I consider the chances to mess this up at at least once at about 98%.

You can somewhat mitigate this by adding a shouting comment to the data member. Still.

Question #3: Is this approach new or well-known? Are there better solutions available?

I hadn't seen this approach, but given your description of before() and after() I immediately thought of the same solution.

I think Stroustrup had an article many (~15?) years ago, where he described a handle class overloading operator->() to return a proxy. This could then, in its ctor and dtor, perform before- and after-actions while being oblivious to the methods being invoked through it.

Edit: I see that Frerich has added an answer fleshing this out. Of course, unless your class already needs to be used through such a handle, this is a burden onto your class' users. (IOW: It won't work.)


问:
High memory usage issues with G1 Garbage collector
We have been testing out G1 garbage collector recently with the following configuration:

-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UseG1GC -XX:MaxGCPauseMillis=1250 -XX:+PrintTenuringDistribution -Xloggc:${logdir}/gc-$(date +%Y_%m_%d-%H_%M).log -XX:+UseStringDeduplication -XX:+PrintStringDeduplicationStatistics -XX:+PrintPromotionFailure -XX:+PrintAdaptiveSizePolicy -XX:+PrintHeapAtGC -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M -XX:+UnlockExperimentalVMOptions -XX:G1NewSizePercent=15 -XX:ParallelGCThreads=8 -XX:+ParallelRefProcEnabled -XX:G1HeapRegionSize=8M
JAVA_OPTS_HEAP: -Xms16g -Xmx16g

We had recently come across an issue recently where two java processes were running with the above configuration on a box with 48 GB RAM and both the processes went on to consume around 20 - 22 GB of RAM each (few small processes consuming the remaining memory), thus filling the entire RAM and then it triggered disk swaps which finally led to the OOM and process getting killed.

This seems worrying because neither the NMT reports this memory usage in a meaningful way nor do we get any clues for this usage from the GC logs. In the NMT stats, the application memory was under 16G and the metaspace usage was under 1G.

We had tried setting maxMetaSpaceSize to 2G but that didn't help either. The RAM usage seems to grow unbounded when the process is running for days.

From the other questions it does seem that G1 garbage collector does tend to consume more memory but the disk swaps is a worrying issue. Could someone please provide some pointers on how this issue could be resolved?

答: Here you can find testing results of G1, Parallel, ConcMarkSweep, Serial and Shenandoah garbage collectors in terms of scaling and resource consumption, as well as some suggestions on what settings can be applied to improve results. So you can choose the most appropriate one for your project and reduce memory usage.</p>


问:
Need this code simplified please
so i just started learning python and found this 2 lines of code for finding multiple indexes of letters in strings/lists.
I'd love if some of you guys can simplify the 2nd line for me,

```<code>text= 'Allowed Hello Hollow'
print [n for n in xrange(len(text)) if text.find('ll', n) == n]
</code>```

I don't know if it's just a shortcut style writing or something, but I'd like it simplified, thanks :D

答:
Here's the "simplified" version

```<code>myList = []
for n in xrange(len(text)) :
    if(text.find('ll', n) == n) :
        list.append(n)
print myList
</code>```

This answer explains the syntax

Title: Need this code simplified please

Body:
so i just started learning python and found this 2 lines of code for finding multiple indexes of letters in strings/lists.
I'd love if some of you guys can simplify the 2nd line for me,

text= 'Allowed Hello Hollow'
print [n for n in xrange(len(text)) if text.find('ll', n) == n]

I don't know if it's just a shortcut style writing or something, but I'd like it simplified, thanks :D

Body:
Here's the "simplified" version

myList = []
for n in xrange(len(text)) :
    if(text.find('ll', n) == n) :
        list.append(n)
print myList

This answer explains the syntax


问:
Starting a new activity or intent in listview for certain items based on content rather than position
I am wondering if it is possible to have clickable items in a listview that start a new activity or intent based upon the content of the items rather than position.  Each specific item needs to have a specific specific action and I want my app to be able to move items from the top or bottom in the listview or add them to a new list.  If the items are stationary, then basing the action on the item's position will work fine, but since the items will move, it will create problems.  Therefore, having the action based on the content of the items(Strings in this instnce) is the best bet, because it will work wherever the items are.

Currently, I am using if (item_position==1), if (item_position==2), if (item_position==3),etc.  Here is the full code for reference:

```<code>public class MainActivity extends AppCompatActivity {

    ArrayList<String> selectedItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectedItems = new ArrayList<String>();
        ListView chl = (ListView) findViewById(R.id.colorselector);
        chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"};
        Adapter adapter=new Adapter(this,items);
        chl.setAdapter(adapter);

        chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                int item_position=i;
                if (item_position==1){

                }
</code>```

答:
You can retrieve the clicked item from the adapter using something like this:

```<code>String clickedItem = adapterView.getAdapter().getItem(position);
</code>```

I'm assuming the items your adapter holds are Strings based on your example. You may need to cast the item to String:

```<code>String clickedItem = (String) adapterView.getAdapter().getItem(position);
</code>```

or cast the Adapter to your specific implementation of adapter:

```<code>String clickedItem = ((MyAdapter)adapterView.getAdapter()).getItem(position);
</code>```

Body:
I am wondering if it is possible to have clickable items in a listview that start a new activity or intent based upon the content of the items rather than position.  Each specific item needs to have a specific specific action and I want my app to be able to move items from the top or bottom in the listview or add them to a new list.  If the items are stationary, then basing the action on the item's position will work fine, but since the items will move, it will create problems.  Therefore, having the action based on the content of the items(Strings in this instnce) is the best bet, because it will work wherever the items are.

Currently, I am using if (item_position==1), if (item_position==2), if (item_position==3),etc.  Here is the full code for reference:

public class MainActivity extends AppCompatActivity {

    ArrayList<String> selectedItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectedItems = new ArrayList<String>();
        ListView chl = (ListView) findViewById(R.id.colorselector);
        chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"};
        Adapter adapter=new Adapter(this,items);
        chl.setAdapter(adapter);

        chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                int item_position=i;
                if (item_position==1){

                }

Body:
You can retrieve the clicked item from the adapter using something like this:

String clickedItem = adapterView.getAdapter().getItem(position);

I'm assuming the items your adapter holds are Strings based on your example. You may need to cast the item to String:

String clickedItem = (String) adapterView.getAdapter().getItem(position);

or cast the Adapter to your specific implementation of adapter:

String clickedItem = ((MyAdapter)adapterView.getAdapter()).getItem(position);


问:
Uncaught TypeError: Cannot read property 'className' of undefined
The following error is being thrown in Google Chrome's developers tools:

Uncaught TypeError: Cannot read property 'className' of undefined

The code on which the error is being thrown is:

```<code>var oTable = $('#resultstable').dataTable({
                            "bAutoWidth" : true,
                            "iDisplayLength" : 10,
                            "bFilter" : false,
                            "bLengthChange" : false
                        });
</code>```

resultstable is the id of a table in the html:

```<code><table cellpadding="0" cellspacing="0" border="0" id="resultstable"
                    name="resultstable" class="display datatable">
</code>```

The weird thing is that after the table tag there is an if statement. The table runs perfectly fine and the CSS shows up correctly when the program is sent into the else if{} section, but it throws the above error and no CSS is applied when it is in the if{} section.

Help please!

答: Encountered  similar problem. Root case was that while dataTable was about to take control of the table, our code also tried to manipulate properties of the table a the same time. The error message does not say so, however, once the table was left to be managed solely by dataTable, the problem was gone.</p>

Body:
The following error is being thrown in Google Chrome's developers tools:

Uncaught TypeError: Cannot read property 'className' of undefined

The code on which the error is being thrown is:

var oTable = $('#resultstable').dataTable({
                            "bAutoWidth" : true,
                            "iDisplayLength" : 10,
                            "bFilter" : false,
                            "bLengthChange" : false
                        });

resultstable is the id of a table in the html:

The weird thing is that after the table tag there is an if statement. The table runs perfectly fine and the CSS shows up correctly when the program is sent into the else if{} section, but it throws the above error and no CSS is applied when it is in the if{} section.

Help please!


问:
Issues in doc2vec tags in Gensim
I am using gensim doc2vec as below.

```<code>from gensim.models import doc2vec
from collections import namedtuple
import re

my_d = {'recipe__001__1': 'recipe 1 details should come here',
 'recipe__001__2': 'Ingredients of recipe 2 need to be added'}
docs = []
analyzedDocument = namedtuple('AnalyzedDocument', 'words tags')
for key, value in my_d.items():
    value = re.sub("[^a-zA-Z]"," ", value)
    words = value.lower().split()
    tags = key
    docs.append(analyzedDocument(words, tags))
model = doc2vec.Doc2Vec(docs, size = 300, window = 10, dm=1, negative=5, hs=0, min_count = 1, workers = 4, iter = 20)
</code>```

However, when I check model.docvecs.offset2doctag I get ['r', 'e', 'c', 'i', 'p', '_', '0', '1', '2'] as the output. The real output should be `'recipe__001__1' and 'recipe__001__2'.

When I use len(model.docvecs.doctag_syn0) I get 9 as the output. But the real value should be 2 because I only have 2 recipes in my test dictionary.

Please let me know, why this happens?

答:
Try to change this line:

```<code>tags = key
</code>```

to

```<code>tags = [key]
</code>```

Title: Issues in doc2vec tags in Gensim

Body:
I am using gensim doc2vec as below.

from gensim.models import doc2vec
from collections import namedtuple
import re

my_d = {'recipe__001__1': 'recipe 1 details should come here',
 'recipe__001__2': 'Ingredients of recipe 2 need to be added'}
docs = []
analyzedDocument = namedtuple('AnalyzedDocument', 'words tags')
for key, value in my_d.items():
    value = re.sub("[^a-zA-Z]"," ", value)
    words = value.lower().split()
    tags = key
    docs.append(analyzedDocument(words, tags))
model = doc2vec.Doc2Vec(docs, size = 300, window = 10, dm=1, negative=5, hs=0, min_count = 1, workers = 4, iter = 20)

However, when I check model.docvecs.offset2doctag I get ['r', 'e', 'c', 'i', 'p', '_', '0', '1', '2'] as the output. The real output should be `'recipe__001__1' and 'recipe__001__2'.

When I use len(model.docvecs.doctag_syn0) I get 9 as the output. But the real value should be 2 because I only have 2 recipes in my test dictionary.

Please let me know, why this happens?

Body:
Try to change this line:

tags = key

to

tags = [key]


问:
GWT Overlay deep copy
What is the best way to make a deep copy of a gwt overlay type?

I'm looking for a function or library that inspects a GWT overlay and clones it. It must be able to clone contained arrays or objects.

Thanks

答:
Based on Lineman78's answer and taking into consideration this other answer from A. Levy I created the following function:

```<code>public class JsoUtils {

    @SuppressWarnings("unchecked")
    public static <T extends JavaScriptObject> T deepCopy(T obj)
    {
        return (T) deepCopyImpl(obj);
    }

    private static native JavaScriptObject deepCopyImpl(JavaScriptObject obj) /*-{

        if (obj == null) return obj;

        var copy;

        if (obj instanceof Date) {
            // Handle Date
            copy = new Date();
            copy.setTime(obj.getTime());
        } else if (obj instanceof Array) {
             // Handle Array
            copy = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                if (obj[i] == null || typeof obj[i] != "object") copy[i] = obj[i];
                else copy[i] = @com.amindea.noah.client.utils.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]);
            }
        } else {
            // Handle Object
            copy = {};
            for (var attr in obj) {
                if (obj.hasOwnProperty(attr)) {
                    if (obj[attr] == null || typeof obj[attr] != "object") copy[attr] = obj[attr];
                    else copy[attr] = @com.amindea.noah.client.utils.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[attr]);
                }
            }
        }
        return copy;
    }-*/;

}
</code>```

It supports deep copy of Object, Array, Date, String, Number, or Boolean. As explained by A. Levy the function will work as long as the data in the objects and arrays form a tree structure.

Title: GWT Overlay deep copy

Body:
Based on Lineman78's answer and taking into consideration this other answer from A. Levy I created the following function:

public class JsoUtils {

    @SuppressWarnings("unchecked")
    public static <T extends JavaScriptObject> T deepCopy(T obj)
    {
        return (T) deepCopyImpl(obj);
    }

    private static native JavaScriptObject deepCopyImpl(JavaScriptObject obj) /*-{

        if (obj == null) return obj;

        var copy;

        if (obj instanceof Date) {
            // Handle Date
            copy = new Date();
            copy.setTime(obj.getTime());
        } else if (obj instanceof Array) {
             // Handle Array
            copy = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                if (obj[i] == null || typeof obj[i] != "object") copy[i] = obj[i];
                else copy[i] = @com.amindea.noah.client.utils.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]);
            }
        } else {
            // Handle Object
            copy = {};
            for (var attr in obj) {
                if (obj.hasOwnProperty(attr)) {
                    if (obj[attr] == null || typeof obj[attr] != "object") copy[attr] = obj[attr];
                    else copy[attr] = @com.amindea.noah.client.utils.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[attr]);
                }
            }
        }
        return copy;
    }-*/;

}

It supports deep copy of Object, Array, Date, String, Number, or Boolean. As explained by A. Levy the function will work as long as the data in the objects and arrays form a tree structure.


问:
Convert what is typed into UITextField to a counter number like 00:01
I have a UITextField where the Keyboard Type is a number pad. I want to be able to type numbers so they are formatted as a time such as: 00:00

For Example

Typing 1 -> 00:01

Typing 1, 2 -> 00:12

Typing 1, 2, 3 -> 01:23

Typing 1, 2, 3, 4 -> 12:34

12:34 symbolizes 12 minutes and 32 seconds

Also, once you reach the max 4 digits typing more will do nothing.

I would also like to convert whatever was typed, such as 01:23 to an Int of seconds - e.g. 83 in this case - if possible.

答:
You back the textfield with an Int and modify the Int when the user pushes a key.  You then display the formatted Int as the text.  Here is an example playground:</p>

```<code>import PlaygroundSupport

import UIKit

class ViewController: UIViewController {
    var textField =  UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
    var number = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.backgroundColor = .white
        textField.keyboardType = .numberPad
        textField.delegate = self
        view.addSubview(textField)
    }
}

extension ViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch string {
        case "0","1","2","3","4","5","6","7","8","9":
            guard number < Int32.max / 100 else {
                return false
            }
            number *= 10
            number += Int(string)!
        case "":
            number /= 10
        default:
            break
        }

        let formatter = NumberFormatter()
        formatter.decimalSeparator = ":"
        formatter.minimumIntegerDigits = 1
        formatter.minimumFractionDigits = 2
        textField.text = formatter.string(from: NSNumber(value: Double(number) / 100.0))
        return false
    }
}

let v = ViewController()
PlaygroundPage.current.liveView = v.view
</code>```

Body:
You back the textfield with an Int and modify the Int when the user pushes a key.  You then display the formatted Int as the text.  Here is an example playground:

import PlaygroundSupport

import UIKit

class ViewController: UIViewController {
    var textField =  UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
    var number = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.backgroundColor = .white
        textField.keyboardType = .numberPad
        textField.delegate = self
        view.addSubview(textField)
    }
}

extension ViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch string {
        case "0","1","2","3","4","5","6","7","8","9":
            guard number < Int32.max / 100 else {
                return false
            }
            number *= 10
            number += Int(string)!
        case "":
            number /= 10
        default:
            break
        }

        let formatter = NumberFormatter()
        formatter.decimalSeparator = ":"
        formatter.minimumIntegerDigits = 1
        formatter.minimumFractionDigits = 2
        textField.text = formatter.string(from: NSNumber(value: Double(number) / 100.0))
        return false
    }
}

let v = ViewController()
PlaygroundPage.current.liveView = v.view


问:
Docusign integration with IBM FileNet
We are trying to integrate asp.net site front-end having all the its content(pdf's) stored in IBM filenet with docusign or any other tool which can let users to checkout the documents and add digital signatures and check in back.

Any suggestions are highly appreciated.

答:
You have 2 separate issues here,

The content management, which can typically be done using IBM FileNet, Microsoft SharePoint, Or Alfresco CMS.

The other issue is the digital signature, which is validating and verifying the document source through a trust mechanism, which can be implemented using DocuSign, eSign Genie, or Adobe Document Cloud.

First you need to clearly address your solution intent, use cases, and features expected then you can have a direction to go.

Title: Docusign integration with IBM FileNet


问:
Insert the contents of a file as the first lines of a file; In bash (GNU)
The specific task is to use the header of a KML file and insert it into hundreds of split up KML data files that do not have the header.

The KML header is multiple lines and specific spacing. I've found I can use Sed with the 'r' readfile option to grab the contents of a file containing the header. However when I insert the data with '1r' the header is placed in the file starting on the second line. sed doesn't seem to let me address 'line 0' to insert before. Insert mode would work, but I wouldn't be able to just grab the header format that is saved in a file and would need to script the entire header.

```<code>#!/bin/bash
for i in ./Split/*;
        do sed -i '1r KML_Header.txt' $i
done
</code>```

The KML Header Looks like this:

```<code><?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
</code>```

The end result with the header will look something like this:

```<code><?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <when>2017-11-16T11:47:52Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>
</code>```

However, this is what my current best command gets me:

```<code><when>2017-11-16T11:47:52Z</when>
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>
</code>```

答:
You can use cat file1 file2 > newfile to prepend file1 to file2. Do this in a loop.

```<code>for i in Split/*
do
    cat KML_Header.txt "$i" > "$i.new" && mv "$i.new" "$i"
done
</code>```

Body:
The specific task is to use the header of a KML file and insert it into hundreds of split up KML data files that do not have the header.

The KML header is multiple lines and specific spacing. I've found I can use Sed with the 'r' readfile option to grab the contents of a file containing the header. However when I insert the data with '1r' the header is placed in the file starting on the second line. sed doesn't seem to let me address 'line 0' to insert before. Insert mode would work, but I wouldn't be able to just grab the header format that is saved in a file and would need to script the entire header.

#!/bin/bash
for i in ./Split/*;
        do sed -i '1r KML_Header.txt' $i
done

The KML Header Looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>

The end result with the header will look something like this:

<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <when>2017-11-16T11:47:52Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>

However, this is what my current best command gets me:

<when>2017-11-16T11:47:52Z</when>
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                 <altitudeMode>clampToGround</altitudeMode>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:47:44Z</when>
            <gx:coord>-97.8216137 30.481513600000003 259</gx:coord>
            <when>2017-11-16T11:45:37Z</when>
            <gx:coord>-97.8216659 30.481537499999998 261</gx:coord>
            <when>2017-11-16T11:44:54Z</when>
            <gx:coord>-97.82162970000002 30.481479699999998 261</gx:coord>
            <when>2017-11-16T11:39:55Z</when>

Body:
You can use cat file1 file2 > newfile to prepend file1 to file2. Do this in a loop.

for i in Split/*
do
    cat KML_Header.txt "$i" > "$i.new" && mv "$i.new" "$i"
done


问:
update my map with uploaded mbtiles tilesets Mapbox API
I want to update a custom map on Mapbox with my uploaded tilesets by the Mapbox API. The MBtiles were uploaded by using the mapbox-Python-SDK and stored as tilesets.
I need to get these Tilesets to a custom map by a script (The Files are Georeferenced pictures from a Drone, which I want to get displayed automatically on my map). Some kind of Livemapping. It works easy in the Mapbox Studio with the "Add tileset to style" - button, but I need to do it by the API.

I have no clue what's the best way to do it. Any Suggestions ?

答:
You can add the source at runtime with map.addLayer, or map.addSource and then map.addLayer as in this example https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/ (although in your case it sounds like your source would be of type: 'raster').

```<code>map.addSource("drone", {
    "type": "raster",
    "url": "mapbox://username.sourceid"
});

map.addLayer({
    "id": "drone-layer",
    "type": "raster",
    "source": "drone"
});
</code>```

Body:
You can add the source at runtime with map.addLayer, or map.addSource and then map.addLayer as in this example https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/ (although in your case it sounds like your source would be of type: 'raster').

map.addSource("drone", {
    "type": "raster",
    "url": "mapbox://username.sourceid"
});

map.addLayer({
    "id": "drone-layer",
    "type": "raster",
    "source": "drone"
});


问:
How to Disable All Automatics in Android Camera2 API
I'm trying to disable auto-exposure, auto-focus, and auto-white-balance in Google's Camera2Basic sample. Here's my code:

```<code>private void disableAutomatics() {
    try {
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_OFF);
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF);
        mPreviewRequestBuilder.set(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE, CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_OFF);
        mPreviewRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, .2f);
        mPreviewRequestBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, 1000000L);

        mPreviewRequest = mPreviewRequestBuilder.build();
        // Set new repeating request with our changed one
        mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
</code>```

The problem is I don't know where to place the method in Camera2BasicFragment.java.

Any help would be greatly appreciated.

答:
There are two places where you may want to do those settings:

If you want to do it before the preview starts, the better place would be inside of the overridden method onConfigured within the createCameraPreviewSession() void (line 696 in the Camera2BasicFragment file provided in the Google's Camera2Basic sample:

```<code>private void createCameraPreviewSession() {
    try {
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;

        // We configure the size of default buffer to be the size of camera preview we want.
        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

        // This is the output Surface we need to start preview.
        Surface surface = new Surface(texture);

        // We set up a CaptureRequest.Builder with the output Surface.
        mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);

        // Here, we create a CameraCaptureSession for camera preview.
        mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
            new CameraCaptureSession.StateCallback() {

                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    // The camera is already closed
                    if (null == mCameraDevice) {
                        return;
                    }

                    // When the session is ready, we start displaying the preview.
                    mCaptureSession = cameraCaptureSession;
                    try {

                        //Place here your custom camera settings

                        // Start displaying the camera preview.
                        mPreviewRequest = mPreviewRequestBuilder.build();
                        mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                mCaptureCallback, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    showToast("Failed");
                }
            }, null
        );
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
</code>```

If you want to do the settings after the preview has started and in runtime just call your disableAutomatics() from the UI or anywhere else and it should work fine.

Note that you don't have to close the older CaptureSession by calling its CaptureSession.close() method as explained in an answer to this other question because the new replaces the older one.

On another hand, I am not sure about setting the exposure time value manually as you did in your question:

mPreviewRequestBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, 1000000L);

because you may get unexpected results varying on different devices. What I know is that doing so is usually discouraged and it's preferred instead to let the camera adjust by its own and then call AE (auto-exposure) lock:

```<code>mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, true);
</code>```

You can check the CONTROL_AE_LOCK reference here.

But if your code needs a fixed exposure time then it should work.

Body:
I'm trying to disable auto-exposure, auto-focus, and auto-white-balance in Google's Camera2Basic sample. Here's my code:

private void disableAutomatics() {
    try {
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_OFF);
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF);
        mPreviewRequestBuilder.set(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE, CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_OFF);
        mPreviewRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, .2f);
        mPreviewRequestBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, 1000000L);

        mPreviewRequest = mPreviewRequestBuilder.build();
        // Set new repeating request with our changed one
        mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

The problem is I don't know where to place the method in Camera2BasicFragment.java.

Any help would be greatly appreciated.

Body:
There are two places where you may want to do those settings:

If you want to do it before the preview starts, the better place would be inside of the overridden method onConfigured within the createCameraPreviewSession() void (line 696 in the Camera2BasicFragment file provided in the Google's Camera2Basic sample:

private void createCameraPreviewSession() {
    try {
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;

        // We configure the size of default buffer to be the size of camera preview we want.
        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

        // This is the output Surface we need to start preview.
        Surface surface = new Surface(texture);

        // We set up a CaptureRequest.Builder with the output Surface.
        mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);

        // Here, we create a CameraCaptureSession for camera preview.
        mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
            new CameraCaptureSession.StateCallback() {

                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    // The camera is already closed
                    if (null == mCameraDevice) {
                        return;
                    }

                    // When the session is ready, we start displaying the preview.
                    mCaptureSession = cameraCaptureSession;
                    try {

                        //Place here your custom camera settings

                        // Start displaying the camera preview.
                        mPreviewRequest = mPreviewRequestBuilder.build();
                        mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                mCaptureCallback, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    showToast("Failed");
                }
            }, null
        );
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

If you want to do the settings after the preview has started and in runtime just call your disableAutomatics() from the UI or anywhere else and it should work fine.

Note that you don't have to close the older CaptureSession by calling its CaptureSession.close() method as explained in an answer to this other question because the new replaces the older one.

On another hand, I am not sure about setting the exposure time value manually as you did in your question:

mPreviewRequestBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, 1000000L);

because you may get unexpected results varying on different devices. What I know is that doing so is usually discouraged and it's preferred instead to let the camera adjust by its own and then call AE (auto-exposure) lock:

mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, true);

You can check the CONTROL_AE_LOCK reference here.

But if your code needs a fixed exposure time then it should work.

ContentLicense: CC BY-SA 4.0