Q:

Drawing scalloped polygon between multiple points

I am trying to draw a scalloped path using SVG between multiple points like it is drawn for rectangle here but between multiple points. Expecting two or more two or more selected points to be connected by scalloped line.
But the problems I am facing are,

Scallops are not symmetric or random in sizes. - I solved this
After clicking multiple points scallops directions and up down. Like in below image.

I am completely ok even if the answer is given in html5 canvas context. I will make adjustments. I am missing some extra calculation but could not figure out what.
Please click multiple times in result page to see the scallops drawn currently

var strokeWidth = 3;

function distance(x1, y1, x2, y2) {
  return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

function findNewPoint(x, y, angle, distance) {
  var result = {};
  result.x = Math.round(Math.cos(angle) * distance + x);
  result.y = Math.round(Math.sin(angle) * distance + y);
  return result;
}

function getAngle(x1, y1, x2, y2) {
  return Math.atan2(y2 - y1, x2 - x1);
}

function scapolledLine(points, strokeWidth) {
  var that = this;
  var scallopSize = strokeWidth * 8;
  var path = [],
    newP = null;
  path.push("M", points[0].x, points[0].y);
  points.forEach(function(s, i) {
    var stepW = scallopSize,
      lsw = 0;
    var e = points[i + 1];
    if (!e) {
      path.push('A', stepW / 2, stepW / 2, "0 0 1", s.x, s.y);
      return;
    }
    var args = [s.x, s.y, e.x, e.y];
    var dist = that.distance.apply(that, args);
    if (dist === 0) return;
    var angle = that.getAngle.apply(that, args);
    newP = s;
    // Number of possible scallops between current points
    var n = dist / stepW,
      crumb;

    if (dist < (stepW * 2)) {
      stepW = (dist - stepW) > (stepW * 0.38) ? (dist / 2) : dist;
    } else {
      n = (n - (n % 1));
      crumb = dist - (n * stepW);
      /*if((stepW - crumb) > (stepW * 0.7)) {
          lsw = crumb;
      } else {
          stepW += (crumb / n);
      }*/
      stepW += (crumb / n);
    }

    // Recalculate possible scallops.
    n = dist / stepW;
    var aw = stepW / 2;
    for (var i = 0; i < n; i++) {
      newP = that.findNewPoint(newP.x, newP.y, angle, stepW);
      if (i === (n - 1)) {
        aw = (lsw > 0 ? lsw : stepW) / 2;
      }
      path.push('A', aw, aw, "0 0 1", newP.x, newP.y);
    }
    // scallopSize = stepW;
  });
  return path.join(' ');
  // return path.join(' ') + (points.length > 3 ? 'z' : '');
}

var points = [];
var mouse = null;
var dblclick = null,
  doneEnding = false;

window.test.setAttribute('stroke-width', strokeWidth);

function feed() {
  if (dblclick && doneEnding) return;
  if (!dblclick && (points.length > 0 && mouse)) {
    var arr = points.slice(0);
    arr.push(mouse);
    var str = scapolledLine(arr, strokeWidth);
    window.test.setAttribute('d', str);
  } else if (dblclick) {
    points.push(points[0]);
    doneEnding = true;
    var str = scapolledLine(points, strokeWidth);
    window.test.setAttribute('d', str);
  }
}

document.addEventListener('mousedown', function(event) {
  points.push({
    x: event.clientX,
    y: event.clientY
  });
  feed();
});

document.addEventListener('dblclick', function(event) {
  dblclick = true;
  feed();
});

document.addEventListener('mousemove', function(event) {
  if (points.length > 0) {
    mouse = {
      x: event.clientX,
      y: event.clientY
    }
    feed();
  }
});
body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0
}
svg {
  height: 100%;
  width: 100%
}
<svg id="svgP">
  <path id="test" style="stroke: RGBA(212, 50, 105, 1.00); fill: none" />
</svg>

A:

