问:
Add cron entry to XAMPP server
I am using Laravel 5.4 on Windows. In the documentation, it does not say how to add cron entries to server. I searched on YouTube, but didn't get any useful video. I need to learn how to add cron entries both to localhost and cPanel.</p>

答:
First of all you can add cron only in Server Not for localhost

To add cron in cPanel follow the steps below

Step1:-
First create a cron function to which the server is going to hit,
and get the Full path like

http://fullpath

Step2:-
Then got to cron jobs in cpanel and set the time when the cron will hit that route.

To set the time you have to follow this

```<code>    Minutes represents the minutes of a given hour, 0-59 respectively.
    Hours represents the hours of a given day, 0-23 respectively.
    Days represents the days of a given month, 1-31 respectively.
    Months represents the months of a given year, 1-12 respectively.
    Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.
</code>```

Like this

Step3:-
Then Write the cron comand like

```<code>curl  http://fullpath
</code>```

Like this:-

This above cron job is set for 1 sec.That means the cron will hit that route in every one sec.

Like this you can set your cron on cPanel.

Title: Add cron entry to XAMPP server

Body:
First of all you can add cron only in Server Not for localhost

To add cron in cPanel follow the steps below

Step1:-
First create a cron function to which the server is going to hit,
and get the Full path like

http://fullpath

Step2:-
Then got to cron jobs in cpanel and set the time when the cron will hit that route.

To set the time you have to follow this

    Minutes represents the minutes of a given hour, 0-59 respectively.
    Hours represents the hours of a given day, 0-23 respectively.
    Days represents the days of a given month, 1-31 respectively.
    Months represents the months of a given year, 1-12 respectively.
    Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.

Like this

Step3:-
Then Write the cron comand like

curl  http://fullpath

Like this:-

This above cron job is set for 1 sec.That means the cron will hit that route in every one sec.

Like this you can set your cron on cPanel.


来源: stackexchange

问:
Browser compatibility issue when using ::before css selector on optgroup tag
The following code gets the desired results only on Chrome:

HTML:

```<code><select multiple style="width:500px">
  <optgroup class="outg" label="Swedish Cars">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </optgroup>
</select>
</code>```

CSS:

```<code>.outg::before {
  content: "";
  border-style: solid;
  border-width: 7px 0 7px 7px;
  border-color: transparent transparent transparent #656565;
  float: left;
  margin-right: 3px;
  width: 10px;
}
</code>```

https://jsfiddle.net/2ny35p94/3/

Chrome 58 - both triangle and label are displayed:

Firefox 53 - only the triangle is displayed:

IE 11 - only the label is displayed:

Any suggestion on how to make it cross browser compatible?

答:
You can't show both because you are overriding the default ::before, that's exactly what the browser does. Chrome seems to apply it but it's not on the standard specification. So in this case, Firefox and IE are working as expected.

The <optgroup> tag is styling by the browser as this:

```<code>optgroup[label]::before {
     content: attr(label);
}
</code>```

If you override the content property, there's nothing you can do.

My suggestion is to remove the content property on your code, but you will have to fix another related issues. See the screenshot:

See it working:

https://jsfiddle.net/2ny35p94/4/

ContentLicense: CC BY-SA 3.0

Body:
The following code gets the desired results only on Chrome:

HTML:

<select multiple style="width:500px">
  <optgroup class="outg" label="Swedish Cars">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </optgroup>
</select>

CSS:

.outg::before {
  content: "";
  border-style: solid;
  border-width: 7px 0 7px 7px;
  border-color: transparent transparent transparent #656565;
  float: left;
  margin-right: 3px;
  width: 10px;
}

https://jsfiddle.net/2ny35p94/3/

Chrome 58 - both triangle and label are displayed:

Firefox 53 - only the triangle is displayed:

IE 11 - only the label is displayed:

Any suggestion on how to make it cross browser compatible?

Body:
You can't show both because you are overriding the default ::before, that's exactly what the browser does. Chrome seems to apply it but it's not on the standard specification. So in this case, Firefox and IE are working as expected.

The <optgroup> tag is styling by the browser as this:

optgroup[label]::before {
     content: attr(label);
}

If you override the content property, there's nothing you can do.

My suggestion is to remove the content property on your code, but you will have to fix another related issues. See the screenshot:

See it working:

https://jsfiddle.net/2ny35p94/4/


问:
Use static JSON string in AJAX query instead of a URL
I am trying to create a dynamic timeline widget in a HTML file as shown in the picture:

It works fine when I parse the data from a JSON URL. This part is shown below :

```<code>    var filename = "snow-patrol.json",
    bandId = filename.replace(".json","");

$.ajax({
    type: "GET",
    url: filename,
    dataType: "json",
    success: function(data){
        init(data);
    }
});
</code>```

Now, I am trying to use a static JSON string in the AJAX query instead of using a URL:

```<code>    $.ajax({
    type: "GET",
    url: filename,
    data: JSON.stringify({"dummy" : "","yearStarted" : 1994, "row" : [{"id" : "garyL","name" : "One","yearJoined" : 2007,"yearLeft" : 2015},{"id" : "markM","name" : "Two","yearJoined" : 2001,"yearLeft" : 2005}]}),
    dataType: "json",
    success: function(data){
        init(data);
    }
});
</code>```

So, in the data: JSON.stringify part, I am using the JSON string but the widget (timeline) does not work. It only works if I have a working URL. Is there a way to use a static JSON string instead of having to use a link in the AJAX query? Everything else works fine. The data used in this AJAX call is being used in other queries in my page as shown in the snippet below (it does not work because of the cross origin thing for the JSON link).

var BAND_TIMELINE = (function() {

    var filename = "snow-patrol.json",
        bandId = filename.replace(".json","");

    $.ajax({
        type: "GET",
        url: filename,
        dataType: "json",
        success: function(data){
            init(data);
        }
    });

    function init(data) {
        THE_BAND.displayBand(data);
        TIMELINE.displayTimescale(data);

        $(".bar").each(function() {
            $(this)
                .data("origWidth", $(this).width())
                .width(0)
                .animate({
                    width: $(this).data("origWidth")
                }, 3000);
        });
    }

})();

