问:
ReactJS - How to use 'ref' property for scrollbar?
In react "^15.4.1", I want to display middle section of a page after reload. So I am trying to do it using scrollbar but I am getting an error like,

```<code>main.js:43122 Uncaught TypeError: Cannot read property 'scrollTop' of null
 at ref (main.js:43122)
 at detachRef (main.js:82172)
 at Object.ReactRef.detachRefs (main.js:82227)
 at Object.receiveComponent (main.js:10145)
 at ReactCompositeComponentWrapper._updateRenderedComponent (main.js:77618)
</code>```

Importing like, import { Scrollbars } from 'react-custom-scrollbars'; and the version is 4.0.1

In .jsx file,

```<code>componentDidMount() {
  this.scrollTop(200);
}

handleScrolling = (frame) => {
 if(frame.top === 1) this.setState({ loading: true })
}

scrollTop = (value) => {
  if(this.refs.scrollbar) this.refs.scrollbar.scrollTop(value);
}

<Scrollbars
    ref={(scrollbar) => {scrollbar.scrollTop(200);}}
    style={{ height: '100vh' }} onScrollFrame={this.handleScrolling}>
    ...
</code>```

How can I fix this issue? Actually I am new to ReactJS. Please help me regarding the same.

答:
In this part you just need to place your ref.

```<code><Scrollbars
  ref={(scrollbar) => { this.scrollbar = scrollbar; }}
</code>```

Then you can use the ref to do your stuff.

```<code>scrollTop (value) => {
  this.scrollbar.scrollTop(value);
}
</code>```

Body:
In react "^15.4.1", I want to display middle section of a page after reload. So I am trying to do it using scrollbar but I am getting an error like,

main.js:43122 Uncaught TypeError: Cannot read property 'scrollTop' of null
 at ref (main.js:43122)
 at detachRef (main.js:82172)
 at Object.ReactRef.detachRefs (main.js:82227)
 at Object.receiveComponent (main.js:10145)
 at ReactCompositeComponentWrapper._updateRenderedComponent (main.js:77618)

Importing like, import { Scrollbars } from 'react-custom-scrollbars'; and the version is 4.0.1

In .jsx file,

componentDidMount() {
  this.scrollTop(200);
}

handleScrolling = (frame) => {
 if(frame.top === 1) this.setState({ loading: true })
}

scrollTop = (value) => {
  if(this.refs.scrollbar) this.refs.scrollbar.scrollTop(value);
}

<Scrollbars
    ref={(scrollbar) => {scrollbar.scrollTop(200);}}
    style={{ height: '100vh' }} onScrollFrame={this.handleScrolling}>
    ...

How can I fix this issue? Actually I am new to ReactJS. Please help me regarding the same.

Body:
In this part you just need to place your ref.

<Scrollbars
  ref={(scrollbar) => { this.scrollbar = scrollbar; }}

Then you can use the ref to do your stuff.

scrollTop (value) => {
  this.scrollbar.scrollTop(value);
}


来源: stackexchange

问:
Error handling checking database with else if for existing email
Im stuck with some code. Im pretty new to this.

If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.

```<code>$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];

if (empty($username)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($email)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();

} else {
        $sql = "SELECT username FROM user WHERE username='$username'";
        $result = mysqli_query($conn, $sql);
        $uidcheck = mysqli_num_rows($result);
        if ($uidcheck > 0) {
            header("Location: ../signup.php?error=username");
            exit();

    } elseif ($uidcheck < 0) {

        $sql = "SELECT email FROM user WHERE email='$email'";
        $result = mysqli_query($conn, $sql);
        $emailcheck = mysqli_num_rows($result);
        if ($emailcheck > 0) {
            header("Location: ../signup.php?error=email");
            exit();

        } else {

            $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
            $result = mysqli_query($conn, $sql);

            header("Location: ../index.php");
        }

    }
}
</code>```

When the emailadress already exists in the database it should exit and add a parameter to the header.

Thanks in advance!

Sven

答:
Try this..

You are checking the MySQL resulted value in a wrong manner. For Example Email  is already existed in you DB then your Query results Value, then you don not check with < or > just try with either it is empty or not.

```<code>$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];

if (empty($username)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($email)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();

} else {
    echo "Username check";
        $sql = "SELECT username FROM user WHERE username='$username'";

        $result = mysqli_query($conn, $sql);
        $uidcheck = mysqli_num_rows($result);
        if (!empty($uidcheck)) {
            header("Location: ../signup.php?error=username");
            exit();
        } elseif (empty($uidcheck)) {
            $sql = "SELECT email FROM user WHERE email='$email'";
            $result = mysqli_query($conn, $sql);
           echo $emailcheck = mysqli_num_rows($result);

        if (!empty($emailcheck)) {
                header("Location: ../signup.php?error=email");
                exit();

        } else {
            echo "asdasd";
            $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
            $result = mysqli_query($conn, $sql);

            header("Location: ../index.php");
        }

    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im stuck with some code. Im pretty new to this.

If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.

$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];

if (empty($username)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($email)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();

} else {
        $sql = "SELECT username FROM user WHERE username='$username'";
        $result = mysqli_query($conn, $sql);
        $uidcheck = mysqli_num_rows($result);
        if ($uidcheck > 0) {
            header("Location: ../signup.php?error=username");
            exit();

    } elseif ($uidcheck < 0) {

        $sql = "SELECT email FROM user WHERE email='$email'";
        $result = mysqli_query($conn, $sql);
        $emailcheck = mysqli_num_rows($result);
        if ($emailcheck > 0) {
            header("Location: ../signup.php?error=email");
            exit();

        } else {

            $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
            $result = mysqli_query($conn, $sql);

            header("Location: ../index.php");
        }

    }
}

When the emailadress already exists in the database it should exit and add a parameter to the header.

Thanks in advance!

Sven

Body:
Try this..

You are checking the MySQL resulted value in a wrong manner. For Example Email  is already existed in you DB then your Query results Value, then you don not check with < or > just try with either it is empty or not.

$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];

if (empty($username)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($email)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();

} else {
    echo "Username check";
        $sql = "SELECT username FROM user WHERE username='$username'";

        $result = mysqli_query($conn, $sql);
        $uidcheck = mysqli_num_rows($result);
        if (!empty($uidcheck)) {
            header("Location: ../signup.php?error=username");
            exit();
        } elseif (empty($uidcheck)) {
            $sql = "SELECT email FROM user WHERE email='$email'";
            $result = mysqli_query($conn, $sql);
           echo $emailcheck = mysqli_num_rows($result);

        if (!empty($emailcheck)) {
                header("Location: ../signup.php?error=email");
                exit();

        } else {
            echo "asdasd";
            $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
            $result = mysqli_query($conn, $sql);

            header("Location: ../index.php");
        }

    }
}


问:
Using xpath containing whitespace
```<code>List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));
</code>```

<p>how to use normalize-space in my case? "situacao" has white spaces </p>

答:
To pass the variable situacao within the xpath you can use the following line of code :

```<code>List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id='tabela']/tbody/tr/td[5][normalize-space()='" + situacao + "']"));
</code>```

Title: Using xpath containing whitespace

Body:
List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));

how to use normalize-space in my case? "situacao" has white spaces

Body:
To pass the variable situacao within the xpath you can use the following line of code :

List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id='tabela']/tbody/tr/td[5][normalize-space()='" + situacao + "']"));


问:
Elm websocket request origin within a browser
Lets say I make an elm app; it requests data from a websocket to check the price of bitcoin from say poloniex.com. I compile it to an .html file and  I deploy it to say Heroku or whatever server I like on the backend.

When a user comes to my website and requests that .html file, and is then looking at the bitcoin price from the websocket request, is the user's IP address making that websocket request or is it the backend's (eg Heroku in this case) IP address making the websocket request?

I ask because I was considering two different designs. Either have my backend pull the bitcoin price data and then serve that to my users or have the users directly request the price from the source itself (i.e poloniex in this case). The latter would be less headache but won't be possible if all the requests end up coming from the backend and therefore one ip address (they would have request limits)

Edit: Bolded for people who couldn't see where the question was.

答:
Assuming you are using the standard Elm Websocket package, elm-lang/websocket, the websocket connects with whatever URL you point it at. If you set it up like this:

```<code>subscriptions model =
    listen "ws://echo.websocket.org" Echo
</code>```

Then the client browser will connect directly with echo.websocket.org. The target of that websocket connection will likely see your application as a referrer, but its connection will be with the IP of the user's browser that is acting as the client.

If you instead want your backend server application to act as a proxy, you would use that URL in listen

```<code>subscriptions model =
    listen "ws://myapp.com" ...
</code>```

Body:
Assuming you are using the standard Elm Websocket package, elm-lang/websocket, the websocket connects with whatever URL you point it at. If you set it up like this:

subscriptions model =
    listen "ws://echo.websocket.org" Echo

Then the client browser will connect directly with echo.websocket.org. The target of that websocket connection will likely see your application as a referrer, but its connection will be with the IP of the user's browser that is acting as the client.

If you instead want your backend server application to act as a proxy, you would use that URL in listen

subscriptions model =
    listen "ws://myapp.com" ...


问:
window.print() not working in Chrome
In the below code, the window.print() function not working in Chrome.what to do?

 <input type="text" placeholder="Enter Item Name" size="20">

 <input type="num" placeholder="quantity" size="20" id="qty">

 <input type="text" placeholder="prize" size="20" id="rs"> <button onclick="mul()" id="add">add </button>

 <input type="text"  size="20" id="amt">  <input type="text" size="7" id="total"> <button onclick="print()" id="print"> print

```

答:
Congratulations, you caused a StackOverflow!

This code:

```<code>function print() {
    window.print();
}
</code>```

is same as writing:

```<code>window.print = function {
    window.print();
}
</code>```

Basically you overwrote the native window.print function with your own function that calls window.print recursively. The solution is simple... remove your function and simply:

```<code><button onclick="window.print()" id="print">print</button>
</code>```

Or this:

