text:
Q: How to make HTML element resizable using pure Javascript? I was wondering how we can make a HTML element like
 or
 tag element resizable when clicked using pure JavaScript, not the jQuery library or any other library.

A: just using the mousemove event in vanilla js
steps

*

*add the mousemove to your target

*listen to the target move event

*get the pointer position, resize your target
codes
    const div = document.querySelector(`div.before`);
    const box = document.querySelector(`div.container`);
    box.addEventListener(`mousemove`, (e) => {
      const {
        offsetX,
        offsetY,
      } = e;
      div.style.width = offsetX + `px`;
    });

live demo
https://codepen.io/xgqfrms/full/wvMQqZL

refs
https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event
https://medium.com/the-z/making-a-resizable-div-in-js-is-not-easy-as-you-think-bda19a1bc53d

A: here is a example with resizer helpers in all sides and corners

element = document.getElementById("element")
makeResizable(element,10,10)
function makeResizable(element, minW = 100, minH = 100, size = 20)
{
    const top = document.createElement('div');
    top.style.width = '100%';
    top.style.height = size + 'px';
    top.style.backgroundColor = 'transparent';
    top.style.position = 'absolute';
    top.style.top = - (size/2) + 'px';
    top.style.left = '0px';
    top.style.cursor = 'n-resize';

    top.addEventListener('mousedown',resizeYNegative())

    element.appendChild(top);

    const bottom = document.createElement('div');
    bottom.style.width = '100%';
    bottom.style.height = size + 'px';
    bottom.style.backgroundColor = 'transparent';
    bottom.style.position = 'absolute';
    bottom.style.bottom = - (size/2) + 'px';
    bottom.style.left = '0px';
    bottom.style.cursor = 'n-resize';

    bottom.addEventListener('mousedown',resizeYPositive())

    element.appendChild(bottom);

    const left = document.createElement('div');
    left.style.width = size + 'px';
    left.style.height = '100%';
    left.style.backgroundColor = 'transparent';
    left.style.position = 'absolute';
    left.style.top = '0px';
    left.style.left = - (size/2) + 'px';
    left.style.cursor = 'e-resize';

    left.addEventListener('mousedown',resizeXNegative())

    element.appendChild(left);

    const right = document.createElement('div');
    right.style.width = size + 'px';
    right.style.height = '100%';
    right.style.backgroundColor = 'transparent';
    right.style.position = 'absolute';
    right.style.top = '0px';
    right.style.right = - (size/2) + 'px';
    right.style.cursor = 'e-resize';

    right.addEventListener('mousedown',resizeXPositive())

    element.appendChild(right);

    const corner1 = document.createElement('div');
    corner1.style.width = size + 'px';
    corner1.style.height = size + 'px';
    corner1.style.backgroundColor = 'transparent';
    corner1.style.position = 'absolute';
    corner1.style.top = - (size/2) + 'px';
    corner1.style.left = - (size/2) + 'px';
    corner1.style.cursor = 'nw-resize';

    corner1.addEventListener('mousedown',resizeXNegative())
    corner1.addEventListener('mousedown',resizeYNegative())

    element.appendChild(corner1);

    const corner2 = document.createElement('div');
    corner2.style.width = size + 'px';
    corner2.style.height = size + 'px';
    corner2.style.backgroundColor = 'transparent';
    corner2.style.position = 'absolute';
    corner2.style.top = - (size/2) + 'px';
    corner2.style.right = - (size/2) + 'px';
    corner2.style.cursor = 'ne-resize';

    corner2.addEventListener('mousedown',resizeXPositive())
    corner2.addEventListener('mousedown',resizeYNegative())

    element.appendChild(corner2);

    const corner3 = document.createElement('div');
    corner3.style.width = size + 'px';
    corner3.style.height = size + 'px';
    corner3.style.backgroundColor = 'transparent';
    corner3.style.position = 'absolute';
    corner3.style.bottom = - (size/2) + 'px';
    corner3.style.left = - (size/2) + 'px';
    corner3.style.cursor = 'sw-resize';

    corner3.addEventListener('mousedown',resizeXNegative())
    corner3.addEventListener('mousedown',resizeYPositive())

    element.appendChild(corner3);

    const corner4 = document.createElement('div');
    corner4.style.width = size + 'px';
    corner4.style.height = size + 'px';
    corner4.style.backgroundColor = 'transparent';
    corner4.style.position = 'absolute';
    corner4.style.bottom = - (size/2) + 'px';
    corner4.style.right = - (size/2) + 'px';
    corner4.style.cursor = 'se-resize';

    corner4.addEventListener('mousedown',resizeXPositive())
    corner4.addEventListener('mousedown',resizeYPositive())

    element.appendChild(corner4);

    function get_int_style(key)
    {
        return parseInt(window.getComputedStyle(element).getPropertyValue(key));
    }

    function resizeXPositive()
    {
        let offsetX
        function dragMouseDown(e) {
            if(e.button !== 0) return
            e = e || window.event;
            e.preventDefault();
            const {clientX} = e;
            offsetX = clientX - element.offsetLeft - get_int_style('width');
            document.addEventListener('mouseup', closeDragElement)
            document.addEventListener('mousemove', elementDrag)
          }

          function elementDrag(e) {
                const {clientX} = e;
                let x = clientX - element.offsetLeft - offsetX
                if(x < minW) x = minW;
                element.style.width =  x + 'px';
          }

          function closeDragElement() {
            document.removeEventListener("mouseup", closeDragElement);
            document.removeEventListener("mousemove", elementDrag);
          }
        return dragMouseDown
    }

    function resizeYPositive()
    {
        let offsetY
        function dragMouseDown(e) {
            if(e.button !== 0) return
            e = e || window.event;
            e.preventDefault();
            const {clientY} = e;
            offsetY = clientY - element.offsetTop - get_int_style('height');

            document.addEventListener('mouseup',closeDragElement)
            document.addEventListener('mousemove',elementDrag)
          }

          function elementDrag(e) {
                const {clientY} = e;
                let y =  clientY - element.offsetTop - offsetY;
                if(y < minH) y = minH;
                element.style.height = y + 'px';
          }

          function closeDragElement() {
            document.removeEventListener("mouseup", closeDragElement);
            document.removeEventListener("mousemove", elementDrag);
          }
        return dragMouseDown
    }

    function resizeXNegative()
    {
        let offsetX
        let startX
        let startW
        let maxX
        function dragMouseDown(e) {
            if(e.button !== 0) return
            e = e || window.event;
            e.preventDefault();
            const {clientX} = e;
            startX = get_int_style('left')
            startW = get_int_style('width')
            offsetX = clientX - startX;
            maxX = startX + startW - minW

            document.addEventListener('mouseup',closeDragElement)
            document.addEventListener('mousemove',elementDrag)
          }

          function elementDrag(e) {
                const {clientX} = e;
                let x = clientX - offsetX
                let w = startW + startX - x
                if(w < minW) w = minW;
                if(x > maxX) x = maxX;
                element.style.left = x + 'px';
                element.style.width = w + 'px';
          }

          function closeDragElement() {
            document.removeEventListener("mouseup", closeDragElement);
            document.removeEventListener("mousemove", elementDrag);
          }
        return dragMouseDown
    }

    function resizeYNegative()
    {
        let offsetY
        let startY
        let startH
        let maxY
        function dragMouseDown(e) {
            if(e.button !== 0) return
            e = e || window.event;
            e.preventDefault();
            const {clientY} = e;
            startY = get_int_style('top')
            startH = get_int_style('height')
            offsetY = clientY - startY;
            maxY = startY + startH - minH

            document.addEventListener('mouseup',closeDragElement,false)
            document.addEventListener('mousemove',elementDrag,false)
          }

          function elementDrag(e) {
                const {clientY} = e;
                let y =  clientY - offsetY
                let h = startH + startY - y
                if(h < minH) h = minH;
                if(y > maxY) y = maxY;
                element.style.top = y + 'px';
                element.style.height = h + 'px';
          }

          function closeDragElement() {
            document.removeEventListener("mouseup", closeDragElement);
            document.removeEventListener("mousemove", elementDrag);
          }
        return dragMouseDown
    }
}
 #element {
  position: absolute;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  left: 40px;
  top:  40px;
  width: 100px;
  height: 100px;
  border-radius: 5px;
}

A: I just created a CodePen that shows how this can be done pretty easily using ES6.
http://codepen.io/travist/pen/GWRBQV
Basically, here is the class that does this.
let getPropertyValue = function(style, prop) {
  let value = style.getPropertyValue(prop);
  value = value ? value.replace(/[^0-9.]/g, '') : '0';
  return parseFloat(value);
}

let getElementRect = function(element) {
  let style = window.getComputedStyle(element, null);
  return {
    x: getPropertyValue(style, 'left'),
    y: getPropertyValue(style, 'top'),
    width: getPropertyValue(style, 'width'),
    height: getPropertyValue(style, 'height')
  }
}

