问:
How to align radio buttons and labels?
I am styling an integration into a 3rd party system, and need to format some radio buttons. The vendor gives us this HTML:

```<code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span>
</code>```

and I need it to render it like so:

I tried, and failed, using flexbox to accomplish this:

span.radiocontainer {
  float: none;
  display: flex;
  align-items: left;
  justify-content: left;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: left;
}

span.radiocontainer > label.selected.radiolabel {
  box-shadow: none;
  width: 50%;
  border: 0px;
}

span.radiocontainer > input {
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span></code>```

Is there any way for me to format the radio buttons on the left? Or do I need to change my design?

I cannot change the HTML, as it is from a vendor, CSS is the only thing we get to customize.

答:
CSS Grid

The most appropriate approach here is CSS Grid Layout. Approach below uses modern syntax but doesn't have IE/Edge support.

.radiocontainer {
  display: inline-grid;
  /* tells the auto-placement algorithm to attempt to fill in holes earlier in the grid if smaller items come up later */
  grid-auto-flow: dense;
  align-items: center;
}

.radiocontainer label {
  grid-column: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span></code>```

If you also need IE and Edge support you'll have to use old syntax. There is no auto-placement behaviour in IE/Edge implementation so you'll have to specify alignment of every item (except first) manually. If you don’t position items they will stack up in the first cell of the grid in IE/Edge. This works in IE10+:

.radiocontainer {
  display: -ms-inline-grid;
  display: inline-grid;
  align-items: center;
}

.radiocontainer label {
  display: block;
}

input:nth-of-type(2) {
  -ms-grid-row: 2;
  grid-row: 2;
}

label:nth-of-type(1) {
  -ms-grid-row: 1;
  grid-row: 1;
  -ms-grid-column: 2;
  grid-column: 2;
}

label:nth-of-type(2) {
  -ms-grid-row: 2;
  grid-row: 2;
  -ms-grid-column: 2;
  grid-column: 2;
}

input:nth-of-type(3) {
  -ms-grid-row: 3;
  grid-row: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
    <input class="selector" id="asdf" name="Gender" type="radio" value="1">
</span></code>```

Flexbox

I would improve @NenadVracar answer:

We can remove need for setting order for every item. We can just set flex-direction: row-reverse for container.

Setting percentage (50%) for both input and label is bad idea. Increasing/decreasing label length will distort our radio button list's look. We need to set fixed width for radio button.

.radiocontainer {
  display: inline-flex;
  flex-direction: row-reverse;
  flex-wrap: wrap;
  align-items: center;
}

.radiocontainer input,
.radiocontainer label {
  margin: 0;
}

.radiocontainer input {
  width: 20px;
}

.radiocontainer label {
  width: calc(100% - 20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span></code>```

CSS Floats

This way will work even in IE9 but centering radio buttons is not working.

If you see @TejasviKarne you'll notice that .radiocontainer's width doesn't takes label's width into account. If you care about it you can do it this way:

.radiocontainer {
  display: inline-block; /* Take width of content */
}

.radiocontainer input,
.radiocontainer label {
  margin: 0;
}

.radiocontainer label {
  width: calc(100% - 15px);
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span></code>```

Title: How to align radio buttons and labels?

Body:
I am styling an integration into a 3rd party system, and need to format some radio buttons. The vendor gives us this HTML:

    Male
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    Female
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">

and I need it to render it like so:

I tried, and failed, using flexbox to accomplish this:

span.radiocontainer {
  float: none;
  display: flex;
  align-items: left;
  justify-content: left;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: left;
}

span.radiocontainer > label.selected.radiolabel {
  box-shadow: none;
  width: 50%;
  border: 0px;
}

span.radiocontainer > input {
  width: 50%;
}

    Male
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    Female
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">

Is there any way for me to format the radio buttons on the left? Or do I need to change my design?

I cannot change the HTML, as it is from a vendor, CSS is the only thing we get to customize.

Body:
CSS Grid

The most appropriate approach here is CSS Grid Layout. Approach below uses modern syntax but doesn't have IE/Edge support.

.radiocontainer {
  display: inline-grid;
  /* tells the auto-placement algorithm to attempt to fill in holes earlier in the grid if smaller items come up later */
  grid-auto-flow: dense;
  align-items: center;
}

.radiocontainer label {
  grid-column: 2;
}

<span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span>

If you also need IE and Edge support you'll have to use old syntax. There is no auto-placement behaviour in IE/Edge implementation so you'll have to specify alignment of every item (except first) manually. If you don’t position items they will stack up in the first cell of the grid in IE/Edge. This works in IE10+:

.radiocontainer {
  display: -ms-inline-grid;
  display: inline-grid;
  align-items: center;
}

.radiocontainer label {
  display: block;
}

input:nth-of-type(2) {
  -ms-grid-row: 2;
  grid-row: 2;
}

label:nth-of-type(1) {
  -ms-grid-row: 1;
  grid-row: 1;
  -ms-grid-column: 2;
  grid-column: 2;
}

label:nth-of-type(2) {
  -ms-grid-row: 2;
  grid-row: 2;
  -ms-grid-column: 2;
  grid-column: 2;
}

input:nth-of-type(3) {
  -ms-grid-row: 3;
  grid-row: 3;
}

<span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
    <input class="selector" id="asdf" name="Gender" type="radio" value="1">
</span>

Flexbox

I would improve @NenadVracar answer:

We can remove need for setting order for every item. We can just set flex-direction: row-reverse for container.

Setting percentage (50%) for both input and label is bad idea. Increasing/decreasing label length will distort our radio button list's look. We need to set fixed width for radio button.

.radiocontainer {
  display: inline-flex;
  flex-direction: row-reverse;
  flex-wrap: wrap;
  align-items: center;
}

.radiocontainer input,
.radiocontainer label {
  margin: 0;
}

.radiocontainer input {
  width: 20px;
}

.radiocontainer label {
  width: calc(100% - 20px);
}

<span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span>

CSS Floats

This way will work even in IE9 but centering radio buttons is not working.

If you see @TejasviKarne you'll notice that .radiocontainer's width doesn't takes label's width into account. If you care about it you can do it this way:

.radiocontainer {
  display: inline-block; /* Take width of content */
}

.radiocontainer input,
.radiocontainer label {
  margin: 0;
}

.radiocontainer label {
  width: calc(100% - 15px);
  float: right;
}

<span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span>


来源: stackexchange

问:
Lambda function returns null from nested async function
The Lambda function is not hitting the memory limit neither timing out. I read somewhere that it may return because the event loop is empty but I have context.callbackWaitsForEmptyEventLoop set to false.

Here is the function:

```<code>module.exports.callMenu = (event, context, callback) => {

  context.callbackWaitsForEmptyEventLoop = false;
  const eventJSON = qs.parse(event.body);
  myMongooseObject.findOne({ value: eventJSON.value }, (err, theObject) => {
    if (!err) {

      newObj = new myMongooseObject();
      newObj.message = 'this worked';

      newObj.save((err) => {
        if (!err) {
          callback(null, { body: 'success' });
        } else {
          console.log(err);
        }
      });
    }
};
</code>```

答:
In your code, you are not adding callbacks for when there is an error in the request. And you may want to add a try/catch to handle any other issues with your code.

Also, you don't need to set callbackWaitsForEmptyEventLoop because you are not adding extra events besides your main request.

Try this:

```<code>const myMongooseObject = defineThisObject(); // maybe you forgot to define it
const qs = defineThisObjectToo(); // maybe another error

module.exports.callMenu = (event, context, callback) => {

    try {
        const eventJSON = qs.parse(event.body);
        myMongooseObject.findOne({ value: eventJSON.value }, (err, theObject) => {

            if (!err) {
                newObj = new myMongooseObject();
                newObj.message = 'this worked';

                // define the newCall object too?

                newCall.save((err) => {
                    if (!err) {
                        callback(null, { body: 'success' });
                    } else {
                        callback(err); // add this
                    }
                });
            } else {
                callback(err); // add this
            }
        });
    } catch (e) {
      callback(e);
    }
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The Lambda function is not hitting the memory limit neither timing out. I read somewhere that it may return because the event loop is empty but I have context.callbackWaitsForEmptyEventLoop set to false.

Here is the function:

module.exports.callMenu = (event, context, callback) => {

  context.callbackWaitsForEmptyEventLoop = false;
  const eventJSON = qs.parse(event.body);
  myMongooseObject.findOne({ value: eventJSON.value }, (err, theObject) => {
    if (!err) {

      newObj = new myMongooseObject();
      newObj.message = 'this worked';

      newObj.save((err) => {
        if (!err) {
          callback(null, { body: 'success' });
        } else {
          console.log(err);
        }
      });
    }
};

Body:
In your code, you are not adding callbacks for when there is an error in the request. And you may want to add a try/catch to handle any other issues with your code.

Also, you don't need to set callbackWaitsForEmptyEventLoop because you are not adding extra events besides your main request.

Try this:

const myMongooseObject = defineThisObject(); // maybe you forgot to define it
const qs = defineThisObjectToo(); // maybe another error

module.exports.callMenu = (event, context, callback) => {

    try {
        const eventJSON = qs.parse(event.body);
        myMongooseObject.findOne({ value: eventJSON.value }, (err, theObject) => {

            if (!err) {
                newObj = new myMongooseObject();
                newObj.message = 'this worked';

                // define the newCall object too?

                newCall.save((err) => {
                    if (!err) {
                        callback(null, { body: 'success' });
                    } else {
                        callback(err); // add this
                    }
                });
            } else {
                callback(err); // add this
            }
        });
    } catch (e) {
      callback(e);
    }
};


问:
Powershell - comparing lines
I need to parse through a file and when lines with the same connection-ID (655629, in this example) are found, compare them and only keep the one that is not 'other'

These two lines, for example:

```<code>08/26-20:26:42.655629  [**] [1:9000003:0] troll [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368
08/26-20:26:42.655629  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368
</code>```

Someone here was already kind enough to share this code, that basically returns the parts of each line that I need, formatted the way that I need.

```<code>Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[0, 9, 11, 4] -replace ':', '|') -join '|') + '|'
} | Out-File "C:\Log\logout.txt"

|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|troll|
|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|other|
</code>```

However, I only want to keep one line when there are multiple lines with the same connection ID (655629 in this example). In cases when there are multiple lines with the same connection ID, I need the line that is NOT 'other'

I'm showing that first indice [0] only for comparison-sake. I need to remove it from the final output for all lines.

For example, final output should look something like this:

```<code>|192.168.0.1|35964|192.168.0.99|368|troll|
|192.168.0.254|35964|192.168.0.99|368|troll|
|192.168.0.9|35964|192.168.0.99|368|other|
|192.168.0.199|35964|192.168.0.99|368|troll|
|192.168.0.199|35964|192.168.0.99|368|other|
</code>```

Any help is much appreciated!

答:
I would strongly recommend parsing your input with a regular expression and creating custom objects from the submatches rather than just splitting the lines like you're doing now.

```<code>$re = '^(.*?)\.(\d+)  \S+ \S+ (\S+) \S+ \S+ \S+ (.*?):(\d+) -> (.*?):(\d+)'

Get-Content $logFile -ReadCount 1 | Where-Object {
    $_ -match $re
} | ForEach-Object {
    New-Object -Type PSObject -Property @{
        Timestamp    = $matches[1]  #?
        ConnectionID = $matches[2]
        ...
        Source       = $matches[4]
        Destination  = $matches[6]
    }
}
</code>```

That will allow you to actually filter the data by field values:

```<code>... | Sort-Object ConnectionID -Unique | ...
</code>```

The data can be exported in delimited format via Export-Csv:

```<code>... | Export-Csv 'C:\path\to\output.txt' -NoType -Delimiter '|'
</code>```

Title: Powershell - comparing lines

Body:
I need to parse through a file and when lines with the same connection-ID (655629, in this example) are found, compare them and only keep the one that is not 'other'

These two lines, for example:

08/26-20:26:42.655629  [**] [1:9000003:0] troll [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368
08/26-20:26:42.655629  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368

Someone here was already kind enough to share this code, that basically returns the parts of each line that I need, formatted the way that I need.

Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[0, 9, 11, 4] -replace ':', '|') -join '|') + '|'
} | Out-File "C:\Log\logout.txt"

|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|troll|
|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|other|

However, I only want to keep one line when there are multiple lines with the same connection ID (655629 in this example). In cases when there are multiple lines with the same connection ID, I need the line that is NOT 'other'

I'm showing that first indice [0] only for comparison-sake. I need to remove it from the final output for all lines.

For example, final output should look something like this:

|192.168.0.1|35964|192.168.0.99|368|troll|
|192.168.0.254|35964|192.168.0.99|368|troll|
|192.168.0.9|35964|192.168.0.99|368|other|
|192.168.0.199|35964|192.168.0.99|368|troll|
|192.168.0.199|35964|192.168.0.99|368|other|

Any help is much appreciated!

Body:
I would strongly recommend parsing your input with a regular expression and creating custom objects from the submatches rather than just splitting the lines like you're doing now.

$re = '^(.*?)\.(\d+)  \S+ \S+ (\S+) \S+ \S+ \S+ (.*?):(\d+) -> (.*?):(\d+)'

Get-Content $logFile -ReadCount 1 | Where-Object {
    $_ -match $re
} | ForEach-Object {
    New-Object -Type PSObject -Property @{
        Timestamp    = $matches[1]  #?
        ConnectionID = $matches[2]
        ...
        Source       = $matches[4]
        Destination  = $matches[6]
    }
}

That will allow you to actually filter the data by field values:

... | Sort-Object ConnectionID -Unique | ...

The data can be exported in delimited format via Export-Csv:

... | Export-Csv 'C:\path\to\output.txt' -NoType -Delimiter '|'


问:
File Browser Window on Android>=6 with PhoneGap/Cordova
I'm having trouble opening a file browser window on Android6+. I'm using latest Cordova/PhoneGap with Visual Studio 2017. When I click the desired button, nothing happens. When I deploy my source code on a webserver and access this site on my tablet, everything works fine. A live example can be seen at:
http://gipong.github.io/shp2geojson.js/. "Upload zip file" won't open a file browser.

```<code><div class="ui teal fluid labeled icon button upload" id="zipfile" data-content="Mandatory files : SHP , DBF" data-variation="inverted large">
                    Upload zip file
                    <i class="file archive outline icon"></i>
                    <input type="file" id="file" accept=".zip">
            </div>
</code>```

My code (from https://github.com/gipong/shp2geojson.js)

```<code> function loadShpZip() {
            var epsg = ($('#epsg').val() == '') ? 4326 : $('#epsg').val(),
                encoding = ($('#encoding').val() == '') ? 'UTF-8' : $('#encoding').val();
            if (file.name.split('.')[1] == 'zip') {
                if (file) $('.dimmer').addClass('active');
                loadshp({
                    url: file,
                    encoding: encoding,
                    EPSG: epsg
                }, function (data) {
                    var URL = window.URL || window.webkitURL || window.mozURL || window.msURL,
                        url = URL.createObjectURL(new Blob([JSON.stringify(data)], { type: "application/json" }));

                    $('#link').attr('href', url);
                    $('#link').html(file.name + '.geojson' + '<i class="download icon"></i>').attr('download', file.name + '.geojson');

                    $('#downloadLink').slideDown(400);

                    $('.shp-modal').toggleClass('effect');
                    $('.overlay').toggleClass('effect');
                    $('#wrap').toggleClass('blur');

                    vector.addData(data);
                    map.fitBounds([
                        [data.bbox[1], data.bbox[0]], [data.bbox[3], data.bbox[2]]
                    ]);
                    $('.dimmer').removeClass('active');
                    $('#preview').addClass('disabled');
                    $('#epsg').val('');
                    $('#encoding').val('');
                    $('#info').addClass('picInfo');
                    $('#option').slideUp(500);

                    newData = data;

                    for (var i = 0; i < newData.features.length; i++) {
                        var c1 = newData.features[i].geometry.coordinates;

                        for (var u = 0; u < c1.length; u++) {
                            var c2 = c1[u];

                            for (var o = 0; o < c2.length; o++) {
                                var oldCoordinate = c2[o];
                                var newCoordinate = [oldCoordinate[1], oldCoordinate[0]];
                                c2[o] = newCoordinate;
                            }
                        }
                    }

                    globaljson = $.parseJSON(JSON.stringify(data));

                });
            } else {
                $('.modal').modal('show');
            }
        }
        initVector();

        $("#file").change(function (evt) {
            file = evt.target.files[0];
            if (file.size > 0) {
                $('#dataInfo').text(' ').append(file.name + ' , ' + file.size + ' kb');
                $('#option').slideDown(500);
                $('#preview').removeClass('disabled');
            }
        });

        $('#preview').click(function () {
            loadShpZip();
        });

        $('.button').popup({
            //inline: true,
            position: 'bottom left'
        });
        $('.tips').popup({
            target: '#addZipfile',
            position: 'top center'
            //variation: 'huge'
        });
        $('#entireLayer').click(function () {
            map.fitBounds(vector.getBounds());
            chrome.storage.local.set({ 'key': 'value' });
            chrome.storage.local.get('key', function (obj) {
                alert(obj.key);
            });

        });
        $('#addZipfile').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#cancel').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#removeLayer').click(function () {
            $('#attr').fadeOut(300);
            window.location.reload();
        });
        $('#encoding').dropdown();
        $('.v').change(function () {
            var msg = '<div class="msg" id="msg" style="display: none;"><div class="ui primary inverted red segment">' +
                '<p>You can find the EPSG Code of your Shapefile on <strong>spatialreference.org</strong></p></div><br /></div>';
            if ($('#epsg').val().match(/^\d{4}$/) != null) {
                $('#zipfile').removeClass('disabled');
                $('.msg').slideUp(750);
            } else {
                if ($('.msg')[0] == undefined) {
                    $('#epsgField').after(msg);
                    $('.msg').slideDown(1500);
                }
            }
        });

        $("#attr").draggable({ containment: $(this).parent().parent(), scroll: false, cursor: "move" });
        $('#cancelAttr').click(function () { $('#attr').hide()
});
</code>```

I've set my permissions in config.xml like this:

```<code>     <platform name="android">
       <config-file target="AndroidManifest.xml" parent="/*">
         android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
         android:name="android.permission.READ_EXTERNAL_STORAGE" />
       </config-file>
     </platform>
</code>```

When I check my app for requested permissions, none show up tho.

This Problem does not exist on a tablet with Android 4.4.

edit: a few logs, which I don't really understand.

```<code>07-04 12:10:20.471 18340 18340 W CordovaInterfaceImpl: Got an activity result, but no plugin was registered to receive it.
07-04 12:10:20.471 18340 18340 D WebView : resumeTimers
07-04 12:10:20.471 18340 18340 D WebView : setNetworkAvailable=true
07-04 12:10:20.472 18340 18340 D ActivityThread: SEND_RESULT handled : 0 / ResultData{token=android.os.BinderProxy@7c8f400 results[ResultInfo{who=null, request=5173, result=0, data=null}]}
07-04 12:10:20.482   202  2362 I BufferQueueProducer: [io.cordova.myappac1b3c/io.cordova.myappac1b3c.MainActivity](this:0x7f9222e400,id:306,api:1,p:18340,c:202) queueBuffer: fps=6.96 dur=1149.87 max=176.61 min=134.62
07-04 12:10:20.530   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182195, ID:0, Index:1969346496
07-04 12:10:20.530   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.611   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182277, ID:0, Index:1969349888
07-04 12:10:20.611   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.696   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182362, ID:0, Index:1969346496
07-04 12:10:20.696   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.766   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182431, ID:0, Index:1969349888
07-04 12:10:20.766   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.838   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182504, ID:0, Index:1969346496
07-04 12:10:20.838   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.886   783  1017 D PowerManagerService: userActivityFromNative
07-04 12:10:20.887   783  1017 D PowerManagerService: userActivityNoUpdateLocked: eventTime=71182552, event=2, flags=0x0, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerNotifier: onUserActivity: event=2, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerService: updateUserActivitySummaryLocked: mWakefulness=Awake, mUserActivitySummary=0x1, nextTimeout=72975552 (in 1792999 ms)
07-04 12:10:20.887   783  1017 D DisplayPowerController: requestPowerState: policy=BRIGHT, useProximitySensor=false, screenBrightness=102, screenAutoBrightnessAdjustment=1.0, brightnessSetByUser=true, useAutoBrightness=true, blockScreenOn=false, lowPowerMode=false, boostScreenBrightness=false, dozeScreenBrightness=-1, dozeScreenState=UNKNOWN, waitForNegativeProximity=false
07-04 12:10:20.887   783  1017 I PowerManagerService: setBrightness mButtonLight 0.
07-04 12:10:20.887   783  1017 D PowerManagerService: updateDisplayPowerStateLocked: mDisplayReady=true, policy=3, mWakefulness=1, mWakeLockSummary=0x23, mUserActivitySummary=0x1, mBootCompleted=true, mScreenBrightnessBoostInProgress=false
07-04 12:10:20.908   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182574, ID:0, Index:1969349888
07-04 12:10:20.908   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.957   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182623, ID:0, Index:1969346496
07-04 12:10:20.957   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:21.039   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182705, ID:0, Index:1969349888
07-04 12:10:21.039   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:21.080   783  2792 I ActivityManager: START u0 {act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip} from uid 10111 from pid 18340 on display 0
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip }
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1809)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3968)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaActivity.startActivityForResult(CordovaActivity.java:332)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3920)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaInterfaceImpl.startActivityForResult(CordovaInterfaceImpl.java:67)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.engine.SystemWebChromeClient.onShowFileChooser(SystemWebChromeClient.java:268)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.webview.chromium.WebViewContentsClientAdapter.showFileChooser(WebViewContentsClientAdapter.java:481)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.android_webview.AwWebContentsDelegateAdapter.runFileChooser(AwWebContentsDelegateAdapter.java:70)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:7)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Handler.dispatchMessage(Handler.java:111)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Looper.loop(Looper.java:207)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.ActivityThread.main(ActivityThread.java:5728)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at java.lang.reflect.Method.invoke(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
07-04 12:10:21.083 18340 18340 D WebView : setNetworkAvailable=false
</code>```

答:
I have been experiencing the very same issue (on visual studio 2015 and 2017)... it turns out something may be wrong with the plugin at this time.

I came up with a simple yet clever solution that allows me to select files from the device gallery without the use of any cordova plugins.

The answer is to create a separate .html page with the usual

```<code><input type="file" name="File2Upload" id="File2Upload">
**...and other form elements**
</code>```

Then introduce that newly created external .html page (with the contents of your form) to your main app via iFrame. Clicking on the input button will instantly open up the device photo gallery or recent photos... but you are not limited to just the photo gallery.. you can then navigate to any directory you wish.

The downside to this method of course is the ugly looking choose file input button that refuses to accept css styling; if you want full control over the look and feel of your file chooser button you will need to write some extra html and css like;

Add a new div below the file picker input tag... then place a new input tag in
  that newly created div... make sure the div at the top is directly above the div below... then hide the ugly original div at the top, now.. once the input tag at the bottom is of type "button" you will be able to style it as you please.

Finally you will need to add an on-change-event to the original div at the top(opacity 0)... so that it updates the styled/visible file chooser input at the bottom. Remember, the real input chooser is at the top but it is not visible because we are unable to style it... so the visible input will need to be updated to show the selected file.

...of course, if you don't mind the look of the original file chooser button then you would have a lot less work to do.

Good luck!

Body:
I'm having trouble opening a file browser window on Android6+. I'm using latest Cordova/PhoneGap with Visual Studio 2017. When I click the desired button, nothing happens. When I deploy my source code on a webserver and access this site on my tablet, everything works fine. A live example can be seen at:
http://gipong.github.io/shp2geojson.js/. "Upload zip file" won't open a file browser.

                    Upload zip file

                    <input type="file" id="file" accept=".zip">

My code (from https://github.com/gipong/shp2geojson.js)

 function loadShpZip() {
            var epsg = ($('#epsg').val() == '') ? 4326 : $('#epsg').val(),
                encoding = ($('#encoding').val() == '') ? 'UTF-8' : $('#encoding').val();
            if (file.name.split('.')[1] == 'zip') {
                if (file) $('.dimmer').addClass('active');
                loadshp({
                    url: file,
                    encoding: encoding,
                    EPSG: epsg
                }, function (data) {
                    var URL = window.URL || window.webkitURL || window.mozURL || window.msURL,
                        url = URL.createObjectURL(new Blob([JSON.stringify(data)], { type: "application/json" }));

                    $('#link').attr('href', url);
                    $('#link').html(file.name + '.geojson' + '').attr('download', file.name + '.geojson');

                    $('#downloadLink').slideDown(400);

                    $('.shp-modal').toggleClass('effect');
                    $('.overlay').toggleClass('effect');
                    $('#wrap').toggleClass('blur');

                    vector.addData(data);
                    map.fitBounds([
                        [data.bbox[1], data.bbox[0]], [data.bbox[3], data.bbox[2]]
                    ]);
                    $('.dimmer').removeClass('active');
                    $('#preview').addClass('disabled');
                    $('#epsg').val('');
                    $('#encoding').val('');
                    $('#info').addClass('picInfo');
                    $('#option').slideUp(500);

                    newData = data;

                    for (var i = 0; i < newData.features.length; i++) {
                        var c1 = newData.features[i].geometry.coordinates;

                        for (var u = 0; u < c1.length; u++) {
                            var c2 = c1[u];

                            for (var o = 0; o < c2.length; o++) {
                                var oldCoordinate = c2[o];
                                var newCoordinate = [oldCoordinate[1], oldCoordinate[0]];
                                c2[o] = newCoordinate;
                            }
                        }
                    }

                    globaljson = $.parseJSON(JSON.stringify(data));

                });
            } else {
                $('.modal').modal('show');
            }
        }
        initVector();

        $("#file").change(function (evt) {
            file = evt.target.files[0];
            if (file.size > 0) {
                $('#dataInfo').text(' ').append(file.name + ' , ' + file.size + ' kb');
                $('#option').slideDown(500);
                $('#preview').removeClass('disabled');
            }
        });

        $('#preview').click(function () {
            loadShpZip();
        });

        $('.button').popup({
            //inline: true,
            position: 'bottom left'
        });
        $('.tips').popup({
            target: '#addZipfile',
            position: 'top center'
            //variation: 'huge'
        });
        $('#entireLayer').click(function () {
            map.fitBounds(vector.getBounds());
            chrome.storage.local.set({ 'key': 'value' });
            chrome.storage.local.get('key', function (obj) {
                alert(obj.key);
            });

        });
        $('#addZipfile').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#cancel').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#removeLayer').click(function () {
            $('#attr').fadeOut(300);
            window.location.reload();
        });
        $('#encoding').dropdown();
        $('.v').change(function () {
            var msg = '

' +
                '
You can find the EPSG Code of your Shapefile on spatialreference.org

';
            if ($('#epsg').val().match(/^\d{4}$/) != null) {
                $('#zipfile').removeClass('disabled');
                $('.msg').slideUp(750);
            } else {
                if ($('.msg')[0] == undefined) {
                    $('#epsgField').after(msg);
                    $('.msg').slideDown(1500);
                }
            }
        });

        $("#attr").draggable({ containment: $(this).parent().parent(), scroll: false, cursor: "move" });
        $('#cancelAttr').click(function () { $('#attr').hide()
});

I've set my permissions in config.xml like this:

     <platform name="android">
       <config-file target="AndroidManifest.xml" parent="/*">
         android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
         android:name="android.permission.READ_EXTERNAL_STORAGE" />
       </config-file>
     </platform>

When I check my app for requested permissions, none show up tho.

This Problem does not exist on a tablet with Android 4.4.

edit: a few logs, which I don't really understand.

07-04 12:10:20.471 18340 18340 W CordovaInterfaceImpl: Got an activity result, but no plugin was registered to receive it.
07-04 12:10:20.471 18340 18340 D WebView : resumeTimers
07-04 12:10:20.471 18340 18340 D WebView : setNetworkAvailable=true
07-04 12:10:20.472 18340 18340 D ActivityThread: SEND_RESULT handled : 0 / ResultData{token=android.os.BinderProxy@7c8f400 results[ResultInfo{who=null, request=5173, result=0, data=null}]}
07-04 12:10:20.482   202  2362 I BufferQueueProducer: [io.cordova.myappac1b3c/io.cordova.myappac1b3c.MainActivity](this:0x7f9222e400,id:306,api:1,p:18340,c:202) queueBuffer: fps=6.96 dur=1149.87 max=176.61 min=134.62
07-04 12:10:20.530   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182195, ID:0, Index:1969346496
07-04 12:10:20.530   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.611   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182277, ID:0, Index:1969349888
07-04 12:10:20.611   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.696   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182362, ID:0, Index:1969346496
07-04 12:10:20.696   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.766   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182431, ID:0, Index:1969349888
07-04 12:10:20.766   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.838   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182504, ID:0, Index:1969346496
07-04 12:10:20.838   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.886   783  1017 D PowerManagerService: userActivityFromNative
07-04 12:10:20.887   783  1017 D PowerManagerService: userActivityNoUpdateLocked: eventTime=71182552, event=2, flags=0x0, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerNotifier: onUserActivity: event=2, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerService: updateUserActivitySummaryLocked: mWakefulness=Awake, mUserActivitySummary=0x1, nextTimeout=72975552 (in 1792999 ms)
07-04 12:10:20.887   783  1017 D DisplayPowerController: requestPowerState: policy=BRIGHT, useProximitySensor=false, screenBrightness=102, screenAutoBrightnessAdjustment=1.0, brightnessSetByUser=true, useAutoBrightness=true, blockScreenOn=false, lowPowerMode=false, boostScreenBrightness=false, dozeScreenBrightness=-1, dozeScreenState=UNKNOWN, waitForNegativeProximity=false
07-04 12:10:20.887   783  1017 I PowerManagerService: setBrightness mButtonLight 0.
07-04 12:10:20.887   783  1017 D PowerManagerService: updateDisplayPowerStateLocked: mDisplayReady=true, policy=3, mWakefulness=1, mWakeLockSummary=0x23, mUserActivitySummary=0x1, mBootCompleted=true, mScreenBrightnessBoostInProgress=false
07-04 12:10:20.908   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182574, ID:0, Index:1969349888
07-04 12:10:20.908   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.957   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182623, ID:0, Index:1969346496
07-04 12:10:20.957   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:21.039   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182705, ID:0, Index:1969349888
07-04 12:10:21.039   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:21.080   783  2792 I ActivityManager: START u0 {act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip} from uid 10111 from pid 18340 on display 0
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip }
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1809)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3968)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaActivity.startActivityForResult(CordovaActivity.java:332)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3920)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaInterfaceImpl.startActivityForResult(CordovaInterfaceImpl.java:67)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.engine.SystemWebChromeClient.onShowFileChooser(SystemWebChromeClient.java:268)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.webview.chromium.WebViewContentsClientAdapter.showFileChooser(WebViewContentsClientAdapter.java:481)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.android_webview.AwWebContentsDelegateAdapter.runFileChooser(AwWebContentsDelegateAdapter.java:70)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:7)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Handler.dispatchMessage(Handler.java:111)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Looper.loop(Looper.java:207)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.ActivityThread.main(ActivityThread.java:5728)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at java.lang.reflect.Method.invoke(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
07-04 12:10:21.083 18340 18340 D WebView : setNetworkAvailable=false

Body:
I have been experiencing the very same issue (on visual studio 2015 and 2017)... it turns out something may be wrong with the plugin at this time.

I came up with a simple yet clever solution that allows me to select files from the device gallery without the use of any cordova plugins.

The answer is to create a separate .html page with the usual

<input type="file" name="File2Upload" id="File2Upload">
**...and other form elements**

Then introduce that newly created external .html page (with the contents of your form) to your main app via iFrame. Clicking on the input button will instantly open up the device photo gallery or recent photos... but you are not limited to just the photo gallery.. you can then navigate to any directory you wish.

The downside to this method of course is the ugly looking choose file input button that refuses to accept css styling; if you want full control over the look and feel of your file chooser button you will need to write some extra html and css like;

Add a new div below the file picker input tag... then place a new input tag in
  that newly created div... make sure the div at the top is directly above the div below... then hide the ugly original div at the top, now.. once the input tag at the bottom is of type "button" you will be able to style it as you please.

Finally you will need to add an on-change-event to the original div at the top(opacity 0)... so that it updates the styled/visible file chooser input at the bottom. Remember, the real input chooser is at the top but it is not visible because we are unable to style it... so the visible input will need to be updated to show the selected file.

...of course, if you don't mind the look of the original file chooser button then you would have a lot less work to do.

Good luck!


问:
Does !fork() create a process?
For instance if I call

```<code>if (!fork())
</code>```

does this create a new process like calling

```<code>if (fork())
</code>```

or does it not?

答:
It is the same, fork is evaluated before check is made.

if (!fork()) is the same as if (fork()) for function itself but not the same for if statement check.

Title: Does !fork() create a process?

Body:
For instance if I call

if (!fork())

does this create a new process like calling

if (fork())

or does it not?


问:
Mysql ENABLE KEYS commands takes a long time
I have a MyISAM database table. I'm inserting about 360000 records there, using DISABLE KEYS before and DISABLE KEYS command after data is being inserted. After inserting data to the table ENABLE KEYS commands proceeds, but it takes more than 17 hours on high performance server (currently it is running, and it is 17 hours..). Where the problem can be?

Table has a lot of Indexes, and it was working fine some weeks ago. Is it problem with MySQL server configuration?

答:
What does your SHOW PROCESSLIST say with respect to the state of your ALTER TABLE table ENABLE KEYS?

Have you changed your MySQL configuration to handle index generation on large tables?

You may have went over a data size threshold in which MySQL changes it's methods to MyISAM index building.

A good blog post to understand/fix/alleviate what's going on:

http://venublog.com/2010/01/04/performance-comparison-of-repair-by-sorting-or-by-keycache/

ContentLicense: CC BY-SA 2.5


问:
MDX Descendants of filtered Descendants
I am new to MDX and Cubes.

I need to slice my data with descendants of the descendants of a given member having a particular attribute.

DIM1 is a dimension with Parent being its parent child hierarchy and it has an attribute Attr1.

Given the following parent tree. Members 601, 711, 712, and 811 must be used to slice. It is ok if any of their parents are returned, measure data only exists at the leaf level.

```
  Id | Parent | Attr1
   1 |        |   1
   2 |     1  |   3
 501 |     2  |   5
 601 |    501 |  11
 701 |    501 |  11
 711 |    701 |  15
 712 |    701 |  16
 810 |    501 |   7
 811 |    810 |  11
```

I am receiving the error "The DESCENDANTS function expects a member or set of a single hierarchy for the 1 argument. A set of multiple hierarchies was passed."
when trying

```<code>WHERE
  DESCENDANTS (
     { { DESCENDANTS ( [DIM1].[PARENT].&[501].CHILDREN ) } * { [DIM1].[Attr1].&[11] } }
)
</code>```

答:
Currently you have a cross-join inside the outer DESCENDANTS function - so this will create a set of multiple hierarchy tuples - hence the exception. If you move the cross-join outside does it still error?

```<code>WHERE
  DESCENDANTS (
     DESCENDANTS (
       [DIM1].[PARENT].&[501].CHILDREN
     )
  ) * { [DIM1].[Attr1].&[11] }
</code>```

Title: MDX Descendants of filtered Descendants

Body:
I am new to MDX and Cubes.

I need to slice my data with descendants of the descendants of a given member having a particular attribute.

DIM1 is a dimension with Parent being its parent child hierarchy and it has an attribute Attr1.

Given the following parent tree. Members 601, 711, 712, and 811 must be used to slice. It is ok if any of their parents are returned, measure data only exists at the leaf level.

  Id | Parent | Attr1
   1 |        |   1
   2 |     1  |   3
 501 |     2  |   5
 601 |    501 |  11
 701 |    501 |  11
 711 |    701 |  15
 712 |    701 |  16
 810 |    501 |   7
 811 |    810 |  11

I am receiving the error "The DESCENDANTS function expects a member or set of a single hierarchy for the 1 argument. A set of multiple hierarchies was passed."
when trying

WHERE
  DESCENDANTS (
     { { DESCENDANTS ( [DIM1].[PARENT].&[501].CHILDREN ) } * { [DIM1].[Attr1].&[11] } }
)

Body:
Currently you have a cross-join inside the outer DESCENDANTS function - so this will create a set of multiple hierarchy tuples - hence the exception. If you move the cross-join outside does it still error?

WHERE
  DESCENDANTS (
     DESCENDANTS (
       [DIM1].[PARENT].&[501].CHILDREN
     )
  ) * { [DIM1].[Attr1].&[11] }


问:
Configure query/command timeout with sqlalchemy create_engine?
The following Python code snippet illustrates the issue:</p>

```<code>print("starting")

# I am trying to configure a query/command timeout of one second.
# sqlalchemy docs suggest execution_options but the documented list of options doesn't include a timeout:
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execution_options
# Below, I am guessing at several likely timeout parameter names:
db_engine = create_engine("postgresql://user:pass@server/catalog",
                          execution_options={"timeout": 1.0,
                                             "statement_timeout": 1.0,
                                             "query_timeout": 1.0,
                                             "execution_timeout": 1.0})

with db_engine.connect() as db_connection:
    print("got db_connection")

    # Artificially force a two second query time with pg_sleep.
    # This is designed to guarantee timeout conditions and trigger an exception.
    result_proxy = db_connection.execute("SELECT pg_sleep(2);")

    # If the timeout worked, this statement will not execute.
    # Currently, it does execute, which means my timeout isn't working.
    print("Query successfully complete. Got result_proxy")
</code>```

答:
You can set configuration values like statement_timeout via the options parameter in libpq. You can access this parameter in psycopg2 as part of the connect call. You can pass additional parameters to the connect call from SQLAlchemy via the connect_args parameter. So, putting it all together:

```<code>engine = create_engine(..., connect_args={"options": "-c statement_timeout=1000"})
</code>```

Body:
The following Python code snippet illustrates the issue:

print("starting")

# I am trying to configure a query/command timeout of one second.
# sqlalchemy docs suggest execution_options but the documented list of options doesn't include a timeout:
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execution_options
# Below, I am guessing at several likely timeout parameter names:
db_engine = create_engine("postgresql://user:pass@server/catalog",
                          execution_options={"timeout": 1.0,
                                             "statement_timeout": 1.0,
                                             "query_timeout": 1.0,
                                             "execution_timeout": 1.0})

with db_engine.connect() as db_connection:
    print("got db_connection")

    # Artificially force a two second query time with pg_sleep.
    # This is designed to guarantee timeout conditions and trigger an exception.
    result_proxy = db_connection.execute("SELECT pg_sleep(2);")

    # If the timeout worked, this statement will not execute.
    # Currently, it does execute, which means my timeout isn't working.
    print("Query successfully complete. Got result_proxy")

Body:
You can set configuration values like statement_timeout via the options parameter in libpq. You can access this parameter in psycopg2 as part of the connect call. You can pass additional parameters to the connect call from SQLAlchemy via the connect_args parameter. So, putting it all together:

engine = create_engine(..., connect_args={"options": "-c statement_timeout=1000"})


问:
Loop formula in excel vba
I am trying to loop a formula instead of using filldown because i have two formulas depending on the length of text in Column A's Cell.

my two formulas are like

.Range("C2").Formula = "=CHAR(83)&CHAR(45)&LEFT(A2,LEN(A2)-9)&CHAR(45)&UPPER(MID(A2,4,LEN(A2)-8))&CHAR(32)&D2&E2"

.Range("C2").Formula = "=LEFT(A2,LEN(A2)-9)&CHAR(45)&UPPER(MID(A2,8,LEN(A2)-12))&CHAR(32)&D2&E2"

This is what i have so far.

```<code>Sub AddFormulas()
Application.ScreenUpdating = False

Dim aCell As String
Dim cCell As String
Dim dCell As String
Dim eCell As String
Dim rowStart As Integer
Dim aCol As Integer
Dim cCol As Integer
Dim dCol As Integer
Dim eCol As Integer
Dim LastRow As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row

rowStart = 2
aCol = 1
cCol = 3
dCol = 4
eCol = 5
'Range("A2")
aCell = Cells(rowStart, aCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)
'Range("C2")
aCell = Cells(rowStart, cCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)
'Range("D2")
dCell = Cells(rowStart, dCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)
'Range("E2")
eCell = Cells(rowStart, eCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)

With ThisWorkbook.Sheets("Sheet1")
        .Range(cCell).Formula = "=CHAR(83)&CHAR(45)&LEFT(aCell,LEN(aCell)-9)&CHAR(45)&UPPER(MID(aCell,4,LEN(aCell)-8))&CHAR(32)&(dCell)&(eCell)"
End With
Application.ScreenUpdating = True
End Sub
</code>```

Thx

答:
You haven't explained the number of chars to determine which formula to use, you can use an IF statement to determine the char length of a cell using LEN Then you can post your formula with just one line of code to the entire range as Excel is smart enough to increment by row. Here is an example:

```<code>Range("B1:B" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "=IF(LEN(A1)=2,123,987)"
</code>```

This will put 123 in column B where the corresponding row in column A has a length of 2 characters otherwise it will enter 987.

Change the LEN(A1)=2 to the length to trigger the first formula, change 123 to the first formula and change 987 to the second formula you want. If you are testing any cell other than column A, also change that in the LEN part of the formula.

Lastly, why on earth are you making this so complex? Why do CHAR(83)&CHAR(45) instead of "S-" its going to be harder to maintain if you put everything in by it's ASCII code.

Title: Loop formula in excel vba

Body:
I am trying to loop a formula instead of using filldown because i have two formulas depending on the length of text in Column A's Cell.

my two formulas are like

.Range("C2").Formula = "=CHAR(83)&CHAR(45)&LEFT(A2,LEN(A2)-9)&CHAR(45)&UPPER(MID(A2,4,LEN(A2)-8))&CHAR(32)&D2&E2"

.Range("C2").Formula = "=LEFT(A2,LEN(A2)-9)&CHAR(45)&UPPER(MID(A2,8,LEN(A2)-12))&CHAR(32)&D2&E2"

This is what i have so far.

Sub AddFormulas()
Application.ScreenUpdating = False

Dim aCell As String
Dim cCell As String
Dim dCell As String
Dim eCell As String
Dim rowStart As Integer
Dim aCol As Integer
Dim cCol As Integer
Dim dCol As Integer
Dim eCol As Integer
Dim LastRow As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row

rowStart = 2
aCol = 1
cCol = 3
dCol = 4
eCol = 5
'Range("A2")
aCell = Cells(rowStart, aCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)
'Range("C2")
aCell = Cells(rowStart, cCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)
'Range("D2")
dCell = Cells(rowStart, dCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)
'Range("E2")
eCell = Cells(rowStart, eCol).Address(RowAbsolute:=False, _
                                ColumnAbsolute:=False)

With ThisWorkbook.Sheets("Sheet1")
        .Range(cCell).Formula = "=CHAR(83)&CHAR(45)&LEFT(aCell,LEN(aCell)-9)&CHAR(45)&UPPER(MID(aCell,4,LEN(aCell)-8))&CHAR(32)&(dCell)&(eCell)"
End With
Application.ScreenUpdating = True
End Sub

Thx

Body:
You haven't explained the number of chars to determine which formula to use, you can use an IF statement to determine the char length of a cell using LEN Then you can post your formula with just one line of code to the entire range as Excel is smart enough to increment by row. Here is an example:

Range("B1:B" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "=IF(LEN(A1)=2,123,987)"

This will put 123 in column B where the corresponding row in column A has a length of 2 characters otherwise it will enter 987.

Change the LEN(A1)=2 to the length to trigger the first formula, change 123 to the first formula and change 987 to the second formula you want. If you are testing any cell other than column A, also change that in the LEN part of the formula.

Lastly, why on earth are you making this so complex? Why do CHAR(83)&CHAR(45) instead of "S-" its going to be harder to maintain if you put everything in by it's ASCII code.


问:
LTS versions installed by stack
Is there a stack command one can run to get a list of all the LTS versions installed by stack on my system?</p>

答:
Not sure about stack command but you can do it with bash command:

```<code>$ ls ~/.stack/snapshots/x86_64-linux/
</code>```

For me it prints:

```<code>lts-8.13  lts-8.15  lts-8.17  lts-8.21  lts-8.3
</code>```

Instead of x86_64-linux should be your arch. But you don't need to remember it. Just press TAB after snapshots/.

Title: LTS versions installed by stack

Body:
Not sure about stack command but you can do it with bash command:

$ ls ~/.stack/snapshots/x86_64-linux/

For me it prints:

lts-8.13  lts-8.15  lts-8.17  lts-8.21  lts-8.3

Instead of x86_64-linux should be your arch. But you don't need to remember it. Just press TAB after snapshots/.


问:
CUDA how to compare two 2D arrays?
Is there any efficient algorithm to compare two 2D arrays in CUDA as fast as possible? As a result I need a number of array fields that are equal.

Thanks in advance for any help!

答: If you just want the number of equal elements between the two arrays, try a reduce operation.  There is an example of this on NVIDIA's site: reduction. Normal sum reductions find the sum of all elements in an array a.  What you want is the sum of the expression a == b for all elements.  You should look articles on CUDA reduction implementations.

Title: CUDA how to compare two 2D arrays?

ContentLicense: CC BY-SA 4.0


问:
Repeating image count for both directories
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}
</code>```

The results of var_dump()

```<code> array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }
</code>```

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

```<code><div class="w3-col m7">
    <div class="w3-row-padding">
        <div class="w3-col m12">
            <div class="w3-card-2 w3-round w3-white">
                <div class="w3-container w3-padding" id="view-photo-albums">
                    <p class="w3-center">Current Albums</p>
                    <br>
                    <?php
foreach ($this->album as $albums):
    ?>
                    <p>
                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>
                    </p>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

答:
There is a problem in this fragment of code:

```<code>foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
     $files[] = $images;
}
</code>```

The variable $dir was used to iterate the array returned by the first invocation of glob():

```<code>foreach (glob(...) as $dir) {
    ...
}
</code>```

Its value after the first foreach loop ends is the last value that was assigned to it into the foreach loop.

In the end, $data['albums'] contains all the directory names and $data['files'] contains the names of the files inside the last directory listed in $data['albums'].

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

array_values() doesn't produce anything new for the $dirname and $files. If they are created (!) these two variables contain values indexed by sequential numbers starting with 0; this is exactly what array_values() returns.

The intention of the code you posted is not very clear for me. I assume you want to display the list of albums and how many images contain each album.

This is how I would do it:

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();

    // Always initialize the arrays before putting values into them.
    // Without this, if the first glob() returns an empty array, the outer
    // foreach loop never runs and both $dirname and $files end up being undefined
    // and this produces trouble in the code that uses these variables later.
    $dirname = array();
    // This will be a two dimensional array. It is indexed by directory
    // names and contains the lists of files for each directory.
    $files   = array();

    // The outer loop enumerates the albums
    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        // The directory name is the album name
        $albumName = basename($dir);

        // Put the album name in $dirname[]
        // This is not really needed as we also have the album name
        // as key in $files but can be useful if you want to keep more
        // information about each album
        $dirname[] = $albumName;

        // Initialize the list of images of this album
        $files[$albumName] = array();

        // The inner loop enumerates the images of this directory
        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }

    // Prepare the data for display
    $data = array(
        'albums' => $dirname,
        'files'  => $files,
    );

    return new ViewModel($data);
}
</code>```

The view (ignored the HTML wrapper, it is ok as it is):

```<code><?php foreach ($this->files as $albumName => $listFiles): ?>
    <p>
        <?php echo $albumName; ?> - Number of images: <?php echo count($listFiles); ?>
    </p>
