问:
Differential equation; function in Octave
I try to solve a differential equation in Octave. In a first attempt, all my independent variables are set constant (n,y,w). This is my code:

```<code>function xdot= f(x,t);

  % xdot=zeros(1,1);

  X=1.44221E+12;
  IO=5.318E+11;
  GO=6.81E+11;
  beta=0;
  gamma=0;
  y=58.5021088;
  w= 31.29;
  n=1363.5;
  tw=0.4;
  tp=0.3;
  sw=0.07;
  sp=0.25;
  mw=0.593941689;
  mp=0.593941689;

  % aw=(1-tw)(sw+mw)
  % ap=(1-tp)(sp+mp)

  xdot=-(X+IO*(1+gamma*(diff(n)/n+diff(y)/y))+GO*beta(tw(diff(n)/n+diff(w)/w)+tp(diff(y)/y-diff(w)/w)-(x*n)/((y-w)((1-tp)(sp+mp)+tp)+((1-tw)(sw+mw)+tw)*w))*x)/(IO*gamma+GO*beta*tw);

 endfunction
</code>```

When I add

```<code> t = [0:(1/360):10]

 x = lsode ("f", 39290000, t);
</code>```

to solve the equation in the command line, I get this error:

```<code>error: index (0.843942): subscripts must be either integers 1 to (2^31)-1 or logicals
error: lsode: evaluation of user-supplied function failed
error: called from
f at line 23 column 7
</code>```

It seems to me, in some way I misunderstood how to make the function.
Any help?

EDIT:

This is my new code:

```<code>function xdot= f(x,t);

 X=1.44221E+12;
 IO=5.318E+11;
 GO=6.81E+11;
 beta=0;
 gamma=0;
 y=58.5021088;
 w= 31.29;
 n=1363.5;
 tw=0.4;
 tp=0.3;
 sw=0.07;
 sp=0.25;
 mw=0.593941689;
 mp=0.593941689;

 xdot=-X+IO-(x*n)/((y-w)*((1-tp)*(sp+mp)+tp)+w*(tw+(1-tp)*(sp+mp)))

endfunction
</code>```

It does work if I copy it into the command line but if I start it as programm (f.m) and solve it then I get this error:

```<code>error: 'x' undefined near line 25 column 15
error: called from
f at line 25 column 7
</code>```

答:
From the documentation of lsode:

Syntax: [x, istate, msg] = lsode (fcn, x_0, t)

...

The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of right hand sides for the set of equations. The function must have the form

```<code>xdot = f (x, t)
</code>```

in which xdot and x are vectors and t is a scalar.

So firstly, your f function is of the wrong form to the one expected by lsode, since it takes 5 arguments as opposed to 2.

Secondly, inside your f function, the variables y, w, and n are overwritten, regardless of whether they were supplied, whereas t and x need to be supplied by the user.

When lsode calls the handle f, it calls it with two arguments as per its specification, which means it instantiates t and y, and calls the function with the remaining input arguments undefined. Of the remaining arguments, w and n are given values inside the function, as we pointed out above, but x remains undefined. So when you run the final calculation which relies on x, you get an error saying it has not yet been defined during the call to this function.

So, to fix this issue, rewrite your function such that its signature is f(x, t), which you can do so easily since y, w, and n are defined inside your function anyway, so they don't really need to be given as inputs.

Body:
I try to solve a differential equation in Octave. In a first attempt, all my independent variables are set constant (n,y,w). This is my code:

function xdot= f(x,t);

  % xdot=zeros(1,1);

  X=1.44221E+12;
  IO=5.318E+11;
  GO=6.81E+11;
  beta=0;
  gamma=0;
  y=58.5021088;
  w= 31.29;
  n=1363.5;
  tw=0.4;
  tp=0.3;
  sw=0.07;
  sp=0.25;
  mw=0.593941689;
  mp=0.593941689;

  % aw=(1-tw)(sw+mw)
  % ap=(1-tp)(sp+mp)

  xdot=-(X+IO*(1+gamma*(diff(n)/n+diff(y)/y))+GO*beta(tw(diff(n)/n+diff(w)/w)+tp(diff(y)/y-diff(w)/w)-(x*n)/((y-w)((1-tp)(sp+mp)+tp)+((1-tw)(sw+mw)+tw)*w))*x)/(IO*gamma+GO*beta*tw);

 endfunction

When I add

 t = [0:(1/360):10]

 x = lsode ("f", 39290000, t);

to solve the equation in the command line, I get this error:

error: index (0.843942): subscripts must be either integers 1 to (2^31)-1 or logicals
error: lsode: evaluation of user-supplied function failed
error: called from
f at line 23 column 7

It seems to me, in some way I misunderstood how to make the function.
Any help?

EDIT:

This is my new code:

function xdot= f(x,t);

 X=1.44221E+12;
 IO=5.318E+11;
 GO=6.81E+11;
 beta=0;
 gamma=0;
 y=58.5021088;
 w= 31.29;
 n=1363.5;
 tw=0.4;
 tp=0.3;
 sw=0.07;
 sp=0.25;
 mw=0.593941689;
 mp=0.593941689;

 xdot=-X+IO-(x*n)/((y-w)*((1-tp)*(sp+mp)+tp)+w*(tw+(1-tp)*(sp+mp)))

endfunction

It does work if I copy it into the command line but if I start it as programm (f.m) and solve it then I get this error:

error: 'x' undefined near line 25 column 15
error: called from
f at line 25 column 7

Body:
From the documentation of lsode:

Syntax: [x, istate, msg] = lsode (fcn, x_0, t)

...

The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of right hand sides for the set of equations. The function must have the form

xdot = f (x, t)

in which xdot and x are vectors and t is a scalar.

So firstly, your f function is of the wrong form to the one expected by lsode, since it takes 5 arguments as opposed to 2.

Secondly, inside your f function, the variables y, w, and n are overwritten, regardless of whether they were supplied, whereas t and x need to be supplied by the user.

When lsode calls the handle f, it calls it with two arguments as per its specification, which means it instantiates t and y, and calls the function with the remaining input arguments undefined. Of the remaining arguments, w and n are given values inside the function, as we pointed out above, but x remains undefined. So when you run the final calculation which relies on x, you get an error saying it has not yet been defined during the call to this function.

So, to fix this issue, rewrite your function such that its signature is f(x, t), which you can do so easily since y, w, and n are defined inside your function anyway, so they don't really need to be given as inputs.


来源: stackexchange

问:
Multiple canvas layers and mousemove
I'm trying to use a mousemove event on a canvas, inspired from Wayne's answer here, and the corresponding fiddle.

The problem is, I'm working with a code which creates "layered" canvas in the following way:

```<code>  // canvas data layers
  ["marks", "foreground", "brushed", "highlight", "clickable_colors"].forEach(function(layer, i) {
    canvas[layer] = selection
      .append("canvas")
      .attr({
      id: layer, //added an id for easier selecting for mouse event
      class: layer,
      style: "z-index: " + i +10000000
      })[0][0];
    ctx[layer] = canvas[layer].getContext("2d");
  });
</code>```

My goal is to get the color which is on the layer "clickable_colors", and so I adapted the fiddle's script to set the mousemove event on that layer:

```<code>var my_clickable_canvas = document.getElementById('clickable_colors');
var context = my_clickable_canvas.getContext('2d');

context.fillStyle = "rgb(255,0,0)";
context.fillRect(0, 0, 50, 50);
context.fillStyle = "rgb(0,0,255)";
context.fillRect(55, 0, 50, 50);

$("#clickable_colors").mousemove(function(e) {
    debugger;
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    console.log(x)
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data;
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#examplecanvas').html(coord + "<br>" + hex);
    console.log("hi")
});
</code>```

However, the mousemove event isn't triggered at all. I first assumed it had to do with z-index, but giving it the highest value to make sure it's on top didn't solve it.

Does anyone know what might be preventing the event from firing? Or what I should pay attention to, given the "layered" formulation of canvases? Any help appreciated!

EDIT:
Another explanation I found is that the "layered" canvases belong to a parent div element, whereas the working fiddle provides a canvas directly in the body. Could this be preventing the mouse event from working? If so, how to cope with canvases in a div?

EDIT2:
In response to a comment, a simplified and verifiable example is provided in this bl.ocks.
The original code is available here (cf. example file brushing.html). The question is also discussed on the corresponding issue board.

答:
Multy layered canvas mouse events

The best way to approch is the simplest. Create just one mouse handler that listens to document mouse events. Then keep track of the active layer and handle it appropreatly.

The snippet is taken from another answer and adapted to create lines on several layers. Click the layer to select it, then click drag to add lines. Each  layer has its own colour and needs to be selected to modify it.

There is only one mouse handler that listens to the document mouse events, the reset is done in the render code.

const ctx1 = canvas1.getContext("2d");
const ctx2 = canvas2.getContext("2d");
const ctx3 = canvas3.getContext("2d");
const ctx4 = canvas4.getContext("2d");

const Point2 = (x,y) => ({x,y});  // creates a point
const Line = (p1,p2) => ({p1,p2});
const setStyle = (style,ctx) => eachOf(Object.keys(style), key => { ctx[key] = style[key] } );
const eachOf = (array, callback) => {var i = 0; while (i < array.length && callback(array[i],i ++) !== true ); };

const list = {
    items : null,
    add(item) { this.items.push(item); return item },
    eachItem(callback) {
        var i = 0;
        while(i < this.items.length){
             callback(this.items[i],i++);
        }
    }
}
function createList(extend){
    return Object.assign({},list,{items : []},extend);
}
// this will extend the points list
function getClosestPoint(from ,minDist) {
    var closestPoint;
    this.eachItem(point => {
        const dist = Math.hypot(from.x - point.x, from.y - point.y);
        if(dist < minDist){
            closestPoint = point;
            minDist = dist;
        }
    });
    return closestPoint;
}
function distanceLineFromPoint(line,point,points){
    const lx = points.items[line.p1].x;
    const ly = points.items[line.p1].y;
    const v1x = points.items[line.p2].x - lx;
    const v1y = points.items[line.p2].y - ly;
    const v2x = point.x - lx;
    const v2y = point.y - ly;
    // get unit dist of closest point
    const u = (v2x * v1x + v2y * v1y)/(v1y * v1y + v1x * v1x);
    if(u >= 0 && u <= 1){  // is the point on the line
        return Math.hypot(lx + v1x * u - point.x, ly + v1y * u - point.y);
    } else if ( u < 0 ) {  // point is before start
        return Math.hypot(lx - point.x, ly - point.y);
    }
    // point is after end of line
    return Math.hypot(points.items[line.p2].x - point.x, points.items[line.p2].y - point.y);
}
// this will extend the lines list
function getClosestline(from ,minDist) {
    var closestLine;
    this.eachItem(line => {
        const dist = distanceLineFromPoint(line,from,this.points);
        if(dist < minDist){
            closestLine = line;
            minDist = dist;
        }
    });
    return closestLine;
}
function drawPoint(point,ctx){
    ctx.moveTo(point.x,point.y);
    ctx.rect(point.x - 2,point.y - 2, 4,4);
}
function drawLine(line,ctx,points){
    ctx.moveTo(points.items[line.p1].x,points.items[line.p1].y);
    ctx.lineTo(points.items[line.p2].x,points.items[line.p2].y);
}
function drawLines(ctx){ this.eachItem(line => drawLine(line,ctx,this.points)) }
function drawPoints(ctx){this.eachItem(point => drawPoint(point,ctx)) }