class Resizer {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.element = element;
        this.options = options;
        this.offsetX = 0;
        this.offsetY = 0;
        this.handle = document.createElement('div');
        this.handle.setAttribute('class', 'drag-resize-handlers');
        this.handle.setAttribute('data-direction', 'br');
        this.wrapper.appendChild(this.handle);
        this.wrapper.style.top = this.element.style.top;
        this.wrapper.style.left = this.element.style.left;
        this.wrapper.style.width = this.element.style.width;
        this.wrapper.style.height = this.element.style.height;
        this.element.style.position = 'relative';
        this.element.style.top = 0;
        this.element.style.left = 0;
        this.onResize = this.resizeHandler.bind(this);
        this.onStop = this.stopResize.bind(this);
        this.handle.addEventListener('mousedown', this.initResize.bind(this));
    }

    initResize(event) {
        this.stopResize(event, true);
        this.handle.addEventListener('mousemove', this.onResize);
        this.handle.addEventListener('mouseup', this.onStop);
    }

    resizeHandler(event) {
        this.offsetX = event.clientX - (this.wrapper.offsetLeft + this.handle.offsetLeft);
        this.offsetY = event.clientY - (this.wrapper.offsetTop + this.handle.offsetTop);
        let wrapperRect = getElementRect(this.wrapper);
        let elementRect = getElementRect(this.element);
        this.wrapper.style.width = (wrapperRect.width + this.offsetX) + 'px';
        this.wrapper.style.height = (wrapperRect.height + this.offsetY) + 'px';
        this.element.style.width = (elementRect.width + this.offsetX) + 'px';
        this.element.style.height = (elementRect.height + this.offsetY) + 'px';
    }

    stopResize(event, nocb) {
        this.handle.removeEventListener('mousemove', this.onResize);
        this.handle.removeEventListener('mouseup', this.onStop);
    }
}

class Dragger {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.options = options;
        this.element = element;
        this.element.draggable = true;
        this.element.setAttribute('draggable', true);
        this.element.addEventListener('dragstart', this.dragStart.bind(this));
    }

    dragStart(event) {
        let wrapperRect = getElementRect(this.wrapper);
        var x = wrapperRect.x - parseFloat(event.clientX);
        var y = wrapperRect.y - parseFloat(event.clientY);
        event.dataTransfer.setData("text/plain", this.element.id + ',' + x + ',' + y);
    }

    dragStop(event, prevX, prevY) {
        var posX = parseFloat(event.clientX) + prevX;
        var posY = parseFloat(event.clientY) + prevY;
        this.wrapper.style.left = posX + 'px';
        this.wrapper.style.top = posY + 'px';
    }
}

class DragResize {
    constructor(element, options) {
        options = options || {};
        this.wrapper = document.createElement('div');
        this.wrapper.setAttribute('class', 'tooltip drag-resize');
        if (element.parentNode) {
          element.parentNode.insertBefore(this.wrapper, element);
        }
        this.wrapper.appendChild(element);
        element.resizer = new Resizer(this.wrapper, element, options);
        element.dragger = new Dragger(this.wrapper, element, options);
    }
}

document.body.addEventListener('dragover', function (event) {
    event.preventDefault();
    return false;
});

document.body.addEventListener('drop', function (event) {
    event.preventDefault();
    var dropData = event.dataTransfer.getData("text/plain").split(',');
    var element = document.getElementById(dropData[0]);
    element.dragger.dragStop(event, parseFloat(dropData[1]), parseFloat(dropData[2]));
    return false;
});

A: I have created a function that recieve an id of an html element and adds a border to it's right side
the function is general and just recieves an id so you can copy it as it is and it will work

var myoffset;
function resizeE(elem){
    var borderDiv = document.createElement("div");
    borderDiv.className = "border";
    borderDiv.addEventListener("mousedown",myresize = function myrsize(e) {
     myoffset = e.clientX - (document.getElementById(elem).offsetLeft + parseInt(window.getComputedStyle(document.getElementById(elem)).getPropertyValue("width")));
     window.addEventListener("mouseup",mouseUp);
     document.addEventListener("mousemove",mouseMove = function mousMove(e) {
      document.getElementById(elem).style.width = `${e.clientX -  myoffset - document.getElementById(elem).offsetLeft}px`;
  });
 });
    document.getElementById(elem).appendChild(borderDiv);
}

function mouseUp() {
    document.removeEventListener("mousemove", mouseMove);
    window.removeEventListener("mouseup",mouseUp);
}

function load()
{
 resizeE("resizeableDiv");
 resizeE("anotherresizeableDiv");
  resizeE("anotherresizeableDiv1");
}
.border {

  position: absolute;
  cursor: e-resize;
  width: 9px;
  right: -5px;
  top: 0;
  height: 100%;
}

#resizeableDiv {
  width: 30vw;
  height: 30vh;
  background-color: #84f4c6;
  position: relative;
}
#anotherresizeableDiv {
  width: 30vw;
  height: 30vh;
  background-color: #9394f4;
  position: relative;
}
#anotherresizeableDiv1 {
  width: 30vw;
  height: 30vh;
  background-color: #43f4f4;
  position: relative;
}
#anotherresizeableDiv1 .border{
  background-color: black;
}
#anotherresizeableDiv .border{
  width: 30px;
  right: -200px;
  background-color: green;
}

change my size with the east border

with visible border

with editted outside border

resizeE("resizeableDiv"); //this calls a function that does the magic to the id inserted

A: Is simple:
Example:https://jsfiddle.net/RainStudios/mw786v1w/
var element = document.getElementById('element');
//create box in bottom-left
var resizer = document.createElement('div');
resizer.style.width = '10px';
resizer.style.height = '10px';
resizer.style.background = 'red';
resizer.style.position = 'absolute';
resizer.style.right = 0;
resizer.style.bottom = 0;
resizer.style.cursor = 'se-resize';
//Append Child to Element
element.appendChild(resizer);
//box function onmousemove
resizer.addEventListener('mousedown', initResize, false);

//Window funtion mousemove & mouseup
function initResize(e) {
   window.addEventListener('mousemove', Resize, false);
   window.addEventListener('mouseup', stopResize, false);
}
//resize the element
function Resize(e) {
   element.style.width = (e.clientX - element.offsetLeft) + 'px';
   element.style.height = (e.clientY - element.offsetTop) + 'px';
}
//on mouseup remove windows functions mousemove & mouseup
function stopResize(e) {
    window.removeEventListener('mousemove', Resize, false);
    window.removeEventListener('mouseup', stopResize, false);
}

A: There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.
Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation.
In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!
let resizerForCenter = new Resizer('center')
resizerForCenter.initResizer()

See it in action with CodeSandbox:
In this example we use ES6, and a module that exports a class called Resizer.
An example is worth a thousand words:

Or with the code snippet:

const html = document.querySelector('html')

class Resizer {
 constructor(elemId) {
  this._elem = document.getElementById(elemId)
  /**
   * Stored binded context handlers for method passed to eventListeners!
   *
   * See: https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions
   */
  this._checkBorderHandler = this._checkBorder.bind(this)
  this._doResizeHandler  = this._doResize.bind(this)
  this._initResizerHandler = this.initResizer.bind(this)
  this._onResizeHandler  = this._onResize.bind(this)
 }

 initResizer() {
  this.stopResizer()
  this._beginResizer()
 }

 _beginResizer() {
  this._elem.addEventListener('mousemove', this._checkBorderHandler, false)
 }

 stopResizer() {
  html.style.cursor = 'default'
  this._elem.style.cursor = 'default'

  window.removeEventListener('mousemove', this._doResizeHandler, false)
  window.removeEventListener('mouseup', this._initResizerHandler, false)

  this._elem.removeEventListener('mousedown', this._onResizeHandler, false)
  this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)
 }

 _doResize(e) {
  let elem = this._elem

  let boxSizing = getComputedStyle(elem).boxSizing
  let borderRight = 0
  let borderLeft = 0
  let borderTop = 0
  let borderBottom = 0

  let paddingRight = 0
  let paddingLeft = 0
  let paddingTop = 0
  let paddingBottom = 0

  switch (boxSizing) {
   case 'content-box':
     paddingRight = parseInt(getComputedStyle(elem).paddingRight)
     paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)
     paddingTop = parseInt(getComputedStyle(elem).paddingTop)
     paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)
    break
   case 'border-box':
     borderRight = parseInt(getComputedStyle(elem).borderRight)
     borderLeft = parseInt(getComputedStyle(elem).borderLeft)
     borderTop = parseInt(getComputedStyle(elem).borderTop)
     borderBottom = parseInt(getComputedStyle(elem).borderBottom)
    break
   default: break
  }

  let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)
  let verticalAdjustment  = (paddingTop + paddingBottom) - (borderTop + borderBottom)

  let newWidth = elem.clientWidth  + e.movementX - horizontalAdjustment + 'px'
  let newHeight = elem.clientHeight + e.movementY - verticalAdjustment   + 'px'

  let cursorType = getComputedStyle(elem).cursor
  switch (cursorType) {
   case 'all-scroll':
     elem.style.width = newWidth
     elem.style.height = newHeight
    break
   case 'col-resize':
     elem.style.width = newWidth
    break
   case 'row-resize':
     elem.style.height = newHeight
    break
   default: break
  }
 }

 _onResize(e) {
  // On resizing state!
  let elem = e.target
  let newCursorType = undefined
  let cursorType = getComputedStyle(elem).cursor
  switch (cursorType) {
   case 'nwse-resize':
    newCursorType = 'all-scroll'
    break
   case 'ew-resize':
    newCursorType = 'col-resize'
    break
   case 'ns-resize':
    newCursorType = 'row-resize'
    break
   default: break
  }

  html.style.cursor = newCursorType // Avoid cursor's flickering
  elem.style.cursor = newCursorType

  // Remove what is not necessary, and could have side effects!
  elem.removeEventListener('mousemove', this._checkBorderHandler, false);

  // Events on resizing state
  /**
   * We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position
   */
  window.addEventListener('mousemove', this._doResizeHandler, false);
  window.addEventListener('mouseup', this._initResizerHandler, false);
 }

 _checkBorder(e) {
  const elem = e.target
  const borderSensitivity = 5
  const coor = getCoordenatesCursor(e)
  const onRightBorder  = ((coor.x + borderSensitivity) > elem.scrollWidth)
  const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)
  const onBottomRightCorner = (onRightBorder && onBottomBorder)

  if (onBottomRightCorner) {
   elem.style.cursor = 'nwse-resize'
  } else if (onRightBorder) {
   elem.style.cursor = 'ew-resize'
  } else if (onBottomBorder) {
   elem.style.cursor = 'ns-resize'
  } else {
   elem.style.cursor = 'auto'
  }

  if (onRightBorder || onBottomBorder) {
   elem.addEventListener('mousedown', this._onResizeHandler, false)
  } else {
   elem.removeEventListener('mousedown', this._onResizeHandler, false)
  }
 }
}

