text:
Q: Best way to avoid repeating code when using addEventListener and functions im pretty new at coding, currently studing front end dev. I´m on my 5:th week learning JS and got a challange to create a toDo list with Typescript.
When i create a task in my app it has a checkbox and a "trash"-button. The idéa of the trash button is pretty clear and the checkbox is going put the task last in the list when its "checked".
I noticed some repetative code  while creating my event listeners. So I found a way to add the event listener to multiple elements but I can't wrap my head around how to call the different functions that corresponds to what was clicked.
this is how I found a way to add the event listener to each element. But from here, how can I call a function based on what was clicked?
    document.querySelectorAll('.add-click-listener').forEach(item => {
        item.addEventListener('click',  event => {

        })
    })

this was the code from the beginning
    let checkbox = Array.from(document.querySelectorAll('.hidden-checkbox'));
    checkbox.forEach((item) => {
        item.addEventListener('click', checkboxStatusShift);
    });

    let trashBtn = Array.from(document.querySelectorAll('.trash-btn'));
    trashBtn.forEach((item) => {
        item.addEventListener('click', deleteTask);
    });

this will be the function to "trash" a task:
function deleteTask(event: any) {
    const index = (event.currentTarget);
    const buttonId = index.id?.replace('remove-', '');
    const currentTask = todoDatabase.filter((object) => object.id === buttonId)[0];
    const currentTaskId = currentTask.id;

    console.log(buttonId);
    console.log(currentTaskId);

    if (buttonId == currentTaskId) {
        todoDatabase.splice(0, 1);
        printTodoList();
    }

}

I haven't started the code for the checkbox function yet.
Very grateful for any tips I can get.

A: Thanks for all the replies, this pointed me in the right direction and I got it working as intended, the following code was the result:
    document.querySelectorAll('.add-click-listener').forEach(item => {
        item.addEventListener('click',  (event: any) => {
            const thisWasClicked = event.currentTarget;
            let trashBtn = Array.from(document.querySelectorAll('.trash-btn'));

            const filterTrashBtn: any = trashBtn.find((btn) => btn.id === thisWasClicked.id);
            const findTask = trashBtn.indexOf(filterTrashBtn);

            if (filterTrashBtn?.id == thisWasClicked.id) {
                todoDatabase.splice(findTask, 1);
                printTodoList();

            }

        });

    });

Now I can just write the code for my checkboxes with another if and some variables etc.

A: From my experience, you can avoid repeating code by using an event delegation pattern. You have to attach an event listener to the parent element, and then inside the handler to check if it matches your child element. The event by clicking on child will bubble so you will catch it. In code it will look like this:
document.querySelector('#parent-element').addEventListener('click', function(e) {
  if (e.target && e.target.matches('.child-element')) {
    // do your stuff here
  }
});

A: You can bind to the root element where the checkboxes are located and handle the target element that fired the event.
If the HTML looks like this:

    <input id="1" type="checkbox" />Checkbox 1
    <input id="2" type="checkbox" />Checkbox 2
    <input id="3" type="checkbox" />Checkbox 3

An example JS code could be as shown below:
const root = document.getElementsByClassName('checkboxes')[0];
root.addEventListener('click', function (event) {
  const target = event.target;

  if (target.tagName == 'INPUT') {
    console.log(target.id);
    console.log(target.checked);
  }
});

Bind a click event to the root div with the class name "checkboxes" and handle who exactly fires the event.
If you can use Jquery then the same can be done with on function
https://api.jquery.com/on
$(div.checkboxes).on("click", ".checkbox", function(event){})


text:
Q: unappend circle when dragged out of group How to unappend a circle element when I drag it out of group? Currently I am able to append it to the group but not able to unappend it on drag. If any body have an idea please help. I am new to d3js and javascript
Demo : http://jsfiddle.net/q7L9qdyv/
Code:
var svg = d3.select("body").append("svg")
                        .attr("width", 800)
                        .attr("height", 803);

                //Draw the Circle
                var circle = svg.append("circle")
                        .attr("r", 25)
                        .attr("cx", 35)
                        .attr("cy", 145)
                        .style("stroke-opacity", .9)
                        .style("stroke", "green")
                        .style("fill", "white")
                        .style("stroke-width", "2px")
                        .classed("baseCircle", true); // created a class to identify

                var targetCircle = circle;
                var tempCircle = circle;

                //unique id for circles
                function guid()
                {
                    function _p8(s)
                    {
                        var p = (Math.random().toString(16) + "000000000").substr(2, 8);
                        return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p;
                    }
                    return _p8() + _p8(true) + _p8(true) + _p8();
                }

                //function to move circles
                function moveCircle()
                {
                    d3.select(this)
                            .attr('cx', d3.event.x)
                            .attr('cy', d3.event.y);
                }

                //Move the group along wth elements/Drag Behaviour for Group
                var dragGroup = d3.behavior.drag()
                        .origin(function () {
                            var g = this;
                            return {x: d3.transform(g.getAttribute("transform")).translate[0],
                                y: d3.transform(g.getAttribute("transform")).translate[1]};
                        })
                        .on("drag", function (d, i) {
                            g = this;
                            translate = d3.transform(g.getAttribute("transform")).translate;
                            console.log(translate);
                            x = d3.event.dx + translate[0],
                                    y = d3.event.dy + translate[1];
                            d3.select(g).attr("transform", "translate(" + x + "," + y + ")");
                            d3.event.sourceEvent.stopPropagation();
                        });

                //Group element
                var targetG = svg.append("g")
                        .call(dragGroup)
                        .style('cursor', 'move')
                        .attr("transform", "translate(150,150)");

                //Append rectangle to group
                targetG.append("rect")
                        .attr("fill", "none")
                        .style("stroke", "black")
                        .style("stroke-width", "2px")
                        .attr("width", 200)
                        .attr("height", 200)
                        .style("fill", "white");

                //Drag behaviour starts for circles
                var drag = d3.behavior.drag()
                        .on("dragstart", dragstart)
                        .on("drag", drag)
                        .on("dragend", dragend);

                //Start
                function dragstart() {
                    console.log("circle dragged is::" + d3.select(this).attr("id"));

                    if (d3.select(this).classed("baseCircle") === true) {

                        targetCircle = svg.append("circle")
                                .attr("r", 25)  //get radius from targetCircle and also styles?
                                .attr("cx", targetCircle.attr("cx"))
                                .attr("cy", targetCircle.attr("cy"))
                                .style("fill", "white")
                                .style("stroke", "green")
                                .style("stroke-width", "2px");
                        targetCircle.call(drag);
                    }
                    else
                    {
                        targetCircle = d3.select(this);
                        tempCircle = this;
                    }
                    targetCircle.classed("dragTarget", true).attr("id", "dragTargetId");
                }

                //Drag
                function drag()
                {
                    targetCircle.attr("cx", d3.event.x)
                            .attr("cy", d3.event.y);
                }

                //End
                function dragend(d) {
                    //Get event x and y
                    var tx = targetCircle.attr("cx"),
                            ty = targetCircle.attr("cy");

                    var flag = 0;
                    //Select all elements in svg
                    try {
                        var elemArr = svg.selectAll("*").each(function (d, i) {
                            //If the element is a member of a group, check
                            if ($(this.parentNode).is("g")) {
                                //Get coordinates
                                var box = this.getBBox();
                                var bx = box.x,
                                        by = box.y,
                                        bw = box.width,
                                        bh = box.height;
                                //Make shape inherit translate of parent element
                                var translate = d3.select(this.parentNode).attr("transform");
                                var translate = translate.substring(translate.indexOf("translate(") + 10, translate.length);
                                translate = (translate.substring(0, translate.indexOf(")"))).split(",");

                                bx += parseInt(translate[0]);
                                by += parseInt(translate[1]);
                                //Check if within x and y bounds
                                if (tx >= bx && tx <= (bx + bw) && !flag && ty >= by && ty <= (by + bh))
                                {
                                    //Flag to prevent further action
                                    flag = 1;
                                    //Append target circle to g element
                                    targetG.append("circle")
                                            .attr("r", 25)  //get radius from targetCircle and also styles?
                                            .attr("id", guid())
                                            .classed("circleAddedClass", true)
                                            .attr("cx", d3.mouse(this)[0])
                                            .attr("cy", d3.mouse(this)[1])
                                            .style("fill", "white")
                                            .style("stroke", "black")
                                            .style("stroke-width", "2px")
                                            .call(
                                                    d3.behavior.drag()
                                                    .on("dragstart", function () {
                                                        d3.event.sourceEvent.stopPropagation();
                                                    })
                                                    .on('drag', moveCircle).origin(function () {
                                                var t = d3.select(this);
                                                return {x: t.attr("cx"), y: t.attr("cy")};
                                            }));

                                    targetCircle.remove();
                                }
                            }
                        });
                    } catch (e) {
                        log(e);
                    }
                }
                function log(s) {
                    console.log(s);
                    return s;
                }
                circle.call(drag);

A: CSS
.baseCircle {
    stroke-opacity: 0.9;
    stroke: green;
    stroke-width: 2px;
    fill: white;
}
.dragTarget {
    stroke: green;
    stroke-width: 2px;
    fill: white;
}
.circleAddedClass {
    stroke: black;
    stroke-width: 2px;
    fill: white;
}

Script
I reorganized your code a bit
// unique id for circles
function guid() {
    function _p8(s) {
        var p = (Math.random().toString(16) + "000000000").substr(2, 8);
        return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p;
    }
    return _p8() + _p8(true) + _p8(true) + _p8();
}

function getNode(d3Element) {
    return d3Element[0][0];
}

// check if within bounds
function isWithin(x, y, box) {
    return (x >= box.x && x <= (box.x + box.width) && y >= box.y && y <= (box.y + box.height))
}

function getTranslate(t) {
    var translate = d3.transform(t.getAttribute("transform")).translate;
    return {
        x: Number(translate[0]),
        y: Number(translate[1])
    };
}

var svg = d3.select("body")
            .append("svg")
            .attr("width", 800)
            .attr("height", 803);

// movement for a transformed element
var dragG = d3.behavior.drag()
                // set the origin to the start position
                .origin(function () {
                    return getTranslate(this);
                })
                .on("drag", function () {
                    d3.select(this).attr(
                        "transform",
                        "translate(" +
                            d3.event.x + "," +
                            d3.event.y + ")");
                });

// drop group
var targetG = svg.append("g")
                .style('cursor', 'move')
                .attr("transform", "translate(150,150)")
                .call(dragG)

// append rectangle to group
targetG.append("rect")
        .attr("fill", "none")
        .style("stroke", "black")
        .style("stroke-width", "2px")
        .attr("width", 200)
        .attr("height", 200)
        .style("fill", "white");

// drag functions
var draggedCircle;
var circleDrag = function () {
    draggedCircle
        .attr("cx", d3.event.x)
        .attr("cy", d3.event.y);
}