const mouse  = {x : 0, y : 0, button : false, drag : false, dragStart : false, dragEnd : false, dragStartX : 0, dragStartY : 0}
function mouseEvents(e){
 mouse.x = e.pageX;
 mouse.y = e.pageY;
 const lb = mouse.button;
 mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
 if(lb !== mouse.button){
  if(mouse.button){
   mouse.drag = true;
   mouse.dragStart = true;
   mouse.dragStartX = mouse.x;
   mouse.dragStartY = mouse.y;
  }else{
   mouse.drag = false;
   mouse.dragEnd = true;
  }
 }
}
["down","up","move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
// short cut vars
var w;
var h;
var cw;  // center
var ch;
var globalTime;
var closestLine;
var closestPoint;
var pointDrag; // true is dragging a point else dragging a line
var dragOffsetX;
var dragOffsetY;
var cursor;
var toolTip;
var helpCount = 0;
const minDist = 20;
var points ;
var lines;
const layers = [{
    lineStyle : { lineWidth : 2, strokeStyle : "green", fillStyle : "Green" },
    pointStyle : { lineWidth : 1, strokeStyle : "green", fillStyle : "Green"},
    font : { fillStyle : "green", font : "18px arial", textAlign : "left"},
    context : ctx1,
    canvas : canvas1,
    points :(points =  createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points }),
    ready : false,
  },{
    lineStyle : { lineWidth : 2, strokeStyle : "blue", fillStyle : "blue" },
    pointStyle : { lineWidth : 1, strokeStyle : "blue", fillStyle : "blue"},
    font : { fillStyle : "blue", font : "18px arial", textAlign : "left"},
    context : ctx2,
    canvas : canvas2,
    points :(points =   createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points}),
    ready : false,
  },{
    lineStyle : { lineWidth : 2, strokeStyle : "gold", fillStyle : "gold" },
    pointStyle : { lineWidth : 1, strokeStyle : "gold", fillStyle : "gold"},
    font : { fillStyle : "gold", font : "18px arial", textAlign : "left"},
    context : ctx3,
    canvas : canvas3,
    points :(points =   createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points}),
    ready : false,
  },{
    lineStyle : { lineWidth : 2, strokeStyle : "aqua", fillStyle : "aqua" },
    pointStyle : { lineWidth : 1, strokeStyle : "aqua", fillStyle : "aqua"},
    font : { fillStyle : "aqua", font : "18px arial", textAlign : "left"},
    context : ctx4,
    canvas : canvas4,
    points : (points =  createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points}),
    ready : false,
  }
];
var currentLayer = 0;
const highlightStyle = {
  lineWidth : 3,
  strokeStyle : "red",
}
const font = {
  font : "18px arial",
  fillStyle : "black",
  textAlign : "center",
}

// main update function
function update(timer){
  if(mouse.button){
    if(mouse.x < 50 && mouse.y < 28 *5){
        mouse.drag=mouse.button=mouse.dragStart = false;
        currentLayer = (mouse.y / 28)|0;
        eachOf(layers,layer=>layer.ready = false);
    }
  }
    const layer = layers[currentLayer];
    const ctx = layer.context;
    const canvas = layer.canvas;
    const lines = layer.lines;
    const points = layer.points;
    const lineStyle = layer.lineStyle;
    const pointStyle = layer.pointStyle;
    cursor = "crosshair";
    toolTip = helpCount < 2 ? "Click drag to create a line" : "";
    globalTime = timer;
    ctx.setTransform(1,0,0,1,0,0); // reset transform
    ctx.globalAlpha = 1;           // reset alpha
 if(w !== innerWidth || h !== innerHeight){
  cw = (w = canvas1.width = innerWidth) / 2;
  ch = (h = canvas1.height = innerHeight) / 2;
    canvas2.height = canvas3.height = canvas4.height = h;
    canvas2.width = canvas3.width = canvas4.width = w;
    eachOf(layers,layer=>layer.ready = false);
 }else{
  ctx.clearRect(0,0,w,h);
 }
  if(mouse.drag=== false){
    if(mouse.x < 50 && mouse.y < 28 *5){
      cursor = "pointer";
      toolTip = "Click to select layer";
      closestPoint = closestLine = undefined;
    }else{

      closestLine = undefined;
      closestPoint = points.getClosest(mouse,minDist);
      if(closestPoint === undefined){
         closestLine = lines.getClosest(mouse,minDist);
      }
      if(closestPoint || closestLine){
         toolTip = "Click drag to move " + (closestPoint ? "point" : "line");
         cursor = "move";
      }
    }
  }
  if(mouse.dragStart){
    if(closestPoint){
      dragOffsetX = closestPoint.x - mouse.x;
      dragOffsetY =  closestPoint.y - mouse.y;
      pointDrag = true;

    }else if( closestLine){
      dragOffsetX = points.items[closestLine.p1].x - mouse.x;
      dragOffsetY = points.items[closestLine.p1].y - mouse.y;
      pointDrag = false;

    } else {
      points.add(Point2(mouse.x,mouse.y));
      closestPoint = points.add(Point2(mouse.x,mouse.y));
      closestLine = lines.add(Line(points.items.length-2,points.items.length-1));
      dragOffsetX = 0;
      dragOffsetY = 0;
      pointDrag = true;
      helpCount += 1;

    }
    mouse.dragStart = false;

  }else if(mouse.drag){
      cursor = 'none';
      if(pointDrag){
        closestPoint.x = mouse.x + dragOffsetX;
        closestPoint.y = mouse.y + dragOffsetY;
      }else{
        const dx = mouse.x- mouse.dragStartX;
        const dy = mouse.y -mouse.dragStartY;
        mouse.dragStartX = mouse.x;
        mouse.dragStartY = mouse.y;
        points.items[closestLine.p1].x +=  dx;
        points.items[closestLine.p1].y +=  dy;
        points.items[closestLine.p2].x +=  dx;
        points.items[closestLine.p2].y +=  dy;
      }
  }else{

  }
  // draw all points and lines
  setStyle(lineStyle,ctx);
  ctx.beginPath();
  lines.draw(ctx);
  ctx.stroke();
  setStyle(pointStyle,ctx);
  ctx.beginPath();
  points.draw(ctx);
  ctx.stroke();

  // draw highlighted point or line
  setStyle(highlightStyle,ctx);
  ctx.beginPath();
  if(closestLine){ drawLine(closestLine,ctx,points) }
  if(closestPoint){ drawPoint(closestPoint, ctx) }

  ctx.stroke();
  eachOf(layers,(layer,i)=>{
    if(!layer.ready){
        const ctx = layer.context;
        ctx.globalAlpha = 0.75;
        ctx.clearRect(0,0,w,h);
        setStyle(layer.lineStyle,ctx);
        ctx.beginPath();
        layer.lines.draw(ctx);
        ctx.stroke();
        setStyle(layer.pointStyle,ctx);
        ctx.beginPath();
        layer.points.draw(ctx);
        ctx.stroke();
        setStyle(layer.font,ctx);
        ctx.fillText("Layer " + (i + 1), 10, i * 28+28);
        layer.ready = true;
        ctx.globalAlpha = 1;
     }
   });

  setStyle(layer.font,ctx);
  ctx.fillText("Layer On" , 10,currentLayer * 28+28);

  if(helpCount < 2){
     setStyle(font,ctx);
     ctx.fillText(toolTip,cw,30);
  }

  canvas4.style.cursor = cursor;
  if(helpCount < 5){
      canvas4.title = toolTip;
  }else{
      canvas4.title = "Click layer to select it";
  }
  requestAnimationFrame(update);
}
requestAnimationFrame(update);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  position : absolute;
  top : 0px;
  left : 0px;
}</code>```

<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
<canvas id="canvas3"></canvas>
<canvas id="canvas4"></canvas>```

ContentLicense: CC BY-SA 3.0

Title: Multiple canvas layers and mousemove

Body:
I'm trying to use a mousemove event on a canvas, inspired from Wayne's answer here, and the corresponding fiddle.

The problem is, I'm working with a code which creates "layered" canvas in the following way:

  // canvas data layers
  ["marks", "foreground", "brushed", "highlight", "clickable_colors"].forEach(function(layer, i) {
    canvas[layer] = selection
      .append("canvas")
      .attr({
      id: layer, //added an id for easier selecting for mouse event
      class: layer,
      style: "z-index: " + i +10000000
      })[0][0];
    ctx[layer] = canvas[layer].getContext("2d");
  });

My goal is to get the color which is on the layer "clickable_colors", and so I adapted the fiddle's script to set the mousemove event on that layer:

var my_clickable_canvas = document.getElementById('clickable_colors');
var context = my_clickable_canvas.getContext('2d');

context.fillStyle = "rgb(255,0,0)";
context.fillRect(0, 0, 50, 50);
context.fillStyle = "rgb(0,0,255)";
context.fillRect(55, 0, 50, 50);

$("#clickable_colors").mousemove(function(e) {
    debugger;
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    console.log(x)
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data;
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#examplecanvas').html(coord + "
" + hex);
    console.log("hi")
});

However, the mousemove event isn't triggered at all. I first assumed it had to do with z-index, but giving it the highest value to make sure it's on top didn't solve it.

Does anyone know what might be preventing the event from firing? Or what I should pay attention to, given the "layered" formulation of canvases? Any help appreciated!

EDIT:
Another explanation I found is that the "layered" canvases belong to a parent div element, whereas the working fiddle provides a canvas directly in the body. Could this be preventing the mouse event from working? If so, how to cope with canvases in a div?

EDIT2:
In response to a comment, a simplified and verifiable example is provided in this bl.ocks.
The original code is available here (cf. example file brushing.html). The question is also discussed on the corresponding issue board.

Body:
Multy layered canvas mouse events

The best way to approch is the simplest. Create just one mouse handler that listens to document mouse events. Then keep track of the active layer and handle it appropreatly.

The snippet is taken from another answer and adapted to create lines on several layers. Click the layer to select it, then click drag to add lines. Each  layer has its own colour and needs to be selected to modify it.

There is only one mouse handler that listens to the document mouse events, the reset is done in the render code.

const ctx1 = canvas1.getContext("2d");
const ctx2 = canvas2.getContext("2d");
const ctx3 = canvas3.getContext("2d");
const ctx4 = canvas4.getContext("2d");

const Point2 = (x,y) => ({x,y});  // creates a point
const Line = (p1,p2) => ({p1,p2});
const setStyle = (style,ctx) => eachOf(Object.keys(style), key => { ctx[key] = style[key] } );
const eachOf = (array, callback) => {var i = 0; while (i < array.length && callback(array[i],i ++) !== true ); };