```<code><button onclick="myPrintFunction()" id="print">print</button>
<script>
    function myPrintFunction() {
        // do something maybe
        window.print();
    }
</script>
</code>```

Title: window.print() not working in Chrome

Body:
Congratulations, you caused a StackOverflow!

This code:

function print() {
    window.print();
}

is same as writing:

window.print = function {
    window.print();
}

Basically you overwrote the native window.print function with your own function that calls window.print recursively. The solution is simple... remove your function and simply:

<button onclick="window.print()" id="print">print</button>

Or this:

<button onclick="myPrintFunction()" id="print">print</button>
<script>
    function myPrintFunction() {
        // do something maybe
        window.print();
    }
</script>


问:
Google Maps not centering on marker
I am trying to get a client's website to display a variable Google Map with an address defined via ACF Maps on WordPress.

The map itself works per se, with it centering not far away from where the marker is.

However, we cannot get the map to center on the marker itself, which defeats the purpose of the map as the company in question is a property management company listing their properties on the website.

This is my functions code:

```<code><?php
    function my_theme_add_scripts() {
    wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCXO1En_anHPp9eAXyu5ApV50MdHzsDU5c', array(), '3', true );
    wp_enqueue_script( 'google-map-init', get_template_directory_uri() . '/js/google-maps.js', array('google-map', 'jquery'), '0.1', true );
}

add_action( 'wp_enqueue_scripts', 'my_theme_add_scripts' );

function my_acf_google_map_api( $api ){

    $api['key'] = 'API_KEY_HERE';

    return $api;

}

add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');
?>
</code>```

This is my jQuery:

```<code>window.map;
(function ($) {
function render_map($el) {

    // var
    var $markers = $el.find('.marker');

    // vars
    var args = {
        zoom: 16,
        center: new google.maps.LatLng('data-lat','data-lng'),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // create map
    window.map = new google.maps.Map($el[0], args);

    // add a markers reference
    map.markers = [];

    // add markers
    $markers.each(function () {

        add_marker($(this), map);

    });

    // center map
    center_map(map);

}

function add_marker($marker, map) {

    // var
    var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));

    // create marker
    var marker = new google.maps.Marker({
        position: latlng,
        center: latlng,
        map: map
    });

    // add to array
    map.markers.push(marker);

    // if marker contains HTML, add it to an infoWindow
    if ($marker.html()) {
        // create info window
        var infowindow = new google.maps.InfoWindow({
            content: $marker.html()
        });

        // show info window when marker is clicked
        google.maps.event.addListener(marker, 'click', function () {

            infowindow.open(map, marker);

        });
    }

}

function center_map(map) {
    // vars
    var bounds = new google.maps.LatLngBounds();
    // loop through all markers and create bounds
    $.each(map.markers, function (i, marker) {
        var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
        bounds.extend(latlng);
    });
    // only 1 marker?
    if (map.markers.length == 1) {
        // set center of map
        map.setCenter(bounds.getCenter());
        map.setZoom(15);
    } else {
        // fit to bounds
        map.fitBounds(bounds);
    }
}

$(document).ready(function () {
    $('.acf-map').each(function () {
        render_map($(this));
    });

    function center_map(map) {
        // vars
        var bounds = new google.maps.LatLngBounds();
        // loop through all markers and create bounds
        $.each(map.markers, function (i, marker) {
            var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
            bounds.extend(latlng);
        });
    }
});

})(jQuery);
</code>```

HTML/PHP:

```<code><?php
                $location = get_field('properties_location');
                if( !empty($location) ):
            ?>
            <div class="acf-map">
                <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>"></div>
            </div>
            <?php endif; ?>
</code>```

CSS:

```<code>.acf-map {
    width: 100%;
    height: 400px;
    border: #ccc solid 1px;
    margin: 20px 0;
}
</code>```

I'm guessing it can be fixed by a simple jQuery fix but I can't for the life of me figure out what the fix is.

Any help is much appreciated.

答:
I discovered what my issue was. It was to do with the bounding box that the map was being displayed in.

I am displaying the maps within a tabbed view underneath the property information (screenshot).

As the Google Maps API won't run unless the map is visible, the centering script wasn't running.

However, I moved all of the Google Maps rendering javascript to run within a tab-click function, to ensure the centering of the maps was rendered.

Sure enough, after moving the code, it now centers the marker.

My new javascript/jquery is as follows:

```<code>$('ul.tabs li.map').one('click', function () {
    function render_map($el) {

        // var
        var $markers = $el.find('.marker');

        // vars
        var args = {
            zoom: 17,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        // create map
        window.map = new google.maps.Map($el[0], args);

        // add a markers reference
        map.markers = [];

        // add markers
        $markers.each(function () {

            add_marker($(this), map);

        });

        // center map
        center_map(map);

    }

    function add_marker($marker, map) {

        // var
        var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));

        // create marker
        var marker = new google.maps.Marker({
            position: latlng,
            center: latlng,
            map: map
        });

        // add to array
        map.markers.push(marker);

        // if marker contains HTML, add it to an infoWindow
        if ($marker.html()) {
            // create info window
            var infowindow = new google.maps.InfoWindow({
                content: $marker.html()
            });

            // show info window when marker is clicked
            google.maps.event.addListener(marker, 'click', function () {

                infowindow.open(map, marker);

            });
        }

    }

    function center_map(map) {
        // vars
        var bounds = new google.maps.LatLngBounds();
        // loop through all markers and create bounds
        $.each(map.markers, function (i, marker) {
            var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
            bounds.extend(latlng);
        });
        // only 1 marker?
        if (map.markers.length == 1) {
            // set center of map
            map.setCenter(bounds.getCenter());
            map.setZoom(17);
        } else {
            // fit to bounds
            map.fitBounds(bounds);
        }
    }

    $(document).ready(function () {
        $('.acf-map').each(function () {
            render_map($(this));
        });
    });
});
</code>```

This runs the code only the first time the tab is clicked to prevent it being re-rendered every time the tab gets clicked. The re-rendering was causing the map to break entirely.

Title: Google Maps not centering on marker

Body:
I am trying to get a client's website to display a variable Google Map with an address defined via ACF Maps on WordPress.

The map itself works per se, with it centering not far away from where the marker is.

However, we cannot get the map to center on the marker itself, which defeats the purpose of the map as the company in question is a property management company listing their properties on the website.

This is my functions code:

<?php
    function my_theme_add_scripts() {
    wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCXO1En_anHPp9eAXyu5ApV50MdHzsDU5c', array(), '3', true );
    wp_enqueue_script( 'google-map-init', get_template_directory_uri() . '/js/google-maps.js', array('google-map', 'jquery'), '0.1', true );
}

add_action( 'wp_enqueue_scripts', 'my_theme_add_scripts' );

function my_acf_google_map_api( $api ){

    $api['key'] = 'API_KEY_HERE';

    return $api;

}

add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');
?>

This is my jQuery:

window.map;
(function ($) {
function render_map($el) {

    // var
    var $markers = $el.find('.marker');

    // vars
    var args = {
        zoom: 16,
        center: new google.maps.LatLng('data-lat','data-lng'),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // create map
    window.map = new google.maps.Map($el[0], args);

    // add a markers reference
    map.markers = [];

    // add markers
    $markers.each(function () {

        add_marker($(this), map);

    });

    // center map
    center_map(map);

}

function add_marker($marker, map) {

    // var
    var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));

    // create marker
    var marker = new google.maps.Marker({
        position: latlng,
        center: latlng,
        map: map
    });

    // add to array
    map.markers.push(marker);

    // if marker contains HTML, add it to an infoWindow
    if ($marker.html()) {
        // create info window
        var infowindow = new google.maps.InfoWindow({
            content: $marker.html()
        });

        // show info window when marker is clicked
        google.maps.event.addListener(marker, 'click', function () {

            infowindow.open(map, marker);

        });
    }

}

function center_map(map) {
    // vars
    var bounds = new google.maps.LatLngBounds();
    // loop through all markers and create bounds
    $.each(map.markers, function (i, marker) {
        var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
        bounds.extend(latlng);
    });
    // only 1 marker?
    if (map.markers.length == 1) {
        // set center of map
        map.setCenter(bounds.getCenter());
        map.setZoom(15);
    } else {
        // fit to bounds
        map.fitBounds(bounds);
    }
}

$(document).ready(function () {
    $('.acf-map').each(function () {
        render_map($(this));
    });

    function center_map(map) {
        // vars
        var bounds = new google.maps.LatLngBounds();
        // loop through all markers and create bounds
        $.each(map.markers, function (i, marker) {
            var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
            bounds.extend(latlng);
        });
    }
});

})(jQuery);

HTML/PHP:

<?php
                $location = get_field('properties_location');
                if( !empty($location) ):
            ?>

                <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">

            <?php endif; ?>

CSS:

.acf-map {
    width: 100%;
    height: 400px;
    border: #ccc solid 1px;
    margin: 20px 0;
}

I'm guessing it can be fixed by a simple jQuery fix but I can't for the life of me figure out what the fix is.

Any help is much appreciated.

Body:
I discovered what my issue was. It was to do with the bounding box that the map was being displayed in.

I am displaying the maps within a tabbed view underneath the property information (screenshot).

As the Google Maps API won't run unless the map is visible, the centering script wasn't running.

However, I moved all of the Google Maps rendering javascript to run within a tab-click function, to ensure the centering of the maps was rendered.

Sure enough, after moving the code, it now centers the marker.

My new javascript/jquery is as follows:

$('ul.tabs li.map').one('click', function () {
    function render_map($el) {

        // var
        var $markers = $el.find('.marker');

        // vars
        var args = {
            zoom: 17,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        // create map
        window.map = new google.maps.Map($el[0], args);

        // add a markers reference
        map.markers = [];

        // add markers
        $markers.each(function () {

            add_marker($(this), map);

        });

        // center map
        center_map(map);

    }

    function add_marker($marker, map) {

        // var
        var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));

        // create marker
        var marker = new google.maps.Marker({
            position: latlng,
            center: latlng,
            map: map
        });

        // add to array
        map.markers.push(marker);

        // if marker contains HTML, add it to an infoWindow
        if ($marker.html()) {
            // create info window
            var infowindow = new google.maps.InfoWindow({
                content: $marker.html()
            });

            // show info window when marker is clicked
            google.maps.event.addListener(marker, 'click', function () {

                infowindow.open(map, marker);

            });
        }

    }

    function center_map(map) {
        // vars
        var bounds = new google.maps.LatLngBounds();
        // loop through all markers and create bounds
        $.each(map.markers, function (i, marker) {
            var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
            bounds.extend(latlng);
        });
        // only 1 marker?
        if (map.markers.length == 1) {
            // set center of map
            map.setCenter(bounds.getCenter());
            map.setZoom(17);
        } else {
            // fit to bounds
            map.fitBounds(bounds);
        }
    }

    $(document).ready(function () {
        $('.acf-map').each(function () {
            render_map($(this));
        });
    });
});

This runs the code only the first time the tab is clicked to prevent it being re-rendered every time the tab gets clicked. The re-rendering was causing the map to break entirely.


问:
Analog clock using CALayers
I'm trying to make an analog clock for the iPhone, in which the clock hands will automatically update to the current time.  I also want the clock hands to be images, unlike this:  http://iphone-dev-tips.alterplay.com/2010/03/analog-clock-using-quartz-core.html.  What would be the easiest way to create this using CALayers to rotate the images/hands?</p>

答:
There are two properties of CALayers that may be of interest to you - the anchorPoint and the transform. Set the anchor point at the origin around which you want to rotate the images, calculate the angle of rotation, make a transformation matrix from it (using CATransform3DMakeRotation around the appropriate axis) and set the transform on the layer.

It's all explained in detail here.

Title: Analog clock using CALayers

ContentLicense: CC BY-SA 2.5


问:
iOS share extension hiding on number of items selected
I see that app like twitter has the feature to automatically hide the share extension depending on number of items selected, .ie in Photo app like:

Anybody has any idea on how to obtain something like twitter share extension

Thanks

答: This can be achieved by setting  NSExtensionActivationSupportsImageWithMaxCount in info.plist


问:
Reinstall default Ruby on MacOS Sierra
I have been playing around with Jekyll and Ruby on my mac. I insalled Ruby 2.4 via MacPorts, messed something up and accidently deleted /Library/Ruby. I am now worried that I have messed up internals on my system.

How can I reinstall default Ruby Gems for Ruby 2.0 that comes with MacOS Sierra?

答:
1)  Install rbenv

```<code>brew install rbenv
</code>```

2) Install ruby version

```<code>rbenv install 2.0.0
</code>```

3) Set your global env to 2.0.0

```<code>rbenv global 2.0.0
</code>```

3 bis) Or set your local env to 2.0.0

```<code>rbenv local 2.0.0
</code>```

Title: Reinstall default Ruby on MacOS Sierra

Body:
1)  Install rbenv

brew install rbenv

2) Install ruby version

rbenv install 2.0.0

3) Set your global env to 2.0.0

rbenv global 2.0.0

3 bis) Or set your local env to 2.0.0

rbenv local 2.0.0


问:
reach the last line with end of line in java
```<code>Scanner console = new Scanner(System.in);
String line = "";
String pera = " ";

System.out.println("Enter the text : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(isr);
int lineNum = 0;
do {
    line = buf.readLine();
    System.out.println();
    pera = line + "";
    lineNum++;
    System.out.print(lineNum + " " + pera);
} while (line != null);
isr.close();
buf.close();
</code>```

input :
Hello world
I am a file
Read me until end-of-file.

output :
1 Hello world
2 I am a file
3 Read me until end-of-file.

and this code output is :
1 Hello world
2 I am a file
3 Read me until end-of-file.
4 null

答:
Let's simplify things. You can assign a variable in a while loop. Read lines one by one in it until it comes to end. We understand this when the BufferedReader reads a null line using (line = br.readLine()) != null.

```<code>System.out.println("Enter the text: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int lineNo = 0;
String line;
while ((line = br.readLine()) != null) {
    System.out.println(++lineNo + " " + line);
}
isr.close();
br.close();
</code>```

Body:
Scanner console = new Scanner(System.in);
String line = "";
String pera = " ";

System.out.println("Enter the text : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(isr);
int lineNum = 0;
do {
    line = buf.readLine();
    System.out.println();
    pera = line + "";
    lineNum++;
    System.out.print(lineNum + " " + pera);
} while (line != null);
isr.close();
buf.close();

input :
Hello world
I am a file
Read me until end-of-file.

output :
1 Hello world
2 I am a file
3 Read me until end-of-file.

and this code output is :
1 Hello world
2 I am a file
3 Read me until end-of-file.
4 null

Body:
Let's simplify things. You can assign a variable in a while loop. Read lines one by one in it until it comes to end. We understand this when the BufferedReader reads a null line using (line = br.readLine()) != null.

System.out.println("Enter the text: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int lineNo = 0;
String line;
while ((line = br.readLine()) != null) {
    System.out.println(++lineNo + " " + line);
}
isr.close();
br.close();


问:
how to implement @GeneratedValue with my own strategy for generating keys
I want to implement my own strategy for generating primary keys for new rows in my table, for example I want that the id of a host will  172.24.85.20 will be 8520.

Can I somehow extend @GeneratedValue annotation? which approach will you recommend?

答:
You may try this one with Date and Calender

```<code>public class StockCodeGenerator implements IdentifierGenerator {
    private static Logger log = Logger.getLogger(StockCodeGenerator.class);
     public StockCodeGenerator() {}

     public int generateCustId() {
         Random random = new Random();
         return random.nextInt(100);
     }

     public Serializable generate(SessionImplementor session, Object object)
     throws HibernateException {
         String prefix = "Custom_String";
         Connection connection = session.connection();
         System.out.println(session.connection());

         Date date = new Date();

         Calendar calendar = Calendar.getInstance();
         return prefix + "_" + generateCustId() + "_" + calendar.get(1);
     }
}
</code>```

And then use it in your @GenericGenerator annotation:

```<code>@Id
@GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
@GeneratedValue(generator="seq_id")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You may try this one with Date and Calender

public class StockCodeGenerator implements IdentifierGenerator {
    private static Logger log = Logger.getLogger(StockCodeGenerator.class);
     public StockCodeGenerator() {}

     public int generateCustId() {
         Random random = new Random();
         return random.nextInt(100);
     }

     public Serializable generate(SessionImplementor session, Object object)
     throws HibernateException {
         String prefix = "Custom_String";
         Connection connection = session.connection();
         System.out.println(session.connection());

         Date date = new Date();

         Calendar calendar = Calendar.getInstance();
         return prefix + "_" + generateCustId() + "_" + calendar.get(1);
     }
}

And then use it in your @GenericGenerator annotation:

@Id
@GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
@GeneratedValue(generator="seq_id")


问:
how to split a text file by line gaps in java
I am reading a text file in Java that looks like this,

"
Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)

Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?

Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why? "

Now, I want to read this file and then store each of these sentences(questions) in a string array. How can I do that in java?

I tried this,

```<code>String mlq = new String(Files.readAllBytes(Paths.get("MLques.txt")));
String[] mlq1=mlq.split("\n\n");
</code>```

But this is not working.

答:
```<code>File file = new File("C:\\MLques.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
    System.out.println(st + "\n");
}
</code>```

I think it will work.

Body:
I am reading a text file in Java that looks like this,

"
Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)

Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?

Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why? "

Now, I want to read this file and then store each of these sentences(questions) in a string array. How can I do that in java?

I tried this,

String mlq = new String(Files.readAllBytes(Paths.get("MLques.txt")));
String[] mlq1=mlq.split("\n\n");

But this is not working.

Body:
File file = new File("C:\\MLques.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
    System.out.println(st + "\n");
}

I think it will work.


问:
What does "asp.net" mean?
I know asp stands for Active Server Pages but wondering if "Active Server" means anything actually? </p>

答: As an aside, ASP.NET isn't really an upgrade for ASP, it was just named that way to get it past corporate departments - you could sell it to your higher-ups as an "upgrade" to ASP even though it was pretty much a separate technology.

OwnerDisplayName: Sesh

Title: What does "asp.net" mean?

OwnerDisplayName: Schnapple


问:
How can I use the C modf function in php?
There does not appear to be one?</p>

答: Use PHP's fmod.</p>

Body: There does not appear to be one?

Body: Use PHP's fmod.


问:
How to make div height equal to width in CSS Grid
I am using CSS Grid to layout a thumbnail gallery, no Javascript or any other responsive techniques. I would like to set the height of thumbnails to be as its width (1:1) square ratio.

Why? when the page loads I need the thumbnail div's to take space, because now if there is no Image inside the thumbnails div it doesn't take any space.

Here is a Live example: https://www.w3schools.com/code/tryit.asp?filename=FMCULIDQUOBX

Here is the Code:

```<code>.container {max-width: 900px;}
.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 15px;
}
.thumbnail {box-shadow: 0 4px 4px rgba(0,0,0,0.50);}
img {width: 100%; display: block;}
</code>```

...............................

```<code><div class="container">
  <div class="gallery">

    <div class="thumbnail">
      <a href="large-image.jpg">
        <img src="thumbnail-image.jpg">
      </a>
    </div>
    <div class="thumbnail">
      ...... same as above ......
    </div>
    <div class="thumbnail">
      ...... same as above ......
    </div>
    <div class="thumbnail">
      ...... same as above ......
    </div>

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

The Code above divides the width (900px) into four fractions, and the 4 thumbnails are placed in 1 row. That's why I don't define any width.

If Images don't load, the thumbnail div wont even be visible.

In other words, if you disable images in browser, thumbnail div should take space in a square shape.

How to fix this? Thanks

答:
The big advantage is that CSS grid by default applies a similar height to its children.

Option is to restructure the HTML and reduce markup (HTML). You can add height to the .gallery class to make it look more square.

.container {max-width: 900px; margin:0 auto;}
.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 15px;
}
.thumbnail {display:block; box-shadow: 0 4px 4px rgba(0,0,0,0.50);}
img {display:block; width:100%; height: auto;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="container">
      <div class="gallery">

            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">

            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">

            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">

            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">

            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">

            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">

            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">

            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">

      </div>
    </div>

    </code>```

Body:
I am using CSS Grid to layout a thumbnail gallery, no Javascript or any other responsive techniques. I would like to set the height of thumbnails to be as its width (1:1) square ratio.

Why? when the page loads I need the thumbnail div's to take space, because now if there is no Image inside the thumbnails div it doesn't take any space.

Here is a Live example: https://www.w3schools.com/code/tryit.asp?filename=FMCULIDQUOBX

Here is the Code:

.container {max-width: 900px;}
.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 15px;
}
.thumbnail {box-shadow: 0 4px 4px rgba(0,0,0,0.50);}
img {width: 100%; display: block;}

...............................

      ...... same as above ......

      ...... same as above ......

      ...... same as above ......

The Code above divides the width (900px) into four fractions, and the 4 thumbnails are placed in 1 row. That's why I don't define any width.

If Images don't load, the thumbnail div wont even be visible.

In other words, if you disable images in browser, thumbnail div should take space in a square shape.

How to fix this? Thanks

Body:
The big advantage is that CSS grid by default applies a similar height to its children.

Option is to restructure the HTML and reduce markup (HTML). You can add height to the .gallery class to make it look more square.

.container {max-width: 900px; margin:0 auto;}
.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 15px;
}
.thumbnail {display:block; box-shadow: 0 4px 4px rgba(0,0,0,0.50);}
img {display:block; width:100%; height: auto;}

    <div class="container">
      <div class="gallery">
          <a class="thumbnail"  href="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
          </a>

          <a class="thumbnail" href="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
          </a>

          <a class="thumbnail"  href="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
          </a>

          <a class="thumbnail"  href="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
          </a>

        <a class="thumbnail"  href="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
          </a>

          <a class="thumbnail" href="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
          </a>

          <a class="thumbnail"  href="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
            <img src="https://static.pexels.com/photos/54278/pexels-photo-54278.jpeg">
          </a>

          <a class="thumbnail"  href="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
            <img src="https://static.pexels.com/photos/242276/pexels-photo-242276.jpeg">
          </a>
      </div>
    </div>


问:
How can i authenticate the user's input?
Building a chatbot using node.js that will be communicating with Luis.

```<code> if (!meeting.datetimeV2) {
            builder.Prompts.text(session, 'what is the date and time');
        } else {
            next();
        }
</code>```

This section is supposed to take date and time code for example:

```<code>Bot: what is the date and time?
human:today at 5pm
</code>```

The issue i'm having is that the bot is accepting inputs like jagahgdh or ffffff basically troll answers which is expected due to the use of builder.Prompts.text but my question is how can i fix that and make sure the users input has the proper format or i'll have to ask the same question again.

答: using NER (Named Entity Recognition) you can check if the user's input contains a "date" and a "time" entities - if not prompt the same question</p>

Body:
Building a chatbot using node.js that will be communicating with Luis.

 if (!meeting.datetimeV2) {
            builder.Prompts.text(session, 'what is the date and time');
        } else {
            next();
        }

This section is supposed to take date and time code for example:

Bot: what is the date and time?
human:today at 5pm

The issue i'm having is that the bot is accepting inputs like jagahgdh or ffffff basically troll answers which is expected due to the use of builder.Prompts.text but my question is how can i fix that and make sure the users input has the proper format or i'll have to ask the same question again.


问:
How To Keep textarea content
I have a code :

```<code><?php
    if(isset($_POST['data'])) {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'w');
        fwrite($fh, $_POST['data']);
    } else {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'r');
        $theData = fread($fh, filesize($myFile));
    }
    fclose($fh);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>
    </head>
    <body>
        <form name="test" method="post" action="">
            <textarea name="data"><?php echo $theData; ?></textarea>
            <input type="submit" name="submit" value="Update File" />
        </form>
    </body>