function circleDragEnd() {
    // get event x and y
    var dx = Number(draggedCircle.attr("cx"));
    var dy = Number(draggedCircle.attr("cy"));
    if (draggedCircle.classed("circleAddedClass")) {
        var t = getTranslate(getNode(draggedCircle).parentNode);
        console.log([dx, dy])
        dx += t.x;
        dy += t.y;
        console.log([dx, dy])
    }

    svg.selectAll("g").each(function () {
        var rect = d3.select(this).select("rect");
        if (rect.length === 1) {
            var box = getNode(rect).getBBox();

            // the actual coordinates of the element must include the parent's transform too
            var t = getTranslate(this);
            box = {
                x: box.x + t.x,
                y: box.y + t.y,
                width: box.width,
                height: box.height
            }

            if (isWithin(dx, dy, box)) {
                if (!draggedCircle.classed("circleAddedClass")) {
                    draggedCircle = draggedCircle.remove()
                                        .attr("cx", dx - t.x)
                                        .attr("cy", dy - t.y)
                                        .attr("id", guid())
                                        .classed("dragTarget", false)
                                        .classed("circleAddedClass", true);

                    // append target circle to g element
                    this.appendChild(getNode(draggedCircle))
                }
            } else if (draggedCircle.classed("circleAddedClass")) {
                if (getNode(draggedCircle).parentNode === this) {
                    draggedCircle = draggedCircle.remove()
                                        .attr("cx", dx)
                                        .attr("cy", dy)
                                        .classed("dragTarget", true)
                                        .classed("circleAddedClass", false);

                    getNode(svg).appendChild(getNode(draggedCircle))
                }
            }
        }
    });
}

// drag behaviour for circle instances
var dragCircleInstance = d3.behavior.drag()
                            .on("dragstart", function () {
                                draggedCircle = d3.select(this)
                                d3.event.sourceEvent.stopPropagation();
                            })
                            .on("drag", circleDrag)
                            .on("dragend", circleDragEnd);

// drag behaviour for circle template
var dragCircleTemplate = d3.behavior.drag()
                            .on("dragstart", function () {
                                draggedCircle = svg.append("circle")
                                                .attr("r", 25)  //get radius from targetCircle and also styles?
                                                .attr("cx", d3.select(this).attr("cx"))
                                                .attr("cy", d3.select(this).attr("cy"))
                                                .classed("dragTarget", true)
                                                .call(dragCircleInstance);
                            })
                            .on("drag", circleDrag)
                            .on("dragend", circleDragEnd);

// draw the circle template
var circle = svg.append("circle")
                .attr("r", 25)
                .attr("cx", 35)
                .attr("cy", 145)
                .classed("baseCircle", true)
                .call(dragCircleTemplate);

Fiddle - http://jsfiddle.net/f7u11xm4/

A: If I was to code review this I'd make the following suggestion:

*

*Too many different drag handlers.  You need two: how do I drag the group and how do I drag a circle.

*Treat this as a state machine and ask what are the various states of my circle -  not in box and dragged in, in box and dragged out, in box and dragged in, out of box and dragged out.  Code to these possibilities.

*I found how you do your dragstart confusing and prone to problems.  I would just create a static circle that marks where you drag from and clone on drag end.  This of course adds another state; initial drag to anywhere.

All this in mind, here's my re-code.

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <script>

    var svg = d3.select("body")
      .append("svg")
      .attr("width", 800)
      .attr("height", 803);

    //Move the group along wth elements/Drag Behaviour for Group
    var dragGroup = d3.behavior.drag()
      .origin(function () {
          var g = this;
          return {
            x: d3.transform(g.getAttribute("transform")).translate[0],
            y: d3.transform(g.getAttribute("transform")).translate[1]
          };
      })
      .on("drag", function (d, i) {
          g = this;
          translate = d3.transform(g.getAttribute("transform")).translate;
          var x = d3.event.dx + translate[0],
              y = d3.event.dy + translate[1];
          d3.select(g).attr("transform", "translate(" + x + "," + y + ")");
          d3.event.sourceEvent.stopPropagation();
      });

      // circle drag
      function dragging(){
        var self = d3.select(this);
        self.attr("cx", d3.event.x)
          .attr("cy", d3.event.y);
      }

      // start
      function dragstart() {
        d3.event.sourceEvent.stopPropagation();
      }

      //End
      function dragend(d) {
        var self = d3.select(this);

        // is this the first time I'm dragged?
        // replace me with a new one
        if (self.classed('initialDragCircle')){
          // append a new inital draggable
          createInitialDragCircle();
          self.attr('class','dragCircle');
        }

        // get necessary coordinates
        var tx = self.attr('cx'),
            ty = self.attr('cy');

        var transG = d3.transform(targG.attr('transform')).translate;
        var bx = transG[0];
            by = transG[1];

        // was it outside of the box?
        if (self.classed('dragCircle')){
          var coords = d3.mouse(targG.node());
          var box = targRect.node().getBBox();
          // and now is it in box?
          if (coords[0] > 0 && coords[1] > 0 &&
              coords[0] < box.width && coords[1] < box.height) {

            targG.append("circle")
              .attr("r", 25)
              .attr("cx", coords[0])
              .attr("cy", coords[1])
              .style("stroke-opacity", .9)
              .style("stroke", "black")
              .style("fill", "white")
              .style("stroke-width", "2px")
              .attr('class','inBoxDragCircle')
              .call(drag);
            self.remove();
          }
        }
        // was it in the box?
        else if (self.classed('inBoxDragCircle'))
        {
          var coords = d3.mouse(targG.node());
          var box = targRect.node().getBBox();
          // and now it is out of the box?
          if (coords[0] < 0 || coords[1] < 0 ||
              coords[0] > box.width || coords[1] > box.height) {
            coords = d3.mouse(svg.node());
            svg.append("circle")
              .attr("r", 25)
              .attr("cx", coords[0])
              .attr("cy", coords[1])
              .style("stroke-opacity", .9)
              .style("stroke", "green")
              .style("fill", "white")
              .style("stroke-width", "2px")
              .attr('class','dragCircle')
              .call(drag);
            self.remove();

          }
        }
      }

    var drag = d3.behavior.drag()
      .on("dragstart", dragstart)
      .on("drag", dragging)
      .on("dragend", dragend);

    //Group element
    var targG = svg.append("g")
      .call(dragGroup)
      .style('cursor', 'move')
      .attr("transform", "translate(150,150)");

    var targRect = targG.append("rect")
      .attr("fill", "none")
      .style("stroke", "black")
      .style("stroke-width", "2px")
      .attr("width", 200)
      .attr("height", 200)
      .style("fill", "white");

    //Draw the Circle
    svg.append("circle")
      .attr("r", 25)
      .attr("cx", 35)
      .attr("cy", 145)
      .style("stroke-opacity", .9)
      .style("stroke", "green")
      .style("fill", "white")
      .style("stroke-width", "2px")
      .classed("baseCircle", true);

    function createInitialDragCircle(){
      svg.append("circle")
        .attr("r", 25)
        .attr("cx", 35)
        .attr("cy", 145)
        .style("stroke-opacity", .9)
        .style("stroke", "green")
        .style("fill", "white")
        .style("stroke-width", "2px")
        .classed("initialDragCircle", true)
        .call(drag);
    };

    createInitialDragCircle();

    </script>
  </body>

</html>

A: Pseudocode as follows:-

*

*Add id=xxx to all circle created.

*a function to determine if circle is inside or outside container (the top_left and bottom_right points of container are used)

*d3.select("_dragged_circle_ID_").append("_another_<g>_container_");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Numerical integration using Birkhoff theorem There is a method for numerical integration that uses Brikhoff ergodic theorem?
For example if we have a irrational number $\alpha$ we know that for every continuous function  $f \colon [0,1] \to \mathbb{R}$ with $f(0)=f(1)$ we have
$$\frac{1}{n} \sum_{i=0}^{n-1} f(i\cdot \alpha \mod 1) \to \int_0^1f(x)dx $$
because the irrational rotation in $\mathbb{R} / \mathbb{Z}$ is uniquely ergodic.
The problem here is the rate of convergence and that computers don't have irrational numbers :(
Any help or reference will be appriciated

A: If $f$ is continuous and bounded, and $a_k$ is uniformly distributed, then by Weyl's Theorem$$\lim_{n\to\infty}{1\over n}\sum_1^nf(a_k)=\int_0^1f$$ The sequence where $a_k$ is the fractional part of $k\alpha$, $\alpha$ irrational, is known to be uniformly distributed. Furthermore, there are estimates of how quickly the sum converges to the integral, e.g., Koksma's inequality says $$\Biggl|{1\over n}\sum_1^nf(a_k)-\int_0^1f\,\Biggr|\le D(a_1,\dots,a_n)V(f)$$ where $D$ is the discrepancy and $V$ is the variation.
For details, see the book by Kuipers and Niederreiter, or search for Weyl Criterion, Koksma's Inequality, and other phrases I've used.

A: If you have only a fixed precision available, then there cannot be a numerical integration method of this type, because you cannot represent irrational numbers in fixed finite precision, as you pointed out. If your precision depended on $n$, then you could attempt to control the precision and $n$ simultaneously to get an error control. I think this would require some estimate of the modulus of continuity of $f$ along with careful estimates of the error in actually computing $f$ as well. This is all very inconvenient on the hardware we have available to us, because performance is much higher in the floating point arithmetic that we have natively available, which on most hardware maxes out at double precision. Put differently, the ratio of the speed of double precision to the speed of single precision is smaller than the ratio of the speed of quadruple precision to the speed of double precision, and the difference is quite large.
That said, I would not be surprised if this general idea were a common technique to accelerate convergence of Monte Carlo methods.


text:
Q: JavaScript get Objects property Hello guys I've web page which have a lot of scripts, I need to get one by it's name. for e.g 'data'. I need to convert data from this script to one string.
Script is the following:
<script>data = [{'Id': '12344567', 'name': 'TestName','Amount': '1066.00', 'NumberTax': '34.00','tranasactionNumber':'139', 'otherInfo': [{'sku': 'ET|Adult','name': 'Test','category': 'Normal','price': '1032.0', 'quantity':'3'}]}];</script>

This data has array with some elements and another array inside.
Using my script I can only get info and create string with String elements from my data, but how can I get elements from inner array?
var json = '[{';
for (var i in data[0]) {
    console.log('type of data[0][i]  = ' + typeof data[0][i]);
    if (typeof data[0][i] === 'string') {
        json = json + '\'' + i + '\'' + ': ' + '\'' + data[0][i] + '\', ';
        console.log(i);
        console.log(data[0][i])
    } else {
        //Get infro from inner array
    }
}
json = json + '}]';
console.log(json);

A: Try JSON.stringify(data) to convert object to string instead of your function.

A: To access the object inside the array you can use the following code:
var obj = data[0]['otherInfo'][0];