Finding circle to fit 3Points
This method uses a function that finds a circle that fits 3 points. Two of the points are the set of points you have. The 3rd point is taken perpendicular to the line between the points and moved out by a factor of the line seg length.
When the circle is found then the start and end angle from the circle center point is found  to make the arc segment and that is all done. Just draw the arcs with ctx.arc(
I am not sure exactly what you want. I have it so the arcs all bend up, But it is easy to make the go around.
If you want them all the same size you have to separate the points be equal distance, which is very simple, but means its hard to fit a given area.
Demo
The demo lets you add and drag point. Mouse wheel changes arc depth.
The const at the top arcDepth determines how deep each arc is compared to line segment length. It is a fraction.
You can make it a constant in pixels see, calcArc for how to change.
Each arc has an independent depth so if you don't like the overlapping arcs reduce the depth for that arc (in the code of course).
Hope that helps.

const pointSize = 4;
const pointCol = "#4AF";
var arcDepth = -0.5; // depth of arc as a factor of line seg length
                       // Note to have arc go the other (positive) way you have
                       // to change the ctx.arc draw call by adding anticlockwise flag
                       // see drawArc for more

const arcCol = "#4FA";
const arcWidth = 3;

// Find a circle that fits 3 points.
function fitCircleTo3P(p1x, p1y, p2x, p2y, p3x, p3y, arc) {
    var vx,
    vy,
    c,
    c1,
    u;

    c = (p2x - p1x) / (p1y - p2y); // slope of vector from vec 1 to vec 2
    c1 = (p3x - p2x) / (p2y - p3y); // slope of vector from vec 2 to vec 3
    // This will not happen in this example
    if (c === c1) { // if slope is the same they must be on the same line
        return null; // points are in a line
    }
    // locate the center
    if (p1y === p2y) { // special case with p1 and p2 have same y
        vx = (p1x + p2x) / 2;
        vy = c1 * vx + (((p2y + p3y) / 2) - c1 * ((p2x + p3x) / 2));
    } else
        if (p2y === p3y) { // special case with p2 and p3 have same y
            vx = (p2x + p3x) / 2;
            vy = c * vx + (((p1y + p2y) / 2) - c * ((p1x + p2x) / 2));
        } else {
            vx = ((((p2y + p3y) / 2) - c1 * ((p2x + p3x) / 2)) - (u = ((p1y + p2y) / 2) - c * ((p1x + p2x) / 2))) / (c - c1);
            vy = c * vx + u;
        }
    arc.x = vx;
    arc.y = vy;
    vx = p1x - vx;
    vy = p1y - vy;
    arc.rad = Math.sqrt(vx * vx + vy * vy);
    return arc;
}

var points = [];
var arcs = [];
function addArc(p1, p2, depth) {

    // remove next 5 line if you dont want all arcs to face the same way.
    if(points[p1][0] > points[p2][0]){
        var temp = p1;
        p1 = p2;
        p2 = temp;
    }
    var arc = {
        p1 : p1,
        p2 : p2,
        depth : depth,
        rad : null, // radius
        a1 : null, // angle from
        a2 : null, // angle to
        x : null,
        y : null,
    }
    arcs.push(arc);
    return arc;
}
function calcArc(arc, depth) {
    var p = points[arc.p1]; // get points
    var pp = points[arc.p2];
    // change depth if needed
    depth = arc.depth = depth !== undefined ? depth : arc.depth;
    var vx = pp[0] - p[0]; // vector from p to pp
    var vy = pp[1] - p[1];
    var cx = (pp[0] + p[0]) / 2; // center point
    var cy = (pp[1] + p[1]) / 2; // center point
    var len = Math.sqrt(vx * vx + vy * vy); // get length
    cx -= vy * depth; // find 3 point at 90 deg to line and dist depth
    cy += vx * depth;

    // To have depth as a fixed length uncomment 4 lines below and comment out 2 lines above.
    //var nx = vx / len;  // normalise vector
    //var ny = vy / len;
    //cx -= ny * depth; // find 3 point at 90 deg to line and dist depth
    //cy += nx * depth;

    fitCircleTo3P(p[0], p[1], cx, cy, pp[0], pp[1], arc); // get the circle that fits
    arc.a1 = Math.atan2(p[1] - arc.y, p[0] - arc.x); // get angle from circle center to first point
    arc.a2 = Math.atan2(pp[1] - arc.y, pp[0] - arc.x); // get angle from circle center to second point

}
function addPoint(x, y) {
    points.push([x, y]);
}
function drawPoint(x, y, size, col) {
    ctx.fillStyle = col;
    ctx.beginPath();
    ctx.arc(x, y, size, 0, Math.PI * 2);
    ctx.fill();
}

function drawArc(arc, width, col) {
    ctx.lineCap = "round";
    ctx.strokeStyle = col;
    ctx.lineWidth = width;
    ctx.beginPath();
    ctx.arc(arc.x, arc.y, arc.rad, arc.a1, arc.a2,false);  // true for anti clock wise
    ctx.stroke();
}
function findClosestPoint(x, y, dist) {
    var index = -1;
    for (var i = 0; i < points.length; i++) {
        var p = points[i];
        var vx = x - p[0];
        var vy = y - p[1];
        var d = Math.sqrt(vx * vx + vy * vy);
        if (d < dist) {
            dist = d;
            index = i;
        }
    }
    return index;
}

var dragging = false;
var drag = -1;
var dragX, dragY;
var recalcArcs = false;
function display() {
    ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
    ctx.globalAlpha = 1; // reset alpha
    ctx.clearRect(0, 0, w, h);
    if(mouse.w > 0){
        arcDepth *= 1.05;
        mouse.w = 0;
        recalcArcs = true;
    }
    if(mouse.w < 0){
        arcDepth *= 1/1.05;
        mouse.w = 0;
        recalcArcs = true;
    }

    if (mouse.buttonRaw & 1) {

        if (!dragging) {
            var i = findClosestPoint(mouse.x, mouse.y, pointSize * 3);
            if (i > -1) {
                drag = i;
                dragging = true;
                dragX = mouse.x - points[drag][0];
                dragY = mouse.y - points[drag][1];
            }
        }
        if (dragging) {
            points[drag][0] = mouse.x - dragX
                points[drag][1] = mouse.y - dragY
                recalcArcs = true;

        } else {
            addPoint(mouse.x, mouse.y);
            if (points.length > 1) {
                calcArc(addArc(points.length - 2, points.length - 1, arcDepth));
            }
            mouse.buttonRaw = 0;
        }

    } else {
        if (dragging) {
            dragging = false;
            drag = -1;
            recalcArcs = true;
        }
        var i = findClosestPoint(mouse.x, mouse.y, pointSize * 3);
        if (i > -1) {
            canvas.style.cursor = "move";
        } else {
            canvas.style.cursor = "default";

        }
    }
    for (var i = 0; i < arcs.length; i++) {
        if (recalcArcs) {
            calcArc(arcs[i],arcDepth);
        }
        drawArc(arcs[i], arcWidth, arcCol);

    }
    recalcArcs = false;

    for (var i = 0; i < points.length; i++) {
        var p = points[i];
        drawPoint(p[0], p[1], pointSize, pointCol);
    }

}

//===========================================================================================
// END OF ANSWER

// Boiler plate code from here down. Does mouse,canvas,resize and what not
var w, h, cw, ch, canvas, ctx, mouse, globalTime = 0, firstRun = true; ;
(function () {
    const RESIZE_DEBOUNCE_TIME = 100;
    var createCanvas,
    resizeCanvas,
    setGlobals,
    resizeCount = 0;
    createCanvas = function () {
        var c,
        cs;
        cs = (c = document.createElement("canvas")).style;
        cs.position = "absolute";
        cs.top = cs.left = "0px";
        cs.zIndex = 1000;
        document.body.appendChild(c);
        return c;
    }
    resizeCanvas = function () {
        if (canvas === undefined) {
            canvas = createCanvas();
        }
        canvas.width = innerWidth;
        canvas.height = innerHeight;
        ctx = canvas.getContext("2d");
        if (typeof setGlobals === "function") {
            setGlobals();
        }
        if (typeof onResize === "function") {
            if (firstRun) {
                onResize();
                firstRun = false;
            } else {
                resizeCount += 1;
                setTimeout(debounceResize, RESIZE_DEBOUNCE_TIME);
            }
        }
    }
    function debounceResize() {
        resizeCount -= 1;
        if (resizeCount <= 0) {
            onResize();
        }
    }
    setGlobals = function () {
        cw = (w = canvas.width) / 2;
        ch = (h = canvas.height) / 2;
    }
    mouse = (function () {
        function preventDefault(e) {
            e.preventDefault();
        }
        var mouse = {
            x : 0,
            y : 0,
            w : 0,
            alt : false,
            shift : false,
            ctrl : false,
            buttonRaw : 0,
            over : false,
            bm : [1, 2, 4, 6, 5, 3],
            active : false,
            bounds : null,
            crashRecover : null,
            mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")
        };
        var m = mouse;
        function mouseMove(e) {
            var t = e.type;
            m.bounds = m.element.getBoundingClientRect();
            m.x = e.pageX - m.bounds.left;
            m.y = e.pageY - m.bounds.top;
            m.alt = e.altKey;
            m.shift = e.shiftKey;
            m.ctrl = e.ctrlKey;
            if (t === "mousedown") {
                m.buttonRaw |= m.bm[e.which - 1];
            } else if (t === "mouseup") {
                m.buttonRaw &= m.bm[e.which + 2];
            } else if (t === "mouseout") {
                m.buttonRaw = 0;
                m.over = false;
            } else if (t === "mouseover") {
                m.over = true;
            } else if (t === "mousewheel") {
                m.w = e.wheelDelta;
            } else if (t === "DOMMouseScroll") {
                m.w = -e.detail;
            }
            e.preventDefault();
        }
        m.start = function (element) {
            if (m.element !== undefined) {
                m.removeMouse();
            }
            m.element = element === undefined ? document : element;
            m.mouseEvents.forEach(n => {
                m.element.addEventListener(n, mouseMove);
            });
            m.element.addEventListener("contextmenu", preventDefault, false);
            m.active = true;
        }
        m.remove = function () {
            if (m.element !== undefined) {
                m.mouseEvents.forEach(n => {
                    m.element.removeEventListener(n, mouseMove);
                });
                m.element.removeEventListener("contextmenu", preventDefault);
                m.element = m.callbacks = undefined;
                m.active = false;
            }
        }
        return mouse;
    })();

    function update(timer) { // Main update loop
        if (ctx === undefined) {
            return;
        }
        globalTime = timer;
        display(); // call demo code
        requestAnimationFrame(update);
    }
    setTimeout(function () {
        resizeCanvas();
        mouse.start(canvas, true);
        window.addEventListener("resize", resizeCanvas);
        requestAnimationFrame(update);
    }, 0);
})();
Left click to add point. Left click drag to move points.<br>
Mouse wheel changes arc depth.

Take two...
Maybe this is what you are after.. Sorry its a bit of a mess as I am short on time at the moment.
Same code as before just add the points to the outside of the box, making sure that the width and height steps are equally spaced from the edge.

const pointSize = 4;
const pointCol = "#4AF";
var arcDepth = -0.5; // depth of arc as a factor of line seg length
                       // Note to have arc go the other (positive) way you have
                       // to change the ctx.arc draw call by adding anticlockwise flag
                       // see drawArc for more

const arcCol = "#F92";
const arcWidth = 8;

// Find a circle that fits 3 points.
function fitCircleTo3P(p1x, p1y, p2x, p2y, p3x, p3y, arc) {
    var vx,
    vy,
    c,
    c1,
    u;

    c = (p2x - p1x) / (p1y - p2y); // slope of vector from vec 1 to vec 2
    c1 = (p3x - p2x) / (p2y - p3y); // slope of vector from vec 2 to vec 3
    // This will not happen in this example
    if (c === c1) { // if slope is the same they must be on the same line
        return null; // points are in a line
    }
    // locate the center
    if (p1y === p2y) { // special case with p1 and p2 have same y
        vx = (p1x + p2x) / 2;
        vy = c1 * vx + (((p2y + p3y) / 2) - c1 * ((p2x + p3x) / 2));
    } else
        if (p2y === p3y) { // special case with p2 and p3 have same y
            vx = (p2x + p3x) / 2;
            vy = c * vx + (((p1y + p2y) / 2) - c * ((p1x + p2x) / 2));
        } else {
            vx = ((((p2y + p3y) / 2) - c1 * ((p2x + p3x) / 2)) - (u = ((p1y + p2y) / 2) - c * ((p1x + p2x) / 2))) / (c - c1);
            vy = c * vx + u;
        }
    arc.x = vx;
    arc.y = vy;
    vx = p1x - vx;
    vy = p1y - vy;
    arc.rad = Math.sqrt(vx * vx + vy * vy);
    return arc;
}

var points = [];
var arcs = [];
function addArc(p1, p2, depth) {
    var arc = {
        p1 : p1,
        p2 : p2,
        depth : depth,
        rad : null, // radius
        a1 : null, // angle from
        a2 : null, // angle to
        x : null,
        y : null,
    }
    arcs.push(arc);
    return arc;
}
function calcArc(arc, depth) {
    var p = points[arc.p1]; // get points
    var pp = points[arc.p2];
    // change depth if needed
    depth = arc.depth = depth !== undefined ? depth : arc.depth;
    var vx = pp[0] - p[0]; // vector from p to pp
    var vy = pp[1] - p[1];
    var cx = (pp[0] + p[0]) / 2; // center point
    var cy = (pp[1] + p[1]) / 2; // center point
    var len = Math.sqrt(vx * vx + vy * vy); // get length
    cx -= vy * depth; // find 3 point at 90 deg to line and dist depth
    cy += vx * depth;

    // To have depth as a fixed length uncomment 4 lines below and comment out 2 lines above.
    //var nx = vx / len;  // normalise vector
    //var ny = vy / len;
    //cx -= ny * depth; // find 3 point at 90 deg to line and dist depth
    //cy += nx * depth;

    fitCircleTo3P(p[0], p[1], cx, cy, pp[0], pp[1], arc); // get the circle that fits
    arc.a1 = Math.atan2(p[1] - arc.y, p[0] - arc.x); // get angle from circle center to first point
    arc.a2 = Math.atan2(pp[1] - arc.y, pp[0] - arc.x); // get angle from circle center to second point

}
function addPoint(x, y) {
    points.push([x, y]);
}
function drawPoint(x, y, size, col) {
    ctx.fillStyle = col;
    ctx.beginPath();
    ctx.arc(x, y, size, 0, Math.PI * 2);
    ctx.fill();
}
function drawArcStart(width,col){
    ctx.lineCap = "round";
    ctx.strokeStyle = col;
    ctx.lineJoin = "round";
    ctx.lineWidth = width;
    ctx.beginPath();

}
function drawArc(arc){
    ctx.arc(arc.x,arc.y,arc.rad,arc.a1,arc.a2);
}
function drawArcDone(){
    ctx.closePath();
    ctx.stroke();
}
function findClosestPoint(x, y, dist) {
    var index = -1;
    for (var i = 0; i < points.length; i++) {
        var p = points[i];
        var vx = x - p[0];
        var vy = y - p[1];
        var d = Math.sqrt(vx * vx + vy * vy);
        if (d < dist) {
            dist = d;
            index = i;
        }
    }
    return index;
}

var dragging = false;
var drag = -1;
var dragX, dragY;
var recalcArcs = false;
var box;
//========================================================================
// New box code from her down

// creates the box when canvas is ready
var onResize = function(){
    box = {
        x : canvas.width * (1/8),
        y : canvas.height * (1/8),
        w : canvas.width * (6/8),
        h : canvas.height * (6/8),
        recalculate : true,
        arcCount : 20, // number of arcs to try and fit. Does not mean that it will happen
    }
}

function display() {
    ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
    ctx.globalAlpha = 1; // reset alpha
    ctx.clearRect(0, 0, w, h);

if(mouse.w !== 0){
    if(mouse.buttonRaw & 4){ // change arc depth
        if(mouse.w < 0){
            arcDepth *= 1/1.05;
        }else{
            arcDepth *= 1.05;
        }
        recalcArcs = true;

    }else{  // change arc count
        box.arcCount += Math.sign(mouse.w);
        box.arcCount = Math.max(4,box.arcCount);
        box.recalculate = true;
    }
    mouse.w = 0;
}
// drag out box;
if(mouse.buttonRaw & 1){
    if(!dragging){
        box.x = mouse.x;
        box.y = mouse.y;
        dragging = true;
    }
    box.w = mouse.x - box.x;
    box.h = mouse.y - box.y;
    box.recalculate = true;
    if(box.w <0){
        box.x = box.x + box.w;
        box.w = - box.w;
    }
    if(box.h <0){
        box.y = box.y + box.h;
        box.h = - box.h;
    }
}else{
    dragging = false;
}
// stop error
if(box.w === 0 || box.h === 0){
    box.recaculate = false;
}

// caculate box arcs
if(box.recalculate){
    // reset arrays
    points.length = 0;
    arcs.length = 0;
    // get perimiter length
    var perimLen = (box.w + box.h)* 2;
    // get estimated step size
    var step = perimLen / box.arcCount;
    // get inset size for width and hight
    var wInStep = (box.w - (Math.floor(box.w/step)-1)*step) / 2;
    var hInStep = (box.h - (Math.floor(box.h/step)-1)*step) / 2;
    // fix if box to narrow
    if(box.w < step){
        wInStep = 0;
        hInStep = 0;
        step = box.h / (Math.floor(box.h/step));
    }else if(box.h < step){
        wInStep = 0;
        hInStep = 0;
        step = box.w / (Math.floor(box.w/step));

    }

    // Add points clock wise
    var x = box.x + wInStep;
    while(x < box.x + box.w){ // across top
        addPoint(x,box.y);
        x += step;
    }
    var y = box.y + hInStep;
    while(y < box.y + box.h){ // down right side
        addPoint(box.x + box.w,y);
        y += step;
    }
    x = box.x + box.w - wInStep;
    while(x > box.x){          // left along bottom
        addPoint(x,box.y + box.h);
        x -= step;
    }
    var y = box.y + box.h - hInStep;
    while(y > box.y){  // up along left side
        addPoint(box.x,y);
        y -= step;
    }
    // caculate arcs.
    for(var i =0; i <points.length; i++){
        calcArc(addArc(i,(i + 1) % points.length,arcDepth));
    }
    box.recalculate = false;
}
// recaculate arcs if needed
for(var i = 0; i < arcs.length; i ++){
    if(recalcArcs){
        calcArc(arcs[i],arcDepth);
    }
}
// draw arcs
drawArcStart(arcWidth,arcCol)
for(var i = 0; i < arcs.length; i ++){
    drawArc(arcs[i]);
}
drawArcDone();
recalcArcs = false;
}

//===========================================================================================
// END OF ANSWER

// Boiler plate code from here down. Does mouse,canvas,resize and what not
var w, h, cw, ch, canvas, ctx, mouse, globalTime = 0, firstRun = true; ;
(function () {
    const RESIZE_DEBOUNCE_TIME = 100;
    var createCanvas,
    resizeCanvas,
    setGlobals,
    resizeCount = 0;
    createCanvas = function () {
        var c,
        cs;
        cs = (c = document.createElement("canvas")).style;
        cs.position = "absolute";
        cs.top = cs.left = "0px";
        cs.zIndex = 1000;
        document.body.appendChild(c);
        return c;
    }
    resizeCanvas = function () {
        if (canvas === undefined) {
            canvas = createCanvas();
        }
        canvas.width = innerWidth;
        canvas.height = innerHeight;
        ctx = canvas.getContext("2d");
        if (typeof setGlobals === "function") {
            setGlobals();
        }
        if (typeof onResize === "function") {
            if (firstRun) {
                onResize();
                firstRun = false;
            } else {
                resizeCount += 1;
                setTimeout(debounceResize, RESIZE_DEBOUNCE_TIME);
            }
        }
    }
    function debounceResize() {
        resizeCount -= 1;
        if (resizeCount <= 0) {
            onResize();
        }
    }
    setGlobals = function () {
        cw = (w = canvas.width) / 2;
        ch = (h = canvas.height) / 2;
    }
    mouse = (function () {
        function preventDefault(e) {
            e.preventDefault();
        }
        var mouse = {
            x : 0,
            y : 0,
            w : 0,
            alt : false,
            shift : false,
            ctrl : false,
            buttonRaw : 0,
            over : false,
            bm : [1, 2, 4, 6, 5, 3],
            active : false,
            bounds : null,
            crashRecover : null,
            mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")
        };
        var m = mouse;
        function mouseMove(e) {
            var t = e.type;
            m.bounds = m.element.getBoundingClientRect();
            m.x = e.pageX - m.bounds.left;
            m.y = e.pageY - m.bounds.top;
            m.alt = e.altKey;
            m.shift = e.shiftKey;
            m.ctrl = e.ctrlKey;
            if (t === "mousedown") {
                m.buttonRaw |= m.bm[e.which - 1];
            } else if (t === "mouseup") {
                m.buttonRaw &= m.bm[e.which + 2];
            } else if (t === "mouseout") {
                m.buttonRaw = 0;
                m.over = false;
            } else if (t === "mouseover") {
                m.over = true;
            } else if (t === "mousewheel") {
                m.w = e.wheelDelta;
            } else if (t === "DOMMouseScroll") {
                m.w = -e.detail;
            }
            e.preventDefault();
        }
        m.start = function (element) {
            if (m.element !== undefined) {
                m.removeMouse();
            }
            m.element = element === undefined ? document : element;
            m.mouseEvents.forEach(n => {
                m.element.addEventListener(n, mouseMove);
            });
            m.element.addEventListener("contextmenu", preventDefault, false);
            m.active = true;
        }
        m.remove = function () {
            if (m.element !== undefined) {
                m.mouseEvents.forEach(n => {
                    m.element.removeEventListener(n, mouseMove);
                });
                m.element.removeEventListener("contextmenu", preventDefault);
                m.element = m.callbacks = undefined;
                m.active = false;
            }
        }
        return mouse;
    })();

    function update(timer) { // Main update loop
        if (ctx === undefined) {
            return;
        }
        globalTime = timer;
        display(); // call demo code
        requestAnimationFrame(update);
    }
    setTimeout(function () {
        resizeCanvas();
        mouse.start(canvas, true);
        window.addEventListener("resize", resizeCanvas);
        requestAnimationFrame(update);
    }, 0);
})();
Left click drag to create a box<br>Mouse wheel to change arc count<br>Hold right button down and wheel to change arc depth.<br>

A:

The following code snippet determines the direction (CW, CCW) of each segment by analyzing the adjacent segments. For segment A, if both adjacent segments are on the same side of A (or if A has only one adjacent segment), there is no ambiguity and the scallops of segment A are on the outside of the convex shape formed by these segments. However, if the adjacent segments are on opposite sides of A, in a zigzag pattern, the adjacent segment that extends the farthest from segment A is chosen to set the direction of segment A.

function distance(x1, y1, x2, y2) {
    return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

function findNewPoint(x, y, angle, distance) {
    var result = {};
    result.x = Math.round(Math.cos(angle) * distance + x);
    result.y = Math.round(Math.sin(angle) * distance + y);
    return result;
}

function getAngle(x1, y1, x2, y2) {
    return Math.atan2(y2 - y1, x2 - x1);
}

function getSeparationFromLine(lineOrigin, lineAngle, pt) {
    x = pt.x - lineOrigin.x;
    y = pt.y - lineOrigin.y;
    return -x * Math.sin(lineAngle) + y * Math.cos(lineAngle);
}

function getDirection(pts, index, closed) {
    var last = pts.length - 1;
    var start = index;
    var end = (closed && start == last) ? 0 : index + 1;
    var prev = (closed && start == 0) ? last : start - 1;
    var next = (closed && end == last) ? 0 : end + 1;

    var isValidSegment = 0 <= start && start <= last && 0 <= end && end <= last && end !== start;

    if (!isValidSegment) {
        return 1;
    }

    var pt1 = pts[start];
    var pt2 = pts[end];

    var pt, x, y;
    var ccw = 0.0;
    var theta = Math.atan2(pt2.y - pt1.y, pt2.x - pt1.x);

    if (0 <= prev && prev <= last) {
        ccw += getSeparationFromLine(pt1, theta, pts[prev]);
    }

    if (0 <= next && next <= last) {
        ccw += getSeparationFromLine(pt1, theta, pts[next]);
    }

    return ccw > 0 ? "1" : "0";
}

function scapolledLine(pts, closed, strokeWidth) {
    var that = this;
    var scallopSize = strokeWidth * 8;
    var lastIndex = pts.length - 1;
    var path = [], newP = null;
    path.push("M", pts[0].x, pts[0].y);

    pts.forEach(function (s, currentIndex) {
        var stepW = scallopSize, lsw = 0;
        var isClosingSegment = closed && currentIndex == lastIndex;
        var nextIndex = isClosingSegment ? 0 : currentIndex + 1;
        var e = pts[nextIndex];
        if (!e) {
            return;
        }

        var direction = getDirection(pts, currentIndex, closed);
        var args = [s.x, s.y, e.x, e.y];
        var dist = that.distance.apply(that, args);
        if (dist === 0) {
            return;
        }

        var angle = that.getAngle.apply(that, args);
        newP = s;

        // Number of possible scallops between current pts
        var n = dist / stepW, crumb;

        if (dist < (stepW * 2)) {
            stepW = (dist - stepW) > (stepW * 0.38) ? (dist / 2) : dist;
        } else {
            n = (n - (n % 1));
            crumb = dist - (n * stepW);
            stepW += (crumb / n);
        }

        // Recalculate possible scallops.
        n = dist / stepW;
        var aw = stepW / 2;
        for (var i = 0; i < n; i++) {
            newP = that.findNewPoint(newP.x, newP.y, angle, stepW);
            if (i === (n - 1)) {
                aw = (lsw > 0 ? lsw : stepW) / 2;
            }
            path.push('A', aw, aw, "0 0 " + direction, newP.x, newP.y);
        }

        if (isClosingSegment) {
            path.push('A', stepW / 2, stepW / 2, "0 0 " + direction, e.x, e.y);
        }
    });
    return path.join(' ');
}

var strokeWidth = 3;
var points = [];
var mouse = null;
var isClosed = false;

window.test.setAttribute('stroke-width', strokeWidth);

function feed(isDoubleClick) {
    if (isClosed) {
        return;
    }
    if (!isDoubleClick && (points.length > 0 && mouse)) {
        var arr = points.slice(0);
        arr.push(mouse);
        var str = scapolledLine(arr, isClosed, strokeWidth);
        window.test.setAttribute('d', str);
    } else if (isDoubleClick) {
        isClosed = true;
        points.pop();
        var str = scapolledLine(points, isClosed, strokeWidth);
        window.test.setAttribute('d', str);
    }
}

document.addEventListener('mousedown', function (event) {
    points.push({
        x: event.clientX,
        y: event.clientY
    });
    feed(false);
});

document.addEventListener('dblclick', function (event) {
    feed(true);
});

document.addEventListener('mousemove', function (event) {
    if (points.length > 0) {
        mouse = {
            x: event.clientX,
            y: event.clientY
        }
        feed(false);
    }
});
body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0
}
svg {
  height: 100%;
  width: 100%
}
<svg id="svgP">
  <path id="test" style="stroke: RGBA(212, 50, 105, 1.00); fill: none" />
</svg>


Q:

What is the top speed of a four legged robot?

In  Neal Stephenson's novel "Snow Crash", a robotic/cybernetic creature known as a "Rat Thing" looses its bounds and runs to rescue another character.  The Rat Thing is portrayed at moving over 700 mph and causing sonic shock waves.  Can such a speed be reached by purely mechanical means?

A:

Currently the fastest four legged robot is Cheetah by Boston Dynamics that runs 29mph. Real cheetahs can run 70mph and are the fastest land animals. I don't think it would be possible for a robot to run much faster than that. Why? At higher speeds aerodynamics play a crucial role, and a legged design would be hard to optimize in that way.
Also keep in mind, that there is currently only one land vehicle that broke a sound barrier - thrustSSC. Powered by jet engines, it consumes insane 18l of fuel per second. The mass of the fuel itself would be extremely hard to carry for a legged robot.


Q:

How to change color of the scrollbar in SynMemo with VCL styles

there. I changed style of standard objects with VCl-theme.
I use Color, Font and Gutter properties to change style of SynMemo. But I don't know, how change style of ScrollBar of SynEdit( apply vcl-theme ). Who can help me ?

A:

To add styling support for the TSynEdit you must register a style hook for such control. Try using the TScrollingStyleHook style hook.
Like so
TStyleManager.Engine.RegisterStyleHook(TCustomSynEdit, TScrollingStyleHook);


Q:

Importing Flash project into Flash Builder

I am on a mac and I have a preexisting Flash project. (i.e usual fla, src, lib) folders.
Now, I want to start writing the code using Flash Builder 4.
How do I import all those files so I can now develop in Flash Builder 4?
Thank you,
Tee

A:

Found it.  Just need to do File > New > Flex Project to define a project for the folder containing your app.
Thanks,
Tee


Q:

WriteAllText, Character Encoding, £ and?

Take the following example:
string testfile1 = Path.Combine(HttpRuntime.AppDomainAppPath, "folder\\" + "test1.txt");
if (!System.IO.File.Exists(testfile1))
{
    System.IO.File.WriteAllText(testfile1, "£100", System.Text.Encoding.ASCII);
}

string testfile2 = Path.Combine(HttpRuntime.AppDomainAppPath, "folder\\" + "test2.txt");
if (!System.IO.File.Exists(testfile2))
{
    System.IO.File.WriteAllText(testfile2, "£100", System.Text.Encoding.UTF8);
}

Note the encoding.  The first outputs ?100.  The second outputs £100.
I know the encoding is different, but can somebody explain why ASCII encoding can't write the £ sign?

A:

ASCII doesn't include the "£" character. That is - there is no byte value (nor a multiple byte value - they don't exist in ASCII) that denotes that symbol. So it shows you a "?" to tell you that. UTF8, on the other hand, does include it.
See here a list of all of the printable characters in ASCII.
If you must use ASCII, consider using "GBP" as mentioned here for Pound sterling. (Also might be relevant: Extended ASCII.)