</html>
</code>```

When I click submit content of the textarea is lost.
How can I solve this?

答:
Make a little change in your code:</p>

```<code>$fh = fopen($myFile, 'rb'); // Notice b here
$theData = fread($fh, filesize($myFile));
</code>```

Title: How To Keep textarea content

Body:
I have a code :

<?php
    if(isset($_POST['data'])) {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'w');
        fwrite($fh, $_POST['data']);
    } else {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'r');
        $theData = fread($fh, filesize($myFile));
    }
    fclose($fh);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>

        <form name="test" method="post" action="">
            <textarea name="data"><?php echo $theData; ?></textarea>
            <input type="submit" name="submit" value="Update File" />
        </form>

When I click submit content of the textarea is lost.
How can I solve this?

Body:
Make a little change in your code:

$fh = fopen($myFile, 'rb'); // Notice b here
$theData = fread($fh, filesize($myFile));


问:
Send an specific header by ajax to flask
In my flask api file (api.py) i want to get the header "USER" to connect him when he send a request. So i have this line :

```<code>@app.before_request
    def prepare():
        print('Step 1 : {}'.format(request.headers.get("USER")), file=sys.stdout)
        username = request.headers.get("USER")
        user = find.user_by_username(username)
        print('Step 2', file=sys.stdout)
</code>```

On my frontend i have an ajax request to get the task of the user :

```<code>$.ajax({
    url : urlBackend+"weapon/"+weapon,
    type : 'GET',
    dataType : 'json',
    headers: {
        'USER':'toto'
    },
    success : function(resu, statut){
        //I get the weapon of my user
    },

    error : function(resultat, statut, erreur){
      console.log("resultat : "+dump(resultat)+"; statut : "+statut+"; erreur : "+erreur);
    },

    complete : function(resultat, statut){

    }

  });