You can then use the same code you have above to loop over it and append its elements. If I understand correctly that if what you wish to do.


text:
Q: Classifying and solving a nonlinear differential algebraic equation (DAE) Suppose that $x,y$ are functions of time and I'm considering the dynamics in a problem with equations as below.$$ \alpha\ddot{z} - k_{1}z - k_2y=0 \, \text{ (differential equation)}$$
$$ k_1 y + k_3 \sin(y) +k_4z=0 \, \text{ (algebraic constraint)} $$
I first made the mistake of assuming this is a nonlinear system of ODEs, but the variable $y$  has $0$ order derivative in both equations. So I looked into classifying this and stumbled on differential algebraic equations. Now I took some steps to cast this into a form that could help in classifying the type of DAE and perhaps if there's a way to numerically solve it. I order reduce the system to make everything in first order by defining $x=\dot{z}, \dot{x}=\ddot{z}.$ Now we have a new system. $$ \alpha\dot{x} -k_1z -k_2y=0$$ $$\dot{z}-x=0 $$ $$k_1 y + k_3 \sin(y) +k_4z=0 $$
This can be cast into a semi-explicit form.
$$ \dot{x}=\frac{1}{\alpha}\left(k_1z +k_2y\right)=:f_1(t,x,y,z) $$ $$ \dot{z}=x=:f_2(t,x,y,z) $$ $$ 0=k_1 y + k_3 \sin(y) +k_4z=:g(t,x,y,z)  $$
This is as far as I got. I'm unable to really go on about solving this. I care about a numerical solution. The defintions I see regarding index of a DAE, lead to something recursive here because I can never isolate the $y$ variable because of the $\sin(y)$ term.
Any help is appreciated!

A: The second equation can be solved for $y$ locally almost everywhere. If $|k_3|<|k_1|$, this solution even exists without restrictions. This makes this equation a semi-explicit index-1 DAE system. For instance the Matlab stiff solvers can handle it, as long as $k_1+k_3\cos(y)\ne 0$.
You could also translate it into an ODE system manually by taking the derivative of the last equation. Then
$$
\dot y=-\frac{k_4x}{k_1+k_3\cos(y)}
$$
replaces the algebraic equation. Note that this ODE formulation will have a drift in the value of $k_1y+k_3\sin(y)+k_4z$. That this expression is zero needs to be enforced by finding consistent initial values and by periodically correcting the numerical solution.

A: From $z = -\frac{1}{k_4}(k_1 y+k_3\sin y)$ we have $z = f_1(y)$. Deriving now twice we get at $\ddot z = f_2(y,\dot y,\ddot y)$. Then substituting into the first differential equation we get
$$
\cases{
\alpha f_2(y,\dot y,\ddot y) - k_1 f_1(y)-k_2 y = 0\\
z = f_1(y)
}
$$


text:
Q: binding List of objects to a list-oriented GUI component (c#) I Have (an instance of ) a class X that manages a list L of objects, and has it's own form to display some of it's properties.
In my form I have a ListView and a TreeView objects, to which I write some attributes of L.
Later on, I'll like to respond to a click on an entity of ListView/TreeView , for which I need to resolve the entity's string back to the object it represents.
What I do now, is to enumerate the objects of L , Looking for the one with that string,
but obviously it'll work only for unique strings. moreover, it seems like bad practice to enumerate like that, as I already had that information before, and also resources-wise.
My question:
Is there a way to bind L to the GUI component in a way that eliminate that situation?
thanks.


text:
Q: Error:__init__() missing 1 required positional argument: 'rec' I am new to python. I am trying to do microphone file that ought to detect, listen, record and write the .wav files. However, it is giving me an error while I am trying to run the file. It is saying:
TypeError: __init__() missing 1 required positional argument: 'rec'
And I have the same issue with listen() as below. Here is my code:
class Recorder:
# compute the rms
def rms(frame):
    count = len(frame) / swidth
    format = "%dh" % (count)
    shorts = struct.unpack(format, frame)

    sum_squares = 0.0
    for sample in shorts:
        n = sample * SHORT_NORMALIZE
        sum_squares += n * n
    rms = math.pow(sum_squares / count, 0.5);
    return rms * 1000

# create an interface to portaudio
@staticmethod
def __init__(rec):
    rec.p= pyaudio.PyAudio()
    rec.stream= rec.p.open(format=FORMAT, channels=CHANNELS, rate=RATE,input=True,output=True,frames_per_buffer=chunk)

# record the detected sound
def record(rec):
    print('sound detected, record begin')
    frames = []
    current = time.time()
    end = current + Timeout
    while current <= end:
        data = rec.stream.read(chunk, execption_on_overflow=False)
        if rec.rms(data) >= Threshold:
            end = time.time() + Timeout
        current = time.time()
        frames.append(data)
    rec.write(b''.join(frames))

# write the recorded sound to .wav file
def write(rec, recording):
    files = len(os.listdir(FileNameTmp))
    filename = os.path.join(FileNameTmp,time.strftime('%Y_%m_%d-%H_%H_%M_%S.wav'.format(FORMAT)))
    filename2 = time.strftime('%Y_%m_%d-%H_%H_%M_%S.wav'.format(FORMAT))
    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(rec.p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(recording)
    wf.close()
    print('Written to file: {}'.format(filename))
    print('Returning to listening')

# listen to the sound
def listen(rec):
    print('Listening beginning')
    while True:
        input = rec.stream.read(chunk, execption_on_overflow=False)
        rms_val = rec.rms(input)
        if rms_val > Threshold:
            rec.record()
k = Recorder()
k.listen()

A: You declare your __init__ as staticmethod and so there is no self (or in your case rec) argument passed into your constructor when you create an object of your class.
k = Recorder() <--- will pass a reference, typical named self, into your __init__

Please take a look at

*

*this

*or this

*and this
when you want to use a static constructor.

A: There many problems in your code and one of them is that, the first argument of member functions must be self (like the this pointer). This is because, python's philosophy is,

Explicit is better than implicit

In general, a python class looks like this:
class MyClass:
    def __init__(self, val):
        self.val = val

    def getVal(self):
        return self.val

    def setVal(self, val):
        self.val = val

obj = MyClass(5)
print(obj.getVal()) # prints 5
obj.setVal(4)
print(obj.getVal()) # prints 4

When you refactor your code to the above grammar, your code would start working. Also, do pick up some book that gives you an introduction to python in a systematic manner :)


text:
Q: Is it possible to resize browser window size using javascript? I want to resize my browser window using Javascript to test my responsive webpage design functionality.
But I didn't find any option for the same.
What I found is, we can modify window size for newly pop up window as shown below:

Open a new window, and resize the width and height to 500px:

<button onclick="openWin()">Create window</button>
<button onclick="resizeWin()">Resize window</button>

I have defined some responsive behaviour using following css code:
@media screen and (max-width: 500px){
     //style changes
}

Can we resize browser window where our page is launched? Or it is not possible?

A: You likely can use resizeBy/resizeTo but why don't you want to use Chrome built-in tester?
You can open developer console cmd/ctrl + alt + I and click on Device Toolbar or cmd/ctrl + shift + M and adjust screen size using predefined templates or create your own
Update
For automation test there are a several ways to adjust it. Which runtime is running your Jasmine tests? For PhantomJS you can use
var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
  width: 480,
  height: 800
};

More info here

A: To resize the window, you can simply do this:
window.resizeTo(width, height);

A: There are 2 options to implement responsive layout structure :

*

*by using javascript..
    function  ResponsiveLayout() {

        if (screen.width <= 1440) {

            $('#content').addClass("pipeline1");

        }
        else if (screen.width > 1440 && screen.width <= 1600) {
            $('#content').addClass("pipeline2");
        }
        else if (screen.width > 1600) {
            $('#content').addClass("pipeline3");
        }
    };ResponsiveLayout()

By using css3 media query :
@media (min-width: 1200px){css attrabutes}
@media (max-width: 1199px) and (min-width: 981px){css attrabutes}
@media (max-width: 980px) and (min-width: 641px){css attrabutes}
@media (max-width: 640px) and (min-width: 481px){css attrabutes}
@media (max-width: 480px) and (min-width: 321px){css attrabutes}
@media (max-width: 320px){css attrabutes}

Professionally Media query would be better option but can we use javascript where limited access of css file or inline css -:)


text:
Q: How to evaluate string that have exponential Javax ScriptEngine and JEval works similarly, you input an string and send it to be evaluated, and it will return you the result of it:
In ScriptEngine (almost the same in JEval):
System.out.println(engine.eval("2*3+4"));

will result in:
10.0

But when I try to make it an exponential:
System.out.println(engine.eval("2^3+4"));

will result in:
5.0

But it really should result in 12 (2^3 = 8, 8+4=12), so my question is how can I set it up in a way that the string which the will be all the whole equation, will evaluate supporting the exponential, and result correctly?
Should I use another library?

A: ^ is the XOR operand, your string means 2 XOR 3 + 4, which in facts evaluates to 1 + 4.
You have to use
Math.pow(2,3) + 4

This is my code:
System.out.println(engine.eval("Math.pow(2,3) + 4"));

Output:
12.0


text:
Q: How can I have a sorted key-value map with prefix key search? I tried to use Rust collections such as BTreeMap to store key-value pairs for use as a sorted list, but I found that it matched the exact key only.
For example, in a phone book case, I can find the item with exact key "David", but not item start with "Dav":
use std::collections::BTreeMap;

fn main() {
    let mut map = BTreeMap::new();
    map.insert("Daniel", "798-1364");

    // FOUND WITH EXACT MATCH ONLY
    //  like map.get(&"Daniel"), Not Found Here
    match map.get(&"Dan") {
        Some(&number) => println!("Found: {}", number),
        _ => println!("Not Found."),
    }
}

Can I do partial matching of the string prefix using collections such as BTreeMap?
Furthermore, if my keys are i64s, can I find a range of items such as when the key is greater than 1000? I know how to iterate through all the items, but I want to iterate just the range of items found.
Can I access the items by index, to do binary search manually?

A: You can do parts of what you like with BTreeMap::range:
use std::collections::BTreeMap;

fn main() {
    let mut map = BTreeMap::new();

    map.insert("Alexia", "123-4567");
    map.insert("Daniel", "798-1364");
    map.insert("Miranda", "987-6543");

    for (k, v) in map.range("Dan"..) {
        println!("Found: {}: {}", k, v);
    }
}

This prints:
Found: Daniel: 798-1364
Found: Miranda: 987-6543

You can extend the loop to have a "starts-with" check that will exit once you are no longer matching a prefix:
for (k, v) in map.range("Dan"..).take_while(|(k, _)| k.starts_with("Dan")) {
    println!("Found: {}: {}", k, v);
}

This concept extends to the integer key case, but you can also specify a complete range to limit the search to:
map.range("Dan".."E")

map.range(0..=1)


