问:
Prevent Fabric js Objects from scaling out of the canvas boundary
I have been trying to keep an object (constructed in fabric js over a canvas) inside the boundaries at all the times. It has been achieved at moving and rotating it. I took help from Move object within canvas boundary limit for achieving this. But when I start to scale the object, it simply keeps on going out of boundary. I do not understand what has to be done to keep it inside the boundary only, even while scaling. Please help me with a code to prevent this behavior. It would be great if you can attach a demo too.

```<code>    <html>
<head>
    <title>Basic usage</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.3/fabric.min.js"></script>

</head>
<body>
<canvas id="canvas" style= "border: 1px solid black" height= 480 width = 360></canvas>
<script>
 var canvas = new fabric.Canvas('canvas');
  canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

  canvas.item(0).set({
    borderColor: 'gray',
    cornerColor: 'black',
    cornerSize: 12,
    transparentCorners: true
  });
  canvas.setActiveObject(canvas.item(0));
  canvas.renderAll();

  canvas.on('object:moving', function (e) {
        var obj = e.target;
         // if object is too big ignore
        if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
            return;
        }
        obj.setCoords();
        // top-left  corner
        if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
            obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
            obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
        }
        // bot-right corner
        if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width){
            obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
            obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
        }
});

</script>
</body>
</html>
</code>```

My demo is attached here. :
https://jsfiddle.net/3v0cLaLk/

答:
I was able to solve the problem as follows:

var canvas = new fabric.Canvas('canvas');
  canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

  canvas.item(0).set({
    borderColor: 'gray',
    cornerColor: 'black',
    cornerSize: 12,
    transparentCorners: true
  });
  canvas.setActiveObject(canvas.item(0));
  canvas.renderAll();

  canvas.on('object:moving', function (e) {
        var obj = e.target;
         // if object is too big ignore
        if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
            return;
        }
        obj.setCoords();
        // top-left  corner
        if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
            obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
            obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
        }
        // bot-right corner
        if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width){
            obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
            obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
        }
});

    var left1 = 0;
    var top1 = 0 ;
    var scale1x = 0 ;
    var scale1y = 0 ;
    var width1 = 0 ;
    var height1 = 0 ;
  canvas.on('object:scaling', function (e){
    var obj = e.target;
    obj.setCoords();
    var brNew = obj.getBoundingRect();

    if (((brNew.width+brNew.left)>=obj.canvas.width) || ((brNew.height+brNew.top)>=obj.canvas.height) || ((brNew.left<0) || (brNew.top<0))) {
    obj.left = left1;
    obj.top=top1;
    obj.scaleX=scale1x;
    obj.scaleY=scale1y;
    obj.width=width1;
    obj.height=height1;
  }
    else{
      left1 =obj.left;
      top1 =obj.top;
      scale1x = obj.scaleX;
      scale1y=obj.scaleY;
      width1=obj.width;
      height1=obj.height;
    }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <title>Basic usage</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.3/fabric.min.js"></script>

</head>
<body>
<canvas id="canvas" style= "border: 1px solid black" height= 480 width = 360></canvas>
</body>
</html></code>```

Body:
I have been trying to keep an object (constructed in fabric js over a canvas) inside the boundaries at all the times. It has been achieved at moving and rotating it. I took help from Move object within canvas boundary limit for achieving this. But when I start to scale the object, it simply keeps on going out of boundary. I do not understand what has to be done to keep it inside the boundary only, even while scaling. Please help me with a code to prevent this behavior. It would be great if you can attach a demo too.

    <title>Basic usage</title>

<canvas id="canvas" style= "border: 1px solid black" height= 480 width = 360></canvas>

My demo is attached here. :
https://jsfiddle.net/3v0cLaLk/

Body:
I was able to solve the problem as follows:

var canvas = new fabric.Canvas('canvas');
  canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

  canvas.item(0).set({
    borderColor: 'gray',
    cornerColor: 'black',
    cornerSize: 12,
    transparentCorners: true
  });
  canvas.setActiveObject(canvas.item(0));
  canvas.renderAll();

  canvas.on('object:moving', function (e) {
        var obj = e.target;
         // if object is too big ignore
        if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
            return;
        }
        obj.setCoords();
        // top-left  corner
        if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
            obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
            obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
        }
        // bot-right corner
        if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width){
            obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
            obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
        }
});

    var left1 = 0;
    var top1 = 0 ;
    var scale1x = 0 ;
    var scale1y = 0 ;
    var width1 = 0 ;
    var height1 = 0 ;
  canvas.on('object:scaling', function (e){
    var obj = e.target;
    obj.setCoords();
    var brNew = obj.getBoundingRect();

    if (((brNew.width+brNew.left)>=obj.canvas.width) || ((brNew.height+brNew.top)>=obj.canvas.height) || ((brNew.left<0) || (brNew.top<0))) {
    obj.left = left1;
    obj.top=top1;
    obj.scaleX=scale1x;
    obj.scaleY=scale1y;
    obj.width=width1;
    obj.height=height1;
  }
    else{
      left1 =obj.left;
      top1 =obj.top;
      scale1x = obj.scaleX;
      scale1y=obj.scaleY;
      width1=obj.width;
      height1=obj.height;
    }
 });

<html>
<head>
    <title>Basic usage</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.3/fabric.min.js"></script>

</head>
<body>
<canvas id="canvas" style= "border: 1px solid black" height= 480 width = 360></canvas>
</body>
</html>


来源: stackexchange

问:
Javascript Timing : is it possible and how to pass a variable to second argument of setTimeout() & setInterval()?
I'm not able to pass an index from an array to the 2nd argument of a window.setTimout() function (https://www.w3schools.com/js/js_timing.asp)

```<code>function joueursCascade(){

     for (i = 0; i <= my_params.nbJoueurs; i++) {
        var del = tabDel[i]; c

        function getName(){

        message = new Paho.MQTT.Message(document.getElementById('btn3').value);

        message.destinationName = document.getElementById('esp'+i).value+"/ledstate";

        mon_client.send(message);

        }
    window.setTimeout(getName(), del);
    }
}
</code>```

called by something like joueursCascade() this code should send "my_params.nbJoueurs" strings via MQTT at "del" time intervals.

答:
window.setTimeout(getName(), del);

Should be:

window.setTimeout(getName, del);

If you pass getName() as 1st argument, then you are in fact passing the return value of that function. You need to pass in a reference to that function, hence only getName

ContentLicense: CC BY-SA 4.0

Body:
I'm not able to pass an index from an array to the 2nd argument of a window.setTimout() function (https://www.w3schools.com/js/js_timing.asp)

function joueursCascade(){

     for (i = 0; i <= my_params.nbJoueurs; i++) {
        var del = tabDel[i]; c

        function getName(){

        message = new Paho.MQTT.Message(document.getElementById('btn3').value);

        message.destinationName = document.getElementById('esp'+i).value+"/ledstate";

        mon_client.send(message);

        }
    window.setTimeout(getName(), del);
    }
}

called by something like joueursCascade() this code should send "my_params.nbJoueurs" strings via MQTT at "del" time intervals.


问:
Swipe to switch tab selection
I have an application that is a Tab activity with various tabs that load an Activity. I would like to add swipe gesturing to switch between tabs, on both the tab control itself and each activity loaded in a tab.  Is something like this possible? I'm not sure at what "depth" the gesture is listened to when you're making gestures on an Activity hosted in the tab control, or if the inner activities would have to pass data to the Tab Host.</p>

答: It's certainly possible; you'll need to write a custom layout and override onTouchEvent and onInterceptTouchEvent to decide whether to dispatch gestures through to the children . See HorizontalPager's source for details on how you could go about doing that. You actually may just want to use HorizontalPager straight up (there's a demo on simulating tabs with it), as I think the scrolling content makes it much clearer that you can swipe between tabs.</p>

ContentLicense: CC BY-SA 3.0

Title: Swipe to switch tab selection


问:
SVG pause/play Can not figure out why this isn't working...?
I need code to work just like on this page.

Play and pausing of an SVG.  I went into inspect and pulled all the code I could, which seemed to be HTML.  I could not see or find CSS or Javascript.  Not sure if that is normal.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="80 0 1024 768" onload="t=setInterval(updateTimer, 100)">

<linearGradient id="grad">
    <stop stop-color="rgb(10%,80%,10%)" offset="0"/>
    <stop stop-color="rgb(10%,40%,20%)" offset="0.4"/>
    <stop stop-color="rgb(10%,90%,30%)" offset="0.7"/>
    <stop stop-color="rgb(10%,50%,40%)" offset="1"/>
  </linearGradient>

<rect fill="url(#grad)" width="0%" height="50" x="100" y="300" rx="5">
    <animate attributeName="width" to="100%" begin="0s" dur="30s"/>
  </rect>

<text id="t" style="font:24px Arial Black;fill:white;stroke:black" transform="translate(100 334)"/>

<animateTransform type="translate" attributeName="transform" xlink:href="#t" begin="1s" dur="29s" from="100 334" to="1024 334"/>

<g transform="translate(100 500)">

   <g onclick="play()">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5"/>
     <path id="play" d="M12 5l20 15l-20 15Z" fill="white" pointer-events="none"/>
   </g>

   <g transform="translate(50 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="pause();"/>
     <path id="pause" d="M14 10l0 20M26 10l0 20" stroke="white" fill="none" stroke-width="8" pointer-events="none"/>
   </g>

   <g transform="translate(100 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="stop()"/>
     <rect x="10" y="10" width="20" height="20" fill="white" pointer-events="none"/>
   </g>
  </g>
</svg>```

When I attempt playback on Code pen, the SVG plays but buttons don't work. At all.  I thought the "onclick" would do it...?

Is this because the JS isn't accessible/applied?  I don't see any "DIV" or "DOM" so I assume its not a CSS thing...

I have a basic knowledge of HTML, less of CSS and know NOTHING about JavaScript

答:
Short version: getCurrentTime & setCurrentTime must be called on the SVG node.

const mySvg = document.getElementById("mySvg")

function updateTimer() {
  const t = `${mySvg.getCurrentTime().toFixed(0)}s`;
  document.getElementById("t").textContent = t;
}

function setCurrentTime(t) {
  mySvg.setCurrentTime(t)
}

function pause() {
  mySvg.pauseAnimations()
}

function play() {
  mySvg.unpauseAnimations()
}

function stop() {
  clearInterval();
  setCurrentTime(0);
  mySvg.pauseAnimations()
  updateTimer();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="mySvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="80 0 1024 768" onload="t=setInterval(updateTimer, 100)">
  <linearGradient id="grad">
    <stop stop-color="rgb(10%,80%,10%)" offset="0"/>
    <stop stop-color="rgb(10%,40%,20%)" offset="0.4"/>
    <stop stop-color="rgb(10%,90%,30%)" offset="0.7"/>
    <stop stop-color="rgb(10%,50%,40%)" offset="1"/>
  </linearGradient>
  <rect fill="url(#grad)" width="0%" height="50" x="100" y="300" rx="5">
    <animate attributeName="width" to="100%" begin="0s" dur="30s"/>
  </rect>
  <text id="t" style="font:24px Arial Black;fill:white;stroke:black" transform="translate(100 334)"/>
  <animateTransform type="translate" attributeName="transform" xlink:href="#t" begin="1s" dur="29s" from="100 334" to="1024 334"/>
  <g transform="translate(100 500)">
    <!-- Play -->
    <g onclick="play()">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5"/>
     <path id="play" d="M12 5l20 15l-20 15Z" fill="white" pointer-events="none"/>
   </g>
   <!-- Pause -->
   <g transform="translate(50 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="pause();"/>
     <path id="pause" d="M14 10l0 20M26 10l0 20" stroke="white" fill="none" stroke-width="8" pointer-events="none"/>
   </g>
   <!-- Stop (rewind and pause) -->
   <g transform="translate(100 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="stop()"/>
     <rect x="10" y="10" width="20" height="20" fill="white" pointer-events="none"/>
   </g>
 </g>
</svg></code>```

Long version: After all that, why wasn't it working in Codepen?
I can see that the link you posted is to an SVG document with it's own inline JavaScript (in the script tag).

The script calls some SVGElement methods on the SVG root element with document.documentElement.pauseAnimations();.
But what exactly is document element?

Document.documentElement returns the Element that is the root element of the document (for example, the  element for HTML documents).

Because this code was called inside an SVG document, document.documentElement returns the SVG root node. However, because codepen is an HTML document, document.documentElement will return the HTML root node.

And you can't call methods like pauseAnimations() on an HTML root node because the HTML root node doesn't understand those methods.

So modern browsers can display SVG documents, HTML documents (and more) but here's the kicker: SVG documents can live inside of HTML documents.

You can see how document.documentElement could refer to two potential things depending on what type of document the JavaScript code was run from.

Body:
I need code to work just like on this page.

Play and pausing of an SVG.  I went into inspect and pulled all the code I could, which seemed to be HTML.  I could not see or find CSS or Javascript.  Not sure if that is normal.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="80 0 1024 768" onload="t=setInterval(updateTimer, 100)">

<linearGradient id="grad">
    <stop stop-color="rgb(10%,80%,10%)" offset="0"/>
    <stop stop-color="rgb(10%,40%,20%)" offset="0.4"/>
    <stop stop-color="rgb(10%,90%,30%)" offset="0.7"/>
    <stop stop-color="rgb(10%,50%,40%)" offset="1"/>
  </linearGradient>

<rect fill="url(#grad)" width="0%" height="50" x="100" y="300" rx="5">
    <animate attributeName="width" to="100%" begin="0s" dur="30s"/>
  </rect>

<text id="t" style="font:24px Arial Black;fill:white;stroke:black" transform="translate(100 334)"/>

<animateTransform type="translate" attributeName="transform" xlink:href="#t" begin="1s" dur="29s" from="100 334" to="1024 334"/>

<g transform="translate(100 500)">

   <g onclick="play()">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5"/>
     <path id="play" d="M12 5l20 15l-20 15Z" fill="white" pointer-events="none"/>
   </g>

   <g transform="translate(50 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="pause();"/>
     <path id="pause" d="M14 10l0 20M26 10l0 20" stroke="white" fill="none" stroke-width="8" pointer-events="none"/>
   </g>

   <g transform="translate(100 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="stop()"/>
     <rect x="10" y="10" width="20" height="20" fill="white" pointer-events="none"/>
   </g>
  </g>
</svg>

When I attempt playback on Code pen, the SVG plays but buttons don't work. At all.  I thought the "onclick" would do it...?

Is this because the JS isn't accessible/applied?  I don't see any "DIV" or "DOM" so I assume its not a CSS thing...

I have a basic knowledge of HTML, less of CSS and know NOTHING about JavaScript

Body:
Short version: getCurrentTime & setCurrentTime must be called on the SVG node.

const mySvg = document.getElementById("mySvg")

function updateTimer() {
  const t = `${mySvg.getCurrentTime().toFixed(0)}s`;
  document.getElementById("t").textContent = t;
}

function setCurrentTime(t) {
  mySvg.setCurrentTime(t)
}

function pause() {
  mySvg.pauseAnimations()
}

function play() {
  mySvg.unpauseAnimations()
}

function stop() {
  clearInterval();
  setCurrentTime(0);
  mySvg.pauseAnimations()
  updateTimer();
}

<svg id="mySvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="80 0 1024 768" onload="t=setInterval(updateTimer, 100)">
  <linearGradient id="grad">
    <stop stop-color="rgb(10%,80%,10%)" offset="0"/>
    <stop stop-color="rgb(10%,40%,20%)" offset="0.4"/>
    <stop stop-color="rgb(10%,90%,30%)" offset="0.7"/>
    <stop stop-color="rgb(10%,50%,40%)" offset="1"/>
  </linearGradient>
  <rect fill="url(#grad)" width="0%" height="50" x="100" y="300" rx="5">
    <animate attributeName="width" to="100%" begin="0s" dur="30s"/>
  </rect>
  <text id="t" style="font:24px Arial Black;fill:white;stroke:black" transform="translate(100 334)"/>
  <animateTransform type="translate" attributeName="transform" xlink:href="#t" begin="1s" dur="29s" from="100 334" to="1024 334"/>
  <g transform="translate(100 500)">
    <!-- Play -->
    <g onclick="play()">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5"/>
     <path id="play" d="M12 5l20 15l-20 15Z" fill="white" pointer-events="none"/>
   </g>
   <!-- Pause -->
   <g transform="translate(50 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="pause();"/>
     <path id="pause" d="M14 10l0 20M26 10l0 20" stroke="white" fill="none" stroke-width="8" pointer-events="none"/>
   </g>
   <!-- Stop (rewind and pause) -->
   <g transform="translate(100 0)">
     <rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="stop()"/>
     <rect x="10" y="10" width="20" height="20" fill="white" pointer-events="none"/>
   </g>
 </g>
</svg>

Long version: After all that, why wasn't it working in Codepen?
I can see that the link you posted is to an SVG document with it's own inline JavaScript (in the script tag).

The script calls some SVGElement methods on the SVG root element with document.documentElement.pauseAnimations();.
But what exactly is document element?

Document.documentElement returns the Element that is the root element of the document (for example, the  element for HTML documents).

Because this code was called inside an SVG document, document.documentElement returns the SVG root node. However, because codepen is an HTML document, document.documentElement will return the HTML root node.

And you can't call methods like pauseAnimations() on an HTML root node because the HTML root node doesn't understand those methods.

So modern browsers can display SVG documents, HTML documents (and more) but here's the kicker: SVG documents can live inside of HTML documents.

You can see how document.documentElement could refer to two potential things depending on what type of document the JavaScript code was run from.


问:
pytest mark order not working
I have about 10 tests in same file and each one them has following set to execute in order

```<code>import pytest
@pytest.mark.order1
.
.
.
@pytest.mark.order10
</code>```

But the tests never run in the order they are assigned. They always run in the order they are arranged. Anything I am missing ?

even @pytest.mark.tryfirst didn't work. One thing I noticed is, the @pytest.mark.order never shows up in suggestions while atleast @pyetst.mark.tryfirst was there in pycharm.

答:
It looks like you're using pytest-ordering. Make sure you already have installed pytest-ordering in you env, here de docs: https://github.com/ftobia/pytest-ordering and try to use the following decoration

@pytest.mark.run(order=1)

Title: pytest mark order not working

Body:
I have about 10 tests in same file and each one them has following set to execute in order

import pytest
@pytest.mark.order1
.
.
.
@pytest.mark.order10

But the tests never run in the order they are assigned. They always run in the order they are arranged. Anything I am missing ?

even @pytest.mark.tryfirst didn't work. One thing I noticed is, the @pytest.mark.order never shows up in suggestions while atleast @pyetst.mark.tryfirst was there in pycharm.


问:
Dynamic Reconfigure in ROS
I am going through the ROS tutorials for Dynamic Reconfigure. I have very little background in C++. I am having trouble understanding some lines in particular.

I have tried to go through some tutorials for C++ and boost but the jargon used is beyond by technical level.
The exact lines are as follows:

```<code>dynamic_reconfigure::Server<parameter_test::parametersConfig>::CallbackType f;
f = boost::bind(&callback, _1, _2);
</code>```

My questions are:

1) Could someone explain in simple terms what :: or the namespace resolution operator does?

2) What exactly is boost::bind() and what does it do?

3) What are the arguments _1 and _2 supposed to do?

The link for the complete file is on:

http://wiki.ros.org/dynamic_reconfigure/Tutorials/SettingUpDynamicReconfigureForANode%28cpp%29

Thanks in advance.

答:
The namespace resolution operator allows you to specify a "path" to the function/class/variable (by default it uses the global namespace or ADL ; here it denotes the fact that we use the bind from the boost namespace.

boost::bind allows you to bind (as a form of Partial Application) parameters of a function.

_1 and _2 are placeholders for boost::bind that tells how to "route" the unbound parameters (those not provided as arguments of bind) :

```<code>void f(int a, int b);

auto x = boost::bind(f, _1, _2);
x(1, 2); //a=1 b=2

auto y = boost::bind(f, _2, _1);
y(1,2); //a=2 b=1
</code>```

Title: Dynamic Reconfigure in ROS

Body:
I am going through the ROS tutorials for Dynamic Reconfigure. I have very little background in C++. I am having trouble understanding some lines in particular.

I have tried to go through some tutorials for C++ and boost but the jargon used is beyond by technical level.
The exact lines are as follows:

dynamic_reconfigure::Server<parameter_test::parametersConfig>::CallbackType f;
f = boost::bind(&callback, _1, _2);

My questions are:

1) Could someone explain in simple terms what :: or the namespace resolution operator does?

2) What exactly is boost::bind() and what does it do?

3) What are the arguments _1 and _2 supposed to do?

The link for the complete file is on:

http://wiki.ros.org/dynamic_reconfigure/Tutorials/SettingUpDynamicReconfigureForANode%28cpp%29

Thanks in advance.

Body:
The namespace resolution operator allows you to specify a "path" to the function/class/variable (by default it uses the global namespace or ADL ; here it denotes the fact that we use the bind from the boost namespace.

boost::bind allows you to bind (as a form of Partial Application) parameters of a function.

_1 and _2 are placeholders for boost::bind that tells how to "route" the unbound parameters (those not provided as arguments of bind) :

void f(int a, int b);

auto x = boost::bind(f, _1, _2);
x(1, 2); //a=1 b=2

auto y = boost::bind(f, _2, _1);
y(1,2); //a=2 b=1


问:
How do I post contents of a Quill editor in a form?
I have what I think is a very common scenario. I would normally have this form:

```<code><form method="post">

<textarea name="text"></textarea>
<input type="submit" value="Save" />

</form>
</code>```

Then with PHP I would capture the data from the form ($_POST['text']) and I could use that in another variable.

Now, I'd like to use Quill so users have a nice rich text editor instead. Quill seems very well suited for this and the documentation is very detailed. However, for some reason I can not find how I can "post" the data to the form. There is one single sample page that sort of does what I want, but I am unable to fully implement this in my sample, and in the quick start guide this rather fundamental (to me) topic is not discussed, and I can not find this in the documentation either.

Is Quill supposed to be used like this? Am I overseeing something? Is there a recommended way to make this work?

This is what I currently have:

```<code><!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">
</head>
<body>
<form method="post">

<!-- Create the toolbar container -->
<div id="toolbar">
  <button class="ql-bold">Bold</button>
  <button class="ql-italic">Italic</button>
</div>

<form method="post">

<!-- Create the editor container -->
<div id="editor">
  <p>Hello World!</p>
</div>

<input type="submit" value="Save" />

</form>

<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
  var editor = new Quill('#editor', {
    modules: { toolbar: '#toolbar' },
    theme: 'snow'
  });
</script>
</body>
</html>
</code>```

答:
Try this:</p>

```<code><!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
    var quill = new Quill('#editor', {
        modules: {
            toolbar: [
                ['bold', 'italic'],
                ['link', 'blockquote', 'code-block', 'image'],
                [{
                    list: 'ordered'
                }, {
                    list: 'bullet'
                }]
            ]
        },
        placeholder: 'Compose an epic...',
        theme: 'snow'
    });

    $("#form").submit(function() {
        $("#description").val(quill.getContents());
    });
</script>
</code>```

Body:
I have what I think is a very common scenario. I would normally have this form:

<form method="post">

<textarea name="text"></textarea>
<input type="submit" value="Save" />

</form>

Then with PHP I would capture the data from the form ($_POST['text']) and I could use that in another variable.

Now, I'd like to use Quill so users have a nice rich text editor instead. Quill seems very well suited for this and the documentation is very detailed. However, for some reason I can not find how I can "post" the data to the form. There is one single sample page that sort of does what I want, but I am unable to fully implement this in my sample, and in the quick start guide this rather fundamental (to me) topic is not discussed, and I can not find this in the documentation either.

Is Quill supposed to be used like this? Am I overseeing something? Is there a recommended way to make this work?

This is what I currently have:

<!doctype html>

<title>Test</title>
<meta charset="UTF-8" />
<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">

<form method="post">

  <button class="ql-bold">Bold</button>
  <button class="ql-italic">Italic</button>

<form method="post">

Hello World!

<input type="submit" value="Save" />

</form>

Body:
Try this:

<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
    var quill = new Quill('#editor', {
        modules: {
            toolbar: [
                ['bold', 'italic'],
                ['link', 'blockquote', 'code-block', 'image'],
                [{
                    list: 'ordered'
                }, {
                    list: 'bullet'
                }]
            ]
        },
        placeholder: 'Compose an epic...',
        theme: 'snow'
    });

    $("#form").submit(function() {
        $("#description").val(quill.getContents());
    });
</script>


问:
How to modify SpeakHere sample code to record and play audio like a loopback?
I want to change SpeakHere application to record and play audio like a loopback, means after recording.. the recorded voice should immediately repeats what is recorded like a eco.

Can anyone tell me in which part of code I have to make changes to achieve this.

Also am not able to download sample code of SpeakHere application from following link. Kindly guide from where to download the code.

https://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007802-Intro-DontLinkElementID_2

Thanks in advance

答:
I just tried the link you posted and it works fine.

To echo the users voice you will need another AudioQueue to monitor input levels. When the input level passes a certain threshold, start recording. When the input level falls below that threshold for a length of time, stop recording and start playback.

You can set up another AudioQueue to monitor by copying the code that does the recording. Just dummy out the callback code so it doesn't actually do anything.

Set the controller as a delegate in the monitor class. That should then receive method calls stating whether the monitor has checked a level above or below the threshold.

Then, in the controller you can start, stop, and playback as need be.

ContentLicense: CC BY-SA 2.5


问:
php curl output ehco it self
I have writen a php curl function for downloading a web page from an ssl enable site.
It is no working as I want it to.  It echos itself even if I have not used the echo command elsewhere.
I want to use this function to save the download page but it saves 1 file not the whole data.

I already googled about this issue but had no success.  Writing on stack overflow is always last option for me and I always avoid due to my bad english as well as bad explanation

```<code>function gssl($target_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,true);
    curl_setopt($ch, CURLOPT_CAINFO, 'C:\Users\PC\Desktop\ssl\cacert-2019-05-15.pem');
    //curl_setopt($ch, CURLOPT_CAINFO, 'https://curl.haxx.se/ca/cacert-2019-05-15.pem');
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_URL,$target_url);
    curl_setopt($ch, CURLOPT_VERBOSE,true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    $html= curl_exec($ch);
    return $html;
    }

function write($post,$myFile){
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $post);
fclose($fh);
}
</code>```

答: Set CURLOPT_RETURNTRANSFER to true</p>

Title: php curl output ehco it self

Body:
I have writen a php curl function for downloading a web page from an ssl enable site.
It is no working as I want it to.  It echos itself even if I have not used the echo command elsewhere.
I want to use this function to save the download page but it saves 1 file not the whole data.

I already googled about this issue but had no success.  Writing on stack overflow is always last option for me and I always avoid due to my bad english as well as bad explanation

function gssl($target_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,true);
    curl_setopt($ch, CURLOPT_CAINFO, 'C:\Users\PC\Desktop\ssl\cacert-2019-05-15.pem');
    //curl_setopt($ch, CURLOPT_CAINFO, 'https://curl.haxx.se/ca/cacert-2019-05-15.pem');
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_URL,$target_url);
    curl_setopt($ch, CURLOPT_VERBOSE,true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    $html= curl_exec($ch);
    return $html;
    }

function write($post,$myFile){
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $post);
fclose($fh);
}

Body: Set CURLOPT_RETURNTRANSFER to true


问:
Invalidating IdentityServer session and access token when a user's password changes
I'm using IdentityServer4 in ASP.NET Core 2.2. The client application (RP) is an API, also an ASP.NET Core 2.2 application. The user logs in using the authorization code flow and gets a cookie from IdentityServer (idsrv). They then get an authorization code and and access token for the API (RP).

I want to be able to revoke a user's existing login session and access tokens in some cases, e.g. if their password has been reset. In IdentityServer I've implemented added my own authentication scheme:

```<code>            .AddCookie("MyAuthenticationScheme", options =>
            {
                options.SessionStore = new MyTicketStore();
                options.EventsType = typeof(MyCookieAuthenticationEvents);
            })
</code>```

This allows me to invalidate the user's IdentityServer session on the server before the authentication ticket expires. For example, when the user is signed in I add a claim that stores the date their password was last changed and in MyCookieAuthenticationEvents.ValidatePrincipal() I check that it has not been changed since, as suggested on https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2#react-to-back-end-changes

I want to do the same with the access token they use the access the RP. If the user's password has changed (and in some other cases) I want the access token to be invalidated immediately, rather than waiting for it to expire. I'm using reference tokens and have implemented IProfileService and ICustomTokenValidator. In IProfileService.GetProfileDataAsync I copy the password change date claim to the access token claims collection and in ICustomTokenValidator.ValidateAccessTokenAsync I again check that claim against the real user.

This works, but it seems quite convoluted and complicated and I wonder if there is a simpler way to accomplish this - it seems like this should be a common requirement.

答: If you are using reference tokens, all you need to in order to invalidate the token is to remove it from whatever implementation of IPersistedGrantStore you have and the next time reference token is attempted to be validated through introspection, it will be invalid since it will no longer exist.

Body:
I'm using IdentityServer4 in ASP.NET Core 2.2. The client application (RP) is an API, also an ASP.NET Core 2.2 application. The user logs in using the authorization code flow and gets a cookie from IdentityServer (idsrv). They then get an authorization code and and access token for the API (RP).

I want to be able to revoke a user's existing login session and access tokens in some cases, e.g. if their password has been reset. In IdentityServer I've implemented added my own authentication scheme:

            .AddCookie("MyAuthenticationScheme", options =>
            {
                options.SessionStore = new MyTicketStore();
                options.EventsType = typeof(MyCookieAuthenticationEvents);
            })

This allows me to invalidate the user's IdentityServer session on the server before the authentication ticket expires. For example, when the user is signed in I add a claim that stores the date their password was last changed and in MyCookieAuthenticationEvents.ValidatePrincipal() I check that it has not been changed since, as suggested on https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2#react-to-back-end-changes

I want to do the same with the access token they use the access the RP. If the user's password has changed (and in some other cases) I want the access token to be invalidated immediately, rather than waiting for it to expire. I'm using reference tokens and have implemented IProfileService and ICustomTokenValidator. In IProfileService.GetProfileDataAsync I copy the password change date claim to the access token claims collection and in ICustomTokenValidator.ValidateAccessTokenAsync I again check that claim against the real user.

This works, but it seems quite convoluted and complicated and I wonder if there is a simpler way to accomplish this - it seems like this should be a common requirement.


问:
Vue.js data-bind style backgroundImage not working
I'm trying to bind the src of an image in an element, but it doesn't seem to work. I'm getting an "Invalid expression. Generated function body:  { backgroundImage:{ url(image) }".

The documentation says to use either 'Kebab-case' or 'camel-case'.

```<code><div class="circular" v-bind:style="{ backgroundImage: { url(image) }"></div>
</code>```

Heres a fiddle: https://jsfiddle.net/0dw9923f/2/

答:
I experienced an issue where background images with spaces in the filename where causing the style to not be applied. To correct this I had to ensure the string path was encapsulated in single quotes.

Note the escaped \' in my example below.

```<code><div :style="{
    height: '100px',
    backgroundColor: '#323232',
    backgroundImage: 'url(\'' + event.image + '\')',
    backgroundPosition: 'center center',
    backgroundSize: 'cover'
    }">