</code>```

My problem is that my function prepare(in file api.py) don't find the user. In my console it's don't print "Step 1 : toto Step 2" but "Step 1 : None"

Someone have an idea of what i did wrong?

答:
If you use custom headers for sending data for a special reason, I'd like to know.
The problem with your request is, is that you specify it as a GET request, but the method used will be OPTIONS. This is because you never send any data

If you were to change this bit:

```<code>headers: {
    'USER':'toto'
},
</code>```

to:

```<code>data: {
    'USER':'toto'
},
</code>```

And in your @app.before_request use:

```<code>print('Step 1 : {}'.format(request.args.get('USER')), file=sys.stdout)
username = request.args.get('USER')
user = find.user_by_username(username)
print('Step 2', file=sys.stdout)
</code>```

This will actually send the data. Please let me know if this helped

Body:
In my flask api file (api.py) i want to get the header "USER" to connect him when he send a request. So i have this line :

@app.before_request
    def prepare():
        print('Step 1 : {}'.format(request.headers.get("USER")), file=sys.stdout)
        username = request.headers.get("USER")
        user = find.user_by_username(username)
        print('Step 2', file=sys.stdout)

On my frontend i have an ajax request to get the task of the user :

$.ajax({
    url : urlBackend+"weapon/"+weapon,
    type : 'GET',
    dataType : 'json',
    headers: {
        'USER':'toto'
    },
    success : function(resu, statut){
        //I get the weapon of my user
    },

    error : function(resultat, statut, erreur){
      console.log("resultat : "+dump(resultat)+"; statut : "+statut+"; erreur : "+erreur);
    },

    complete : function(resultat, statut){

    }

  });

My problem is that my function prepare(in file api.py) don't find the user. In my console it's don't print "Step 1 : toto Step 2" but "Step 1 : None"

Someone have an idea of what i did wrong?

Body:
If you use custom headers for sending data for a special reason, I'd like to know.
The problem with your request is, is that you specify it as a GET request, but the method used will be OPTIONS. This is because you never send any data

If you were to change this bit:

headers: {
    'USER':'toto'
},

to:

data: {
    'USER':'toto'
},

And in your @app.before_request use:

print('Step 1 : {}'.format(request.args.get('USER')), file=sys.stdout)
username = request.args.get('USER')
user = find.user_by_username(username)
print('Step 2', file=sys.stdout)

This will actually send the data. Please let me know if this helped


问:
apc.cache_by_default with CodeIgniter
I'm trying to use APC (Alternative PHP Cache) on my localhost with wamp 2, PHP 5.3 and CodeIgniter 1.7.2, however If I turn on cache_by_default and enable apc.stat the server will crash and I get the following error:

[apc-error] Cannot redeclare class
  ci_benchmark in
  C:\wamp\www\k\mvc\codeigniter\Common.php
  on line 127.

What can I do to fix this issue?

答:
When you disable apc.stat, apc seems to have a problem with relative paths.  CodeIgniter uses a relative path in the main index.php file, so it breaks things.

Open up index.php and change this:

```<code>$system = '../system';
</code>```

to this:

```<code>$system = '/var/www/system';
</code>```

Substitute '/var/www/' with whatever your server's full path to CodeIgniter's system folder is.

Title: apc.cache_by_default with CodeIgniter

Body:
When you disable apc.stat, apc seems to have a problem with relative paths.  CodeIgniter uses a relative path in the main index.php file, so it breaks things.

Open up index.php and change this:

$system = '../system';

to this:

$system = '/var/www/system';

Substitute '/var/www/' with whatever your server's full path to CodeIgniter's system folder is.


问:
How much of ‘What Every Programmer Should Know About Memory’ is still valid?
I am wondering how much of Ulrich Drepper's What Every Programmer Should Know About Memory from 2007 is still valid. Also I could not find a newer version than 1.0 or an errata.

(Also in PDF form on Ulrich Drepper's own site: https://www.akkadia.org/drepper/cpumemory.pdf)

答:
The guide in PDF form is at https://www.akkadia.org/drepper/cpumemory.pdf.

It is still generally excellent and highly recommended (by me, and I think by other performance-tuning experts).  It would be cool if Ulrich (or anyone else) wrote a 2017 update, but that would be a lot of work (e.g. re-running the benchmarks).  See also other x86 performance-tuning and SSE/asm (and C/C++) optimization links in the x86 tag wiki.  (Ulrich's article isn't x86 specific, but most (all) of his benchmarks are on x86 hardware.)

The low level hardware details about how DRAM and caches work all still apply.  DDR4 uses the same commands as described for DDR1/DDR2 (read/write burst).  The DDR3/4 improvements aren't fundamental changes.  AFAIK, all the arch-independent stuff still applies generally, e.g. to AArch64 / ARM32.

See also the Latency Bound Platforms section of this answer for important details about the effect of memory/L3 latency on single-threaded bandwidth: bandwidth <= max_concurrency / latency, and this is actually the primary bottleneck for single-threaded bandwidth on a modern many-core CPU like a Xeon. But a quad-core Skylake desktop can come close to maxing out DRAM bandwidth with a single thread.  That link has some very good info about NT stores vs. normal stores on x86.  Why is Skylake so much better than Broadwell-E for single-threaded memory throughput? is a summary.

Thus Ulrich's suggestion in 6.5.8 Utilizing All Bandwidth about using remote memory on other NUMA nodes as well as your own, is counter-productive on modern hardware where memory controllers have more bandwidth than a single core can use. Well possibly you can imagine a situation where there's a net benefit to running multiple memory-hungry threads on the same NUMA node for low-latency inter-thread communication, but having them use remote memory for high bandwidth not-latency-sensitive stuff. But this is pretty obscure, normally just divide threads between NUMA nodes and have them use local memory.  Per-core bandwidth is sensitive to latency because of max-concurrency limits (see below), but all the cores in one socket can usually more than saturate the memory controllers in that socket.

(usually) Don't use software prefetch

One major thing that's changed is that hardware prefetch is much better than on the Pentium 4 and can recognize strided access patterns up to a fairly large stride, and multiple streams at once (e.g. one forward / backward per 4k page).  Intel's optimization manual describes some details of the HW prefetchers in various levels of cache for their Sandybridge-family microarchitecture.  Ivybridge and later have next-page hardware prefetch, instead of waiting for a cache miss in the new page to trigger a fast-start. I assume AMD has some similar stuff in their optimization manual.  Beware that Intel's manual is also full of old advice, some of which is only good for P4.  The Sandybridge-specific sections are of course accurate for SnB, but e.g. un-lamination of micro-fused uops changed in HSW and the manual doesn't mention it.

The usual advice these days is to remove all SW prefetch from old code, and only consider putting it back in if profiling shows cache misses (and you're not saturating memory bandwidth).  Prefetching both sides of the next step of a binary search can still help.  e.g. once you decide which element to look at next, prefetch the 1/4 and 3/4 elements so they can load in parallel with loading/checking middle.

The suggestion to use a separate prefetch thread (6.3.4) is totally obsolete, I think, and was only ever good on Pentium 4.  P4 had hyperthreading (2 logical cores sharing one physical core), but not enough trace-cache (and/or out-of-order execution resources) to gain throughput running two full computation threads on the same core.  But modern CPUs (Sandybridge-family and Ryzen) are much beefier and should either run a real thread or not use hyperthreading (leave the other logical core idle so the solo thread has the full resources instead of partitioning the ROB).

Software prefetch has always been "brittle": the right magic tuning numbers to get a speedup depend on the details of the hardware, and maybe system load.  Too early and it's evicted before the demand load.  Too late and it doesn't help.  This blog article shows code + graphs for an interesting experiment in using SW prefetch on Haswell for prefetching the non-sequential part of a problem.  See also How to properly use prefetch instructions?.  NT prefetch is interesting, but even more brittle because an early eviction from L1 means you have to go all the way to L3 or DRAM, not just L2.  If you need every last drop of performance, and you can tune for a specific machine, SW prefetch is worth looking at for sequential access, but it may still be a slowdown if you have enough ALU work to do while coming close to bottlenecking on memory.

Cache line size is still 64 bytes.  (L1D read/write bandwidth is very high, and modern CPUs can do 2 vector loads per clock + 1 vector store if it all hits in L1D.  See How can cache be that fast?.)  With AVX512, line size = vector width, so you can load/store an entire cache line in one instruction.  Thus every misaligned load/store crosses a cache-line boundary, instead of every other for 256b AVX1/AVX2, which often doesn't slow down looping over an array that wasn't in L1D.

Unaligned load instructions have zero penalty if the address is aligned at runtime, but compilers (especially gcc) make better code when autovectorizing if they know about any alignment guarantees.  Actually unaligned ops are generally fast, but page-splits still hurt (much less on Skylake, though; only ~11 extra cycles latency vs. 100, but still a throughput penalty).

As Ulrich predicted, every multi-socket system is NUMA these days: integrated memory controllers are standard, i.e. there is no external Northbridge.  But SMP no longer means multi-socket, because multi-core CPUs are widespread.  Intel CPUs from Nehalem to Skylake have used a large inclusive L3 cache as a backstop for coherency between cores. AMD CPUs are different, but I'm not as clear on the details.

Skylake-X (AVX512) no longer has an inclusive L3, but I think there's still a tag directory that lets it check what's cached anywhere on chip (and if so where) without actually broadcasting snoops to all the cores.  SKX uses a mesh rather than a ring bus, with generally even worse latency than previous many-core Xeons, unfortunately.

Basically all of the advice about optimizing memory placement still applies, just the details of exactly what happens when you can't avoid cache misses or contention vary.

6.1 Bypassing the Cache - SSE4.1 movntdqa (_mm_stream_load_si128) NT loads only ever do anything on WC memory regions.  On normal memory you get from malloc/new or mmap (WB memory attribute = write-back cacheable), movntqda runs the same as a normal SIMD load, not bypassing cache.  But it costs an extra ALU uop.   AFAIK, this was true even on CPUs at the time the article was written, making this a rare mistake in the guide.  Unlike NT stores, NT loads do not override the usual memory ordering rules for the region.  And they have to respect coherency, so they can't fully skip cache on WB-cacheable regions, the data needs to be somewhere other cores can invalidate on write.  But SSE4.1 wasn't introduced until 2nd-gen Core 2, so there weren't single-core CPUs with it.

NT prefetch (prefetchnta) can minimize cache pollution, but does still fill L1d cache, and one way of L3 on Intel CPUs with inclusive L3 cache.  But it's brittle and hard to tune: to short a prefetch distance and you get demand loads which probably defeat the NT aspect, too long and your data is evicted before use.  And since it wasn't in L2, and maybe not even L3, it might miss all the way to DRAM.  Since prefetch distance depends on the system and workload from other code, not just your own code, this is a problem.

Related:

Difference between PREFETCH and PREFETCHNTA instructions

Non-temporal loads and the hardware prefetcher, do they work together?

Copying Accelerated Video Decode Frame Buffers - Intel whitepaper describing the use-case for SSE4.1 movntdqa, reading from video RAM.

6.4.2 Atomic ops: the benchmark showing a CAS-retry loop as 4x worse than hardware-arbitrated lock add does probably still reflect a maximum contention case.  But in real multi-threaded programs, synchronization is kept to a minimum (because it's expensive), so contention is low and a CAS-retry loop usually succeeds without having to retry.

C++11 std::atomic fetch_add will compile to a lock add (or lock xadd if the return value is used), but an algorithm using CAS to do something that can't be done with a locked instruction is usually not a disaster.  Use C++11 std::atomic or C11 stdatomic instead of gcc legacy __sync built-ins or the newer __atomic built-ins unless you want to mix atomic and non-atomic access to the same location...

8.1 DWCAS (cmpxchg16b): You can coax gcc into emitting it, but if you want efficient loads of just one half of the object, you need ugly union hacks: How can I implement ABA counter with c++11 CAS?.  (Don't confuse DWCAS with DCAS of 2 separate memory locations.  Lock-free atomic emulation of DCAS isn't possible with DWCAS, but transactional memory (like x86 TSX) makes it possible.)

8.2.4 transactional memory: After a couple false starts (released then disabled by a microcode update because of a rarely-triggered bug), Intel has working transactional memory in late-model Broadwell and all Skylake CPUs.  The design is still what David Kanter described for Haswell. There's a lock-elision way to use it to speed up code that uses (and can fall back to) a regular lock (especially with a single lock for all elements of a container so multiple threads in the same critical section often don't collide), or to write code that knows about transactions directly.

Update: and now Intel has disabled lock-elision on later CPUs (including Skylake) with a microcode update.  The RTM (xbegin / xend) non-transparent part of TSX can still work if the OS allows it, but TSX in general is seriously turning into Charlie Brown's football.

Has Hardware Lock Elision gone forever due to Spectre Mitigation? (Yes but because of a MDS type of side-channel vulnerability (TAA), not Spectre.  My understanding is that updated microcode does totally disable HLE.  In that case the OS can only enable RTM, not HLE.)

7.5 Hugepages: anonymous transparent hugepages work well on Linux without having to manually use hugetlbfs.  Make allocations >= 2MiB with 2MiB alignment (e.g. posix_memalign, or an aligned_alloc that doesn't enforce the stupid ISO C++17 requirement to fail when size % alignment != 0).

A 2MiB-aligned anonymous allocation will use hugepages by default.  Some workloads (e.g. that keep using large allocations for a while after making them) may benefit from

echo defer+madvise >/sys/kernel/mm/transparent_hugepage/defrag to get the kernel to defrag physical memory whenever needed, instead of falling back to 4k pages.  (See the kernel docs). Use madvise(MADV_HUGEPAGE) after making large allocations (preferably still with 2MiB alignment) to more strongly encourage the kernel to stop and defrag now. defrag = always is too aggressive for most workloads and will spend more time copying pages around than it saves in TLB misses.  (kcompactd could maybe be more efficient.)

BTW, Intel and AMD call 2M pages "large pages", with "huge" only used for 1G pages.  Linux uses "hugepage" for everything larger than the standard size.

(32-bit mode legacy (non-PAE) page tables only had 4M pages as the next largest size, with only 2-level page tables with more compact entries.  The next size up would have been 4G, but that's the whole address space, and that "level" of translation is the CR3 control register, not a page directory entry.  IDK if that's related to Linux's terminology.)

Appendix B: Oprofile: Linux perf has mostly superseded oprofile.  perf list / perf stat -e event1,event2 ... has names for most of the useful ways to program HW performance counters.

```<code>perf stat -etask-clock,context-switches,cpu-migrations,page-faults,cycles,\
branches,branch-misses,instructions,uops_issued.any,\
uops_executed.thread,idq_uops_not_delivered.core -r2 ./a.out
</code>```

A few years ago, the ocperf.py wrapper was needed to translate event names into codes, but these days perf has that functionality built-in.

For some examples of using it, see Can x86's MOV really be "free"? Why can't I reproduce this at all?.

Body:
The guide in PDF form is at https://www.akkadia.org/drepper/cpumemory.pdf.

It is still generally excellent and highly recommended (by me, and I think by other performance-tuning experts).  It would be cool if Ulrich (or anyone else) wrote a 2017 update, but that would be a lot of work (e.g. re-running the benchmarks).  See also other x86 performance-tuning and SSE/asm (and C/C++) optimization links in the x86 tag wiki.  (Ulrich's article isn't x86 specific, but most (all) of his benchmarks are on x86 hardware.)

The low level hardware details about how DRAM and caches work all still apply.  DDR4 uses the same commands as described for DDR1/DDR2 (read/write burst).  The DDR3/4 improvements aren't fundamental changes.  AFAIK, all the arch-independent stuff still applies generally, e.g. to AArch64 / ARM32.

See also the Latency Bound Platforms section of this answer for important details about the effect of memory/L3 latency on single-threaded bandwidth: bandwidth <= max_concurrency / latency, and this is actually the primary bottleneck for single-threaded bandwidth on a modern many-core CPU like a Xeon. But a quad-core Skylake desktop can come close to maxing out DRAM bandwidth with a single thread.  That link has some very good info about NT stores vs. normal stores on x86.  Why is Skylake so much better than Broadwell-E for single-threaded memory throughput? is a summary.

Thus Ulrich's suggestion in 6.5.8 Utilizing All Bandwidth about using remote memory on other NUMA nodes as well as your own, is counter-productive on modern hardware where memory controllers have more bandwidth than a single core can use. Well possibly you can imagine a situation where there's a net benefit to running multiple memory-hungry threads on the same NUMA node for low-latency inter-thread communication, but having them use remote memory for high bandwidth not-latency-sensitive stuff. But this is pretty obscure, normally just divide threads between NUMA nodes and have them use local memory.  Per-core bandwidth is sensitive to latency because of max-concurrency limits (see below), but all the cores in one socket can usually more than saturate the memory controllers in that socket.

(usually) Don't use software prefetch

One major thing that's changed is that hardware prefetch is much better than on the Pentium 4 and can recognize strided access patterns up to a fairly large stride, and multiple streams at once (e.g. one forward / backward per 4k page).  Intel's optimization manual describes some details of the HW prefetchers in various levels of cache for their Sandybridge-family microarchitecture.  Ivybridge and later have next-page hardware prefetch, instead of waiting for a cache miss in the new page to trigger a fast-start. I assume AMD has some similar stuff in their optimization manual.  Beware that Intel's manual is also full of old advice, some of which is only good for P4.  The Sandybridge-specific sections are of course accurate for SnB, but e.g. un-lamination of micro-fused uops changed in HSW and the manual doesn't mention it.

The usual advice these days is to remove all SW prefetch from old code, and only consider putting it back in if profiling shows cache misses (and you're not saturating memory bandwidth).  Prefetching both sides of the next step of a binary search can still help.  e.g. once you decide which element to look at next, prefetch the 1/4 and 3/4 elements so they can load in parallel with loading/checking middle.

The suggestion to use a separate prefetch thread (6.3.4) is totally obsolete, I think, and was only ever good on Pentium 4.  P4 had hyperthreading (2 logical cores sharing one physical core), but not enough trace-cache (and/or out-of-order execution resources) to gain throughput running two full computation threads on the same core.  But modern CPUs (Sandybridge-family and Ryzen) are much beefier and should either run a real thread or not use hyperthreading (leave the other logical core idle so the solo thread has the full resources instead of partitioning the ROB).

Software prefetch has always been "brittle": the right magic tuning numbers to get a speedup depend on the details of the hardware, and maybe system load.  Too early and it's evicted before the demand load.  Too late and it doesn't help.  This blog article shows code + graphs for an interesting experiment in using SW prefetch on Haswell for prefetching the non-sequential part of a problem.  See also How to properly use prefetch instructions?.  NT prefetch is interesting, but even more brittle because an early eviction from L1 means you have to go all the way to L3 or DRAM, not just L2.  If you need every last drop of performance, and you can tune for a specific machine, SW prefetch is worth looking at for sequential access, but it may still be a slowdown if you have enough ALU work to do while coming close to bottlenecking on memory.

Cache line size is still 64 bytes.  (L1D read/write bandwidth is very high, and modern CPUs can do 2 vector loads per clock + 1 vector store if it all hits in L1D.  See How can cache be that fast?.)  With AVX512, line size = vector width, so you can load/store an entire cache line in one instruction.  Thus every misaligned load/store crosses a cache-line boundary, instead of every other for 256b AVX1/AVX2, which often doesn't slow down looping over an array that wasn't in L1D.

Unaligned load instructions have zero penalty if the address is aligned at runtime, but compilers (especially gcc) make better code when autovectorizing if they know about any alignment guarantees.  Actually unaligned ops are generally fast, but page-splits still hurt (much less on Skylake, though; only ~11 extra cycles latency vs. 100, but still a throughput penalty).

As Ulrich predicted, every multi-socket system is NUMA these days: integrated memory controllers are standard, i.e. there is no external Northbridge.  But SMP no longer means multi-socket, because multi-core CPUs are widespread.  Intel CPUs from Nehalem to Skylake have used a large inclusive L3 cache as a backstop for coherency between cores. AMD CPUs are different, but I'm not as clear on the details.

Skylake-X (AVX512) no longer has an inclusive L3, but I think there's still a tag directory that lets it check what's cached anywhere on chip (and if so where) without actually broadcasting snoops to all the cores.  SKX uses a mesh rather than a ring bus, with generally even worse latency than previous many-core Xeons, unfortunately.

Basically all of the advice about optimizing memory placement still applies, just the details of exactly what happens when you can't avoid cache misses or contention vary.

6.1 Bypassing the Cache - SSE4.1 movntdqa (_mm_stream_load_si128) NT loads only ever do anything on WC memory regions.  On normal memory you get from malloc/new or mmap (WB memory attribute = write-back cacheable), movntqda runs the same as a normal SIMD load, not bypassing cache.  But it costs an extra ALU uop.   AFAIK, this was true even on CPUs at the time the article was written, making this a rare mistake in the guide.  Unlike NT stores, NT loads do not override the usual memory ordering rules for the region.  And they have to respect coherency, so they can't fully skip cache on WB-cacheable regions, the data needs to be somewhere other cores can invalidate on write.  But SSE4.1 wasn't introduced until 2nd-gen Core 2, so there weren't single-core CPUs with it.

NT prefetch (prefetchnta) can minimize cache pollution, but does still fill L1d cache, and one way of L3 on Intel CPUs with inclusive L3 cache.  But it's brittle and hard to tune: to short a prefetch distance and you get demand loads which probably defeat the NT aspect, too long and your data is evicted before use.  And since it wasn't in L2, and maybe not even L3, it might miss all the way to DRAM.  Since prefetch distance depends on the system and workload from other code, not just your own code, this is a problem.

Related:

Difference between PREFETCH and PREFETCHNTA instructions

Non-temporal loads and the hardware prefetcher, do they work together?

Copying Accelerated Video Decode Frame Buffers - Intel whitepaper describing the use-case for SSE4.1 movntdqa, reading from video RAM.

6.4.2 Atomic ops: the benchmark showing a CAS-retry loop as 4x worse than hardware-arbitrated lock add does probably still reflect a maximum contention case.  But in real multi-threaded programs, synchronization is kept to a minimum (because it's expensive), so contention is low and a CAS-retry loop usually succeeds without having to retry.

C++11 std::atomic fetch_add will compile to a lock add (or lock xadd if the return value is used), but an algorithm using CAS to do something that can't be done with a locked instruction is usually not a disaster.  Use C++11 std::atomic or C11 stdatomic instead of gcc legacy __sync built-ins or the newer __atomic built-ins unless you want to mix atomic and non-atomic access to the same location...

8.1 DWCAS (cmpxchg16b): You can coax gcc into emitting it, but if you want efficient loads of just one half of the object, you need ugly union hacks: How can I implement ABA counter with c++11 CAS?.  (Don't confuse DWCAS with DCAS of 2 separate memory locations.  Lock-free atomic emulation of DCAS isn't possible with DWCAS, but transactional memory (like x86 TSX) makes it possible.)

8.2.4 transactional memory: After a couple false starts (released then disabled by a microcode update because of a rarely-triggered bug), Intel has working transactional memory in late-model Broadwell and all Skylake CPUs.  The design is still what David Kanter described for Haswell. There's a lock-elision way to use it to speed up code that uses (and can fall back to) a regular lock (especially with a single lock for all elements of a container so multiple threads in the same critical section often don't collide), or to write code that knows about transactions directly.

Update: and now Intel has disabled lock-elision on later CPUs (including Skylake) with a microcode update.  The RTM (xbegin / xend) non-transparent part of TSX can still work if the OS allows it, but TSX in general is seriously turning into Charlie Brown's football.

Has Hardware Lock Elision gone forever due to Spectre Mitigation? (Yes but because of a MDS type of side-channel vulnerability (TAA), not Spectre.  My understanding is that updated microcode does totally disable HLE.  In that case the OS can only enable RTM, not HLE.)

7.5 Hugepages: anonymous transparent hugepages work well on Linux without having to manually use hugetlbfs.  Make allocations >= 2MiB with 2MiB alignment (e.g. posix_memalign, or an aligned_alloc that doesn't enforce the stupid ISO C++17 requirement to fail when size % alignment != 0).

A 2MiB-aligned anonymous allocation will use hugepages by default.  Some workloads (e.g. that keep using large allocations for a while after making them) may benefit from

echo defer+madvise >/sys/kernel/mm/transparent_hugepage/defrag to get the kernel to defrag physical memory whenever needed, instead of falling back to 4k pages.  (See the kernel docs). Use madvise(MADV_HUGEPAGE) after making large allocations (preferably still with 2MiB alignment) to more strongly encourage the kernel to stop and defrag now. defrag = always is too aggressive for most workloads and will spend more time copying pages around than it saves in TLB misses.  (kcompactd could maybe be more efficient.)

BTW, Intel and AMD call 2M pages "large pages", with "huge" only used for 1G pages.  Linux uses "hugepage" for everything larger than the standard size.

(32-bit mode legacy (non-PAE) page tables only had 4M pages as the next largest size, with only 2-level page tables with more compact entries.  The next size up would have been 4G, but that's the whole address space, and that "level" of translation is the CR3 control register, not a page directory entry.  IDK if that's related to Linux's terminology.)

Appendix B: Oprofile: Linux perf has mostly superseded oprofile.  perf list / perf stat -e event1,event2 ... has names for most of the useful ways to program HW performance counters.

perf stat -etask-clock,context-switches,cpu-migrations,page-faults,cycles,\
branches,branch-misses,instructions,uops_issued.any,\
uops_executed.thread,idq_uops_not_delivered.core -r2 ./a.out

A few years ago, the ocperf.py wrapper was needed to translate event names into codes, but these days perf has that functionality built-in.

For some examples of using it, see Can x86's MOV really be "free"? Why can't I reproduce this at all?.


问:
Can't BeautifulSoup show me the content of the website?
I want to scrape the contents of a website, using the library called BeautifulSoup.

Code:

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen
html_http_response = urlopen("http://www.airlinequality.com/airport-reviews/jeddah-airport/")
data = html_http_response.read()
soup = BeautifulSoup(data, "html.parser")
print(soup.prettify())
</code>```