text: Q: How can I find all columns that have only NULL values? Is there a quick and easy way to identify all of the columns with all NULL values in my table?  I have a table with the maximum limit of columns and since I want to add additional columns, I have to first delete some of the existing non-used columns.  How can I do this?


text:
Q: Turning Type to something passable to T I'm currently trying to make a simple Web API framework that is essentially "controller-less", but loads controllers, modals, and what nots from dlls.
On startup, the framework does the following

*

*Go though the DLLs in the Plugin Folder -GOT THIS

*Look for, and invoke the "CacheRegistration" and "ContextRegistration" methods (which adds the type the list accordingly) - GOT THIS

(After going through the DLLs)

*Inject the model types into OnModelCreating (then create the database) - Check

*Iterate though the list and call Cacher.RegisterModel<T>(); (Gets the data from server and loads them into memory)

My problem is how do I call Cacher.RegisterModel<T> just buy using a Type. Some articles are pointing me to Activator.CreateInstance() but I don't need an instance, I need something that i can pass into T.
The Cacher can be refractored if needed
EDIT
On a non dynamic system EF would just do all the work on #3. As for #4, I would create a CacheConfigurator class and dump everything there and call it from global.ascx
CacherConfigurator
public static void Initialize()
{
    Cacher<Customer>.SyncData();
    Cacher<Items>.SyncData();
    // Other models
}

A: Cacher<Customer>.SyncData();
Cacher<Items>.SyncData();

If you're looking to replace this in a dynamic fashion, then reflection is (still) the way to go:
// this comes from somewhere dynamic
Type[] types = new Type[] { typeof(Customer), typeof(Items) };

foreach (Type t in types)
{
    var m = typeof(Cacher<>).MakeGenericType(t).GetMethod("SyncData", BindingFlags.Static);
    m.Invoke(null, null);
}

This will iterate through all the types, get the generic type Cacher<T> and call the static method SyncData on that type.


text:
Q: Elasticsearch UI I'm migrating from Solr to Elasticsearch and was wondering if there was a UI available that is similar to Solritas.  There is a great tool here:
http://mobz.github.com/elasticsearch-head/
Which provides browsing/searching capabilities, but it doesn't seem to have faceted browsing implemented yet (please correct me if I'm wrong).  Is there another UI that is popular with elasticsearch, or would I be better off implementing something using the extensive client apis?
Thanks,

A: Saw this recently. May be a good starting point for what you're looking for: https://github.com/okfn/facetview

A: Kibana is coming along nicely.  It requires a bit of customization to get it the way you want it, but it's built from the ground up to work with facets.

A: There is no better UI available for ES as ES-HEAD is already great and steadily improves.
But maybe this is the perfect solution ;)

"why not contribute to that project, implementing facets and sending a
  patch / pull request? – Mauricio Scheffer"

Link to source: https://github.com/mobz/elasticsearch-head

A: You can use Sense(Beta) extension of chrome browser.

A: ElasticSearch data browser
Search, charts, one-click setup....

A: Take a look at Calaca, it's a simple, yet good looking, search UI for Elasticsearch and with minimum configs required to get started. It doesn't support faceting though, but if all you need is simple search and browse, then this might work for you. On github - https://github.com/romansanchez/Calaca


text:
Q: How to get OpenVPN Client (Mikrotik RouterOS) <-> OpenVPN server (Debian/Linux) setup to work I have some issues with making MT to work with OpenVPN server (Debian). I can make successfull connection to OVPN server, but traffic is not routed through OVPN server. Here is my configuration.
Setup - http://i.imgur.com/WvbjQaj.jpg
OpenVPN server (Debian/Linux) configuration

# cat /etc/openvpn/server.conf
local 95.2.171.3
port 1194
proto tcp
dev tun

ca ca.crt
cert server.crt
key server.key
dh dh.pem

server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt

client-config-dir ccd
route 192.168.81.0/24 255.255.255.0

keepalive 10 120
tun-mtu 1500
mssfix 1450

cipher AES-256-CBC
auth sha1

persist-key
persist-tun

status /var/log/openvpn-status.log
log-append /var/log/openvpn.log

verb 5
crl-verify /etc/openvpn/easy-rsa/pki/crl.pem

# cat /etc/openvpn/ccd/client
iroute 192.168.81.0 255.255.255.0 10.8.0.2
ifconfig-push 10.8.0.2 10.8.0.1

# cat /proc/sys/net/ipv4/ip_forward
1

# netstat -an | grep 1194
tcp        0      0 95.2.171.3:1194       0.0.0.0:*               LISTEN
tcp        0      0 95.2.171.3:1194       81.190.190.100:62973    ESTABLISHED

# ifconfig
eth0   Link encap:Ethernet  HWaddr 20:cf:30:f2:a8:76
          inet addr:95.2.171.3  Bcast:95.2.171.31  Mask:255.255.255.224
          inet6 addr: fe80::22cf:30ff:fef2:a876/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:255189 errors:0 dropped:0 overruns:0 frame:0
          TX packets:333054 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:34521411 (32.9 MiB)  TX bytes:367074147 (350.0 MiB)
          Interrupt:26 Base address:0x8000

lo       Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:15579 errors:0 dropped:0 overruns:0 frame:0
          TX packets:15579 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1326071 (1.2 MiB)  TX bytes:1326071 (1.2 MiB)

tun0   Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:57 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:6669 (6.5 KiB)  TX bytes:504 (504.0 B)

# netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.8.0.2        0.0.0.0         255.255.255.255 UH        0 0          0 tun0
95.2.171.0    0.0.0.0         255.255.255.224 U         0 0          0 eth0
192.168.81.0    10.8.0.2        255.255.255.0   UG        0 0          0 tun0
10.8.0.0        10.8.0.2        255.255.255.0   UG        0 0          0 tun0
0.0.0.0         95.2.171.30   0.0.0.0         UG        0 0          0 eth0

# iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -i !lo -j REJECT --reject-with icmp-port-unreachable
-A INPUT -i tun0 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 1194 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j REJECT --reject-with icmp-port-unreachable
-A OUTPUT -j ACCEPT

# iptables -t nat -S
-P PREROUTING ACCEPT
-P POSTROUTING ACCEPT
-P OUTPUT ACCEPT
-A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 95.2.171.3
-A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 95.2.171.3
-A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 95.2.171.3

# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=1 ttl=55 time=12.9 ms
64 bytes from 8.8.8.8: icmp_req=2 ttl=55 time=12.8 ms

This is all my config on OpenVPN Server (Debian/Linux).
OpenVPN Client side (Mikrotik RouterOS 6) configuration

/interface print
Flags: D - dynamic, X - disabled, R - running, S - slave
 #     NAME                                TYPE       ACTUAL-MTU L2MTU  MAX-L2MTU MAC-ADDRESS
 0  R  ether1                              ether            1500  1600       4076 D4:CA:6D:31:14:F4
 1   S ether2                              ether            1500  1598       2028 D4:CA:6D:31:14:F5
 2   S ether3                              ether            1500  1598       2028 D4:CA:6D:31:14:F6
 3   S ether4                              ether            1500  1598       2028 D4:CA:6D:31:14:F7
 4   S ether5                              ether            1500  1598       2028 D4:CA:6D:31:14:F8
 5  RS wlan1                               wlan             1500  1600            D4:CA:6D:31:14:F9
 6  R  bridge1                             bridge           1500  1598            D4:CA:6D:31:14:F5
 7  R  ovpn-out1                           ovpn-out         1500                  FE:3E:27:7D:61:8C

 /interface bridge print
Flags: X - disabled, R - running
 0  R name="bridge1" mtu=auto actual-mtu=1500 l2mtu=1598 arp=enabled mac-address=D4:CA:6D:31:14:F5 protocol-mode=rstp priority=0x8000 auto-mac=yes admin-mac=00:00:00:00:00:00 max-message-age=20s forward-delay=15s transmit-hold-count=6 ageing-time=5m

/interface bridge port print
Flags: X - disabled, I - inactive, D - dynamic
 #    INTERFACE    BRIDGE        PRIORITY  PATH-COST    HORIZON
 0 I  ether2       bridge1                       0x80         10       none
 1 I  ether3       bridge1                       0x80         10       none
 2 I  ether4       bridge1                       0x80         10       none
 3 I  ether5       bridge1                       0x80         10       none
 4    wlan1        bridge1                       0x80         10       none

 /ip address print
Flags: X - disabled, I - invalid, D - dynamic
 #   ADDRESS            NETWORK         INTERFACE
 0   192.168.81.1/24    192.168.81.0    bridge1
 1 D 192.168.7.200/24   192.168.7.0     ether1
 2 D 10.8.0.2/32        10.8.0.1        ovpn-out1

 /ip firewall nat print
Flags: X - disabled, I - invalid, D - dynamic
 0    chain=srcnat action=masquerade to-addresses=0.0.0.0 out-interface=ether1 log=no log-prefix=""

 /ip route print
Flags: X - disabled, A - active, D - dynamic, C - connect, S - static, r - rip, b - bgp, o - ospf, m - mme, B - blackhole, U - unreachable, P - prohibit
 #      DST-ADDRESS        PREF-SRC        GATEWAY            DISTANCE
 0 ADS  0.0.0.0/0                          192.168.7.1               0
 1 ADC  10.8.0.1/32        10.8.0.2        ovpn-out1                 0
 2 ADC  192.168.7.0/24     192.168.7.200   ether1                    0
 3 ADC  192.168.81.0/24    192.168.81.1    bridge1                   0

 /interface ovpn-client print
Flags: X - disabled, R - running
 0  R name="ovpn-out1" mac-address=FE:3E:27:7D:61:8C max-mtu=1500 connect-to=195.13.171.3 port=1194 mode=ip user="client" password="" profile=default certificate=Client auth=sha1 cipher=aes256 add-default-route=no

 /ping 10.8.0.1
  SEQ HOST                                     SIZE TTL TIME  STATUS
    0 10.8.0.1                                   56  64 6ms
    1 10.8.0.1                                   56  64 9ms
    2 10.8.0.1                                   56  64 7ms
    3 10.8.0.1                                   56  64 6ms
    sent=4 received=4 packet-loss=0% min-rtt=6ms avg-rtt=7ms max-rtt=9ms

As you can see, I can ping OpenVPN server from Mikrotik. But when I use internet from Local PC it shows 81.190.190.100 IP address, not the one I would like to see - OpenVPN servers IP - 95.2.171.3.
I can successfully ping/traceroute to 10.8.0.1 from Laptop (192.168.81.100/24), but cannot understand why it's not routed through VPN tunnel. I think I'm missing something with routing either on server (Linux) or client (mikrotik).
Thanks for your help! I'm playing whit this for a while now, and cannot get it running :(
Have a good day!

A: Your client is not routing through OVPN tunnel because there is no route(default gateway) on mikrotik!
So add another gateway on mikrotik with a routing mark with destination of OVPN server 10.8.0.1
 /ip route add dst-address=0.0.0.0/0 gateway=10.8.0.1 routing-mark=clientmark