<?php endforeach; ?>
</code>```

As a remark, the inner foreach loop is not even needed because all it does is to copy one by one the values from the array returned by glob() into a new array.

It is faster and easier to read and understand to just store the value returned by glob() into $files[$albumName]. Since the values stored in $dirname are never used, this variable can be omitted completely and the function becomes shorter (comments omitted):

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $files    = array();

    foreach (glob(getcwd().'/public/images/profile/'.$identity.'/albums/*', GLOB_ONLYDIR) as $dir) {
        $albumName = basename($dir);
        $files[$albumName] = glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE);
    }

    return new ViewModel(array('files' => $files));
}
</code>```

Body:
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}

The results of var_dump()

 array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

Current Albums

                    <?php
foreach ($this->album as $albums):
    ?>

                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>

                    <?php endforeach; ?>

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

Body:
There is a problem in this fragment of code:

foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
     $files[] = $images;
}

The variable $dir was used to iterate the array returned by the first invocation of glob():

foreach (glob(...) as $dir) {
    ...
}

Its value after the first foreach loop ends is the last value that was assigned to it into the foreach loop.

In the end, $data['albums'] contains all the directory names and $data['files'] contains the names of the files inside the last directory listed in $data['albums'].

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

array_values() doesn't produce anything new for the $dirname and $files. If they are created (!) these two variables contain values indexed by sequential numbers starting with 0; this is exactly what array_values() returns.

