问:
User uploading 2nd image before deleting 1st image
Background :

User click on Mask & upload their own image on the mask.

Once image uploaded, Remove Text is displaying on the image.

Once user click on Remove Text, we are deleting the uploaded image.

Also User can drag uploaded image....

Issue :

User can able to upload another [2nd] image before click on "Remove" button.

Requirement :

User should be able to upload another image only after click on "Remove" button....

My work to get the solution :

I added below 3 lines of code , after that i got solution in Codepen1 , but now i can't able to drag the uploaded image....

```<code>$("#"+String(target)).css("pointer-events", "none");
$('.container').css('pointer-events','');
$(canvasId).css("pointer-events","");
</code>```

Code Snippet :

 var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 612,
        "layers": [{
            "x": 160,
            "src": "ax0HVTs.png",
            "y": 291,
            "height": 296,
            "width": 429,
            "name": "mask_1"
        }, {
            "x": 25,
            "src": "hEM2kEP.png",
            "height": 324,
            "width": 471,
            "y": 22,
            "name": "mask_2"
        }],
        "y": 0,
        "width": 612
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {

    // Upload image onclick mask image

    containerElement.click(function(e) {
        var res = e.target;
        target = res.id;
        if (e.target.getContext) {
            // click only inside Non Transparent part
            var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
            if (pixel[3] === 255) {
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        }
    });

    // Fetch mask images from json file - IGNORE this code

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            height,
                            width,
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data) {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);
        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            } of arr) {

            //Get Height and width of mask image [ edit button ]
            var ImagePosition = arr;
            //code end

            var mask = $(".container").mask({
                imageUrl: imageUrl,

                // Fetch Mask images
                maskImageUrl: 'http://i.imgur.com/' + src,
                // end

                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            // here
            table.push(mask);
            fileup.onchange = function() {
   // my work
          //  $("#"+String(target)).css("pointer-events", "none");
   // end
                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";

                //  Remove image

                $("
Remove").insertAfter(".masked-img" + newImageLoadedId).css({
                    "left": ImagePosition[newImageLoadedId].x + (ImagePosition[newImageLoadedId].width / 2) + "px",
                    "top": ImagePosition[newImageLoadedId].y + (ImagePosition[newImageLoadedId].height / 2 + 25) + "px"
                });

                $(".remove").click(function(event) {
    // my work
   // $('.container').css('pointer-events','');
    // end
                    const canvasId = "canvas#" + event.currentTarget.id;
                    // Delete the uploaded image & icon
                    const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
                    ctx.fillStyle = "white"
                    ctx.fillRect(0, 0, 500, 500)

                    // Delete the Remove button
                    $(this).remove();
     // my work
    // $(canvasId).css("pointer-events","");
     //end

                });

                // Remove image code end here....
            };
            counter++;
        }
        return mask;
    }
    mask = json(jsonData);
}); // end of function

// Image code

(function($) {
    window.JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
            rotate: 0,
        }, options);

        // Create the image properties
        settings.maskImage = new Image
        settings.image = new Image

        // set the cross-origin attributes
        settings.maskImage.setAttribute('crossOrigin', 'anonymous');
        settings.image.setAttribute('crossOrigin', 'anonymous');

        settings.maskImage.onload = function() {
            // once the mask is loaded, load the image
            container.loadImage(settings.imageUrl)
        }

        settings.image.onload = function() {
            // once the image is loaded, render to canvas
            container.drawMask()
            container.drawImage()
        }

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            scale = settings.scale,
            div;

        container.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }

        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };

        container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }

        container.drawMask = function() {
            canvas.width = settings.maskImage.width;
            canvas.height = settings.maskImage.height;
            context.save();
            context.beginPath();
            context.globalCompositeOperation = "source-over";
            // draw the masked image after scaling
            context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage
                .height);
            context.restore()
        };

        container.drawImage = function() {
            const img = settings.image

            settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
            settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;

            context.globalCompositeOperation = 'source-atop';
            context.save();
            context.translate(settings.x + img.width / 2, settings.y + img.height / 2);
            context.rotate(settings.rotate);
            context.scale(settings.scale, settings.scale);
            context.translate(-(settings.x + img.width / 2), -(settings.y + img.height / 2));
            let width = img.width,
                height = img.height;
            context.drawImage(img, settings.x, settings.y, width, height);
            context.restore();
            initImage = false;
        }

        container.onDragStart = function(evt) {
           // console.log('Draw started');
            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;

                $(canvas).attr("active", "true");
                container.selected(evt);
                prevX = evt.clientX;
                prevY = evt.clientY;
                var img = new Image();
                evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
                evt.originalEvent.dataTransfer.setData('text/plain', 'anything');

            }
        };

        container.onDragOver = function(evt) {
           // console.log('Drag over');

            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
                if (pixel[3] === 255) {
                    if (draggable && $(canvas).attr("active") === "true") {
                        var x = settings.x + evt.clientX - prevX;
                        var y = settings.y + evt.clientY - prevY;
                        if (x == settings.x && y == settings.y)
                            return; // position has not changed
                        settings.x += evt.clientX - prevX;
                        settings.y += evt.clientY - prevY;
                        prevX = evt.clientX;
                        prevY = evt.clientY;

                        clearTimeout(timeout);
                        timeout = setTimeout(function() {
                            container.drawMask();
                            container.drawImage();
                        }, 1);
                    }
                } else {
                    evt.stopPropagation();
                    return false;
                }
            }
        };

        container.loadImage = function(imageUrl) {
            settings.y = startY;
            settings.x = startX;
            settings.scale = 1;
            settings.rotate = 0;
            prevX = prevY = 0;
            initImage = true;
            settings.image.src = imageUrl; // CHANGED
            // sirpepole Add this
            return settings.id;
        };

        container.loadMaskImage = function(imageUrl, from) {
            console.log('loading mask image from', imageUrl, from)
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImage.src = imageUrl // CHANGED

            div = $("
", {
                "class": "masked-img"
            }).append(canvas);

            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);

            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        // Edit image
        div.addClass('masked-img' + settings.id);
        div.attr('data-id', settings.id);
        // ends
        return container;
    };
}(jQuery));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
 background: silver;
 position: relative;
}

.container img {
 position: absolute;
 top: 0;
 bottom: 250px;
 left: 0;
 right: 0;
 margin: auto;
 z-index: 999;
}

.masked-img {
 overflow: hidden;
 position: relative;
}

.pip {
 display: inline-block;
 margin: 0;
 position: absolute;
}

.remove {
 background: #444;
 border: 1px solid black;
 color: white;
 text-align: center;
 cursor: pointer;
 position: absolute;
 z-index: 3;
}

.remove:hover {
 background: white;
 color: black;
}</code>```

    <input id="fileup" name="fileup" type="file" style="display:none">

 ```

Here is Codepen2 ,  Jsfiddle , Pastebin

答:
Adding a jQuery data object can help determine if an image has been set for a canvas or not.

I have added image_set${id} value and set it to true when a User uploads an image and set it to false after it has been removed.

Hope this helps :)