Ofcourse you shoud add a mangle rule for routing-mark like:
/ip firewall mangle add action=mark-routing chain=prerouting src-address=192.168.81.0/24 new-routing-mark=clientmark

Also there should be a nat rule for client(src-addresses 192.168.81.0/24) on it.
ip firewall nat add action=masquerade chain=srcnat src-address=192.168.81.0/24 out-interface=ovpn-out1


text:
Q: How to hide the undrlying data in a ggplot scatterplot I am trying to make a scatter plot in ggplot and would like to loose the points and show only the smooth line and the confidence interval. I checked geom_point() function and there is no option for turning it off such that the points/underlying data is hidden. Any suggestions? much appreciated.
Joseph

A: To plot smooth line with confidence interval around the line you should use geom_smooth(). This will smoothed line using loess if there are less than 1000 observations and gam if more. But you can change smoothing method with argument method=.
ggplot(mtcars,aes(wt,mpg))+geom_smooth()


text:
Q: "Run if I haven't been called in x seconds" in JavaScript Suppose I have a callback firing perpetually as the result of some event; i.e. Someone's moving a mouse.
I'd like to run a cleanup action if the callback hasn't fired in x seconds; i.e. If they haven't moved the mouse in 2 seconds, fire.
I think I could probably fix something up with setTimeout, but I'm wondering if any standard libraries have a function for this? Sort of a 'dead-mans-switch', seems like it would be common enough to have a standard method. If not I'm making one. Anyone?

A: De-bouncing may be a technique that will help.
It is essentially a method of wrapping a function so that you have control over when the wrapped function will execute, regardless of how often the debounced version is called.
This is most commonly used for events, like window resize. Then you can only execute your handler once the user has finished resizing the window rather then whilst they are resizing it.
There is also throttling, this is similar but has important differences.
Throttled functions will execute once every n time rather than a debounced version which will executed after it hasn't be called for n time.
underscore and lodash have implementations of de-bouncing and throttling.
However they it is quite easy to achieve and you don't really need a large library if its not already being used.

A: I think you're on the right track about setTimeout. As per your wonder, I am not aware of a module that would do it. And due to the intrusive nature of this process, it makes sense.
You could do this tho:
var yourmodule; //assuming you're using a module to store your app code; the object should obviously exist before continuing
yourmodule.cleanupSequenceId = -1;

function yourEventCallback() {
    if (yourmodule.cleanupSequenceId !== -1) clearTimeout(yourmodule.cleanupSequenceId);

    //function logic

    //cleanup:
    yourmodule.cleanupSequenceId = setTimeout(cleanupMethod, 2000);
}

A: After stumbling upon this (very old) question, and reading many others like it, I found a solution that works for me so I wanted to share it.
You define a "Debounce" function like this:
var debounce_timeout // Global debouncer timer, so all calls target this specific timeout.
function debounce(func, delay = 2000) {
    clearTimeout(debounce_timeout)
    debounce_timeout = setTimeout(() => {
        func()
    }, delay)
}

Now if you wish to debounce some function, you do:
debounce(myFunction)

Debouncing essentially means, that when your function is called, we observe for 'delay' duration, if any other calls to the function is made. If another call is made, we reset our observing time.


text:
Q: Shell script for running subprocesses two at a time Let's assume there are a total of 10 subprocesses which I want my shell script to run. Subprocess (i.e. a process created within the shell script)  being called x1...10 for simplicity. A normal shell script would have 10 lines; let's assume each line calls ./xi. However, to maximize efficiency, I know my hardware allows for two of the subprocesses to be launched at the same time. Therefore, at any point in time, two of these processes should be running. The moment that one is done, the next is launched. No order should be assumed in how they finish, any order is fine as they are assumed independent. Is there an elegant way of doing this in a shell script? Note, each x1...x10 should run once only.

A: seq 10 | xargs -P2 -I{} ./xi

*

*seq 10 - Outputs 10 numbers. We don't care about them.

*xargs run a command for each input

*

*-P2 runs two processes at a time.

*-I{} replaces each {} in the command for the input line. So just discard the input.

*./x{} run this command for each line in the input.

Final answer: cat myshellscript.sh | xargs -L 1 -I CMD -P 2 bash -c CMD
With myshellscript.sh being a file like this:
./task-jsuqh
./task-siuww
./task-uqywh
./task-sdqaw