The intention of the code you posted is not very clear for me. I assume you want to display the list of albums and how many images contain each album.

This is how I would do it:

public function viewphotoalbumsAction()
{
    $identity = $this->identity();

    // Always initialize the arrays before putting values into them.
    // Without this, if the first glob() returns an empty array, the outer
    // foreach loop never runs and both $dirname and $files end up being undefined
    // and this produces trouble in the code that uses these variables later.
    $dirname = array();
    // This will be a two dimensional array. It is indexed by directory
    // names and contains the lists of files for each directory.
    $files   = array();

    // The outer loop enumerates the albums
    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        // The directory name is the album name
        $albumName = basename($dir);

        // Put the album name in $dirname[]
        // This is not really needed as we also have the album name
        // as key in $files but can be useful if you want to keep more
        // information about each album
        $dirname[] = $albumName;

        // Initialize the list of images of this album
        $files[$albumName] = array();

        // The inner loop enumerates the images of this directory
        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }

    // Prepare the data for display
    $data = array(
        'albums' => $dirname,
        'files'  => $files,
    );

    return new ViewModel($data);
}

The view (ignored the HTML wrapper, it is ok as it is):

<?php foreach ($this->files as $albumName => $listFiles): ?>
    <p>
        <?php echo $albumName; ?> - Number of images: <?php echo count($listFiles); ?>
    </p>