Output:

```<code><html style="height:100%">
 <head>
  <meta content="NOINDEX, NOFOLLOW" name="ROBOTS"/>
  <meta content="telephone=no" name="format-detection"/>
  <meta content="initial-scale=1.0" name="viewport"/>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>
 </head>
 <body style="margin:0px;height:100%">
  <iframe frameborder="0" height="100%" marginheight="0px" marginwidth="0px" src="/_Incapsula_Resource?CWUDNSAI=9&xinfo=9-57435048-0%200NNN%20RT%281512733380259%202%29%20q%280%20-1%20-1%20-1%29%20r%280%20-1%29%20B12%284%2c315%2c0%29%20U19&incident_id=466002040110357581-305794245507288265&edet=12&cinfo=04000000" width="100%">
   Request unsuccessful. Incapsula incident ID: 466002040110357581-305794245507288265
  </iframe>
 </body>
</html>
</code>```

The body contains an iFrame balise instead of the content shown when inspecting the content from the browser.

答:
This website uses cookies to validate the requests. If you the website for the first time, you need to check I'm not Robot option. So it passes incap_ses_415_965359,  PHPSESSID, visid_incap_965359, _ga and _gid values on the header of the requests and sends it.

So, I got cookies from chrome dev tool and saved it in a dictionary.