Q:

VS Code: enable inline spell checker, but disable spell check in the "Problems" panel

I use the code spell checker for VS Code. I would like to disable the spell checker warnings/errors in the "PROBLEMS" panel (standard keyboard binding Ctrl+Shift+M) where "more serious" problems show up.
Often there are so many spell checker errors that I have to scroll down to the "real" problems :-)

A:

See issues: don't show in Problems pane.  It is suggested to try:
  "cSpell.diagnosticLevel": "Hint",

in your settings.json.  This will remove them from the problems pane.  However, in your files these "hints" are now indicated by three small dots under the beginning of the misspell and are not all that apparent.  You can modify them with the colorCustomization:
"workbench.colorCustomizations": {

  // will change the color of three dots to red
  "editorHint.foreground": "#ff0000",

  // will underline the entire word with dots in your chosen color
  "editorHint.border": "#00ff66"
}

This will give you both sets of hint dots, you can hide the built-in three dots by making them transparent:
"editorHint.foreground": "#f000",


Q:

Add encoding parameter to logging.basicConfig

How do I add an encoding parameter to logging.basicConfig?
I have found this bug report that states that this is now possible for Python 3.3. I need this for Python 2.7 and the bug report says to use a custom logging.FileHandler object, but I can't get it to work.

A:

It will be easier to avoid using basicConfig() in your case - just create the handler and add it programmatically (ensuring that the code runs just once), e.g.:
root_logger= logging.getLogger()
root_logger.setLevel(logging.DEBUG) # or whatever
handler = logging.FileHandler('test.log', 'w', 'utf-8') # or whatever
handler.setFormatter(logging.Formatter('%(name)s %(message)s')) # or whatever
root_logger.addHandler(handler)

That's more or less what basicConfig() does.
Update: As of Python 3.9 (still in development), basicConfig() should have encoding and errors keywords available.

A:

Vinay's response was very helpful, but to get it working I had to tweak the syntax:
root_logger= logging.getLogger()
root_logger.setLevel(logging.DEBUG) # or whatever
handler = logging.FileHandler('test.log', 'w', 'utf-8') # or whatever
formatter = logging.Formatter('%(name)s %(message)s') # or whatever
handler.setFormatter(formatter) # Pass handler as a parameter, not assign
root_logger.addHandler(handler)

A:

You can pass a list of specific file handlers:
import logging

logging.basicConfig(handlers=[logging.FileHandler(filename="./log_records.txt",
                                                 encoding='utf-8', mode='a+')],
                    format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
                    datefmt="%F %A %T",
                    level=logging.INFO)

and it works pretty well (python version == Python 3.6.8 :: Anaconda, Inc.)


Q:

Request focus for keylistener, not sure if i have focus or not?

I'm not sure why when I press w my rectangle doesn't adjust accordingly.  Do I have my focus set up right, or do I need to request it from a separate class?  Should I be doing this in my drawingComponent class or in my "core" class?
package scratch;

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.*;

public class drawingComponent extends JComponent implements KeyListener {

    Rectangle hello = new Rectangle(300, 100, 50, 50);

    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(new Color(255,25,0));
        g2.setFont(new Font("monospace", Font.BOLD+Font.ITALIC, 30));
        g2.drawString("nothing yet",300,320);
        g2.fill(hello);

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_W){

             hello.setLocation(hello.x-50, hello.y);
             repaint();

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}

I have solved the problem by adding the following to my drawingComponent class.
setFocusable(true);
requestFocus();
addKeyListener(this);

A:

You want to use Key Bindings, not a KeyListener for several reasons, but one being that you don't have to worry so much about focus with Key Bindings. Also, you'll want to in the future post a minimal example program that we can test, run and modify, something like this:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class DrawingComponent extends JPanel {
   private static final int PREF_W = 800;
   private static final int PREF_H = 600;
   private static final Color RECT_COLOR = new Color(255,25,0);
   private Rectangle rect = new Rectangle(300, 100, 50, 50);

   public DrawingComponent() {
      setUpKeyBindings();
   }

   private void setUpKeyBindings() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();

      KeyStroke wStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0);
      inputMap.put(wStroke, wStroke.toString());
      actionMap.put(wStroke.toString(), new WAction());
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setColor(RECT_COLOR);
      g2.fill(rect);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class WAction extends AbstractAction {
      @Override
      public void actionPerformed(ActionEvent e) {
         rect.setLocation(rect.x-50, rect.y);
         repaint();
      }
   }

   private static void createAndShowGui() {
      DrawingComponent mainPanel = new DrawingComponent();

      JFrame frame = new JFrame("DrawingComponent");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Also, call the super's paintComponent method in your override, else your JPanel won't erase the old images.


Q:

API Gateway mapping template : Convert form-data(POST) request to JSON

I am sending some form-data in request body from postman. In aws API Gateway I have set Content-type as "multipart/form-data" and mapping template is following:
    #set($allParams = $input.params())
{
"body-json" : $input.json('$'),
"params" : {
#foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
"$type" : {
    #foreach($paramName in $params.keySet())
    "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
        #if($foreach.hasNext),#end
    #end
}
    #if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
    #if($foreach.hasNext),#end
#end
},
"context" : {
    "account-id" : "$context.identity.accountId",
    "api-id" : "$context.apiId",
    "api-key" : "$context.identity.apiKey",
    "authorizer-principal-id" : "$context.authorizer.principalId",
    "caller" : "$context.identity.caller",
    "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
    "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
    "cognito-identity-id" : "$context.identity.cognitoIdentityId",
    "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
    "http-method" : "$context.httpMethod",
    "stage" : "$context.stage",
    "source-ip" : "$context.identity.sourceIp",
    "user" : "$context.identity.user",
    "user-agent" : "$context.identity.userAgent",
    "user-arn" : "$context.identity.userArn",
    "request-id" : "$context.requestId",
    "resource-id" : "$context.resourceId",
    "resource-path" : "$context.resourcePath"
    }
}

However when I am getting the request on my lambda function everything is properly mapped into JSON, except my request body. Request body is coming as String. Following is the complete request:
  {
    "context": {
        "authorizer-principal-id": "",
        "cognito-authentication-type": "",
        "cognito-identity-id": "",
        "resource-path": "/env/Response",
        "account-id": "",
        "cognito-identity-pool-id": "",
        "request-id": "cd2052-11e7-92b6-e3c7d7dgh01",
        "api-id": "39dhjsr8",
        "resource-id": "skdsk5",
        "user-arn": "",
        "caller": "",
        "http-method": "POST",
        "cognito-authentication-provider": "",
        "api-key": "",
        "user": "",
    },
    "body-json": "------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"sig\"\r\n\r\nmcHeelgDQcYnjh5L2L92H8KLLE=\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"resultdescription\"\r\n\r\ncancelled.\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"result\"\r\n\r\nF\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"errorcode\"\r\n\r\n101\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"id\"\r\n\r\n420LU2UEG\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"key\"\r\n\r\ntdx\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"refid\"\r\n\r\n10480\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nTest\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"date\"\r\n\r\n2016-02-28T20:05:05.6330000Z\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx\r\nContent-Disposition: form-data; name=\"timestamp\"\r\n\r\n2016-02-29T04:15:47.4797Z\r\n------WebKitFormBoundaryLAn6jCAA10bF7ZMx--",
    "params": {
        "path": {},
        "querystring": {},
        "header": {
           },
    "stage-variables": {}
}

I have 2 queries regarding this:

Is there any way where I can convert request body into JSON Object in API gateway mapping template itself?(Means instead of String, Request Body should come as JSON Object).
Or I have to convert request body String into JSON Object at lambda handler in my java code?

Any help will be highly appreciated, as I am new to AWS.

A:

It would be best if you send your payload as application/json. That way, you can have it parsed in the mapping template using $util.parseJson() and the request body will come out as an object.
If you want to stick with form-data, you'll have to convert it inside your handler.
In Node.js, I use querystring module for this. Not sure what you can use in Java.


Q:

how to draw graph of records in WPF by using graphviz4net

From http://www.graphviz.org/pdf/dotguide.pdf, I see an example of drawing of records. I am wondering how to achieve that in wpf.

A:

It's not supported in .NET wrapper.


Q:

Does WAMP messaging have to route messages through a broker?

I've been reviewing Websockets messaging protocols. Looking at WAMP, it has the basic features I want. But in reading the docs, it appears that it requires a messages to route through the broker. Is this correct?
I am looking for real time messaging. While the broker role may be useful as a means of bringing together the publishers and subscribers, I would want the broker to only negotiate the connection, then hand-off sockets/IPs to the parties - allowing direct routing between the involved parties without requiring the broker to manage all the real time messaging. Can WAMP do this?

A:

Two WebSocket clients (e.g. browsers) cannot talk directly to each other. So there will be an intermediary involved in any case.
WAMP is for real-time messaging. To be precise, WebSocket is for soft real-time. There are no hard real-time guarantees in any TCP based protocol running over networks.
Regarding publish & subscribe: a broker is always required, since it is exactly this part which decouples publishers and subscribers. If publisher would be directly connected to subscribers (not possible with 2 WebSocket client anyway, but ..), then you would introduce coupling. But decoupling a main point of doing PubSub anyway.
What exactly is your concern with having a broker (PubSub) or a dealer (RPC) being involved? Latency?


Q:

Difference between "open-ended lists" and "difference lists"

What is the difference between "open-ended lists" and "difference lists"?

A:

As explained on http://homepages.inf.ed.ac.uk/pbrna/prologbook/node180.html, open list is a tool used to implement a difference list.
Open list is any list where you have a unassigned variable at some point in the list, e.g.: [a,b,c|X]. You can use open list to implement a data structure called difference list, which formally specifies a structure of two terms pointing to first element and to the open end, traditionally defined as: [a,b,c|X]-X, to make operating on such lists easier.
For example, if all you have is an open list, adding element to the end is possible, but you need to iterate over all items. In a difference list you can just use the end-of-list variable (called a Hole on the page above) to skip iteration and perform the operation in constant time.

A:

For example
Open-ended : [a,b,c | _]
Difference-list : [a,b,c|U]-U.

A:

Both notions seem to be lists, but in fact they are not. One is a concrete term, the other rather a convention.
Open-ended lists, partial lists
Open-ended lists are terms that are not lists but can be instantiated such that they become lists. In standard lingo, they are called partial lists. Here are partial lists: X, [a|X], [X|X] are all partial lists.
The notion open-ended lists suggests a certain usage of such lists to simulate some open-ended state. Think of a dictionary that might be represented by an open-ended list. Every time you add a new item, the variable "at the end of the partial list" is instantiated to a new element. While this programming technique is quite possible in Prolog, it has one big downside: The programs will heavily depend on a procedural interpretation. And in many situations there is no way to have a declarative interpretation at all.
Difference lists
Difference lists are effectively not lists as such but a certain way how lists are used such that the intended list is represented by two variables: one for the start and one for the end of the list. For this reason it would help a lot to rather talk of list differences instead of difference lists.
Consider:
el(E, [E|L],L).

Here, the last two arguments can be seen as forming a difference: a list that contains the single element [E]. You can now construct more complex lists out of simpler ones, provided you respect certain conventions which are essentially that the second argument is only passed further on. The differences as such are never compared to each other!
el2(E, F, L0,L) :-
   el(E, L0,L1),
   el(F, L1,L).

Note that this is merely a convention. The lists are not enforced. Think of:
?- el2(E, F, L, nonlist).
L = [E,F|nonlist].

This technique is also used to encode dcgs.


Q:

How can I crop an image before loading it to the view controller

In my view controller, my UIImageView is set to 370x370, when I load an image it currently stretches to fit the ImageView.
This is what I currently have for picking an image:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // Runs when user is picking image from library
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.previewImageView.image = pickedImage
        self.selectImageButton.isEnabled = false
        self.selectImageButton.isHidden = true
        uploadImage(image: pickedImage)
        picker.dismiss(animated: true, completion: nil)
    }
}

I'm fairly new to Swift, what would be the best was to implement an image crop into my code?

A:

When you call the ImagePicker function, set allowsEditing as true:
self.imagePicker.allowsEditing = true
self.imagePicker.sourceType = .camera
self.present(self.imagePicker, animated: true, completion: nil)

Another option, if you want a bit more customization, you can use this library: https://github.com/TimOliver/TOCropViewController
And in didFinishPickingMediaWithInfo, you do something like this:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
        dismiss(animated: true, completion: nil)
        let cropVC = TOCropViewController(image: pickedImage)
        cropVC.delegate = self
        cropVC.aspectRatioPickerButtonHidden = true
        cropVC.aspectRatioPreset = .presetSquare
        cropVC.aspectRatioLockEnabled = true
        cropVC.resetAspectRatioEnabled = false
        self.present(cropVC, animated: true, completion: nil)
    }
}


Q:

どうして「お聞き遊ばして」が現代語訳では「お吸いなさいまして」になるのか分からない

現代訳を頼りに、泉鏡花さんの「外科室」を読もうとしているところですが、分からない箇所があります。
原文の

　看護婦は医学士の旨を領してのち、かの腰元に立ち向かいて、
  「もう、なんですから、あのことを、ちょっと、あなたから」
  　腰元はその意を得て、手術台に擦り寄りつ、優に膝のあたりまで両手を下げて、しとやかに立礼し、
「夫人、ただいま、お薬を差し上げます。どうぞそれを、お聞きあそばして、いろはでも、数字でも、お算えあそばしますように」
  　伯爵夫人は答なし。

は現代訳ではこうなる。

　看護婦は医学士の指示を承知した後、あの侍女に向かって、
  「もう、時間ですから、あのことを、ちょっと、あなたから申し上げてください」
  　侍女はその言葉の意味を理解して、手術台に擦り寄り、膝のあたりまで両手を下げて、しとやかに深く立礼し、
「奥様、ただいま、お薬を差し上げます。どうぞそれを、お吸いなさいまして、いろはでも、数字でも、お数えなさいますように」
  　伯爵夫人の答えはない。

「お聞きあそばして」を見た時に、「お聞きなさいまして」と解釈したが、現代訳によると、「お聞きなさいまして」ではなく、「お吸いなさいまして」という意味だそうです。理由は何ですか。

A:

明鏡国語辞典によりますと、「聞く」の意味として、

きく
  ⑤[聞]においをかぐ。また、においのよしあしなどを感じとる。「[香]{こう}を聞く」
  ⑥[聞]酒の良しあしなどを舌で感じとる。「酒を聞く」
  表記 ⑥は「利く」とも。

とあります。どんなお薬なのか（飲み薬ではない？）、先を読めばわかるかもしれませんが、この場合、５の意味として解釈されているのだと思います。少し古いような、硬い感じの表現なので、現代語訳では「吸う」にされているのだと思います。


Q:

in foreach loop, should I expect an error since query collection has changed?