const list = {
    items : null,
    add(item) { this.items.push(item); return item },
    eachItem(callback) {
        var i = 0;
        while(i < this.items.length){
             callback(this.items[i],i++);
        }
    }
}
function createList(extend){
    return Object.assign({},list,{items : []},extend);
}
// this will extend the points list
function getClosestPoint(from ,minDist) {
    var closestPoint;
    this.eachItem(point => {
        const dist = Math.hypot(from.x - point.x, from.y - point.y);
        if(dist < minDist){
            closestPoint = point;
            minDist = dist;
        }
    });
    return closestPoint;
}
function distanceLineFromPoint(line,point,points){
    const lx = points.items[line.p1].x;
    const ly = points.items[line.p1].y;
    const v1x = points.items[line.p2].x - lx;
    const v1y = points.items[line.p2].y - ly;
    const v2x = point.x - lx;
    const v2y = point.y - ly;
    // get unit dist of closest point
    const u = (v2x * v1x + v2y * v1y)/(v1y * v1y + v1x * v1x);
    if(u >= 0 && u <= 1){  // is the point on the line
        return Math.hypot(lx + v1x * u - point.x, ly + v1y * u - point.y);
    } else if ( u < 0 ) {  // point is before start
        return Math.hypot(lx - point.x, ly - point.y);
    }
    // point is after end of line
    return Math.hypot(points.items[line.p2].x - point.x, points.items[line.p2].y - point.y);
}
// this will extend the lines list
function getClosestline(from ,minDist) {
    var closestLine;
    this.eachItem(line => {
        const dist = distanceLineFromPoint(line,from,this.points);
        if(dist < minDist){
            closestLine = line;
            minDist = dist;
        }
    });
    return closestLine;
}
function drawPoint(point,ctx){
    ctx.moveTo(point.x,point.y);
    ctx.rect(point.x - 2,point.y - 2, 4,4);
}
function drawLine(line,ctx,points){
    ctx.moveTo(points.items[line.p1].x,points.items[line.p1].y);
    ctx.lineTo(points.items[line.p2].x,points.items[line.p2].y);
}
function drawLines(ctx){ this.eachItem(line => drawLine(line,ctx,this.points)) }
function drawPoints(ctx){this.eachItem(point => drawPoint(point,ctx)) }

const mouse  = {x : 0, y : 0, button : false, drag : false, dragStart : false, dragEnd : false, dragStartX : 0, dragStartY : 0}
function mouseEvents(e){
 mouse.x = e.pageX;
 mouse.y = e.pageY;
 const lb = mouse.button;
 mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
 if(lb !== mouse.button){
  if(mouse.button){
   mouse.drag = true;
   mouse.dragStart = true;
   mouse.dragStartX = mouse.x;
   mouse.dragStartY = mouse.y;
  }else{
   mouse.drag = false;
   mouse.dragEnd = true;
  }
 }
}
["down","up","move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
// short cut vars
var w;
var h;
var cw;  // center
var ch;
var globalTime;
var closestLine;
var closestPoint;
var pointDrag; // true is dragging a point else dragging a line
var dragOffsetX;
var dragOffsetY;
var cursor;
var toolTip;
var helpCount = 0;
const minDist = 20;
var points ;
var lines;
const layers = [{
    lineStyle : { lineWidth : 2, strokeStyle : "green", fillStyle : "Green" },
    pointStyle : { lineWidth : 1, strokeStyle : "green", fillStyle : "Green"},
    font : { fillStyle : "green", font : "18px arial", textAlign : "left"},
    context : ctx1,
    canvas : canvas1,
    points :(points =  createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points }),
    ready : false,
  },{
    lineStyle : { lineWidth : 2, strokeStyle : "blue", fillStyle : "blue" },
    pointStyle : { lineWidth : 1, strokeStyle : "blue", fillStyle : "blue"},
    font : { fillStyle : "blue", font : "18px arial", textAlign : "left"},
    context : ctx2,
    canvas : canvas2,
    points :(points =   createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points}),
    ready : false,
  },{
    lineStyle : { lineWidth : 2, strokeStyle : "gold", fillStyle : "gold" },
    pointStyle : { lineWidth : 1, strokeStyle : "gold", fillStyle : "gold"},
    font : { fillStyle : "gold", font : "18px arial", textAlign : "left"},
    context : ctx3,
    canvas : canvas3,
    points :(points =   createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points}),
    ready : false,
  },{
    lineStyle : { lineWidth : 2, strokeStyle : "aqua", fillStyle : "aqua" },
    pointStyle : { lineWidth : 1, strokeStyle : "aqua", fillStyle : "aqua"},
    font : { fillStyle : "aqua", font : "18px arial", textAlign : "left"},
    context : ctx4,
    canvas : canvas4,
    points : (points =  createList({ getClosest : getClosestPoint,draw : drawPoints})),
    lines : createList({getClosest : getClosestline, draw : drawLines, points : points}),
    ready : false,
  }
];
var currentLayer = 0;
const highlightStyle = {
  lineWidth : 3,
  strokeStyle : "red",
}
const font = {
  font : "18px arial",
  fillStyle : "black",
  textAlign : "center",
}

// main update function
function update(timer){
  if(mouse.button){
    if(mouse.x < 50 && mouse.y < 28 *5){
        mouse.drag=mouse.button=mouse.dragStart = false;
        currentLayer = (mouse.y / 28)|0;
        eachOf(layers,layer=>layer.ready = false);
    }
  }
    const layer = layers[currentLayer];
    const ctx = layer.context;
    const canvas = layer.canvas;
    const lines = layer.lines;
    const points = layer.points;
    const lineStyle = layer.lineStyle;
    const pointStyle = layer.pointStyle;
    cursor = "crosshair";
    toolTip = helpCount < 2 ? "Click drag to create a line" : "";
    globalTime = timer;
    ctx.setTransform(1,0,0,1,0,0); // reset transform
    ctx.globalAlpha = 1;           // reset alpha
 if(w !== innerWidth || h !== innerHeight){
  cw = (w = canvas1.width = innerWidth) / 2;
  ch = (h = canvas1.height = innerHeight) / 2;
    canvas2.height = canvas3.height = canvas4.height = h;
    canvas2.width = canvas3.width = canvas4.width = w;
    eachOf(layers,layer=>layer.ready = false);
 }else{
  ctx.clearRect(0,0,w,h);
 }
  if(mouse.drag=== false){
    if(mouse.x < 50 && mouse.y < 28 *5){
      cursor = "pointer";
      toolTip = "Click to select layer";
      closestPoint = closestLine = undefined;
    }else{

      closestLine = undefined;
      closestPoint = points.getClosest(mouse,minDist);
      if(closestPoint === undefined){
         closestLine = lines.getClosest(mouse,minDist);
      }
      if(closestPoint || closestLine){
         toolTip = "Click drag to move " + (closestPoint ? "point" : "line");
         cursor = "move";
      }
    }
  }
  if(mouse.dragStart){
    if(closestPoint){
      dragOffsetX = closestPoint.x - mouse.x;
      dragOffsetY =  closestPoint.y - mouse.y;
      pointDrag = true;

    }else if( closestLine){
      dragOffsetX = points.items[closestLine.p1].x - mouse.x;
      dragOffsetY = points.items[closestLine.p1].y - mouse.y;
      pointDrag = false;

    } else {
      points.add(Point2(mouse.x,mouse.y));
      closestPoint = points.add(Point2(mouse.x,mouse.y));
      closestLine = lines.add(Line(points.items.length-2,points.items.length-1));
      dragOffsetX = 0;
      dragOffsetY = 0;
      pointDrag = true;
      helpCount += 1;

    }
    mouse.dragStart = false;

  }else if(mouse.drag){
      cursor = 'none';
      if(pointDrag){
        closestPoint.x = mouse.x + dragOffsetX;
        closestPoint.y = mouse.y + dragOffsetY;
      }else{
        const dx = mouse.x- mouse.dragStartX;
        const dy = mouse.y -mouse.dragStartY;
        mouse.dragStartX = mouse.x;
        mouse.dragStartY = mouse.y;
        points.items[closestLine.p1].x +=  dx;
        points.items[closestLine.p1].y +=  dy;
        points.items[closestLine.p2].x +=  dx;
        points.items[closestLine.p2].y +=  dy;
      }
  }else{

  }
  // draw all points and lines
  setStyle(lineStyle,ctx);
  ctx.beginPath();
  lines.draw(ctx);
  ctx.stroke();
  setStyle(pointStyle,ctx);
  ctx.beginPath();
  points.draw(ctx);
  ctx.stroke();

  // draw highlighted point or line
  setStyle(highlightStyle,ctx);
  ctx.beginPath();
  if(closestLine){ drawLine(closestLine,ctx,points) }
  if(closestPoint){ drawPoint(closestPoint, ctx) }

  ctx.stroke();
  eachOf(layers,(layer,i)=>{
    if(!layer.ready){
        const ctx = layer.context;
        ctx.globalAlpha = 0.75;
        ctx.clearRect(0,0,w,h);
        setStyle(layer.lineStyle,ctx);
        ctx.beginPath();
        layer.lines.draw(ctx);
        ctx.stroke();
        setStyle(layer.pointStyle,ctx);
        ctx.beginPath();
        layer.points.draw(ctx);
        ctx.stroke();
        setStyle(layer.font,ctx);
        ctx.fillText("Layer " + (i + 1), 10, i * 28+28);
        layer.ready = true;
        ctx.globalAlpha = 1;
     }
   });

  setStyle(layer.font,ctx);
  ctx.fillText("Layer On" , 10,currentLayer * 28+28);

  if(helpCount < 2){
     setStyle(font,ctx);
     ctx.fillText(toolTip,cw,30);
  }

  canvas4.style.cursor = cursor;
  if(helpCount < 5){
      canvas4.title = toolTip;
  }else{
      canvas4.title = "Click layer to select it";
  }
  requestAnimationFrame(update);
}
requestAnimationFrame(update);

canvas {
  position : absolute;
  top : 0px;
  left : 0px;
}

<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
<canvas id="canvas3"></canvas>
<canvas id="canvas4"></canvas>


问:
Activation functions - Neural Network
I am working with neural network in my freetime.
I developed already an easy XOR-Operation with a neural network.
But I dont know when I should use the correct activations function.

Is there an trick or is it just math logic?

答:
There are a lot of options of activation functions such as identity, logistic, tanh, Relu, etc.
The choice of the activation function can be based on the gradient computation (back-propagation). E.g. logistic function is always differentiable but it kind of saturate when the input has large value and therefore slows down the speed of optimization. In this case Relu is prefered over logistic.
Above is only one simple example for the choise of activation function. It really depends on the actual situation.
Besides, I dont think the activation functions used in XOR neural network is representative in more complex application. </p>

ContentLicense: CC BY-SA 4.0

Title: Activation functions - Neural Network


问:
How to sort matrix column values then rows?
For example this matrix:

```<code>3 2
2 2
1 2
</code>```