Check code below:

 var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 612,
        "layers": [{
            "x": 160,
            "src": "ax0HVTs.png",
            "y": 291,
            "height": 296,
            "width": 429,
            "name": "mask_1"
        }, {
            "x": 25,
            "src": "hEM2kEP.png",
            "height": 324,
            "width": 471,
            "y": 22,
            "name": "mask_2"
        }],
        "y": 0,
        "width": 612
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {

    // Upload image onclick mask image

    containerElement.click(function(e) {
        var res = e.target;
        target = res.id;
        if (e.target.getContext) {
            // click only inside Non Transparent part
            var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
            if (pixel[3] === 255) {
              if(!$(e.currentTarget).data('image_set'+target))
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        }
    });

    // Fetch mask images from json file - IGNORE this code

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            height,
                            width,
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data) {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);
        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            } of arr) {

            //Get Height and width of mask image [ edit button ]
            var ImagePosition = arr;
            //code end

            var mask = $(".container").mask({
                imageUrl: imageUrl,

                // Fetch Mask images
                maskImageUrl: 'http://i.imgur.com/' + src,
                // end

                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            // here
            table.push(mask);
            fileup.onchange = function() {
   // my work
          //  $("#"+String(target)).css("pointer-events", "none");
   // end
                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";

                //  Remove image

                $("
Remove").insertAfter(".masked-img" + newImageLoadedId).css({
                    "left": ImagePosition[newImageLoadedId].x + (ImagePosition[newImageLoadedId].width / 2) + "px",
                    "top": ImagePosition[newImageLoadedId].y + (ImagePosition[newImageLoadedId].height / 2 + 25) + "px"
                });

                $(".remove").click(function(event) {
    // my work
   // $('.container').css('pointer-events','');
    // end
                    const canvasId = "canvas#" + event.currentTarget.id;
                    // Delete the uploaded image & icon
                    const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
                    ctx.fillStyle = "white"
                    ctx.fillRect(0, 0, 500, 500)
                    $('#container').data('image_set'+event.currentTarget.id, false)
                    // Delete the Remove button
                    $(this).remove();
     // my work
    // $(canvasId).css("pointer-events","");
     //end

                });

                // Remove image code end here....
            };
            counter++;
        }
        return mask;
    }
    mask = json(jsonData);
}); // end of function

// Image code

(function($) {
    window.JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
            rotate: 0,
        }, options);

        // Create the image properties
        settings.maskImage = new Image
        settings.image = new Image

        // set the cross-origin attributes
        settings.maskImage.setAttribute('crossOrigin', 'anonymous');
        settings.image.setAttribute('crossOrigin', 'anonymous');

        settings.maskImage.onload = function() {
            // once the mask is loaded, load the image
            container.loadImage(settings.imageUrl, true)
        }

        settings.image.onload = function() {
            // once the image is loaded, render to canvas
            container.drawMask()
            container.drawImage()
        }

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            scale = settings.scale,
            div;

        container.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }

        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };

        container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }

        container.drawMask = function() {
            canvas.width = settings.maskImage.width;
            canvas.height = settings.maskImage.height;
            context.save();
            context.beginPath();
            context.globalCompositeOperation = "source-over";
            // draw the masked image after scaling
            context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage
                .height);
            context.restore()
        };

        container.drawImage = function() {
            const img = settings.image

            settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
            settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;

            context.globalCompositeOperation = 'source-atop';
            context.save();
            context.translate(settings.x + img.width / 2, settings.y + img.height / 2);
            context.rotate(settings.rotate);
            context.scale(settings.scale, settings.scale);
            context.translate(-(settings.x + img.width / 2), -(settings.y + img.height / 2));
            let width = img.width,
                height = img.height;
            context.drawImage(img, settings.x, settings.y, width, height);
            context.restore();
            initImage = false;
        }

        container.onDragStart = function(evt) {
           // console.log('Draw started');
            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;

                $(canvas).attr("active", "true");
                container.selected(evt);
                prevX = evt.clientX;
                prevY = evt.clientY;
                var img = new Image();
                evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
                evt.originalEvent.dataTransfer.setData('text/plain', 'anything');

            }
        };

        container.onDragOver = function(evt) {
           // console.log('Drag over');

            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
                if (pixel[3] === 255) {
                    if (draggable && $(canvas).attr("active") === "true") {
                        var x = settings.x + evt.clientX - prevX;
                        var y = settings.y + evt.clientY - prevY;
                        if (x == settings.x && y == settings.y)
                            return; // position has not changed
                        settings.x += evt.clientX - prevX;
                        settings.y += evt.clientY - prevY;
                        prevX = evt.clientX;
                        prevY = evt.clientY;

                        clearTimeout(timeout);
                        timeout = setTimeout(function() {
                            container.drawMask();
                            container.drawImage();
                        }, 1);
                    }
                } else {
                    evt.stopPropagation();
                    return false;
                }
            }
        };

        container.loadImage = function(imageUrl, isMask) {
            settings.y = startY;
            settings.x = startX;
            settings.scale = 1;
            settings.rotate = 0;
            prevX = prevY = 0;
            initImage = true;
            settings.image.src = imageUrl; // CHANGED
            if(!isMask)
               container.data('image_set'+settings.id, true)
            // sirpepole Add this
            return settings.id;
        };

        container.loadMaskImage = function(imageUrl, from) {
            console.log('loading mask image from', imageUrl, from)
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImage.src = imageUrl // CHANGED

            div = $("
", {
                "class": "masked-img"
            }).append(canvas);

            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);

            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        // Edit image
        div.addClass('masked-img' + settings.id);
        div.attr('data-id', settings.id);
        // ends
        return container;
    };
}(jQuery));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
 background: silver;
 position: relative;
}

.container img {
 position: absolute;
 top: 0;
 bottom: 250px;
 left: 0;
 right: 0;
 margin: auto;
 z-index: 999;
}

.masked-img {
 overflow: hidden;
 position: relative;
}

.pip {
 display: inline-block;
 margin: 0;
 position: absolute;
}

.remove {
 background: #444;
 border: 1px solid black;
 color: white;
 text-align: center;
 cursor: pointer;
 position: absolute;
 z-index: 3;
}

.remove:hover {
 background: white;
 color: black;
}</code>```

    <input id="fileup" name="fileup" type="file" style="display:none">

 ```

PS: I would suggest using a framework given the complexity of your code even though the above code changes would help you.

Body:
Background :

User click on Mask & upload their own image on the mask.

Once image uploaded, Remove Text is displaying on the image.

Once user click on Remove Text, we are deleting the uploaded image.

Also User can drag uploaded image....

Issue :

User can able to upload another [2nd] image before click on "Remove" button.

Requirement :

User should be able to upload another image only after click on "Remove" button....

My work to get the solution :

I added below 3 lines of code , after that i got solution in Codepen1 , but now i can't able to drag the uploaded image....

$("#"+String(target)).css("pointer-events", "none");
$('.container').css('pointer-events','');
$(canvasId).css("pointer-events","");