For example
       var query = myDic.Where(x => !blacklist.Contains(x.Key));
        foreach (var item in query)
        {
            if (condition)
              blacklist.Add(item.key+1);  //key is int type
            ret.add(item);
        }
       return ret;

would this code be valid? and how do I improve it?
Updated
i am expecting my blacklist.add(item.key+1) would result in smaller ret then otherwise. The ToList() approach won't achieve my intention in this sense.
is there any other better ideas, correct and unambiguous.

A:

That is perfectly safe to do and there shouldn't be any problems as you're not directly modifying the collection that you are iterating over.  Though you are making other changes that affects where clause, it's not going to blow up on you.
The query (as written) is lazily evaluated so blacklist is updated as you iterate through the collection and all following iterations will see any newly added items in the list as it is iterated.
The above code is effectively the same as this:
foreach (var item in myDic)
{
    if (!blacklist.Contains(item.Key))
    {
        if (condition)
            blacklist.Add(item.key + 1);
    }
}

So what you should get out of this is that as long as you are not directly modifying the collection that you are iterating over (the item after in in the foreach loop), what you are doing is safe.
If you're still not convinced, consider this and what would be written out to the console:
var blacklist = new HashSet<int>(Enumerable.Range(3, 100));
var query = Enumerable.Range(2, 98).Where(i => !blacklist.Contains(i));
foreach (var item in query)
{
    Console.WriteLine(item);
    if ((item % 2) == 0)
    {
        var value = 2 * item;
        blacklist.Remove(value);
    }
}


Q:

Get intellij python to autocomplete on tab instead of space (and tab) which is does now

Is there a way to prevent intelli(Idea) pycharm plugin from not autocompleting on space; I want autocomplete only when I hit the tab.
Space to me means I want to continue typing without being bothered.
E.g. I'm trying to say something like d = 0.
Idea forces me to escape. A space will autocomplete to delattr.

A:

You can disable "Settings | Editor | General | Code Completion | Insert selected variant by typing dot, space, etc", then only Enter and Tab will choose the selected item in autopopup completion.


Q:

Qt5 Memory Polling

I'm new here so I apologize if I have posted in the wrong area or am missing some information in my question. Is it possible to poll global memory usage in windows with Qt5? I've searched through the Qt5 Classes and I didn't find anything that I thought would fit the bill. For more specificity, I'm looking for something similar to GlobalMemoryStatusEx.

A:

Qt doesn't offer a portable API to do so, since querying the OS for memory usage is indeed, an OS specific task.
You can however, write a wrapper class, which uses the correct API depending on the OS you are running.
As an example, on Windows you could use the API you have already mentioned (GlobalMemoryStatusEx), while on Linux you could use the sysinfo API).
Once you have identified the APIs to use for the target platforms, you can use conditional compilation to compile only the correct code for each platform, while offering the same interface to the outside world.
Qt offers a few defines (Q_OS_) which are set or not depending on the target OS. Have a look at the documentation here for more details.
Example:
/*!
 * \brief MemoryUsage::getMemoryUsage
 * \return the overall memory usage in percent.
 */
int MemoryUsage::getMemoryUsage()
{
    int result = 0;

#ifdef Q_OS_LINUX
    struct sysinfo sys_info;

    sysinfo(&sys_info);

    unsigned long long total = sys_info.totalram *(unsigned long long)sys_info.mem_unit / 1024;
    unsigned long long free = sys_info.freeram *(unsigned long long)sys_info.mem_unit/ 1024;

    result = (total - free) * 100 / total;
#endif

#ifdef Q_OS_WIN
    MEMORYSTATUSEX statex;
    statex.dwLength = sizeof (statex);

    GlobalMemoryStatusEx (&statex);

    result = statex.dwMemoryLoad);
#endif

    return result;
}