function getCoordenatesCursor(e) {
 let elem = e.target;

 // Get the Viewport-relative coordinates of cursor.
 let viewportX = e.clientX
 let viewportY = e.clientY

 // Viewport-relative position of the target element.
 let elemRectangle = elem.getBoundingClientRect()

 // The  function returns the largest integer less than or equal to a given number.
 let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth
 let y = Math.floor(viewportY - elemRectangle.top) // - elem.scrollHeight

 return {x, y}
}

let resizerForCenter = new Resizer('center')
resizerForCenter.initResizer()

let resizerForLeft = new Resizer('left')
resizerForLeft.initResizer()

setTimeout(handler, 10000, true); // 10s

function handler() {
  resizerForCenter.stopResizer()
}
body {
 background-color: white;
}

#wrapper div {
 /* box-sizing: border-box; */
 position: relative;
 float:left;
 overflow: hidden;
 height: 50px;
 width: 50px;
 padding: 3px;
}

#left {
 background-color: blueviolet;
}
#center {
 background-color:lawngreen ;
}
#right {
 background: blueviolet;
}
#wrapper {
 border: 5px solid hotpink;
 display: inline-block;

}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Resizer v0.0.1</title>

Left

Center

Right

A: See my cross browser compatible resizer.

    <!doctype html>

        <title>resizer</title>
        <meta name="author" content="Andrej Hristoliubov anhr@mail.ru">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Resizer

Please see example of resizing of the HTML element by mouse dragging.

Drag the red rectangle if you want to change the width of the Element 1 and Element 2

Drag the green rectangle if you want to change the height of the Element 1 Element 2 and Element 3

Drag the small blue square at the left bottom of the Element 2, if you want to resize of the Element 1 Element 2 and Element 3

                    Element 2

Element 1

Element 3

Also see my example of resizer

A:

// import
function get_difference(pre, mou) {
  return {
    x: mou.x - pre.x,
    y: mou.y - pre.y
  };
}

/*
if your panel is in a nested environment, which the parent container's width and height does not equa to document width
and height, for example, in an element `canvas`, then edit it to

function oMousePos(e) {
  var rc = canvas.getBoundingClientRect();
  return {
    x: e.clientX - rc.left,
    y: e.clientY - rc.top,
  };
}
*/

function oMousePos(e) {
  return {
    x: e.clientX,
    y: e.clientY,
  };
}

function render_element(styles, el) {
  for (const [kk, vv] of Object.entries(styles)) {
    el.style[kk] = vv;
  }
}

class MoveablePanel {

  /*
  prevent an element from moving out of window
  */
  constructor(container, draggable, left, top) {
    this.container = container;
    this.draggable = draggable;
    this.left = left;
    this.top = top;
    let rect = container.getBoundingClientRect();
    this.width = rect.width;
    this.height = rect.height;
    this.status = false;

    // initial position of the panel, should not be changed
    this.original = {
      left: left,
      top: top
    };

    // current left and top postion
    // {this.left, this.top}

    // assign the panel to initial position
    // initalize in registration
    this.default();

    if (!MoveablePanel._instance) {
      MoveablePanel._instance = [];
    }
    MoveablePanel._instance.push(this);
  }

  mousedown(e) {
    this.status = true;
    this.previous = oMousePos(e)
  }

  mousemove(e) {
    if (!this.status) {
      return;
    }
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;
    let kleft, ktop;

    if (vleft < 0) {
      kleft = 0;
    } else if (vleft > window.innerWidth - this.width) {
      kleft = window.innerWidth - this.width;
    } else {
      kleft = vleft;
    }

    if (vtop < 0) {
      ktop = 0;
    } else if (vtop > window.innerHeight - this.height) {
      ktop = window.innerHeight - this.height;
    } else {
      ktop = vtop;
    }
    this.container.style.left = `${kleft}px`;
    this.container.style.top = `${ktop}px`;
  }

  /*
  sometimes user move the cursor too fast which mouseleave is previous than mouseup
  to prevent moving too fast and break the control, mouseleave is handled the same as mouseup
  */

  mouseupleave(e) {
    if (!this.status) {
      return null;
    }
    this.status = false;
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;

    if (vleft < 0) {
      this.left = 0;
    } else if (vleft > window.innerWidth - this.width) {
      this.left = window.innerWidth - this.width;
    } else {
      this.left = vleft;
    }

    if (vtop < 0) {
      this.top = 0;
    } else if (vtop > window.innerHeight - this.height) {
      this.top = window.innerHeight - this.height;
    } else {
      this.top = vtop;
    }

    this.show();
    return true;
  }

  default () {
    this.container.style.left = `${this.original.left}px`;
    this.container.style.top = `${this.original.top}px`;
  }

  /*
  panel with a higher z index will interupt drawing
  therefore if panel is not displaying, set it with a lower z index that canvas

  change index doesn't work, if panel is hiding, then we move it out
  hide: record current position, move panel out
  show: assign to recorded position

  notice this position has nothing to do panel drag movement
  they cannot share the same variable
  */

  hide() {
    // move to the right bottom conner
    this.container.style.left = `${window.screen.width}px`;
    this.container.style.top = `${window.screen.height}px`;
  }

  show() {
    this.container.style.left = `${this.left}px`;
    this.container.style.top = `${this.top}px`;
  }
}
// end of import

class DotButton{
    constructor(
        width_px,
        styles, // mainly pos, padding and margin, e.g. {top: 0, left: 0, margin: 0},
        color,
        color_hover,
        border, // boolean
        border_dismiss, // boolean: dismiss border when hover
    ){
        this.width = width_px;
        this.styles = styles;
        this.color = color;
        this.color_hover = color_hover;
        this.border = border;
        this.border_dismiss = border_dismiss;
    }

    create(_styles=null){
        var el = document.createElement('div');
        Object.keys(this.styles).forEach(kk=>{
            el.style[kk] = `${this.styles[kk]}px`;
        });
        if(_styles){
            Object.keys(_styles).forEach(kk=>{
                el.style[kk] = `${this.styles[kk]}px`;
            });
        }
        el.style.width = `${this.width}px`
        el.style.height = `${this.width}px`
        el.style.position = 'absolute';
        el.style.left = `${this.left_px}px`;
        el.style.top = `${this.top_px}px`;
        el.style.background = this.color;
        if(this.border){
            el.style.border = '1px solid';
        }
        el.style.borderRadius = `${this.width}px`;

        el.addEventListener('mouseenter', ()=>{
            el.style.background = this.color_hover;
            if(this.border_dismiss){
                el.style.border = `1px solid ${this.color_hover}`;
            }
        });
        el.addEventListener('mouseleave', ()=>{
            el.style.background = this.color;
            if(this.border_dismiss){
                el.style.border = '1px solid';
            }
        });
        return el;
    }
}

function cursor_hover(el, default_cursor, to_cursor){
    el.addEventListener('mouseenter', function(){
        this.style.cursor = to_cursor;
    }.bind(el));

    el.addEventListener('mouseleave', function(){
        this.style.cursor = default_cursor;
    }.bind(el));
}