<?php endforeach; ?>

As a remark, the inner foreach loop is not even needed because all it does is to copy one by one the values from the array returned by glob() into a new array.

It is faster and easier to read and understand to just store the value returned by glob() into $files[$albumName]. Since the values stored in $dirname are never used, this variable can be omitted completely and the function becomes shorter (comments omitted):

public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $files    = array();

    foreach (glob(getcwd().'/public/images/profile/'.$identity.'/albums/*', GLOB_ONLYDIR) as $dir) {
        $albumName = basename($dir);
        $files[$albumName] = glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE);
    }

    return new ViewModel(array('files' => $files));
}


问:
Use of immutable stack
I've seen the post announcing the release of a stable version of the Microsoft.Bcl.Immutable NuGet package today.

I'm wondering: what would be usage for an immutable stack? I can't find an example or a scenario where that would be useful. Might be my understanding of immutability. If you could shed some light on why this thing might be useful, preferably with a concrete example, this would be nice.

答:
I love the immutable collections but they often feel like a solution in need of a problem. They can be unexpectedly slow due to how they are implemented: they try very hard to use memory efficiently at the cost of making foreach loops and indexers much more algorithmically complex. With how plentiful memory is, it can be hard to justify that cost. There's a dearth of information to be found on the web about successful uses of immutable collections (other than ImmutableArray<T>). In an attempt to rectify that, I thought I'd add an answer to this 3+ year old question about a case where I found ImmutableStack<T> to be truly useful.