With the same trick you must also ensure the correct headers are included (e.g. don't include  when you are compiling for Linux).


Q:

Can a subquery be used with the VALUES keyword?

I was under the impression that it could not, but then I ran across these 2 examples (using Oracle XE and SQL Developer):
Example 1 - executes without error
insert into regions (region_id, region_name)
values ((select max(region_id)+1 from regions), 'Great Britain');

Example 2 - returns error (shown below)
insert into regions (region_id, region_name)
values (select region_id, region_name from regions);

Error:
Error starting at line 1 in command:
insert into regions (region_id, region_name)
values (select region_id, region_name from regions)
Error at Command Line:2 Column:9
Error report:
SQL Error: ORA-00936: missing expression
00936. 00000 -  "missing expression"
*Cause:
*Action:

So, it appears that there is more to it. Can anyone provide an explanation of under what conditions it is/isn't ok to include subqueries with the VALUES keyword?

A:

You need to insert subqueries in parentheses.  The opening paren for values doesn't count.  It is the start of a list, not a subquery.  You can include subqueries in the VALUES clause when they return one row and one column.
Instead, though, you can use this syntax:
insert into regions (region_id, region_name)
    select max(region_id) + 1, 'Great Britain'
    from regions;

Better yet would be to assign a sequence to the region_id (identity or auto-increment column in other databases) so it is assigned automatically.  Then you would just do:
insert into regions (region_name)
    select 'Great Britain'
    from dual;


Q:

What mechanism prevents any user from accessing any other user's files via root?

On a multi-user system, what protects against any user accessing any other users files via root?  As context, the question is based on my understanding as follows:
There are two commands related to root privileges, sudo and su. With sudo, you don't become another user (including root). sudo has a pre-defined list of approved commands that it executes on your behalf.  Since you are not becoming root or another user, you just authenticate yourself with your own password.
With su, you actually become root or another user. If you want to become user Bob, you need Bob's password. To become root, you need the root password (which would be defined on a multi-user system).
ref's: howtogeek.com:

su switches you to the root user account and requires the root account’s password. sudo runs a single command with root privileges –
  it doesn’t switch to the root user.

and

If you execute the su bob command, you’ll be prompted to enter Bob’s password and the shell will switch to Bob’s user account;   Similar description at computerhope.com

tecmint.com:

‘sudo‘ is a root binary setuid, which executes root commands on behalf
  of authorized users

If you become root, you have access to everything. Anyone not authorized to access another user's account would not be given the root password and would not have sudo definitions allowing it.
This all makes sense until you look at something like this link, which is a tutorial for using sudo -V and then sudo su - to become root using only your own password.
If any user can become root without the root password, what mechanism protects user files from unauthorized access?

A:

The major difference between sudo and su is the mechanism used to authenticate.  With su the user must know the root password (which should be a closely guarded secret), while with sudo the user uses his/her own password.  In order to stop all users causing mayhem, the priviliges discharged by the sudo command can, fortunately, be configured using the /etc/sudoers file.
Both commands run a command as another user, quite often root.
sudo su - works in the example you gave because the user (or a group where the user is a member) is configured in the /etc/sudoers file.  That is, they are allowed to use sudo. Armed with this, they use the sudo to temporarily gain root privileges (which is default when no username is provided) and as root start another shell (su -).  They now have root access without knowing root's password.
Conversely, if you don't allow the user to use sudo then they won't be able to sudo su -.
Distros generally have a group (often called wheel) whose members are allowed to use sudo to run all commands.  Removing them from this group will mean that they cannot use sudo at all by default.
The line in /etc/sudoers that does this is:
## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

While removing users from this group would make your system more secure, it would also result in you (or other system adminstrators) being required to carry out more administrative tasks on the system on behalf of your users.
A more sensible compromise would configure sudo to give you more fine grained control of who is allowed to use sudo and who isn't, along with which commands they are allowed to use (instead of the default of all commands).  For example,
## Allows members of the users group to mount and unmount the
## cdrom as root
%users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

(only useful with the previous %wheel line commented out, or no users in the wheel group).
Presumably, distros don't come with this finer grained configuration as standard as it's impossible to forecast what the admin's requirements are for his/her users and system.
Bottom line is - learn the details of sudo and you can stop sudo su - while allowing other commands that don't give the user root shell access or access to commands that can change other users' files. You should give serious consideration to who you allow to use sudo and to what level.
WARNING: Always use the visudo command to edit the sudoers file as it checks your edits for you and tries to save you from the embarrassing situation where a misconfigured file (due to a syntax error) stops you from using sudo to edit any errors.  This is especially true on Debian/Ubuntu and variants where the root account is disabled by default.

A:

There are two commands related to root privileges, SUDO and SU. With SUDO, you don't become another user (including root). SUDO has a pre-defined list of approved commands that it executes on your behalf (this addresses what I asked in the comment about how you give selected users selective privileges). Since you are not becoming root or another user, you just authenticate yourself with your own password.

This is incorrect. The biggest difference between su and sudo is that you enter your own password instead of the target user's password, and that sudo is more flexible. Both of them's whole point is leting you become another user. su can run a specific command and sudo can start an interactive shell, they just have different default modes.
Most commonly you have a group, conventionally named wheel, that is allowed to run any command as any user. Sometimes you want to restrict a user to only run a specific command as a specific user though, and this is what's more flexible about sudo compared to su.

With SU, you actually become root or another user. If you want to become user Bob, you need Bob's password. To become root, you need the root password (which would be defined on a multi-user system).

You can become any user with sudo too, with your own password, provided that the rules in /etc/sudoers are set up to allow you to. sudo lets you restrict the command a user can run tho, yes, and prevents you from having to disclose the passwords of specific users, or even not having a password at all on specific users disallowing regular logins.

If you become root, you have access to everything. Anyone not authorized to access another user's account would not be given the root password and would not have SUDO definitions allowing it.
This all makes sense until you look at something like this link, which is a tutorial for using SUDO -V and then SUDO SU - to become root using only your own password.
If any user can become root without the root password, what mechanism protects user files from unauthorized access?
  First of all, sudo -V prints the version of your sudo binary, and sudo -v validates the cached credentials and are irrelevant to the later part.

Second, sudo su is a rather silly thing to do because there is already a sudo option to start an interactive shell as the specified user (sudo -i), and running one privilege authorization tool (sudo) to run another privilege authorization tool (su) is really silly.
Third, "any user" should definitely NOT be able to become root. If they can your whole system is completely unsecured. the root user is all powerful and can do anything at all, and running a command as root is only one of the uses of sudo, it's a general authorization tool which can let a specific user run a specific command as a specific user.


Q:

android intentを用いて画面遷移するとき同じActivityが開いてしまう

androidでカウンターアプリを作りたいのですが、うまくいきません。
やりたいことは、Mainactivity(Countermain)で「Config」ボタンがおされた時にSubactivity(Newcounter)に移動するということです。(戻る処理はまだ実装していません)
これを実行したところ、intentを使った部分がうまく働いていないことが分かりました。具体的には、Configを押すとCounterconfigが開く予定なのにCountermainが開いてしまいます。Manifestファイルにも登録はしたはずなのですが...
同じ症状になったことがある方や、原因がわかる方ご回答お願いします。
伝わらなかったことや足りないことがあれば答えます。
Androidバージョンは4.X(API19)
eclipseは4.4(たぶん)です
以下ソース

Countermain.java
package countermain.countermain;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Countermain extends Activity implements OnClickListener{   private int mCount;//←カウンターの数字を入れておく変数
   @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.countermain);//c_mainは
    Button btn = (Button)findViewById(R.id.button12);//←button12はConfigキー
    btn.setOnClickListener(this);
}

   @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

   //カウンター部分の処理

   public void plus(View view) {
     mCount++;
     updateCountView();
}

   public void minus(View view) {
    mCount--;
    updateCountView();
}

   public void clear(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst1(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst2(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst3(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst4(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst5(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst6(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst7(View view) {
    mCount = 0;
    updateCountView();
}
   public void btnst8(View view) {
    mCount = 0;
    updateCountView();
}

   public void onClick(View v) {
    Intent intent = new Intent(this,Newcounter.class);//←おかしい部分？
    startActivity(intent);
}
    private void updateCountView() {
    TextView countView = (TextView) findViewById(R.id.textView1);
    countView.setText(String.valueOf(mCount));
    }

countermain.xml

    xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="countermain.countermain.Countermain" >
<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/button2"
    android:layout_alignBottom="@+id/button2"
    android:layout_alignParentRight="true"
    android:layout_marginRight="47dp"
    android:onClick="clear"
    android:text="clear" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/button1"
    android:layout_alignBottom="@+id/button1"
    android:layout_centerHorizontal="true"
    android:onClick="minus"
    android:text="-1" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="42dp"
    android:layout_toLeftOf="@+id/button2"
    android:onClick="plus"
    android:text="+1" />

<Button
    android:id="@+id/button4"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/button1"
    android:layout_marginLeft="15dp"
    android:layout_marginTop="36dp"
    android:onClick="btnst1"
    android:text="Button" />

<Button
    android:id="@+id/button5"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/button4"
    android:layout_alignBottom="@+id/button4"
    android:layout_toRightOf="@+id/button4"
    android:onClick="btnst2"
    android:text="Button" />

<Button
    android:id="@+id/button6"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/button5"
    android:layout_toRightOf="@+id/button5"
    android:onClick="btnst3"
    android:text="Button" />

<Button
    android:id="@+id/button7"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/button6"
    android:layout_toRightOf="@+id/button6"
    android:onClick="btnst4"
    android:text="Button" />

<Button
    android:id="@+id/button8"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/button4"
    android:layout_below="@+id/button4"
    android:onClick="btnst5"
    android:text="Button" />

<Button
    android:id="@+id/button9"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/button8"
    android:layout_toLeftOf="@+id/button6"
    android:onClick="btnst6"
    android:text="Button" />

<Button
    android:id="@+id/button10"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button5"
    android:layout_toRightOf="@+id/button5"
    android:onClick="btnst7"
    android:text="Button" />

<Button
    android:id="@+id/button11"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button7"
    android:layout_alignTop="@+id/button10"
    android:onClick="btnst8"
    android:text="Button" />

<Button
    android:id="@+id/button12"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="config" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button2"
    android:layout_alignTop="@+id/button12"
    android:layout_marginTop="21dp"
    android:text="0"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="90sp" />

CountermainのManifest

    package="countermain.countermain"
    android:versionCode="1"
    android:versionName="1.0" >
<uses-sdk
    android:minSdkVersion="19"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

     <activity
        android:name="Countermain"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
       android:name="Newcounter"
       android:label="@string/app_name"
        >
    </activity>

</application>

Newcounter.java
package countermain.countermain;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import countermain.countermain.R;

public class Newcounter extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.countermain);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}
newcounter.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="config.config.Counterconfig" >
<EditText
    android:id="@+id/EditText02"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/EditText01"
    android:layout_alignBottom="@+id/EditText01"
    android:layout_toRightOf="@+id/EditText01"
    android:ems="10"
    android:inputType="number" />

<EditText
    android:id="@+id/EditText01"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/editText1"
    android:layout_alignBottom="@+id/editText1"
    android:layout_toRightOf="@+id/editText1"
    android:ems="10"
    android:inputType="number" />

<EditText
    android:id="@+id/EditText03"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/EditText02"
    android:layout_alignBottom="@+id/EditText02"
    android:layout_toRightOf="@+id/EditText02"
    android:ems="10"
    android:inputType="number" />

<TextView
    android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/EditText02"
    android:layout_centerVertical="true"
    android:text="ボタン3" />

<TextView
    android:id="@+id/TextView02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/EditText02"
    android:text="ボタン2" />

<TextView
    android:id="@+id/TextView03"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/EditText03"
    android:layout_centerVertical="true"
    android:text="ボタン4" />

<TextView
    android:id="@+id/TextView07"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/EditText03"
    android:layout_below="@+id/EditText03"
    android:layout_marginTop="25dp"
    android:text="ボタン8" />

<TextView
    android:id="@+id/TextView06"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView07"
    android:layout_alignBottom="@+id/TextView07"
    android:layout_alignRight="@+id/EditText01"
    android:text="ボタン6" />

<TextView
    android:id="@+id/TextView05"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView07"
    android:layout_alignBottom="@+id/TextView07"
    android:layout_toLeftOf="@+id/EditText03"
    android:text="ボタン7" />

<TextView
    android:id="@+id/TextView04"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView06"
    android:layout_alignBottom="@+id/TextView06"
    android:layout_toLeftOf="@+id/EditText01"
    android:text="ボタン5" />

<EditText
    android:id="@+id/EditText06"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/TextView04"
    android:layout_toLeftOf="@+id/EditText01"
    android:ems="10"
    android:inputType="number" />

<EditText
    android:id="@+id/EditText07"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/EditText06"
    android:layout_alignBottom="@+id/EditText06"
    android:layout_toLeftOf="@+id/EditText02"
    android:ems="10"
    android:inputType="number" />

<EditText
    android:id="@+id/EditText04"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/EditText07"
    android:layout_alignBottom="@+id/EditText07"
    android:layout_toLeftOf="@+id/EditText03"
    android:ems="10"
    android:inputType="number" />

<EditText
    android:id="@+id/EditText05"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/EditText04"
    android:layout_alignBottom="@+id/EditText04"
    android:layout_alignRight="@+id/TextView07"
    android:ems="10"
    android:inputType="number" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="47dp"
    android:text="ボタンを一回押すごとに     増える数の設定"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView02"
    android:layout_alignBottom="@+id/TextView02"
    android:layout_alignLeft="@+id/textView2"
    android:layout_marginLeft="22dp"
    android:text="ボタン１" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="15dp"
    android:ems="10"
    android:inputType="number" />

A:

NewCounter.javaのビュー設定がcountermain.xmlとなっているためでは？
具体的に言うとNewcounter.javaのonCreate()中の
setContentView(R.layout.countermain);
が
setContentView(R.layout.newcounter);
となっていないためではないでしょうか．


Q:

How is ordering defined for tuples in Rust?

I was looking at the documentation and found an example code that looked unfamiliar.
std::cmp::Reverse - Rust
use std::cmp::Reverse;

let mut v = vec![1, 2, 3, 4, 5, 6];
v.sort_by_key(|&num| (num > 3, Reverse(num)));
assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);

How does (num > 3, Reverse(num)) define ordering between themselves?
I had a look into documentation for tuple, and it said

The sequential nature of the tuple applies to its implementations of various traits. For example, in PartialOrd and Ord, the elements are compared sequentially until the first non-equal set is found.

That makes sense for equality checks, but it seems to me that it does not give explanation for how > and < acts on tuples.
I did some experiments, but understood nothing.
    println!("{}", (5, 5) > (3, 4)); // true
    println!("{}", (2, 2) > (3, 4)); // false
    println!("{}", (2, 5) > (3, 4)); // false
    println!("{}", (3, 5) > (3, 4)); // true
    println!("{}", (5, 2) > (3, 4)); // true

A:

As what you quoted notes, tuples are compared lexicographically.
That is, the first elements of each tuple are compared, then if they're equal the second elements are, then the third, etc.. until a non-equal pair is found and provides the ordering of the tuples. If all pairs are equal then the tuples are, obviously, equal.

println!("{}", (5, 5) > (3, 4)); // true

5 > 3, therefore (5, _) > (3, _)

println!("{}", (2, 2) > (3, 4)); // false

2 < 3, therefore (2, _) < (3, _)

println!("{}", (2, 5) > (3, 4)); // false

see above

println!("{}", (3, 5) > (3, 4)); // true

3 == 3, 5 > 4, therefore (3, 5) > (3, 4)

println!("{}", (5, 2) > (3, 4)); // true

see first case

How does (num > 3, Reverse(num)) define ordering between themselves?

booleans sort false < true, therefore it first orders the elements in two broad categories (numbers below 3 then numbers above 3) then within each category items are ordered based on their reverse natural order (that is, largest-first). Though it obviously does that in a single pass.

A:

You can read the source code of tuple:
impl<$($T:PartialOrd + PartialEq),+> PartialOrd for ($($T,)+)
    where last_type!($($T,)+): ?Sized {
    #[inline]
    fn partial_cmp(&self, other: &($($T,)+)) -> Option<Ordering> {
        lexical_partial_cmp!($(self.$idx, other.$idx),+)
    }
    // ...
    #[inline]
    fn gt(&self, other: &($($T,)+)) -> bool {
        lexical_ord!(gt, $(self.$idx, other.$idx),+)
    }
}

And the lexical_ord macro:
// Constructs an expression that performs a lexical ordering using method $rel.
// The values are interleaved, so the macro invocation for
// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_ord!(lt, a1, b1, a2, b2,
// a3, b3)` (and similarly for `lexical_cmp`)
macro_rules! lexical_ord {
    ($rel: ident, $a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        if $a != $b { lexical_ord!($rel, $a, $b) }
        else { lexical_ord!($rel, $($rest_a, $rest_b),+) }
    };
    ($rel: ident, $a:expr, $b:expr) => { ($a) . $rel (& $b) };
}

So (a, b) > (c, d) will call (a, b).gt(&(c, d)), which will use the lexical_ord macro like this (see comment in the code):
lexical_ord(gt, a, c, b, d)

(Actually, it should be something like lexical_ord(gt, (a, b).0, (c, d).0, (a, b).1, (c, d).1), if I'm reading the macro correctly, but I've simplified it here.)
Which will be translated (at compile-time) to this:
if a != c {
    (a).gt(&c)
} else {
    (b).gt(&d)
}

So the actual code that will be called for (a, b) > (c, d) will be:
fn gt(&self, other: &($T, $T)) -> bool {
    if self.0 != other.0 {
        (self.0).gt(&other.0)  // self.0 > other.0
    } else {
        (self.1).gt(&other.1)  // self.1 > other.1
    }
}

So it's comparing the values in each tuple one-by-one in pairs.


Q:

How to eliminate ReturnUrl from the browser address

Now on unauthorized attempt to access an action my ASP.NET MVC app redirects user to the login page and generates URL shown below:
http://www.mysite.com/Account/Log?ReturnUrl=%2Ftest%2Fsampleaction
So, is there a way to eliminate this string from the URL, but to save it somewhere to be able to redirect user back after login?

A:

I wonder why you would want to do that. Maybe you are sick of misused, excessive URL parameter orgies, and you like the clean RESTful URL style and the elegant way it can be implemented using the new ASP.NET Routing feature.
However, in this case, this is exactly what URL parameters are intended for. It's not bad practice or bad style at all. And there is absolutely no reason to apply SEO witchery to your login page. So why should you make this process less reliable for the user by requiring the session state directly (or indirectly via TempData), or any other workaround?


Q:

Calculation of covariant derivative

In the book "The Ricci flow:techniques and applications: Geometric Aspects" by B. Chow at page 9, there is an equation
$$\Delta(\nabla_if)=\nabla_i(\Delta f)+R_{ik}g^{kl}\nabla_lf.$$
The author said the above equation can be derived from commuting covariant derivatives. But I can not get this equation. Please help me to find the intermediate steps

A:

Commuting covariant derivatives implies
$$\nabla_i\nabla_j(\nabla^kf)=\nabla_j\nabla_i (\nabla^kf)+R^k_{ijl}\nabla^lf$$
Tracing over $k$ and $j$ yields
$$\nabla_i\nabla_j(\nabla^jf)=\nabla_j\nabla_i (\nabla^jf)+R_{il}\nabla^lf$$
This will lead to your result.


Q:

detecting POS tag pattern along with specified words

I need to identify certain POS tags before/after certain specified words, for example the following tagged sentence:
[('This', 'DT'), ('feature', 'NN'), ('would', 'MD'), ('be', 'VB'), ('nice', 'JJ'), ('to', 'TO'), ('have', 'VB')]

can be abstracted to the form "would be" + Adjective
Similarly:
[('I', 'PRP'), ('am', 'VBP'), ('able', 'JJ'), ('to', 'TO'), ('delete', 'VB'), ('the', 'DT'), ('group', 'NN'), ('functionality', 'NN')]

is of the form "am able to" + Verb
How can I go about checking for these type of a pattern in sentences. I am using NLTK.

A:

Assuming you want to check literally for "would" followed by "be", followed by some adjective, you can do this:
def would_be(tagged):
    return any(['would', 'be', 'JJ'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][1]] for i in xrange(len(tagged) - 2))

The input is a POS tagged sentence (list of tuples, as per NLTK).
It checks if there are any three elements in the list such that "would" is next to "be" and "be" is next to a word tagged as an adjective ('JJ'). It will return True as soon as this "pattern" is matched.
You can do something very similar for the second type of sentence:
def am_able_to(tagged):
    return any(['am', 'able', 'to', 'VB'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][0], tagged[i+3][1]] for i in xrange(len(tagged) - 3))

Here's a driver for the program:
s1 = [('This', 'DT'), ('feature', 'NN'), ('would', 'MD'), ('be', 'VB'), ('nice', 'JJ'), ('to', 'TO'), ('have', 'VB')]
s2 = [('I', 'PRP'), ('am', 'VBP'), ('able', 'JJ'), ('to', 'TO'), ('delete', 'VB'), ('the', 'DT'), ('group', 'NN'), ('functionality', 'NN')]

def would_be(tagged):
   return any(['would', 'be', 'JJ'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][1]] for i in xrange(len(tagged) - 2))

def am_able_to(tagged):
    return any(['am', 'able', 'to', 'VB'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][0], tagged[i+3][1]] for i in xrange(len(tagged) - 3))