```<code> from bs4 import BeautifulSoup
import requests

cookies = {
     'incap_ses_415_965359':'djRha9OqhshstDcXvPV8cmHCBQGBKloAAAAAN3/D9dvoqwEc7GPEwefkhQ==', 'PHPSESSID':'fjmr7plc0dmocm8roq7togcp92', 'visid_incap_965359':'akteT8lDT1iyST7XJO7wdQGBKloAAAns;aAAQkIPAAAAAACAWbWAAQ6Ozzrln35KG6DhLXMRYnMjxOmY', '_ga':'GA1.2.894579844.151uus2734989', '_gid':"GA1.2.1055878562.1598994989"
}
html_http_response = requests.get("http://www.airlinequality.com/airport-reviews/jeddah-airport", cookies=cookies)
data = html_http_response.text
soup = BeautifulSoup(data, "html.parser")
print(soup.prettify())
</code>```

Get cookie values from your browser and update it

Body:
I want to scrape the contents of a website, using the library called BeautifulSoup.

Code:

from bs4 import BeautifulSoup
from urllib.request import urlopen
html_http_response = urlopen("http://www.airlinequality.com/airport-reviews/jeddah-airport/")
data = html_http_response.read()
soup = BeautifulSoup(data, "html.parser")
print(soup.prettify())

Output:

  <meta content="NOINDEX, NOFOLLOW" name="ROBOTS"/>
  <meta content="telephone=no" name="format-detection"/>
  <meta content="initial-scale=1.0" name="viewport"/>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>

   Request unsuccessful. Incapsula incident ID: 466002040110357581-305794245507288265

The body contains an iFrame balise instead of the content shown when inspecting the content from the browser.

Body:
This website uses cookies to validate the requests. If you the website for the first time, you need to check I'm not Robot option. So it passes incap_ses_415_965359,  PHPSESSID, visid_incap_965359, _ga and _gid values on the header of the requests and sends it.

So, I got cookies from chrome dev tool and saved it in a dictionary.

 from bs4 import BeautifulSoup
import requests

cookies = {
     'incap_ses_415_965359':'djRha9OqhshstDcXvPV8cmHCBQGBKloAAAAAN3/D9dvoqwEc7GPEwefkhQ==', 'PHPSESSID':'fjmr7plc0dmocm8roq7togcp92', 'visid_incap_965359':'akteT8lDT1iyST7XJO7wdQGBKloAAAns;aAAQkIPAAAAAACAWbWAAQ6Ozzrln35KG6DhLXMRYnMjxOmY', '_ga':'GA1.2.894579844.151uus2734989', '_gid':"GA1.2.1055878562.1598994989"
}
html_http_response = requests.get("http://www.airlinequality.com/airport-reviews/jeddah-airport", cookies=cookies)
data = html_http_response.text
soup = BeautifulSoup(data, "html.parser")
print(soup.prettify())

Get cookie values from your browser and update it


问:
Binding input field on a single div click
I have this:

```<code><td>
    <div></div>
    <input hidden>
</td>
...
<td>
    <div></div>
    <input hidden>
</td>
</code>```

When I click the div, I want to hide the div and bind the input and so:

```<code>$(document).one("click", 'div',function(){
    $(input).bind('blur keyup',function(e) {
            ....
</code>```

BUT apparently the input gets bind only when I click IN the input again to edit it.

As a result I can click on multiple divs and not bind any of them.

How Can I click on a div and bind the input field without having to click the input field first ?!