Consider this very basic tree-like structure:

```<code>public class TreeNode
{
    public TreeNode Parent { get; private set; }
    public List<TreeNode> ChildNodes { get; set; }

    public TreeNode(TreeNode parent)
    {
        Parent = parent;
    }
}
</code>```

I've created classes that follow this basic pattern many, many times, and in practice, it's always worked for me. More recently, I've started to do something like this:

```<code>public class TreeNode
{
    public ImmutableStack<TreeNode> NodeStack { get; private set; }
    public ImmutableStack<TreeNode> ParentStack { get { return NodeStack.IsEmpty ? ImmutableStack<TreeNode>.Empty : NodeStack.Pop(); } }
    public TreeNode Parent { get { return ParentStack.IsEmpty ? null : ParentStack.Peek(); } }

    public ImmutableArray<TreeNode> ChildNodes { get; set; }

    public TreeNode(TreeNode parent)
    {
        if (parent == null)
            NodeStack = ImmutableStack<TreeNode>.Empty;
        else
            NodeStack = parent.NodeStack.Push(this);
    }
}
</code>```

For a variety of reasons, I've come to prefer storing an ImmutableStack<T> of TreeNode instances that I can traverse to the root rather than simply a reference to the Parent instance.

ImmutableStack<T>'s implementation is basically a linked list. Each instance of ImmutableStack<T> is really a node on a linked list. That's why the ParentStack property just Pop's the NodeStack. ParentStack will return the same instance of ImmutableStack<T> as Parent.NodeStack would.