text:
Q: .focus() jQuery & vanilla js not working on element in firefox I have a  element that I've made focusable through tabindex="0" attribute. These labels contain inputs and are custom checkboxes. The typical functionality between checkboxes and radios in a group is to use the up and down arrow keys to switch between them and space to select.
I am trying to recreate this behavior, which doesn't work because of the nesting within in divs.
I have recreated the behavior with jQuery's .next() and .prev() to go focus on the next or previous label and focus on it. This works fine in chrome.
It does not work in firefox.
When I log the element that I am selecting (console.log($(event.target).prev()[0]) exists and it exists and is the right element. When I try to use .focus() on it or wrap it in a jQuery selector and then try jQuery's .focus() on it, nothing happens. Only in firefox.
I read somewhere to put it in a setTime delaying after the keyup event, but that doesn't work either.
Does anyone have any ideas?
Here is a sample of my html:

                    <fieldset class="formify-fieldset">

Is the district operating as the fiscal agent of a consortium or
                            shared
                            service agreement: *

                            <input class="formify-field formify-radio ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" ng-model="formData.fiscalAgentCOrSA" name="fiscalAgentCOrSA" value="1" id="formify-field-537-0" required="" type="radio">

                            Yes

                            <input class="formify-field formify-radio ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" ng-model="formData.fiscalAgentCOrSA" name="fiscalAgentCOrSA" value="0" id="formify-field-537-1" required="" type="radio">

                            No
                    </fieldset>

Here is the jQuery:
 $('.formify-radio').on('keyup', function(e){
    var event=e||window.event;
    if(event.which===13 || event.which===32){
        $(event.target).find('input').trigger('click');
    }
    if(event.which===38){
        if($(event.target).prev().is('label')) $($(event.target).prev()[0]).focus();
    }
    if(event.which===40){
        if($(event.target).next().is('label')) $($(event.target).next()[0]).focus();
    }
});

Update: Here is a jsfiddle: https://jsfiddle.net/afxkutvm/


text:
Q: Prestashop - Admin Order Confirmation Mail Template modification I am trying to edit an order confirmation mail sent to admin. Can anyone guide me where to find that piece of code. I was able to change the User confirmation mail, but can't find the mail sent to admin.
Note: I am using a MailAlert module.

A: To modify the body of a message can be done from the support of the backoffice in translations.
Location ---> Translations, (Translations of emails)
To change transactional aspects, it will depend a lot on what you want to change, but many changes can be solved from the file:
public_html / classes / Mail.php
For example,. if you want to modify the subject or similar things.

A: It is your-site/modules/mailalerts/mails/en/new_order.html.


text:
Q: center arabic words or images with tikz I want to center the Arabic content (words and images) in the page with tikz. The content is not placed in the center as expected. Any advice?
 % !TEX TS-program=lualatex
    \documentclass[a5paper,12pt,landscape]{article}
    %\usepackage[empty]{fullpage}
    \usepackage{graphicx}
    \usepackage{tikz}
    \usetikzlibrary{calc,positioning,backgrounds}
    \definecolor{gris}{HTML}{D7D7D7}
    \usepackage{gradientframe}
    \usepackage{garamondlibre}
    \pagenumbering{gobble}
    \usepackage{polyglossia}
    \setmainlanguage[locale=algeria,numerals=maghrib]{arabic}
    \setotherlanguage{english}
    \usepackage{fontspec}
    \setmainfont[Script=Arabic]{Amiri}

    \begin{document}

    \begin{tikzpicture}[remember picture,overlay]
    \node  (image) at (current page.center) {\gradientframe[linewidth=1px,padding =5 mm ]{\includegraphics[width=0.8\paperwidth,height=0.7\paperheight]{myimage}}};
    \node[font=\fontsize{50}{60}\selectfont,below=2ex of image](word) {القراءة};
    \end{tikzpicture}

    \end{document}

A: If you refrain from using the polyglossia package, your image will be centred as desired:
% !TEX TS-program=lualatex
\documentclass[a5paper,12pt,landscape]{article}
%\usepackage[empty]{fullpage}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{calc,positioning,backgrounds}
\definecolor{gris}{HTML}{D7D7D7}
\usepackage{gradientframe}
\usepackage{garamondlibre}
\pagenumbering{gobble}
\usepackage[bidi=default]{babel}
\babelprovide[import]{arabic}
\babelfont[arabic]{rm}{Amiri}

\begin{document}

\begin{tikzpicture}[remember picture,overlay]
\node  (image) at (current page.center) {\gradientframe[linewidth=1px,padding =5 mm ]{\includegraphics[width=0.8\paperwidth,height=0.7\paperheight]{example-image-duck}}};
\node[font=\fontsize{50}{60}\selectfont,below=-3ex of image](word) {\foreignlanguage{arabic}{القراءة}};
\end{tikzpicture}

\end{document}

A: Compiling with LuaLaTeX using a trick like:
\node[
    anchor=center,
    xshift=12.5cm,
    yshift=0mm
    ]

\documentclass[a5paper,12pt,landscape]{article}
%\usepackage[empty]{fullpage}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{calc,positioning,backgrounds}
\definecolor{gris}{HTML}{D7D7D7}
\pagenumbering{gobble}
\usepackage{polyglossia}
\setmainlanguage[locale=algeria,numerals=maghrib]{arabic}
\setotherlanguage{english}
\usepackage{fontspec}
\setmainfont[Script=Arabic]{Amiri}
\usepackage{gradientframe}

\begin{document}
\begin{tikzpicture}[remember picture,overlay]
\node[
    anchor=center,
    xshift=12.5cm,
    yshift=0mm
    ]  (image) at (current page.center) {\gradientframe[linewidth=1px,padding =5 mm ]{\includegraphics[width=0.8\paperwidth,height=0.7\paperheight]{example-image-a}}};
    \node[font=\fontsize{50}{60}\selectfont,below=-3ex of image](word) {القراءة};
\end{tikzpicture}
\end{document}

A: Curious: There seems to be a complex interaction between margins, text directionality, total tikz picture size and overlay (=data in .aux file from previous runs) when calculating 'center'.
Keeping polyglossia, and using absolute image positioning, no remembered overlay, geometry's default settings plus smaller margins, and slightly scaled down image and caption and caption position gives:

which seems to be stable.
MWE
    \documentclass[a5paper,12pt,landscape]{article}
    \usepackage[margin=1cm]{geometry}

    \usepackage{graphicx}
    \usepackage{tikz}
    \usetikzlibrary{calc,positioning,backgrounds}
    \definecolor{gris}{HTML}{D7D7D7}
    \usepackage{gradientframe}
    \usepackage{garamondlibre}
    \pagenumbering{gobble}
    \usepackage{polyglossia}
    \setmainlanguage[locale=algeria,numerals=maghrib]{arabic}
    \setotherlanguage{english}
    \newfontfamily\arabicfont[Script=Arabic,Renderer=HarfBuzz,Colour=blue]{Amiri}
    \newfontfamily\captionfont[Scale=2.5,Script=Arabic,Renderer=HarfBuzz,Colour=red]{Amiri}
%    \usepackage{fontspec}
%    \setmainfont[Script=Arabic]{Amiri}

    \begin{document}
\fcolorbox{black}{green!3}{%
    \begin{tikzpicture}%[remember picture,overlay]
    \node  (image) at (current page.center) {%
    \gradientframe[linewidth=1px,padding =5 mm ]{%
    \includegraphics[width=0.75\textwidth]{example-image-duck}%
    }%
    };
    \node[below=0.5ex of image](word) {{\captionfont القراءة}};
    \end{tikzpicture}
}
%\selectlanguage{arabic}
%
%    القراءة
%
    \end{document}


text:
Q: Google app engine CNAME redirection I have an application which is running on GAE. I would like to use a custom URL and
have configured the cname as per the instructions on google. But end up getting an SSL error even though the cname look up works fine. I am wondering if there's any special setting i need to enable on the GAE side?
*
Find the CNAME settings and enter the following as the CNAME value or alias:
status
Set the CNAME destination to the following address:
ghs.googlehosted.com

*
The specific error I am getting back is:
Error 107 (net::ERR_SSL_PROTOCOL_ERROR): SSL protocol error.


text: Q: Working with hexadecimal color codes I am working on a Web Api that returns JSON data. How do I return a converted Color from hex code as a string or whatever type that can be wired up in the front end to represent a color?, in other words, how can I return the color White from #ffffff hex code and assign it to a Model property so it can be returned as part of a JSON response?


text:
Q: Julia: Zygote.@adjoint from Enzyme.autodiff Given the function f! below :
function f!(s::Vector, a::Vector, b::Vector)

  s .= a .+ b
  return nothing

end # f!

How can I define an adjoint for Zygote based on
Enzyme.autodiff(f!, Const, Duplicated(s, dz_ds). Duplicated(a, zero(a)), Duplicated(b, zero(b))) ?
Zygote.@adjoint f!(s, a, b) = f!(s, a, b), # What would come here ?

A: Could figure out a way, sharing it here.
For a given function foo, Zygote.pullback(foo, args...) returns foo(args...) and the backward pass (which allows for gradients computations).
My goal is to tell Zygote to use Enzyme for the backward pass.
This can be done by means of Zygote.@adjoint (see more here).
In case of array-valued functions, Enzyme requires a mutating version that returns nothing and its result to be in args (see more here).
The function f! in the question post is an Enzyme-compatible version of a sum of two arrays.
Since f! returns nothing, Zygote would simply return nothing
when the backward pass is called on some gradient passed to us.
A solution is to place f! inside a wrapper (say f) that returns the array s
and to define Zygote.@adjoint for f, rather than f!.
Hence,
function f(a::Vector, b::Vector)

  s = zero(a)
  f!(s, a, b)
  return s

end

function enzyme_back(dzds, a, b)

  s    = zero(a)
  dzda = zero(dzds)
  dzdb = zero(dzds)
  Enzyme.autodiff(
    f!,
    Const,
    Duplicated(s, dzds),
    Duplicated(a, dzda),
    Duplicated(b, dzdb)
  )
  return (dzda, dzdb)

end

and
Zygote.@adjoint f(a, b) = f(a, b), dzds -> enzyme_back(dzds, a, b)

inform Zygote to use Enzyme in the backward pass.

Finally, you can check that calling Zygote.gradient either on
g1(a::Vector, b::Vector) = sum(abs2, a + b)

or
g2(a::Vector, b::Vector) = sum(abs2, f(a, b))

yields the same results.


text:
Q: Change face of plain text between double quotation marks in Emacs I am looking for a way to highlight or use different face of quoted text in plain text. It seems that there should be a sophisticated/enhanced text mode but I cannot find it.
If there isn't a easy solution, can you let me know where should I begin to write a function?
Thank you very much!
A noob who has been using Emacs from 19.xx

A: I'm not sure about a major-mode that already does this, but you can make one easily enough using define-derived-mode
(define-derived-mode rich-text-mode text-mode "Rich Text"
  "text mode with string highlighting."

  ;;register keywords
  (setq rich-text-font-lock-keywords
        '(("\"\\(\\(?:.\\|\n\\)*?[^\\]\\)\"" 0 font-lock-string-face)))
  (setq font-lock-defaults rich-text-font-lock-keywords)
  (font-lock-mode 1))

Alternatively, you can add a hook to text-mode:
(defun add-quotes-to-font-lock-keywords ()
  (font-lock-add-keywords nil '(("\"\\(\\(?:.\\|\n\\)*?[^\\]\\)\"" 0 font-lock-string-face))))

(add-hook 'text-mode-hook 'add-quotes-to-font-lock-keywords)

Generally speaking, a good mode for editing any text is org-mode.  It does not font-lock strings by default, though.

A: For the regexp, I think you want to exclude " itself in the string content, except when escaped.  Something like this --- ", followed by either a non " or an escaped character, followed by ":
\"\\([^\"]\\|\\\\\\(.\\|[\n]\\)\\)*\"

But be aware that matching quotations "..." is notorious.  I do exactly that in Info+, but there are a few Info nodes where this highlighting gets thrown off by the occasional lone \" or ?\" in manuals that refer to such programming constructs.


text:
Q: Class with generic type and generic list I want to have a list of custom objects with a "generic" type in one of the properties.
public class Tag
{
    public string Name { get; set; }
    public int id { get; set; }

    public ??? value {get;set;}

}

The "value" can be int,double,string or bool.
How can I make a "generic" list of my custom Tag class?
public list<Tag> t;

I have looked the "generic" collections and classes, but the problem, is that if I made
class Tag<T>{}

I can not do:
List<Tag<T>> list = new List<Tag<T>>();
list.add(new Tag<int>());
list.add(new Tag<double>());

I have tried using interfaces, base classes ... I don't know where to look
Some ideas? help?
Thank  you so much.

A: A common approach would be to make an interface or base class.
public interface ITag
{
    string Name { get; set; }
    int Id { get; set; }

    object Value { get; }
    Type ValueType { get; }
}

Then Tag can be generic:
public class Tag<T> : ITag
{
    public string Name { get; set; }
    public int Id { get; set; }

    public T Value { get; set; }

    object ITag.Value => this.Value;
    Type ITag.ValueType => typeof(T);
}

Now you can do this:
List<ITag> list = new List<ITag>();
list.Add(new Tag<int>());
list.Add(new Tag<double>());

The question is still why?


text:
Q: Why won't Windows Installer use the UI in the .msi file during removal? Has anyone been able to get Windows Installer to use the InstallUISequence table during removal?
I started with an MSI file produced by the Visual Studio msi builder, decompiled it into WiX source code and handcrafted it, but I cannot get the installer to use my UI during removal.    It insists on using a default UI provided by Windows Installer.
I have also analyzed several MSI files, and I have been unable to find one where Windows Installer will use the provided UI during removal.
I captured the msiexec logs during removal, and sure enough, Windows Installer appears to be ignoring the InstallUISequence table.
It seems that msiexec runs with minimal UI during removal.   If I specify the /qf switch (use full UI) during removal, then Windows Installer does take the UI from the .msi file.   However, this doesn't help the regular user, because she won't do the removal from msiexec.
Does anyone know of a way to convince Windows Installer to use the UI in the MSI file by default?

A: When removing an application from Add/Remove Programs, this will always run with "basic" UI.
You can't make uninstall run with full UI, the best you can do is prevent removal and force people to 'modify' (which does run with UI) and remove from there.
Whatever you do, there's still no way to prevent someone right clicking on the original MSI and selecting 'Remove', this will always run with basic UI.

A: The "Why" is basically because Microsoft says so. :-)  Can't say I disagree as I get annoyed when ISV's get all cute when I'm just trying to remove a program.


text:
Q: Унифицированный способ хранения данных Есть колонка в таблице бд, и в ней я хочу хранить несколько различных значений, ну и чтобы в конечном итоге до этих значений был удобный доступ, как вариант припустим создать массив и сериализировать его и в таком виде хранить, но в таком случае доступность будет зависеть от конкретного ЯП и его реализации сериализации, какую можно выбрать альтернативу? Я думаю XML или есть еще что-то?
A: Если нужно хранить <жизнь>, <урон>, <защита> и подобное — то можно в той же таблице персонажей:
id | name  | health | power | defence
 1 | Some  |    100 |     2 |       3
 2 | Other |     78 |     2 |       3

И в большинстве случаев это лучший вариант.
А вот когда дойдет дело, скажем, до вещмешка, то его содержимое нужно хранить в отдельной таблице, причем сначала нужно составить таблицу всех возможных единиц:
id | name
 1 | Отвертка
 2 | Ключ
 3 | Разводной ключ

А потом сделать таблицу связей (у кого что есть):
id | person_id | item_id | quantity
 1 |         1 |       1 |        2
 2 |         2 |       3 |        1
 3 |         1 |       2 |        3

Выходит, что знаешь, у кого какие есть инструменты и в каком количестве (иногда есть смысл вместо указания количества quantity просто добавлять еще одну строку, но это некошерно).
Получается, что ты можешь узнать с помощью одного простого запроса, у кого сколько здоровья, силы и прочее. А когда нужно будет получить содержимое вещмешка персонажа (у тебя есть его id персонажа), нужно будет выполнить 1 запрос со склейкой (ну или с подзапросом), в результате ты получишь вот это:
id | person_id | item_id | quantity | item_name | item_quantity
 1 |         1 |       1 |        2 | Отвертка  |             2
 3 |         1 |       2 |        3 | Ключ      |             3

То есть, у персонажа #1 по имени Some есть 2 отвертки и 3 ключа.


text:
Q: BLE itag alarm on every xx hours in swift Im trying to develop app for iOS in swift language that will on remote notification trigger alarm (beep) on BLE iTag. For now i can make it to work when app is in background state. But i would like to make it work also when user force-quit or swipe away app. Is it possible? Is it possible to keep iTag connected when user force-quit app?

A: No, it is not possible to receive remote notifications or do anything if your app is not running.


text:
Q: How to implementing two collection view inside of view controller? Hi I am beginner in Swift programming language and I have problem to implementing two collection view inside of view controller, this is the link of my picture that I want to achieve:
The picture I want to achieve
is it possible? so far I have the codes that doesn't seems work:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate{

@IBOutlet weak var collectionView: UICollectionView!

@IBOutlet weak var collectionViewTwo: UICollectionView!

var optionOne = ["Gulsah", "Hurrem", "Mihrimah", "Nilufer"]

override func viewDidLoad() {
    super.viewDidLoad()

    self.resetFilterThumbnails()
    self.collectionView.delegate = self

}
//For the collectionView, number of filters in the section
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if (filters == true){
        //do all the stuff here for FILTER_CELL
        return self.filters.count}
    else{
        return self.optionOne.count}

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FILTER_CELL", forIndexPath: indexPath) as FilterThumbnailCell
    let cellTwo = collectionView.dequeueReusableCellWithReuseIdentifier("FILTER_CELL_TWO", forIndexPath: indexPath) as FilterThumbnailCell
    var filterThumbnail = self.filterThumbnails[indexPath.row]
    println("filter cell two")

    if (indexPath.item == 0){
        //do all the stuff here for FILTER_CELL
        if filterThumbnail.filteredThumbnail != nil {
            cell.imageView.image = filterThumbnail.filteredThumbnail
        } else {
            cell.imageView.image = filterThumbnail.originalThumbnail
            //filterThumbnail is a class instance
            filterThumbnail.generateThumbnail({ (image) -> Void in
                if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? FilterThumbnailCell {
                    cell.imageView.image = image
                }
            })
        }
        return cell

    }else{
        //FILTER_CELL_TWO
        var  button = cellTwo.viewWithTag(1) as UILabel

        button.text = optionOne[indexPath.row]
        cellTwo.backgroundColor = UIColor.redColor()

        return cellTwo

    }

}
}

A: This is very Possible.  You could do this in several ways.
1:
You could implement two contained view controllers.  This might be the cleanest since you could handle interaction in separate controllers. In this case you may need to also implement some delegate/protocols to pass information back to the parentViewController.
2:
You could create a separate datasource/delegate class to handle the associated functions for each view controller and assign them in viewDidLoad.  This case may also need to have delegates/protocols implemented to pass information from the collectionView dataSource/Delegate class.
Here is an example, taken from the Master-Detail starting class  Create your class like this (add conform to the UITableViewDelegate if needed):
import UIKit

class MyDataSource: NSObject, UITableViewDataSource {

    var objects = [AnyObject]()

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return objects.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        let object = objects[indexPath.row] as NSDate
        cell.textLabel!.text = object.description
        return cell
    }

}
Then in your UIViewController you create a variable of type MyDataSource:
var dataSource1 = MyDataSource()
var dataSource2 = MyDataSource()