答:
$(document).ready(function() {
  $("div").click(function() {
    $(this).hide();
    var current_input = $(this).next('input')
    current_input.css('display', 'block')

    if (current_input.val())
      alert('Entered Value "' + current_input.val() + '"')
    current_input.focus()
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.divi {
  width: 150px;
  height: 30px;
  background: gray;
  text-align: center;
}</code>```

<!DOCTYPE html>

Div 1

          <input hidden>

Div 2

          <input hidden>

```

Body:
I have this:

    <input hidden>

...

    <input hidden>

When I click the div, I want to hide the div and bind the input and so:

$(document).one("click", 'div',function(){
    $(input).bind('blur keyup',function(e) {
            ....

BUT apparently the input gets bind only when I click IN the input again to edit it.

As a result I can click on multiple divs and not bind any of them.

How Can I click on a div and bind the input field without having to click the input field first ?!

Body:
$(document).ready(function() {
  $("div").click(function() {
    $(this).hide();
    var current_input = $(this).next('input')
    current_input.css('display', 'block')

    if (current_input.val())
      alert('Entered Value "' + current_input.val() + '"')
    current_input.focus()
  });
});

.divi {
  width: 150px;
  height: 30px;
  background: gray;
  text-align: center;
}

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>
  <table>
    <tbody>
      <tr>
        <td>
          <div class="divi">Div 1</div>
          <input hidden>
        </td>
        <td>
          <div class="divi">Div 2</div>
          <input hidden>
        </td>
      </tr>
    </tbody>
  </table>
</body>

</html>


问:
FCM - Timer function in node.js
This is how I am making a firebase cloud function to send silent push notification:

```<code>exports.sendSilentPyngNotification = functions.database.ref('/SNotification/{userid}').onWrite(event => {

const userid = event.params.userid
console.log('Start sending SILENT Notificaitons:-');

// Get the list of device notification tokens for the respective user
const getDeviceTokensPromise =  admin.database().ref(`/personal/${userid}/notificationTokens`).once('value');

// Get the user profile.
const getUserProfilePromise = admin.auth().getUser(userid);

return Promise.all([getDeviceTokensPromise, getUserProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const user = results[1];

// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
  return console.log('There are no notification tokens to send to.');
}

// Notification details.
const payload = {

  notification: {
    content_available : 'true'
  },

  data : {
    senderid: 'Test',
    notificationtype: String(event.data.val().type)
  }

};

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
     console.log('Successfull sent SILENT NOTIFICATION');
  });
  return Promise.all(tokensToRemove);
});
});
});
</code>```

Question: I want to fire this silent notification function repeatedly using a timer . I really got no any idea how to write timer function in node.js for this kind of function.

Does anyone can quick guide me ?
I am an iOS Dev with no knowledge in node.js.

Thanks.

答:
You might want to look at https://nodejs.org/en/docs/guides/timers-in-node/
The easiest way to repeat any codeblock multiple times is setInterval

```<code>// The function you want to fire multiple times
function functionToRepeat() {
    // Put your code here
}

// Calls functionToRepeat every 1500ms
var intervalObj = setInterval(functionToRepeat, 1500);

// To stop the interval
clearInterval(intervalObj)
</code>```

Hope this helps!

Title: FCM - Timer function in node.js

Body:
This is how I am making a firebase cloud function to send silent push notification:

exports.sendSilentPyngNotification = functions.database.ref('/SNotification/{userid}').onWrite(event => {

const userid = event.params.userid
console.log('Start sending SILENT Notificaitons:-');

// Get the list of device notification tokens for the respective user
const getDeviceTokensPromise =  admin.database().ref(`/personal/${userid}/notificationTokens`).once('value');

// Get the user profile.
const getUserProfilePromise = admin.auth().getUser(userid);

return Promise.all([getDeviceTokensPromise, getUserProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const user = results[1];

// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
  return console.log('There are no notification tokens to send to.');
}

// Notification details.
const payload = {

  notification: {
    content_available : 'true'
  },

  data : {
    senderid: 'Test',
    notificationtype: String(event.data.val().type)
  }

};

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
     console.log('Successfull sent SILENT NOTIFICATION');
  });
  return Promise.all(tokensToRemove);
});
});
});

Question: I want to fire this silent notification function repeatedly using a timer . I really got no any idea how to write timer function in node.js for this kind of function.

Does anyone can quick guide me ?
I am an iOS Dev with no knowledge in node.js.

Thanks.

Body:
You might want to look at https://nodejs.org/en/docs/guides/timers-in-node/
The easiest way to repeat any codeblock multiple times is setInterval

// The function you want to fire multiple times
function functionToRepeat() {
    // Put your code here
}

// Calls functionToRepeat every 1500ms
var intervalObj = setInterval(functionToRepeat, 1500);

// To stop the interval
clearInterval(intervalObj)

Hope this helps!


问:
Device Chooser Offine
I'm trying to use Eclipse to write Android Apps. When I try to connect my Samsung Epic I get a message that shows it Offline. Does anyone know what the problem could be?</p>

答: Settings -> Applications-> Development -> USB debugging</p>

Title: Device Chooser Offine


问:
Javascript: Save html window as pdf using jsPDF
I am using this piece of javascript to print out some html content:

```<code>function printHTML(htmlToPrint) {
    var mywindow = window.open('', 'PRINT', 'height=400, width=600');

    mywindow.document.write("<html><head><title>My Doc Title</title>");
    mywindow.document.write("</head><body>");
    mywindow.document.write(htmlToPrint);
    mywindow.document.write("</body></html>");

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}
</code>```

And this work absolutely fine.

It opens the print dialog and then you can either 'print' it or 'save it as pdf'.

What I'd like to do is to skip the print dialog and save (download) it as pdf sraight away at the end of my function. I found a lot of suggestions to use jsPDF library for this, but couldn't find any easy examples on how to use it in my case...

Any advise is highly appreciated :)

答:
I found a nice demo here showing what you need.

There is also a codepen link for the same given at the bottom of that page where you can check out the complete code with html markup

In short, if your HTML markup is like below

```<code><div id="content">
    <h3>Sample h3 tag</h3>
    <p>Sample pararaph</p>
</div>
<button id="cmd">Generate PDF</button>
</code>```

Then on click over button, you can generate the pdf this way just by calling save function over the jsPDF object

```<code>var doc = new jsPDF();

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
        'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});
</code>```

Body:
I am using this piece of javascript to print out some html content:

function printHTML(htmlToPrint) {
    var mywindow = window.open('', 'PRINT', 'height=400, width=600');

    mywindow.document.write("<title>My Doc Title</title>");
    mywindow.document.write("");
    mywindow.document.write(htmlToPrint);
    mywindow.document.write("");

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

And this work absolutely fine.

It opens the print dialog and then you can either 'print' it or 'save it as pdf'.

What I'd like to do is to skip the print dialog and save (download) it as pdf sraight away at the end of my function. I found a lot of suggestions to use jsPDF library for this, but couldn't find any easy examples on how to use it in my case...

Any advise is highly appreciated :)

Body:
I found a nice demo here showing what you need.

There is also a codepen link for the same given at the bottom of that page where you can check out the complete code with html markup

In short, if your HTML markup is like below

<div id="content">
    <h3>Sample h3 tag</h3>
    <p>Sample pararaph</p>
</div>
<button id="cmd">Generate PDF</button>

Then on click over button, you can generate the pdf this way just by calling save function over the jsPDF object

var doc = new jsPDF();

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
        'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});


问:
Python Iterating over lists in lists with map()
So my intention is to iterate over lists in lists with map, filter and lambda
e.g.:

[ [33,3,3,0] , [34,1,0,4] ]  should result in [ [33,3,3] , [34,1,4] ]

```<code>   def no_zeros(lst):
      a=map(filter(lambda x:(y==0 for y in x) ,lst),lst)
      print (list(a))
      #(says that filter is not callable)
</code>```

I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . Im gratefull for any kind of tipps or help.

答:
map applies the function in first parameter to the second parameter. It tries to call your filter object...

A fixed version would be:

```<code>list(map(lambda z: list(filter(None,z)),lst))
</code>```

(still not very clear even if it yields the expected result... it took me 3 or 4 tries to get it right by trial & error, and the fact that filter & map need to be iterated upon in Python 3 doesn't help and kills the whole hype about those fashionable keywords)

At this point of lambda/map/filter complexity you'd be better off with a list comprehension:

```<code>lst = [ [33,3,3,0] , [34,1,0,4] ]

result = [ [x for x in sl if x] for sl in lst]

print(result)
</code>```

result:

```<code>[[33, 3, 3], [34, 1, 4]]
</code>```

Body:
So my intention is to iterate over lists in lists with map, filter and lambda
e.g.:

[ [33,3,3,0] , [34,1,0,4] ]  should result in [ [33,3,3] , [34,1,4] ]

   def no_zeros(lst):
      a=map(filter(lambda x:(y==0 for y in x) ,lst),lst)
      print (list(a))
      #(says that filter is not callable)

I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . Im gratefull for any kind of tipps or help.

Body:
map applies the function in first parameter to the second parameter. It tries to call your filter object...

A fixed version would be:

list(map(lambda z: list(filter(None,z)),lst))

(still not very clear even if it yields the expected result... it took me 3 or 4 tries to get it right by trial & error, and the fact that filter & map need to be iterated upon in Python 3 doesn't help and kills the whole hype about those fashionable keywords)

At this point of lambda/map/filter complexity you'd be better off with a list comprehension:

lst = [ [33,3,3,0] , [34,1,0,4] ]

result = [ [x for x in sl if x] for sl in lst]

print(result)

result:

[[33, 3, 3], [34, 1, 4]]


问:
Checking multiple columns for multiple value mySql
I have table with columns say:

```<code>col1, col2, col3
</code>```

I want to find if either values say 22 or 33 or 3 is/are in the columns.
For single value assume 22, I could have done:

```<code>SELECT * from table_name
WHERE 22 IN (col1, col2, col3)
</code>```

How can I find 22, 33 in columns col1, col2, col3.

Any help is highly appreciable.
Thanks!

答:
```<code>SELECT * from table_name
WHERE col1 IN (1,2,3) or
      col2 IN (1,2,3) or
      col3 IN (1,2,3)
</code>```

Maybe also like this

```<code>with search as
(
  select 1 v
  union all
  select 2 v
  union all
  select 3 v
)
select distinct t.*
from table_name t
join search s on t.col1 = s.v or t.col2 = s.v or t.col3 = s.v
</code>```

dbfiddle demo

Body:
I have table with columns say:

col1, col2, col3

I want to find if either values say 22 or 33 or 3 is/are in the columns.
For single value assume 22, I could have done:

SELECT * from table_name
WHERE 22 IN (col1, col2, col3)

How can I find 22, 33 in columns col1, col2, col3.

Any help is highly appreciable.
Thanks!

Body:
SELECT * from table_name
WHERE col1 IN (1,2,3) or
      col2 IN (1,2,3) or
      col3 IN (1,2,3)

Maybe also like this

with search as
(
  select 1 v
  union all
  select 2 v
  union all
  select 3 v
)
select distinct t.*
from table_name t
join search s on t.col1 = s.v or t.col2 = s.v or t.col3 = s.v

dbfiddle demo


问:
How to OrderBy an integer in a string field in a Linq query
I have some data coming out of an DB that I can't readily change the schema of.  I want to sort it and bind it to a control based on a numerical ID.  The problem is that the API stores the number in a string field instead of as an int and Linq barfs on the conversion attempt.

```<code>myControl.DataSource = dataFromDB.OrderBy(o => int.Parse(o.StringHoldingAnInt));
</code>```

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

Convert.ToInt32 doesn't work either.

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

Sorting as a string isn't suitable because the values aren't all the same length and it would order them like this:  1, 10, 11, 2, 3..

答:
It's possible to do it on the DB side. The idea is taken from here. So it does sorting by properly formatted string(zero chars are added to the left and then needed amount of chars is taken from the right)</p>

```<code>myControl.DataSource = dataFromDB
    .OrderBy(o =>  DbFunctions.Right("00000" + o.StringHoldingAnInt, 7));
</code>```

Body:
I have some data coming out of an DB that I can't readily change the schema of.  I want to sort it and bind it to a control based on a numerical ID.  The problem is that the API stores the number in a string field instead of as an int and Linq barfs on the conversion attempt.

myControl.DataSource = dataFromDB.OrderBy(o => int.Parse(o.StringHoldingAnInt));

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

Convert.ToInt32 doesn't work either.

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

Sorting as a string isn't suitable because the values aren't all the same length and it would order them like this:  1, 10, 11, 2, 3..

Body:
It's possible to do it on the DB side. The idea is taken from here. So it does sorting by properly formatted string(zero chars are added to the left and then needed amount of chars is taken from the right)

myControl.DataSource = dataFromDB
    .OrderBy(o =>  DbFunctions.Right("00000" + o.StringHoldingAnInt, 7));