If you store a reference to the Parent TreeNode, it would be easy to create a circular loop that would cause operations such as finding the root node to never terminate, and you'd either get a stack overflow or an infinite loop. An ImmutableStack<T>, on the other hand, can be ascended by Pop-ing, guaranteeing that it will terminate.

The fact that you use a collection (ImmutableStack<T>) means that you can prevent circular loops from happening in the first place by simply making sure the parent TreeNode does not occur twice when constructing the TreeNode.

That's just to start with. I think the ImmutableStack<T> makes tree operations simpler and safer. You can (safely) use LINQ on it. Want to know if one TreeNode is a descendent of another? You could simply do ParentStack.Any(node => node == otherNode)

More generally, the ImmutableStack<T> class is for any case where you would like a Stack<T> that you can guarantee will never be modified, or you need an easy way to get a "snapshot" of a Stack<T> but don't want to create create a bunch of copies of that stack. If you have a series of nested steps, you could use an ImmutableStack<T> to track progress, and so when a step is completed, it can hand off work to its parent step. Its immutable nature is especially helpful when you're trying to do work in parallel.

Title: Use of immutable stack

Body:
I love the immutable collections but they often feel like a solution in need of a problem. They can be unexpectedly slow due to how they are implemented: they try very hard to use memory efficiently at the cost of making foreach loops and indexers much more algorithmically complex. With how plentiful memory is, it can be hard to justify that cost. There's a dearth of information to be found on the web about successful uses of immutable collections (other than ImmutableArray<T>). In an attempt to rectify that, I thought I'd add an answer to this 3+ year old question about a case where I found ImmutableStack<T> to be truly useful.