Writed as this:

```<code>IEnumerable<IEnumerable<int>> inputRows = ...;
</code>```

Must become:

```<code>1 2
2 2
2 3
</code>```

So, all biggest numbers will be concentrated in the down right corner.
First, I need to sort column numbers (not entire columns), which is pretty easy to do:

```<code>var result = inputRows.Select(x=> x.OrderBy(y=>y));
</code>```

After this step matrix will become:

```<code>2 3
2 2
1 2
</code>```

But how do I sort out entire rows with LINQ?

PS Im not interested in fixed arrays solutions.

答:
Maybe this?

```<code>var result = inputRows.Select(row => row.OrderBy(col => col)).OrderBy(row => row.Sum());
</code>```

It's not clear how do you want order rows: by the whole row or by each cell?

Body:
For example this matrix:

3 2
2 2
1 2

Writed as this:

IEnumerable<IEnumerable<int>> inputRows = ...;

Must become:

1 2
2 2
2 3

So, all biggest numbers will be concentrated in the down right corner.
First, I need to sort column numbers (not entire columns), which is pretty easy to do:

var result = inputRows.Select(x=> x.OrderBy(y=>y));

After this step matrix will become:

2 3
2 2
1 2

But how do I sort out entire rows with LINQ?

PS Im not interested in fixed arrays solutions.

Body:
Maybe this?

var result = inputRows.Select(row => row.OrderBy(col => col)).OrderBy(row => row.Sum());

It's not clear how do you want order rows: by the whole row or by each cell?


问:
PHP - Random round behavior issue
I am actually facing a big problem with several websites (actually 3) based on Prestashop. The problem is that PHP or Prestashop randomly rounds prices to the nearest integer and it is not systematic.

Most of the time, it works perfectly, as it should, but sometimes (it can takes weeks or months between two problems), a price is rounded. My round mode option is correctly set to display two decimals.

The problem can occur when editing a product price in the back-office or when the customer is at the checkout step.

I tried to reproduce the problem, so I created a basic test: I retrieve a cart information and I display its price. I refreshed the page many times and I saw the price rounded a few times only. The most intriguous thing is that neither the context nor the code have changed between the beginning and the ending of the test.

I searched for help on Google and no one seemed to have this problem...

Did someone encounter this problem? Do you think it is a PHP issue or a Prestashop one? Thanks in advance for your help.

Here is the code of the round function Prestashop is using:

```<code>round($value, 2, PHP_ROUND_HALF_UP);
</code>```

For information, the version of PHP 5.4.39.

答:
There might be issues with locales. In german for example thousands separators and decimal points are the other way around. If you are not very careful handling those you might store wrong values in some persistence or break some value when casting it to float. Remember - when calculation with strings (eg: "2.55") php will cast them to float, handling german numbers ("2,55") will result in the wrong floating point number.

```<code>(float) "2.55" = 2.55
(float) "2,55" = 2
</code>```

The issue can be fixed by configuring the locales correctly.

If you are able to tell a wrong result from a valid automatically, you might want to log the debug_backtrace at that point to evaluate the programs flow in that case.

Title: PHP - Random round behavior issue

Body:
I am actually facing a big problem with several websites (actually 3) based on Prestashop. The problem is that PHP or Prestashop randomly rounds prices to the nearest integer and it is not systematic.

Most of the time, it works perfectly, as it should, but sometimes (it can takes weeks or months between two problems), a price is rounded. My round mode option is correctly set to display two decimals.

The problem can occur when editing a product price in the back-office or when the customer is at the checkout step.

I tried to reproduce the problem, so I created a basic test: I retrieve a cart information and I display its price. I refreshed the page many times and I saw the price rounded a few times only. The most intriguous thing is that neither the context nor the code have changed between the beginning and the ending of the test.

I searched for help on Google and no one seemed to have this problem...

Did someone encounter this problem? Do you think it is a PHP issue or a Prestashop one? Thanks in advance for your help.

Here is the code of the round function Prestashop is using:

round($value, 2, PHP_ROUND_HALF_UP);

For information, the version of PHP 5.4.39.

Body:
There might be issues with locales. In german for example thousands separators and decimal points are the other way around. If you are not very careful handling those you might store wrong values in some persistence or break some value when casting it to float. Remember - when calculation with strings (eg: "2.55") php will cast them to float, handling german numbers ("2,55") will result in the wrong floating point number.

(float) "2.55" = 2.55
(float) "2,55" = 2

The issue can be fixed by configuring the locales correctly.

If you are able to tell a wrong result from a valid automatically, you might want to log the debug_backtrace at that point to evaluate the programs flow in that case.


问:
can i run multiple instance of logstash in the same server?
I want to get RSS feed from five news website with RSS logstash input plugin and as well tweet of twitter with twitter plugin I create one logstash config file for RSS and one for twitter. my question is, can I run multiple instance of logstash by this command bin/logstash -f first_config.conf and bin/logstash -f second_config.conf if I do, will I face with bottleneck problem ?

答:
You want to run "Multiple Pipelines".
If you need to run more than one pipeline in the same process, Logstash provides a way to do this through a configuration file called pipelines.yml. See docs in the link.</p>


问:
How to return a list of serializable XML elements
I know how to make function return a "pretty" result as xml, and I want just that, but without the extra parent element.

Using this function

```<code>[HttpGet]
public XElement MyFunction() { ... }
</code>```

gets me half way. I get this:

```<code><Result>
    <row>
        <cell>...</cell>
        <cell>...</cell>
        <cell>...</cell>
    </row>
    <row>
        <cell>...</cell>
        <cell>...</cell>
        <cell>...</cell>
    </row>
</Result>
</code>```

I want result like this:

```<code><row>
    <cell>...</cell>
    <cell>...</cell>
    <cell>...</cell>
</row>
<row>
    <cell>...</cell>
    <cell>...</cell>
    <cell>...</cell>
</row>
</code>```

And using function like this:

```<code>[HttpGet]
public IEnumerable<XElement> MyFunction() { ... }
</code>```

Gets me a result like this:

```<code><ArrayOfXElement
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/System.Xml.Linq">
    <XElement>
        <row xmlns="">
            <cell>...</cell>
            <cell>...</cell>
            <cell>...</cell>
        </row>
    </XElement>
    <XElement>
        <row xmlns="">
            <cell>...</cell>
            <cell>...</cell>
            <cell>...</cell>
        </row>
    </XElement>
    etc...
</code>```

Which is, I mean... look at it... its hideous.

I beleave that there must be a simple solution to this, or at least a workaround.

EDIT As @Fabio suggested in the first comment, XML is invalid if it has no root element, and thus, this question becomes silly, since I do need other systems to be able to read the result of my functions. Even so, I will not remove this question, because I hope that somebody else who needs a solution like this will, like me, realise that that kind of XML document is invalid. Also, if anyone answers the question, I will approve the answer.

答:
get a reader and get the innerXml. This should get you what you need. </p>

```<code>   var MainElement= XElementA.CreateReader();
    MainElement.MoveToContent();

    var Content=MainElement.ReadInnerXml();
</code>```

Body:
I know how to make function return a "pretty" result as xml, and I want just that, but without the extra parent element.

Using this function

[HttpGet]
public XElement MyFunction() { ... }

gets me half way. I get this:

<Result>
    <row>
        <cell>...</cell>
        <cell>...</cell>
        <cell>...</cell>
    </row>
    <row>
        <cell>...</cell>
        <cell>...</cell>
        <cell>...</cell>
    </row>
</Result>

I want result like this:

<row>
    <cell>...</cell>
    <cell>...</cell>
    <cell>...</cell>
</row>
<row>
    <cell>...</cell>
    <cell>...</cell>
    <cell>...</cell>
</row>

And using function like this:

[HttpGet]
public IEnumerable<XElement> MyFunction() { ... }

Gets me a result like this:

<ArrayOfXElement
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/System.Xml.Linq">
    <XElement>
        <row xmlns="">
            <cell>...</cell>
            <cell>...</cell>
            <cell>...</cell>
        </row>
    </XElement>
    <XElement>
        <row xmlns="">
            <cell>...</cell>
            <cell>...</cell>
            <cell>...</cell>
        </row>
    </XElement>
    etc...

Which is, I mean... look at it... its hideous.

I beleave that there must be a simple solution to this, or at least a workaround.

EDIT As @Fabio suggested in the first comment, XML is invalid if it has no root element, and thus, this question becomes silly, since I do need other systems to be able to read the result of my functions. Even so, I will not remove this question, because I hope that somebody else who needs a solution like this will, like me, realise that that kind of XML document is invalid. Also, if anyone answers the question, I will approve the answer.

Body:
get a reader and get the innerXml. This should get you what you need.

   var MainElement= XElementA.CreateReader();
    MainElement.MoveToContent();

    var Content=MainElement.ReadInnerXml();


问:
postgresql schemas conflict
I created new database named test1, new user test1_user and i granted all on database test1 to test1_user. Moreover, I created schema test1_user. Now, I also created new schema functions_package and its owner is test1_user.

my code :

```<code>CREATE OR REPLACE FUNCTION functions_package.newFunction(file_id
utl_file.file_type) RETURNS VOID AS $body$
 BEGIN
 functions_package.old_function1(file_id);
 functions_package.old_function2(file_id);
 functions_package.old_function3(file_id);

 End;
 --
 $body$
 LANGUAGE PLPGSQL
 SECURITY DEFINER
 STABLE;
</code>```

I created few functions under schema functions_package and now I`m trying to create new function that uses the old functions but im getting eror :

```<code>ERROR:  syntax error at or near "functions_package"
LINE 3:    functions_package.old_function('aa');
</code>```

IM trying to create the new function from user test1_user;
Im getting this error for every function in schema functions_package that i`m trying to summon in my new function. In all the old function I didnt summon any function at all so i didnt have this kind of error.
Some help ?

答:
you lack select before function name:
try:

```<code>CREATE OR REPLACE FUNCTION functions_package.newFunction(file_id
utl_file.file_type) RETURNS VOID AS $body$
 BEGIN
 perform functions_package.old_function1(file_id);
 perform functions_package.old_function2(file_id);
 perform functions_package.old_function3(file_id);

 End;
 --
 $body$
 LANGUAGE PLPGSQL
 SECURITY DEFINER
 STABLE;
</code>```

Title: postgresql schemas conflict

Body:
I created new database named test1, new user test1_user and i granted all on database test1 to test1_user. Moreover, I created schema test1_user. Now, I also created new schema functions_package and its owner is test1_user.

my code :

CREATE OR REPLACE FUNCTION functions_package.newFunction(file_id
utl_file.file_type) RETURNS VOID AS $body$
 BEGIN
 functions_package.old_function1(file_id);
 functions_package.old_function2(file_id);
 functions_package.old_function3(file_id);

 End;
 --
 $body$
 LANGUAGE PLPGSQL
 SECURITY DEFINER
 STABLE;

