问:
Javascript is not working after clicking on html  tag?
I have a pinch/zoom code want to execute after click on html  tag. The code works fine when I insert
 directly into the image, but it does not work after I insert  indirectly by clicking a html tag + javascript.

The idea is that the pinch/zoom code will only be executed when I click on the image. So how to fix javascript is not loading after clicking on html  tag? Does anyone have any suggestions for me? I will appreciate you a lot!

Thanks in advance!

Below is what I have done.

// Click on image and add class to pinch/zoom
$(document).ready(function(e) {
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
  jQuery.fn.extend({
    live: function (event, callback) {
      if (this.selector) {
      jQuery(document).on(event, this.selector, callback);
      }
    }
  });
}
$('a.img').click(function(){
  var link_img = $(this).attr('href');
  $('body').append('

');
  return false;
});
});

// Code pinch/zoom
"use strict";

zoom();

function zoom(classNames, settings) {
    classNames = (typeof(classNames) !== 'undefined' && Object.keys(classNames).length ? classNames : {});
    settings = (typeof(settings) !== 'undefined' && Object.keys(settings).length ? settings : {});
    var C_scaleDefault = settings["scaleDefault"] || 2;
    var C_scaleDifference = settings["scaleDifference"] || 0.5;
    var C_scaleMax = settings["scaleMax"] || 10;
    var C_scaleMin = settings["scaleMin"] || 1;
    var _active = classNames["active"] || "active";
    var _dataScale = "data-scale";
    var _dataTranslateX = "data-translate-x";
    var _dataTranslateY = "data-translate-y";
    var _transition = classNames["transition"] || "transition";
    var _visible = classNames["visible"] || "visible";
    var $container;
    var $element;
    var $zoom = document.getElementsByClassName(classNames["zoom"] || "zoom");
    var capture = false;
    var doubleClickMonitor = [null];
    var containerHeight;
    var containerWidth;
    var containerOffsetX;
    var containerOffsetY;
    var initialScale;
    var elementHeight;
    var elementWidth;
    var heightDifference;
    var initialOffsetX;
    var initialOffsetY;
    var initialPinchDistance;
    var initialPointerOffsetX;
    var initialPointerOffsetX2;
    var initialPointerOffsetY;
    var initialPointerOffsetY2;
    var limitOffsetX;
    var limitOffsetY;
    var mousemoveCount = 0;
    var offset;
    var pinchOffsetX;
    var pinchOffsetY;
    var pointerOffsetX;
    var pointerOffsetX2;
    var pointerOffsetY;
    var pointerOffsetY2;
    var scaleDirection;
    var scaleDifference;
    var targetOffsetX;
    var targetOffsetY;
    var targetPinchDistance;
    var targetScale;
    var touchable = false;
    var touchCount;
    var touchmoveCount = 0;
    var doubleTapMonitor = [null];
    var widthDifference;
    for (var i = 0; i < $zoom.length; i++) {
        $container = $zoom[i];
        $element = $container.children[0];
        $element.setAttribute(_dataScale, 1);
        $element.setAttribute(_dataTranslateX, 0);
        $element.setAttribute(_dataTranslateY, 0);
    }
    window.addEventListener("load", function() {
        for (var i = 0; i < $zoom.length; i++) {
            $container = $zoom[i];
            $element = $container.children[0];

            addClass($element, _visible);
        }
        window.addEventListener("resize", function() {
            for (var i = 0; i < $zoom.length; i++) {
                $container = $zoom[i];
                $element = $container.children[0];
                if (hasClass($container, _active) === false) {
                    continue;
                }
                containerHeight = $container.clientHeight;
                containerWidth = $container.clientWidth;
                elementHeight = $element.clientHeight;
                elementWidth = $element.clientWidth;
                initialOffsetX = parseFloat($element.getAttribute(_dataTranslateX));
                initialOffsetY = parseFloat($element.getAttribute(_dataTranslateY));
                targetScale = C_scaleDefault;
                limitOffsetX = ((elementWidth * targetScale) - containerWidth) / 2;
                limitOffsetY = ((elementHeight * targetScale) - containerHeight) / 2;
                targetOffsetX = (elementWidth * targetScale) > containerWidth ? minMax(initialOffsetX, limitOffsetX * (-1), limitOffsetX) : 0;
                targetOffsetY = (elementHeight * targetScale) > containerHeight ? minMax(initialOffsetY, limitOffsetY * (-1), limitOffsetY) : 0;
                if (targetScale === 1) {
                    removeClass($container, _active);
                }
                $element.setAttribute(_dataScale, targetScale);
                $element.setAttribute(_dataTranslateX, targetOffsetX);
                $element.setAttribute(_dataTranslateY, targetOffsetY);
                moveScaleElement($element, targetOffsetX + "px", targetOffsetY + "px", targetScale);
            }
        });
    });
    massAddEventListener($zoom, "mousedown", mouseDown);
    massAddEventListener($zoom, "mouseenter", mouseEnter);
    massAddEventListener($zoom, "mouseleave", mouseLeave);
    document.addEventListener("mousemove", mouseMove);
    document.addEventListener("mouseup", mouseUp);
    document.addEventListener("touchstart", function() {
        touchable = true;
    });
    massAddEventListener($zoom, "touchstart", touchStart);
    document.addEventListener("touchmove", touchMove);
    document.addEventListener("touchend", touchEnd);
    massAddEventListener($zoom, "wheel", wheel);
    function mouseEnter() {
        disableScroll();
    }
    function mouseLeave() {
        enableScroll();
    }
    function mouseDown(e) {
        e.preventDefault();

        if (touchable === true || e.which !== 1) {
            return false;
        }
        $container = this;
        $element = this.children[0];
        initialPointerOffsetX = e.clientX;
        initialPointerOffsetY = e.clientY;
        if (doubleClickMonitor[0] === null) {
            doubleClickMonitor[0] = e.target;
            doubleClickMonitor[1] = initialPointerOffsetX;
            doubleClickMonitor[2] = initialPointerOffsetY;
            setTimeout(function() {
                doubleClickMonitor = [null];
            }, 300);
        } else if (doubleClickMonitor[0] === e.target && mousemoveCount <= 5 && isWithinRange(initialPointerOffsetX, doubleClickMonitor[1] - 10, doubleClickMonitor[1] + 10) === true && isWithinRange(initialPointerOffsetY, doubleClickMonitor[2] - 10, doubleClickMonitor[2] + 10) === true) {
            addClass($element, _transition);

            if (hasClass($container, _active) === true) {
                $element.setAttribute(_dataScale, 1);
                $element.setAttribute(_dataTranslateX, 0);
                $element.setAttribute(_dataTranslateY, 0);

                removeClass($container, _active);
                moveScaleElement($element, 0, 0, 1);
            } else {
                $element.setAttribute(_dataScale, C_scaleDefault);
                $element.setAttribute(_dataTranslateX, 0);
                $element.setAttribute(_dataTranslateY, 0);
                addClass($container, _active);
                moveScaleElement($element, 0, 0, C_scaleDefault);
            }
            setTimeout(function()
            {
                removeClass($element, _transition);
            }, 200);
            doubleClickMonitor = [null];
            return false;
        }
        offset = $container.getBoundingClientRect();
        containerOffsetX = offset.left;
        containerOffsetY = offset.top;
        containerHeight = $container.clientHeight;
        containerWidth = $container.clientWidth
        elementHeight = $element.clientHeight;
        elementWidth = $element.clientWidth;
        initialOffsetX = parseFloat($element.getAttribute(_dataTranslateX));
        initialOffsetY = parseFloat($element.getAttribute(_dataTranslateY));
        initialScale = minMax(parseFloat($element.getAttribute(_dataScale)), C_scaleMin, C_scaleMax);
        mousemoveCount = 0;
        capture = true;
    }
    function mouseMove(e) {
        if (touchable === true || capture === false) {
            return false;
        }
        pointerOffsetX = e.clientX;
        pointerOffsetY = e.clientY;
        targetScale = initialScale;
        limitOffsetX = ((elementWidth * targetScale) - containerWidth) / 2;
        limitOffsetY = ((elementHeight * targetScale) - containerHeight) / 2;
        targetOffsetX = (elementWidth * targetScale) <= containerWidth ? 0 : minMax(pointerOffsetX - (initialPointerOffsetX - initialOffsetX), limitOffsetX * (-1), limitOffsetX);
        targetOffsetY = (elementHeight * targetScale) <= containerHeight ? 0 : minMax(pointerOffsetY - (initialPointerOffsetY - initialOffsetY), limitOffsetY * (-1), limitOffsetY);
        mousemoveCount++;

        if (Math.abs(targetOffsetX) === Math.abs(limitOffsetX)) {
            initialOffsetX = targetOffsetX;
            initialPointerOffsetX = pointerOffsetX;
        }

        if (Math.abs(targetOffsetY) === Math.abs(limitOffsetY)) {
            initialOffsetY = targetOffsetY;
            initialPointerOffsetY = pointerOffsetY;
        }
        $element.setAttribute(_dataScale, targetScale);
        $element.setAttribute(_dataTranslateX, targetOffsetX);
        $element.setAttribute(_dataTranslateY, targetOffsetY);
        moveScaleElement($element, targetOffsetX + "px", targetOffsetY + "px", targetScale);
    }
    function mouseUp() {
        if (touchable === true || capture === false) {
            return false;
        }
        capture = false;
    }
    function touchStart(e) {
        e.preventDefault();
        if (e.touches.length > 2) {
            return false;
        }
        $container = this;
        $element = this.children[0];
        offset = $container.getBoundingClientRect();
        containerOffsetX = offset.left;
        containerOffsetY = offset.top;
        containerHeight = $container.clientHeight;
        containerWidth = $container.clientWidth;
        elementHeight = $element.clientHeight;
        elementWidth = $element.clientWidth;
        initialPointerOffsetX = e.touches[0].clientX;
        initialPointerOffsetY = e.touches[0].clientY;
        initialScale = minMax(parseFloat($element.getAttribute(_dataScale)), C_scaleMin, C_scaleMax);
        touchCount = e.touches.length;
        if (touchCount === 1) {
            if (doubleTapMonitor[0] === null) {
                doubleTapMonitor[0] = e.target;
                doubleTapMonitor[1] = initialPointerOffsetX;
                doubleTapMonitor[2] = initialPointerOffsetY;
                setTimeout(function() {
                    doubleTapMonitor = [null];
                }, 300);
            } else if (doubleTapMonitor[0] === e.target && touchmoveCount <= 1 && isWithinRange(initialPointerOffsetX, doubleTapMonitor[1] - 10, doubleTapMonitor[1] + 10) === true && isWithinRange(initialPointerOffsetY, doubleTapMonitor[2] - 10, doubleTapMonitor[2] + 10) === true) {
                addClass($element, _transition);
                if (hasClass($container, _active) === true) {
                    $element.setAttribute(_dataScale, 1);
                    $element.setAttribute(_dataTranslateX, 0);
                    $element.setAttribute(_dataTranslateY, 0);
                    removeClass($container, _active);
                    moveScaleElement($element, 0, 0, 1);
                } else {
                    $element.setAttribute(_dataScale, C_scaleDefault);
                    $element.setAttribute(_dataTranslateX, 0);
                    $element.setAttribute(_dataTranslateY, 0);
                    addClass($container, _active);
                    moveScaleElement($element, 0, 0, C_scaleDefault);
                }
                setTimeout(function()
                {
                    removeClass($element, _transition);
                }, 200);
                doubleTapMonitor = [null];
                return false;
            }
            initialOffsetX = parseFloat($element.getAttribute(_dataTranslateX));
            initialOffsetY = parseFloat($element.getAttribute(_dataTranslateY));
        } else if (touchCount === 2) {
            initialOffsetX = parseFloat($element.getAttribute(_dataTranslateX));
            initialOffsetY = parseFloat($element.getAttribute(_dataTranslateY));
            initialPointerOffsetX2 = e.touches[1].clientX;
            initialPointerOffsetY2 = e.touches[1].clientY;
            pinchOffsetX = (initialPointerOffsetX + initialPointerOffsetX2) / 2;
            pinchOffsetY = (initialPointerOffsetY + initialPointerOffsetY2) / 2;
            initialPinchDistance = Math.sqrt(((initialPointerOffsetX - initialPointerOffsetX2) * (initialPointerOffsetX - initialPointerOffsetX2)) + ((initialPointerOffsetY - initialPointerOffsetY2) * (initialPointerOffsetY - initialPointerOffsetY2)));
        }
        touchmoveCount = 0;
        capture = true;
    }
    function touchMove(e) {
        e.preventDefault();
        if (capture === false) {
            return false;
        }
        pointerOffsetX = e.touches[0].clientX;
        pointerOffsetY = e.touches[0].clientY;
        touchCount = e.touches.length;
        touchmoveCount++;
        if (touchCount > 1) {
            pointerOffsetX2 = e.touches[1].clientX;
            pointerOffsetY2 = e.touches[1].clientY;
            targetPinchDistance = Math.sqrt(((pointerOffsetX - pointerOffsetX2) * (pointerOffsetX - pointerOffsetX2)) + ((pointerOffsetY - pointerOffsetY2) * (pointerOffsetY - pointerOffsetY2)));
            if (initialPinchDistance === null) {
                initialPinchDistance = targetPinchDistance;
            }
            if (Math.abs(initialPinchDistance - targetPinchDistance) >= 1) {
                targetScale = minMax(targetPinchDistance / initialPinchDistance * initialScale, C_scaleMin, C_scaleMax);
                limitOffsetX = ((elementWidth * targetScale) - containerWidth) / 2;
                limitOffsetY = ((elementHeight * targetScale) - containerHeight) / 2;
                scaleDifference = targetScale - initialScale;
                targetOffsetX = (elementWidth * targetScale) <= containerWidth ? 0 : minMax(initialOffsetX - ((((((pinchOffsetX - containerOffsetX) - (containerWidth / 2)) - initialOffsetX) / (targetScale - scaleDifference))) * scaleDifference), limitOffsetX * (-1), limitOffsetX);
                targetOffsetY = (elementHeight * targetScale) <= containerHeight ? 0 : minMax(initialOffsetY - ((((((pinchOffsetY - containerOffsetY) - (containerHeight / 2)) - initialOffsetY) / (targetScale - scaleDifference))) * scaleDifference), limitOffsetY * (-1), limitOffsetY);
                if (targetScale > 1) {
                    addClass($container, _active);
                } else {
                    removeClass($container, _active);
                }
                moveScaleElement($element, targetOffsetX + "px", targetOffsetY + "px", targetScale);
                initialPinchDistance = targetPinchDistance;
                initialScale = targetScale;
                initialOffsetX = targetOffsetX;
                initialOffsetY = targetOffsetY;
            }
        } else {
            targetScale = initialScale;
            limitOffsetX = ((elementWidth * targetScale) - containerWidth) / 2;
            limitOffsetY = ((elementHeight * targetScale) - containerHeight) / 2;
            targetOffsetX = (elementWidth * targetScale) <= containerWidth ? 0 : minMax(pointerOffsetX - (initialPointerOffsetX - initialOffsetX), limitOffsetX * (-1), limitOffsetX);
            targetOffsetY = (elementHeight * targetScale) <= containerHeight ? 0 : minMax(pointerOffsetY - (initialPointerOffsetY - initialOffsetY), limitOffsetY * (-1), limitOffsetY);
            if (Math.abs(targetOffsetX) === Math.abs(limitOffsetX)) {
                initialOffsetX = targetOffsetX;
                initialPointerOffsetX = pointerOffsetX;
            }
            if (Math.abs(targetOffsetY) === Math.abs(limitOffsetY)) {
                initialOffsetY = targetOffsetY;
                initialPointerOffsetY = pointerOffsetY;
            }
            $element.setAttribute(_dataScale, initialScale);
            $element.setAttribute(_dataTranslateX, targetOffsetX);
            $element.setAttribute(_dataTranslateY, targetOffsetY);
            moveScaleElement($element, targetOffsetX + "px", targetOffsetY + "px", targetScale);
        }
    }
    function touchEnd(e) {
        touchCount = e.touches.length;
        if (capture === false) {
            return false;
        }
        if (touchCount === 0) {
            $element.setAttribute(_dataScale, initialScale);
            $element.setAttribute(_dataTranslateX, targetOffsetX);
            $element.setAttribute(_dataTranslateY, targetOffsetY);
            initialPinchDistance = null;
            capture = false;
        } else if (touchCount === 1) /* Single touch */ {
            initialPointerOffsetX = e.touches[0].clientX;
            initialPointerOffsetY = e.touches[0].clientY;
        } else if (touchCount > 1) /* Pinch */ {
            initialPinchDistance = null;
        }
    }
    function wheel(e) {
        $container = this;
        $element = this.children[0];
        offset = $container.getBoundingClientRect();
        containerHeight = $container.clientHeight;
        containerWidth = $container.clientWidth;
        elementHeight = $element.clientHeight;
        elementWidth = $element.clientWidth;
        containerOffsetX = offset.left;
        containerOffsetY = offset.top;
        initialScale = minMax(parseFloat($element.getAttribute(_dataScale), C_scaleMin, C_scaleMax));
        initialOffsetX = parseFloat($element.getAttribute(_dataTranslateX));
        initialOffsetY = parseFloat($element.getAttribute(_dataTranslateY));
        pointerOffsetX = e.clientX;
        pointerOffsetY = e.clientY;
        scaleDirection = e.deltaY < 0 ? 1 : -1;
        scaleDifference = C_scaleDifference * scaleDirection;
        targetScale = initialScale + scaleDifference;
        if (targetScale < C_scaleMin || targetScale > C_scaleMax) {
            return false;
        }
        limitOffsetX = ((elementWidth * targetScale) - containerWidth) / 2;
        limitOffsetY = ((elementHeight * targetScale) - containerHeight) / 2;
        if (targetScale <= 1) {
            targetOffsetX = 0;
            targetOffsetY = 0;
        } else {
            targetOffsetX = (elementWidth * targetScale) <= containerWidth ? 0 : minMax(initialOffsetX - ((((((pointerOffsetX - containerOffsetX) - (containerWidth / 2)) - initialOffsetX) / (targetScale - scaleDifference))) * scaleDifference), limitOffsetX * (-1), limitOffsetX);
            targetOffsetY = (elementHeight * targetScale) <= containerHeight ? 0 : minMax(initialOffsetY - ((((((pointerOffsetY - containerOffsetY) - (containerHeight / 2)) - initialOffsetY) / (targetScale - scaleDifference))) * scaleDifference), limitOffsetY * (-1), limitOffsetY);
        }
        if (targetScale > 1) {
            addClass($container, _active);
        } else {
            removeClass($container, _active);
        }
        $element.setAttribute(_dataScale, targetScale);
        $element.setAttribute(_dataTranslateX, targetOffsetX);
        $element.setAttribute(_dataTranslateY, targetOffsetY);
        moveScaleElement($element, targetOffsetX + "px", targetOffsetY + "px", targetScale);
    }
}
function addClass($element, targetClass) {
    if (hasClass($element, targetClass) === false) {
        $element.className += " " + targetClass;
    }
}
function disableScroll() {
    if (window.addEventListener)
    {
        window.addEventListener('DOMMouseScroll', preventDefault, false);
    }
    window.onwheel = preventDefault;
    window.onmousewheel = document.onmousewheel = preventDefault;
    window.ontouchmove = preventDefault;
    document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
    if (window.removeEventListener) {
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    }
    window.onmousewheel = document.onmousewheel = null;
    window.onwheel = null;
    window.ontouchmove = null;
    document.onkeydown = null;
}
function isWithinRange(value, min, max) {
    if (value >= min && value <= max) {
        return true;
    } else {
        return false;
    }
}
function hasClass($element, targetClass) {
    var rgx = new RegExp("(?:^|\\s)" + targetClass + "(?!\\S)", "g");
    if ($element.className.match(rgx)) {
        return true;
    } else {
        return false;
    }
}
function massAddEventListener($elements, event, customFunction, useCapture) {
    var useCapture = useCapture || false;
    for (var i = 0; i < $elements.length; i++) {
        $elements[i].addEventListener(event, customFunction, useCapture);
    }
}
function minMax(value, min, max) {
    if (value < min) {
        value = min;
    } else if (value > max) {
        value = max;
    }
    return value;
}
function moveScaleElement($element, targetOffsetX, targetOffsetY, targetScale) {
    $element.style.cssText = "-moz-transform : translate(" + targetOffsetX + ", " + targetOffsetY + ") scale(" + targetScale + "); -ms-transform : translate(" + targetOffsetX + ", " + targetOffsetY + ") scale(" + targetScale + "); -o-transform : translate(" + targetOffsetX + ", " + targetOffsetY + ") scale(" + targetScale + "); -webkit-transform : translate(" + targetOffsetX + ", " + targetOffsetY + ") scale(" + targetScale + "); transform : translate3d(" + targetOffsetX + ", " + targetOffsetY + ", 0) scale3d(" + targetScale + ", " + targetScale + ", 1);";
}
function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    }
    e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
    var keys = {
        37: 1,
        38: 1,
        39: 1,
        40: 1
    };
    if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
    }
}
function removeClass($element, targetClass) {
    var rgx = new RegExp("(?:^|\\s)" + targetClass + "(?!\\S)", "g");

    $element.className = $element.className.replace(rgx, "");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- insert <div class="zoom"> indirectly with javascript through class "img"-->

<img border="0" src="https://3.bp.blogspot.com/-SrY4SGEWA0U/XkzC8iFrPWI/AAAAAAAAFck/pj319hsOteYRIVjJ2Z8RNJ5y_fjr_e8xQCKgBGAsYHg/s1600/ban-nha-duong-so-59-phuong-14-quan-go-vap-2.jpg"/>

<!-- insert <div class = "zoom"> directly-->
<div class="zoom">

<img border="0" src="https://3.bp.blogspot.com/-SrY4SGEWA0U/XkzC8iFrPWI/AAAAAAAAFck/pj319hsOteYRIVjJ2Z8RNJ5y_fjr_e8xQCKgBGAsYHg/s1600/ban-nha-duong-so-59-phuong-14-quan-go-vap-2.jpg"/>

</div></code>```

答:
You can add event.preventDefault(); to prevent  click default;

```<code>$('a.img').click(function(event){
  event.preventDefault();
</code>```

See document
https://api.jquery.com/event.preventdefault/

Title: Javascript is not working after clicking on html <a> tag?

Body:
You can add event.preventDefault(); to prevent  click default;

$('a.img').click(function(event){
  event.preventDefault();

See document
https://api.jquery.com/event.preventdefault/


来源: stackexchange

问:
How to allow empty value for Laravel numeric validation
How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...</p>

```<code>$this->validate($request, [
        'provinces_id' => 'required|numeric',
        'type' => 'required',
        'bed' => 'numeric',
]);
</code>```

答: In Laravel 6 or 5.8, you should use nullable. But sometimes keyword doesn't work on that versions.

ContentLicense: CC BY-SA 4.0

Body:
How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...

$this->validate($request, [
        'provinces_id' => 'required|numeric',
        'type' => 'required',
        'bed' => 'numeric',
]);


问:
replace literal value by variable in for loop
I have this code that works as expected. "db" is MongoClient object.

```<code>collections = {
    "cmrb": cmrb,
    "rbss": rbss,
    "ndrb": ndrb,
    "nder": nder,
    "rbph": rbph,
    "rb90": rb90,
    "rbphne": rbphne,
    "dirb": dirb,
}

c=db.cmrb
c.insert_one(collections['cmrb'])
</code>```

But when I replace the collection name with variable i using for loop, all the entries gets added to collection "i" and not to "cmrb", "rbss" etc.

```<code>for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])
</code>```

What is wrong with the code mentioned above? How do I replace the literal "i"?

答:
That's because MongoClient is assuming i as a name of collection, in this case you have to use indexing operator to access the collection.

Replace:

```<code>for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])
</code>```

With:

```<code>for i in collections.keys():
    c = db[i]
    c.insert_one(collections[i])