Consider this very basic tree-like structure:

public class TreeNode
{
    public TreeNode Parent { get; private set; }
    public List<TreeNode> ChildNodes { get; set; }

    public TreeNode(TreeNode parent)
    {
        Parent = parent;
    }
}

I've created classes that follow this basic pattern many, many times, and in practice, it's always worked for me. More recently, I've started to do something like this:

public class TreeNode
{
    public ImmutableStack<TreeNode> NodeStack { get; private set; }
    public ImmutableStack<TreeNode> ParentStack { get { return NodeStack.IsEmpty ? ImmutableStack<TreeNode>.Empty : NodeStack.Pop(); } }
    public TreeNode Parent { get { return ParentStack.IsEmpty ? null : ParentStack.Peek(); } }

    public ImmutableArray<TreeNode> ChildNodes { get; set; }

    public TreeNode(TreeNode parent)
    {
        if (parent == null)
            NodeStack = ImmutableStack<TreeNode>.Empty;
        else
            NodeStack = parent.NodeStack.Push(this);
    }
}

For a variety of reasons, I've come to prefer storing an ImmutableStack<T> of TreeNode instances that I can traverse to the root rather than simply a reference to the Parent instance.

ImmutableStack<T>'s implementation is basically a linked list. Each instance of ImmutableStack<T> is really a node on a linked list. That's why the ParentStack property just Pop's the NodeStack. ParentStack will return the same instance of ImmutableStack<T> as Parent.NodeStack would.

If you store a reference to the Parent TreeNode, it would be easy to create a circular loop that would cause operations such as finding the root node to never terminate, and you'd either get a stack overflow or an infinite loop. An ImmutableStack<T>, on the other hand, can be ascended by Pop-ing, guaranteeing that it will terminate.

The fact that you use a collection (ImmutableStack<T>) means that you can prevent circular loops from happening in the first place by simply making sure the parent TreeNode does not occur twice when constructing the TreeNode.

That's just to start with. I think the ImmutableStack<T> makes tree operations simpler and safer. You can (safely) use LINQ on it. Want to know if one TreeNode is a descendent of another? You could simply do ParentStack.Any(node => node == otherNode)

More generally, the ImmutableStack<T> class is for any case where you would like a Stack<T> that you can guarantee will never be modified, or you need an easy way to get a "snapshot" of a Stack<T> but don't want to create create a bunch of copies of that stack. If you have a series of nested steps, you could use an ImmutableStack<T> to track progress, and so when a step is completed, it can hand off work to its parent step. Its immutable nature is especially helpful when you're trying to do work in parallel.