Code Snippet :

 var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 612,
        "layers": [{
            "x": 160,
            "src": "ax0HVTs.png",
            "y": 291,
            "height": 296,
            "width": 429,
            "name": "mask_1"
        }, {
            "x": 25,
            "src": "hEM2kEP.png",
            "height": 324,
            "width": 471,
            "y": 22,
            "name": "mask_2"
        }],
        "y": 0,
        "width": 612
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {

    // Upload image onclick mask image

    containerElement.click(function(e) {
        var res = e.target;
        target = res.id;
        if (e.target.getContext) {
            // click only inside Non Transparent part
            var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
            if (pixel[3] === 255) {
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        }
    });

    // Fetch mask images from json file - IGNORE this code

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            height,
                            width,
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data) {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);
        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            } of arr) {

            //Get Height and width of mask image [ edit button ]
            var ImagePosition = arr;
            //code end

            var mask = $(".container").mask({
                imageUrl: imageUrl,

                // Fetch Mask images
                maskImageUrl: 'http://i.imgur.com/' + src,
                // end

                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            // here
            table.push(mask);
            fileup.onchange = function() {
   // my work
          //  $("#"+String(target)).css("pointer-events", "none");
   // end
                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";

                //  Remove image

                $("
Remove").insertAfter(".masked-img" + newImageLoadedId).css({
                    "left": ImagePosition[newImageLoadedId].x + (ImagePosition[newImageLoadedId].width / 2) + "px",
                    "top": ImagePosition[newImageLoadedId].y + (ImagePosition[newImageLoadedId].height / 2 + 25) + "px"
                });

                $(".remove").click(function(event) {
    // my work
   // $('.container').css('pointer-events','');
    // end
                    const canvasId = "canvas#" + event.currentTarget.id;
                    // Delete the uploaded image & icon
                    const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
                    ctx.fillStyle = "white"
                    ctx.fillRect(0, 0, 500, 500)

                    // Delete the Remove button
                    $(this).remove();
     // my work
    // $(canvasId).css("pointer-events","");
     //end

                });

                // Remove image code end here....
            };
            counter++;
        }
        return mask;
    }
    mask = json(jsonData);
}); // end of function

// Image code

(function($) {
    window.JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
            rotate: 0,
        }, options);

        // Create the image properties
        settings.maskImage = new Image
        settings.image = new Image

        // set the cross-origin attributes
        settings.maskImage.setAttribute('crossOrigin', 'anonymous');
        settings.image.setAttribute('crossOrigin', 'anonymous');

        settings.maskImage.onload = function() {
            // once the mask is loaded, load the image
            container.loadImage(settings.imageUrl)
        }

        settings.image.onload = function() {
            // once the image is loaded, render to canvas
            container.drawMask()
            container.drawImage()
        }

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            scale = settings.scale,
            div;

        container.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }

        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };

        container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }

        container.drawMask = function() {
            canvas.width = settings.maskImage.width;
            canvas.height = settings.maskImage.height;
            context.save();
            context.beginPath();
            context.globalCompositeOperation = "source-over";
            // draw the masked image after scaling
            context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage
                .height);
            context.restore()
        };

        container.drawImage = function() {
            const img = settings.image

            settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
            settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;

            context.globalCompositeOperation = 'source-atop';
            context.save();
            context.translate(settings.x + img.width / 2, settings.y + img.height / 2);
            context.rotate(settings.rotate);
            context.scale(settings.scale, settings.scale);
            context.translate(-(settings.x + img.width / 2), -(settings.y + img.height / 2));
            let width = img.width,
                height = img.height;
            context.drawImage(img, settings.x, settings.y, width, height);
            context.restore();
            initImage = false;
        }

        container.onDragStart = function(evt) {
           // console.log('Draw started');
            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;

                $(canvas).attr("active", "true");
                container.selected(evt);
                prevX = evt.clientX;
                prevY = evt.clientY;
                var img = new Image();
                evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
                evt.originalEvent.dataTransfer.setData('text/plain', 'anything');

            }
        };

        container.onDragOver = function(evt) {
           // console.log('Drag over');

            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
                if (pixel[3] === 255) {
                    if (draggable && $(canvas).attr("active") === "true") {
                        var x = settings.x + evt.clientX - prevX;
                        var y = settings.y + evt.clientY - prevY;
                        if (x == settings.x && y == settings.y)
                            return; // position has not changed
                        settings.x += evt.clientX - prevX;
                        settings.y += evt.clientY - prevY;
                        prevX = evt.clientX;
                        prevY = evt.clientY;

                        clearTimeout(timeout);
                        timeout = setTimeout(function() {
                            container.drawMask();
                            container.drawImage();
                        }, 1);
                    }
                } else {
                    evt.stopPropagation();
                    return false;
                }
            }
        };

        container.loadImage = function(imageUrl) {
            settings.y = startY;
            settings.x = startX;
            settings.scale = 1;
            settings.rotate = 0;
            prevX = prevY = 0;
            initImage = true;
            settings.image.src = imageUrl; // CHANGED
            // sirpepole Add this
            return settings.id;
        };

        container.loadMaskImage = function(imageUrl, from) {
            console.log('loading mask image from', imageUrl, from)
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImage.src = imageUrl // CHANGED

            div = $("
", {
                "class": "masked-img"
            }).append(canvas);

            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);

            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        // Edit image
        div.addClass('masked-img' + settings.id);
        div.attr('data-id', settings.id);
        // ends
        return container;
    };
}(jQuery));

.container {
 background: silver;
 position: relative;
}

.container img {
 position: absolute;
 top: 0;
 bottom: 250px;
 left: 0;
 right: 0;
 margin: auto;
 z-index: 999;
}

.masked-img {
 overflow: hidden;
 position: relative;
}

.pip {
 display: inline-block;
 margin: 0;
 position: absolute;
}

.remove {
 background: #444;
 border: 1px solid black;
 color: white;
 text-align: center;
 cursor: pointer;
 position: absolute;
 z-index: 3;
}

.remove:hover {
 background: white;
 color: black;
}

    <input id="fileup" name="fileup" type="file" style="display:none">

Here is Codepen2 ,  Jsfiddle , Pastebin

Body:
Adding a jQuery data object can help determine if an image has been set for a canvas or not.

I have added image_set${id} value and set it to true when a User uploads an image and set it to false after it has been removed.

Hope this helps :)

Check code below:

 var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 612,
        "layers": [{
            "x": 160,
            "src": "ax0HVTs.png",
            "y": 291,
            "height": 296,
            "width": 429,
            "name": "mask_1"
        }, {
            "x": 25,
            "src": "hEM2kEP.png",
            "height": 324,
            "width": 471,
            "y": 22,
            "name": "mask_2"
        }],
        "y": 0,
        "width": 612
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {

    // Upload image onclick mask image

    containerElement.click(function(e) {
        var res = e.target;
        target = res.id;
        if (e.target.getContext) {
            // click only inside Non Transparent part
            var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
            if (pixel[3] === 255) {
              if(!$(e.currentTarget).data('image_set'+target))
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        }
    });

    // Fetch mask images from json file - IGNORE this code

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            height,
                            width,
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data) {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);
        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            } of arr) {

            //Get Height and width of mask image [ edit button ]
            var ImagePosition = arr;
            //code end

            var mask = $(".container").mask({
                imageUrl: imageUrl,

                // Fetch Mask images
                maskImageUrl: 'http://i.imgur.com/' + src,
                // end

                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            // here
            table.push(mask);
            fileup.onchange = function() {
   // my work
          //  $("#"+String(target)).css("pointer-events", "none");
   // end
                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";

                //  Remove image

                $("<br/><span id=\"" + newImageLoadedId + "\" class=\"remove\">Remove</span>").insertAfter(".masked-img" + newImageLoadedId).css({
                    "left": ImagePosition[newImageLoadedId].x + (ImagePosition[newImageLoadedId].width / 2) + "px",
                    "top": ImagePosition[newImageLoadedId].y + (ImagePosition[newImageLoadedId].height / 2 + 25) + "px"
                });

                $(".remove").click(function(event) {
    // my work
   // $('.container').css('pointer-events','');
    // end
                    const canvasId = "canvas#" + event.currentTarget.id;
                    // Delete the uploaded image & icon
                    const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
                    ctx.fillStyle = "white"
                    ctx.fillRect(0, 0, 500, 500)
                    $('#container').data('image_set'+event.currentTarget.id, false)
                    // Delete the Remove button
                    $(this).remove();
     // my work
    // $(canvasId).css("pointer-events","");
     //end

                });

                // Remove image code end here....
            };
            counter++;
        }
        return mask;
    }
    mask = json(jsonData);
}); // end of function