////
var THE_BAND = (function() {

    var presentYear = new Date().getFullYear();

    function displaydummy(dummy) {
        $('.band-name').text(dummy);
    }

    function displayBandDetails(data) {
        displaydummy(data.dummy);
        listrow(data);
    }

    function listrow(data) {
        var yearBandStarted = TIMELINE.getYearStarted(data),
            row = data.row,
            $rowList = $(".band-members"),
            barPosition = {};

        for (var member in row) {
            if (row.hasOwnProperty(member)) {
                var person = row[member],
                    yearsInBand = getYearsActive(person);

                $rowList.append('
' + person.name +
                                        ' (' + yearsInBand + ')
');

                barPosition = calculatePositionOnTimeline(person, yearBandStarted);

                if (barPosition.left) {
                    $('#' + person.id).css({left: barPosition.left + '%'});
                }
                $('#' + person.id).width(barPosition.width + '%');
            }
        }
    }

    function getYearsActive(person) {
        var yearsActive = "";

        if (!person.yearLeft) {
            yearsActive = person.yearJoined + " - present";
        } else {
            yearsActive = person.yearJoined + " - " + person.yearLeft;
        }

        return yearsActive;
    }

    function calculatePositionOnTimeline(person, yearBandStarted) {
        var yearsInBand = 1,
            widthPerYear = getWidthPerYear(yearBandStarted),
            barPosition = "",
            barProperties = { "left" : 0, "width" : 0};

        if (person.yearLeft) {
            yearsInBand += person.yearLeft - person.yearJoined;
        } else if (person.yearJoined < presentYear) {
            yearsInBand += presentYear - person.yearJoined;
        }

        barProperties.width = widthPerYear * yearsInBand;

        if (person.yearJoined > yearBandStarted) {
            var yearsFromStart = person.yearJoined - yearBandStarted;
            barProperties.left = (widthPerYear * yearsFromStart);
        }

        return barProperties;
    }

    function getWidthPerYear(yearBandStarted) {
        var present = new Date().getFullYear(),
            numberOfYears = (present - yearBandStarted) + 1,
            timelineWidth = $(".timeline").width(),
            widthPerYear = ((timelineWidth/numberOfYears)/timelineWidth)*100;

        return widthPerYear;
    }

    return {
        displayBand : displayBandDetails
    };

})();

/////
var TIMELINE = (function() {

    function displayTimelineScale(data) {
        var $timelineScale = $(".years"),
            presentYear = new Date().getFullYear(),
            yearZero = getYearStartPoint(data),
            year = yearZero;

        while (year <= presentYear) {
            if (year === yearZero) {
                $timelineScale.append('
' + trimYear(year.toString()) + '
');
            } else if (year === presentYear) {
                $timelineScale.append('
' + trimYear(year.toString()) + '
');
            } else {
                $timelineScale.append("
" + trimYear(year.toString()) + "
");
            }
            year++;
        }

        // widths are set as percentages to allow for a flexible widths chart
        // NOTE: there is a limit to how flexible the width can be as more years = more space needed
        $('ul.years li').width(getWidthPerYear(yearZero) + '%');
    }

    function getYearStartPoint(data) {
        var row = data.row,
            startAtYear = row[0].yearJoined;

        for (var i = 0; i < row.length; i++) {
            for (var j = 1; j < row.length; j++) {
                var personA = row[i],
                    personB = row[j];

                if (personB.yearJoined < personA.yearJoined && personB.yearJoined < startAtYear) {
                    startAtYear = personB.yearJoined;
                } else if (personA.yearJoined < personB.yearJoined && personA.yearJoined < startAtYear) {
                    startAtYear = personA.yearJoined;
                }
            }
        }

        return startAtYear;
    }

    function getWidthPerYear(yearStarted) {
        var present = new Date().getFullYear(),
            numberOfYears = (present - yearStarted) + 1,
            borderPadding = numberOfYears,
            timelineWidth = $(".timeline").width(),
            widthPerYear = (((timelineWidth-borderPadding)/numberOfYears)/timelineWidth)*100;

        return widthPerYear;
    }

    function trimYear(yearStr) {
        var trimmedYear = "";

        if (yearStr.length === 4) {
            trimmedYear = "'" + yearStr.slice(2,4);
        } else if (yearStr.length === 3 && yearStr.startsWith("'")) {
            trimmedYear = yearStr;
        } else if (yearStr.length === 2) {
            trimmedYear = "'" + yearStr;
        }

        return trimmedYear;
    }

    return {
        displayTimescale : displayTimelineScale,
        getYearStarted : getYearStartPoint
    };
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font-weight: 400;
    font: inherit;
    vertical-align: baseline;
}
strong {
    font-weight: bold;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}

/* --- General style --- */

body {
    font: 400 1em/1.15 "Fira Sans Light", "Helvetica Neue", Helvetica, Arial, sans-serif;
    background: #fefefe;
    padding: 0 10px;
}
h1 {
    padding-top: 1.25%;
    padding-bottom: 1.5%;
    font: 400 1.5em/1 "Patua One", Georgia, "Times New Roman", serif;
    font-weight: bold;
    color: #333;
}
p {
    padding-top: 0.8%;
    padding-bottom: 0.8%;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

::selection {
    background: #ffb50d;
}
::-moz-selection {
    background: #ffb50d;
}

.description {
    clear: both;
    margin: 45px 0;
}

.band-name {
    background-color: #203e74;
    color: transparent;
    text-shadow: 0px 2px 5px rgba(255,255,255,0.6);
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
}

/* --- Timeline Style --- */

.years {
    list-style-type: none;
    padding: 0;
    display: block;
}

.years li {
    font-size: 0.85em;
    border-right: 1px solid #fff;
    background: #f3f3f3;
    float: left;
    margin: 0;
    padding: 10px 0;
    text-align: center;
}
.years.top li {
    border-bottom: 1px solid #000;
}
.years.bottom li {
    border-top: 1px solid #000;
}

.years .start {
    border-left: 1px solid #fff;
}
.years .present {
    border-right: none;
}

.band-members {
    clear: both;
    list-style: none;
    margin: 0;
    padding: 15px 0;
    margin-left: -1px;
    height: 330px;
}

.band-members li {
    color: #f3f3f3;
    text-shadow: 0px 2px 3px #565656;
    border: 2px solid #ddd;
    position: relative;
    left: -2px;
    -moz-border-radius: 25px;
    -webkit-border-radius: 25px;
    border-radius: 25px;
    -moz-box-shadow: 2px 2px 3px #696969;
    -webkit-box-shadow: 2px 2px 3px #696969;
    box-shadow: 2px 2px 3px #696969;
    margin-bottom: 5px;
    padding: 3px 0;
    text-align: center;
}

.band-members em {
    font-family: "Fira Sans Light Italic", "Helvetica Neue", Helvetica, Arial, sans-serif;
    padding-left: 0;
    display: inline-block;
}

#garyL {
    background: #f2374d;
    background: -webkit-linear-gradient(top, #cf061d, #f2374d);
    background:    -moz-linear-gradient(top, #cf061d, #f2374d);
    background:     -ms-linear-gradient(top, #cf061d, #f2374d);
    background:      -o-linear-gradient(top, #cf061d, #f2374d);
    background:         linear-gradient(to bottom, #cf061d, #f2374d);
}

#markM, #paulW {
    background: #fcbf17;
    background: -webkit-linear-gradient(top, #fcbf17, #fdd66a);
    background:    -moz-linear-gradient(top, #fcbf17, #fdd66a);
    background:     -ms-linear-gradient(top, #fcbf17, #fdd66a);
    background:      -o-linear-gradient(top, #fcbf17, #fdd66a);
    background:         linear-gradient(to bottom, #fcbf17, #fdd66a);
}

#michaelM, #jonnyQ {
    background: #6c9bde;
    background: -webkit-linear-gradient(top, #2779eb, #6c9bde);
    background:    -moz-linear-gradient(top, #2779eb, #6c9bde);
    background:     -ms-linear-gradient(top, #2779eb, #6c9bde);
    background:      -o-linear-gradient(top, #2779eb, #6c9bde);
    background:         linear-gradient(to bottom, #2779eb, #6c9bde);
}

#nathanC {
    background: #73b84d;
    background: -webkit-linear-gradient(top, #24a624, #73b84d);
    background:    -moz-linear-gradient(top, #24a624, #73b84d);
    background:     -ms-linear-gradient(top, #24a624, #73b84d);
    background:      -o-linear-gradient(top, #24a624, #73b84d);
    background:         linear-gradient(to bottom, #24a624, #73b84d);
}

#tomS {
    background: #7ba6ad;
    background: -webkit-linear-gradient(top, #4a95ab, #7ba6ad);
    background:    -moz-linear-gradient(top, #4a95ab, #7ba6ad);
    background:     -ms-linear-gradient(top, #4a95ab, #7ba6ad);
    background:      -o-linear-gradient(top, #4a95ab, #7ba6ad);
    background:         linear-gradient(to bottom, #4a95ab, #7ba6ad);
}

#johnnyM {
    background: #9c79bd;
    background: -webkit-linear-gradient(top, #8952bd, #9c79bd);
    background:    -moz-linear-gradient(top, #8952bd, #9c79bd);
    background:     -ms-linear-gradient(top, #8952bd, #9c79bd);
    background:      -o-linear-gradient(top, #8952bd, #9c79bd);
    background:         linear-gradient(to bottom, #8952bd, #9c79bd);
}</code>```

```

答:
Why not just pass the whole object to your init function?

You don't need AJAX if you're going to use a static JSON object.

```<code>init({"dummy" : "","yearStarted" : 1994, "row" : [{"id" : "garyL","name" : "One","yearJoined" : 2007,"yearLeft" : 2015},{"id" : "markM","name" : "Two","yearJoined" : 2001,"yearLeft" : 2005}]});
</code>```

Body:
I am trying to create a dynamic timeline widget in a HTML file as shown in the picture:

It works fine when I parse the data from a JSON URL. This part is shown below :

    var filename = "snow-patrol.json",
    bandId = filename.replace(".json","");

$.ajax({
    type: "GET",
    url: filename,
    dataType: "json",
    success: function(data){
        init(data);
    }
});

Now, I am trying to use a static JSON string in the AJAX query instead of using a URL:

    $.ajax({
    type: "GET",
    url: filename,
    data: JSON.stringify({"dummy" : "","yearStarted" : 1994, "row" : [{"id" : "garyL","name" : "One","yearJoined" : 2007,"yearLeft" : 2015},{"id" : "markM","name" : "Two","yearJoined" : 2001,"yearLeft" : 2005}]}),
    dataType: "json",
    success: function(data){
        init(data);
    }
});

So, in the data: JSON.stringify part, I am using the JSON string but the widget (timeline) does not work. It only works if I have a working URL. Is there a way to use a static JSON string instead of having to use a link in the AJAX query? Everything else works fine. The data used in this AJAX call is being used in other queries in my page as shown in the snippet below (it does not work because of the cross origin thing for the JSON link).

var BAND_TIMELINE = (function() {

    var filename = "snow-patrol.json",
        bandId = filename.replace(".json","");

    $.ajax({
        type: "GET",
        url: filename,
        dataType: "json",
        success: function(data){
            init(data);
        }
    });

    function init(data) {
        THE_BAND.displayBand(data);
        TIMELINE.displayTimescale(data);

        $(".bar").each(function() {
            $(this)
                .data("origWidth", $(this).width())
                .width(0)
                .animate({
                    width: $(this).data("origWidth")
                }, 3000);
        });
    }

})();

////
var THE_BAND = (function() {

    var presentYear = new Date().getFullYear();

    function displaydummy(dummy) {
        $('.band-name').text(dummy);
    }

    function displayBandDetails(data) {
        displaydummy(data.dummy);
        listrow(data);
    }

    function listrow(data) {
        var yearBandStarted = TIMELINE.getYearStarted(data),
            row = data.row,
            $rowList = $(".band-members"),
            barPosition = {};

        for (var member in row) {
            if (row.hasOwnProperty(member)) {
                var person = row[member],
                    yearsInBand = getYearsActive(person);

                $rowList.append('
' + person.name +
                                        ' (' + yearsInBand + ')
');

                barPosition = calculatePositionOnTimeline(person, yearBandStarted);

                if (barPosition.left) {
                    $('#' + person.id).css({left: barPosition.left + '%'});
                }
                $('#' + person.id).width(barPosition.width + '%');
            }
        }
    }

    function getYearsActive(person) {
        var yearsActive = "";

        if (!person.yearLeft) {
            yearsActive = person.yearJoined + " - present";
        } else {
            yearsActive = person.yearJoined + " - " + person.yearLeft;
        }

        return yearsActive;
    }

    function calculatePositionOnTimeline(person, yearBandStarted) {
        var yearsInBand = 1,
            widthPerYear = getWidthPerYear(yearBandStarted),
            barPosition = "",
            barProperties = { "left" : 0, "width" : 0};

        if (person.yearLeft) {
            yearsInBand += person.yearLeft - person.yearJoined;
        } else if (person.yearJoined < presentYear) {
            yearsInBand += presentYear - person.yearJoined;
        }

        barProperties.width = widthPerYear * yearsInBand;

        if (person.yearJoined > yearBandStarted) {
            var yearsFromStart = person.yearJoined - yearBandStarted;
            barProperties.left = (widthPerYear * yearsFromStart);
        }

        return barProperties;
    }

    function getWidthPerYear(yearBandStarted) {
        var present = new Date().getFullYear(),
            numberOfYears = (present - yearBandStarted) + 1,
            timelineWidth = $(".timeline").width(),
            widthPerYear = ((timelineWidth/numberOfYears)/timelineWidth)*100;

        return widthPerYear;
    }

    return {
        displayBand : displayBandDetails
    };

})();

/////
var TIMELINE = (function() {

    function displayTimelineScale(data) {
        var $timelineScale = $(".years"),
            presentYear = new Date().getFullYear(),
            yearZero = getYearStartPoint(data),
            year = yearZero;

        while (year <= presentYear) {
            if (year === yearZero) {
                $timelineScale.append('
' + trimYear(year.toString()) + '
');
            } else if (year === presentYear) {
                $timelineScale.append('
' + trimYear(year.toString()) + '
');
            } else {
                $timelineScale.append("
" + trimYear(year.toString()) + "
");
            }
            year++;
        }

        // widths are set as percentages to allow for a flexible widths chart
        // NOTE: there is a limit to how flexible the width can be as more years = more space needed
        $('ul.years li').width(getWidthPerYear(yearZero) + '%');
    }

    function getYearStartPoint(data) {
        var row = data.row,
            startAtYear = row[0].yearJoined;

        for (var i = 0; i < row.length; i++) {
            for (var j = 1; j < row.length; j++) {
                var personA = row[i],
                    personB = row[j];

                if (personB.yearJoined < personA.yearJoined && personB.yearJoined < startAtYear) {
                    startAtYear = personB.yearJoined;
                } else if (personA.yearJoined < personB.yearJoined && personA.yearJoined < startAtYear) {
                    startAtYear = personA.yearJoined;
                }
            }
        }

        return startAtYear;
    }

    function getWidthPerYear(yearStarted) {
        var present = new Date().getFullYear(),
            numberOfYears = (present - yearStarted) + 1,
            borderPadding = numberOfYears,
            timelineWidth = $(".timeline").width(),
            widthPerYear = (((timelineWidth-borderPadding)/numberOfYears)/timelineWidth)*100;

        return widthPerYear;
    }

    function trimYear(yearStr) {
        var trimmedYear = "";

        if (yearStr.length === 4) {
            trimmedYear = "'" + yearStr.slice(2,4);
        } else if (yearStr.length === 3 && yearStr.startsWith("'")) {
            trimmedYear = yearStr;
        } else if (yearStr.length === 2) {
            trimmedYear = "'" + yearStr;
        }

        return trimmedYear;
    }

    return {
        displayTimescale : displayTimelineScale,
        getYearStarted : getYearStartPoint
    };
})();

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font-weight: 400;
    font: inherit;
    vertical-align: baseline;
}
strong {
    font-weight: bold;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}

/* --- General style --- */

body {
    font: 400 1em/1.15 "Fira Sans Light", "Helvetica Neue", Helvetica, Arial, sans-serif;
    background: #fefefe;
    padding: 0 10px;
}
h1 {
    padding-top: 1.25%;
    padding-bottom: 1.5%;
    font: 400 1.5em/1 "Patua One", Georgia, "Times New Roman", serif;
    font-weight: bold;
    color: #333;
}
p {
    padding-top: 0.8%;
    padding-bottom: 0.8%;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

::selection {
    background: #ffb50d;
}
::-moz-selection {
    background: #ffb50d;
}

.description {
    clear: both;
    margin: 45px 0;
}

.band-name {
    background-color: #203e74;
    color: transparent;
    text-shadow: 0px 2px 5px rgba(255,255,255,0.6);
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
}

/* --- Timeline Style --- */

.years {
    list-style-type: none;
    padding: 0;
    display: block;
}

.years li {
    font-size: 0.85em;
    border-right: 1px solid #fff;
    background: #f3f3f3;
    float: left;
    margin: 0;
    padding: 10px 0;
    text-align: center;
}
.years.top li {
    border-bottom: 1px solid #000;
}
.years.bottom li {
    border-top: 1px solid #000;
}

.years .start {
    border-left: 1px solid #fff;
}
.years .present {
    border-right: none;
}

.band-members {
    clear: both;
    list-style: none;
    margin: 0;
    padding: 15px 0;
    margin-left: -1px;
    height: 330px;
}

.band-members li {
    color: #f3f3f3;
    text-shadow: 0px 2px 3px #565656;
    border: 2px solid #ddd;
    position: relative;
    left: -2px;
    -moz-border-radius: 25px;
    -webkit-border-radius: 25px;
    border-radius: 25px;
    -moz-box-shadow: 2px 2px 3px #696969;
    -webkit-box-shadow: 2px 2px 3px #696969;
    box-shadow: 2px 2px 3px #696969;
    margin-bottom: 5px;
    padding: 3px 0;
    text-align: center;
}

.band-members em {
    font-family: "Fira Sans Light Italic", "Helvetica Neue", Helvetica, Arial, sans-serif;
    padding-left: 0;
    display: inline-block;
}

#garyL {
    background: #f2374d;
    background: -webkit-linear-gradient(top, #cf061d, #f2374d);
    background:    -moz-linear-gradient(top, #cf061d, #f2374d);
    background:     -ms-linear-gradient(top, #cf061d, #f2374d);
    background:      -o-linear-gradient(top, #cf061d, #f2374d);
    background:         linear-gradient(to bottom, #cf061d, #f2374d);
}

#markM, #paulW {
    background: #fcbf17;
    background: -webkit-linear-gradient(top, #fcbf17, #fdd66a);
    background:    -moz-linear-gradient(top, #fcbf17, #fdd66a);
    background:     -ms-linear-gradient(top, #fcbf17, #fdd66a);
    background:      -o-linear-gradient(top, #fcbf17, #fdd66a);
    background:         linear-gradient(to bottom, #fcbf17, #fdd66a);
}

#michaelM, #jonnyQ {
    background: #6c9bde;
    background: -webkit-linear-gradient(top, #2779eb, #6c9bde);
    background:    -moz-linear-gradient(top, #2779eb, #6c9bde);
    background:     -ms-linear-gradient(top, #2779eb, #6c9bde);
    background:      -o-linear-gradient(top, #2779eb, #6c9bde);
    background:         linear-gradient(to bottom, #2779eb, #6c9bde);
}

#nathanC {
    background: #73b84d;
    background: -webkit-linear-gradient(top, #24a624, #73b84d);
    background:    -moz-linear-gradient(top, #24a624, #73b84d);
    background:     -ms-linear-gradient(top, #24a624, #73b84d);
    background:      -o-linear-gradient(top, #24a624, #73b84d);
    background:         linear-gradient(to bottom, #24a624, #73b84d);
}

#tomS {
    background: #7ba6ad;
    background: -webkit-linear-gradient(top, #4a95ab, #7ba6ad);
    background:    -moz-linear-gradient(top, #4a95ab, #7ba6ad);
    background:     -ms-linear-gradient(top, #4a95ab, #7ba6ad);
    background:      -o-linear-gradient(top, #4a95ab, #7ba6ad);
    background:         linear-gradient(to bottom, #4a95ab, #7ba6ad);
}

#johnnyM {
    background: #9c79bd;
    background: -webkit-linear-gradient(top, #8952bd, #9c79bd);
    background:    -moz-linear-gradient(top, #8952bd, #9c79bd);
    background:     -ms-linear-gradient(top, #8952bd, #9c79bd);
    background:      -o-linear-gradient(top, #8952bd, #9c79bd);
    background:         linear-gradient(to bottom, #8952bd, #9c79bd);
}

Body:
Why not just pass the whole object to your init function?

You don't need AJAX if you're going to use a static JSON object.

init({"dummy" : "","yearStarted" : 1994, "row" : [{"id" : "garyL","name" : "One","yearJoined" : 2007,"yearLeft" : 2015},{"id" : "markM","name" : "Two","yearJoined" : 2001,"yearLeft" : 2005}]});


问:
Combine datasets of multiple HDF5 files into a virtual dataset
I have several HDF5 files that contain the same two datasets each, data and labels. These datasets are multidimensional arrays and the first is dimension is the same for both.

I would like to combine the HDF5 files into one file and I think the best way would be to create a virtual dataset, [h5py reference], [HDF5 tutorial in C++]. However, I have not found any example in Python and h5py.

Is there any alternative to the virtual dataset or do you know of any example using h5py?

答:
Someone has tried it. Example is here, but unfortunately I was not able to get it to work and also it seems to be syntactically incorrect. https://github.com/aaron-parsons/h5py/blob/1e467f6db3df23688e90f44bde7558bde7173a5b/docs/vds.rst#using-the-vds-feature-from-h5py</p>

```<code>f = h5py.File("VDS.h5", 'w', libver='latest')
file_names_to_concatenate = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5.File(file_names_to_concatenate[0],'r')[entry_key].shape # get the first ones shape.

TGT = h5.VirtualTarget(outfile, outkey, shape=(len(file_names_to_concatenate, ) + sh)

for i in range(num_projections):
    VSRC = h5.VirtualSource(file_names_to_concatenate[i]), entry_key, shape=sh)
    VM = h5.VirtualMap(VSRC[:,:,:], TGT[i:(i+1):1,:,:,:],dtype=np.float)
    VMlist.append(VM)

d = f.create_virtual_dataset(VMlist=VMlist,fillvalue=0)
f.close()
</code>```

Body:
Someone has tried it. Example is here, but unfortunately I was not able to get it to work and also it seems to be syntactically incorrect. https://github.com/aaron-parsons/h5py/blob/1e467f6db3df23688e90f44bde7558bde7173a5b/docs/vds.rst#using-the-vds-feature-from-h5py

f = h5py.File("VDS.h5", 'w', libver='latest')
file_names_to_concatenate = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5.File(file_names_to_concatenate[0],'r')[entry_key].shape # get the first ones shape.

TGT = h5.VirtualTarget(outfile, outkey, shape=(len(file_names_to_concatenate, ) + sh)

for i in range(num_projections):
    VSRC = h5.VirtualSource(file_names_to_concatenate[i]), entry_key, shape=sh)
    VM = h5.VirtualMap(VSRC[:,:,:], TGT[i:(i+1):1,:,:,:],dtype=np.float)
    VMlist.append(VM)

d = f.create_virtual_dataset(VMlist=VMlist,fillvalue=0)
f.close()


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答:
Because the structure of the code can be difficult to follow.

This

```<code>y:
// do more stuff
goto x

p:
// do stuff
// then done
goto y;

x:
  // do a bunch of stuff
  if (...)
      goto y;
  else
      goto p;

done:
</code>```

is much less clear than

```<code>int main()
{
    x();
}

function p()
{
    if (...)
    {
         return;
    }
}

function x()
{
    if (...)
    {
         return;
    }
    else
    {
         p();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

Body:
Because the structure of the code can be difficult to follow.

This

y:
// do more stuff
goto x

p:
// do stuff
// then done
goto y;

x:
  // do a bunch of stuff
  if (...)
      goto y;
  else
      goto p;

done:

is much less clear than

int main()
{
    x();
}

function p()
{
    if (...)
    {
         return;
    }
}

function x()
{
    if (...)
    {
         return;
    }
    else
    {
         p();
    }
}

OwnerDisplayName: Doug T.


问:
AS3: Can we skip an optional parameter and assign value to the parameter after the skipped one?
Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

```<code>public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}
</code>```

I can easily call the function with a message and a title:

```<code> Dialog("HELLO","Intro");
</code>```

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

```<code>Dialog("HELLO",,dialogsize);
</code>```

Is it possible to skip some optional parameters without using (rest) parameter?

答:
I would use a valued object instead of an object to have more control over the contents:

```<code>// DialogVO.as
package
{
    public class DialogVO
    {
        public var message : String;
        public var title : String;
        public var size : int;
    }
}
</code>```

```<code>// Test.as
public function createDialog(vo : DialogVO) : void
{
    if(vo.title)
        // write code for title here

    if(vo.message)
        // write code for meassage here

    if(vo.size)
        // write code for size here
}
</code>```

```<code>// test your method
var dialogData : DialogVO = new DialogVO();
    dialogData.message = "This is the message";
    dialogData.size = 92;

createDialog(dialogData);
</code>```

Body:
Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}

I can easily call the function with a message and a title:

 Dialog("HELLO","Intro");

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

Dialog("HELLO",,dialogsize);

Is it possible to skip some optional parameters without using (rest) parameter?

Body:
I would use a valued object instead of an object to have more control over the contents:

// DialogVO.as
package
{
    public class DialogVO
    {
        public var message : String;
        public var title : String;
        public var size : int;
    }
}

// Test.as
public function createDialog(vo : DialogVO) : void
{
    if(vo.title)
        // write code for title here

    if(vo.message)
        // write code for meassage here

    if(vo.size)
        // write code for size here
}

// test your method
var dialogData : DialogVO = new DialogVO();
    dialogData.message = "This is the message";
    dialogData.size = 92;

createDialog(dialogData);


问:
Part of dateRangeInput ui gets hidden under the shiny dashboard header
Is there a way to always make the ui of dateRangeInput fully visible?
 Minimising the window and clicking on the date, this happens:

```<code>library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Home", tabName = "Home")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "Home",
        fluidRow(
          br(),
          br(),
          br(),
          br(),
          br(),
          br(),
          box(
            dateRangeInput("daterange", "Date range:", start = "2001-01-01", end = "2010-12-31"),
            title="Select Dates", solidHeader=T, status="primary",width=6,height=250)
        )
      )
    )
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)
</code>```

答:
You can use css to make the z-index of .dropdown-menu more than that of dashboard header using the following tag:

tags$div(tags$style(HTML( ".dropdown-menu{z-index:10000 !important;}")))

In your apps ui it would be as follows:

```<code>ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Home", tabName = "Home")
    )
  ),
  dashboardBody(

    tags$div(tags$style(HTML( ".dropdown-menu{z-index:10000 !important;}"))),

    tabItems(
      tabItem(tabName = "Home",
              fluidRow(
                br(),
                br(),
                br(),
                br(),
                br(),
                br(),
                box(
                  dateRangeInput("daterange", "Date range:", start = "2001-01-01", end = "2010-12-31"),
                  title="Select Dates", solidHeader=T, status="primary",width=6,height=250)
              )
      )
    )
  )
)
</code>```

You would get something like this:

Hope it helps!

Body:
Is there a way to always make the ui of dateRangeInput fully visible?
 Minimising the window and clicking on the date, this happens:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Home", tabName = "Home")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "Home",
        fluidRow(
          br(),
          br(),
          br(),
          br(),
          br(),
          br(),
          box(
            dateRangeInput("daterange", "Date range:", start = "2001-01-01", end = "2010-12-31"),
            title="Select Dates", solidHeader=T, status="primary",width=6,height=250)
        )
      )
    )
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)

Body:
You can use css to make the z-index of .dropdown-menu more than that of dashboard header using the following tag:

tags$div(tags$style(HTML( ".dropdown-menu{z-index:10000 !important;}")))

In your apps ui it would be as follows:

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Home", tabName = "Home")
    )
  ),
  dashboardBody(

    tags$div(tags$style(HTML( ".dropdown-menu{z-index:10000 !important;}"))),

    tabItems(
      tabItem(tabName = "Home",
              fluidRow(
                br(),
                br(),
                br(),
                br(),
                br(),
                br(),
                box(
                  dateRangeInput("daterange", "Date range:", start = "2001-01-01", end = "2010-12-31"),
                  title="Select Dates", solidHeader=T, status="primary",width=6,height=250)
              )
      )
    )
  )
)

You would get something like this:

Hope it helps!


问:
Detect backspace in empty UITextField
Is there any way to detect when the Backspace/Delete key is pressed in the iPhone keyboard on a UITextField that is empty?  I want to know when Backspace is pressed only if the UITextField is empty.

Based on the suggestion from @Alex Reynolds in a comment, I've added the following code while creating my text field:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(handleTextFieldChanged:)
              name:UITextFieldTextDidChangeNotification
            object:searchTextField];
</code>```

This notification is received (handleTextFieldChanged function is called), but still not when I press the Backspace key in an empty field.  Any ideas?

There seems to be some confusion around this question.  I want to receive a notification when the Backspace key is pressed.  That's it.  But the solution must also work when the UITextField is already empty.

答:
please use below code it will help you to detect keyboard delete key even if you textfield is empty.

Objective C :

- (BOOL)keyboardInputShouldDelete:(UITextField *)textField { return YES; }

Swift :

```<code>func keyboardInputShouldDelete(_ textField: UITextField) -> Bool { return true }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Detect backspace in empty UITextField

Body:
Is there any way to detect when the Backspace/Delete key is pressed in the iPhone keyboard on a UITextField that is empty?  I want to know when Backspace is pressed only if the UITextField is empty.

Based on the suggestion from @Alex Reynolds in a comment, I've added the following code while creating my text field:

[[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(handleTextFieldChanged:)
              name:UITextFieldTextDidChangeNotification
            object:searchTextField];

This notification is received (handleTextFieldChanged function is called), but still not when I press the Backspace key in an empty field.  Any ideas?

There seems to be some confusion around this question.  I want to receive a notification when the Backspace key is pressed.  That's it.  But the solution must also work when the UITextField is already empty.

Body:
please use below code it will help you to detect keyboard delete key even if you textfield is empty.

Objective C :

- (BOOL)keyboardInputShouldDelete:(UITextField *)textField { return YES; }

Swift :

func keyboardInputShouldDelete(_ textField: UITextField) -> Bool { return true }


问:
python fabric multiple commands
I'm trying to understand how fabric is working with multiple commands on one machine.
I need to run several commands on each host (thousands of hosts) and would like to know what would be best.

Using multiple runs:

```<code>res_1 = run(command_1)
res_2 = run(command_2)
...
...
res_n = run(command_n)
</code>```

Or:

```<code>res = run(command_1 && command_2 && ... command_n)
res.splitlines()
res_1 = res[0]
res_2 = res[1]
...
...
res_n = res[n-1]
</code>```

What I want to know is how fabric handles multiple runs, will it open multiple sessions or do all commands in the same session?

答:
Regardless of whether you use multiple run calls or a single run call with &&, AFAIK, fabric will open only one network connection. The difference between the two is that each new run executes in a different environment. For example you can try this.

```<code>run('ls')
run('cd /tmp/')
run('ls')
</code>```

Both times it will show you a listing of your home directory. But if you try this

```<code>run('ls')
run('cd /tmp/ && ls')
</code>```

It will show you your home directory the first time, followed by a listing of /tmp/. Thus if you want the state to be preserved from one command to another you should do run('cmd1 && cmd1') but if you are not bothered about it, you should use multiple run calls.

Title: python fabric multiple commands

Body:
I'm trying to understand how fabric is working with multiple commands on one machine.
I need to run several commands on each host (thousands of hosts) and would like to know what would be best.

Using multiple runs:

res_1 = run(command_1)
res_2 = run(command_2)
...
...
res_n = run(command_n)

Or:

res = run(command_1 && command_2 && ... command_n)
res.splitlines()
res_1 = res[0]
res_2 = res[1]
...
...
res_n = res[n-1]

What I want to know is how fabric handles multiple runs, will it open multiple sessions or do all commands in the same session?

Body:
Regardless of whether you use multiple run calls or a single run call with &&, AFAIK, fabric will open only one network connection. The difference between the two is that each new run executes in a different environment. For example you can try this.

run('ls')
run('cd /tmp/')
run('ls')

Both times it will show you a listing of your home directory. But if you try this

run('ls')
run('cd /tmp/ && ls')

It will show you your home directory the first time, followed by a listing of /tmp/. Thus if you want the state to be preserved from one command to another you should do run('cmd1 && cmd1') but if you are not bothered about it, you should use multiple run calls.


问:
Comparing objects
I have a class it contains some string members, some double members and some array objects.

I create two objects of this class, is there any simplest, efficient way of comparing these objects and say their equal? Any suggestions?

I know how to write a compare function, but will it be time consuming.

答:
Since these are objects my guess is that you will have to override the Equals method for objects. Otherwise the Equals method will give you ok only if both objects refering to the same object.

I know this is not the answer you want. But since there is little number of properties in your class you can easily override the method.

Title: Comparing objects


问:
How to use page.php?id={id} routes on laravel
I'm rewriting an website in laravel, and for the sake of the SEO, I have to create some routes that will do a 301 redirect in case the visitor get to access the old style links of the website:

Using Laravel 5.4 + PHP 7.0

For example:

Old links: www.website.com/category.php?category={id}

will redirect to:

New Link: www.website.com/category/{category-name}

But when I create a route like this on laravel, it doesn't work:

```<code>Route::get('/category.php?category={id}', function ($id) {
 // Old route style, search new route and do the redirect.
});
</code>```

If I remove the "?" it kinda works, but then it won't target my old links, cause there's no "?" in the url.

Is this supported on laravel ?

If it isn't, what would be a good way to achieve this?

答:
What is your controller?
You can get your controller resource
And all those route will be added to your route:list with no pain.</p>

```<code>Route:: resource ('category', 'controller');
</code>```

Body:
I'm rewriting an website in laravel, and for the sake of the SEO, I have to create some routes that will do a 301 redirect in case the visitor get to access the old style links of the website:

Using Laravel 5.4 + PHP 7.0

For example:

Old links: www.website.com/category.php?category={id}

will redirect to:

New Link: www.website.com/category/{category-name}

But when I create a route like this on laravel, it doesn't work:

Route::get('/category.php?category={id}', function ($id) {
 // Old route style, search new route and do the redirect.
});

If I remove the "?" it kinda works, but then it won't target my old links, cause there's no "?" in the url.

Is this supported on laravel ?

If it isn't, what would be a good way to achieve this?

Body:
What is your controller?
You can get your controller resource
And all those route will be added to your route:list with no pain.

Route:: resource ('category', 'controller');


问:
Mail not send using PHPMailer from production server
Is it necessary to turn on the less secure apps of my gmail account? why I'm asking this means am trying to do send email in production server.
I used PHPHMailer and I tried without turn on my less secure apps of my email account, I get error like below

SMTP ERROR: Password command failed: 534-5.7.14

SMTP Error: Could not authenticate.

what can I do?

答:
You need to enable less secure apps if you would use SMTP with classic authentication mechanisms.

Otherwise you can use XOAUTH2 with PHPMailer: https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2


问:
"Any public static members of XmlDocument are thread safe. Any instance members are not guaranteed to be thread safe" : yes, but
I see in the XmlDocument class documentation on MSDN that

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Same thing for the XmlNodeList class.

I am using those classes in the following context. Inside a Parallel.Foreach I do :

```<code>X MyX = new X();
string XMLstring = MyX.GetXML(ID, true);
XmlDocument doc = new XmlDocument();
doc.LoadXml(XMLstring);
XmlNodeList nodeList = doc.SelectNodes("blah/secondblah");
</code>```

where X is defined in a library the IT's are providing to me and where ID is an int (roughly on which I loop).

This has been tested thoroughly in a non parallel context, the strings produced by GetXML are indeed correct, the corresponding XmlDocument as well, and "parsing" it via XmlNodeList provides the expected results.

Now, it this parallel context and assuming that X and GetXML are indeed thread-safe, does the fact that I new an XmlDocument in every loop ensure thread-safety or not ? I mean, how can I know that the string member (first of all is there such a string ? as I don't see any string property in the document) of XmlDocument receiving the LoadXml is static or not ?

I suppose I don't really understand the bit of MSDN documentation I am quoting above ...

答:
The documentation means that any methods that are static (which would look like XmlDocument.MethodCall are thread-safe. That isn't relevant to you - you aren't calling any of those. Other methods (e.g. against doc) are not static - so they are not guaranteed to be thread-safe.

Your code will be 100% fine, as long as doc (and nodeList and other 'non thread-safe' variables) are used solely within the context of a single thread.

So if you populated doc before the Parallel.ForEach and then used doc inside the Parallel.ForEach - that won't work.

But if you populate and used doc inside the Parallel.ForEach you will be fine (since each thread will get its 'own doc'- thus thread-safety won't be an issue).

To be 100% sure, you'd need to post the entire method (including the Parallel.ForEach call) for us to have a look at.

Body:
I see in the XmlDocument class documentation on MSDN that

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Same thing for the XmlNodeList class.

I am using those classes in the following context. Inside a Parallel.Foreach I do :

X MyX = new X();
string XMLstring = MyX.GetXML(ID, true);
XmlDocument doc = new XmlDocument();
doc.LoadXml(XMLstring);
XmlNodeList nodeList = doc.SelectNodes("blah/secondblah");

where X is defined in a library the IT's are providing to me and where ID is an int (roughly on which I loop).

This has been tested thoroughly in a non parallel context, the strings produced by GetXML are indeed correct, the corresponding XmlDocument as well, and "parsing" it via XmlNodeList provides the expected results.

Now, it this parallel context and assuming that X and GetXML are indeed thread-safe, does the fact that I new an XmlDocument in every loop ensure thread-safety or not ? I mean, how can I know that the string member (first of all is there such a string ? as I don't see any string property in the document) of XmlDocument receiving the LoadXml is static or not ?

I suppose I don't really understand the bit of MSDN documentation I am quoting above ...


问:
pull property object as parent object
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

```<code>let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]
</code>```

How can I group school first? I need the format to be like this

```<code>[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]
</code>```

答:
You could create an hash object that stores each school at its id, so you can push the students to it:

```<code>var hash=x.reduce(function(obj,el){
 (obj[el.school.id]=obj[el.school.id]||{id:el.school.id,name:el.school.name,data:[]}).data.push({name:el.name,age:el.age});
  return obj;
},{});

var arr=Object.values(hash);
</code>```

http://jsbin.com/vedajijiye/edit?console

Title: pull property object as parent object

Body:
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]

How can I group school first? I need the format to be like this

[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]

Body:
You could create an hash object that stores each school at its id, so you can push the students to it:

var hash=x.reduce(function(obj,el){
 (obj[el.school.id]=obj[el.school.id]||{id:el.school.id,name:el.school.name,data:[]}).data.push({name:el.name,age:el.age});
  return obj;
},{});

var arr=Object.values(hash);

http://jsbin.com/vedajijiye/edit?console


问:
Cannot use '&' operator in Gnu AS expression
I would like to get the address of a variable and'ed by 4096 (which would correspond to the address of its memory page). Since this is something that can be computed offline I did something that looks like this (v is the variable and vpage should contain the address of its page):

```<code>    .data
    v:        .zero 0x100
    vpage:  .long v & 0xfffff000
</code>```

Trying to compile this file with the x86 assembler results in the following error:

```<code>test.S: Assembler messages:
test.S:3: Error: invalid sections for operation on `v' and `L0'
</code>```

Why would GAS refuse to compute this? Now the weird part: replace '&' by "+" and the code will compile and the address will even be correctly computed after link. Any hint on the why of this behavior or how to fix it would be very welcome.

答: In Intel syntax you can use _AND, _OR, _NOT, _SHL, _SHR and maybe others to accomplish this.  This might work in GNU's assembler as well.

Body:
I would like to get the address of a variable and'ed by 4096 (which would correspond to the address of its memory page). Since this is something that can be computed offline I did something that looks like this (v is the variable and vpage should contain the address of its page):

    .data
    v:        .zero 0x100
    vpage:  .long v & 0xfffff000

Trying to compile this file with the x86 assembler results in the following error:

test.S: Assembler messages:
test.S:3: Error: invalid sections for operation on `v' and `L0'

Why would GAS refuse to compute this? Now the weird part: replace '&' by "+" and the code will compile and the address will even be correctly computed after link. Any hint on the why of this behavior or how to fix it would be very welcome.


问:
:eq() selector returns undefined
I'm learning jQuery and I get this 'undefined' error when using :eq() selector. Here is the HTML:

```<code><!DOCTYPE html>
<html>
<head>
    <title>:eq() selector example</title>
</head>
<body>
    <div>
        <button>Button #1</button>
        <button>Button #2</button>
        <button>Button #3</button>
        <button>Button #4</button>
        <button>Button #5</button>
        <button>Button #6</button>
    </div>

    <script src="jquery-2.1.4.min.js"></script>
    <script src="script.js"></script>
</body>
</html>
</code>```

And the script:

```<code>var myButton = $('button:eq(5)');
console.log(myButton.textContent);
</code>```

When I use var myButton = $('button')[5]; everything is fine though.

答:
$('button')[5] return a reference of DOM element which has textContent property thus it works.

However $('button:eq(5)') is a jQuery object which doesn't have the property thus undefined is returned.

Use .text() function with jQuery object.

```<code>var text = $('button:eq(5)').text()
</code>```

Title: :eq() selector returns undefined

Body:
I'm learning jQuery and I get this 'undefined' error when using :eq() selector. Here is the HTML:

<!DOCTYPE html>

    <title>:eq() selector example</title>

        <button>Button #1</button>
        <button>Button #2</button>
        <button>Button #3</button>
        <button>Button #4</button>
        <button>Button #5</button>
        <button>Button #6</button>

And the script:

var myButton = $('button:eq(5)');
console.log(myButton.textContent);

When I use var myButton = $('button')[5]; everything is fine though.

Body:
$('button')[5] return a reference of DOM element which has textContent property thus it works.

However $('button:eq(5)') is a jQuery object which doesn't have the property thus undefined is returned.

Use .text() function with jQuery object.

var text = $('button:eq(5)').text()


答:
You can use the reduce() method:

let data = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
];
let schools = data.reduce((acc, x) => {
  // Check if the school already exists
  let school = acc.find(y => y.id === x.school.id);
  if (!school) {
    // If not, the current school is the school of the current person
    school = x.school;
    school.data = [];
    acc.push(school);
  } else {
    // Prevent duplication of school objects with the same id
    x.school = school;
  }
  school.data.push(x);
  return acc;
}, []);
console.log(schools);```

Title: pull property object as parent object


问:
Mock an object created in the middle of a method
I know that creating an instance of a Class in the middle of a method it's a bad practice since it makes code hard to test.
But I can't refactor the code, so I need to find a way to mock an Object created with new in the middle of a method under test.

Used Frameworks: PHPUnit, Mockery, WP_Mock

Example: Here I need to mock the get_second_string() method from the instance of the class ExternalClass

```<code>Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}
</code>```

答:
You can not mock entire object.
But with phpunit you can do something like this:

```<code> $f = $this->getMockBuilder(<your_class>)->disableOriginalConstructor()
      ->setMethods(array(
          <mocked_method_1>, <mocked_method_2>
       ))->getMock();
</code>```

This way, newly created object ommits constructor and you specify which method are going to behave normally and which you mock.

in testing you can specify what the method/s will return, like this:

```<code>$f->method(<mocked_method_1>)->willReturn(<dummy_data>);
</code>```

using this, you will not test the mocked object in any way, but can test method which is creating the object..

Body:
I know that creating an instance of a Class in the middle of a method it's a bad practice since it makes code hard to test.
But I can't refactor the code, so I need to find a way to mock an Object created with new in the middle of a method under test.

Used Frameworks: PHPUnit, Mockery, WP_Mock

Example: Here I need to mock the get_second_string() method from the instance of the class ExternalClass

Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}

Body:
You can not mock entire object.
But with phpunit you can do something like this:

 $f = $this->getMockBuilder(<your_class>)->disableOriginalConstructor()
      ->setMethods(array(
          <mocked_method_1>, <mocked_method_2>
       ))->getMock();

This way, newly created object ommits constructor and you specify which method are going to behave normally and which you mock.

in testing you can specify what the method/s will return, like this:

$f->method(<mocked_method_1>)->willReturn(<dummy_data>);

using this, you will not test the mocked object in any way, but can test method which is creating the object..


答: Yes it is thread safe. You are not sharing anything between threads. I have used similar XmlDocument code in large multi-threaded applications without problems. In theory there could be private static data in XmlDocument that we don't know about which is not thread safe, but my experience is that this is not the case. I think the MSDN documentation is implying that Microsoft have made sure that any static stuff which may be shared across threads, is in fact thread safe.</p>

Title: "Any public static members of XmlDocument are thread safe. Any instance members are not guaranteed to be thread safe" : yes, but


问:
Files in dir that is also a VOLUME?
I am just curious. To List files in exited container I can use docker diff, but if target directory is also a volume, such as:

```<code>RUN mkdir /target
VOLUME /target
</code>```

Then docker diff won't show anything. Does that mean that /target is left empty after container exits? How can I check the contents of that /target in exited container?

答:
docker diff doesn't show any changes because this command inspect changes to files or directories on a container filesystem.

A volume, referring to Docker documentation, is this:

A data volume is a specially-designated directory within one or more containers that bypasses the Union File System.

This explains why docker diff doesn't show changes inside a volume.

Does that mean that /target is left empty after container exits?

No. Data volumes persist even if the container is deleted.

How can I check the contents of that /target in exited container?

You can find container volumes using docker inspect command.

docker inspect container_name

The output will be something like this, where Source specifies location of the volume in the host machine.

```<code>...
"Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]
...
</code>```

I do mkdir /target before making it a volume. So what happens to the contents of this dir if it already exists inside of container in this case

If the dir existed previously, contents are copied into the new created volume. So, if you make your directory a volume, you'll not lose your changes.

Title: Files in dir that is also a VOLUME?

Body:
I am just curious. To List files in exited container I can use docker diff, but if target directory is also a volume, such as:

RUN mkdir /target
VOLUME /target

Then docker diff won't show anything. Does that mean that /target is left empty after container exits? How can I check the contents of that /target in exited container?

Body:
docker diff doesn't show any changes because this command inspect changes to files or directories on a container filesystem.

A volume, referring to Docker documentation, is this:

A data volume is a specially-designated directory within one or more containers that bypasses the Union File System.

This explains why docker diff doesn't show changes inside a volume.

Does that mean that /target is left empty after container exits?

No. Data volumes persist even if the container is deleted.

How can I check the contents of that /target in exited container?

You can find container volumes using docker inspect command.

docker inspect container_name

The output will be something like this, where Source specifies location of the volume in the host machine.

...
"Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]
...

I do mkdir /target before making it a volume. So what happens to the contents of this dir if it already exists inside of container in this case

If the dir existed previously, contents are copied into the new created volume. So, if you make your directory a volume, you'll not lose your changes.


问:
Angular build failure when creating production build
I am having a below error while running the ng build --prod this is compile work for ng build and ng server

ERROR in ng:{path}/dashboard/promotions/add-promotion/promotion-form.component.html (33,13): Property 'controls' does not exist on type 'AbstractControl'.

```<code>ERROR in ng:{path}/dashboard/promotions/add-promotion/promotion-form.component.html (33,13): Property 'controls' does not exist on type 'AbstractControl'.

ERROR in ng:{path}/dashboard/promotions/add-promotion/promotion-form.component.html (45,13): Property 'controls' does not exist on type 'AbstractControl'.

ERROR in ng://{path}/dashboard/promotions/add-promotion/promotion-form.component.html (45,13): Property 'controls' does not exist on type 'AbstractControl'.
</code>```

Below is my component form builder and the html

```<code> this.promotionForm = this.fb.group({
      'id':[null],
      'title': [null, Validators.compose([Validators.required, Validators.maxLength(50),
        Validators.pattern('[a-zA-Z ]*'), Validators.required,Validators.minLength(1)])],
      'description': [null, Validators.compose([Validators.required])],
      'imageSrc': [null, [Validators.required]],
      'contactPerson' : this.fb.group({
                          'name': [null, [Validators.required]],
                          'email': [null, [Validators.required,Validators.pattern(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)]],
                          'phone': [null, [Validators.required,
                            Validators.pattern(/^[0-9]{10}$/)]]
                        }),
    });
</code>```

Html for the component

```<code><form [formGroup] ="promotionForm" (submit)="submit(promotionForm.value)">
  <--Top Form fields-->
  <table class="full-width" cellspacing="0">
    <tr >
      <div formGroupName="contactPerson">
        <td >
          <md-input-container class="full-width">
            <input mdInput
                   formControlName="name"
                   placeholder="Sales Person" [ngModel]="promoData?.contactPerson.name"
                   [formControl]="promotionForm.controls['name']">
            <div *ngIf="!promotionForm.controls.contactPerson.controls.name.valid
                            && (promotionForm.controls.contactPerson.controls.name.dirty)">
              <span class="primary">Please enter a valid name.</span>
            </div>
          </md-input-container>
        </td>
        <td>
          <md-input-container class="full-width">
            <input mdInput formControlName="phone"
                   placeholder="Mobile Number" [ngModel]="promoData?.contactPerson.phone"
            [formControl]="promotionForm.controls['phone']">
            <div *ngIf="!promotionForm.controls.contactPerson.controls.phone.valid
                            && (promotionForm.controls.contactPerson.controls.phone.dirty)">
              <span class="primary">Please enter a valid phone number.</span>
            </div>
          </md-input-container>
        </td>
        <td>
          <md-input-container class="full-width">
            <input mdInput formControlName="email"
                   placeholder="Email Address" [ngModel]="promoData?.contactPerson.email">

            <div *ngIf="!promotionForm.controls.contactPerson.controls.email.valid
                            && (promotionForm.controls.contactPerson.controls.email.dirty)">
              <span class="primary">Please enter a valid email.</span>
            </div>
          </md-input-container>
        </td>
      </div>
    </tr>
  </table>
....</form>
</code>```

答:
Generally, you shouldn't access controls like that, this is what you should do :

change

```<code> promotionForm.controls['name']
</code>```

to

```<code> promotionForm.get('name')
</code>```

and change

```<code>  promotionForm.controls.contactPerson.controls.phone
</code>```

to

```<code> promotionForm.get('contactPerson.phone')
</code>```

find others and fix them as well.

Body:
I am having a below error while running the ng build --prod this is compile work for ng build and ng server

ERROR in ng:{path}/dashboard/promotions/add-promotion/promotion-form.component.html (33,13): Property 'controls' does not exist on type 'AbstractControl'.

ERROR in ng:{path}/dashboard/promotions/add-promotion/promotion-form.component.html (33,13): Property 'controls' does not exist on type 'AbstractControl'.

ERROR in ng:{path}/dashboard/promotions/add-promotion/promotion-form.component.html (45,13): Property 'controls' does not exist on type 'AbstractControl'.

ERROR in ng://{path}/dashboard/promotions/add-promotion/promotion-form.component.html (45,13): Property 'controls' does not exist on type 'AbstractControl'.

Below is my component form builder and the html

 this.promotionForm = this.fb.group({
      'id':[null],
      'title': [null, Validators.compose([Validators.required, Validators.maxLength(50),
        Validators.pattern('[a-zA-Z ]*'), Validators.required,Validators.minLength(1)])],
      'description': [null, Validators.compose([Validators.required])],
      'imageSrc': [null, [Validators.required]],
      'contactPerson' : this.fb.group({
                          'name': [null, [Validators.required]],
                          'email': [null, [Validators.required,Validators.pattern(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)]],
                          'phone': [null, [Validators.required,
                            Validators.pattern(/^[0-9]{10}$/)]]
                        }),
    });

Html for the component

<form [formGroup] ="promotionForm" (submit)="submit(promotionForm.value)">
  <--Top Form fields-->

          <md-input-container class="full-width">
            <input mdInput
                   formControlName="name"
                   placeholder="Sales Person" [ngModel]="promoData?.contactPerson.name"
                   [formControl]="promotionForm.controls['name']">

              Please enter a valid name.

          </md-input-container>

          <md-input-container class="full-width">
            <input mdInput formControlName="phone"
                   placeholder="Mobile Number" [ngModel]="promoData?.contactPerson.phone"
            [formControl]="promotionForm.controls['phone']">

              Please enter a valid phone number.

          </md-input-container>

          <md-input-container class="full-width">
            <input mdInput formControlName="email"
                   placeholder="Email Address" [ngModel]="promoData?.contactPerson.email">

              Please enter a valid email.

          </md-input-container>

....</form>

Body:
Generally, you shouldn't access controls like that, this is what you should do :

change

 promotionForm.controls['name']

to

 promotionForm.get('name')

and change

  promotionForm.controls.contactPerson.controls.phone

to

 promotionForm.get('contactPerson.phone')

find others and fix them as well.


问:
Exim - Disable VRFY and EXPN?
A penetration test has been run on one of my servers that runs Exim for mail and they have this complaint:

Description: The Mailserver on this host answers to VRFY and/or EXPN
  requests. VRFY and EXPN ask the server for information about an
  address. They are inherently unusable through firewalls, gateways,
  mail exchangers for part-time hosts, etc. OpenVAS suggests that, if
  you really want to publish this type of information, you use a
  mechanism that legitimate users actually know about, such as Finger or
  HTTP.

Solution: Disable VRFY and/or EXPN on your Mailserver. For postfix add
  'disable_vrfy_command=yes' in 'main.cf'. For Sendmail add the option
  'O PrivacyOptions=goaway'.

Unfortunately it's Exim and not Sendmail/postfix. Their output shows that running the EXPN command generates the response "550 Administrative prohibition". I tested this with telnet and it is correct.

Is there a way to stop it from replying at all? Thanks in advance

答:
RFC 2505 states:

Both SMTP VRFY and EXPN provide means for a potential spammer to test whether the addresses on his list are valid (VRFY) and even get more addresses (EXPN). Therefore, the MTA SHOULD control who is is allowed to issue these commands. This may be "on/off" or it may use access lists similar to those mentioned previously.

Note that the "VRFY" command is required according to RFC821, 1.

The response can, though, be "252 Argument not checked" to represent
"off" or blocked via an access list. This should be the default.

According to the exim documentation here http://www.exim.org/exim-html-current/doc/html/spec_html/ch-smtp_processing.html

"When Exim receives a VRFY or EXPN command on a TCP/IP connection, it runs the ACL specified by acl_smtp_vrfy or acl_smtp_expn (as appropriate) in order to decide whether the command should be accepted or not.

When no ACL is defined for VRFY, or if it rejects without setting an explicit response code, the command is accepted (with a 252 SMTP response code) in order to support awkward clients that do a VRFY before every RCPT".

To me, this suggests always return a 252, rather than turning if off completely.

Title: Exim - Disable VRFY and EXPN?


问:
Error while compiling app

Error:A problem occurred configuring root project 'Myapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Timeout waiting to lock artifact cache (C:\Users\prasid444.gradle\caches\modules-2). It is currently in use by another Gradle instance.
       Owner PID: 5232
       Our PID: 7292
       Owner Operation: resolve configuration ':classpath'
       Our operation: resolve configuration ':classpath'
       Lock file: C:\Users\prasid444.gradle\caches\modules-2\modules-2.lock

答: Delete everything in ~/.gradle/caches directory and restart/rebuild the project.

Title: Error while compiling app


问:
No file at UIImagePickerControllerMediaURL after upgrading to Xcode 7
After upgrading my Swift video app to Swift 2.0/Xcode 7/iOS 9, everything works fine except getting videos from UIImagePickerController. All permissions check out for camera and library. I can get to both and record a new video or select an existing video from the library. However, when the delegate method imagePickerController:didFinishPickingMediaWithInfo is called, an NSFileManager tells me there is no file at the UIImagePickerControllerMediaURL. This is true both before and after calling dismissViewControllerAnimated on the UIImagePickerController.

It was working flawlessly before and there were no major code changes to accommodate the upgrades. I have found no other similar issues reported online, so I figure I must have screwed something up like folder permissions but I can't figure out what. I thought maybe using NSAppTransportSecurity had something to do with it as it relates to file:/// URLs, but the issue persists in iOS 7, 8, and 9 regardless of whether or not that dictionary is present in my info.plist.

If anyone can give me some leads to look into I would greatly appreciate it. I've tried this on iPhones 6, 5s, & 4s with the same result. I do recall going round and round with "kUTTypeMovie" during the Swift 2 upgrades. The "[kUTTypeMovie as String]" below is the only thing I found that Xcode would accept. That could be a weak point, but I doubt it since it seems to work as expected. The only reason I mention it is that if you don't ask for a type, the app doesn't have permission to receive it.

Additional information

I am able to use UIImagePickerController to get images from the camera/library as normal. On a whim, I thought maybe I could get around this issue by just grabbing the original video and compressing it myself, but the NSFileManager tells me that there is no file at the UIImagePickerControllerReferenceURL either. I don’t know how this could be possible unless my app is being denied access somehow.

Log using code below: THERE IS NOT a file at:
assets-library://asset/asset.MOV?id=22A4CFF1-BBC0-4084-990D-B217908F0616&ext=MOV

This is so strange that I've filed a bug report with Apple.

Relevant code here:

```<code> @IBAction func actionTakeVideo(sender: AnyObject) {
    if videoPickerController == nil {
        videoPickerController = UIImagePickerController()
        videoPickerController.delegate = self
        videoPickerController.mediaTypes = [kUTTypeMovie as String]
        videoPickerController.videoMaximumDuration = NSTimeInterval(maxVideoDuration-1)
        videoPickerController.allowsEditing = true
        videoPickerController.videoQuality = UIImagePickerControllerQualityType.TypeHigh
 }
</code>```

...

```<code>// From Library
       let status:ALAuthorizationStatus = ALAssetsLibrary.authorizationStatus()
       if status != ALAuthorizationStatus.Authorized{
           print("Library not authorized: status != ALAuthorizationStatus.Authorized")
       } else {
           self.videoPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
           self.presentViewController(self.videoPickerController, animated: true, completion: nil)
       }
</code>```

...

```<code>//From Camera
      if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
            self.videoPickerController.sourceType = UIImagePickerControllerSourceType.Camera
            self.videoPickerController.cameraDevice = UIImagePickerControllerCameraDevice.Front
            self.presentViewController(self.videoPickerController, animated: true, completion: nil)
      }
</code>```

...

```<code>//Delegate
     func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         let manager = NSFileManager.defaultManager();
         let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
         if manager.fileExistsAtPath(videoURL.absoluteString) {
             print("THERE IS a file at: \(videoURL.absoluteString)")
         } else {
             print("THERE IS NOT a file at: \(videoURL.absoluteString)") // ALWAYS LANDS HERE.
         }
     }
</code>```

UIImagePickerControllerMediaURL is like, file:///private/var/mobile/Containers/Data/Application/6754830D-ER98-31OL-GU34-78067GD908PI/tmp/trim.578E437C-EEBC-4BC5-AD5C-C351BD0822B2.MOV

答:
I know this question is quite old but I stumbled upon the same error today.

The problem is that you're getting the file URL string from videoURL.absoluteString and passing it to NSFileManager's fileExistsAtPath method instead of a path. You should get the path to the file by reading NSURL's "path" property.

The file URL as read from videoURL.absoluteString looks like this:

file:///private/var/mobile/Containers/Data/Application/6754830D-ER98-31OL-GU34-78067GD908PI/tmp/trim.578E437C-EEBC-4BC5-AD5C-C351BD0822B2.MOV

The file path as read from videoURL.path would look like this:

/private/var/mobile/Containers/Data/Application/6754830D-ER98-31OL-GU34-78067GD908PI/tmp/trim.578E437C-EEBC-4BC5-AD5C-C351BD0822B2.MOV

The following code:

```<code>    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         let manager = NSFileManager.defaultManager();
         let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
         if manager.fileExistsAtPath(videoURL.absoluteString) {
             print("THERE IS a file at: \(videoURL.absoluteString)")
         } else {
             print("THERE IS NOT a file at: \(videoURL.absoluteString)") // ALWAYS LANDS HERE.
         }
     }
</code>```

Must be changed to:

```<code>    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         let manager = NSFileManager.defaultManager();
         let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
         if manager.fileExistsAtPath(videoURL.path) {
             print("THERE IS a file at: \(videoURL.path)")
         } else {
             print("THERE IS NOT a file at: \(videoURL.path)") // ALWAYS LANDS HERE.
         }
     }
</code>```

And keeping in mind that UIImagePickerControllerMediaURL might not be present:

```<code>    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         if let videoURL = info[UIImagePickerControllerMediaURL] as? URL {
             if FileManager.default.fileExistsAtPath(videoURL.path) {
                 print("THERE IS a file at: \(videoURL.path)")
             } else {
                 print("THERE IS NOT a file at: \(videoURL.path)") // ALWAYS LANDS HERE.
             }
         }
     }
</code>```

Body:
After upgrading my Swift video app to Swift 2.0/Xcode 7/iOS 9, everything works fine except getting videos from UIImagePickerController. All permissions check out for camera and library. I can get to both and record a new video or select an existing video from the library. However, when the delegate method imagePickerController:didFinishPickingMediaWithInfo is called, an NSFileManager tells me there is no file at the UIImagePickerControllerMediaURL. This is true both before and after calling dismissViewControllerAnimated on the UIImagePickerController.

It was working flawlessly before and there were no major code changes to accommodate the upgrades. I have found no other similar issues reported online, so I figure I must have screwed something up like folder permissions but I can't figure out what. I thought maybe using NSAppTransportSecurity had something to do with it as it relates to file:/// URLs, but the issue persists in iOS 7, 8, and 9 regardless of whether or not that dictionary is present in my info.plist.

If anyone can give me some leads to look into I would greatly appreciate it. I've tried this on iPhones 6, 5s, & 4s with the same result. I do recall going round and round with "kUTTypeMovie" during the Swift 2 upgrades. The "[kUTTypeMovie as String]" below is the only thing I found that Xcode would accept. That could be a weak point, but I doubt it since it seems to work as expected. The only reason I mention it is that if you don't ask for a type, the app doesn't have permission to receive it.

Additional information

I am able to use UIImagePickerController to get images from the camera/library as normal. On a whim, I thought maybe I could get around this issue by just grabbing the original video and compressing it myself, but the NSFileManager tells me that there is no file at the UIImagePickerControllerReferenceURL either. I don’t know how this could be possible unless my app is being denied access somehow.

Log using code below: THERE IS NOT a file at:
assets-library://asset/asset.MOV?id=22A4CFF1-BBC0-4084-990D-B217908F0616&ext=MOV

This is so strange that I've filed a bug report with Apple.

Relevant code here:

 @IBAction func actionTakeVideo(sender: AnyObject) {
    if videoPickerController == nil {
        videoPickerController = UIImagePickerController()
        videoPickerController.delegate = self
        videoPickerController.mediaTypes = [kUTTypeMovie as String]
        videoPickerController.videoMaximumDuration = NSTimeInterval(maxVideoDuration-1)
        videoPickerController.allowsEditing = true
        videoPickerController.videoQuality = UIImagePickerControllerQualityType.TypeHigh
 }

...

// From Library
       let status:ALAuthorizationStatus = ALAssetsLibrary.authorizationStatus()
       if status != ALAuthorizationStatus.Authorized{
           print("Library not authorized: status != ALAuthorizationStatus.Authorized")
       } else {
           self.videoPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
           self.presentViewController(self.videoPickerController, animated: true, completion: nil)
       }

...

//From Camera
      if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
            self.videoPickerController.sourceType = UIImagePickerControllerSourceType.Camera
            self.videoPickerController.cameraDevice = UIImagePickerControllerCameraDevice.Front
            self.presentViewController(self.videoPickerController, animated: true, completion: nil)
      }

...

//Delegate
     func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         let manager = NSFileManager.defaultManager();
         let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
         if manager.fileExistsAtPath(videoURL.absoluteString) {
             print("THERE IS a file at: \(videoURL.absoluteString)")
         } else {
             print("THERE IS NOT a file at: \(videoURL.absoluteString)") // ALWAYS LANDS HERE.
         }
     }

UIImagePickerControllerMediaURL is like, file:///private/var/mobile/Containers/Data/Application/6754830D-ER98-31OL-GU34-78067GD908PI/tmp/trim.578E437C-EEBC-4BC5-AD5C-C351BD0822B2.MOV

Body:
I know this question is quite old but I stumbled upon the same error today.

The problem is that you're getting the file URL string from videoURL.absoluteString and passing it to NSFileManager's fileExistsAtPath method instead of a path. You should get the path to the file by reading NSURL's "path" property.

The file URL as read from videoURL.absoluteString looks like this:

file:///private/var/mobile/Containers/Data/Application/6754830D-ER98-31OL-GU34-78067GD908PI/tmp/trim.578E437C-EEBC-4BC5-AD5C-C351BD0822B2.MOV

The file path as read from videoURL.path would look like this:

/private/var/mobile/Containers/Data/Application/6754830D-ER98-31OL-GU34-78067GD908PI/tmp/trim.578E437C-EEBC-4BC5-AD5C-C351BD0822B2.MOV

The following code:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         let manager = NSFileManager.defaultManager();
         let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
         if manager.fileExistsAtPath(videoURL.absoluteString) {
             print("THERE IS a file at: \(videoURL.absoluteString)")
         } else {
             print("THERE IS NOT a file at: \(videoURL.absoluteString)") // ALWAYS LANDS HERE.
         }
     }

Must be changed to:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         let manager = NSFileManager.defaultManager();
         let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
         if manager.fileExistsAtPath(videoURL.path) {
             print("THERE IS a file at: \(videoURL.path)")
         } else {
             print("THERE IS NOT a file at: \(videoURL.path)") // ALWAYS LANDS HERE.
         }
     }

And keeping in mind that UIImagePickerControllerMediaURL might not be present:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
         if let videoURL = info[UIImagePickerControllerMediaURL] as? URL {
             if FileManager.default.fileExistsAtPath(videoURL.path) {
                 print("THERE IS a file at: \(videoURL.path)")
             } else {
                 print("THERE IS NOT a file at: \(videoURL.path)") // ALWAYS LANDS HERE.
             }
         }
     }


问:
How can I create sidebar menu and clickable sub menu with html css bootstrap?
This is a piece of my code for sidebar menu.I want to create dashboard and  drop down menu in left of screen. when I go on flower don't show  it's sub menu.
(i want clickable)</p>

```<code>  <div class="navbar-default navbar-right sidebar">
                <div class="sidebar-nav navbar-collapse">
                    <ul class="nav-fall">
                        <li class="charj"><a href="">flower<i class="fa fa-angle-right arrow" aria-hidden="true"></i></a>
                            <ul class="nav-second-level">
                                <li><a href="">name</a></li>
                                <li><a href="">price</a></li>
                            </ul>
                        </li>

                        <li><a href="">one</a></li>
                        <li><a href="">two</a></li>
                        <li><a href="">three</a></li>
                    </ul>

                </div>
            </div>

<!------css----->

.sidebar .fa.arrow:before {
content: "\f105";
}
.sidebar .nav-second-level {
  display: none;
}
.sidebar .nav-fall .charj a:hover .nav-second-level {
  display: block;
}
</code>```

答:
Below 2 examples. The first one uses hover, the second one uses a click event.

.sidebar .fa.arrow:before {
  content: "\f105";
  margin-left: 3px;
}

.nav-second-level {
  display: none;
}

.sidebar .nav-fall li:hover .nav-second-level {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar-default navbar-right sidebar">
  <div class="sidebar-nav navbar-collapse">
    <ul class="nav-fall">
      <li class="charj">flower<i class="fa fa-angle-right arrow" aria-hidden="true"></i>
        <ul class="nav-second-level">
          <li>name</li>
          <li>price</li>
        </ul>
      </li>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </div>
</div></code>```

$(document).on("click", ".charj", function() {
  $(this).find("ul").show();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidebar .fa.arrow:before {
  content: "\f105";
  margin-left: 3px;
}

.nav-second-level {
  display: none;
}</code>```

flower

name

price

one

two

three

```

Body:
This is a piece of my code for sidebar menu.I want to create dashboard and  drop down menu in left of screen. when I go on flower don't show  it's sub menu.
(i want clickable)

flower

name

price

one

two

three

.sidebar .fa.arrow:before {
content: "\f105";
}
.sidebar .nav-second-level {
  display: none;
}
.sidebar .nav-fall .charj a:hover .nav-second-level {
  display: block;
}

Body:
Below 2 examples. The first one uses hover, the second one uses a click event.

.sidebar .fa.arrow:before {
  content: "\f105";
  margin-left: 3px;
}

.nav-second-level {
  display: none;
}

.sidebar .nav-fall li:hover .nav-second-level {
  display: block;
}

<div class="navbar-default navbar-right sidebar">
  <div class="sidebar-nav navbar-collapse">
    <ul class="nav-fall">
      <li class="charj"><a href="">flower<i class="fa fa-angle-right arrow" aria-hidden="true"></i></a>
        <ul class="nav-second-level">
          <li><a href="">name</a></li>
          <li><a href="">price</a></li>
        </ul>
      </li>
      <li><a href="">one</a></li>
      <li><a href="">two</a></li>
      <li><a href="">three</a></li>
    </ul>
  </div>
</div>

$(document).on("click", ".charj", function() {
  $(this).find("ul").show();
})

.sidebar .fa.arrow:before {
  content: "\f105";
  margin-left: 3px;
}

.nav-second-level {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navbar-default navbar-right sidebar">
  <div class="sidebar-nav navbar-collapse">
    <ul class="nav-fall">
      <li class="charj"><a href="#">flower<i class="fa fa-angle-right arrow" aria-hidden="true"></i></a>
        <ul class="nav-second-level">
          <li><a href="">name</a></li>
          <li><a href="">price</a></li>
        </ul>
      </li>
      <li><a href="">one</a></li>
      <li><a href="">two</a></li>
      <li><a href="">three</a></li>
    </ul>
  </div>
</div>


问:
Can't remove LFCR from text with the usual methods, Excel bug?
I have a list of strings littered with carriage return and line feed which I am trying to clean. I have tried the following methods:

find and replace of CTRL+J in excel

find and replace of ALT+0010/ALT+0013 in excel

find and replace of ALT+010/ALT+013 in excel

CLEAN in excel

copy list in excel, paste into notepad++, save as txt, reimport into excel ("Â" character was added on import) and finally replace "Â"

I've also tried the Text to Columns option with CTRL+J, absolutely no result whatsoever

EDIT: SUBSTITUTE CHAR(10) and CHAR(13) in excel didn't work either

None of the above worked, my list still contains line feeds and carriage returns. Is this a bug in excel?

Manually deleting these is out of the question due to the size of the list. I tried replacing these characters in notepad++ with pipe, and importing back into excel (choose delimited by pipe upon import and then copy/paste transpose), but again, the list is too long.

Anyone ideas?
Many thankZ

答:
It seems one can find/replace a LF but not the combo LFCR.

The following formula will replace the LFCR with a space:

```<code>=SUBSTITUTE(A1,CHAR(10)&CHAR(13)," ")
</code>```

You can then Copy ► Paste as values to remove the formula.

Body:
It seems one can find/replace a LF but not the combo LFCR.

The following formula will replace the LFCR with a space:

=SUBSTITUTE(A1,CHAR(10)&CHAR(13)," ")

You can then Copy ► Paste as values to remove the formula.