I created few functions under schema functions_package and now I`m trying to create new function that uses the old functions but im getting eror :

ERROR:  syntax error at or near "functions_package"
LINE 3:    functions_package.old_function('aa');

IM trying to create the new function from user test1_user;
Im getting this error for every function in schema functions_package that i`m trying to summon in my new function. In all the old function I didnt summon any function at all so i didnt have this kind of error.
Some help ?

Body:
you lack select before function name:
try:

CREATE OR REPLACE FUNCTION functions_package.newFunction(file_id
utl_file.file_type) RETURNS VOID AS $body$
 BEGIN
 perform functions_package.old_function1(file_id);
 perform functions_package.old_function2(file_id);
 perform functions_package.old_function3(file_id);

 End;
 --
 $body$
 LANGUAGE PLPGSQL
 SECURITY DEFINER
 STABLE;


问:
Express get requests
I am making a site with angular 4, express and mongo. It is my first site and I am not really sure how to use get requests. I know that they are for requesting data from the server. So i used them for my request to the database. The problem with that is if the user is on the localhost:3000/games/1 if he refreshes the page he does not recieve the site. Instead he recieves only the info from the database. How do i fix this? Any help would be appreaciated.

```<code>this.Router
  .get("/games/:id", (req, res) => this.controller.getAll(req, res))
  .get("/*", this.controller.getSite);
</code>```

Above is an expmple of my problem if i am on games/:id and i refresh i only get the db info and not the webpage

答: Always keep the URLs of API and Views different, for example if user visits example.com/games/1 to view the webpage than the API to get the data should not be same, keep it something like example.com/api/games/1 which would resolve this issue.

Title: Express get requests

Body:
I am making a site with angular 4, express and mongo. It is my first site and I am not really sure how to use get requests. I know that they are for requesting data from the server. So i used them for my request to the database. The problem with that is if the user is on the localhost:3000/games/1 if he refreshes the page he does not recieve the site. Instead he recieves only the info from the database. How do i fix this? Any help would be appreaciated.

this.Router
  .get("/games/:id", (req, res) => this.controller.getAll(req, res))
  .get("/*", this.controller.getSite);

Above is an expmple of my problem if i am on games/:id and i refresh i only get the db info and not the webpage


问:
JSQMessageViewController customize send button
I'm building an messaging app, I use JSQMessageViewController to render messages and it's awesome.
Now I have a little problem trying to customize the send button:

Basically I want to replace left and right BarButtonItem to customized button with images.
After some hours of reading and searching, I got this far now:

button without text

button with text

As shown in the pictures, the voice button which is replacing the original send button is disabled if there is no text in the textField, this behavior is not what I want. How do I disable this behavior and make the button available all the time?

And this is how I customize the send button:

```<code>  UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [rightButton setBackgroundImage:[UIImage imageNamed:@"AudioButton@2x.png"] forState:UIControlStateNormal];
  self.inputToolbar.contentView.rightBarButtonItem = rightButton;
</code>```

答:
this will work if you are replacing your custom button in rightBarButtonItem

add this in viewDidAppear

```<code>[self.inputToolbar.contentView.rightBarButtonItem setEnabled:YES];
</code>```

and override textview delegate

```<code>-(void)textViewDidChange:(UITextView *)textView;
</code>```

Body:
I'm building an messaging app, I use JSQMessageViewController to render messages and it's awesome.
Now I have a little problem trying to customize the send button:

Basically I want to replace left and right BarButtonItem to customized button with images.
After some hours of reading and searching, I got this far now:

button without text

button with text

As shown in the pictures, the voice button which is replacing the original send button is disabled if there is no text in the textField, this behavior is not what I want. How do I disable this behavior and make the button available all the time?

And this is how I customize the send button:

  UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [rightButton setBackgroundImage:[UIImage imageNamed:@"AudioButton@2x.png"] forState:UIControlStateNormal];
  self.inputToolbar.contentView.rightBarButtonItem = rightButton;

Body:
this will work if you are replacing your custom button in rightBarButtonItem

add this in viewDidAppear

[self.inputToolbar.contentView.rightBarButtonItem setEnabled:YES];

and override textview delegate

-(void)textViewDidChange:(UITextView *)textView;


问:
How to add
 to wordpress widget title?
I'm trying to add
 code to widget titles in Wordpress, as most of my widget's titles are on two lines, and I would like to format the text so it makes more sense to the reader.

I've tried a few different suggested solutions, including adding various code to the Functions file:

```<code>    add_filter('widget_title', 'change_widget_title', 10, 3);
    function change_widget_title($title, $instance, $wid){
    return $title = str_replace('Widget Title', '<span style="color: red">Custom</span>', $title);
    }
</code>```

That didn't work for me unfortunately.

Nor did #4 on this page:
http://www.rvamedia.com/wordpress/customize-wordpress-widget-title

I don't even need the title to link to anything, I just want to put in a
 so it'll show properly on two lines.

Any help would be greatly appreciated.

答:
I know its a little late for the answer but may be it will help others
Its very simple, You can get help from shortcode by

```<code>    add_filter('widget_title', 'do_shortcode');

function line_break() {
    return '<br />';
}

add_shortcode('br', 'line_break');
</code>```

Put this in your functions.php file at the end than use
 as shortcode i.e. br

Title: How to add <br /> to wordpress widget title?

Body:
I'm trying to add
 code to widget titles in Wordpress, as most of my widget's titles are on two lines, and I would like to format the text so it makes more sense to the reader.

I've tried a few different suggested solutions, including adding various code to the Functions file:

    add_filter('widget_title', 'change_widget_title', 10, 3);
    function change_widget_title($title, $instance, $wid){
    return $title = str_replace('Widget Title', 'Custom', $title);
    }

That didn't work for me unfortunately.

Nor did #4 on this page:
http://www.rvamedia.com/wordpress/customize-wordpress-widget-title

I don't even need the title to link to anything, I just want to put in a
 so it'll show properly on two lines.

Any help would be greatly appreciated.

Body:
I know its a little late for the answer but may be it will help others
Its very simple, You can get help from shortcode by

    add_filter('widget_title', 'do_shortcode');

function line_break() {
    return '<br />';
}

add_shortcode('br', 'line_break');

Put this in your functions.php file at the end than use <br/> as shortcode i.e. br


问:
Unable to load a JSON file from google cloud storage to bigquery using python
I am attempting to export a file from my Google cloud storage to Google bigquery but am running into numerous problems.

```<code>#standardSQL
import json
import argparse
import time
import uuid

from google.cloud import bigquery
from google.cloud import storage

dataset = 'dataworks-356fa'
source = 'gs://dataworks-356fa-backups/pullnupload.json'

def load_data_from_gcs(dataset, test10, source ):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table(test10)
    job_name = str(uuid.uuid4())

    job= bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/pullnupload.json")
    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()

    # wait_for_job(job)
    print("state of job is: " + job.state)
#     print("errors: " + job.errors)

load_data_from_gcs(dataset, 'test10', source)
</code>```

When the wait_for_job(job) line is not commented out I receive this error

```<code>Traceback (most recent call last):
File "cloudtobq.py", line 42, in <module>
load_data_from_gcs(dataset, 'test10', source)
File "cloudtobq.py", line 38, in load_data_from_gcs
wait_for_job(job)
NameError: global name 'wait_for_job' is not defined
</code>```

And when print("errors: " + job.errors) is not commented out I receive this error.

```<code>Traceback (most recent call last):
File "cloudtobq.py", line 42, in <module>
load_data_from_gcs(dataset, 'test10', source)
File "cloudtobq.py", line 40, in load_data_from_gcs
print("errors: " + job.errors)
TypeError: cannot concatenate 'str' and 'NoneType' objects
</code>```

When both are commented out this is what I receive and then being returned to the original terminal screen.

```<code>Wess-MacBook-Pro:desktop wesstephens$ python cloudtobq.py
state of job is: RUNNING
Wess-MacBook-Pro:desktop wesstephens$
</code>```

答:
You need to include the definition of the function from the documentation sample code:

```<code>def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
        time.sleep(1)
</code>```

You don't need to print job.errors, since wait_for_job will raise an exception if the job was unsuccessful.

Body:
I am attempting to export a file from my Google cloud storage to Google bigquery but am running into numerous problems.

#standardSQL
import json
import argparse
import time
import uuid

from google.cloud import bigquery
from google.cloud import storage

dataset = 'dataworks-356fa'
source = 'gs://dataworks-356fa-backups/pullnupload.json'

def load_data_from_gcs(dataset, test10, source ):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table(test10)
    job_name = str(uuid.uuid4())

    job= bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/pullnupload.json")
    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()

    # wait_for_job(job)
    print("state of job is: " + job.state)
#     print("errors: " + job.errors)

load_data_from_gcs(dataset, 'test10', source)

When the wait_for_job(job) line is not commented out I receive this error

Traceback (most recent call last):
File "cloudtobq.py", line 42, in <module>
load_data_from_gcs(dataset, 'test10', source)
File "cloudtobq.py", line 38, in load_data_from_gcs
wait_for_job(job)
NameError: global name 'wait_for_job' is not defined

And when print("errors: " + job.errors) is not commented out I receive this error.

Traceback (most recent call last):
File "cloudtobq.py", line 42, in <module>
load_data_from_gcs(dataset, 'test10', source)
File "cloudtobq.py", line 40, in load_data_from_gcs
print("errors: " + job.errors)
TypeError: cannot concatenate 'str' and 'NoneType' objects

When both are commented out this is what I receive and then being returned to the original terminal screen.

Wess-MacBook-Pro:desktop wesstephens$ python cloudtobq.py
state of job is: RUNNING
Wess-MacBook-Pro:desktop wesstephens$

Body:
You need to include the definition of the function from the documentation sample code:

def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
        time.sleep(1)

You don't need to print job.errors, since wait_for_job will raise an exception if the job was unsuccessful.


问:
How does Intellij deploy to JBoss?
I finally have my application in IntelliJ and deploying to JBoss. I'd like to get hot deploy working but it looks like I need to understand how IntelliJ and JBoss interact.

When I build my project in IntelliJ and then start JBoss, the ear file does not appear in the deploy directory so I assume that there is some magic that IntelliJ does so that JBoss reads from a different folder. What is happening during this step?

Thanks :)

答:
Please refer to the documentation.

Basically, you need an exploded Artifact configuration with the directory name ending with .ear.

Build | Make performs hot deployment as well as Update action (which is configurable and can update only resources, resources and classes, optionally redeploy or restart the server).

Instead of copying your application to JBoss, IDEA runs it with appropriate parameters so that it uses Artifact directory instead. Configuration is very flexible and you can just change the artifact directory location to reside under JBoss directory.

ContentLicense: CC BY-SA 2.5

Title: How does Intellij deploy to JBoss?


问:
Using Jdbc Template with DataSourceUtils.getConnection method
I am not sure below is the correct way to manage a db connectivity in a connection pooled environment using Jdbc template with DataSourceUtils.getConnection.

What I have done:

We are using apache dbcp for connection pooling.In Spring appconfig configured connection pooling and Jdbc template as shown below