// Image code

(function($) {
    window.JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
            rotate: 0,
        }, options);

        // Create the image properties
        settings.maskImage = new Image
        settings.image = new Image

        // set the cross-origin attributes
        settings.maskImage.setAttribute('crossOrigin', 'anonymous');
        settings.image.setAttribute('crossOrigin', 'anonymous');

        settings.maskImage.onload = function() {
            // once the mask is loaded, load the image
            container.loadImage(settings.imageUrl, true)
        }

        settings.image.onload = function() {
            // once the image is loaded, render to canvas
            container.drawMask()
            container.drawImage()
        }

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            scale = settings.scale,
            div;

        container.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }

        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };

        container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }

        container.drawMask = function() {
            canvas.width = settings.maskImage.width;
            canvas.height = settings.maskImage.height;
            context.save();
            context.beginPath();
            context.globalCompositeOperation = "source-over";
            // draw the masked image after scaling
            context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage
                .height);
            context.restore()
        };

        container.drawImage = function() {
            const img = settings.image

            settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
            settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;

            context.globalCompositeOperation = 'source-atop';
            context.save();
            context.translate(settings.x + img.width / 2, settings.y + img.height / 2);
            context.rotate(settings.rotate);
            context.scale(settings.scale, settings.scale);
            context.translate(-(settings.x + img.width / 2), -(settings.y + img.height / 2));
            let width = img.width,
                height = img.height;
            context.drawImage(img, settings.x, settings.y, width, height);
            context.restore();
            initImage = false;
        }

        container.onDragStart = function(evt) {
           // console.log('Draw started');
            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;

                $(canvas).attr("active", "true");
                container.selected(evt);
                prevX = evt.clientX;
                prevY = evt.clientY;
                var img = new Image();
                evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
                evt.originalEvent.dataTransfer.setData('text/plain', 'anything');

            }
        };

        container.onDragOver = function(evt) {
           // console.log('Drag over');

            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
                if (pixel[3] === 255) {
                    if (draggable && $(canvas).attr("active") === "true") {
                        var x = settings.x + evt.clientX - prevX;
                        var y = settings.y + evt.clientY - prevY;
                        if (x == settings.x && y == settings.y)
                            return; // position has not changed
                        settings.x += evt.clientX - prevX;
                        settings.y += evt.clientY - prevY;
                        prevX = evt.clientX;
                        prevY = evt.clientY;

                        clearTimeout(timeout);
                        timeout = setTimeout(function() {
                            container.drawMask();
                            container.drawImage();
                        }, 1);
                    }
                } else {
                    evt.stopPropagation();
                    return false;
                }
            }
        };

        container.loadImage = function(imageUrl, isMask) {
            settings.y = startY;
            settings.x = startX;
            settings.scale = 1;
            settings.rotate = 0;
            prevX = prevY = 0;
            initImage = true;
            settings.image.src = imageUrl; // CHANGED
            if(!isMask)
               container.data('image_set'+settings.id, true)
            // sirpepole Add this
            return settings.id;
        };

        container.loadMaskImage = function(imageUrl, from) {
            console.log('loading mask image from', imageUrl, from)
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImage.src = imageUrl // CHANGED

            div = $("<div/>", {
                "class": "masked-img"
            }).append(canvas);

            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);

            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        // Edit image
        div.addClass('masked-img' + settings.id);
        div.attr('data-id', settings.id);
        // ends
        return container;
    };
}(jQuery));

.container {
 background: silver;
 position: relative;
}

.container img {
 position: absolute;
 top: 0;
 bottom: 250px;
 left: 0;
 right: 0;
 margin: auto;
 z-index: 999;
}

.masked-img {
 overflow: hidden;
 position: relative;
}

.pip {
 display: inline-block;
 margin: 0;
 position: absolute;
}

.remove {
 background: #444;
 border: 1px solid black;
 color: white;
 text-align: center;
 cursor: pointer;
 position: absolute;
 z-index: 3;
}