Inside of viewDidLoad you can assign the dataSource its objects and assign the datasource to the tableviews:
dataSource1.objects = objects1;
dataSource2.objects = objects2;

tableView1.dataSource = dataSource1
tableView2.dataSource = dataSource2

Now each of the tableviews will use a different instance of this DataSource, with its own set of model objects.  If you need to further customize you datasource (as it looks like you do) Simply create another data source class and assign it to the appropriate object.  If you conform to the delegate of the tableview inside these data source objects, you should implement a standard protocol for the data source, and conform to that protocol inside of your view controller:
Above the datasource object:
protocol DataSourceDelegate{
    func didSelectCellAtIndexPath(indexPath:NSIndexPath)
}

Inside of the data source object:
var dataSourceDelegate:DataSourceDelegate?

Inside of the view controller:
dataSource.dataSourceDelegate = self

Make sure to conform to the delegate in the class definition.  Then instantiate the method in the view controller:
func didSelectCellAtIndexPath(indexPath:NSIndexPath){
     // Your code here
}

Make sure to call the delegate inside the datasource
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    dataSourceDelegate?.didSelectCellAtIndexPath(indexPath)

}

To register cells, if you are using storyboard, just make sure that the cell identifiers are the correct ones, and you will not need to register anything else.  If not, you could register the cell inside the dataSource (probably a good idea, since it would keep all the info contained)
3:
You could use one viewController and differentiate between the cases by comparing the collectionView passed into the dataSource/Delegate functions to an outlet connected to the corresponding collectionViews in the view.  While this case will not need any delegates implemented, it will fill the viewController up with a lot of if/else statements, perhaps making the code more difficult to maintain/read.


text:
Q: Harmony for python? Is there a Javascript and DOM environment like Harmony for Python?
I want to execute Javascript on the DOM elements of a fetched/generated HTML. How can I do it in Python?

A: Given that Harmony uses Johnson, which is a Ruby interface to Spidermonkey, and envjs, which is a pure javascript browser environment, you could probably use pyv8 (http://code.google.com/p/pyv8/) to achieve the same effect.


text:
Q: mount: No such file or directory with encrypted recovery I have destroyed my Mint Linux installation.  I just wanted access to my remote storefront.  So what happened was I was having trouble with ICEauthority file in my home directory.  So following different directions on the internet I came to the conclusion that I could set the home directory recursively to chmod 755 to allow that file to work…eventually I ran into problems with the system loading.  Eventually by setting the home directory to executable permission for root was I able to get read/write access…but then i reset my machine oh why oh why did i reset my machine!!! - now the system throws me the same error with ICEauthority but it never gets me into the OS because the disk is encrypted.  Nothing I've tried seems to work and I don't have the original mounting seed.  I've also tried sudo ecryptfs-recover-private but my system then just says No such file or directory:
frankenmint@honeybadger /home $ sudo ecryptfs-recover-private
INFO: Searching for encrypted private directories (this might take a while)...
INFO: Found [/home/.ecryptfs/frankenmint/.Private].
Try to recover this directory? [Y/n]: y
INFO: Found your wrapped-passphrase
Do you know your LOGIN passphrase? [Y/n] y
INFO: Enter your LOGIN passphrase...
Passphrase:
Inserted auth tok with sig [979c6cdf80d2e44d] into the user session keyring
mount: No such file or directory
ERROR: Failed to mount private data at [/tmp/ecryptfs.Hy3BV96c].

I'm really worried because I had important files on there that were stored on a virtual machine…If I could just get to those files then I would have no qualms nuking the setup and starting over

A: I found that running sudo bash and then running ecryptfs-recover-private as root (rather than via sudo) worked.  Not sure why it should be any different.
Edit:
TL;DR:
# ecryptfs-unwrap-passphrase /mnt/crypt/.ecryptfs/user/.ecryptfs/wrapped-passphrase - | ecryptfs-add-passphrase --fnek -
    < Type your login password here >
Inserted auth tok with sig [aaaaaaaaaaaaaaaa] into the user session keyring
Inserted auth tok with sig [bbbbbbbbbbbbbbbb] into the user session keyring

You will not see a prompt and must type your login password, blind, into the above command.
Replace the aaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbb below with the hex signatures between brackets from the output above, in order:
# mount -i -t ecryptfs -o ecryptfs_sig=aaaaaaaaaaaaaaaa,ecryptfs_fnek_sig=bbbbbbbbbbbbbbbb,ecryptfs_cipher=aes,ecryptfs_key_bytes=16 /mnt/crypt/.ecryptfs/user/.Private /mnt/plain

Preliminaries
It turns out just running as root did not work reliably for me; sometimes it did, sometimes it didn't.  Basically, ecryptfs seems buggy and quite user-unfriendly, often confusing login passwords and mount passphrases.  After going down a deep, dark rabbit hole, I have some tips that should help.  These notes are for Ubuntu 17.10, ecryptfs-utils 111-0, and you should become root before starting.  I assume you want to mount your home directory from /mnt/crypt (which should already be mounted) to /mnt/plain, and you should replace user with the username.
Start Easy
The first thing to try is:
# ecryptfs-recover-private /mnt/crypt/.ecryptfs/user/.Private

If this works, well, you're lucky.  If not, it may give an error message from mount about no such file or directory.  This is extremely misleading: what it really means is your mount passphrase is wrong or missing.
Get The Signatures
Here is the important part: we need to verify ecryptfs is really trying the right mount passphrase(s).  The passphrases must be loaded into the Linux kernel before ecryptfs can mount your filesystem.  ecryptfs asks the kernel for them by their signature.  The signature is a 16-byte hex value (and is not cryptographically sensitive).  You can find the passphrase signatures ecryptfs is expecting:
# cat /mnt/crypt/.ecryptfs/user/.ecryptfs/Private.sig
aaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb

Remember these. The goal is to get passphrases with these signatures loaded into the kernel and then tell ecryptfs to use them.  The first signature (aaaaaaaaaaaaaaaa) is for the data, and the second (bbbbbbbbbbbbbbbb) is the FileName Encryption Key (FNEK).
Get the mount passphrase
This command will ask you for you login password (with a misleading prompt), and output your mount passphrase:
# ecryptfs-unwrap-passphrase /mnt/crypt/.ecryptfs/user/.ecryptfs/wrapped-passphrase

Copy this but be careful!!, as this is extremely cryptographically sensitive, the keys to the kingdom.
Try an interactive mount
The next thing to try is:
# mount -t ecryptfs /mnt/crypt/.ecryptfs/user/.Private /mnt/plain

The crucial thing here is that mount needs your (super-sensitive) mount passphrase that we just copied (not your login password).
This will ask you some questions, and you can accept the defaults except say yes to Enable filename encryption.  It may give you a warning and ask to cache the signatures; you can say yes to both, but do double-check that you've got the right mount passphrase.
You will see the options that mount has decided to try for you:
Attempting to mount with the following options:
  ecryptfs_unlink_sigs
  ecryptfs_fnek_sig=bbbbbbbbbbbbbbbb
  ecryptfs_key_bytes=16
  ecryptfs_cipher=aes
  ecryptfs_sig=aaaaaaaaaaaaaaaa
Mounted eCryptfs

If the signatures are wrong (don't match what you got from Private.sig), the mount won't work.
...but it will very unhelpfully report that it did.  You will have to do an ls /mnt/plain and cat a file to make sure.  At this point you can also look in /var/log/syslog and verify that ecryptfs is looking for the same signatures we are.
There are clearly two serious issues with ecryptfs here, and we have to work around them.
Load the keys into the kernel
If the interactive mount didn't help, we have to load the keys into the kernel ourselves and manually specify them in the mount options.
# ecryptfs-add-passphrase --fnek

And paste in your (super-senstive) mount passphrase copied from above.  This should output:
Inserted auth tok with sig [aaaaaaaaaaaaaaaa] into the user session keyring
Inserted auth tok with sig [bbbbbbbbbbbbbbbb] into the user session keyring

Mount manually
Now the passphrases are loaded into the kernel, and we just need to tell mount to use them:
# umount /mnt/plain
# mount -i -t ecryptfs -o ecryptfs_sig=aaaaaaaaaaaaaaaa,ecryptfs_fnek_sig=bbbbbbbbbbbbbbbb,ecryptfs_cipher=aes,ecryptfs_key_bytes=16 /mnt/crypt/.ecryptfs/user/.Private /mnt/plain

You'll notice the options are similar to what the interactive mount printed out, except we're manually telling ecryptfs what's up.
Hopefully this works.  If not, you can check that the keys are loaded into the kernel with the correct signatures using keyctl list @u, which should print out at least the two signatures you're expecting.

A: To future viewers of this Q&A: the same apparent symptom may be caused by different underlying reasons. The symptom looks like:
INFO: Found [/home/.ecryptfs/frankenmint/.Private].
Try to recover this directory? [Y/n]: y
INFO: Found your wrapped-passphrase
Do you know your LOGIN passphrase? [Y/n] y
INFO: Enter your LOGIN passphrase...
Passphrase:
Inserted auth tok with sig [979c6cdf80d2e44d] into the user session keyring
mount: No such file or directory
ERROR: Failed to mount private data at [/tmp/ecryptfs.Hy3BV96c].

In my case, this answer held the key to the solution. The problem was that I was trying to do everything remotely over SSH in a Tmux session, which somehow messes up with user session keyrings.
The aforementioned answer suggests to comment a certain line in /etc/pam.d/sshd out and try again in a new session, but that did not work for me. The simple workaround that worked instead was to do it on location, avoiding SSH and Tmux altogether.
Update:
Inspired heavily by this answer, I was able to mount my old encrypted home, while connected over SSH in a Tmux session, using the following approach:
Assuming that the old root partition (where /home/ used to be) is mounted at /mnt/oldroot/, and the old username is olduser:
mkdir -p ~/.ecryptfs
echo "/mnt/oldroot/home/.ecryptfs/olduser/.Private /mnt/oldroot/home/olduser ecryptfs" > ~/.ecryptfs/oldhome.conf
cp -a /mnt/oldroot/home/.ecryptfs/olduser/.ecryptfs/Private.sig ~/.ecryptfs/oldhome.sig

# This will prompt for the old login password:
ecryptfs-insert-wrapped-passphrase-into-keyring /mnt/oldroot/home/.ecryptfs/olduser/.ecryptfs/wrapped-passphrase

# This will mount the old decrypted home contents over /mnt/oldroot/home/olduser:
mount.ecryptfs_private oldhome


text:
Q: removing write permission does not prevent root from writing to the file I just noticed on my Ubuntu machine (ext3 filesystem) that removing write permissions from a file does not keep root from writing to it.
Is this a general rule of UNIX file permissions? Or specific to Ubuntu? Or a misconfiguration on my machine?

# touch abc
# chmod ugo-w abc
# python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> open('abc','w').write('AAA\n')
>>>
# cat abc
AAA

Writing to the file fails (as expected) if I do this from my normal user account.

*

*Is this normal behavior?

*Is there a way to prevent root from accidentally writing to a file? (Preferably using normal filesystem mechanisms, not AppArmor, etc.)
Please teach me about something that I most definitely don't understand.
NOTE: I understand that root has total control over the system and can, eg, change the permissions on any file. My question is whether currently set permissions are enforced on code running as root. The idea is the root user preventing her/himself from accidentally writing to a file.
NOTE: I also understand that one should not be logged in as root for normal operations. I just noticed this behavior and am asking you about it.

A: 1) This is a normal behaviour. root has rw access on all files at all times.
2) You can protect a file even from root (not deliberate action, but accidental, anyway) by using
chattr +i filename.ext