</code>```

Body:
I have this code that works as expected. "db" is MongoClient object.

collections = {
    "cmrb": cmrb,
    "rbss": rbss,
    "ndrb": ndrb,
    "nder": nder,
    "rbph": rbph,
    "rb90": rb90,
    "rbphne": rbphne,
    "dirb": dirb,
}

c=db.cmrb
c.insert_one(collections['cmrb'])

But when I replace the collection name with variable i using for loop, all the entries gets added to collection "i" and not to "cmrb", "rbss" etc.

for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])

What is wrong with the code mentioned above? How do I replace the literal "i"?

Body:
That's because MongoClient is assuming i as a name of collection, in this case you have to use indexing operator to access the collection.

Replace:

for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])

With:

for i in collections.keys():
    c = db[i]
    c.insert_one(collections[i])


问:
Plus and minus button (Javascript)
I have tried out the add and minus button.

The thing i am trying to do is if i have selected 10 bus tickets, then how do i write a javascript function to limit the maximum of the input. For instance, if adult is increment by 1, then the maximum input for the child will be changed into 9.

Here is my code

function myFunction() {
  var adult = document.getElementByID("adult").value;
  var child = document.getElementByID("child").value;
  var maxAdult = document.getElementByID("adult").max;
  var maxChild = document.getElementByID("child").max;
  if (adult + 1) {
    maxChild = -1;
  }
  if (adult + 1) {
    maxAdult = -1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="input-group" style="width: 150px;margin: 20px;">
  <span class="input-group-btn"> <!--  This is for adult tickets -->
  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
  </span>
  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">
  <span class="input-group-btn">
  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
    <span class="glyphicon glyphicon-plus"></span>
  </button>
  </span>
</div>
<div class="input-group" style="width: 150px;margin: 20px;">
  <span class="input-group-btn"> <!-- This is for child tickets -->
  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
  </span>
  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">
  <span class="input-group-btn">
  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
    <span class="glyphicon glyphicon-plus"></span>
  </button>
  </span>
</div></code>```