class FlexPanel extends MoveablePanel{
    constructor(
        parent_el,
        top_px,
        left_px,
        width_px,
        height_px,
        background,
        handle_width_px,
        coner_vmin_ratio,
        button_width_px,
        button_margin_px,
    ){
        super(
            (()=>{
                var el = document.createElement('div');
                render_element(
                    {
                        position: 'fixed',
                        top: `${top_px}px`,
                        left: `${left_px}px`,
                        width: `${width_px}px`,
                        height: `${height_px}px`,
                        background: background,
                    },
                    el,
                );
                return el;
            })(), // iife returns a container (panel el)
            new DotButton(button_width_px, {top: 0, right: 0, margin: button_margin_px}, 'green', 'lightgreen', false, false).create(), // draggable
            left_px, // left
            top_px, // top
        );

        this.draggable.addEventListener('mousedown', e => {
            e.preventDefault();
            this.mousedown(e);
        });

        this.draggable.addEventListener('mousemove', e => {
            e.preventDefault();
            this.mousemove(e);
        });

        this.draggable.addEventListener('mouseup', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.draggable.addEventListener('mouseleave', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.parent_el = parent_el;
        this.background = background;

        // parent
        this.width = width_px;
        this.height = height_px;

        this.handle_width_px = handle_width_px;
        this.coner_vmin_ratio = coner_vmin_ratio;

        this.panel_el = document.createElement('div');

        // styles that won't change
        this.panel_el.style.position = 'absolute';
        this.panel_el.style.top = `${this.handle_width_px}px`;
        this.panel_el.style.left = `${this.handle_width_px}px`;
        this.panel_el.style.background = this.background;

        this.handles = [
            this.handle_top,
            this.handle_left,
            this.handle_bottom,
            this.handle_right,

            this.handle_lefttop,
            this.handle_topleft,
            this.handle_topright,
            this.handle_righttop,
            this.handle_rightbottom,
            this.handle_bottomright,
            this.handle_bottomleft,
            this.handle_leftbottom,
        ] = Array.from({length: 12}, i => document.createElement('div'));

        this.handles.forEach(el=>{
            el.style.position = 'absolute';
        });

        this.handle_topleft.style.top = '0';
        this.handle_topleft.style.left = `${this.handle_width_px}px`;

        this.handle_righttop.style.right = '0';
        this.handle_righttop.style.top = `${this.handle_width_px}px`;

        this.handle_bottomright.style.bottom = '0';
        this.handle_bottomright.style.right = `${this.handle_width_px}px`;

        this.handle_leftbottom.style.left = '0';
        this.handle_leftbottom.style.bottom = `${this.handle_width_px}px`;

        this.handle_lefttop.style.left = '0';
        this.handle_lefttop.style.top = '0';

        this.handle_topright.style.top = '0';
        this.handle_topright.style.right = '0';

        this.handle_rightbottom.style.right = '0';
        this.handle_rightbottom.style.bottom = '0';

        this.handle_bottomleft.style.bottom = '0';
        this.handle_bottomleft.style.left = '0';

        this.update_ratio();

        [
            'ns-resize', // |
            'ew-resize', // -
            'ns-resize', // |
            'ew-resize', // -

            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
        ].map((dd, ii)=>{
            cursor_hover(this.handles[ii], 'default', dd);
        });

        this.vtop = this.top;
        this.vleft = this.left;
        this.vwidth = this.width;
        this.vheight = this.height;

        this.update_ratio();

        this.handles.forEach(el=>{
            this.container.appendChild(el);
        });

        cursor_hover(this.draggable, 'default', 'move');

        this.panel_el.appendChild(this.draggable);
        this.container.appendChild(this.panel_el);
        this.parent_el.appendChild(this.container);

        [
            this.edgemousedown,
            this.verticalmousemove,
            this.horizontalmousemove,
            this.nwsemousemove,
            this.neswmousemove,
            this.edgemouseupleave,
        ] = [
            this.edgemousedown.bind(this),
            this.verticalmousemove.bind(this),
            this.horizontalmousemove.bind(this),
            this.nwsemousemove.bind(this),
            this.neswmousemove.bind(this),
            this.edgemouseupleave.bind(this),
        ];

        this.handle_top.addEventListener('mousedown', e=>{this.edgemousedown(e, 'top')});
        this.handle_left.addEventListener('mousedown', e=>{this.edgemousedown(e, 'left')});
        this.handle_bottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottom')});
        this.handle_right.addEventListener('mousedown', e=>{this.edgemousedown(e, 'right')});
        this.handle_lefttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'lefttop')});
        this.handle_topleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topleft')});
        this.handle_topright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topright')});
        this.handle_righttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'righttop')});
        this.handle_rightbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'rightbottom')});
        this.handle_bottomright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomright')});
        this.handle_bottomleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomleft')});
        this.handle_leftbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'leftbottom')});

        this.handle_top.addEventListener('mousemove', this.verticalmousemove);
        this.handle_left.addEventListener('mousemove', this.horizontalmousemove);
        this.handle_bottom.addEventListener('mousemove', this.verticalmousemove);
        this.handle_right.addEventListener('mousemove', this.horizontalmousemove);
        this.handle_lefttop.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topleft.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topright.addEventListener('mousemove', this.neswmousemove);
        this.handle_righttop.addEventListener('mousemove', this.neswmousemove);
        this.handle_rightbottom.addEventListener('mousemove', this.nwsemousemove);
        this.handle_bottomright.addEventListener('mousemove', this.nwsemousemove);
        this.handle_bottomleft.addEventListener('mousemove', this.neswmousemove);
        this.handle_leftbottom.addEventListener('mousemove', this.neswmousemove);

        this.handle_top.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_left.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()});
        this.handle_bottom.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_right.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()});
        this.handle_lefttop.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topleft.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topright.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_righttop.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_rightbottom.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_bottomright.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_bottomleft.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_leftbottom.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});

        this.handle_top.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_left.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_right.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_lefttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_righttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_rightbottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_leftbottom.addEventListener('mouseleave', this.edgemouseupleave);
    }

    // box size change triggers corner handler size change
    update_ratio(){
        this.container.style.top = `${this.vtop}px`;
        this.container.style.left = `${this.vleft}px`;
        this.container.style.width = `${this.vwidth}px`;
        this.container.style.height = `${this.vheight}px`;

        this.panel_el.style.width = `${this.vwidth - 2 * this.handle_width_px}px`;
        this.panel_el.style.height = `${this.vheight - 2 * this.handle_width_px}px`;

        this.ratio = this.vwidth < this.vheight ? this.coner_vmin_ratio * this.vwidth : this.coner_vmin_ratio * this.vheight;
        [
            this.handle_top,
            this.handle_bottom,
        ].forEach(el=>{
            el.style.width = `${this.vwidth - 2 * this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_left,
            this.handle_right,
        ].forEach(el=>{
            el.style.height = `${this.vheight - 2 * this.ratio}px`;
            el.style.width = `${this.handle_width_px}px`;
        });

        this.handle_top.style.top = `0`;
        this.handle_top.style.left = `${this.ratio}px`;

        this.handle_left.style.top = `${this.ratio}px`;
        this.handle_left.style.left = `0`;

        this.handle_bottom.style.bottom = `0`;
        this.handle_bottom.style.right = `${this.ratio}px`;

        this.handle_right.style.bottom = `${this.ratio}px`;
        this.handle_right.style.right = `0`;

        [
            this.handle_topright,
            this.handle_bottomleft,
        ].forEach(el=>{
            el.style.width = `${this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_lefttop,
            this.handle_rightbottom,
        ].forEach(el=>{
            el.style.width = `${this.handle_width_px}px`;
            el.style.height = `${this.ratio}px`;
        });

        [
            this.handle_topleft,
            this.handle_bottomright,
        ].forEach(el=>{
            el.style.width = `${this.ratio - this.handle_width_px}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_righttop,
            this.handle_leftbottom,
        ].forEach(el=>{
            el.style.height = `${this.handle_width_px}px`;
            el.style.width = `${this.ratio - this.handle_width_px}px`;
        });
    }

    edgemousedown(e, flag){
        this.previous = oMousePos(e);
        this.flag = flag;
        this.drag = true;
    }

    verticalmousemove(e){
        if(this.drag){
            // -
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            switch(this.flag){
                case 'top':
                    this.vtop = this.top + ydif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;

                case 'bottom':
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;
            }
            this.update_ratio();
        }
    }

    horizontalmousemove(e){
        if(this.drag){
            // |
            this.mouse = oMousePos(e);
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'left':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;

                    this.vtop = this.top;
                    this.vheight = this.height;
                break;

                case 'right':
                    this.vwidth = this.width + xdif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vheight = this.height;
                break;
            }
            this.update_ratio();
        }
    }

    nwsemousemove(e){
        if(this.drag){
            // \
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topleft':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'lefttop':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'bottomright':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;

                case 'rightbottom':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;
            }
            this.update_ratio();
        }
    }

    neswmousemove(e){
        if(this.drag){
            // /
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topright':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'righttop':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'bottomleft':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;

                case 'leftbottom':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;
            }
            this.update_ratio();
        }
    }

    edgemouseupleave(){
        this.drag = false;
        this.top = this.vtop;
        this.left = this.vleft;
        this.width = this.vwidth;
        this.height = this.vheight;
    }

    mouseupleave(e){
        if(super.mouseupleave(e)){
            this.vtop = this.top;
            this.vleft = this.left;
        }
    }
}

var fp = new FlexPanel(
    document.body, // parent div container
    20, // top margin
    20, // left margin
    200, // width
    150, // height
    'lightgrey', // background
    20, // handle height when horizontal; handle width when vertical
    0.2, // edge up and left resize bar width : top resize bar width = 1 : 5
    35, // green move button width and height
    2, // button margin
);

/*
this method creates an element for you
which you don't need to pass in a selected element

to manipuate dom element
fp.container -> entire panel
fp.panel_el -> inside panel
*/

Achieving functionalities fully requires a lot of hard coding. Please refer to the documentation, it will show you how to use each class as element.

A: const onMouseDownEvent=(ev: React.DragEvent)=>{
    let imgElem = (ev.target as HTMLImageElement);
    let childElem = (ev.currentTarget && ev.currentTarget.childNodes && ev.currentTarget.childNodes[0]);
    let original_height = parseFloat(getComputedStyle(imgElem, null).getPropertyValue('height').replace('px', ''));
    let original_width = parseFloat(getComputedStyle(imgElem, null).getPropertyValue('width').replace('px', ''));
    let original_Y =  imgElem.getBoundingClientRect().top;
    let original_X =  imgElem.getBoundingClientRect().right;

    ev.preventDefault();
    var original_mouse_y = ev.pageY;
    var original_mouse_x = ev.pageX;
    document.addEventListener('mousemove', resize);
    document.addEventListener('mouseup', stopResize);

    function resize(mouseMoveEvent) {
        const height = original_height + (mouseMoveEvent.pageY - original_mouse_y);
        const width = original_width + (mouseMoveEvent.pageX - original_mouse_x);

        imgElem.style.height = height + 'px';
        mouseMoveEvent.target.childNodes[0].innerHTML = imgElem.style.height;

        imgElem.style.width = width + 'px';
        mouseMoveEvent.target.childNodes[0].innerHTML = imgElem.style.width;
    }

    function stopResize() {
        document.removeEventListener('mousemove', resize)
    }
}

A: I really recommend using some sort of library, but you asked for it, you get it:
var p = document.querySelector('p'); // element to make resizable

p.addEventListener('click', function init() {
    p.removeEventListener('click', init, false);
    p.className = p.className + ' resizable';
    var resizer = document.createElement('div');
    resizer.className = 'resizer';
    p.appendChild(resizer);
    resizer.addEventListener('mousedown', initDrag, false);
}, false);

var startX, startY, startWidth, startHeight;

function initDrag(e) {
   startX = e.clientX;
   startY = e.clientY;
   startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
   startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
   document.documentElement.addEventListener('mousemove', doDrag, false);
   document.documentElement.addEventListener('mouseup', stopDrag, false);
}

function doDrag(e) {
   p.style.width = (startWidth + e.clientX - startX) + 'px';
   p.style.height = (startHeight + e.clientY - startY) + 'px';
}

function stopDrag(e) {
    document.documentElement.removeEventListener('mousemove', doDrag, false);
    document.documentElement.removeEventListener('mouseup', stopDrag, false);
}

Demo
Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).

A: what about a pure css3 solution?
div {
    resize: both;
    overflow: auto;
}

MDN Web Docs
W3Schools example
Browser support

A: I'm not sure if this is what you are looking for, but you can always use CSS resize property and add it to an element using javascript; For example lets say you have a div element with the id myDiv and you want to make it resizable:
document.getElementById("myDiv").style.resize = "both";

here's the related links:
Style resize Property
CSS resize Property

A:

var resizeHandle = document.getElementById('resizable');
var box = document.getElementById('resize');
resizeHandle.addEventListener('mousedown', initialiseResize, false);

function initialiseResize(e) {
  window.addEventListener('mousemove', startResizing, false);
  window.addEventListener('mouseup', stopResizing, false);
}

function stopResizing(e) {
  window.removeEventListener('mousemove', startResizing, false);
  window.removeEventListener('mouseup', stopResizing, false);
}

function startResizing(e) {
  box.style.width = (e.clientX) + 'px';
  box.style.height = (e.clientY) + 'px';
}

function startResizing(e) {
  box.style.width = (e.clientX - box.offsetLeft) + 'px';
  box.style.height = (e.clientY - box.offsetTop) + 'px';
}
#resize {
  position: relative;
  width: 130px;
  height: 130px;
  border: 2px solid blue;
  color: white;
}

#resizable {
  background-color: white;
  width: 10px;
  height: 10px;
  cursor: se-resize;
  position: absolute;
  right: 0;
  bottom: 0;
}


text:
Q: C Array Memory Error?(Beginner) When I try to print all the values in the array(which should be zero?), it starts printing 0's but at the end prints wonky numbers:
"(printing zeros)...0,0,0,0,0,0,0,1810432,0,1809600,0,1809600,0,0,0,5,0,3907584..."
When I extend the array, only at the end do the numbers start to mess up. Is this a memory limitation or something? Very confused, would greatly appreciate if anyone could help a newbie out.
Done in CS50IDE, not sure if that changes anything
int main()
{
  int counter [100000];
  for(int i = 0; i < 100000; i++)
  {
    printf("%i,", counter[i]);
  }
}

A: Your array isn't initialized. You simply declare it but never actually set it. In C (and C++, Objective-C) you need to manually set a starting value. Unlike Python, Java, JavaScript or C# this isn't done for you...

which should be zero?

The above assertion is incorrect.

A: The reason why this is happening is because you reserved 100000*4 = 400000 bytes of memory but didn't write anything to it (didn't initialize it).
So therefore, garbage is printed if you access a memory location which hasn't been written to yet. The reason why 0's aren't printed is because we want optimization and don't want the compiler wasting time in writing to 100000 integer addresses and also the best practices expect a developer to never access a memory place that he has never written to or allocated yet. If you try printing:
printf("%d\n", counter[100000]);

This would also print a garbage value, but you didn't allocate that did you? It's because C/C++ don't restrict or raise errors when you try to do such operation unlike Java.
Try it yourself
for (int i=0; i<100000; i++) {
    counter[i] = i;
    printf("%d\n", counter[i]);
}

Now only numbers from 1,2,3....99999 will be printed on the screen.

A: When you declare an array in C, it does not set the elements to zero by default. Instead, it will be filled with whatever data last occupied that location in memory, which could be anything.
The fact that the first portion of the array contained zeros is just a coincidence.
This beginning state of an array is referred to as an "uninitialized" array, as you have not provided any initial values for the array. Before you can use the array, it should be "initialized", meaning that you specify a default value for each position.

A: auto variables (variables declared within a block without the static keyword) are not initialized to any particular value when they are created; their value is indeterminate.  You can't rely on that value being 0 or anything else.
static variables (declared at file scope or with the static keyword) are initialized to 0 or NULL, depending on type.
You can initialize all of the elements of the array to 0 by doing
int counter [100000] = {{0}};

If there are fewer elements in the initializer than there are elements in the array, then the extra elements are initialized as though they were static - 0 or NULL.  So the first element is being explicitly initialized to 0, and the remaining 99999 elements are implicitly initialized to 0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I schedule jobs on different time in Gitlab I have build and test jobs in Gitlab CI yaml.
I want to trigger build job every evening at 16.00
and I want to trigger test jobs every morning 4.00 on GitLab
and I know on Gitlab CI/CD - Schedules - New Schedule
but I don't know how can I write this and works in Gitlab CI yaml
I have uploaded my Gitlab CI yaml file.
Can you show me please?
variables:
  MSBUILD_PATH: 'C:\Program Files (x86)\MSBuild\14.0\Bin\msbuild.exe'
  SOLUTION_PATH: 'Source/NewProject.sln'

stages:
  - build
  - test

build_job:
  stage: build
  script:
    - '& "$env:MSBUILD_PATH" "$env:SOLUTION_PATH" /nologo /t:Rebuild /p:Configuration=Debug'
    - pwd
  artifacts:
    paths:
     -  'Output'

test_job:
  stage: test
  only:
    - schedules
  script:
    - 'Output\bin\Debug\NewProject.exe'

A: Did you try only:variables/except:variables?
First you need to set proper variable in your schedule then add only variables to your yml config. Example:
...
build_job:
...
  only:
    variables:
      - $SCHEDULED_BUILD == "True"

test_job:
...
  only:
    variables:
      - $SCHEDULED_TEST == "True"

If you always want to have 12 hours of delay you could use just one schedule and add when:delayed
  when: delayed
  start_in: 12 hours

UPDATE: As per request in comments added complete example of simple pipeline configuration, job build should run when SCHEDULED_BUILD is set to True and test job should run when SCHEDULED_TEST is set to True:
build:
    script:
      - echo only build
    only:
      variables:
        - $SCHEDULED_BUILD == "True"

test:
    script:
      - echo only test
    only:
      variables:
        - $SCHEDULED_TEST == "True"


text:
Q: How to align title at center of ActionBar in default theme(Theme.Holo.Light) I searched a lot but can not find a way, How can I set then title at center of ActionBar instead of left aligned. I used below code to set the title at center :
ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView();
LinearLayout root= (LinearLayout) decorView.getChildAt(0);
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0);
TextView title= (TextView) titleContainer.getChildAt(0);
title.setGravity(Gravity.CENTER);

But it gives error as below :
ClassCastException : com.android.internal.widget.ActionBarView can not
be cast to android.widget.TextView.

Any other solution ..Any help will be appreciated.

A: It seems there is no way to do this without custom view. You can get the title view:
View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));

But changing of gravity or layout_gravity doesn't have an effect.
The problem in the ActionBarView, which layout its children by itself so changing of layout params of its children also doesn't have an effect.
To see this excecute following code:
ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);

A: Check out new Tool bar on support library class in  Lollipop update you can design actionbar by adding toolbar in your layout
add these items in your app theme
 <item name="android:windowNoTitle">true</item>
 <item name="windowActionBar">false</item>

Create your toolbar in a layout and include your textview in center design your toolbar
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/acbarcolor">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/app_name"
            android:textColor="#ffffff"
            android:textStyle="bold" />

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

add your action bar as tool bar
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

please ensure that you need to include toolbar on your resource file like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <include
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/toolbar" />

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Framelayout to display Fragments -->
        <FrameLayout
            android:id="@+id/frame_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <include
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                layout="@layout/homepageinc" />

        </FrameLayout>

        <fragment
            android:id="@+id/fragment1"
            android:layout_gravity="start"
            android:name="com.shouldeye.homepages.HomeFragment"
            android:layout_width="250dp"
            android:layout_height="match_parent" />

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

A: I know my answer is not on time but this is purely code no xml required.
This is for use in  Activity
public void setTitle(String title){
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
}

This is for use in Fragment
public void setTitle(String title){
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(getActivity());
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}

A: if You are Using Toolbar the just Add
android:layout_gravity="center_horizontal"
Under the Toolbar Just like this snippet
 <android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"    //Important
            android:textColor="@color/whitecolor"
            android:textSize="20sp"
            android:textStyle="bold" />
    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

A: This actually works:
 getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
 getActionBar().setCustomView(R.layout.custom_actionbar);
  ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.gravity = Gravity.CENTER;

You have to define custom_actionbar.xml layout which is as per your requirement e.g. :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#2e2e2e"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/top_banner"
        android:layout_gravity="center"
        />
</LinearLayout>

A: You can create a custom layout and apply it to the actionBar.
To do so, follow those 2 simple steps:

*

*Java Code
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar);

Where R.layout.actionbar is the following layout.

*XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/action_bar_title"
    android:text="YOUR ACTIVITY TITLE"
    android:textColor="#ffffff"
    android:textSize="24sp" />
</LinearLayout>

It can be as complex as you want. Try it out!
EDIT:
To set the background you can use the property android:background in the container layout (LinearLayout in that case). You may need to set the layout height android:layout_height to match_parent instead of wrap_content.
Moreover, you can also add a LOGO / ICON to it. To do so, simply add an ImageView inside your layout, and set layout orientation property android:orientation to horizontal (or simply use a RelativeLayout and manage it by yourself).
To change the title of above custom action bar dynamically, do this:
TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");

A: I think by positioning views on action bar you will reach what you want.On action bar's layout when layout params set to match parent it does not match full width
that's why I did it programmatically where I succeed.By setting width (it works like layout_weight="value") we can set our view wherever we want:
    actionBar = getSupportActionBar();
    actionBar.setDisplayShowCustomEnabled(true);

    LayoutInflater ll = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout linearLayout = (LinearLayout) ll.inflate(R.layout.custom_actionbar, null);
    //inner layout within above linear layout
    LinearLayout inner = (LinearLayout) linearLayout.findViewById(R.id.inner_linear_ractionbar);
    inner.setMinimumWidth(getWidth() * 2 / 10);
    // we will set our textview to center and display there some text
    TextView t = (TextView) linearLayout.findViewById(R.id.center_text);
    t.setWidth(getWidth() * 6 / 10);

    Button b = (Button) linearLayout.findViewById(R.id.edit_button);
    b.setWidth(getWidth() *3/ 20);

    ImageButton imageButton = (ImageButton) linearLayout.findViewById(R.id.action_bar_delete_item);
    imageButton.setMinimumWidth(deviceUtils.getWidth() / 20);

and here is getWidth() method:
 public int getWidth() {
    DisplayMetrics dm = new DisplayMetrics();
     mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    return dm.widthPixels;
   }

A: Java code:
write this in onCreate()
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.action_bar);
and for you custom view, simply use FrameLayout, east peasy!
android.support.v7.widget.Toolbar is another option
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|center_vertical"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/app_name"
        android:textColor="@color/black"
        android:id="@+id/textView" />
</FrameLayout>

A: I had the same problem, and because of the "Home" button added automatically in the toolbar, my text was not exactly entered.
I fixed it the dirty way but it works well in my case. I simply added a margin to the right of my TextView to compensate for the home button on the left. Here's my toolbar layout :
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:elevation="1dp"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_collapseMode="pin"
    android:gravity="center"
    android:background="@color/mainBackgroundColor"
    android:fitsSystemWindows="true" >

    <com.lunabee.common.utils.LunabeeShadowTextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="?attr/actionBarSize"
        android:gravity="center"
        style="@style/navigation.toolbar.title" />

</android.support.v7.widget.Toolbar>

A: You can force the toolbar by wrapping title and level right padding which has default left padding for title. Than put background color to the parent of toolbar and that way part which is cut out by wrapping title is in the same color(white in my example):
<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

        <android.support.v7.widget.Toolbar
           android:id="@+id/toolbar"
           android:layout_width="wrap_content"
           android:layout_height="56dp"
           android:layout_gravity="center_horizontal"
           android:paddingEnd="15dp"
           android:paddingRight="15dp"
           android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
           app:titleTextColor="@color/black"/>

</android.support.design.widget.AppBarLayout>

A: solution is based on these things:

*

*you need to use your own class that extends Toolbar (support.v7.widget.toolbar)

*you need to override one method Toolbar#addView

what does it do:
when first time toolbar is executing #setTitle, it creates AppCompatTextView and uses it to display title text.
when the AppCompatTextView is created, toolbar (as ViewGroup), adds it into it's own hierarchy with #addView method.
also, while trying to find solution i noticed that the textview has layout width set to "wrap_content", so i decided to make it "match_parent" and assign textalignment to "center".
MyToolbar.kt, skipping unrelated stuff (constructors/imports):
class MyToolbar : Toolbar {

  override fun addView(child: View, params: ViewGroup.LayoutParams) {
    if (child is TextView) {
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        child.textAlignment= View.TEXT_ALIGNMENT_CENTER
    }
    super.addView(child, params)
  }
}

possible "side effects" - this will apply to "subtitle" too

A: After two days of going through the web, this is what I came up with in Kotlin. Tested and works on my app
  private fun setupActionBar() {
    supportActionBar?.apply {
        displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
        displayOptions = ActionBar.DISPLAY_SHOW_TITLE
        setDisplayShowCustomEnabled(true)
        title = ""

        val titleTextView = AppCompatTextView(this@MainActivity)
        titleTextView.text = getText(R.string.app_name)
        titleTextView.setSingleLine()
        titleTextView.textSize = 24f
        titleTextView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.appWhite))

        val layoutParams = ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT
        )
        layoutParams.gravity = Gravity.CENTER
        setCustomView(titleTextView, layoutParams)

        setBackgroundDrawable(
            ColorDrawable(
                ContextCompat.getColor(
                    this@MainActivity,
                    R.color.appDarkBlue
                )
            )
        )

    }
}


text:
Q: Google Cloud Storage mount on windows I use Google Cloud Storage successfully in Linux for backups. I first mount the storage and then easily copy the files.
Now I want to do the same in windows, but I can't find a way to mount Google Cloud Storage as device.

A: You can use Rclone. Rclone is an open-source command-line program to manage files on cloud storage. It use WinFsp to mount remote drive to Windows.

*

*Install Rclone and WinFsp. Remember to add Rclone location to your PATH.

*Follow the steps here to set up your remote GCP bucket. If your GCP bucket use Uniform bucket-level access, remember to set the --gcs-bucket-policy-only option to true when configuring Rclone remote drive.

*Mount the remote GCP bucket as a local disk
rclone mount remote:path/to/files X:

where X: is an unused drive letter. You can find more details here.

A: There are many 3rd party tools (i.e. [1][2]) that will allow you to mount a bucket and see it as a drive in Windows.  Nevertheless,  FUSE is only available for Linux.  As per the previous comment, if you are only using GCS to store your backups, you can upload them from the disk using gsutil or Cloud Tools for PowerShell.

A: A workaround for that would be to mount it using FUSE into a Linux instance and share it via network Samba/NFS. This would allow you to mount it as a unit in your Windows Machine, even share the bucket with different instances in the network. With this way you could restrict the accesses from Samba, adding an extra layer. Perhaps it's not optimal but it offers more possibilities.


text:
Q: Having LaTeX equation in LyX numbered equation I have a LaTeX Equation that I am trying to insert in my LyX document as in the attached image
So, I Click Ctrl+L to insert TeX code inside that numbered equation but it doesn't work.
It only works when I Enter the LaTeX equation in the TeX Code (Ctrl+L) but outside the numbered equation (that is shown in the image).
Is there a way I can work around it to have TeX Code inside a numbered equation?

A: You can copy and paste the LaTeX equation directly into the box for a numbered equation without using Ctrl+L. I often write the equation in an online GUI or MathType, then copy the equation directly into Lyx's numbered equation.


text:
Q: How do I get commits from a merged and reverted PR into a new one? To make a long story short, I am in the following situation:
A feature branch was created, worked on for a while collecting some 30 commits, and merged into master. The merge was then reverted through GitHub's web interface (by creating a new PR that reverted the effects of the old one).
Now, I have fixed the problems that caused us to revert the merge, and I'd like to create a new PR with both all of the 30 or so commits from the original PR and a couple of more for my fix.
I've based my feature-fix branch on the (unmerged) head of the feature branch, committed a couple of times more and then pushed to create a PR - but for some reason, the PR only picks up the new commits, not the old ones.
How do I include the old commits in my new PR?
I have push access to the repo (we're using the shared repo model) so almost any operations that don't require a force-push to master are OK.
Simplified git history:
* [feature-fix]  <-- This is the branch I want to pull from now
| * [master]
| * [merge revert PR]
* |\
| | * [revert PR]
* |/              <-- This is the first commit included in the new PR by github
| * [merge PR]
|/|
* | [feature]  <-- This is where the original PR came from
| |
* |   <-- I want these commits, originally included in the old PR, to be included
* |       in my new PR too.
| |
* | <-- Started work on feature here. This is the first commit I want to include.
 \|
  * <-- Common ancestor between `feature-fix` and `master`, as far as I can see

A: If I am understanding you correctly you need to do the following.
git checkout master
git revert SHA_OF_MERGE_REVERT_PR
git merge feature-fix

The key step is reverting the commit that reverted your merge.  That SHA removed all your changes, but preserved all your merge history which is why you are only seeing the new commits.
You can read more about it from Linus himself here


text:
Q: MyOpenID is no longer supported - alternatives most likely to be immune to this type of change? Following myOpenID shuts down February 1, 2014; add an alternative login method to your account, I would like to follow the suggestions and add a new means of logging in, as suggested by the OP of that questions.
However, I am not sure which provider I should pick.

*

*Which one is least likely to "pull the plug" so to speak, as Janrain has done with MyOpenID?

*Are there other things I should consider when choosing a new provider?

Thanks!

I do understand that this question would attract quite a few primarily opinion based answers, and so I would like to ask that you refrain from simply stating "I recommend provider X". Please give objective reason(s) to back your recommendation!

A: The obvious choice:

Guaranteed to exist and be supported by Stack Exchange for as long as Stack Exchange exists.

A: OpenID providers
http://openid.net/get-an-openid/
OpenID providers not listed there include:

*

*Stack Exchange
Immunity to change
I can't predict such things.
As observed by Yannis and @Arjan:

*

*a Stack Exchange account should be supported by Stack Exchange for as long as the service exists.

However:

*

*I can't predict whether Stack Exchange will continue to be an OpenID provider throughout that duration.

A: If you have your own domain and homepage, the best you can do is using that as your OpenID account.
Fortunately you don't need to set up a whole OpenID server there, as OpenID supports delegation. Just register to an OpenID provider which supports delegated accounts (MyOpenID was like this, but fortunately Stack Exchange is also okay), and add the following few lines to the <head> of your homepage (this example is for SE based delgation):
<link rel="openid2.provider" href="https://openid.stackexchange.com/openid/provider">
<link rel="openid2.local_id" href="https://openid.stackexchange.com/user/YOURLOCALID">

Now, until you own your own domain (which you should) you will always have access to your OpenID account. If SE closes it's OpenID provider (or decides to not maintain it anymore) you can simply switch to another one by changing the URLs above. And if all of sudden ALL OpenID providers that support delegation go out of service then you still have the option to set up your own OpenID server.
For example my OpenID is http://sztupy.hu. If you check the source of my homepage's index that it contains this (EDIT: not anymore, it now contains the SE delegation, but this was the old one):
<link rel="openid.server" href="http://www.myopenid.com/server" />
<link rel="openid.delegate" href="http://sztupy2k.myopenid.com/" />
<link rel="openid2.provider" href="http://www.myopenid.com/server" />
<link rel="openid2.local_id" href="http://sztupy2k.myopenid.com/" />

But now, that MyOpenID is apparently not maintained anymore, I'll probably just switch to SE, update the links, and continue using my old OpenID URL.
Here is how you can set up Stack Exchange's OpenID provider for delegation:
https://blog.stackoverflow.com/2009/01/using-your-own-url-as-your-openid/
Advantages:

*

*Complete control of your own OpenID

Drawbacks:

*

*You need to have a homepage, which you control (you don't actually need a domain for this, but it's much nicer that way)

*If someone hacks/defaces your page, he can replace the delegation parts, so you're also in charge of the security of your OpenID not just the service you registered on


text:
Q: Solution to probability problems could you please help me?
I know the correct solutions which are different from mine, and I absolutely agree that they are correct. However, I cannot find out what's wrong with my solutions that typed below.
1)

Five balls are randomly chosen, without replacement, from an urn that
  contains 5 red, 6 white, and 7 blue balls. Find the probability that
  at least one ball of each color is chosen.

Sample space consists of $\binom{18}5$ outcomes. To meet the requirement I need to choose red ball by $\binom51$ ways, white - $\binom61$ and blue - $\binom71$. At the moment we have 3 out of 5 balls. The final balls could be drawn by $\binom{18-3}2$. Thus, the answer is
$$\binom51 \binom61 \binom71 \binom{15}2 / \binom{18}5$$
The most terrible thing about the above solution is that the probability exceeds 1.
2)

Balls are randomly removed from an urn initially containing 20 red and
  10 blue balls. What is the probability that all of the red balls are
  removed before all of the blue ones have been removed?

Imagine 30-element vector that could be filled with either letter "r" or "b". Hence, sample space consists of $2^{30}$ outcomes.
Obviously, the last element in this vector must be "b". That leaves 29 positions to be occupied, i.e. $2^{29}$ outcomes.
The probability is $2^{29}/2^{30} = \frac12$

Could you help me to find flaw(s) in my reasoning?

A: For 1: I think it fails because you're using different partitions for your balls. First, you say you're partitioning your balls into the red (size: 5), white (size: 6) and blue (size: 7) balls, and using binomial coefficients to count the different possibilities for each set. But then you're partitioning the balls into the ones you've already chosen (size: 3) and the ones you haven't (size: 15). I think choosing different partitions is problematic in itself with these type of counting and multiplication calculations, and partitioning based on "having already chosen" balls also leads to problems.
For 2: note that not all 30-element vectors are valid outcomes. For example, if the first 20 elements are "r", then there is only one choice for the remaining 10 elements.


text:
Q: AWS ALB Routing I configured an internet facing ALB in AWS with two listeners (80 and 443) and the target groups are in private network (10.0.1.0/24).  When http/https request are sent by ALB to the target group in 10.0.1.0 network, how the request is sent back to ALB?  ALB has a public IP, and the target group do not have a route to internet.  I can configure a NAT gateway and setup a route 0.0.0.0/0 to use the NAT gateway.  But the web response will go all the way to internet and then comeback to ALB.  Highly undesirable.  I can't put these instances in public facing subnet either.
Can some one help how this can be done?  I  thought of VPC endpoint, and configured one with the load balancer (I used ELB, as I couldn't find ALB endpoint service).  Now, the endpoint shows it has an IP in the 10.0.1.0 subnet.  However, I don't know how this will work.  Can someone suggest what's to be done.  Thanks.

A: Not sure exactly what your question here is. But giving you a simple explanation of how AWS ELB works.
In both AWS Classic Load Balancers and Application Load Balancers, two connections are involved:

*

*A connection between client (browser, etc) and ELB

*A connection between ELB and backend target instances (webservers)

When creating an Internet facing ELB, you are given the option of selecting two subnets. These subnets should be public subnets which have a route to an Internet Gateway. The ELB will launch at least one ELB node in each of these subnets. Clients on the Internet will be able to connect to these ELB nodes using their public IPs through the IGW.
Once the ELB receives the request from the client, it forwards the request to its backend targets. This communication uses the PRIVATE IPs of the ELB nodes and the target instances. Therefore, even if the instances are in the private subnet, the ELB will still be able to forward requests to them because the connection is over private IPs which uses the 'local' route in the route tables. The response from the target then goes to the ELB over private IP, and is then forwarded to the client over public IP.
Client <--public IP--> ELB <--private IP--> Targets

The connection between client and ELB is over public IP, the connection between ELB and webservers is over private IPs which does not need a route to an IGW or NAT.
Don't worry about NAT Gateways for your private subnets. Just make sure the subnets you choose when creating the ELB are public and have a route to an internet gateway.


text:
Q: Error using makefile to convert to topojson: [SyntaxError: Unexpected token ILLEGAL] I am following this Mike Bostock tutorial for making a bubble map but using a different shapefile and a different dataset.  This is for a class project.  Full disclosure - I am not a programmer and have been just sort of figuring this out as I go along, but I'm totally stuck here, so hopefully someone can help me out.
I created a Makefile to download the shapefile and unzip it in a directory.  That took some figuring out, but not I'm at the point where I want to convert the shapefile to a topojson file.  I am using this command:
make build/neighborhoods.json

And I'm getting back this error:
[SyntaxError: Unexpected token ILLEGAL]
make: *** [build/neighborhoods.json] Error 1

This is after a long list of topojson options.
This seems pretty obvious - I'm making some sort of syntax error.  But I have no idea what it is.
This is my makefile:
build/Census_Data.zip:
    mkdir -p $(dir $@)
    curl -o $@ http://apps.pittsburghpa.gov/dcp/$(notdir $@)

build/Census_Data: build/Census_Data.zip
    unzip -od $(dir $@) $<
    touch $@

build/Neighborhood.shp: build/Neighborhood.zip
    unzip -od $(dir $@) $<
    touch $@

build/neighborhoods.json: build/Neighborhood.shp
    node_modules/.bin/topojson \
        -o $@ \
        --projection='width = 960, height = 600, d3.geo.albersUsa() \
            #.scale(1280) \
            #.translate([width / 2, height / 2])' \
        --simplify=.5 \
        --filter=none \
        --neighborhoods=$<

The build directory and the makefile are in the same parent directory.  The shapefile is in the build directory.
If anyone can help me out it would be much appreciated.  Alternately, if anyone can suggest another way of doing this that would be great.  I am also planning to merge the json file with a .csv data file later as Bostock does in the tutorial.  Thanks!

A: I don't know if this is THE answer, but downloading Xcode (I'm usng a mac) solved this.  I recommend downloading it from the apple developer site because it kept stalling out when I tried to download it from the App Store and I read a lot of reports of the same thing happening to others.  Thanks!


text:
Q: How do you receive a file stream in javascript and POST it using AJAX? I'm receiving a file using a FORM POST in ASP.NET and sending it back like this:
StreamReader sr = new StreamReader(fStream);
Response.Write(sr.ReadToEnd());

What I want to do at this point is take the data and then repost it using AJAX. The problem is I am trying to understand how the data should be encoded or added to the data attribute of a jQuery AJAX POST.
Is this even possible? Can I receive a file stream server-side, send it back as a stream (or something else), store it in a JS variable and then send it as the 'data' in a jQuery AJAX POST?

A: Yes it is possible to upload a file using jquery AJAX.
Uploadify
This link can be useful for you. It is exactly same example what you want. See the code and let me know if you have any query. I have successfully implemented it in my code.
Advantages :

*

*It is also helpful for you if your file size is too large.

*It is easy to implement.

*AJAX.


text:
Q: Redirecting standard input of console application I have a console application which I'm trying to automate by redirecting Standard input stream of the process. In manual mode after opening the application, it waits for user input like below,
I created the process with redirected Standard input stream.The code snippet is as follows,
Process newProcess = new Process();
newProcess.StartInfo.FileName = exeName;
newProcess.StartInfo.Arguments = argsLine;
newProcess.StartInfo.UseShellExecute = false;
newProcess.StartInfo.RedirectStandardOutput = false ;
newProcess.StartInfo.CreateNoWindow = false;
newProcess.StartInfo.RedirectStandardInput = true;
newProcess.Start();

But creating process like this gives an infinite loop shown below,

It's like I'm sending Enter key command continuously to the process input stream. Can anyone point me to what I'm doing wrong here?
Similarly, standard output stream redirection is also not working after making

newProcess.StartInfo.RedirectStandardOutput = true

But I can manage with that.
Does redirection of standard streams work with all console applications or is there any exception?

A: Following the previous answer, I'll just add the extension method of SubArray, just in case add this class to your code where it's not nested inside any class ( the code didn't look readable in a comment, so I added it here )
public static class CharArrayExtensions
{
    public static char[] SubArray(this char[] input,int startIndex, int length)
    {
        List<char> result= new List<char>();
        for (int i = startIndex; i < length; i++)
        {
            result.Add(input[i]);
        }

        return result.ToArray();
    }
}

A: Here is a class I have written in order to handle that kind of stuff. Feel free to use it. Its purpose is to start a console application and "talk" to it. It has the ability to receive output as well. Good luck.
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

public class ConsoleAppManager
{
    private readonly string appName;
    private readonly Process process = new Process();
    private readonly object theLock = new object();
    private SynchronizationContext context;
    private string pendingWriteData;

    public ConsoleAppManager(string appName)
    {
        this.appName = appName;

        this.process.StartInfo.FileName = this.appName;
        this.process.StartInfo.RedirectStandardError = true;
        this.process.StartInfo.StandardErrorEncoding = Encoding.UTF8;

        this.process.StartInfo.RedirectStandardInput = true;
        this.process.StartInfo.RedirectStandardOutput = true;
        this.process.EnableRaisingEvents = true;
        this.process.StartInfo.CreateNoWindow = true;

        this.process.StartInfo.UseShellExecute = false;

        this.process.StartInfo.StandardOutputEncoding = Encoding.UTF8;

        this.process.Exited += this.ProcessOnExited;
    }

    public event EventHandler<string> ErrorTextReceived;
    public event EventHandler ProcessExited;
    public event EventHandler<string> StandartTextReceived;

    public int ExitCode
    {
        get { return this.process.ExitCode; }
    }

    public bool Running
    {
        get; private set;
    }

    public void ExecuteAsync(params string[] args)
    {
        if (this.Running)
        {
            throw new InvalidOperationException(
                "Process is still Running. Please wait for the process to complete.");
        }

        string arguments = string.Join(" ", args);

        this.process.StartInfo.Arguments = arguments;

        this.context = SynchronizationContext.Current;

        this.process.Start();
        this.Running = true;

        new Task(this.ReadOutputAsync).Start();
        new Task(this.WriteInputTask).Start();
        new Task(this.ReadOutputErrorAsync).Start();
    }

    public void Write(string data)
    {
        if (data == null)
        {
            return;
        }

        lock (this.theLock)
        {
            this.pendingWriteData = data;
        }
    }

    public void WriteLine(string data)
    {
        this.Write(data + Environment.NewLine);
    }

    protected virtual void OnErrorTextReceived(string e)
    {
        EventHandler<string> handler = this.ErrorTextReceived;

        if (handler != null)
        {
            if (this.context != null)
            {
                this.context.Post(delegate { handler(this, e); }, null);
            }
            else
            {
                handler(this, e);
            }
        }
    }

    protected virtual void OnProcessExited()
    {
        EventHandler handler = this.ProcessExited;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    protected virtual void OnStandartTextReceived(string e)
    {
        EventHandler<string> handler = this.StandartTextReceived;

        if (handler != null)
        {
            if (this.context != null)
            {
                this.context.Post(delegate { handler(this, e); }, null);
            }
            else
            {
                handler(this, e);
            }
        }
    }

    private void ProcessOnExited(object sender, EventArgs eventArgs)
    {
        this.OnProcessExited();
    }

    private async void ReadOutputAsync()
    {
        var standart = new StringBuilder();
        var buff = new char[1024];
        int length;

        while (this.process.HasExited == false)
        {
            standart.Clear();

            length = await this.process.StandardOutput.ReadAsync(buff, 0, buff.Length);
            standart.Append(buff.SubArray(0, length));
            this.OnStandartTextReceived(standart.ToString());
            Thread.Sleep(1);
        }

        this.Running = false;
    }

    private async void ReadOutputErrorAsync()
    {
        var sb = new StringBuilder();

        do
        {
            sb.Clear();
            var buff = new char[1024];
            int length = await this.process.StandardError.ReadAsync(buff, 0, buff.Length);
            sb.Append(buff.SubArray(0, length));
            this.OnErrorTextReceived(sb.ToString());
            Thread.Sleep(1);
        }
        while (this.process.HasExited == false);
    }

    private async void WriteInputTask()
    {
        while (this.process.HasExited == false)
        {
            Thread.Sleep(1);

            if (this.pendingWriteData != null)
            {
                await this.process.StandardInput.WriteLineAsync(this.pendingWriteData);
                await this.process.StandardInput.FlushAsync();

                lock (this.theLock)
                {
                    this.pendingWriteData = null;
                }
            }
        }
    }
}

A: Thank you for the ConsoleAppManager, it works well but I have to mention that the same effect for capturing output and error messages could be achieved using events found in the Process class:OutputDataReceived and ErrorDataReceived and call BeginOutputReadLine() and BeginErrorReadLine() after starting the process.
Also that WriteInputTask() is killing the CPU, might want to use some sort of ResetEvent between the while loop and setting of pendingWriteData or send the input directly to the process.


text:
Q: MemoryError on Windows but not MacOS when using np.zeros I want to build a numpy array but I get MemoryError in windows that has 16 GB RAM. To give more information the details are as follows:
Python 2.7.13 |Anaconda custom (64-bit)| (default, May 11 2017, 13:17:26) [MSCv.1500 64 bit (AMD64)] on win32

xx = np.zeros((110000,80000,3))

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError

However exactly the same code runs on mac computer with 8 GB RAM. The details are:
Python 2.7.12 |Anaconda 4.2.0 (x86_64) [GCC 4.2.1 (LLVM build ... )on darwin)]

xx = np.zeros((1100000,8000000,3)) doesn't give error.

And when I increase the size at last I get error on Mac however the error is different as follows:
xx = np.zeros((1100000,80000000,3))
python(713,0x7fffa76b33c0) malloc: *** mach_vm_map(size=211200000000000)
failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError

How could I deal with this problem?

A: Your array is too huge to fit in the physical RAM on both systems:
110000 * 80000 * 3 * 8 / 1024 / 1024 / 1024 = 196.[69] GB

However it depends on your system how it deals with the memory-request and how it "stores" the memory. For example the system could simply "reserve" memory for your process but postpones the actual allocation until the memory is read/modified. And even if the memory is allocated the memory can be compressed (as noted in the comments, thanks @Martijn Pieters) and having lots of zeros can be compressed really well - however as soon as you modify the memory the compression will become less efficient and more "real memory" is used.
That means it's up to the system when it fails (both will eventually fail if you actually do something with the array). Windows in your case chooses to fail immediately when you request more physical memory than you have. On Mac it seems like you have to modify "enough" values (see also this answer on "Why a 352GB NumPy ndarray can be used on a 8GB memory macOS computer?") until it fails.
import numpy as np
arr = np.zeros((110000,80000,3))  # MemoryError on Windows
arr += 10                         # MemoryError on Mac

You could use for example psutil to check the amount of memory used (physical and virtual):
import psutil
print(psutil.virtual_memory())
# svmem(total=4170924032, available=1666629632, percent=60.0, used=2504294400, free=1666629632)
arr = np.zeros((10000, 10000))
print(psutil.virtual_memory())
# svmem(total=4170924032, available=1664675840, percent=60.1, used=2506248192, free=1664675840)
arr += 10
print(psutil.virtual_memory())
# svmem(total=4170924032, available=864059392, percent=79.3, used=3306864640, free=864059392)

So even on Windows the np.zeros doesn't immediately "use" the physical memory until it is needed.

How could I deal with this problem ?

The easiest (but probably most costly) option would be to buy (a lot) more RAM. But you could also try to "chunk" the processing with chunk sizes that fit into your physical memory. Ultimately the best solution would be to rethink your approach/algorithm so you don't need that much memory.

A: As already stated, your array is way too large to fit into physical memory on both machines.
But the point is that physical memory is only part of the memory that is typically available on moder systems, the other one being virtual memory.
I am not sure whether Windows version of NumPy is actually compiled to only use physical memory, this could be, but I find it unlikely.
So, probably, the reason why you your Mac can handle that array is that it is configured to have a much larger virtual memory (read swap) than the virtual memory (read PageFile) available on Windows machine.
Therefore, increasing the PageFile size on your Windows machine is likely to fix your issue.
However, this is far from ideal as the virtual memory is typically orders of magnitude slower than the physical memory.
Your best bet is to use an algorithm that can work on chunks, or, if that is not possible, you should use memmap arrays, which, to the least may allow to work in-place on disk, thus avoiding copy huge amounts of data back and forth.