.remove:hover {
 background: white;
 color: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>

    <input id="fileup" name="fileup" type="file" style="display:none">

    <div id="container" class="container">
    </div>

PS: I would suggest using a framework given the complexity of your code even though the above code changes would help you.


来源: stackexchange

问:
vba stack object
How to store objects in stack in vba?

Thanks for your answer.

Regards,
Balu.

答:
You can implement a stack in VBA by using a collection.

You would write simple functions to implement push and pop.  Push would add the argument to the collection.  Pop would return the .count Item of the collection and then remove the .count item.

ContentLicense: CC BY-SA 4.0

Title: vba stack object


问:
what is the unique id of informix temp table?
I create a temp table which consist of several table with UNION ALL statement like here below. I want later map this table to the entity for repository in spring. With other words I wanna map temp table to entity in spring jpa or hibernate.

```<code>select * from name  UNION ALL
select * from soft where id >3
into temp namesoft_tmp
</code>```

I tried the following.

```<code>select * from namesoft_tmp
</code>```

but i can't see what is the column which can point me to the conclusion that this is primary key.

What is the unique id(primary key) of table namesoft_tmp?

How can i add auto generated id to temp table?

How can i excute select statement based on unique id?**

答:
In general, the result of a UNION ALL query does not have a primary key; there is no guarantee that there are not duplicate rows in the result set.

Imagine a table describing the table of elements — called elements.

```<code>SELECT * FROM elements WHERE atomic_number < 10
UNION ALL
SELECT * FROM elements WHERE symbol MATCHES '[A-F]*'
INTO TEMP union_all;
</code>```

Here, the elements Boron (B), Carbon (C), Beryllium (Be) and Fluorine (F) are all listed twice.

However, you can use:

```<code>SELECT ROWID, * FROM union_all ORDER BY atomic_number;
</code>```

to get a unique identifier, the ROWID, in the result set.  Note that this unique identifier is unique at any given time, but is not guaranteed to be stable.  If you delete rows and add them again, the ROWID of the replaced rows may be different from before.  But the ROWID will be unique until you edit the table.

```<code>+-------+--------+--------+--------------+-----------+--------+-------+
| rowid | atomic | symbol | name         | atomic    | period | group |
|       | number |        |              | weight    |        |       |
+-------+--------+--------+--------------+-----------+--------+-------+
|   257 |      1 | H      | Hydrogen     |    1.0079 |      1 | 1     |
|   258 |      2 | He     | Helium       |    4.0026 |      1 | 18    |
|   259 |      3 | Li     | Lithium      |    6.9410 |      2 | 1     |
|   260 |      4 | Be     | Beryllium    |    9.0122 |      2 | 2     |
|   266 |      4 | Be     | Beryllium    |    9.0122 |      2 | 2     |
|   267 |      5 | B      | Boron        |   10.8110 |      2 | 13    |
|   261 |      5 | B      | Boron        |   10.8110 |      2 | 13    |
|   268 |      6 | C      | Carbon       |   12.0110 |      2 | 14    |
|   262 |      6 | C      | Carbon       |   12.0110 |      2 | 14    |
|   263 |      7 | N      | Nitrogen     |   14.0070 |      2 | 15    |
|   264 |      8 | O      | Oxygen       |   15.9990 |      2 | 16    |
|   265 |      9 | F      | Fluorine     |   18.9980 |      2 | 17    |
|   269 |      9 | F      | Fluorine     |   18.9980 |      2 | 17    |
|   270 |     13 | Al     | Aluminium    |   26.9820 |      3 | 13    |
|   271 |     17 | Cl     | Chlorine     |   35.4530 |      3 | 17    |
|   272 |     18 | Ar     | Argon        |   39.9480 |      3 | 18    |
|   273 |     20 | Ca     | Calcium      |   40.0780 |      4 | 2     |
|   274 |     24 | Cr     | Chromium     |   51.9960 |      4 | 6     |
|   275 |     26 | Fe     | Iron         |   55.8450 |      4 | 8     |
|   276 |     27 | Co     | Cobalt       |   58.9330 |      4 | 9     |
|   277 |     29 | Cu     | Copper       |   63.5460 |      4 | 11    |
|   278 |     33 | As     | Arsenic      |   74.9220 |      4 | 15    |
|   279 |     35 | Br     | Bromine      |   79.9040 |      4 | 17    |
|   280 |     47 | Ag     | Silver       |  107.8700 |      5 | 11    |
|   281 |     48 | Cd     | Cadmium      |  112.4100 |      5 | 12    |
|   282 |     55 | Cs     | Caesium      |  132.9100 |      6 | 1     |
|   283 |     56 | Ba     | Barium       |  137.3300 |      6 | 2     |
|   284 |     58 | Ce     | Cerium       |  140.1200 |      6 | L     |
|   285 |     63 | Eu     | Europium     |  151.9600 |      6 | L     |
|   286 |     66 | Dy     | Dyprosium    |  162.5000 |      6 | L     |
|   287 |     68 | Er     | Erbium       |  167.2600 |      6 | L     |
|   288 |     79 | Au     | Gold         |  196.9700 |      6 | 11    |
|   289 |     83 | Bi     | Bismuth      |  208.9800 |      6 | 15    |
|   290 |     85 | At     | Astatine     |  209.9900 |      6 | 17    |
|   291 |     87 | Fr     | Francium     |  223.0200 |      7 | 1     |
|   292 |     89 | Ac     | Actinium     |  227.0300 |      7 | A     |
|   293 |     95 | Am     | Americium    |  243.0600 |      7 | A     |
|   294 |     96 | Cm     | Curium       |  247.0700 |      7 | A     |
|   295 |     97 | Bk     | Berkelium    |  247.0700 |      7 | A     |
|   296 |     98 | Cf     | Californium  |  251.0800 |      7 | A     |
|   297 |     99 | Es     | Einsteinium  |  252.0800 |      7 | A     |
|   298 |    100 | Fm     | Fermium      |  257.1000 |      7 | A     |
|   299 |    105 | Db     | Dubnium      |  270.1300 |      7 | 5     |
|   300 |    107 | Bh     | Bohrium      |  270.1300 |      7 | 7     |
|   301 |    110 | Ds     | Darmstadtium |  281.1700 |      7 | 10    |
|   302 |    112 | Cn     | Copernicium  |  285.1800 |      7 | 12    |
|   303 |    114 | Fl     | Flerovium    |  289.1900 |      7 | 14    |
+-------+--------+--------+--------------+-----------+--------+-------+
</code>```

Body:
I create a temp table which consist of several table with UNION ALL statement like here below. I want later map this table to the entity for repository in spring. With other words I wanna map temp table to entity in spring jpa or hibernate.

select * from name  UNION ALL
select * from soft where id >3
into temp namesoft_tmp

I tried the following.

select * from namesoft_tmp

but i can't see what is the column which can point me to the conclusion that this is primary key.

What is the unique id(primary key) of table namesoft_tmp?

How can i add auto generated id to temp table?

How can i excute select statement based on unique id?**

Body:
In general, the result of a UNION ALL query does not have a primary key; there is no guarantee that there are not duplicate rows in the result set.

Imagine a table describing the table of elements — called elements.

SELECT * FROM elements WHERE atomic_number < 10
UNION ALL
SELECT * FROM elements WHERE symbol MATCHES '[A-F]*'
INTO TEMP union_all;

Here, the elements Boron (B), Carbon (C), Beryllium (Be) and Fluorine (F) are all listed twice.

However, you can use:

SELECT ROWID, * FROM union_all ORDER BY atomic_number;

to get a unique identifier, the ROWID, in the result set.  Note that this unique identifier is unique at any given time, but is not guaranteed to be stable.  If you delete rows and add them again, the ROWID of the replaced rows may be different from before.  But the ROWID will be unique until you edit the table.

+-------+--------+--------+--------------+-----------+--------+-------+
| rowid | atomic | symbol | name         | atomic    | period | group |
|       | number |        |              | weight    |        |       |
+-------+--------+--------+--------------+-----------+--------+-------+
|   257 |      1 | H      | Hydrogen     |    1.0079 |      1 | 1     |
|   258 |      2 | He     | Helium       |    4.0026 |      1 | 18    |
|   259 |      3 | Li     | Lithium      |    6.9410 |      2 | 1     |
|   260 |      4 | Be     | Beryllium    |    9.0122 |      2 | 2     |
|   266 |      4 | Be     | Beryllium    |    9.0122 |      2 | 2     |
|   267 |      5 | B      | Boron        |   10.8110 |      2 | 13    |
|   261 |      5 | B      | Boron        |   10.8110 |      2 | 13    |
|   268 |      6 | C      | Carbon       |   12.0110 |      2 | 14    |
|   262 |      6 | C      | Carbon       |   12.0110 |      2 | 14    |
|   263 |      7 | N      | Nitrogen     |   14.0070 |      2 | 15    |
|   264 |      8 | O      | Oxygen       |   15.9990 |      2 | 16    |
|   265 |      9 | F      | Fluorine     |   18.9980 |      2 | 17    |
|   269 |      9 | F      | Fluorine     |   18.9980 |      2 | 17    |
|   270 |     13 | Al     | Aluminium    |   26.9820 |      3 | 13    |
|   271 |     17 | Cl     | Chlorine     |   35.4530 |      3 | 17    |
|   272 |     18 | Ar     | Argon        |   39.9480 |      3 | 18    |
|   273 |     20 | Ca     | Calcium      |   40.0780 |      4 | 2     |
|   274 |     24 | Cr     | Chromium     |   51.9960 |      4 | 6     |
|   275 |     26 | Fe     | Iron         |   55.8450 |      4 | 8     |
|   276 |     27 | Co     | Cobalt       |   58.9330 |      4 | 9     |
|   277 |     29 | Cu     | Copper       |   63.5460 |      4 | 11    |
|   278 |     33 | As     | Arsenic      |   74.9220 |      4 | 15    |
|   279 |     35 | Br     | Bromine      |   79.9040 |      4 | 17    |
|   280 |     47 | Ag     | Silver       |  107.8700 |      5 | 11    |
|   281 |     48 | Cd     | Cadmium      |  112.4100 |      5 | 12    |
|   282 |     55 | Cs     | Caesium      |  132.9100 |      6 | 1     |
|   283 |     56 | Ba     | Barium       |  137.3300 |      6 | 2     |
|   284 |     58 | Ce     | Cerium       |  140.1200 |      6 | L     |
|   285 |     63 | Eu     | Europium     |  151.9600 |      6 | L     |
|   286 |     66 | Dy     | Dyprosium    |  162.5000 |      6 | L     |
|   287 |     68 | Er     | Erbium       |  167.2600 |      6 | L     |
|   288 |     79 | Au     | Gold         |  196.9700 |      6 | 11    |
|   289 |     83 | Bi     | Bismuth      |  208.9800 |      6 | 15    |
|   290 |     85 | At     | Astatine     |  209.9900 |      6 | 17    |
|   291 |     87 | Fr     | Francium     |  223.0200 |      7 | 1     |
|   292 |     89 | Ac     | Actinium     |  227.0300 |      7 | A     |
|   293 |     95 | Am     | Americium    |  243.0600 |      7 | A     |
|   294 |     96 | Cm     | Curium       |  247.0700 |      7 | A     |
|   295 |     97 | Bk     | Berkelium    |  247.0700 |      7 | A     |
|   296 |     98 | Cf     | Californium  |  251.0800 |      7 | A     |
|   297 |     99 | Es     | Einsteinium  |  252.0800 |      7 | A     |
|   298 |    100 | Fm     | Fermium      |  257.1000 |      7 | A     |
|   299 |    105 | Db     | Dubnium      |  270.1300 |      7 | 5     |
|   300 |    107 | Bh     | Bohrium      |  270.1300 |      7 | 7     |
|   301 |    110 | Ds     | Darmstadtium |  281.1700 |      7 | 10    |
|   302 |    112 | Cn     | Copernicium  |  285.1800 |      7 | 12    |
|   303 |    114 | Fl     | Flerovium    |  289.1900 |      7 | 14    |
+-------+--------+--------+--------------+-----------+--------+-------+


问:
Why do .Net applications receive WM_NCHITTEST twice?
I'm doing a function that seamless simulates the messages generated by SendInput.

So far i'm sending WM_NCHITTEST to the window.
Then WM_SETCURSOR with the result of the hit test.
And finally WM_MOUSEMOVE.

But some windows (ie: visualstudio, .net ones) receive a sequence of 2 or more identical WM_NCHITTEST.

How can i know how many hit tests are sent to a window?

```<code>/*Example from vstudio 2010:*/
<15008> 000E030E S WM_NCHITTEST xPos:509 yPos:543   //1st
<15009> 000E030E R WM_NCHITTEST nHittest:HTCLIENT
<15010> 000E030E S WM_NCHITTEST xPos:509 yPos:543   //2nd
<15011> 000E030E R WM_NCHITTEST nHittest:HTCLIENT
<15012> 000E030E S WM_SETCURSOR hwnd:000E030E nHittest:HTCLIENT wMouseMsg:WM_MOUSEMOVE
<15013> 000E030E R WM_SETCURSOR fHaltProcessing:False
<15014> 000E030E P WM_MOUSEMOVE fwKeys:0000 xPos:509 yPos:543
</code>```

答:
The Windows OS or any application may send WM_NCHITTEST for any coordinate anytime it needs to inquire about the geometry of your window. If your code makes any assumptions at all about when it is called, your code is wrong.

In theory, "Because I felt like it" is a valid answer to "why did you send WM_NCHITTEST."

In the broad sense, simulating SendInput() by SendMessage() doesn't work right. You should stop trying to do that.

ContentLicense: CC BY-SA 3.0

Body:
I'm doing a function that seamless simulates the messages generated by SendInput.

So far i'm sending WM_NCHITTEST to the window.
Then WM_SETCURSOR with the result of the hit test.
And finally WM_MOUSEMOVE.

But some windows (ie: visualstudio, .net ones) receive a sequence of 2 or more identical WM_NCHITTEST.

How can i know how many hit tests are sent to a window?

/*Example from vstudio 2010:*/
<15008> 000E030E S WM_NCHITTEST xPos:509 yPos:543   //1st
<15009> 000E030E R WM_NCHITTEST nHittest:HTCLIENT
<15010> 000E030E S WM_NCHITTEST xPos:509 yPos:543   //2nd
<15011> 000E030E R WM_NCHITTEST nHittest:HTCLIENT
<15012> 000E030E S WM_SETCURSOR hwnd:000E030E nHittest:HTCLIENT wMouseMsg:WM_MOUSEMOVE
<15013> 000E030E R WM_SETCURSOR fHaltProcessing:False
<15014> 000E030E P WM_MOUSEMOVE fwKeys:0000 xPos:509 yPos:543


问:
remove element with specific class only when other class is active
I have an element that can be removed when it has the class "edit-mode". The class "edit-mode" is toggled by a button. The problem here is that when the "edit-mode" class gets removed, this element can be removed on click which shouldn't happen.

Consider the following code :

$(document).ready(function() {
  $('.active-edit-mode').click(function() {
    $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
    $('.my-element.edit-mode').click(function() {
      $(this).remove();
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.my-element {
  color: #007aff;
  cursor: pointer;
}

.edit-mode {
  font-weight: bold;
}</code>```

    this element

    this element

    this element

<button class="active-edit-mode">
active edit mode
</button>```

Jsfiddle : jsfiddle

答:
You should check this logic in the onClick event handler of .my-element, this would be more clearer.

$(document).ready(function(){
 $('.active-edit-mode').click(function(){
   $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
  });

  $('.my-element').click(function(){
    if ($(this).hasClass('edit-mode')) {
      console.log('click removing')
      $(this).remove();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.my-element { color: #007aff;cursor:pointer; }
.edit-mode {font-weight:bold;}</code>```

  this element

  this element

  this element

<button class="active-edit-mode">
active edit mode
</button>```

Body:
I have an element that can be removed when it has the class "edit-mode". The class "edit-mode" is toggled by a button. The problem here is that when the "edit-mode" class gets removed, this element can be removed on click which shouldn't happen.

Consider the following code :

$(document).ready(function() {
  $('.active-edit-mode').click(function() {
    $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
    $('.my-element.edit-mode').click(function() {
      $(this).remove();
    });
  });
});

.my-element {
  color: #007aff;
  cursor: pointer;
}

.edit-mode {
  font-weight: bold;
}

    this element

    this element

    this element

<button class="active-edit-mode">
active edit mode
</button>

Jsfiddle : jsfiddle

Body:
You should check this logic in the onClick event handler of .my-element, this would be more clearer.

$(document).ready(function(){
 $('.active-edit-mode').click(function(){
   $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
  });

  $('.my-element').click(function(){
    if ($(this).hasClass('edit-mode')) {
      console.log('click removing')
      $(this).remove();
    }
  });
});

.my-element { color: #007aff;cursor:pointer; }
.edit-mode {font-weight:bold;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elements">
  <div class="my-element">
  this element
  </div>
    <div class="my-element">
  this element
  </div>
      <div class="my-element">
  this element
  </div>
</div>
<button class="active-edit-mode">
active edit mode
</button>


问:
How can I access/process content within TensorFlow Datasets?
I am working with the cnn_dailymail dataset which is part of the TensorFlow Datasets.
I access it as follows:

```<code>import tensorflow_datasets as tfds
data, info = tfds.load('cnn_dailymail', with_info=True)
train_data, test_data = data['train'], data['test']
</code>```

To extract a single example from the dataset I use:

```<code>cnn_ex, = train_data.take(1)
cnn_ex['highlights'].numpy()
</code>```

This will return a string similar to this: "emma monaghan, 27, from glasgow, used to weigh 18st 5lbs .". I would like to apply some pre-processing steps to this dataset so I can use it as an input into a deep learning algorithm. The example above should look like this after preprocessing: "<start> emma monaghan, 27, from glasgow, used to weigh 18st 5lbs . <end>".

Is there a way to access and pre-process all the text (within train_data) at once without having to apply the take() function multiple times? For example converting the TensorFlow Dataset into a numpy array would already help. Thanks!

答:
You could use dataset.map() to apply transformations to your data. For example:

import tensorflow as tf
import tensorflow_datasets as tfds

data, info = tfds.load('cnn_dailymail', with_info=True)
dataset_train, dataset_test = data['train'], data['test']

def map_fn(x, start=tf.constant('<start>'), end=tf.constant('<end>')):
    strings = [start, x['highlights'], end]
    x['highlights'] = tf.strings.join(strings, separator=' ')
    return x

dataset_train = dataset_train.map(map_fn) # <-- apply transformation for the whole data
elem,  = dataset_train.take(1)
print(elem['highlights'].numpy())
# b'<start> arthur potts dawson: british ... <end>'

```

Body:
I am working with the cnn_dailymail dataset which is part of the TensorFlow Datasets.
I access it as follows:

import tensorflow_datasets as tfds
data, info = tfds.load('cnn_dailymail', with_info=True)
train_data, test_data = data['train'], data['test']

To extract a single example from the dataset I use:

cnn_ex, = train_data.take(1)
cnn_ex['highlights'].numpy()

This will return a string similar to this: "emma monaghan, 27, from glasgow, used to weigh 18st 5lbs .". I would like to apply some pre-processing steps to this dataset so I can use it as an input into a deep learning algorithm. The example above should look like this after preprocessing: "<start> emma monaghan, 27, from glasgow, used to weigh 18st 5lbs . <end>".

Is there a way to access and pre-process all the text (within train_data) at once without having to apply the take() function multiple times? For example converting the TensorFlow Dataset into a numpy array would already help. Thanks!


问:
Serialization java to c#
I have manged to serialize an arraylist in java using xstream, send it to my c# application via http and then write that to file (just for now).

The serialized data was an arraylist in java. I want to try and re form this arraylist in c# from the xml i have.

I have been looking at http://code.google.com/p/xstream-dot-net/ to do this. Does anyone know if that is the right way to go or is there a better way of reforming the serialized data in c#?

答: I have used JSON.NET (Newtonsoft) on the .NET side and Google's GSON on the java side and it seems to work for Dictionaries, Maps, Sets, Lists, Date, and primitive types with very little configuration involved. Refer to https://github.com/chandru9279/Spikes for it.</p>

ContentLicense: CC BY-SA 2.5

Title: Serialization java to c#


问:
How do I change only one part of the string with variable values
I have a question about how to change the "%d" of the text vector by the value of the variable a.

```<code>int a = 3;
char text[]= "How I change this value: %d"
</code>```

And prints this:

How I change this value: 3

答:
Since you only want to print it:</p>

```<code>printf(text, a);
</code>```

Body:
I have a question about how to change the "%d" of the text vector by the value of the variable a.

int a = 3;
char text[]= "How I change this value: %d"

And prints this:

How I change this value: 3

Body:
Since you only want to print it:

printf(text, a);


答:
It will work if you bind the removal function independently. Your JS would look like:</p>

```<code>$(document).ready(function(){
    $('.active-edit-mode').click(function(){
    $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
  });
});
$(document).on('click','.my-element.edit-mode',function(){
    $(this).remove();
  });
</code>```

Title: remove element with specific class only when other class is active

Body:
It will work if you bind the removal function independently. Your JS would look like:

$(document).ready(function(){
    $('.active-edit-mode').click(function(){
    $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
  });
});
$(document).on('click','.my-element.edit-mode',function(){
    $(this).remove();
  });


问:
How to extract comma separated substrings from a string?
Need to parse the algorithms separated by comma in group.

```<code>SSH Enabled - version 2.0
Authentication methods:publickey,keyboard-interactive,password
Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
MAC Algorithms:hmac-sha1,hmac-sha1-96
Authentication timeout: 120 secs; Authentication retries: 3
Minimum expected Diffie Hellman key size : 1024 bits
IOS Keys in SECSH format(ssh-rsa, base64 encoded):
</code>```

I have tried to separate them with comma  but not getting the expected results:

```<code>^Encryption Algorithms:(.*?)(?:,|$)
</code>```

Expected results is to have each algorithm in group 1 with no empty group

```<code>aes128-ctr
aes192-ctr
aes256-ctr
aes128-cbc
3des-cbc
aes192-cbc
aes256-cbc
</code>```

答:
Another way could be to match the string starting with Encryption Algorithms:, and then capture in a group a repeating pattern that matches the part with the hyphen and repeats that with a comma prepended.

If there is a match, you could split the first capturing group on a comma.

```<code>^Encryption Algorithms:(\w+-\w+(?:,\w+-\w+)*)
</code>```

Explanation

^

Encryption Algorithms:

( Start capturing group

\w+-\w+ Match 1+ word chars, - and 1+ word chars

(?:,\w+-\w+)* 0+ times repeat a comma followed by 1+ word chars, - and 1+ word chars

) Close capturing group

Regex demo | Python demo

```<code>import re
regex = r"^Encryption Algorithms:(\w+-\w+(?:,\w+-\w+)*)"
test_str = ("SSH Enabled - version 2.0\n"
            "Authentication methods:publickey,keyboard-interactive,password\n"
            "Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc\n"
            "MAC Algorithms:hmac-sha1,hmac-sha1-96\n"
            "Authentication timeout: 120 secs; Authentication retries: 3\n"
            "Minimum expected Diffie Hellman key size : 1024 bits\n"
            "IOS Keys in SECSH format(ssh-rsa, base64 encoded):")

matches = re.search(regex, test_str, re.MULTILINE)
if matches:
    print(matches.group(1).split(","))
</code>```

Result:

```<code>['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc']
</code>```

Body:
Need to parse the algorithms separated by comma in group.

SSH Enabled - version 2.0
Authentication methods:publickey,keyboard-interactive,password
Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
MAC Algorithms:hmac-sha1,hmac-sha1-96
Authentication timeout: 120 secs; Authentication retries: 3
Minimum expected Diffie Hellman key size : 1024 bits
IOS Keys in SECSH format(ssh-rsa, base64 encoded):

I have tried to separate them with comma  but not getting the expected results:

^Encryption Algorithms:(.*?)(?:,|$)

Expected results is to have each algorithm in group 1 with no empty group

aes128-ctr
aes192-ctr
aes256-ctr
aes128-cbc
3des-cbc
aes192-cbc
aes256-cbc

Body:
Another way could be to match the string starting with Encryption Algorithms:, and then capture in a group a repeating pattern that matches the part with the hyphen and repeats that with a comma prepended.

If there is a match, you could split the first capturing group on a comma.

^Encryption Algorithms:(\w+-\w+(?:,\w+-\w+)*)

Explanation

^

Encryption Algorithms:

( Start capturing group

\w+-\w+ Match 1+ word chars, - and 1+ word chars

(?:,\w+-\w+)* 0+ times repeat a comma followed by 1+ word chars, - and 1+ word chars

) Close capturing group

Regex demo | Python demo

import re
regex = r"^Encryption Algorithms:(\w+-\w+(?:,\w+-\w+)*)"
test_str = ("SSH Enabled - version 2.0\n"
            "Authentication methods:publickey,keyboard-interactive,password\n"
            "Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc\n"
            "MAC Algorithms:hmac-sha1,hmac-sha1-96\n"
            "Authentication timeout: 120 secs; Authentication retries: 3\n"
            "Minimum expected Diffie Hellman key size : 1024 bits\n"
            "IOS Keys in SECSH format(ssh-rsa, base64 encoded):")

matches = re.search(regex, test_str, re.MULTILINE)
if matches:
    print(matches.group(1).split(","))

Result:

['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc']


问:
How does Kubernetes control replication?
I was curious about how Kubernetes controls replication.  I my config yaml file specifies I want three pods, each with an Nginx server, for instance (from here -- https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#how-a-replicationcontroller-works)

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
</code>```

How does Kubernetes know when to shut down pods and when to spin up more?  For example, for high traffic loads, I'd like to spin up another pod, but I'm not sure how to configure that in the YAML file so I was wondering if Kubernetes has some behind-the-scenes magic that does that for you.

答:
You can use HorizontalPodAutoscaler along with deployment as below. This will autoscale your pod declaratively based on target CPU utilization.</p>

```<code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: $DEPLOY_NAME
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: $DEPLOY_NAME
    spec:
      containers:
      - name: $DEPLOY_NAME
        image: $DEPLOY_IMAGE
        imagePullPolicy: Always
        resources:
          requests:
            cpu: "0.2"
            memory: 256Mi
          limits:
            cpu: "1"
            memory: 1024Mi
---
apiVersion: v1
kind: Service
metadata:
  name: $DEPLOY_NAME
spec:
  selector:
    app: $DEPLOY_NAME
  ports:
      - port: 8080
  type: ClusterIP
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: $DEPLOY_NAME
  namespace: $K8S_NAMESPACE
spec:
  scaleTargetRef:
    apiVersion: apps/v1beta1
    kind: Deployment
    name: $DEPLOY_NAME
  minReplicas: 2
  maxReplicas: 6
  targetCPUUtilizationPercentage: 60
</code>```

Body:
I was curious about how Kubernetes controls replication.  I my config yaml file specifies I want three pods, each with an Nginx server, for instance (from here -- https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#how-a-replicationcontroller-works)

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80

How does Kubernetes know when to shut down pods and when to spin up more?  For example, for high traffic loads, I'd like to spin up another pod, but I'm not sure how to configure that in the YAML file so I was wondering if Kubernetes has some behind-the-scenes magic that does that for you.

Body:
You can use HorizontalPodAutoscaler along with deployment as below. This will autoscale your pod declaratively based on target CPU utilization.

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: $DEPLOY_NAME
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: $DEPLOY_NAME
    spec:
      containers:
      - name: $DEPLOY_NAME
        image: $DEPLOY_IMAGE
        imagePullPolicy: Always
        resources:
          requests:
            cpu: "0.2"
            memory: 256Mi
          limits:
            cpu: "1"
            memory: 1024Mi
---
apiVersion: v1
kind: Service
metadata:
  name: $DEPLOY_NAME
spec:
  selector:
    app: $DEPLOY_NAME
  ports:
      - port: 8080
  type: ClusterIP
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: $DEPLOY_NAME
  namespace: $K8S_NAMESPACE
spec:
  scaleTargetRef:
    apiVersion: apps/v1beta1
    kind: Deployment
    name: $DEPLOY_NAME
  minReplicas: 2
  maxReplicas: 6
  targetCPUUtilizationPercentage: 60


问:
Move carousel caption outside carousel
I'm trying to move the caption outside the coursel towards the left side but the problem it's not working.  Whenever it moves outside its parent container it stops showing. Can somebody please help me out. Here is a JS bin link --> JSBin

It would be great if anyone could help me out. Thanks

```<code>OS: Mac

Browser: Chrome 74.0

Bootstrap version: 4.1.1
</code>```

答:
Set the caption relative to the image:</p>

```<code>  .carousel-inner img {
      width: 100%;
      height: 100%;
      position: absoloute;
  }

  .carousel-caption {
    color: #000;
    position: relative;
    float: left;
    left: 0;
    margin-left: 30px;
    margin-top: 30px;
  }
</code>```

Title: Move carousel caption outside carousel

Body:
I'm trying to move the caption outside the coursel towards the left side but the problem it's not working.  Whenever it moves outside its parent container it stops showing. Can somebody please help me out. Here is a JS bin link --> JSBin

It would be great if anyone could help me out. Thanks

OS: Mac

Browser: Chrome 74.0

Bootstrap version: 4.1.1

Body:
Set the caption relative to the image:

  .carousel-inner img {
      width: 100%;
      height: 100%;
      position: absoloute;
  }

  .carousel-caption {
    color: #000;
    position: relative;
    float: left;
    left: 0;
    margin-left: 30px;
    margin-top: 30px;
  }


答:
snprintf is what you are looking for, if you want to hold the result in a variable. printf will print to stdout (your terminal).
You will find a great description the man-page.

In your case, the following code will work:

```<code>int a = 3;
char text[]= "How I change this value: %d";
char buf[MAX_LEN];
snprintf(buf, MAX_LEN, text, a);
</code>```

Now, the buffer buf will hold the string "How I change this value: 3"

Title: How do I change only one part of the string with variable values

Body:
snprintf is what you are looking for, if you want to hold the result in a variable. printf will print to stdout (your terminal).
You will find a great description the man-page.

In your case, the following code will work:

int a = 3;
char text[]= "How I change this value: %d";
char buf[MAX_LEN];
snprintf(buf, MAX_LEN, text, a);

Now, the buffer buf will hold the string "How I change this value: 3"