<bean id="dbName"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${oracle.driver}" />
    <property name="url" value="${xxxx.oracle.url}" />
    <property name="username" value="${xxxx.oracle.username}" />
    <property name="password" value="${xxxx.oracle.password}" />
    <property name="minIdle" value="1" />
</bean>
<bean id="jdbcTemplateUib"
class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dbName" />
</bean>

In DAOImpl, inside the method we have to invoke a stored procedure with custom SQL data types. Hence we are required to get connection object for the same. We are getting the connection as follows :

this.connection =
DataSourceUtils.getConnection(jdbcTemplate.getDataSource());

where DataSourceUtils is a Spring implementation described here.

The above configuration is working fine in local but we are bit worried on the following aspects of this program:

If we access connection in this manner will it override the connection pooling mechanism in appconfig file?

As per documnetation here, DataSourceUtils.getConnection(DataSource dataSource) will reuse existing connection. So I am assuming this will not break any connection created via JdbcTemplate and dbcp objects.

No need of explicitly releasing this connection since it is managed by the jdbcTemplate.

I am not quite sure on the above mentioned items. Need some expert opinion.

答:
I would recommend using the JdbcTemplate#execute(ConnectionCallback action) method. That allows you access to the connection while still taking advantage of Spring's resource and exception management features. You just need to implement the doInConnection callback method.

```<code>jdbcTemplate.execute(new ConnectionCallback<Object>() {
    @Override
    public Object doInConnection(Connection connection)
            throws SQLException, DataAccessException {

         // do your processing here

        return null;
    }
});
</code>```

Body:
I would recommend using the JdbcTemplate#execute(ConnectionCallback action) method. That allows you access to the connection while still taking advantage of Spring's resource and exception management features. You just need to implement the doInConnection callback method.

jdbcTemplate.execute(new ConnectionCallback<Object>() {
    @Override
    public Object doInConnection(Connection connection)
            throws SQLException, DataAccessException {

         // do your processing here

        return null;
    }
});


问:
javascript help me fix my first hands on code
help me fix this, simple convert to roman numerals code. with two input box, first where i input a number, 2nd box where the result will be shown. and a submit button

result wont show up on 2nd box after hitting convert/submit button