sent1 = ' '.join(s[0] for s in s1)
sent2 = ' '.join(s[0] for s in s2)

print("Is '{1}' of type 'would be' + adj? {0}".format(would_be(s1), sent1))
print("Is '{1}' of type 'am able to' + verb? {0}".format(am_able_to(s1), sent1))

print("Is '{1}' of type 'would be' + adj? {0}".format(would_be(s2), sent2))
print("Is '{1}' of type 'am able to' + verb? {0}".format(am_able_to(s2), sent2))

This correctly outputs:
Is 'This feature would be nice to have' of type 'would be' + adj? True
Is 'This feature would be nice to have' of type 'am able to' + verb? False
Is 'I am able to delete the group functionality' of type 'would be' + adj? False
Is 'I am able to delete the group functionality' of type 'am able to' + verb? True

If you'd like to generalize this, you can change whether you're checking the literal words or their POS tag.


Q:

How to debug an app on another handset without having access to that handset

I'm making an app for Android in Eclipse. Currently the app works fine on my Droid Incredible, but it does not work at all on my friends' model which I emailed the apk to. Is there a way for me to emulate different phone models to run the app on without physically having them?
Thanks

A:

The short answer is no. The long answer is that emulators are never perfect as they don't simulate the electronics of the devices but the logic in them. You should run automated tests on your device and if possible in physical target devices. There's a service, similar to vnc, i didn't used this service nor do i recommend it, but it exists, it's called deviceanywhere , google it, it offers remote testing on real hardware, but of course it's a paid service.
Another way to test the application is to give a beta version to android forums and get feedback from users, and don't forget to include internal tests and logging.


Q:

Как добавить в div несколько div'ов?

Приветствую!
Подскажите пожалуйста, как добавить в див несколько дивов через перебор.
У меня есть 9 квадратов, в них я пытаюсь добавить 9 пустых дивов, но добавляется только по одному диву в каждый квадрат.
Вот мой код:
var squere = document.body.getElementsByClassName("squere");
for( var i = 0; i < squere.length; i++){
    var div = document.createElement("div");
squere[i].appendChild(div);
}

Буду очень признателен за помощь.
Спасибо!

A:

Для каждого элемента div.squere действие создания дочернего элемента нужно повторить девять раз:
var squere = document.body.getElementsByClassName("squere");
for(var i = 0; i < squere.length; i++) {
  for(var j = 0; j < 9; j++) {
    var div = document.createElement("div");
    squere[i].appendChild(div);
  }
}


Q:

How get window values in Tests with Enzyme, Jest + Create React App

Due to the build process I'm using to push my app out I'm passing some environment variables in a file after build, which works fine. However it breaks my tests with the following error message:
TypeError: Cannot read property 'DATA' of undefined

  57 |   Auth: {
  58 |     oth,
> 59 |
     | ^
  60 |
  61 |     identity: checkEnv(window.env.DATA,
  62 |       process.env.REACT_APP_DATA),

I've tried many solutions but have yet to be able to mock the window.env data, how would I do so?

A:

Create React App allows you to initialize the test environment by including a src/setupTests.js file that "will be automatically executed before running your tests".
Create React App also sets up the testing environment with jsdom which provides the global window object.
You can set window.env in src/setupTests.js and it will be available during your tests:
src/setupTests.js
window.env = {
  DATA: 'hi'
}

src/code.js
export const getData = () => window.env.DATA

src/code.test.js
import { getData } from './code';

test('env', () => {
  expect(getData()).toBe('hi');  // SUCCESS
})


Q:

Cast string data type to Int in SQL QUery for MS Access

I am trying to write a query in access that will pull results that are
in the database in a text
Acually,I have RECEIPTNO Column whose datatype is TEXT in Table Membership, & I want to pull all the results from RECEIPTNO column where RECEIPTNO is BETWEEN 1 AND 10
And I tried Below Code.
SELECT Cint(RECEIPTNO) FROM MEMBERSHIP where Cint(RECEIPTNO) BETWEEN 1 AND 10

Result is: Overflow ,
Any Idea?

A:

Do you want:
SELECT RECEIPTNO FROM MEMBERSHIP
WHERE Val(RECEIPTNO) BETWEEN 1 AND 10

A:

Ohhh I got the answer, & it's working
& the Query Like
SELECT Cint(RECEIPTNO) FROM MEMBERSHIP where RECEIPTNO BETWEEN 1 AND 10