答:
const all_count = 10;
let adult_count = 0;
let child_count = 0;

$('.btn-number').on("click", function() {
  let role = $(this).closest("div").attr("id");
  let type = $(this).attr("data-type");

  switch (role) {
    case 'adult':
      switch (type) {
        case 'plus':
          if ((adult_count + child_count) < all_count)
            adult_count++;
          break;
        case 'minus':
          if (adult_count != 0)
            adult_count--;
          break;
      }
      $('#adult_input').val(adult_count);
      break;
    case 'child':
      switch (type) {
        case 'plus':
          if ((adult_count + child_count) < all_count)
            child_count++;
          break;
        case 'minus':
          if (child_count != 0)
            child_count--;
          break;
      }
      $('#child_input').val(child_count);
      break;
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <h4>This is for adult tickets</h4>
    <div id="adult">
      <span class="input-group-btn">
      <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
      <span class="glyphicon glyphicon-minus"></span>
      </button>
      </span>
      <input type="text" name="quant1" id="adult_input" class="form-control input-number" value="0" min="0" max="5">
      <span class="input-group-btn">
        <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
        <span class="glyphicon glyphicon-plus"></span>
      </button>
      </span>
    </div>

    <h4>This is for child tickets</h4>
    <div id="child">
      <span class="input-group-btn">
      <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
      <span class="glyphicon glyphicon-minus"></span>
      </button>
      </span>
      <input type="text" name="quant1" id="child_input" class="form-control input-number" value="0" min="0" max="5">
      <span class="input-group-btn">
        <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
        <span class="glyphicon glyphicon-plus"></span>
      </button>
      </span>
    </div>

</body>

</html></code>```

Title: Plus and minus button (Javascript)

Body:
I have tried out the add and minus button.

The thing i am trying to do is if i have selected 10 bus tickets, then how do i write a javascript function to limit the maximum of the input. For instance, if adult is increment by 1, then the maximum input for the child will be changed into 9.

Here is my code

function myFunction() {
  var adult = document.getElementByID("adult").value;
  var child = document.getElementByID("child").value;
  var maxAdult = document.getElementByID("adult").max;
  var maxChild = document.getElementByID("child").max;
  if (adult + 1) {
    maxChild = -1;
  }
  if (adult + 1) {
    maxAdult = -1;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">

  </button>

  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">

  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">

  </button>

  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">

  </button>

  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">

  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">

  </button>

Body:
const all_count = 10;
let adult_count = 0;
let child_count = 0;

$('.btn-number').on("click", function() {
  let role = $(this).closest("div").attr("id");
  let type = $(this).attr("data-type");

  switch (role) {
    case 'adult':
      switch (type) {
        case 'plus':
          if ((adult_count + child_count) < all_count)
            adult_count++;
          break;
        case 'minus':
          if (adult_count != 0)
            adult_count--;
          break;
      }
      $('#adult_input').val(adult_count);
      break;
    case 'child':
      switch (type) {
        case 'plus':
          if ((adult_count + child_count) < all_count)
            child_count++;
          break;
        case 'minus':
          if (child_count != 0)
            child_count--;
          break;
      }
      $('#child_input').val(child_count);
      break;
  }

});

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <h4>This is for adult tickets</h4>
    <div id="adult">
      <span class="input-group-btn">
      <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
      <span class="glyphicon glyphicon-minus"></span>
      </button>
      </span>
      <input type="text" name="quant1" id="adult_input" class="form-control input-number" value="0" min="0" max="5">
      <span class="input-group-btn">
        <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
        <span class="glyphicon glyphicon-plus"></span>
      </button>
      </span>
    </div>

    <h4>This is for child tickets</h4>
    <div id="child">
      <span class="input-group-btn">
      <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
      <span class="glyphicon glyphicon-minus"></span>
      </button>
      </span>
      <input type="text" name="quant1" id="child_input" class="form-control input-number" value="0" min="0" max="5">
      <span class="input-group-btn">
        <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
        <span class="glyphicon glyphicon-plus"></span>
      </button>
      </span>
    </div>

</body>

</html>


问:
Is it possible to create annotation which would check if user is authenticated? Kotlin
I am writing an app, and some parts of it require the user to be authenticated. Is it possible to write an annotation for a method, which would check user status, and depending on it either function would be called or it would navigate to the login screen -> if login success it will come back and call the function? like this:</p>

```<code>@RequiresAuth
fun commentOnTask(){
    ...
}
</code>```

答:
No, by this time I could not find a way of how to do it with annotation.

The only workaround is to use such a pattern https://codelabs.developers.google.com/codelabs/advanced-android-kotlin-training-login-navigation/index.html?index=..%2F..index#9

Body:
I am writing an app, and some parts of it require the user to be authenticated. Is it possible to write an annotation for a method, which would check user status, and depending on it either function would be called or it would navigate to the login screen -> if login success it will come back and call the function? like this:

@RequiresAuth
fun commentOnTask(){
    ...
}


问:
Winform-Export To Excel - XLWorkbook - Date and Time NumberFormat
My Requirement is -

I have to export Datatable to .xls file.

For all Date Columns in Datatable, the excel cell should be of Date Format instead of Text or General.
This is because, the user can filter data according to date as required.

MY CODE

```<code>            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            StringBuilder sb = new StringBuilder();
            sb.Append("<html><body>");
            sb.Append("<table style='border: 1px solid black;'>");
            var index = 1;
            sb.Append("<tr>");
            sb.Append("<th colspan='9'>SANJAY MALAKIYA</th>");
            sb.Append("</tr>");
            sb.Append("<tr></tr>");
            sb.Append("<tr>");
            sb.Append("<td colspan='9'><b>SANJAY</td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td style='border: 1px solid black'>SrNO</td>");
            foreach (DataColumn column in dtDataTable1.Columns)
            {
                sb.Append("<td style='border: 1px solid black'>" + column.ColumnName + "</td>");
            }
            sb.Append("</tr>");
            ExcelApp.Windows.Application.ActiveWindow.DisplayGridlines = false;
            StringBuilder objSB = new StringBuilder();

            foreach (DataRow row in dtDataTable1.Rows)
            {
                sb.Append("<tr>");

                sb.Append("<td style='width:100px;border: 1px solid black'>" + index.ToString() + "</td>");
                foreach (DataColumn column in dtDataTable1.Columns)
                {
                    sb.Append("<td style='width:100px;border: 1px solid black'>" + row[column.ColumnName].ToString() + "</td>");
                }
                index++;
                sb.Append("</tr>");
            }
            if (dtDataTable1.Rows.Count > 0)
            {

                ExcelApp.Columns.AutoFit();

            }
            sb.Append("</table>");
            sb.Append("</body></html>");
            String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
            if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
            {
                Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
            }
            using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate + "\\Summury_final " + Convert.ToDateTime(cmbmonth.SelectedItem).ToString("dd/MM/yyyy") + ".XLS"))
            {
                file.WriteLine(sb.ToString());
            }
            Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook1 = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            xlWorkBook1 = Excel.Workbooks.Open("C:\\Users\\Krupal\\Desktop\\" + Todaysdate + "\\Summury_final " + Convert.ToDateTime(cmbmonth.SelectedItem).ToString("dd/MM/yyyy") + ".XLS", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Microsoft.Office.Interop.Excel.Worksheet Wt = (Excel.Worksheet)xlWorkBook1.Worksheets.get_Item(1);
            Excel.Visible = true;
</code>```

答:
You can set the date format like below</p>

```<code>Range rg = (Excel.Range)worksheetobject.Cells[1,1];
rg.EntireColumn.NumberFormat = "MM/DD/YYYY";
</code>```

Body:
My Requirement is -

I have to export Datatable to .xls file.

For all Date Columns in Datatable, the excel cell should be of Date Format instead of Text or General.
This is because, the user can filter data according to date as required.

MY CODE

            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            StringBuilder sb = new StringBuilder();
            sb.Append("");
            sb.Append("
");
            var index = 1;
            sb.Append("
");
            sb.Append("SANJAY MALAKIYA	");
            sb.Append("
");
            sb.Append("

");
            sb.Append("
");
            sb.Append("SANJAY	");
            sb.Append("
");
            sb.Append("
");
            sb.Append("SrNO	");
            foreach (DataColumn column in dtDataTable1.Columns)
            {
                sb.Append("" + column.ColumnName + "	");
            }
            sb.Append("
");
            ExcelApp.Windows.Application.ActiveWindow.DisplayGridlines = false;
            StringBuilder objSB = new StringBuilder();

            foreach (DataRow row in dtDataTable1.Rows)
            {
                sb.Append("
");

                sb.Append("" + index.ToString() + "	");
                foreach (DataColumn column in dtDataTable1.Columns)
                {
                    sb.Append("" + row[column.ColumnName].ToString() + "	");
                }
                index++;
                sb.Append("
");
            }
            if (dtDataTable1.Rows.Count > 0)
            {

                ExcelApp.Columns.AutoFit();

            }
            sb.Append("
");
            sb.Append("");
            String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
            if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
            {
                Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
            }
            using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate + "\\Summury_final " + Convert.ToDateTime(cmbmonth.SelectedItem).ToString("dd/MM/yyyy") + ".XLS"))
            {
                file.WriteLine(sb.ToString());
            }
            Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook1 = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            xlWorkBook1 = Excel.Workbooks.Open("C:\\Users\\Krupal\\Desktop\\" + Todaysdate + "\\Summury_final " + Convert.ToDateTime(cmbmonth.SelectedItem).ToString("dd/MM/yyyy") + ".XLS", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Microsoft.Office.Interop.Excel.Worksheet Wt = (Excel.Worksheet)xlWorkBook1.Worksheets.get_Item(1);
            Excel.Visible = true;

Body:
You can set the date format like below

Range rg = (Excel.Range)worksheetobject.Cells[1,1];
rg.EntireColumn.NumberFormat = "MM/DD/YYYY";


问:
Why use different type and constructor when instantiating a class?
Suppose we have a class ProductA that inherited another class called Product. What's the meaning of

```<code>Product product = new ProductA();
</code>```

And what's the difference between that and

```<code>ProductA product = new ProductA();
</code>```

答:
A big difference. A context difference. A generality difference. Let me give you a simple example

```<code>public class Animal {
 ...
}
</code>```

and

```<code>public class Dog : Animal {
...
}
</code>```

then if you have a Animal dog = new Dog(); that's not going to expose (in the compile time realm) any additional properties the dog has over the animal. your "dog" is just an animal and as such it should be treated. nothing additional will appear in intellisense auto complete for example. All you want to "know" when you are using this object is therefor limited to it being an animal. if you have a Dog dog = new Dog(); you want (in the compile time realm) to treat it like a dog. It will expose it's full functionality and properties. A dog has a tail, and an animal doesn't for example. Do you want to use "tail" property in your code?

Also suppose you have a DogTender with a TakeCareOfDog(Dog myDoggy) method. If you stated Animal dog = new Dog(); well than the instance of DogTender can't handle your dog (because it's not a dog. It's an animal). However, your animal can fit well in an AnimalCollection (like a Zoo). We call this the Liskov principle or the Substitution principle - the decendant classes tell their base class  - "anything you can do, I can do better". Anything an Animal can do, a dog can also do, but not the other way around.

Body:
Suppose we have a class ProductA that inherited another class called Product. What's the meaning of

Product product = new ProductA();

And what's the difference between that and

ProductA product = new ProductA();

Body:
A big difference. A context difference. A generality difference. Let me give you a simple example

public class Animal {
 ...
}

and

public class Dog : Animal {
...
}

then if you have a Animal dog = new Dog(); that's not going to expose (in the compile time realm) any additional properties the dog has over the animal. your "dog" is just an animal and as such it should be treated. nothing additional will appear in intellisense auto complete for example. All you want to "know" when you are using this object is therefor limited to it being an animal. if you have a Dog dog = new Dog(); you want (in the compile time realm) to treat it like a dog. It will expose it's full functionality and properties. A dog has a tail, and an animal doesn't for example. Do you want to use "tail" property in your code?

Also suppose you have a DogTender with a TakeCareOfDog(Dog myDoggy) method. If you stated Animal dog = new Dog(); well than the instance of DogTender can't handle your dog (because it's not a dog. It's an animal). However, your animal can fit well in an AnimalCollection (like a Zoo). We call this the Liskov principle or the Substitution principle - the decendant classes tell their base class  - "anything you can do, I can do better". Anything an Animal can do, a dog can also do, but not the other way around.


问:
The response received in AJAX call is shown in another HTML page
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.

Form HTML

```<code><form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
    <div class="form-group">
        <input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
        <button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
    </div>
</form>
</code>```

AJAX

```<code><script>
    $("#AssociateForm").submit(function(e) {
        e.preventDefault();

        var form = $(this);
        var url = form.attr('action');

        var local_id = $('input[name=J_ID]').attr('id');

        var formData = {
            'J_ID' : $('input[name=J_ID]').val()
        };
        console.log(formData)

        $.ajax({
            url: url,
            data: formData,
            dataType: 'json',

            success: function (datas) {
                var data = JSON.parse(datas);
                if(datas.status){
                    alert(datas);
                   //$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
                }
            },
            error: function(jqXHR, textStatus){
                alert("In error")
            }
        })
        .done(function(data){
            alert(data)
        });
    });
</script>
</code>```

for some reason, the above code is not printing the console log as well.

But,

When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.

JSON Response

{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

below is from View-Page-source

```<code><html>
   <head></head>
   <body data-gr-c-s-loaded="true">
     <pre style="word-wrap: break-word; white-space: pre-wrap;">

        {"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

     ```

```

答:
```<code>success: function (datas) {
            if (datas.status) {
                alert(datas);
                $('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
            }
        }
</code>```

Body:
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.

Form HTML

<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">

        <input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
        <button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>

</form>

AJAX

for some reason, the above code is not printing the console log as well.

But,

When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.

JSON Response

{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

below is from View-Page-source

        {"category": "known", "j_id": "AU298", "j_status": "Confirmed"}


问:
round() doesn't seem to be rounding properly
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:

```<code>n = 5.59
round(n, 1) # 5.6
</code>```

But, in actuality, good old floating point weirdness creeps in and you get:

```<code>5.5999999999999996
</code>```

For the purposes of UI, I need to display 5.6. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.

Short of creating my own round library, is there any way around this?

答:
I would avoid relying on round() at all in this case. Consider

```<code>print(round(61.295, 2))
print(round(1.295, 2))
</code>```

will output

```<code>61.3
1.29
</code>```

which is not a desired output if you need solid rounding to the nearest integer. To bypass this behavior go with math.ceil() (or math.floor() if you want to round down):

```<code>from math import ceil
decimal_count = 2
print(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)
print(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)
</code>```

outputs

```<code>61.3
1.3
</code>```

Hope that helps.

OwnerDisplayName: swilliams

Body:
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:

n = 5.59
round(n, 1) # 5.6

But, in actuality, good old floating point weirdness creeps in and you get:

5.5999999999999996

For the purposes of UI, I need to display 5.6. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.

Short of creating my own round library, is there any way around this?

LastEditorDisplayName: swilliams

Body:
I would avoid relying on round() at all in this case. Consider

print(round(61.295, 2))
print(round(1.295, 2))

will output

61.3
1.29

which is not a desired output if you need solid rounding to the nearest integer. To bypass this behavior go with math.ceil() (or math.floor() if you want to round down):

from math import ceil
decimal_count = 2
print(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)
print(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)

outputs

61.3
1.3

Hope that helps.


问:
Add css style using Javascript when a select option is selected
Is there a way to append a style to an existing class using Javascript, based on which option you have selected in an html select option drop down?

For example, in the below table, I would like the appropriate number the become bold or highlighted when that number has been selected from the option box.

Thanks so much!

Finder

Show category:

<select type="search" class="select-table-filter" data-table="order-table" id="searchInput">
  <option value="">All</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<input type="search" class="light-table-filter" data-table="order-table" placeholder="Search ..." />

      Category
      Name
      Last Name
      Phone
      Email

      1
      Taylor
      Swift
      1234 5678
      taytay@gmail.com

      2, 3
      John
      Smith
      1234 5678
      johnnyboy@gmail.com

      3
      Jane
      Doh
      1234 5678
      dohnut@gmail.com

      3, 4
      Taylor
      Doh
      1234 5678
      td@gmail.com

```

答:
(function () {
    var previous;
    $("select[name=searchInput]").focus(function () {
        // Store the current value on focus, before it changes
        previous = this.value;
    }).change(function() {
      if(previous) {
      let element = $('#' + previous);
      element.removeClass("active");
      }

     let element = $('#' + this.value);
      element.addClass("active");

     previous = this.value;
    });
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active{
color: white;
background: black;
}</code>```

Finder

Show category:

<select type="search" name='searchInput' class="select-table-filter" data-table="order-table" id="searchInput">
  <option value="all">All</option>
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>
  <option value="four">4</option>

</select>
<input type="search" class="light-table-filter" data-table="order-table" placeholder="Search ..." />

      Category
      Name
      Last Name
      Phone
      Email

      1
      Taylor
      Swift
      1234 5678
      taytay@gmail.com

      2, 3
      John
      Smith
      1234 5678
      johnnyboy@gmail.com

      3
      Jane
      Doh
      1234 5678
      dohnut@gmail.com

      3, 4
      Taylor
      Doh
      1234 5678
      td@gmail.com

```

Body:
(function () {
    var previous;
    $("select[name=searchInput]").focus(function () {
        // Store the current value on focus, before it changes
        previous = this.value;
    }).change(function() {
      if(previous) {
      let element = $('#' + previous);
      element.removeClass("active");
      }

     let element = $('#' + this.value);
      element.addClass("active");

     previous = this.value;
    });
})();

.active{
color: white;
background: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Finder</h2>
<div class="step1">
  <p>Show category:</p>
</div>
<select type="search" name='searchInput' class="select-table-filter" data-table="order-table" id="searchInput">
  <option value="all">All</option>
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>
  <option value="four">4</option>

</select>
<input type="search" class="light-table-filter" data-table="order-table" placeholder="Search ..." />
<table class="order-table" id="myTable">
  <thead>
    <tr class="header">
      <th>Category</th>
      <th>Name</th>
      <th>Last Name</th>
      <th>Phone</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr id="one">
      <td>1</td>
      <td>Taylor</td>
      <td>Swift</td>
      <td>1234 5678</td>
      <td>taytay@gmail.com</td>
    </tr>
    <tr  id="two">
      <td>2, 3</td>
      <td>John</td>
      <td>Smith</td>
      <td>1234 5678</td>
      <td>johnnyboy@gmail.com</td>
    </tr>
    <tr id='three'>
      <td>3</td>
      <td>Jane</td>
      <td>Doh</td>
      <td>1234 5678</td>
      <td>dohnut@gmail.com</td>
    </tr>
    <tr  id='four'>
      <td>3, 4</td>
      <td>Taylor</td>
      <td>Doh</td>
      <td>1234 5678</td>
      <td>td@gmail.com</td>
    </tr>
  </tbody>
</table>


答:
There's no difference in the terms of what instance gets created, but there is a difference. In your first example, you can only access members defined by Product.

This is similar to the following.

```<code>object x1 = "hello";
string x2 = "hello";
</code>```

In both cases a string instance is created, but you can call .Length on x2, but not on x1.

Title: Why use different type and constructor when instantiating a class?

Body:
There's no difference in the terms of what instance gets created, but there is a difference. In your first example, you can only access members defined by Product.

This is similar to the following.

object x1 = "hello";
string x2 = "hello";

In both cases a string instance is created, but you can call .Length on x2, but not on x1.


问:
Postgres text search with GIN index and sorted DESC on other column
I'm currently working on a search feature that ends up hitting the db with a LIKE query. It used to be of the form
WHERE some_id = blah AND some_timestamp > blah AND (field1 LIKE '%some_text%' OR field2 LIKE '%some_text%' OR ...) ORDER BY some_timestamp DESC.
This hasn't scaled well now that the table is in the size of tens of millions of rows, especially when it is filtered on a very old timestamp.

After some research it looked like a trigram index might be more performant for the text searching.
So I added a trigram index on all of the text fields concatenated and got good results initially. After varying the new query though I found a regression. An old index (btree on some_id and some_timestamp DESC) was not being hit anymore.
So the new text searching helps with certain text queries that used to be very slow, and other text queries that used to be very fast (a few ms) due to the btree index are now super slow (see below).

Is there a way to get the best of both worlds? Fast trigram text searching and fast btree indexing for the queries that need it?

Notes:

Postgres 11.6

I tried a btree_gin index to index the timestamp column as well but got pretty much the same performance.

I slightly modified my query (concatenated whitespace) to bypass the trigram index and verified the slow queries return to the btree index and <10ms execution times.

I tried some query rearrangement to try to get both indexes hit to no avail.

Table:

```<code>table1
---------------------------------
some_id        | bigint
field1         | text
field2         | text
field3         | text
field4         | text
field5         | text
field6         | bigint
some_timestamp | timestamp without time zone
</code>```

Trigram Index:

```<code>CREATE INDEX CONCURRENTLY IF NOT EXISTS trgm_idx ON table1 USING gin ((COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) gin_trgm_ops);
</code>```

Query:

```<code>SELECT *
FROM table1 i
WHERE i.some_id = 1
    AND (COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) ILIKE '%some_text%'
    AND i.some_timestamp > '2015-01-00 00:00:00.0'
ORDER BY some_timestamp DESC limit 20;
</code>```

Explain:

```<code> Limit  (cost=1043.06..1043.11 rows=20 width=446) (actual time=37240.094..37240.099 rows=20 loops=1)
   ->  Sort  (cost=1043.06..1043.15 rows=39 width=446) (actual time=37240.092..37240.095 rows=20 loops=1)
         Sort Key: some_timestamp
         Sort Method: top-N heapsort  Memory: 36kB
         ->  Bitmap Heap Scan on table1 i  (cost=345.01..1042.03 rows=39 width=446) (actual time=1413.415..37202.331 rows=83066 loops=1)
               Recheck Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
               Rows Removed by Index Recheck: 23
               Filter: ((some_timestamp > '2015-01-00 00:00:00'::timestamp without time zone) AND (some_id = 1))
               Rows Removed by Filter: 5746666
               Heap Blocks: exact=395922
               ->  Bitmap Index Scan on trgm_idx  (cost=0.00..345.00 rows=667 width=0) (actual time=1325.867..1325.867 rows=5833670 loops=1)
                     Index Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
 Planning Time: 0.252 ms
 Execution Time: 37243.205 ms
(14 rows)
</code>```

答:
Create an additional index:

```<code>CREATE INDEX ON table1 (some_id, some_timestamp);
</code>```

Then you have a good chance of getting a bitmap or of a scan on both indexes, which should be much faster than having over 5 million rows removed by a filter.

Body:
I'm currently working on a search feature that ends up hitting the db with a LIKE query. It used to be of the form
WHERE some_id = blah AND some_timestamp > blah AND (field1 LIKE '%some_text%' OR field2 LIKE '%some_text%' OR ...) ORDER BY some_timestamp DESC.
This hasn't scaled well now that the table is in the size of tens of millions of rows, especially when it is filtered on a very old timestamp.

After some research it looked like a trigram index might be more performant for the text searching.
So I added a trigram index on all of the text fields concatenated and got good results initially. After varying the new query though I found a regression. An old index (btree on some_id and some_timestamp DESC) was not being hit anymore.
So the new text searching helps with certain text queries that used to be very slow, and other text queries that used to be very fast (a few ms) due to the btree index are now super slow (see below).

Is there a way to get the best of both worlds? Fast trigram text searching and fast btree indexing for the queries that need it?

Notes:

Postgres 11.6

I tried a btree_gin index to index the timestamp column as well but got pretty much the same performance.

I slightly modified my query (concatenated whitespace) to bypass the trigram index and verified the slow queries return to the btree index and <10ms execution times.

I tried some query rearrangement to try to get both indexes hit to no avail.

Table:

table1
---------------------------------
some_id        | bigint
field1         | text
field2         | text
field3         | text
field4         | text
field5         | text
field6         | bigint
some_timestamp | timestamp without time zone

Trigram Index:

CREATE INDEX CONCURRENTLY IF NOT EXISTS trgm_idx ON table1 USING gin ((COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) gin_trgm_ops);

Query:

SELECT *
FROM table1 i
WHERE i.some_id = 1
    AND (COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) ILIKE '%some_text%'
    AND i.some_timestamp > '2015-01-00 00:00:00.0'
ORDER BY some_timestamp DESC limit 20;

Explain:

 Limit  (cost=1043.06..1043.11 rows=20 width=446) (actual time=37240.094..37240.099 rows=20 loops=1)
   ->  Sort  (cost=1043.06..1043.15 rows=39 width=446) (actual time=37240.092..37240.095 rows=20 loops=1)
         Sort Key: some_timestamp
         Sort Method: top-N heapsort  Memory: 36kB
         ->  Bitmap Heap Scan on table1 i  (cost=345.01..1042.03 rows=39 width=446) (actual time=1413.415..37202.331 rows=83066 loops=1)
               Recheck Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
               Rows Removed by Index Recheck: 23
               Filter: ((some_timestamp > '2015-01-00 00:00:00'::timestamp without time zone) AND (some_id = 1))
               Rows Removed by Filter: 5746666
               Heap Blocks: exact=395922
               ->  Bitmap Index Scan on trgm_idx  (cost=0.00..345.00 rows=667 width=0) (actual time=1325.867..1325.867 rows=5833670 loops=1)
                     Index Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
 Planning Time: 0.252 ms
 Execution Time: 37243.205 ms
(14 rows)

Body:
Create an additional index:

CREATE INDEX ON table1 (some_id, some_timestamp);

Then you have a good chance of getting a bitmap or of a scan on both indexes, which should be much faster than having over 5 million rows removed by a filter.


问:
Can I change the appearance of an html image during hover without a second image?
Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>

答:
Here's some good information about image opacity and transparency with CSS.

So to make an image with opacity 50%, you'd do this:

```<code><img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" />
</code>```

The opacity: part is how Firefox does it, and it's a value between 0.0 and 1.0. filter: is how IE does it, and it's a value from 0 to 100.

OwnerDisplayName: Brent Nesbitt

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brent Nesbitt

Body:
Here's some good information about image opacity and transparency with CSS.

So to make an image with opacity 50%, you'd do this:

<img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" />

The opacity: part is how Firefox does it, and it's a value between 0.0 and 1.0. filter: is how IE does it, and it's a value from 0 to 100.

OwnerDisplayName: Jeremy Ruten

ContentLicense: CC BY-SA 3.0


问:
Scala equivalent for Java stream findFirst, filter, map
I have java code shown below, how to convert it to scala?</p>

```<code>feature.getFeatures()
            .stream()
            .filter(a -> a.getFeatureName().equals(feature))
            .findFirst()
            .map(f -> f.Accounts().contains(accountId))
            .orElse(true);
</code>```

答:
Whenever you see filter or find chained with map, think collect or collectFirst

So something like this should work:

```<code>feature.getFeatures()
  .collectFirst {
    case f if f.getFeatureName().equals(feature) =>
      f.Accounts().contains(accountId)
  }.getOrElse(true)
</code>```

Body:
I have java code shown below, how to convert it to scala?

feature.getFeatures()
            .stream()
            .filter(a -> a.getFeatureName().equals(feature))
            .findFirst()
            .map(f -> f.Accounts().contains(accountId))
            .orElse(true);

Body:
Whenever you see filter or find chained with map, think collect or collectFirst

So something like this should work:

feature.getFeatures()
  .collectFirst {
    case f if f.getFeatureName().equals(feature) =>
      f.Accounts().contains(accountId)
  }.getOrElse(true)


答:
In general, to access an object attribute by string, use getattr():

for name, value in collections.items():
    c = getattr(db, name)
    c.insert_one(value)
```

Title: replace literal value by variable in for loop

Body:
I have this code that works as expected. "db" is MongoClient object.

collections = {
    "cmrb": cmrb,
    "rbss": rbss,
    "ndrb": ndrb,
    "nder": nder,
    "rbph": rbph,
    "rb90": rb90,
    "rbphne": rbphne,
    "dirb": dirb,
}

c=db.cmrb
c.insert_one(collections['cmrb'])

But when I replace the collection name with variable i using for loop, all the entries gets added to collection "i" and not to "cmrb", "rbss" etc.

for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])

What is wrong with the code mentioned above? How do I replace the literal "i"?


问:
Touch event handling on Canvas in WeChat mini-program
I created a 3D simulation WeChat mini-game.
For some reason, I should re-implement it as a WeChat mini-program.
So I created a canvas on index.wxml.

<view class="container">
  <canvas type="webgl" id="myCanvas" style="height: 750rpx; width: 750rpx;"></canvas>
</view>
```

<p>I tried to capture the touch event on the canvas as I used to in HTML5.</p>

<pre class="lang-js prettyprint-override"><code>const app = getApp()

Page({
  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#myCanvas').node().exec((res) => {
      const canvas = res[0].node
      canvas.addEventListener("touchstart", function (e) {
        console.log(getTouchPos(canvas, e))
      }, false);
    })
  }
})
</code>```

But I got an error message and mini-program didn't run.

VM379:1 thirdScriptError
canvas.addEventListener is not a function;at SelectorQuery callback function
TypeError: canvas.addEventListener is not a function
```

On mini-game, it was done by wx.onTouchStart() or sth like that.

How can I get Touch events on canvas in WeChat mini-program?

答:
I changed some of my code so that I could listen to the touch event.

<view class="container">
  <canvas
    type="webgl"
    id="myCanvas"
    style="height: 750rpx; width: 750rpx;"
    bindtap="onTap"
    ></canvas>
</view>
```

<pre class="lang-js prettyprint-override"><code>// index.js
Page({
  onReady() {},
  onTap: (event) => {
    console.log(event)
  }
})
</code>```

Although I solved this issue, more answers and comments are welcomed. For example:

a detailed explanation about the difference between HTML5 canvas and WeChat mini-program canvas (not WeChat mini-game canvas

other straightforward or a more intuitive way for touch event handling

Body:
I created a 3D simulation WeChat mini-game.
For some reason, I should re-implement it as a WeChat mini-program.
So I created a canvas on index.wxml.

<view class="container">
  <canvas type="webgl" id="myCanvas" style="height: 750rpx; width: 750rpx;"></canvas>
</view>

I tried to capture the touch event on the canvas as I used to in HTML5.

const app = getApp()

Page({
  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#myCanvas').node().exec((res) => {
      const canvas = res[0].node
      canvas.addEventListener("touchstart", function (e) {
        console.log(getTouchPos(canvas, e))
      }, false);
    })
  }
})

But I got an error message and mini-program didn't run.

VM379:1 thirdScriptError
canvas.addEventListener is not a function;at SelectorQuery callback function
TypeError: canvas.addEventListener is not a function

On mini-game, it was done by wx.onTouchStart() or sth like that.

How can I get Touch events on canvas in WeChat mini-program?

Body:
I changed some of my code so that I could listen to the touch event.

<!--index.wxml-->
<view class="container">
  <canvas
    type="webgl"
    id="myCanvas"
    style="height: 750rpx; width: 750rpx;"
    bindtap="onTap"
    ></canvas>
</view>

// index.js
Page({
  onReady() {},
  onTap: (event) => {
    console.log(event)
  }
})

Although I solved this issue, more answers and comments are welcomed. For example:

a detailed explanation about the difference between HTML5 canvas and WeChat mini-program canvas (not WeChat mini-game canvas

other straightforward or a more intuitive way for touch event handling


问:
No prefetched files with preload-webpack-plugin
I have a question related to prefetching and preloading.

I have vue app and after build I receive double loaded files in my dist/index.html. You can see it below.

Moreover the "scripts" are not preloaded/prefetched. I do not know why. I have a plugin installed.

```<code><head>
<title></title>
<link href=/app.128b43f14088f83cb6c0.js rel=preload as=script>
<link href=/chunk-vendors.128b43f14088f83cb6c0.js rel=preload as=script>

<div id=app></div>
<script src=/chunk-vendors.128b43f14088f83cb6c0.js></script>
<script src=/app.128b43f14088f83cb6c0.js></script>
</code>```

vue.config.js

```<code>modules.export = {
    configureWebpack: () => {
        return {
            devtool: 'source-map',
            output: {
                filename: '[name].[hash].js',
                chunkFilename: '[name].[hash].js'
            },
            plugins: [
                new PreloadWebpackPlugin(),
                new CleanWebpackPlugin()
            ],
            resolve: {
                alias: {
                   styles: path.join(__dirname, 'src/assets')
                }
            }
        }
    }
}
</code>```

答:
I have vue app and after build I receive double loaded files in my dist/index.html.

Vue CLI already injects its own preload plugin, so your plugin is duplicating the preload/prefetch. Simply remove yours to resolve the duplication.

You should stick with the one already provided by Vue CLI, as it's modified to work with the Vue CLI toolchain. If you prefer to use your own for some reason, you could remove the built-in plugin with:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')
  }
}
```

Body:
I have a question related to prefetching and preloading.

I have vue app and after build I receive double loaded files in my dist/index.html. You can see it below.

Moreover the "scripts" are not preloaded/prefetched. I do not know why. I have a plugin installed.

<title></title>
<link href=/app.128b43f14088f83cb6c0.js rel=preload as=script>
<link href=/chunk-vendors.128b43f14088f83cb6c0.js rel=preload as=script>

vue.config.js

modules.export = {
    configureWebpack: () => {
        return {
            devtool: 'source-map',
            output: {
                filename: '[name].[hash].js',
                chunkFilename: '[name].[hash].js'
            },
            plugins: [
                new PreloadWebpackPlugin(),
                new CleanWebpackPlugin()
            ],
            resolve: {
                alias: {
                   styles: path.join(__dirname, 'src/assets')
                }
            }
        }
    }
}


问:
How to query a json string in Postgres
I want to get a specific string from a column. How can I get that.

Here is the json with column name json with table name my_table

I want to fetch "extensionAttribute.simSerial": "310240000029929".

```<code>{
  "name": "urn:imei:930000001801583",
  "type": "DEVICE",
  "sourceId": "P-n1000USCqT4",
  "consumers": "CDM",
  "crudStatus": {
    "status": "SUCCESS",
    "operation": "UPDATE"
  },
  "targetName": "urn:imei:930000001801583",
  "deviceTypeId": "dgs11b74714f7020ctoogu3zfugc6",
  "createdUserId": "a8aacc5d978d494eb54ae4243e714646",
  "onboardStatus": "DONE",
  "consrStatus": "",
  "deviceTypeName": "performance_device_type_2",
  "lwm2mPskSecret": "49443",
  "createdUserName": "manager",
  "bootstrapRequest": true,
  "lwm2mPskIdentity": "urn:imei:930000001801583",
  "boostrapPskSecret": "49443",
  "deviceTypeVersion": 1,
  "lastUpdatedUserId": "",
  "lwm2mSecurityMode": "psk",
  "consumersForUpdate": "",
  "bootstrapPskIdentity": "urn:imei:930000001801583",
  "pureCoapSecurityMode": "NONE",
  "bootstrapSecurityMode": "psk",
  "extensionAttribute.imsi": "310240000029929",
  "extensionAttribute.msisdn": "310240000029929",
  "extensionAttribute.simSerial": "310240000029929",
  "extensionAttribute.msisdnStatus": "active"
}
</code>```

答:
Solution

You can do it as follows:

```<code>select column_name->>'extensionAttribute.simSerial' as simSerial from my_table;
</code>```

where column_name is your column name in a table.

If you will have JSON with higher depth you can do something like:

```<code>column_name->'key_in_json'->'another_key_in_json'->>'last_key_in_json'
</code>```

Manual

JSON Functions and Operators

PostgreSQL JSON Tutorial

Title: How to query a json string in Postgres

Body:
I want to get a specific string from a column. How can I get that.

Here is the json with column name json with table name my_table

I want to fetch "extensionAttribute.simSerial": "310240000029929".

{
  "name": "urn:imei:930000001801583",
  "type": "DEVICE",
  "sourceId": "P-n1000USCqT4",
  "consumers": "CDM",
  "crudStatus": {
    "status": "SUCCESS",
    "operation": "UPDATE"
  },
  "targetName": "urn:imei:930000001801583",
  "deviceTypeId": "dgs11b74714f7020ctoogu3zfugc6",
  "createdUserId": "a8aacc5d978d494eb54ae4243e714646",
  "onboardStatus": "DONE",
  "consrStatus": "",
  "deviceTypeName": "performance_device_type_2",
  "lwm2mPskSecret": "49443",
  "createdUserName": "manager",
  "bootstrapRequest": true,
  "lwm2mPskIdentity": "urn:imei:930000001801583",
  "boostrapPskSecret": "49443",
  "deviceTypeVersion": 1,
  "lastUpdatedUserId": "",
  "lwm2mSecurityMode": "psk",
  "consumersForUpdate": "",
  "bootstrapPskIdentity": "urn:imei:930000001801583",
  "pureCoapSecurityMode": "NONE",
  "bootstrapSecurityMode": "psk",
  "extensionAttribute.imsi": "310240000029929",
  "extensionAttribute.msisdn": "310240000029929",
  "extensionAttribute.simSerial": "310240000029929",
  "extensionAttribute.msisdnStatus": "active"
}

Body:
Solution

You can do it as follows:

select column_name->>'extensionAttribute.simSerial' as simSerial from my_table;

where column_name is your column name in a table.

If you will have JSON with higher depth you can do something like:

column_name->'key_in_json'->'another_key_in_json'->>'last_key_in_json'

Manual

JSON Functions and Operators

PostgreSQL JSON Tutorial


问:
Performance Issue with Http2 vs Http1.1
I have upgraded to HTTP2 from http1.1 for a tomcat9 application. After this upgrade, I can see that the performance of the rest APIs is slow. I ran a load test for 1000 samples and as a result, HTTP1.1 has better throughput and average response time however I was expecting it to be for HTTP2.

is there any configuration that has to be done or am I missing something?

PS: The response Content-type is application/json type.

答:
You are comparing HTTP/1.1 without HTTPS with HTTP/2 with HTTPS. That’s not a true comparison of the protocols alone as HTTPS has significant overheads - particularly for just one connection.

Yes it’s true that HTTP/2 normally requires HTTPS as no browser supports HTTP/2 without HTTPS but then again browsers are increasingly warming against unsecured HTTP-only connections and limiting features like HTTP/2, Brotli, Service Workers, Geo... etc. to HTTPS anyway.

HTTP/2 over HTTPS can beat HTTP/1.1 over HTTP in certain circumstances but in general that’s a heck of a back foot to start on.

Additionally when making only one request per connection (like you are in jMeter using threads) the expense of HTTPS will be a large percentage of the connection due to the HTTPS handshake that needs to happen to set up the connection. Future requests on the same connection won’t have the same expense as in general the encryption/decryption part is relatively fast on modern hardware and so doesn’t create a noticeable delay - but the initial setup part definitely does.

Finally HTTP/2 is generally faster than HTTP/1.1 over slower, high latency connections due in large part to multiplexing. If testing over the same network, as I suspect you might be doing, where there are basically no network delays, then the benefit of HTTP/2 over HTTP/1.1 may not be apparent.

Title: Performance Issue with Http2 vs Http1.1


问:
Xcode 4 shows no files after loading project
I've loaded a project in Xcode 4 after not looking at it for a while.  Xcode shows its progress bar and indicates in text that the project is loading, and it appears to finish, but then there are no files shown in the hierarchy or flat views.  There is nothing showing in any view (except for one breakpoint in the breakpoints view).

Any ideas?  Xcode gives me zero indication that anything is wrong, it shows me nothing.

答:
I had a similar issue. After archiving a project the files would disappear from the project navigator.

It turned out that somehow XCode had added the word "main" to the searchbar below the project navigator so that almost all files where invisible. Quite frustrating.

It might be the same case for you..


问:
ObervableObject being init multiple time, and not refreshing my view
I have a structure like this:

contentView {
    navigationView {
        foreach {
            NavigationLink(ViewA(id: id))
        }
    }
}
```
<pre class="lang-swift prettyprint-override"><code>/// where ViewA contains an request trigger when it appears
struct ViewA: View {

    @State var filterString: String = ""

    var id: String!
    @ObservedObject var model: ListObj = ListObj()

    init(id: String) {
        self.id = id
    }

    var body: some View {
        VStack {
            SearchBarView(searchText: $filterString)
            List {
                ForEach(model.items.filter({ filterString.isEmpty || $0.id.contains(filterString) || $0.name.contains(filterString)  }), id: \.id) { item in
                    NavigationLink(destination: ViewB(id: item.id)) {
                        VStack {
                            Text("\(item.name) ")
                        }
                    }
                }
            }

        }
        .onAppear {
            self.model.getListObj(id: self.id) //api request, fill data and call objectWillChange.send()
        }
    }
}
</code>```

ViewB has the same code as ViewA: It receives an id, stores and requests an API to collect data.

But the viewB list is not being refreshed.

I also noticed that viewB's model property

@ObservedObject var model: model = model()
```

was instantiated multiple times.

Debugging, I found that every navigationLink instantiates its destination even before it is triggered. That's not a problem usually, but in my case i feel like the ViewB model is being instantiated 2 times, and my onAppear call the wrong one, reason why self.objectWillChange.send() not refreshing my view.

答:
There are two issues here:

SwiftUI uses value types that that get initialized over and over again each pass through body.

Related to #1, NavigationLink is not lazy.

#1

A new ListObj gets instantiated every time you call ViewA.init(...).  ObservedObject does not work the same as @State where SwiftUI keeps careful track of it for you throughout the onscreen lifecycle.  SwiftUI assumes that ultimate ownership of an @ObservedObject exists at some level above the View it's used in.

In other words, you should almost always avoid things like @ObservedObject var myObject = MyObservableObject().

(Note, even if you did @State var model = ListObj() it would be instantiated every time.  But because it's @State SwiftUI will replace the new instance with the original before body gets called.)

#2

In addition to this, NavigationLink is not lazy.  Each time you instantiate that NavigationLink you pass a newly instantiated ViewA, which instantiates your ListObj.

So for starters, one thing you can do is make a LazyView to delay instantiation until NavigationLink.destination.body actually gets called:

// Use this to delay instantiation when using `NavigationLink`, etc...
struct LazyView<Content: View>: View {
    var content: () -> Content
    var body: some View {
        self.content()
    }
}
```

Now you can do NavigationLink(destination: LazyView { ViewA() }) and instantiation of ViewA will be deferred until the destination is actually shown.

Simply using LazyView will fix your current problem as long as it's the top view in the hierarchy, like it is when you push it in a NavigationView or if you present it.

However, this is where @user3441734's comment comes in.  What you really need to do is keep ownership of model somewhere outside of your View because of what was explained in #1.

Body:
I have a structure like this:

contentView {
    navigationView {
        foreach {
            NavigationLink(ViewA(id: id))
        }
    }
}

/// where ViewA contains an request trigger when it appears
struct ViewA: View {

    @State var filterString: String = ""

    var id: String!
    @ObservedObject var model: ListObj = ListObj()

    init(id: String) {
        self.id = id
    }

    var body: some View {
        VStack {
            SearchBarView(searchText: $filterString)
            List {
                ForEach(model.items.filter({ filterString.isEmpty || $0.id.contains(filterString) || $0.name.contains(filterString)  }), id: \.id) { item in
                    NavigationLink(destination: ViewB(id: item.id)) {
                        VStack {
                            Text("\(item.name) ")
                        }
                    }
                }
            }

        }
        .onAppear {
            self.model.getListObj(id: self.id) //api request, fill data and call objectWillChange.send()
        }
    }
}

ViewB has the same code as ViewA: It receives an id, stores and requests an API to collect data.

But the viewB list is not being refreshed.

I also noticed that viewB's model property

@ObservedObject var model: model = model()

was instantiated multiple times.

Debugging, I found that every navigationLink instantiates its destination even before it is triggered. That's not a problem usually, but in my case i feel like the ViewB model is being instantiated 2 times, and my onAppear call the wrong one, reason why self.objectWillChange.send() not refreshing my view.

Body:
There are two issues here:

SwiftUI uses value types that that get initialized over and over again each pass through body.

Related to #1, NavigationLink is not lazy.

#1

A new ListObj gets instantiated every time you call ViewA.init(...).  ObservedObject does not work the same as @State where SwiftUI keeps careful track of it for you throughout the onscreen lifecycle.  SwiftUI assumes that ultimate ownership of an @ObservedObject exists at some level above the View it's used in.

In other words, you should almost always avoid things like @ObservedObject var myObject = MyObservableObject().

(Note, even if you did @State var model = ListObj() it would be instantiated every time.  But because it's @State SwiftUI will replace the new instance with the original before body gets called.)

#2

In addition to this, NavigationLink is not lazy.  Each time you instantiate that NavigationLink you pass a newly instantiated ViewA, which instantiates your ListObj.

So for starters, one thing you can do is make a LazyView to delay instantiation until NavigationLink.destination.body actually gets called:

// Use this to delay instantiation when using `NavigationLink`, etc...
struct LazyView<Content: View>: View {
    var content: () -> Content
    var body: some View {
        self.content()
    }
}

Now you can do NavigationLink(destination: LazyView { ViewA() }) and instantiation of ViewA will be deferred until the destination is actually shown.

Simply using LazyView will fix your current problem as long as it's the top view in the hierarchy, like it is when you push it in a NavigationView or if you present it.

However, this is where @user3441734's comment comes in.  What you really need to do is keep ownership of model somewhere outside of your View because of what was explained in #1.


问:
Adding C library to c++11 distutils project
I have a c++11 project that I want to export as a package for use by python scripts. My code uses lzfse C files I download and add to my project.
This project need to compile on both MacOS and Linux.
I created the following setup.py file:

```<code>from distutils.core import setup, Extension

module1 = Extension('car_mechanic',
                    extra_compile_args=["-std=c++11"],
                    sources=['car_mechanic_py.cpp', 'png_parse.cpp', 'car_parse.cpp', 'lodepng.cpp', 'logger.cpp'
                             , 'lzfse/src/lzfse_fse_py.c', 'lzfse/src/lzfse_decode_py.c', 'lzfse/src/lzfse_encode_py.c'
                            , 'lzfse/src/lzfse_decode_base_py.c', 'lzfse/src/lzfse_encode_base_py.c'
                            , 'lzfse/src/lzvn_decode_base_py.c', 'lzfse/src/lzvn_encode_base_py.c'])

setup(name='car_mechanic',
       version='1.0',
       description='This package parses and changes the Asset.car ios apps use',
       ext_modules=[module1])
</code>```

Then used python setup.py build

There are 2 issues with this solution:

-std=c++11 flag doesn't work for .c files under MacOS as it runs clang which doesn't support it. It also issues a warning on Linux

For each .c file from the lzfse library, I needed to add an #include <python2.7/Python.h>. Since I didn't want to change the original files, I created a lzfse_XXX_py.c file for every lsfse_XXX.c, which does only:

#include <python2.7/Python.h>
 #include "lzfse_XXX.c"

any better way to turn lzfse into a library used by my python package? Will Setuptools solve my problems?

答:
using @phd's answer:

```<code>git clone --recursive https://github.com/dimkr/pylzfse
cd pylzfse
python setup.py build
</code>```

removed all lzfse files from my module, then copied to lzfse.so and imported before importing my module

Body:
I have a c++11 project that I want to export as a package for use by python scripts. My code uses lzfse C files I download and add to my project.
This project need to compile on both MacOS and Linux.
I created the following setup.py file:

from distutils.core import setup, Extension

module1 = Extension('car_mechanic',
                    extra_compile_args=["-std=c++11"],
                    sources=['car_mechanic_py.cpp', 'png_parse.cpp', 'car_parse.cpp', 'lodepng.cpp', 'logger.cpp'
                             , 'lzfse/src/lzfse_fse_py.c', 'lzfse/src/lzfse_decode_py.c', 'lzfse/src/lzfse_encode_py.c'
                            , 'lzfse/src/lzfse_decode_base_py.c', 'lzfse/src/lzfse_encode_base_py.c'
                            , 'lzfse/src/lzvn_decode_base_py.c', 'lzfse/src/lzvn_encode_base_py.c'])

setup(name='car_mechanic',
       version='1.0',
       description='This package parses and changes the Asset.car ios apps use',
       ext_modules=[module1])

Then used python setup.py build

There are 2 issues with this solution:

-std=c++11 flag doesn't work for .c files under MacOS as it runs clang which doesn't support it. It also issues a warning on Linux

For each .c file from the lzfse library, I needed to add an #include <python2.7/Python.h>. Since I didn't want to change the original files, I created a lzfse_XXX_py.c file for every lsfse_XXX.c, which does only:

#include <python2.7/Python.h>
 #include "lzfse_XXX.c"

any better way to turn lzfse into a library used by my python package? Will Setuptools solve my problems?

Body:
using @phd's answer:

git clone --recursive https://github.com/dimkr/pylzfse
cd pylzfse
python setup.py build

removed all lzfse files from my module, then copied to lzfse.so and imported before importing my module


问:
Recreating kubelet sandbox false when reboot cluster server using kubeadm
When I reboot the master and work node, the pod of coredns show the below error message seem that it can not recreate kubelet after server restart.</p>

```<code>  Normal   SandboxChanged          12s                   kubelet, izbp1dyjigsfwmw0dtl85gz  Pod sandbox changed, it will be killed and re-created.
  Warning  FailedCreatePodSandBox  11s                   kubelet, izbp1dyjigsfwmw0dtl85gz  Failed to create pod sandbox: rpc error: code = Unknown desc = failed to set up sandbox container "5e850ee3e8bf86688fec2badd9b0272127a0d775620a5783e7c30b4e0d412b01" network for pod "coredns-6955765f44-4xnhj": networkPlugin cni failed to set up pod "coredns-6955765f44-4xnhj_kube-system" network: open /run/flannel/subnet.env: no such file or directory
</code>```

答:
You can try cleaning up flannel and reinstalling it.

```<code>kubectl delete -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml

rm -rf /var/lib/cni/
rm -rf /run/flannel
rm -rf /etc/cni/
</code>```

Remove interfaces related to and flannel:

```<code>ip link
</code>```

For each interface flannel, do the following

```<code>ifconfig <name of interface from ip link> down
ip link delete <name of interface from ip link>
</code>```

After this install flannel

```<code>kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml
</code>```

For flannel to work correctly, you must pass --pod-network-cidr=10.244.0.0/16 to kubeadm init

Body:
When I reboot the master and work node, the pod of coredns show the below error message seem that it can not recreate kubelet after server restart.

  Normal   SandboxChanged          12s                   kubelet, izbp1dyjigsfwmw0dtl85gz  Pod sandbox changed, it will be killed and re-created.
  Warning  FailedCreatePodSandBox  11s                   kubelet, izbp1dyjigsfwmw0dtl85gz  Failed to create pod sandbox: rpc error: code = Unknown desc = failed to set up sandbox container "5e850ee3e8bf86688fec2badd9b0272127a0d775620a5783e7c30b4e0d412b01" network for pod "coredns-6955765f44-4xnhj": networkPlugin cni failed to set up pod "coredns-6955765f44-4xnhj_kube-system" network: open /run/flannel/subnet.env: no such file or directory

Body:
You can try cleaning up flannel and reinstalling it.

kubectl delete -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml

rm -rf /var/lib/cni/
rm -rf /run/flannel
rm -rf /etc/cni/

Remove interfaces related to and flannel:

ip link

For each interface flannel, do the following

ifconfig <name of interface from ip link> down
ip link delete <name of interface from ip link>

After this install flannel

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml

For flannel to work correctly, you must pass --pod-network-cidr=10.244.0.0/16 to kubeadm init