js code:

    function toRoman(){
 var num = document.getElementById('num').value;
 var result = "";
 var db = { 'M':1000, 'CM':900,'D':500,'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1 };
 for(var i in db){
  var m = parseInt(num/db[i]);
  result = i.repeat(m);
  num = num%db[i];
 }
 return result;
 document.getElementById('result').value = result;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <body>

    <label for="num">Number</label><br/>
    <input type="Number" name="num" id="num"><br/><br/>
    <label for="result">Result</label><br/>
    <textarea id="result" name="result"></textarea><br/><br/>
    <input type="submit" id="submit" value="Convert!" onclick="toRoman()">

    <script src="toRoman.js"></script>
    </body>
    </code>```

答:
You're overwriting the value of result in each iteration of your loop instead of adding to it.

Change it to result += i.repeat(m); instead.

Also, you'll have to either remove your return line, move it to the end of the function, or implement the function in a different way - return will exit the function at that line, meaning your last line (populating the result box) will never execute.

Working Example:

function toRoman() {
  var num = +(document.getElementById('num').value);
  var result = "";
  var db = {
    'M': 1000,
    'CM': 900,
    'D': 500,
    'CD': 400,
    'C': 100,
    'XC': 90,
    'L': 50,
    'XL': 40,
    'X': 10,
    'IX': 9,
    'V': 5,
    'IV': 4,
    'I': 1
  };
  for (var i in db) {
    var m = parseInt(num / db[i]);
    result += i.repeat(m);
    num = num % db[i];
  }
  document.getElementById('result').value = result;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="num">Number</label>
<br/>
<input type="Number" name="num" id="num">
<br/>
<br/>
<label for="result">Result</label>
<br/>
<textarea id="result" name="result"></textarea>
<br/>
<br/>
<input type="submit" id="submit" value="Convert!" onclick="toRoman()"></code>```

And a piece of advice...

Try implementing some basic debugging steps when you're looking for issues in your code - throw a few console.log() lines in your function so you know it's executing, and you can ensure that your values are returning what you expect.

With a simple console.log(result) in your loop, I was able to see that somewhere in the middle, result did in fact have a value, however by the end of the loop, it no longer had a value. This lead me to question "Why would it have a value in the middle but not at the end, unless we're removing the value with each loop?" - and sure enough, there was your answer.

Body:
help me fix this, simple convert to roman numerals code. with two input box, first where i input a number, 2nd box where the result will be shown. and a submit button

result wont show up on 2nd box after hitting convert/submit button

js code:

    function toRoman(){
 var num = document.getElementById('num').value;
 var result = "";
 var db = { 'M':1000, 'CM':900,'D':500,'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1 };
 for(var i in db){
  var m = parseInt(num/db[i]);
  result = i.repeat(m);
  num = num%db[i];
 }
 return result;
 document.getElementById('result').value = result;
    }

    Number

    <input type="Number" name="num" id="num">

    Result

    <textarea id="result" name="result"></textarea>

    <input type="submit" id="submit" value="Convert!" onclick="toRoman()">

Body:
You're overwriting the value of result in each iteration of your loop instead of adding to it.

Change it to result += i.repeat(m); instead.

Also, you'll have to either remove your return line, move it to the end of the function, or implement the function in a different way - return will exit the function at that line, meaning your last line (populating the result box) will never execute.

Working Example:

function toRoman() {
  var num = +(document.getElementById('num').value);
  var result = "";
  var db = {
    'M': 1000,
    'CM': 900,
    'D': 500,
    'CD': 400,
    'C': 100,
    'XC': 90,
    'L': 50,
    'XL': 40,
    'X': 10,
    'IX': 9,
    'V': 5,
    'IV': 4,
    'I': 1
  };
  for (var i in db) {
    var m = parseInt(num / db[i]);
    result += i.repeat(m);
    num = num % db[i];
  }
  document.getElementById('result').value = result;

}

<label for="num">Number</label>
<br/>
<input type="Number" name="num" id="num">
<br/>
<br/>
<label for="result">Result</label>
<br/>
<textarea id="result" name="result"></textarea>
<br/>
<br/>
<input type="submit" id="submit" value="Convert!" onclick="toRoman()">

And a piece of advice...

Try implementing some basic debugging steps when you're looking for issues in your code - throw a few console.log() lines in your function so you know it's executing, and you can ensure that your values are returning what you expect.

With a simple console.log(result) in your loop, I was able to see that somewhere in the middle, result did in fact have a value, however by the end of the loop, it no longer had a value. This lead me to question "Why would it have a value in the middle but not at the end, unless we're removing the value with each loop?" - and sure enough, there was your answer.


问:
Close all tabs, but not the window, in Sublime Text
Is there a way to close all tabs in one go in Sublime Text, but leave the window with the current project open? It is really annoying when I just want to close all open file and start the new task I have to Cmd-W them one by one. If I do Cmd-Opt-W it will close all tabs and the current project.

答:
The Coolest way is :
File - > Close All Tabs


问:
NTLM authentication works with curl, but not from Java
I try to connect to application which is deployed on Windows Server.
I uses NTLM. I'm using Ubuntu and Java8.

I'm getting HTTP 401 code, but only if I try to connect
from my Java application. Curl request with exactly the same
authentication details works ok, I'm getting HTTP 200:

```<code>curl -v -L --ntlm -u 'myuser\mydomain:mypass' 'http://myip/api/element/151
</code>```

This is my Java code
(I simplified it a bit, to include only problem-related stuff):

```<code>import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
...
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
...
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.RequestEntityProcessing;
...

class MyConnector {

    private final Client client;
    ...

    protected ClientConfig prepareClientConfig() {
        ClientConfig config = new ClientConfig();
        config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
        config.property(ClientProperties.FOLLOW_REDIRECTS, true);
        config.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("myuser", "mypassword",
                "mydomain", "mydomain"));

        config.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
        config.connectorProvider(new ApacheConnectorProvider());

        return config;
    }

    ...

    MyConnector(...) {

    ...
    client = ClientBuilder.newClient(prepareClientConfig());

    }

    protected String getDocString(...) throws MyException {

        WebTarget target = client.target("http://myipi/api").path("element/151");

        Invocation.Builder temp = target.request();
        Response response = target.request().get();

        if (response.getStatus() == Status.OK.getStatusCode()) {
            String docString = response.readEntity(String.class);

            return docString;
        }

        throw new MyException("Couldn't obtain doc. HTTP error code: " + response.getStatus());
    }

    ...
}
</code>```

It takes 5-15 (!) minutes to invoke the getDocString function.
I also believe that application eats unusually large amount of RAM,
although no other function is run simultaneously (the program is not parallelised).
Then I get HTTP 401 code.

I had some cases when my Java application worked. The story was:

my application worked without NTLM

my colleagues added NTLM to their app, I adjusted code, my app got 401, my curl request got 401

I upgraded from Ubuntu 14 LTS to Ubuntu 16.0.2 LTS, my app got 200, curl got 200

I gave out the server on which the setup worked (I don't have it any more)

I set up a new server, again with Ubuntu 16.0.2 LTS, my app got 401, curl got 200

I upgraded to Ubuntu 17.04 (non-LTS), my app got 200 once, but I cannot
reproduce it, now exactly the same request gets 401, curl gets 200

I'm aware of this question:
How to send NTLM authenticated post request using jersey?
I used the code and it allowed my app to work in combination with server upgrade (at point 3.).
But I don't know how to make it work again.

I used mitmproxy to debug the request, the output looks like this
(I obscured the Authorization/WWW-Authenticate fields):

```<code>Proxy server listening at http://0.0.0.0:8080
127.0.0.1:39622: clientconnect
127.0.0.1:39622: request
  -> Request(GET /api/element/151)
127.0.0.1:39622: serverconnect
  -> myip:80
127.0.0.1:39622: response
  -> Response(401 Unauthorized, text/html, 1.26k)
127.0.0.1:39622: GET http://myip/api/element/151
    User-Agent: Jersey/2.26-b03 (Apache HttpClient 4.5.3)
    Host: myip
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
 << 401 Unauthorized 1.26k
    Content-Type: text/html
    Server: Microsoft-IIS/8.5
    WWW-Authenticate: Negotiate
    WWW-Authenticate: NTLM
    X-Powered-By: ASP.NET
    Date: Mon, 29 May 2017 13:38:36 GMT
    Content-Length: 1293
127.0.0.1:39622: request
  -> Request(GET /api/element/151)
127.0.0.1:39622: response
  -> Response(401 Unauthorized, text/html; charset=us-ascii, 341b)
127.0.0.1:39622: GET http://myip/api/element/151
    User-Agent: Jersey/2.26-b03 (Apache HttpClient 4.5.3)
    Host: myip
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
    Authorization: NTLM TlRAAA==
 << 401 Unauthorized 341b
    Content-Type: text/html; charset=us-ascii
    Server: Microsoft-HTTPAPI/2.0
    WWW-Authenticate: NTLM TlRAAABBBBBBAAA==
    Date: Mon, 29 May 2017 13:38:36 GMT
    Content-Length: 341
127.0.0.1:39622: request
  -> Request(GET /api/element/151)
127.0.0.1:39622: server communication error: TcpDisconnect('[Errno 104] Connection reset by peer',)
127.0.0.1:39622: serverdisconnect
  -> myip:80
127.0.0.1:39622: serverconnect
  -> myip:80
127.0.0.1:39622: response
  -> Response(401 Unauthorized, text/html, 1.26k)
127.0.0.1:39622: GET http://myip/api/element/151
    User-Agent: Jersey/2.26-b03 (Apache HttpClient 4.5.3)
    Host: myip
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
    Authorization: NTLM TlRAAABBBDDDAAA==
 << 401 Unauthorized 1.26k
    Content-Type: text/html
    Server: Microsoft-IIS/8.5
    WWW-Authenticate: Negotiate
    WWW-Authenticate: NTLM
    X-Powered-By: ASP.NET
    Date: Mon, 29 May 2017 13:44:35 GMT
    Content-Length: 1293
127.0.0.1:39622: serverdisconnect
  -> myip:80
127.0.0.1:39622: clientdisconnect
</code>```

I will be very grateful for any remarks on this.

Update: I also tried Debian8 and Debian9. The result is the same. I got 401 ad Debian8, updated to Debian9, got 200 once and then continuously 401 (for the exactly same request).

答:
I resolved this issue by using JCIFS library instead of default NTLM authentication from HttpClient. You can see the example on the Apache page:
https://hc.apache.org/httpcomponents-client-4.5.x/ntlm.html

The problem is that I couldn't find a way to make it compatible with Jersey. Jersey uses javax.ws.rs.client.Client and I didn't know how to update the AuthScheme of it (there's no method to set it). So I switched to org.apache.http.impl.client.CloseableHttpClient and rewrote whole application to use raw HttpClient methods.

Body:
I try to connect to application which is deployed on Windows Server.
I uses NTLM. I'm using Ubuntu and Java8.

I'm getting HTTP 401 code, but only if I try to connect
from my Java application. Curl request with exactly the same
authentication details works ok, I'm getting HTTP 200:

curl -v -L --ntlm -u 'myuser\mydomain:mypass' 'http://myip/api/element/151

This is my Java code
(I simplified it a bit, to include only problem-related stuff):

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
...
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
...
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.RequestEntityProcessing;
...

class MyConnector {

    private final Client client;
    ...

    protected ClientConfig prepareClientConfig() {
        ClientConfig config = new ClientConfig();
        config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
        config.property(ClientProperties.FOLLOW_REDIRECTS, true);
        config.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("myuser", "mypassword",
                "mydomain", "mydomain"));

        config.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
        config.connectorProvider(new ApacheConnectorProvider());

        return config;
    }

    ...

    MyConnector(...) {

    ...
    client = ClientBuilder.newClient(prepareClientConfig());

    }

    protected String getDocString(...) throws MyException {

        WebTarget target = client.target("http://myipi/api").path("element/151");

        Invocation.Builder temp = target.request();
        Response response = target.request().get();

        if (response.getStatus() == Status.OK.getStatusCode()) {
            String docString = response.readEntity(String.class);

            return docString;
        }

        throw new MyException("Couldn't obtain doc. HTTP error code: " + response.getStatus());
    }

    ...
}

It takes 5-15 (!) minutes to invoke the getDocString function.
I also believe that application eats unusually large amount of RAM,
although no other function is run simultaneously (the program is not parallelised).
Then I get HTTP 401 code.

I had some cases when my Java application worked. The story was:

my application worked without NTLM

my colleagues added NTLM to their app, I adjusted code, my app got 401, my curl request got 401

I upgraded from Ubuntu 14 LTS to Ubuntu 16.0.2 LTS, my app got 200, curl got 200

I gave out the server on which the setup worked (I don't have it any more)

I set up a new server, again with Ubuntu 16.0.2 LTS, my app got 401, curl got 200

I upgraded to Ubuntu 17.04 (non-LTS), my app got 200 once, but I cannot
reproduce it, now exactly the same request gets 401, curl gets 200

I'm aware of this question:
How to send NTLM authenticated post request using jersey?
I used the code and it allowed my app to work in combination with server upgrade (at point 3.).
But I don't know how to make it work again.

I used mitmproxy to debug the request, the output looks like this
(I obscured the Authorization/WWW-Authenticate fields):

Proxy server listening at http://0.0.0.0:8080
127.0.0.1:39622: clientconnect
127.0.0.1:39622: request
  -> Request(GET /api/element/151)
127.0.0.1:39622: serverconnect
  -> myip:80
127.0.0.1:39622: response
  -> Response(401 Unauthorized, text/html, 1.26k)
127.0.0.1:39622: GET http://myip/api/element/151
    User-Agent: Jersey/2.26-b03 (Apache HttpClient 4.5.3)
    Host: myip
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
 << 401 Unauthorized 1.26k
    Content-Type: text/html
    Server: Microsoft-IIS/8.5
    WWW-Authenticate: Negotiate
    WWW-Authenticate: NTLM
    X-Powered-By: ASP.NET
    Date: Mon, 29 May 2017 13:38:36 GMT
    Content-Length: 1293
127.0.0.1:39622: request
  -> Request(GET /api/element/151)
127.0.0.1:39622: response
  -> Response(401 Unauthorized, text/html; charset=us-ascii, 341b)
127.0.0.1:39622: GET http://myip/api/element/151
    User-Agent: Jersey/2.26-b03 (Apache HttpClient 4.5.3)
    Host: myip
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
    Authorization: NTLM TlRAAA==
 << 401 Unauthorized 341b
    Content-Type: text/html; charset=us-ascii
    Server: Microsoft-HTTPAPI/2.0
    WWW-Authenticate: NTLM TlRAAABBBBBBAAA==
    Date: Mon, 29 May 2017 13:38:36 GMT
    Content-Length: 341
127.0.0.1:39622: request
  -> Request(GET /api/element/151)
127.0.0.1:39622: server communication error: TcpDisconnect('[Errno 104] Connection reset by peer',)
127.0.0.1:39622: serverdisconnect
  -> myip:80
127.0.0.1:39622: serverconnect
  -> myip:80
127.0.0.1:39622: response
  -> Response(401 Unauthorized, text/html, 1.26k)
127.0.0.1:39622: GET http://myip/api/element/151
    User-Agent: Jersey/2.26-b03 (Apache HttpClient 4.5.3)
    Host: myip
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
    Authorization: NTLM TlRAAABBBDDDAAA==
 << 401 Unauthorized 1.26k
    Content-Type: text/html
    Server: Microsoft-IIS/8.5
    WWW-Authenticate: Negotiate
    WWW-Authenticate: NTLM
    X-Powered-By: ASP.NET
    Date: Mon, 29 May 2017 13:44:35 GMT
    Content-Length: 1293
127.0.0.1:39622: serverdisconnect
  -> myip:80
127.0.0.1:39622: clientdisconnect

I will be very grateful for any remarks on this.

Update: I also tried Debian8 and Debian9. The result is the same. I got 401 ad Debian8, updated to Debian9, got 200 once and then continuously 401 (for the exactly same request).


问:
Access is denied when use del /f in windows 10 64bit
I'm going to delete 1.mp3 but it gives me the error "Access is denied".

More info about file's perms:

```<code>attrib 1.mp3
A   C:\Users\Alipour\Desktop\1\1.mp3
</code>```

I also used attrib -s -h 1.mp3

but still it can not be deleted by

```<code>del /f/s/q 1.mp3 > NUL
</code>```

or

```<code>del /f/s/q 1.mp3
</code>```

or

```<code>del /f 1.mp3
</code>```

答:
There are several methods to remove such a file:

1. Process Explorer if the file is in use:

You can use ProcessExplorer from Windows Sysinternals to identifiy which program locks the file. Download and start ProcessExplorer and go to Find|Find Handle or DLL... Ctrl+F and enter the name of the locked file: 1.mp3.

ProcessExplorer will show you the process that is responsible for the lock because of accessing the file. If you've got the proccess kill that one and delete the file.

Example with MS Word accessing a file called LockedFile.docx:

2. Safe mode boot:

Another possibility is to boot into safe mode. In pre Windows 8 era this was done by pressing F8 before Windows boots.

In Windows 8 and higher you can press Shift+F8 before Windows boots or more easily you can hold Shift and click Restart in the login screen or even in Windows. If this was too short, look here how to get into safe mode.

Once you're in the safe mode you can try again deleting that file.

3. Remove file on Windows boot via PendingFileRenameOperations:

With PendingFileRenameOperations you can rename and even delete a file on Windows boot procedure when nothing else can access and block that file.
PendingFileRenameOperations will be entered in the Windows registry and consists of pairs of file paths.

You can do it manually as described below or again with a Windows Sysinternals program called MoveFile. Download that program and use it in a console window (Start -> Run or Windows-Key+R, type cmd and press ENTER).

Type movefile foo.exe "" to delete a file on reboot.

Manual method via registry:

The 1st path is the file to be renamed.

The 2nd path is the new file path.
If the 2nd path is empty (0x0000) the file get's removed.

Start -> Run or Windows-Key+R

Type in regedit, and press ENTER

Goto HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager

Create a new Multi-String value: PendingFileRenameOperations

Enter \??\filepath as the data (e.g. \??\C:\Users\xyz\Desktop\foo.exe)

Press OK

Right-click on the key, click Modify Binary Data

At the end of the hex string, add 0000 (4 zeros which represent an empty string)

Press OK

Restart your computer

Body:
I'm going to delete 1.mp3 but it gives me the error "Access is denied".

More info about file's perms:

attrib 1.mp3
A   C:\Users\Alipour\Desktop\1\1.mp3

I also used attrib -s -h 1.mp3

but still it can not be deleted by

del /f/s/q 1.mp3 > NUL

or

del /f/s/q 1.mp3

or

del /f 1.mp3


问:
MSXML. Get data as Base64
I'm using C++ with MSXML and want to get data from XML file as Base64. I'm using this code:

```<code>    hr = nodeList->get_item((long)i, (IXMLDOMNode **)&vXMLNode);
    if ( FAILED(hr) )
        throw "Unable to retrieve child node";

    vXMLNode->put_dataType(_bstr_t("bin.base64"));

    hr = vXMLNode->get_nodeTypedValue(&varValue);
    if ( FAILED(hr) )
        throw "Unable to retrieve 'xmltext' text";
</code>```

So vXMLNode is a child node with data. Node type of vXMLNode is NODE_ELEMENT. If I check data type for this node, I get VT_NULL. Therefore I get my data as a string.

What is wrong in my code?

答:
I believe the problem lies outside of your supplied sample code.  Here's a working console program that uses nodeTypedValue.  I hope this helps.</p>

```<code>// Base64CPP.cpp : Defines the entry point for the console application.

//  NOTE:
//  This code is provided as is in the form of a sample with no warranties of any kind,
//  either expressed or implied for any purpose. Use at your own risk.

#include "stdafx.h"

#include <TCHAR.H>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream>
#include <string.h>

#include <atlbase.h>
#import <msxml4.dll> named_guids
using namespace MSXML2;

inline void EVAL_HR( HRESULT _hr )
   { if FAILED(_hr) throw(_hr); }

//  Binary to Base64 Encoding
bool DoEncoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
    bool bRetVal = false;
    try
    {
        long lFileSize;
        struct stat fileSizeVal;

        //  Get the file size
        if (stat(lpszBinFile, &fileSizeVal) == 0)
        {
            lFileSize = fileSizeVal.st_size;
            if(lFileSize <= 0)
                return false;
        }
        else
            return false;

        //  Instantiate XML DOMDocument
        CComPtr<IXMLDOMDocument2> spXMLDoc;
        CComPtr<MSXML2::IXMLDOMElement> spDataElement;
        HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
        EVAL_HR(hr);
        spXMLDoc->loadXML(_T("<?xml version='1.0' encoding='UTF-8'?> <Data/>"));

        //  Prepare the top node to store binary data as base64
        spDataElement = spXMLDoc->documentElement;
        ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));

        hr = spDataElement->put_dataType(CComBSTR(_T("bin.base64")));
        EVAL_HR(hr);

        //  Read the file into memory
        std::ifstream binDataFile;
        binDataFile.open(lpszBinFile, std::ios::binary);
        binDataFile.seekg(std::ios::beg);
        SAFEARRAY* psa = SafeArrayCreateVector( VT_UI1, 0L, lFileSize);
        binDataFile.read((char*)psa->pvData, lFileSize);
        binDataFile.close();

        //  Save the binary data into Data node
        VARIANT var;
        VariantInit(&var);
        var.parray = psa;
        var.vt = (VT_ARRAY | VT_UI1 );
        spDataElement->nodeTypedValue = var;

        //  Save the XML Document
        spXMLDoc->save(lpszXMLFile);

        bRetVal = true;
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    return bRetVal;
}

//  Base64 to binary decoding
bool DoDecoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
    bool bRetVal = false;
    try
    {
        //  Instantiate DOMDocument and load XML file
        CComPtr<IXMLDOMDocument2> spXMLDoc;
        CComPtr<MSXML2::IXMLDOMElement> spDataElement;
        HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
        EVAL_HR(hr);
        CComVariant vtFileName = CComBSTR(lpszXMLFile);
        spXMLDoc->load(vtFileName);

        //  ASSUMPTION: documentElement (top element) contains base64 data
        spDataElement = spXMLDoc->documentElement;
        ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));

        //  Prepare the file for writing
        std::ofstream binDataFile (lpszBinFile, std::ios::out | std::ios::binary);

        //  Save the binary data into data file
        long lDataLength=0;
        hr = SafeArrayGetUBound(spDataElement->nodeTypedValue.parray, 1, &lDataLength);
        EVAL_HR(hr);
        lDataLength++;

        binDataFile.write((char*)(spDataElement->nodeTypedValue.parray->pvData), lDataLength);
        binDataFile.close();

        bRetVal = true;
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    return bRetVal;
}

int main(int argc, char* argv[])
{
    if(argc < 4)
    {//insufficient parameters
        printf(_T("\nSample app to encode/decode binary data as base64 XML using MSXML.\n"));
        printf(_T("\nUsage:\tBase64CPP.exe <e>|<d> <XMLFileName> <BinaryDataFile>"));
        printf(_T("\n\nExamples:"));
        printf(_T("\n\tEncode binary data in 1.jpg and save as Base64 into 1.xml:"));
        printf(_T("\n\t\tBase64CPP.exe e c:\\1.xml c:\\1.jpg\n"));
        printf(_T("\n\tDecode base64 data in 1.xml and save as binary into 2.jpg:"));
        printf(_T("\n\t\tBase64CPP.exe d c:\\1.xml c:\\2.jpg\n\n"));
        return -1;
    }

    try
    {
        HRESULT hr = CoInitialize(NULL);
        EVAL_HR(hr);

        if(_tcsicmp(argv[1], _T("e")) == 0)
        {
            if(DoEncoding(argv[2], argv[3]))
                printf(_T("Success. See %s for results."), argv[2]);
            else
                printf(_T("Failed."));
        }
        else
        {
            if(DoDecoding(argv[2], argv[3]))
                printf(_T("Success. See %s for results."), argv[3]);
            else
                printf(_T("Failed."));
        }
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    CoUninitialize();
    getchar();
    return 0;
}
</code>```

Title: MSXML. Get data as Base64

Body:
I'm using C++ with MSXML and want to get data from XML file as Base64. I'm using this code:

    hr = nodeList->get_item((long)i, (IXMLDOMNode **)&vXMLNode);
    if ( FAILED(hr) )
        throw "Unable to retrieve child node";

    vXMLNode->put_dataType(_bstr_t("bin.base64"));

    hr = vXMLNode->get_nodeTypedValue(&varValue);
    if ( FAILED(hr) )
        throw "Unable to retrieve 'xmltext' text";

So vXMLNode is a child node with data. Node type of vXMLNode is NODE_ELEMENT. If I check data type for this node, I get VT_NULL. Therefore I get my data as a string.

What is wrong in my code?

Body:
I believe the problem lies outside of your supplied sample code.  Here's a working console program that uses nodeTypedValue.  I hope this helps.

// Base64CPP.cpp : Defines the entry point for the console application.

//  NOTE:
//  This code is provided as is in the form of a sample with no warranties of any kind,
//  either expressed or implied for any purpose. Use at your own risk.

#include "stdafx.h"

#include <TCHAR.H>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream>
#include <string.h>

#include <atlbase.h>
#import <msxml4.dll> named_guids
using namespace MSXML2;

inline void EVAL_HR( HRESULT _hr )
   { if FAILED(_hr) throw(_hr); }

//  Binary to Base64 Encoding
bool DoEncoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
    bool bRetVal = false;
    try
    {
        long lFileSize;
        struct stat fileSizeVal;

        //  Get the file size
        if (stat(lpszBinFile, &fileSizeVal) == 0)
        {
            lFileSize = fileSizeVal.st_size;
            if(lFileSize <= 0)
                return false;
        }
        else
            return false;

        //  Instantiate XML DOMDocument
        CComPtr<IXMLDOMDocument2> spXMLDoc;
        CComPtr<MSXML2::IXMLDOMElement> spDataElement;
        HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
        EVAL_HR(hr);
        spXMLDoc->loadXML(_T("<?xml version='1.0' encoding='UTF-8'?> <Data/>"));

        //  Prepare the top node to store binary data as base64
        spDataElement = spXMLDoc->documentElement;
        ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));

        hr = spDataElement->put_dataType(CComBSTR(_T("bin.base64")));
        EVAL_HR(hr);

        //  Read the file into memory
        std::ifstream binDataFile;
        binDataFile.open(lpszBinFile, std::ios::binary);
        binDataFile.seekg(std::ios::beg);
        SAFEARRAY* psa = SafeArrayCreateVector( VT_UI1, 0L, lFileSize);
        binDataFile.read((char*)psa->pvData, lFileSize);
        binDataFile.close();

        //  Save the binary data into Data node
        VARIANT var;
        VariantInit(&var);
        var.parray = psa;
        var.vt = (VT_ARRAY | VT_UI1 );
        spDataElement->nodeTypedValue = var;

        //  Save the XML Document
        spXMLDoc->save(lpszXMLFile);

        bRetVal = true;
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    return bRetVal;
}

//  Base64 to binary decoding
bool DoDecoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
    bool bRetVal = false;
    try
    {
        //  Instantiate DOMDocument and load XML file
        CComPtr<IXMLDOMDocument2> spXMLDoc;
        CComPtr<MSXML2::IXMLDOMElement> spDataElement;
        HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
        EVAL_HR(hr);
        CComVariant vtFileName = CComBSTR(lpszXMLFile);
        spXMLDoc->load(vtFileName);

        //  ASSUMPTION: documentElement (top element) contains base64 data
        spDataElement = spXMLDoc->documentElement;
        ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));

        //  Prepare the file for writing
        std::ofstream binDataFile (lpszBinFile, std::ios::out | std::ios::binary);

        //  Save the binary data into data file
        long lDataLength=0;
        hr = SafeArrayGetUBound(spDataElement->nodeTypedValue.parray, 1, &lDataLength);
        EVAL_HR(hr);
        lDataLength++;

        binDataFile.write((char*)(spDataElement->nodeTypedValue.parray->pvData), lDataLength);
        binDataFile.close();

        bRetVal = true;
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    return bRetVal;
}

int main(int argc, char* argv[])
{
    if(argc < 4)
    {//insufficient parameters
        printf(_T("\nSample app to encode/decode binary data as base64 XML using MSXML.\n"));
        printf(_T("\nUsage:\tBase64CPP.exe <e>|<d> <XMLFileName> <BinaryDataFile>"));
        printf(_T("\n\nExamples:"));
        printf(_T("\n\tEncode binary data in 1.jpg and save as Base64 into 1.xml:"));
        printf(_T("\n\t\tBase64CPP.exe e c:\\1.xml c:\\1.jpg\n"));
        printf(_T("\n\tDecode base64 data in 1.xml and save as binary into 2.jpg:"));
        printf(_T("\n\t\tBase64CPP.exe d c:\\1.xml c:\\2.jpg\n\n"));
        return -1;
    }

    try
    {
        HRESULT hr = CoInitialize(NULL);
        EVAL_HR(hr);

        if(_tcsicmp(argv[1], _T("e")) == 0)
        {
            if(DoEncoding(argv[2], argv[3]))
                printf(_T("Success. See %s for results."), argv[2]);
            else
                printf(_T("Failed."));
        }
        else
        {
            if(DoDecoding(argv[2], argv[3]))
                printf(_T("Success. See %s for results."), argv[3]);
            else
                printf(_T("Failed."));
        }
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    CoUninitialize();
    getchar();
    return 0;
}


问:
How can i hold a first letter of `h1` content after pressing backspace
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}</code>```

    Click here to edit content

```

答:
Have a look to the solution https://jsfiddle.net/5brr7sj1/6/

```<code>$(document).ready(function(){

    var txt = $('.editor').text();
    var splitTxt = txt.split('');

    $('.editor').keyup(function(e){
       if(e.keyCode === 8){
           if( $(this).text().length === 1){
               $(this).text(splitTxt[1]);
           }
       }
    });

 });
</code>```

If you need any change please add it in the comments

Body:
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});

.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}

    Click here to edit content

Body:
Have a look to the solution https://jsfiddle.net/5brr7sj1/6/

$(document).ready(function(){

    var txt = $('.editor').text();
    var splitTxt = txt.split('');

    $('.editor').keyup(function(e){
       if(e.keyCode === 8){
           if( $(this).text().length === 1){
               $(this).text(splitTxt[1]);
           }
       }
    });

 });

If you need any change please add it in the comments