That is "change attributes add immutable". To remove the protection:
chattr -i filename.ext

have a look at man chattr for more info

A: *

*Yes, this is normal.  Root is god.

*Yes, there are ways to prevent root from overwriting files.

*

*Set the immutable bit with chattr (+i sets, -i unsets).  Requires root access, works only on ext2/ext3 (presumably ext4 too), but is otherwise practical.

*Don't run apps as root.  No root privs, no overwriting files.  Use sudo to access system functions.

*Unmount the filesystem.  No mounted fs, no overwriting files.  [*]

*Turn off computer.  No electricity, no overwriting files.

These methods follow logically from #1.  As you can see, the last two methods are generally not useful, in the same way that protecting Windows against viruses by unplugging the network is generally not useful.  This is why root is dangerous.[+]
[*] Discounting the possibility of "accidentally" writing directly to the block device, of course.  Yes, root can do that.  Yes, you can prevent that: disconnect the device.
[+] This is also where those BOfH myths come from.  They're not all myths.

A: You can also restrict file access for the root user, by using Linux kernel "Capabilities": http://www.securityfocus.com/infocus/1400
There is also the possibility of using SE-Linux or some other kernel patch to make some files immutable even to root.

A: I think that as long as root is the superuser, and he can do anything, you cannot remove him any permission, also if you are the root. It is supposed to be the will of the root to prevent himself of doing or not an operation (such as write into a file, or open an application).
So no, chances are you would only deactivate the root account, to prevent a bad use of it.
Regards
[note to self: ye shall be humble...maybe ye are wrong]


text:
Q: Accuracy of model is 0.86 while AUC is 0.50? I ran a few models in sklearn. Here is the code for the same.
# Function for Stochastic Gradient Descent Logistic Regression with Elastic Net
def SGDlogistic(k_fold,train_X,train_Y):
        """Method to implement Multi-class SVM using
        Stochastic Gradient Descent
        """

        from sklearn.linear_model import SGDClassifier
        scores_sgd_lr = []

        for train_indices, test_indices in k_fold:
            train_X_cv = train_X[train_indices]
            train_Y_cv= train_Y[train_indices]

            test_X_cv = train_X[test_indices]
            test_Y_cv= train_Y[test_indices]

            sgd_lr=SGDClassifier(loss='log',penalty='elasticnet')
            scores_sgd_lr.append(sgd_lr.fit(train_X_cv,train_Y_cv).score(test_X_cv,test_Y_cv))

        print("The mean accuracy of Stochastic Gradient Descent Logistic on CV data is:", np.mean(scores_sgd_lr))

        return sgd_lr

def test_performance(test_X,test_Y,classifier,name):
        """This method checks the performance of each algorithm on test data."""

        from sklearn import metrics

        # For SGD
        print ("The accuracy of "+ name + " on test data is:",classifier.score(test_X,test_Y))
        print 'Classification Metrics for'
        print metrics.classification_report(test_Y, classifier.predict(test_X))
        print "Confusion matrix"
        print metrics.confusion_matrix(test_Y, classifier.predict(test_X))

def plot_ROC(test_X,test_Y,classifier):
    """ This functions plots the ROC curve of the classifier"""

    from sklearn.metrics import roc_curve, auc
    false_positive_rate, true_positive_rate, thresholds =roc_curve(test_Y, classifier.predict(test_X))
    roc_auc= auc(false_positive_rate, true_positive_rate)
    plt.title('Receiver Operating Characteristic')
    plt.plot(false_positive_rate, true_positive_rate, 'b',label='AUC = %0.2f'% roc_auc)
    plt.legend(loc='lower right')
    plt.ylabel('True Positive Rate')
    plt.xlabel('False Positive Rate')

The first function does logistic regression with Elastic net penalty.
The second function is testing the perfomance of the algo on the test data. This gives confusion matrix and the accuracy.
While plot_ROC plots the ROC curve on test data.
Here is what I see.
('The accuracy of Logistic with Elastic Net on test data is:', 0.90566607467092586)
Classification Metrics for
             precision    recall  f1-score   support

          0       0.91      1.00      0.95    227948
          1       0.50      0.00      0.00     23743

avg / total       0.87      0.91      0.86    251691

Confusion matrix
[[227944      4]
 [ 23739      4]]

(array([ 0.        ,  0.00001755,  1.        ]),
 array([ 0.        ,  0.00016847,  1.        ]),
 array([2, 1, 0]))

If you see , the accuracy on test data 90% and even the confusion matrix shows good precision and recall. So it's not just accuracy which might be misleading. But the ROC and AUC it gives is like 0.50?. That's so weird. It is behaving as a random guess as per ROC while the accuracy and Confusion matrix show a different picture.
Help pls
Edit 2:
Ok. SO I added the code for using probabilities instead of actual classification in AUC.
This is what I get now.

As you see AUC of 0.71.  I haven't done anything for class imbalance. One question. How do I convert the prediction scores to probabilities for SVM etc. Currently it has predict_proba for only log loss or Huber Loss functions. That means I can't go beyond Logistic regression to get AUC?

A: Your results seem to indicate the classifier is prediction 0 in almost all cases.
Below is an example where the data is 90% in class 0 and the classifier always predicts 0. It looks very similar to your results.
from sklearn.metrics import confusion_matrix, classification_report
y_true = [0] * 90 + [1] * 10 # 90% Class 0, 10% class 1
y_pred = [0] * 90 + [0] * 10 # All predictions are class 0

print classification_report(y_true, y_pred)

#             precision    recall  f1-score   support
#
#          0       0.90      1.00      0.95        90
#          1       0.00      0.00      0.00        10
#
# avg / total       0.81      0.90      0.85       100

print confusion_matrix(y_true, y_pred)

#[[90  0]
# [10  0]]

print roc_auc_score(y_true, y_pred)

# 0.5

Also, for measuring AUC you should be predicting probabilities using predict_proba instead of predicting labels.
probs = classifier.predict_proba(test_X).T[1]
false_positive_rate, true_positive_rate, thresholds = \
     roc_curve(test_Y, probs)


text:
Q: How to remove the specific class I have removed schema through plugin but few lines of class still appearing on my website header.

A: Just need to remove the below code from the header.php inside the activated theme.
<?php body_class(); ?>


text:
Q: How to prevent crontab from executing simultaneously? I have configured a web scraper, that scrapes a website for live soccer matches being played. The scraper runs every 20 minutes through a cron and takes about 1-2min to scrape each game. Once a game is scraped, its game link is added to a "blacklist" JSON file so it does not get scraped again.
This works fine at times when there are only few games going on simultaneously. On days like Saturday or Sunday there may be so many games simultaneously, that the program cannot catch up anymore and scraping the games takes longer than 30 minutes so that already a new browser opens before the other session has concluded.
Eventually that leads to 7+ browsers being open, some of them even scraping the same game, and the whole thing crashing..
How can I structure this better, so that this cannot occur? Setting the cronjob to less frequently than every 30m is not an option, I would actually like to set it more frequently to every 5m.
I have tried the following crontabs, none of them seem to work in order to actually block the script if the script is already running:
* * * * * /usr/bin/flock -w 0 /var/cron.lock  /usr/bin/python3 /home/pi/Desktop/Oddsportal/oddsarranger_func_v5_rules_live.py >> /home/pi/Desktop/Oddsportal/log.txt 2>&1

*/30 * * * * run-one /usr/bin/python3 /home/pi/Desktop/Oddsportal/oddsarranger_func_v5_rules_live.py

* * * * * root (/usr/bin/pgrep -f /home/pi/Desktop/Oddsportal/oddsarranger_func_v5_rules_live.py || /home/pi/Desktop/Oddsportal/oddsarranger_func_v5_rules_live.py)

What am I missing?