</div>
</code>```

Body:
I'm trying to bind the src of an image in an element, but it doesn't seem to work. I'm getting an "Invalid expression. Generated function body:  { backgroundImage:{ url(image) }".

The documentation says to use either 'Kebab-case' or 'camel-case'.

Heres a fiddle: https://jsfiddle.net/0dw9923f/2/

Body:
I experienced an issue where background images with spaces in the filename where causing the style to not be applied. To correct this I had to ensure the string path was encapsulated in single quotes.

Note the escaped \' in my example below.

<div :style="{
    height: '100px',
    backgroundColor: '#323232',
    backgroundImage: 'url(\'' + event.image + '\')',
    backgroundPosition: 'center center',
    backgroundSize: 'cover'
    }">
</div>


问:
problem with rails - "Could not find gem 'pg"
bonjour dudes.
i have a small problem with rails.
today i install rails 3 and decided create a new project.

```<code>rails new blablabla --database=postgresql
</code>```

i edited database.yml and paste to it my databases, logins and passwords of postgres.
my postgresql works on port 5433 (instead of 5432)
database.yml example:

```<code>development:
adapter: postgresql
database: devdb
encoding: utf8
username: postgres
password: mypassword
host: localhost
port: 5433
</code>```

i just want to start server, or add controller, but rails says:

```<code>Could not find gem 'pg (>= 0)' in any of the gem sources listed in your Gemfile
</code>```

but i have 'pg'. i think problem with port, but i dont know how fix problem.

sorry for bad english, and thanks for answers.

答:
It would appear from the error message that you are using Bundler to manage your gems for the project.  Have you tried running bundle install to bring all of your sources in the Gemfile up to date?  Here is an example:

```<code>> bundle install
Using rake (0.8.7)
Using abstract (1.0.0)
Using activesupport (3.0.3)
[...]
Using zendesk_remote_auth (0.9.0)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
</code>```

Body:
bonjour dudes.
i have a small problem with rails.
today i install rails 3 and decided create a new project.

rails new blablabla --database=postgresql

i edited database.yml and paste to it my databases, logins and passwords of postgres.
my postgresql works on port 5433 (instead of 5432)
database.yml example:

development:
adapter: postgresql
database: devdb
encoding: utf8
username: postgres
password: mypassword
host: localhost
port: 5433

i just want to start server, or add controller, but rails says:

Could not find gem 'pg (>= 0)' in any of the gem sources listed in your Gemfile

but i have 'pg'. i think problem with port, but i dont know how fix problem.

sorry for bad english, and thanks for answers.

Body:
It would appear from the error message that you are using Bundler to manage your gems for the project.  Have you tried running bundle install to bring all of your sources in the Gemfile up to date?  Here is an example:

> bundle install
Using rake (0.8.7)
Using abstract (1.0.0)
Using activesupport (3.0.3)
[...]
Using zendesk_remote_auth (0.9.0)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.


答:
You are returning the result of curl_exec($ch); not the page from the web site. Use the CURLOPT_FILE cURL option to have the returned data put directly into a file.

And, as James said, enable CURLOPT_RETURNTRANSFER too.

Title: php curl output ehco it self


问:
Heroku Apache, Parse HTML also as PHP
How can I modify .htaccess and httpd.conf in Heroku? I connected it with a repository on Github.

In Github I've tried multiple things, those all don't work. Putting httpd.conf in a folder called /conf/httpd/default.conf didn't work, not sure not even in the repo root it worked, when I tried to put httpd.conf and .htaccess in there, nothing ever happens and I'm not sure why.

I am using the apache2 buildpack from Heroku that is inside a Procfile heroku-php-apache2

I am trying to tell the httpd.conf to parse .html also with php, so I can include things in it.

There is that thing on Github https://github.com/heroku/heroku-buildpack-php not sure if that can help.

Update:

Apperantly when using -c httpd.conf to tell where the httpd.conf is, it started recognising it and using it, what I get now is this:

no listening sockets available, shutting down

Update:

I used -C httpd.conf and it included it now, the problem is
The changes I want to make do not really apply. I'm trying to parse HTML also as PHP.

答:
I just ended up using PHP.

You could try it with a custom buildpack but I don't know how to make one so it can actually use it's own httpd.conf and not the one from the heroku php buildpack.

Title: Heroku Apache, Parse HTML also as PHP


问:
How to remove invisible chars in bash (tr and sed not working)
I want to remove invisible chars from a response:

Here is my code:

```<code>test_id=`clasp run testRunner`
echo "visible"
echo "$test_id"
echo "invisible"
echo "$test_id" | cat -v
echo "invisible2"
echo "$test_id" | tr -dc '[:print:]' | cat -v
echo "invisible3"
echo "$test_id" | sed 's/[^a-zA-Z0-9]//g' | cat -v
echo "invisible4"
printf '%q\n' "$test_id"
</code>```

Here's the output:

```<code>visible
1d5422fb
invisible
^[[2K^[[1G1d5422fb
invisible2
[2K[1G1d5422fbinvisible3
2K1G1d5422fb
invisible4
$'\E[2K\E[1G1d5422fb'
</code>```

答:
The following code works with your example:

```<code>shopt -s extglob
test_id=$'\e[2K\e[1G1d5422fb'
test_id="${test_id//$'\e['*([^a-zA-Z])[a-zA-Z]}"
echo "$test_id" | cat -v
</code>```

The crucial part is the third line, which applies a string substitution to the expanded variable. It matches (and removes) all occurrences of the pattern

$'\e[' - a single Esc character followed by [

*( ... ) - (this is what extglob is needed for) zero or more occurrences of ...

[^a-zA-Z] - a single non-alphabetic character

[a-zA-Z] - a single alphabetic character

In your example this gets rid of the two escape sequences \e[2K (erase line) and \e[1G (move cursor to column 1).

Body:
I want to remove invisible chars from a response:

Here is my code:

test_id=`clasp run testRunner`
echo "visible"
echo "$test_id"
echo "invisible"
echo "$test_id" | cat -v
echo "invisible2"
echo "$test_id" | tr -dc '[:print:]' | cat -v
echo "invisible3"
echo "$test_id" | sed 's/[^a-zA-Z0-9]//g' | cat -v
echo "invisible4"
printf '%q\n' "$test_id"

Here's the output:

visible
1d5422fb
invisible
^[[2K^[[1G1d5422fb
invisible2
[2K[1G1d5422fbinvisible3
2K1G1d5422fb
invisible4
$'\E[2K\E[1G1d5422fb'

Body:
The following code works with your example:

shopt -s extglob
test_id=$'\e[2K\e[1G1d5422fb'
test_id="${test_id//$'\e['*([^a-zA-Z])[a-zA-Z]}"
echo "$test_id" | cat -v

The crucial part is the third line, which applies a string substitution to the expanded variable. It matches (and removes) all occurrences of the pattern

$'\e[' - a single Esc character followed by [

*( ... ) - (this is what extglob is needed for) zero or more occurrences of ...

[^a-zA-Z] - a single non-alphabetic character

[a-zA-Z] - a single alphabetic character

In your example this gets rid of the two escape sequences \e[2K (erase line) and \e[1G (move cursor to column 1).


问:
Is there a way to plot a bar chart with using a dataframe tuple index as 'x' input?
I have a dataframe (see below), which contains the probability that a flood occurs within ranges of rainfall magnitude (pcp, the index of this df), and  . I understand this to be a tuple index??

```<code>                FLd_prb
pcp
(0.0, 1.0]      0.166667
(1.0, 2.0]      0.315789
(2.0, 3.0]      0.437500
(3.0, 4.0]      0.222222
(4.0, 5.0]      0.142857
(5.0, 7.5]      0.437500
(7.5, 10.0]     0.250000
(10.0, 12.5]    0.000000
(12.5, 15.0]    0.200000
</code>```

I am trying to plot a matplotlib bar chart but I seem to be unable to use this index as an 'x' input. To be clearer, in the user guide I understand that to make this type of plot by:

```<code>plt.bar(x, height...)
</code>```

So I want to use the tuple index as 'x' and the 'Fld_prb' and height...

Can you offer some ideas?

Thanks

答:
Strictly speaking your df's index does not consist of tuples, but non-overlapping ranges of values, which you can think of as ordinal categories for plotting.

Simply calling df.plot.bar() will do the trick:

```<code>import matplotlib.pyplot as plt

df.plot.bar(rot=0, figsize=(10, 10))
plt.show()
</code>```

You can look at the docs for options to customize the plot.

Body:
I have a dataframe (see below), which contains the probability that a flood occurs within ranges of rainfall magnitude (pcp, the index of this df), and  . I understand this to be a tuple index??

                FLd_prb
pcp
(0.0, 1.0]      0.166667
(1.0, 2.0]      0.315789
(2.0, 3.0]      0.437500
(3.0, 4.0]      0.222222
(4.0, 5.0]      0.142857
(5.0, 7.5]      0.437500
(7.5, 10.0]     0.250000
(10.0, 12.5]    0.000000
(12.5, 15.0]    0.200000

I am trying to plot a matplotlib bar chart but I seem to be unable to use this index as an 'x' input. To be clearer, in the user guide I understand that to make this type of plot by:

plt.bar(x, height...)

So I want to use the tuple index as 'x' and the 'Fld_prb' and height...

Can you offer some ideas?

Thanks

Body:
Strictly speaking your df's index does not consist of tuples, but non-overlapping ranges of values, which you can think of as ordinal categories for plotting.

Simply calling df.plot.bar() will do the trick:

import matplotlib.pyplot as plt

df.plot.bar(rot=0, figsize=(10, 10))
plt.show()

You can look at the docs for options to customize the plot.


问:
Passing Arrays to C# DLL from Python Without Unsafe Code and Native C# Arrays
Anyone know of a better way of passing arrays from Python to a C# DLL without having to resort to unsafe C# code, and preferably using native C# arrays? Also, is there a better or cleaner way of creating the array types in Python that needed to be passed to the C# DLL without having to instantiate each element?

I'm calling a C# library from python as shown here: Calling a C# library from python. Here's my current C# DLL code:

```<code>using System.Runtime.InteropServices;
using RGiesecke.DllExport;

namespace TestLib
{
    public class TestLib
    {
        [DllExport("running_sum", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static int running_sum(double* running_sum, int n, double* values)
        {
            // check for errors and return error code
            if (n <= 0 || running_sum == null || values == null)
                return 1;

            running_sum[0] = values[0];
            int i = 1;
            while (i < n)
            {
                running_sum[i] = running_sum[i - 1] + values[i];
                i++;
            }

            // return success
            return 0;
        }
    }
}
</code>```

Here's my Python 3.4 code calling this C# DLL:

```<code>import ctypes

library = ctypes.cdll.LoadLibrary('../TestLib/TestLib')
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
running_sum_c = ctypes.ARRAY(ctypes.c_double, len(values))()
values_c = ctypes.ARRAY(ctypes.c_double, len(values))()
for i in range(len(values)):
    values_c[i] = values[i]
print('running sum return code: ', library.running_sum(running_sum_c, len(values), values_c))
print('result: ', list(running_sum_c))
</code>```

答:
I don't think it would be possible, recently exists CoreRT which allows to compile native libs and use outside of .Net Framework (really .Net Core). It's really cool and works as fine as is possible. (Only for windows, linux and osx x64 platform)

https://dev.to/encrypt0r/writing-native-libraries-in-c-3kl

Body:
Anyone know of a better way of passing arrays from Python to a C# DLL without having to resort to unsafe C# code, and preferably using native C# arrays? Also, is there a better or cleaner way of creating the array types in Python that needed to be passed to the C# DLL without having to instantiate each element?

I'm calling a C# library from python as shown here: Calling a C# library from python. Here's my current C# DLL code:

using System.Runtime.InteropServices;
using RGiesecke.DllExport;

namespace TestLib
{
    public class TestLib
    {
        [DllExport("running_sum", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static int running_sum(double* running_sum, int n, double* values)
        {
            // check for errors and return error code
            if (n <= 0 || running_sum == null || values == null)
                return 1;

            running_sum[0] = values[0];
            int i = 1;
            while (i < n)
            {
                running_sum[i] = running_sum[i - 1] + values[i];
                i++;
            }

            // return success
            return 0;
        }
    }
}

Here's my Python 3.4 code calling this C# DLL:

import ctypes

library = ctypes.cdll.LoadLibrary('../TestLib/TestLib')
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
running_sum_c = ctypes.ARRAY(ctypes.c_double, len(values))()
values_c = ctypes.ARRAY(ctypes.c_double, len(values))()
for i in range(len(values)):
    values_c[i] = values[i]
print('running sum return code: ', library.running_sum(running_sum_c, len(values), values_c))
print('result: ', list(running_sum_c))


问:
mod_Rewrite conditions and rules ( confused ) help please
Help please,

After numerous hours searching for the solution to my problem i have become completely confused, so my appologies if this as been answered before.

I have a current URL as so :

http://www.mydomain.com/news/dentistry_dental/article_detail.php?article=2968&title=redefining-oral-hygiene-intervention

I am cleaning up my urls so have now created a rewrite rule to parse the following to the previous url :

http://www.mydomain.com/dental_news/2968/Redefining-oral-hygiene-intervention

The rule i have used in the .htaccess file for this is as below :

```<code>RewriteRule ^dental_news/([^/]*)/([^/]*)$ /news/dentistry_dental/article_detail.php?article=$1&title=$2 [L]
</code>```

This is working as expected, however.. I need to also have the OLD url ( That is indexed on many Search Engines ) to now point to the NEW url with a 301 redirect.

I have tried numerous things but as of yet i get nothing but errors, i presume its a looping error i have.

Does anyone out there have any idea how i can achieve the 2 way redirect without looping?

Any help will be greatly appreciated

EDIT

The above problem has been resolved, as you can see by the answer below, however i now have another query, this should help me in understanding whats going on i hope :)

I have another URL www.mydomain.com/news/dentistry_dental/index.php that i want to redirect with 301 to www.mydomain.com/dental_news/

I have tried rewriting the code from the answer below to do this but it was a fail, i am still lacking understanding of the whole thing i think.

Any help be great :)

Regards
M

答:
Try the following.  The first condition should protect you from a redirect loop (it only matches requests not beginning with /dental_news.  The %1 and %2 will match the corresponding regex groups from the previous RewriteCond.  Also, the trailing ? on the RewriteRule, will remove the querystring on redirect.

```<code>RewriteCond %{REQUEST_URI} !^\/dental_news\/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=(.*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]
</code>```

Hope this helps.

EDIT:
I changed the last group of the second RewriteCond to match up until the $ of $fr=1, if this is intended to be &1, you can change the end of the RewriteCond to group ([^&]*) instead.

```<code>RewriteCond %{REQUEST_URI} !^\/dental_news\/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^$]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]
</code>```

EDIT:

```<code>RewriteEngine On

RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]
</code>```

Body:
Help please,

After numerous hours searching for the solution to my problem i have become completely confused, so my appologies if this as been answered before.

I have a current URL as so :

http://www.mydomain.com/news/dentistry_dental/article_detail.php?article=2968&title=redefining-oral-hygiene-intervention

I am cleaning up my urls so have now created a rewrite rule to parse the following to the previous url :

http://www.mydomain.com/dental_news/2968/Redefining-oral-hygiene-intervention

The rule i have used in the .htaccess file for this is as below :

RewriteRule ^dental_news/([^/]*)/([^/]*)$ /news/dentistry_dental/article_detail.php?article=$1&title=$2 [L]

This is working as expected, however.. I need to also have the OLD url ( That is indexed on many Search Engines ) to now point to the NEW url with a 301 redirect.

I have tried numerous things but as of yet i get nothing but errors, i presume its a looping error i have.

Does anyone out there have any idea how i can achieve the 2 way redirect without looping?

Any help will be greatly appreciated

EDIT

The above problem has been resolved, as you can see by the answer below, however i now have another query, this should help me in understanding whats going on i hope :)

I have another URL www.mydomain.com/news/dentistry_dental/index.php that i want to redirect with 301 to www.mydomain.com/dental_news/

I have tried rewriting the code from the answer below to do this but it was a fail, i am still lacking understanding of the whole thing i think.

Any help be great :)

Regards
M

Body:
Try the following.  The first condition should protect you from a redirect loop (it only matches requests not beginning with /dental_news.  The %1 and %2 will match the corresponding regex groups from the previous RewriteCond.  Also, the trailing ? on the RewriteRule, will remove the querystring on redirect.

RewriteCond %{REQUEST_URI} !^\/dental_news\/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=(.*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

Hope this helps.

EDIT:
I changed the last group of the second RewriteCond to match up until the $ of $fr=1, if this is intended to be &1, you can change the end of the RewriteCond to group ([^&]*) instead.

RewriteCond %{REQUEST_URI} !^\/dental_news\/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^$]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

EDIT:

RewriteEngine On

RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]


问:
How to track spring controller api response in brave trace object
We are using annotation based span tags to tag method values and request object in controller. We have seen two behaviors

When there is error or runtime exception trace object gets http status 500 and error message which is expected.

When API call is successful it doesn't not show any http status code tag in span object which should be 200 ok.

We are not able to include api response object in span.
Controller API call is like this:

```<code>  @PostMapping(path = "/{reuqestParam}/submit")
  @ContinueSpan(log = "submit")
  public IngestionResponse submit(final InputStream inputStream,
      @SpanTag("reuqestParam") @PathVariable String reuqestParam,
      @SpanTag("HttpHeaders") @RequestHeader HttpHeaders httpHeaders) {
    LOGGER.info("[Upload to Stream]: Begin");
    final IngestionResponse ingestionResponse = ingestionService
        .ingestInputStream(inputStream, reuqestParam, httpHeaders);
    LOGGER.info("[Upload to Stream]: Completed");
    return ingestionResponse;
  }
</code>```

Span object contains method parameter / method name but HTTP status code is missing also response object. We need to capture both information regardless api success or failure.

答:
You will need to create an instance of HttpServerParser overriding this bean: https://github.com/spring-cloud/spring-cloud-sleuth/blob/master/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceHttpAutoConfiguration.java#L109

The reason is documented in the default implementation: https://github.com/apache/incubator-zipkin-brave/blob/master/instrumentation/http/src/main/java/brave/http/HttpParser.java#L75...L94

You should be able to override that with minimal changes

Body:
We are using annotation based span tags to tag method values and request object in controller. We have seen two behaviors

When there is error or runtime exception trace object gets http status 500 and error message which is expected.

When API call is successful it doesn't not show any http status code tag in span object which should be 200 ok.

We are not able to include api response object in span.
Controller API call is like this:

  @PostMapping(path = "/{reuqestParam}/submit")
  @ContinueSpan(log = "submit")
  public IngestionResponse submit(final InputStream inputStream,
      @SpanTag("reuqestParam") @PathVariable String reuqestParam,
      @SpanTag("HttpHeaders") @RequestHeader HttpHeaders httpHeaders) {
    LOGGER.info("[Upload to Stream]: Begin");
    final IngestionResponse ingestionResponse = ingestionService
        .ingestInputStream(inputStream, reuqestParam, httpHeaders);
    LOGGER.info("[Upload to Stream]: Completed");
    return ingestionResponse;
  }

Span object contains method parameter / method name but HTTP status code is missing also response object. We need to capture both information regardless api success or failure.


问:
XSLT Create Subtags from Metadata
not sure if metadata is the correct terminology but I couldn't find a better descriptor. I have an XML that I need to transform in a few ways, but I need help with the ENTINFO tags specifically. What I'd like to do, is create a base tag called ENTINFO and then within that have each ENTINFO tag be a separate sub-field.

I have an XSLT written for the other transformations, but it's from back when I thought I didn't need the ENTINFO tags so it currently excludes them. I haven't found much in the documentation regarding how I can do what I need to do.

Original XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI fitype="B" xref="54815594127">
         <FIName>BANK OF FURY, N.A.</FIName>
         <FITIN>987654321</FITIN>
      </FI>
      <OIs>
         <OI xref="54815594128">
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectFullName type="L">SMITH/JANE/C</SubjectFullName>
            <SubjectLastName type="L">SMITH</SubjectLastName>
            <SubjectFirstName type="L">JANE</SubjectFirstName>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-001">Refer to <ENAMEX type="BANKDIV" id="BAN-123456789-000">FCI</ENAMEX>
            <NUMEX type="CASENUM" id="CAS-123456789-001">Case # FRD-123</NUMEX>.</S>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            NORM="333222111000"
            REFID="ACC-123456789-013"
            ACCT-TYPE="CHK"
            MENTION="MI checking account # 333222111000"/>
   <ENTINFO ID="ACC-123456789-027"
            TYPE="ACCOUNT"
            NORM="000111222333444"
            REFID="ACC-123456789-027"
            ACCT-TYPE="UNK"
            MENTION="debit card #s 000111222333444"/>
</NORMDOC>
</code>```

XSLT

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>
</code>```

Actual Output

```<code><DOC>
   <DOCID>123456789</DOCID>
   <FI>
      <FIName>BANK OF FURY, N.A.</FIName>
      <FITIN>987654321</FITIN>
   </FI>
   <OIs>
      <OI>
         <OIName>BANK OF FURY, N.A.</OIName>
      </OI>
   </OIs>
   <Subjects>
      <Subject>
         <SubjectFullName>SMITH/JANE/C</SubjectFullName>
         <SubjectLastName>SMITH</SubjectLastName>
         <SubjectFirstName>JANE</SubjectFirstName>
      </Subject>
   </Subjects>
   <RAW_TXT>Refer to FCICase # FRD-123.For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
   <TXT>
      <S>
         <ENAMEX_BANKDIV>FCI</ENAMEX_BANKDIV>
         <NUMEX_CASENUM>Case # FRD-123</NUMEX_CASENUM>
      </S>
      <S>
         <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
         <IDEX_PHONE>000-000-0000</IDEX_PHONE>
         <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
      </S>
   </TXT>
</DOC>
</code>```

Expected Output

```<code><DOC>
   <DOCID>123456789</DOCID>
   <FI>
      <FIName>BANK OF FURY, N.A.</FIName>
      <FITIN>987654321</FITIN>
   </FI>
   <OIs>
      <OI>
         <OIName>BANK OF FURY, N.A.</OIName>
      </OI>
   </OIs>
   <Subjects>
      <Subject>
         <SubjectFullName>SMITH/JANE/C</SubjectFullName>
         <SubjectLastName>SMITH</SubjectLastName>
         <SubjectFirstName>JANE</SubjectFirstName>
      </Subject>
   </Subjects>
   <RAW_TXT>Refer to FCICase # FRD-123.For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
   <TXT>
      <S>
         <ENAMEX_BANKDIV>FCI</ENAMEX_BANKDIV>
         <NUMEX_CASENUM>Case # FRD-123</NUMEX_CASENUM>
      </S>
      <S>
         <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
         <IDEX_PHONE>000-000-0000</IDEX_PHONE>
         <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
      </S>
   </TXT>
</DOC>
<ENTINFO>
   <ENTINFO>
       <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
       <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
       <ENTINFO_NORM>333222111000</ENTINFO_NORM>
       <ENTINFO_REFID>ACC-123456789-013</ENTINFO_REFID>
       <ENTINFO_ACCTTYPE>CHK</ENTINFO_ACCTTYPE>
       <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
   </ENTINFO>
   <ENTINFO>
       <ENTINFO_ID>ACC-123456789-027</ENTINFO_ID>
       <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
       <ENTINFO_NORM>000111222333444</ENTINFO_NORM>
       <ENTINFO_REFID>ACC-123456789-027</ENTINFO_REFID>
       <ENTINFO_ACCTTYPE>UNK</ENTINFO_ACCTTYPE>
       <ENTINFO_MENTION>debit card #s 000111222333444</ENTINFO_MENTION>
   </ENTINFO>
</ENTINFO>
</code>```

答:
If you change your first template to:

```<code><xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFO>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFO>
</xsl:template>
</code>```

and add:

```<code><xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{name()}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</code>```

you should get the result shown in your question.

Title: XSLT Create Subtags from Metadata

Body:
not sure if metadata is the correct terminology but I couldn't find a better descriptor. I have an XML that I need to transform in a few ways, but I need help with the ENTINFO tags specifically. What I'd like to do, is create a base tag called ENTINFO and then within that have each ENTINFO tag be a separate sub-field.

I have an XSLT written for the other transformations, but it's from back when I thought I didn't need the ENTINFO tags so it currently excludes them. I haven't found much in the documentation regarding how I can do what I need to do.

Original XML

<?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI fitype="B" xref="54815594127">
         <FIName>BANK OF FURY, N.A.</FIName>
         <FITIN>987654321</FITIN>
      </FI>
      <OIs>
         <OI xref="54815594128">
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectFullName type="L">SMITH/JANE/C</SubjectFullName>
            <SubjectLastName type="L">SMITH</SubjectLastName>
            <SubjectFirstName type="L">JANE</SubjectFirstName>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-001">Refer to <ENAMEX type="BANKDIV" id="BAN-123456789-000">FCI</ENAMEX>
            <NUMEX type="CASENUM" id="CAS-123456789-001">Case # FRD-123</NUMEX>.</S>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            NORM="333222111000"
            REFID="ACC-123456789-013"
            ACCT-TYPE="CHK"
            MENTION="MI checking account # 333222111000"/>
   <ENTINFO ID="ACC-123456789-027"
            TYPE="ACCOUNT"
            NORM="000111222333444"
            REFID="ACC-123456789-027"
            ACCT-TYPE="UNK"
            MENTION="debit card #s 000111222333444"/>
</NORMDOC>

XSLT

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

Actual Output

<DOC>
   <DOCID>123456789</DOCID>
   <FI>
      <FIName>BANK OF FURY, N.A.</FIName>
      <FITIN>987654321</FITIN>
   </FI>
   <OIs>
      <OI>
         <OIName>BANK OF FURY, N.A.</OIName>
      </OI>
   </OIs>
   <Subjects>
      <Subject>
         <SubjectFullName>SMITH/JANE/C</SubjectFullName>
         <SubjectLastName>SMITH</SubjectLastName>
         <SubjectFirstName>JANE</SubjectFirstName>
      </Subject>
   </Subjects>
   <RAW_TXT>Refer to FCICase # FRD-123.For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
   <TXT>
      <S>
         <ENAMEX_BANKDIV>FCI</ENAMEX_BANKDIV>
         <NUMEX_CASENUM>Case # FRD-123</NUMEX_CASENUM>
      </S>
      <S>
         <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
         <IDEX_PHONE>000-000-0000</IDEX_PHONE>
         <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
      </S>
   </TXT>
</DOC>

Expected Output

<DOC>
   <DOCID>123456789</DOCID>
   <FI>
      <FIName>BANK OF FURY, N.A.</FIName>
      <FITIN>987654321</FITIN>
   </FI>
   <OIs>
      <OI>
         <OIName>BANK OF FURY, N.A.</OIName>
      </OI>
   </OIs>
   <Subjects>
      <Subject>
         <SubjectFullName>SMITH/JANE/C</SubjectFullName>
         <SubjectLastName>SMITH</SubjectLastName>
         <SubjectFirstName>JANE</SubjectFirstName>
      </Subject>
   </Subjects>
   <RAW_TXT>Refer to FCICase # FRD-123.For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
   <TXT>
      <S>
         <ENAMEX_BANKDIV>FCI</ENAMEX_BANKDIV>
         <NUMEX_CASENUM>Case # FRD-123</NUMEX_CASENUM>
      </S>
      <S>
         <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
         <IDEX_PHONE>000-000-0000</IDEX_PHONE>
         <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
      </S>
   </TXT>
</DOC>
<ENTINFO>
   <ENTINFO>
       <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
       <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
       <ENTINFO_NORM>333222111000</ENTINFO_NORM>
       <ENTINFO_REFID>ACC-123456789-013</ENTINFO_REFID>
       <ENTINFO_ACCTTYPE>CHK</ENTINFO_ACCTTYPE>
       <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
   </ENTINFO>
   <ENTINFO>
       <ENTINFO_ID>ACC-123456789-027</ENTINFO_ID>
       <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
       <ENTINFO_NORM>000111222333444</ENTINFO_NORM>
       <ENTINFO_REFID>ACC-123456789-027</ENTINFO_REFID>
       <ENTINFO_ACCTTYPE>UNK</ENTINFO_ACCTTYPE>
       <ENTINFO_MENTION>debit card #s 000111222333444</ENTINFO_MENTION>
   </ENTINFO>
</ENTINFO>

Body:
If you change your first template to:

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFO>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFO>
</xsl:template>

and add:

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{name()}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

you should get the result shown in your question.


问:
Continuous Acquistion with nidaqmx
I am not being able to acquire continuos data from NI DAQ using nidaqxm on Python 3.

I already acquired finite data with a similar code, although I can't understand what I need to change to acquire data continuously.

```<code>import nidaqmx
from nidaqmx import constants
from nidaqmx import stream_readers
from nidaqmx import stream_writers
import matplotlib.pyplot as plt

#user input Acquisition
Ch00_name = 'A00'
Sens_Ch00 = 100#sensibilidade em mV/g
Ch01_name = 'A01'
Sens_Ch01 = 100#sensibilidade em mV/g
fs_acq = 1651 #sample frequency
t_med = 2 #time to acquire data

with nidaqmx.Task() as task:
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai0", name_to_assign_to_channel=Ch00_name,
                                       sensitivity=Sens_Ch00, min_val=-5, max_val=5, current_excit_val=0.002)
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai1", name_to_assign_to_channel=Ch01_name,
                                       sensitivity=Sens_Ch01, min_val=-5, max_val=5, current_excit_val=0.002)

    task.timing.cfg_samp_clk_timing(rate=fs_acq, sample_mode= constants.AcquisitionType.CONTINUOUS, samps_per_chan=(t_med * fs_acq),)

    reader = stream_readers.AnalogMultiChannelReader(task.in_stream)
    writer = stream_writers.AnalogMultiChannelWriter(task.out_stream)
</code>```

What do I have to change in my code to acquire continuos data?

答:
You need to register a callback function. I am assuming that your box is running and there is some type of status LED flashing to show that the task is running.

```<code>import nidaqmx
from nidaqmx import constants
from nidaqmx import stream_readers
from nidaqmx import stream_writers
import matplotlib.pyplot as plt

import numpy as np

#user input Acquisition
Ch00_name = 'A00'
Sens_Ch00 = 100#sensibilidade em mV/g
Ch01_name = 'A01'
Sens_Ch01 = 100#sensibilidade em mV/g
num_channels = 2
fs_acq = 1651 #sample frequency
t_med = 2 #time to acquire data

with nidaqmx.Task() as task:
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai0", name_to_assign_to_channel=Ch00_name,
                                       sensitivity=Sens_Ch00, min_val=-5, max_val=5, current_excit_val=0.002)
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai1", name_to_assign_to_channel=Ch01_name,
                                       sensitivity=Sens_Ch01, min_val=-5, max_val=5, current_excit_val=0.002)

    task.timing.cfg_samp_clk_timing(rate=fs_acq, sample_mode=constants.AcquisitionType.CONTINUOUS,
                                    samps_per_chan=(t_med * fs_acq),) # you may not need samps_per_chan

    # I set an input_buf_size
    samples_per_buffer = int(fs_acq // 30)  # 30 hz update
    # task.in_stream.input_buf_size = samples_per_buffer * 10  # plus some extra space

    reader = stream_readers.AnalogMultiChannelReader(task.in_stream)
    writer = stream_writers.AnalogMultiChannelWriter(task.out_stream)

    def reading_task_callback(task_idx, event_type, num_samples, callback_data=None):
        """After data has been read into the NI buffer this callback is called to read in the data from the buffer.

        This callback is for working with the task callback register_every_n_samples_acquired_into_buffer_event.

        Args:
            task_idx (int): Task handle index value
            event_type (nidaqmx.constants.EveryNSamplesEventType): ACQUIRED_INTO_BUFFER
            num_samples (int): Number of samples that was read into the buffer.
            callback_data (object)[None]: No idea. Documentation says: The callback_data parameter contains the value
                you passed in the callback_data parameter of this function.
        """
        buffer = np.zeros((num_channels, num_samples), dtype=np.float32)
        reader.read_many_sample(buffer, num_samples, timeout=constants.WAIT_INFINITELY)

        # Convert the data from channel as a row order to channel as a column
        data = buffer.T.astype(np.float32)

        # Do something with the data
        return 0      # callback must return an integer, otherwise callback throws a wall of errors

    task.register_every_n_samples_acquired_into_buffer_event(samples_per_buffer, reading_task_callback)
</code>```

This is what worked for me. I hope it helps

Title: Continuous Acquistion with nidaqmx

Body:
I am not being able to acquire continuos data from NI DAQ using nidaqxm on Python 3.

I already acquired finite data with a similar code, although I can't understand what I need to change to acquire data continuously.

import nidaqmx
from nidaqmx import constants
from nidaqmx import stream_readers
from nidaqmx import stream_writers
import matplotlib.pyplot as plt

#user input Acquisition
Ch00_name = 'A00'
Sens_Ch00 = 100#sensibilidade em mV/g
Ch01_name = 'A01'
Sens_Ch01 = 100#sensibilidade em mV/g
fs_acq = 1651 #sample frequency
t_med = 2 #time to acquire data

with nidaqmx.Task() as task:
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai0", name_to_assign_to_channel=Ch00_name,
                                       sensitivity=Sens_Ch00, min_val=-5, max_val=5, current_excit_val=0.002)
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai1", name_to_assign_to_channel=Ch01_name,
                                       sensitivity=Sens_Ch01, min_val=-5, max_val=5, current_excit_val=0.002)

    task.timing.cfg_samp_clk_timing(rate=fs_acq, sample_mode= constants.AcquisitionType.CONTINUOUS, samps_per_chan=(t_med * fs_acq),)

    reader = stream_readers.AnalogMultiChannelReader(task.in_stream)
    writer = stream_writers.AnalogMultiChannelWriter(task.out_stream)

What do I have to change in my code to acquire continuos data?

Body:
You need to register a callback function. I am assuming that your box is running and there is some type of status LED flashing to show that the task is running.

import nidaqmx
from nidaqmx import constants
from nidaqmx import stream_readers
from nidaqmx import stream_writers
import matplotlib.pyplot as plt

import numpy as np

#user input Acquisition
Ch00_name = 'A00'
Sens_Ch00 = 100#sensibilidade em mV/g
Ch01_name = 'A01'
Sens_Ch01 = 100#sensibilidade em mV/g
num_channels = 2
fs_acq = 1651 #sample frequency
t_med = 2 #time to acquire data

with nidaqmx.Task() as task:
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai0", name_to_assign_to_channel=Ch00_name,
                                       sensitivity=Sens_Ch00, min_val=-5, max_val=5, current_excit_val=0.002)
    task.ai_channels.add_ai_accel_chan(physical_channel="cDAQ9191-1B7B393Mod1/ai1", name_to_assign_to_channel=Ch01_name,
                                       sensitivity=Sens_Ch01, min_val=-5, max_val=5, current_excit_val=0.002)

    task.timing.cfg_samp_clk_timing(rate=fs_acq, sample_mode=constants.AcquisitionType.CONTINUOUS,
                                    samps_per_chan=(t_med * fs_acq),) # you may not need samps_per_chan

    # I set an input_buf_size
    samples_per_buffer = int(fs_acq // 30)  # 30 hz update
    # task.in_stream.input_buf_size = samples_per_buffer * 10  # plus some extra space

    reader = stream_readers.AnalogMultiChannelReader(task.in_stream)
    writer = stream_writers.AnalogMultiChannelWriter(task.out_stream)

    def reading_task_callback(task_idx, event_type, num_samples, callback_data=None):
        """After data has been read into the NI buffer this callback is called to read in the data from the buffer.

        This callback is for working with the task callback register_every_n_samples_acquired_into_buffer_event.

        Args:
            task_idx (int): Task handle index value
            event_type (nidaqmx.constants.EveryNSamplesEventType): ACQUIRED_INTO_BUFFER
            num_samples (int): Number of samples that was read into the buffer.
            callback_data (object)[None]: No idea. Documentation says: The callback_data parameter contains the value
                you passed in the callback_data parameter of this function.
        """
        buffer = np.zeros((num_channels, num_samples), dtype=np.float32)
        reader.read_many_sample(buffer, num_samples, timeout=constants.WAIT_INFINITELY)

        # Convert the data from channel as a row order to channel as a column
        data = buffer.T.astype(np.float32)

        # Do something with the data
        return 0      # callback must return an integer, otherwise callback throws a wall of errors

    task.register_every_n_samples_acquired_into_buffer_event(samples_per_buffer, reading_task_callback)

This is what worked for me. I hope it helps


问:
Laravel Blade double curly brace not working
By reading the Laravel documentation, I've understood that I should be able to use {{ }} to escape my strings. However, by doing this, I'm getting an error, but the string works fine if I run {!! !!}. Is there anything I'm missing in my code?

A complete view of the code blade file (login.blade.php)

@extends('layouts.app')

@section('content')

Sign In To Account

                                <form class="kt-form" method="post" action="/login">

        {!! csrf_field() !!}

          <input class="form-control" type="text" placeholder="Email" name="email" value="" autocomplete="off">

          <input class="form-control" type="password" placeholder="Password" name="password">

         @if ($errors->any())

          @foreach($errors->all() as $error)

{!! error !!}

          @endforeach

         @endif

            <input type="checkbox" name="remember"> Remember me

           Forget Password ?

          <button id="kt_login_signin_submit" class="btn btn-brand btn-elevate kt-login__btn-primary">Sign In</button>

        </form>

         Don't have an account yet ?

        Sign Up!

@endsection```

Error

ErrorException (E_ERROR) syntax error, unexpected 't' (T_STRING),
  expecting ',' or ')' (View:
  C:\xampp\htdocs\test\resources\views\auth\login.blade.php) Previous
  exceptions syntax error, unexpected 't' (T_STRING), expecting ',' or
  ')' (0)

答:
You need to make 'error' a variable with double brackets. It's considered an undefined constant otherwise.

@foreach($errors->all() as $error)

{{ $error }}

@endforeach
```

<p>You also need to add the right curly brace and the missing right single quote for the URL in the <code>asset()</code> helper function.</p>

<pre class="lang-php prettyprint-override"><code><div class="kt-grid__item kt-grid__item--fluid kt-grid kt-grid--hor"
    style="background-image: url({{ asset('assets/media/bg/bg-3.jpg') }}">
</code>```

Body:
By reading the Laravel documentation, I've understood that I should be able to use {{ }} to escape my strings. However, by doing this, I'm getting an error, but the string works fine if I run {!! !!}. Is there anything I'm missing in my code?

A complete view of the code blade file (login.blade.php)

@extends('layouts.app')

@section('content')

Sign In To Account

                                <form class="kt-form" method="post" action="/login">

        {!! csrf_field() !!}

          <input class="form-control" type="text" placeholder="Email" name="email" value="" autocomplete="off">

          <input class="form-control" type="password" placeholder="Password" name="password">

         @if ($errors->any())

          @foreach($errors->all() as $error)

{!! error !!}

          @endforeach

         @endif

            <input type="checkbox" name="remember"> Remember me

           Forget Password ?

          <button id="kt_login_signin_submit" class="btn btn-brand btn-elevate kt-login__btn-primary">Sign In</button>

        </form>

         Don't have an account yet ?

        Sign Up!

@endsection

Error

ErrorException (E_ERROR) syntax error, unexpected 't' (T_STRING),
  expecting ',' or ')' (View:
  C:\xampp\htdocs\test\resources\views\auth\login.blade.php) Previous
  exceptions syntax error, unexpected 't' (T_STRING), expecting ',' or
  ')' (0)

Body:
You need to make 'error' a variable with double brackets. It's considered an undefined constant otherwise.

@foreach($errors->all() as $error)
    <p>{{ $error }}</p>
@endforeach

You also need to add the right curly brace and the missing right single quote for the URL in the asset() helper function.

<div class="kt-grid__item kt-grid__item--fluid kt-grid kt-grid--hor"
    style="background-image: url({{ asset('assets/media/bg/bg-3.jpg') }}">


问:
Relative z-index?
I've got a "Dialog" widget that pops up with a z-index of 100.  When I create another popup (a floating div), it appears underneath the dialog widget, because I haven't explicitly set the z-index on the new popup.

The structure ends up looking something like

```<code><div id="dialogbox" style="z-index: 100">
    <div>
        <div id="widgetThatCausesThePopup" />
    </div>
</div>
<div id="popupHiddenBehindTheDialog" />
</code>```

I'm using GWT to generate this HTML.  There can be arbitrary levels of nesting between dialogbox and widgetThatCausesThePopup, and the actual z-index may be arbitrary as well.

How can I ensure that the new div will be shown in front of the dialogbox?

答: Get the computed z-index of the parent (see In GWT how to know all the styles applied to a given element (by id or class name)) and increment it for each child.</p>

Title: Relative z-index?

Body:
I've got a "Dialog" widget that pops up with a z-index of 100.  When I create another popup (a floating div), it appears underneath the dialog widget, because I haven't explicitly set the z-index on the new popup.

The structure ends up looking something like

I'm using GWT to generate this HTML.  There can be arbitrary levels of nesting between dialogbox and widgetThatCausesThePopup, and the actual z-index may be arbitrary as well.

How can I ensure that the new div will be shown in front of the dialogbox?


问:
How to avoid calling malloc for each node in a linked list
This question was inspired by

Prevent malloc function wrapping

I have written a program that allocates memory for individual nodes in a linked list by calling malloc.

There are speed tests in which malloc is wrapped by a function that causes malloc calls to take more time than normal. This allows the tests to detect frequent usage of malloc.

How do I avoid calling malloc for each node?

答:
There are speed tests in which malloc is called by wrapped function which is written to take more time and allocate memory. So every time when I call malloc in my pogram it is called but it takes more time so the tests can detect very often usage of malloc. The problem is that I use linked lists so the memory is allocated separately for every node of the list. I don't know how to change this implementation because it is really comfortable to use linked lists in my structure.

You might be able to use an array instead.

For a simple example:

```<code>#include <stdio.h>
#include <stdlib.h>

struct list_entry {
    struct list_entry *next;
    int foo;
};

#define MAX_THINGS 1234567
struct list_entry myArray[MAX_THINGS];
int firstFreeEntry = 0;

struct list_entry *freeListHead = NULL;

struct list_entry *listHead = NULL;

struct list_entry *allocEntry(void) {
    struct list_entry *temp;

    if(freeListHead != NULL) {
        // Recycle a previously freed entry
        temp = freeListHead;
        freeListHead = temp->next;
        return temp;
    }
    // Try to take a new entry from the array
    if(firstFreeEntry < MAX_THINGS) {
        return &myArray[firstFreeEntry++];
    }
    // Give up (no free entries)
    return NULL;
}

void freeEntry(struct list_entry *entry) {
    int offset;

    // Try to give it back to the array
    offset = entry - myArray;
    if(offset == firstFreeEntry - 1) {
        firstFreeEntry--;
        return;
    }
    // Put it on the list of freed things
    entry->next = freeListHead;
    freeListHead = entry;
}

// Allocate an entry, initialize/construct it, and put it on the linked list

struct list_entry *createEntry(int value) {
    struct list_entry *newEntry;
    newEntry = allocEntry();
    if(newEntry != NULL) {
        newEntry->foo = value;
        newEntry->next = listHead;
        listHead = newEntry;
    }
    return newEntry;
}

int main() {
    const int node_count = 1000 * 1000;
    struct list_entry *head = NULL;
    for (int index = 0; index < node_count; index++) {
        head = createEntry(0xdeadbeef);
        printf("address of head = %p\n", head);
    }
    while (head) {
        struct list_entry *next = head->next;
        printf("address of head = %p\n", head);
        freeEntry(head);
        head = next;
    }
    return 0;
}
</code>```

Output

```<code>address of head = 0x101d32040
address of head = 0x101d32050
address of head = 0x101d32060
...
address of head = 0x101d32040
</code>```

Verification

```<code>$ ./test > storage.txt
$ split -l 1000000 storage.txt
$ tac xab > xac
$ diff xaa xac
</code>```

Body:
There are speed tests in which malloc is called by wrapped function which is written to take more time and allocate memory. So every time when I call malloc in my pogram it is called but it takes more time so the tests can detect very often usage of malloc. The problem is that I use linked lists so the memory is allocated separately for every node of the list. I don't know how to change this implementation because it is really comfortable to use linked lists in my structure.

You might be able to use an array instead.

For a simple example:

#include <stdio.h>
#include <stdlib.h>

struct list_entry {
    struct list_entry *next;
    int foo;
};

#define MAX_THINGS 1234567
struct list_entry myArray[MAX_THINGS];
int firstFreeEntry = 0;

struct list_entry *freeListHead = NULL;

struct list_entry *listHead = NULL;

struct list_entry *allocEntry(void) {
    struct list_entry *temp;

    if(freeListHead != NULL) {
        // Recycle a previously freed entry
        temp = freeListHead;
        freeListHead = temp->next;
        return temp;
    }
    // Try to take a new entry from the array
    if(firstFreeEntry < MAX_THINGS) {
        return &myArray[firstFreeEntry++];
    }
    // Give up (no free entries)
    return NULL;
}

void freeEntry(struct list_entry *entry) {
    int offset;

    // Try to give it back to the array
    offset = entry - myArray;
    if(offset == firstFreeEntry - 1) {
        firstFreeEntry--;
        return;
    }
    // Put it on the list of freed things
    entry->next = freeListHead;
    freeListHead = entry;
}

// Allocate an entry, initialize/construct it, and put it on the linked list

struct list_entry *createEntry(int value) {
    struct list_entry *newEntry;
    newEntry = allocEntry();
    if(newEntry != NULL) {
        newEntry->foo = value;
        newEntry->next = listHead;
        listHead = newEntry;
    }
    return newEntry;
}

int main() {
    const int node_count = 1000 * 1000;
    struct list_entry *head = NULL;
    for (int index = 0; index < node_count; index++) {
        head = createEntry(0xdeadbeef);
        printf("address of head = %p\n", head);
    }
    while (head) {
        struct list_entry *next = head->next;
        printf("address of head = %p\n", head);
        freeEntry(head);
        head = next;
    }
    return 0;
}

Output

address of head = 0x101d32040
address of head = 0x101d32050
address of head = 0x101d32060
...
address of head = 0x101d32040

Verification

$ ./test > storage.txt
$ split -l 1000000 storage.txt
$ tac xab > xac
$ diff xaa xac