问:
Can not remove fragment from backstack using popBackStack() or remove()
I have 2 fragments: SportsList and Workout

I put SportsList fragment as this:

```<code>FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("SportsList").replace(R.id.fragment, sportsListFragment);
</code>```

And then I put Workout

```<code>FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("Workout").replace(R.id.fragment, workoutFragment);
</code>```

I am using replace() method so SportsList should be removed, but when I call popBackStackImmediate() it remains there.

So I tried removing SportsList manually at Workout fragment, when I click a button. So I do this:

```<code>FragmentManager fm = getActivity().getSupportFragmentManager();
Fragment oldFragment = fm.findFragmentByTag("SportsList");
fm.beginTransaction().remove(oldFragment).commit();
</code>```

But this gives me following error:

FATAL EXCEPTION: main
                                                                              java.lang.NullPointerException: Attempt to write to field 'int android.support.v4.app.Fragment.mNextAnim' on a null object reference
                                                                                at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:770)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:541)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I also tried to do this:

```<code>fm.popBackStack("SportsList", 0);
</code>```

and this:

```<code>fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
</code>```

and this:

```<code>fm.popBackStack("SportsList", FragmentManager.POP_BACK_STACK_INCLUSIVE);
</code>```

But these are removing current fragment (Workout fragment) instead of SportsList fragment. I am out of ideas right now. Besides that:

```<code>ft.replace(R.id.fragment, sportsListFragment);
</code>```

still adding SportsList fragment to the backstack. How could this be possible?

答:
try this : </p>

```<code>ft.addToBackStack("SportsList").replace(R.id.fragment, sportsListFragment).addToBackStack(null);
</code>```

Body:
I have 2 fragments: SportsList and Workout

I put SportsList fragment as this:

FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("SportsList").replace(R.id.fragment, sportsListFragment);

And then I put Workout

FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("Workout").replace(R.id.fragment, workoutFragment);

I am using replace() method so SportsList should be removed, but when I call popBackStackImmediate() it remains there.

So I tried removing SportsList manually at Workout fragment, when I click a button. So I do this:

FragmentManager fm = getActivity().getSupportFragmentManager();
Fragment oldFragment = fm.findFragmentByTag("SportsList");
fm.beginTransaction().remove(oldFragment).commit();

But this gives me following error:

FATAL EXCEPTION: main
                                                                              java.lang.NullPointerException: Attempt to write to field 'int android.support.v4.app.Fragment.mNextAnim' on a null object reference
                                                                                at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:770)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:541)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I also tried to do this:

fm.popBackStack("SportsList", 0);

and this:

fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

and this:

fm.popBackStack("SportsList", FragmentManager.POP_BACK_STACK_INCLUSIVE);

But these are removing current fragment (Workout fragment) instead of SportsList fragment. I am out of ideas right now. Besides that:

ft.replace(R.id.fragment, sportsListFragment);

still adding SportsList fragment to the backstack. How could this be possible?

Body:
try this :

ft.addToBackStack("SportsList").replace(R.id.fragment, sportsListFragment).addToBackStack(null);


问:
module.exports value not found when used in another file
Not sure why, I can import this file and use expect in my test files just fine, but I am getting an eslint error:

```<code>error  expect not found in '../../testImports' import/named
</code>```

This is where I export, testImports.js:

```<code>import chai from 'chai'
const expect = require('chai').expect
import { BrowserRouter } from 'react-router-dom'
import { jsdom } from './jsdom'

module.exports = {
  BrowserRouter,
  expect,
  jsdom
}
</code>```

And I'm importing as so into files: import { expect } from '../../testImports'.

答:
The problem is eslint-plugin-import only picks up on ES6 module system exports, not ES5. They mean the same thing, the plugin just doesn't catch it. Since the plugin doesn't see you've exported anything, it reports the error, but there's nothing actually wrong about your code. If you want to get rid of the error, just use ES6's export:

```<code>export {
  BrowserRouter,
  expect,
  jsdom
};
</code>```

Body:
Not sure why, I can import this file and use expect in my test files just fine, but I am getting an eslint error:

error  expect not found in '../../testImports' import/named

This is where I export, testImports.js:

import chai from 'chai'
const expect = require('chai').expect
import { BrowserRouter } from 'react-router-dom'
import { jsdom } from './jsdom'

module.exports = {
  BrowserRouter,
  expect,
  jsdom
}

And I'm importing as so into files: import { expect } from '../../testImports'.

Body:
The problem is eslint-plugin-import only picks up on ES6 module system exports, not ES5. They mean the same thing, the plugin just doesn't catch it. Since the plugin doesn't see you've exported anything, it reports the error, but there's nothing actually wrong about your code. If you want to get rid of the error, just use ES6's export:

export {
  BrowserRouter,
  expect,
  jsdom
};


问:
JDOM.Element.getChild(String) is returning unexpected results
According to the API at jdom.org, the semantics of getChild(String name):

This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.

Therefore, if I have an XML structure like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2>
        <lvl3/>
    </lvl2>
</lvl1>
</code>```

I have a JDOM Element which is currently pointing to <lvl1>. I should be able to make the following call:

```<code>Element lvl3 = lvl1Element.getChild("lvl3");
</code>```

and lvl3 should have non-null.

However, I'm finding that lvl3 is actually null.  Am I missing something?

Here is a sample code snippet that should work:

```<code>import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
    Document doc = new SAXBuilder().build(new StringReader("path to file"));
    Element lvl1Element = doc.getRootElement();
    Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}
</code>```

答:
---lvl1

```<code>---lvl2(child of lvl1)

  ---lvl3(child of lvl2)
</code>```

Body:
According to the API at jdom.org, the semantics of getChild(String name):

This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.

Therefore, if I have an XML structure like:

<?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2>
        <lvl3/>
    </lvl2>
</lvl1>

I have a JDOM Element which is currently pointing to <lvl1>. I should be able to make the following call:

Element lvl3 = lvl1Element.getChild("lvl3");

and lvl3 should have non-null.

However, I'm finding that lvl3 is actually null.  Am I missing something?

Here is a sample code snippet that should work:

import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
    Document doc = new SAXBuilder().build(new StringReader("path to file"));
    Element lvl1Element = doc.getRootElement();
    Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}

Body:
---lvl1

---lvl2(child of lvl1)

  ---lvl3(child of lvl2)


问:
How do I get argument values inferred from usage?
So I'm following through some code snippets for AutoInjector and Automapper online, and noticed something that I don't really understand.

In the code, AutoInjector is Registering Automapper for use in this line.

container.Register(() => config.CreateMapper(container.GetInstance));

I noticed that container.GetInstance isn't having anything passed into it.

After some tinkering, I tried to do var instance = container.GetInstance(); in a console app, but it gives the error The type arguments for method 'Container.GetInstance<TService>() cannot be inferred from the usage. Try specifying the type arguments explicitly.

Obviously, the arguments being passed are inferred from the outer method config.CreateMapper()

I was wondering if there was a way to step through the code so I can see what is being passed into container.GetInstance(). When I step through the code, it just steps over the line and doesn't show me what's being passed into the method.

答:
CreateMapper expects as its argument a function which takes an input of Type and returns object.

```<code>Func<Type, object>
</code>```

Looks like container.GetInstance is one such function.

Since you seem to be interested in the internals, here they are:

MapperConfiguration.cs

```<code>public IMapper CreateMapper() => new Mapper(this);
</code>```

Mapper.cs

```<code>public Mapper(IConfigurationProvider configurationProvider)
    : this(configurationProvider, configurationProvider.ServiceCtor)
{
}

public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor)
{
    _configurationProvider = configurationProvider;
    _serviceCtor = serviceCtor;
    DefaultContext = new ResolutionContext(new ObjectMappingOperationOptions(serviceCtor), this);
}
</code>```

Body:
CreateMapper expects as its argument a function which takes an input of Type and returns object.

Func<Type, object>

Looks like container.GetInstance is one such function.

Since you seem to be interested in the internals, here they are:

MapperConfiguration.cs

public IMapper CreateMapper() => new Mapper(this);

Mapper.cs

public Mapper(IConfigurationProvider configurationProvider)
    : this(configurationProvider, configurationProvider.ServiceCtor)
{
}

public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor)
{
    _configurationProvider = configurationProvider;
    _serviceCtor = serviceCtor;
    DefaultContext = new ResolutionContext(new ObjectMappingOperationOptions(serviceCtor), this);
}