text:
Q: d3 shrinking radar chart shape using attrTween Hi I'm trying to use attrTween for my radar chart.
I made it happen for arc chart so I wanted to apply the same logic to my radar chart but it didn't work out.
can anyone let me know which part I missed?
I would like to shrink the radar chart on 'click'.
the code is as below.
d3.selectAll('.btn').on('click', function(d) {
        let selectedone = d3.select(this).attr('class').split(' ')[1]
        console.log(selectedone);

        d3.select(`.radar${selectedone}`)
            .transition()
            .duration(1000)
            .attrTween('d', shrinkRadar(0))

        function shrinkRadar(target) {

            return function(d) {
                console.log(d)
                let interpolate = d3.interpolate(rscale(d.value), target)

                return function(t) {
                    console.log(d.radius);
                    d.radius = interpolate(t)
                    return radarLine(d)
                }
            }
        }

        // .attrTween('d',shrinkRadar(finalvalue))
    })

Full code in the following link
https://codepen.io/jotnajoa/pen/dypJzmZ

A: Your radar chart's line functions take an array of data to output a path (line and area fill).  You are attempting, though, to operate the attrTween like it's manipulating a single piece of data and not an array.  Take a look at this quick re-write:
function shrinkRadar(target) {
    return function(d) {
        // create an array of interpolators
        // one for each point in the line
        // that run the value from starting to 0
        var interps = d.map( da => d3.interpolate(da.value, target));
        return function(t) {
            // for each point call it's interpolator
            // and re-assign the value
            d.forEach( (da,i) => {
              da.value = interps[i](t);
            });
            // regenerate path with new value
            return radarLine(d)
        }
    }
}

Running code:

let margin = {
  top: 100,
  bottom: 100,
  left: 100,
  right: 100
}

let width = Math.min(700, window.innerWidth - 10) - margin.left - margin.right;
let height = Math.min(width, window.innerHeight - margin.top - margin.bottom - 20);

var data = [
  [ //iPhone
    {
      axis: "Battery Life",
      value: 0.22
    },
    {
      axis: "Brand",
      value: 0.28
    },
    {
      axis: "Contract Cost",
      value: 0.29
    },
    {
      axis: "Design And Quality",
      value: 0.17
    },
    {
      axis: "Have Internet Connectivity",
      value: 0.22
    },
    {
      axis: "Large Screen",
      value: 0.02
    },
    {
      axis: "Price Of Device",
      value: 0.21
    },
    {
      axis: "To Be A Smartphone",
      value: 0.50
    }
  ],
  [ //Samsung
    {
      axis: "Battery Life",
      value: 0.27
    },
    {
      axis: "Brand",
      value: 0.16
    },
    {
      axis: "Contract Cost",
      value: 0.35
    },
    {
      axis: "Design And Quality",
      value: 0.13
    },
    {
      axis: "Have Internet Connectivity",
      value: 0.20
    },
    {
      axis: "Large Screen",
      value: 0.13
    },
    {
      axis: "Price Of Device",
      value: 0.35
    },
    {
      axis: "To Be A Smartphone",
      value: 0.38
    }
  ],
  [ //Nokia Smartphone
    {
      axis: "Battery Life",
      value: 0.26
    },
    {
      axis: "Brand",
      value: 0.10
    },
    {
      axis: "Contract Cost",
      value: 0.30
    },
    {
      axis: "Design And Quality",
      value: 0.14
    },
    {
      axis: "Have Internet Connectivity",
      value: 0.22
    },
    {
      axis: "Large Screen",
      value: 0.04
    },
    {
      axis: "Price Of Device",
      value: 0.41
    },
    {
      axis: "To Be A Smartphone",
      value: 0.30
    }
  ]
];

var color = d3.scaleOrdinal()
  .range(['#6678D9', '#61F06C', '#FF36AA'])

var radarChartOptions = {
  w: width,
  h: height,
  margin: margin,
  maxValue: 0.5,
  levels: 5,
  roundStrokes: true,
  color: color
};

//   blue, green pink inorder

RadarChart('.radarChart', data, radarChartOptions)

function RadarChart(id, data, options) {

  let cfg = {
    w: 600,
    h: 600,
    margin: {
      top: 20,
      right: 20,
      bottom: 20,
      left: 20
    },
    levels: 3,
    maxValue: 0,
    labelFactor: 1.25,
    wrapWidth: 60,
    opacityArea: 0.35,
    dotRadius: 4,
    opacityCircles: 0.1,
    strokeWidth: 2,
    roundStroke: false,
    color: ['#6678D9', '#61F06C', '#FF36AA']
  }

  if ('undefined' !== typeof options) {
    for (var i in options) {
      if ('undefined' !== typeof options[i]) {
        cfg[i] = options[i];
      }
    } //for i
  } //if

  //   결론적으로 options에 들어가있는 녀석과 함수에있는 녀석을 매치시키는것
  var maxValue =

    // Math.max(cfg.maxValue,

    d3.max(data,
      (i) => d3.max(
        i.map((o) => o.value)
        // 벨류로 이루어진 어레이를 만들고, 그 어레이에서 최대값을 출력해낸다.
      )
    )
  // )

  var allAxis = data[0].map((d) => {
    return d.axis
  })

  var total = allAxis.length,
    radius = Math.min(cfg.w / 2, cfg.h / 2),
    Format = d3.format('%'),
    angleSlice = Math.PI * 2 / total

  var rscale = d3.scaleLinear()
    .range([0, radius])
    .domain([0, maxValue])

  d3.select(id).select('svg').remove()

  var svg = d3.select(id).append('svg')
    .attr('width', cfg.w + cfg.margin.left + cfg.margin.right)
    .attr('height', cfg.h + cfg.margin.top + cfg.margin.bottom)
    .attr('class',
      'radar' + id);

  var g = svg.append('g').attr('transform', `translate(${cfg.w/2+cfg.margin.left},${cfg.h/2+cfg.margin.top})`)

  var filter = g.append('defs').append('filter').attr('id', 'glow')
  var feGaussianBlur = filter.append('feGaussianBlur').attr('stdDeviation', '2.5')
    .attr('result', 'coloredBlur')
  var feMerge = filter.append('feMerge')
  var feMergeNode1 = feMerge.append('feMergeNode').attr('in', 'coloredBlur')
  var feMergeNode2 = feMerge.append('feMergeNode').attr('in', 'SourceGraphic')

  var axisGrid = g.append('g').attr('class', 'axisWrapper')

  axisGrid.selectAll('.levels').data(
      d3.range(1, (cfg.levels + 1))
    )
    .join('circle')
    .attr('class', 'gridCircle')
    .attr('r', (d) => {
      return radius / cfg.levels * d
    })
    .style('fill', '#CDCDCD')
    .style('stroke', '#CDCDCD')
    .style('fill-opacity', cfg.opacityCircles)
    .style('filter', 'url(#glow)')

  axisGrid.selectAll('.axisLabel')
    .data(d3.range(1, cfg.levels + 1))
    .join('text')
    .attr('class', 'axisLabel')
    .attr('x', 4)
    .attr('y', (d) => {
      return -d * radius / cfg.levels
    })
    .attr('dy', '0.4em')
    .style('font-size', '10px')
    .attr('fill', '#737373')
    .text((d, i) => {
      return Format(maxValue * d / cfg.levels)
    })

  var axis = axisGrid.selectAll('.axis')
    .data(allAxis)
    .join('g')
    .attr('class', 'axis')

  axis.append('line')
    .attr('x1', 0)
    .attr('y1', 0)
    .attr("x2", function(d, i) {
      return rscale(maxValue * 1.1) * Math.cos(angleSlice * i - Math.PI / 2);
    })
    .attr("y2", function(d, i) {
      return rscale(maxValue * 1.1) * Math.sin(angleSlice * i - Math.PI / 2);
    })
    .attr("class", "line")
    .style("stroke", "white")
    .style("stroke-width", "2px");

  axis.append("text")
    .attr("class", "legend")
    .style("font-size", "11px")
    .attr("text-anchor", "middle")
    .attr("dy", "0.35em")
    .attr("x", function(d, i) {
      return rscale(maxValue * cfg.labelFactor) * Math.cos(angleSlice * i - Math.PI / 2);
    })
    .attr("y", function(d, i) {
      return rscale(maxValue * cfg.labelFactor) * Math.sin(angleSlice * i - Math.PI / 2);
    })
    .text(function(d) {
      return d
    })
    .call(wrap, cfg.wrapWidth)
  // .call(testfunc, 'testString')

  var radarLine = d3.radialLine()
    .radius(function(d) {

      return rscale(d.value)
    })
    .angle(function(d, i, t) {

      return i * angleSlice
    })
    .curve(d3.curveCardinalClosed)

  // if (cfg.roundStrokes) {
  //     radarLine.interpolate("cardinal-closed");
  // }

  const blobWrapper = g.selectAll(".radarWrapper")
    .data(data)
    .join('g')
    .attr("class", "radarWrapper");

  blobWrapper
    .append("path")
    .attr("class", "radarArea")
    .attr("d", function(d) {

      return radarLine(d)

    })
    .attr('class', function(d, i) {
      return `radar${i}`
    })
    .style("fill", (d, i) => cfg.color(i))
    .style("fill-opacity", cfg.opacityArea)
    .on('mouseover', function(d, i) {
      d3.selectAll('.radarArea').transition().duration(200)
        .style('fill-opacity', 0.1)
      d3.select(this).transition().duration(200).style('fill-opacity', cfg.opacityArea);
    })
    .on('mouseout', function() {
      //Bring back all blobs
      d3.selectAll(".radarArea")
        .transition().duration(200)
        .style("fill-opacity", cfg.opacityArea);
    });

  blobWrapper.append('path')
    .attr('class', 'radarStroke')
    .attr('d', radarLine)
    .attr('class', function(d, i) {
      return `radarStroke${i}`
    })
    .style('stroke', (d, i) => cfg.color(i))
    .style('stroke-width', cfg.strokeWidth + 'px')
    .style('fill', 'none')
    .style('filter', 'url(#glow)')

  let round = 0;

  blobWrapper.selectAll(".radarCircle")
    .data(data)
    .data(function(d) {
      return d
    })
    .join('circle')
    .attr("class", "radarCircle")
    .attr("r", cfg.dotRadius)
    .attr("cx", function(d, i) {
      return rscale(d.value) * Math.cos(angleSlice * i - Math.PI / 2);
    })
    .attr("cy", function(d, i) {
      return rscale(d.value) * Math.sin(angleSlice * i - Math.PI / 2);
    })
    .style("fill", function(d, i, j) {
      if (i == 0) {
        round = round + 1;;
      }
      return cfg.color(round - 1);
    })
    .style("fill-opacity", 0.8);

  var blobCircleWrapper = g.selectAll('.radarCircleWrapper')
    .data(data)
    .join('g')
    .attr('class', 'radarCircleWrapper')

  blobCircleWrapper.selectAll('circles').data(function(d) {
      return d
    })
    .join('circle').attr('class', 'invisibleCircles')
    .attr('r', cfg.dotRadius * 1.5)
    .attr("cx", function(d, i) {
      return rscale(d.value) * Math.cos(angleSlice * i - Math.PI / 2);
    })
    .attr("cy", function(d, i) {
      return rscale(d.value) * Math.sin(angleSlice * i - Math.PI / 2);
    })
    .style('fill', 'none')
    .style('pointer-events', 'all')
    .on('mouseover', function(d, i) {
      newX = parseFloat(d3.select(this).attr('cx')) - 10;
      newY = parseFloat(d3.select(this).attr('cy')) - 10;

      tooltip
        .attr('x', newX)
        .attr('y', newY)
        .text(Format(d.value))
        .transition().duration(200)
        .style('opacity', 1);

    })
    .on("mouseout", function() {
      tooltip.transition().duration(200)
        .style("opacity", 0);
    });

  var tooltip = g.append("text")
    .attr("class", "tooltip")
    .style("opacity", 0);

  d3.selectAll('.btn').on('click', function(d) {
    let selectedone = d3.select(this).attr('class').split(' ')[1]
    console.log(selectedone);

    d3.select(`.radar${selectedone}`)
      .transition()
      .duration(1000)
      .attrTween('d', shrinkRadar(0))

    function shrinkRadar(target) {

      return function(d) {
        var interps = d.map(da => d3.interpolate(da.value, target));
        return function(t) {
          d.forEach((da, i) => {
            da.value = interps[i](t);
          });
          return radarLine(d)
        }
      }
    }

    // .attrTween('d',shrinkRadar(finalvalue))
  })

}

function wrap(text, width) {

  text.each(function() {
    var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1.4, // ems
      y = text.attr("y"),
      x = text.attr("x"),
      dy = parseFloat(text.attr("dy")),
      tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");

    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}
.radarChart {
    width: 1000px;
    height: 500px;
}

.buttonwrap {
    margin-left: 200px;
    text-align: left;
    /* border: dashed grey 0.5px; */
}

.btn {
    text-align: center;
    display: inline-block;
    width: 100px;
    height: 20px;
    border: solid 1px navy;
    border-radius: 5px;
    margin: auto;
    cursor: pointer;
}

<svg class="radarChart"></svg>

Show 1

Show 2

show 3


text:
Q: MySQL: Error in query with UPDATE and JOIN, when ORDER BY is used I have a problem, where I can't find help. When I delete the ORDER BY and LIMIT addtions, then this query works fine. But with them it causes an "Call to a member function execute() on a non-object"-Error. Using LEFT or INNER JOIN makes no difference.
$sql = "UPDATE tasks JOIN service
ON tasks_account_id = service_id
SET `tasks_status` = 'prog' ,
tasks_user = '".$user."'
WHERE `tasks_status` = 'free' AND `service_besetzt` = '0'
ORDER BY `tasks_client_date` ASC, `tasks_id` ASC
LIMIT ".$limit."";
$result = $db->prepare( $sql );
$result->execute();

Has someone an idea?
Thanks!

A: The issue is that you are using multiple-table UPDATE and ORDER BY and LIMIT clauses cannot be used with it; however they work nice with a single-table UPDATE. Please refer para 2 on http://dev.mysql.com/doc/refman/5.0/en/update.html.

A: $db->prepare($sql) is returning null. :)
Maybe the prepare method cannot handle LIMIT/ORDER BY... which makes sense as you cannot order an UPDATE query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which adjective does 'pills', 'powder' and 'liquid' belong to? My native language is Spanish and today I was wondering how do you say 'presentación' referring to the type of presentation the medicine come from. For example, if you go to the drug store to buy a medicine you can ask if you have it in injectable form or in pills. How can you ask in which presentations the medicine came from? It is ok to say 'presentation' as a literal translation from the Spanish or it have a different word to refer to it?

A: The word used for this in English is form. "Presentation" is a false cognate.
The Wikipedia page on the concept here used the longer term "dosage form," but in practice we wouldn't use such a specific phrase unless we had to disambiguate with other meanings of the word.


text:
Q: jquery-validation on Meteor I'm trying jquery-validation package according to the site
https://atmospherejs.com/themeteorchef/jquery-validation

*

*Make test project. (meteor create test)

*Copy & Pasete the codes to my files. (test.js , test.html)

*Add the package. (meteor add themeteorchef:jquery-validation)

*Run. (meteor run)

And I got an error message in console like below.

"Uncaught TypeError: Template.exampleForm.rendered is not a function"

Could you tell me why the codes doesn't work ?
Actually I add a code "console.log($("#validation-example"))" and search 'validate' method in console, but I couldn't find it in the object "$("#validation-example")".

A: Here is how to use onRendered as of meteor v1.1 (instead of the deprecated rendered property):
Template.exampleForm.onRendered(function () {
  // place your code here
  console.log("exampleForm is rendered");
});

For history purposes, here is the old version's way. Notice how we assign a function to it and not call rendered():
Template.exampleForm.rendered = function () {
  // place your code here
  console.log("exampleForm is rendered");
};


text:
Q: eclipse projects build path is driving me nuts I have this number of apps/libraries which I set up in different projects.  Development and refactorings are mostly simultaneous so I don't want to "build library, deploy to lib folder of depending projects, rebuild depending projects".
At the leaf of the dependency tree is CLIENT.  I only have the JRE library in Libraries->Module Path.  Builds just fine.  (CLIENT has a module.info that exports its packages.)
One depending app is DBROWSER.  Requires only JRE+CLIENT, so I have CLIENT in Projects->Module Path and JRE in Libraries->Module Path.  Builds fine.  DBROWSER has a module.info that requires what it needs, and exports nothing (it's a main GUI app.)
Other depending app is SERVER.  Requires only JRE+CLIENT, so I have CLIENT in Projects->Module Path and JRE in Libraries->Module Path.  Refuses to build.  Error message is "The project was not built since its build path is incomplete. Cannot find the class file for java.util.Set. Fix the build path then try building this project".  I've tried cleaning dozens of times, only results in seemingly random shifting around to other error messages, mostly "could not be resolved" and "indirectly referenced from existing .class files".
What am I missing ?
EDIT
I also found this
"It sounds like this has been a known issue (Bug 67414)that was resolved in 3.0 ... someone has commented that it's occurring for them in 3.4 as well.
In the mean time, the work around is to remove the JRE System Library from the project and then add it back again."
at
Eclipse error: indirectly referenced from required .class files?
Didn't work either.

A: From the symptom I'd guess that this is https://bugs.eclipse.org/547181 which is fixed in current milestone / integration builds, so please try installing 2019-09 M2


text:
Q: Bootstrap 4 row layout is not responsive I'm creating an html template for a news article layout using Bootstrap 4, on the MEAN stack, but that shouldn't matter...
The requirements are for this general layout, one 'featured' article in its own column, and 8 other articles on two rows in another column. When viewed on smaller screens or mobile, the other articles should tuck under the first and under each other as necessary:
Desktop:
-----------------------------------------------------------------
                 | Article 1 | Article 2 | Article 3 | Article 4 |
Article 0        |                                               |
                 | Article 5 | Article 6 | Article 7 | Article 8 |
-----------------------------------------------------------------

Mobile:
-----------------
Article 0
-----------------
Article 1
-----------------
Article 2
-----------------
.
.

This is the what I'm using to achieve the layout:

          Article 0

            Article 1

            Article 2

            Article 3

            Article 4

            Article 5

            Article 6

            Article 7

            Article 8

This works great on desktop, but on mobile every element is jammed together on a single row. I would like them all to fall into a single column when the screen size is small. I suspect the outer <div class="row" is the reason for the mobile behavior, but on desktop I can't get the Article 0 to stay on the same row with the others without using that. I know I'm probably missing something fundamental about Bootstrap, so there must be a better way of doing this.
How can I make this layout, which works great on the desktop, render properly on mobile? Thanks.

A: If you only specify class="col-3" then this will be for all screen sizes. If you want to override this for a specific size you have to overwrite it with a css class like:
col-sm-3
Here you can have the choice between -sm, -md, -lg and -xl, depending on which screensize you want to affect.
So yours would be something like this:

          Article 0

            Article 1

            Article 2

            Article 3

            Article 4

            Article 5

            Article 6

            Article 7

            Article 8

See also bootstraps grid documentation for further info

A: When you set
 you're telling bootstrap to make that div take up three columns on every breakpoint, even the smallest screens. To resolve that, tell Bootstrap to make that div take up the full width on small screens with col-12 and only three columns on medium sized screens and up with col-md-3. E.g.

          Article 0

            Article 1

            Article 2

            Article 3

            Article 4

            Article 5

            Article 6

            Article 7

            Article 8

Bootply example

A: Try using col-md-* instead of col-*. More info

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      Article 0

        Article 1

        Article 2

        Article 3

        Article 4

        Article 5

        Article 6

        Article 7

        Article 8

A: I suggest you use the command col- *
I made an example by aligning the content in the middle as in the demo

.flex{
  display: flex;
}

.align-middle{
    margin-top: auto;
    margin-bottom: auto;
}

div.borda{
  border: 1px solid red;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      Article 0

        Article 1

        Article 2

        Article 3

        Article 4

        Article 5

        Article 6

        Article 7

        Article 8


text:
Q: cannot get scrollspy to work I am hving some issues getting bootstrap's scrollspy to work. The output page is generating fine without any javascript errors.
But when scrolling I just cant get the CSS class to apply the active.
Below is the JSFiddle I've setup.
Thanks
http://jsfiddle.net/475sT/15/

One

Two

Three

One

Two

Three

A: Call the scrollspy via JavaScript:
$('#main-navigation').scrollspy()

By http://twitter.github.com/bootstrap/javascript.html#scrollspy


text:
Q: How does Axiom of Choice imply Axiom of Dependent Choice? Axiom of Choice:
Given a collection $A$ of nonempty sets, there exists a function

$$c: A \to \bigcup_{A_{i} \in A}A_{i}$$

such that $c(A_{i})\in A_{i}$ for all $A_{i} \in A$.
Axiom of Dependent Choice:
Given a nonempty set $A$ and a binary relation $\mathcal{R}$ on $A$ such that for all $a\in A$, there exists $b\in A$ such that $a\mathcal{R}b$. There exists a sequence

$$(a_{n})_{n\in \mathbb{N}}$$

such that $a_{n}\mathcal{R}a_{n+1}$ for all $n \in \mathbb{N}$.
Here is my incomplete proof that Axiom of Choice implies Axiom of Dependent Choice:

For $a\in A$, let $R(a)=\{b\in A\mid a\mathcal{R}b\}\implies R(a)\neq\varnothing$ for all $a\in A$.
Using Axiom of Choice for the indexed family of sets $(R(a))_{a\in A}$, there exists a mapping

$$f:A\to A$$

such that $$\forall a\in A:f(a)\in R(a)$$

$\text{That is }\forall a\in A:a\mathcal{R}f(a)$. Let $B=\{(a,f(a))\mid a\in A\}$

I don't know how to proceed to prove the existence of the required sequence $(a_{n})_{n\in \mathbb{N}}$ from set $B$.
Please help me complete my proof! Many thanks for you!

A: You're basically done already: pick some $a\in A$ and consider the sequence $$a, f(a),f(f(a)), f(f(f(a))), ...$$ The $f$ that choice provides us is exactly the "strategy" we use to build the desired sequence.

A: Once you have $f$, use the assumption that $A$ is nonempty to choose $x \in A$.  Now, you can define a sequence recursively by $a_0 = x$, $a_{n+1} = f(a_n)$.  (So for example, $a_1 = f(x)$, $a_2 = f(f(x))$, $a_3 = f(f(f(x)))$, etc.)

A: I think you're almost there: now define
$$ a_0 := a, a_n := f^n(a)$$
for some $a \in A$.


text:
Q: alternative for iterative COPY with LIMIT and OFFSET in POSTGRESQL what i am doing right now
i have a database table with 1000 rows
limit, offset and somefile are variables
i iterate and in every iteration i do:
recalculate offset by adding the old value to it
and copy some rows to a csv file
COPY (SELECT somevalue1, somevalue2, avg(somevalue3) as avg FROM table
GROUP BY somevalue1 ORDER BY somevalue2 LIMIT Limit OFFSET Offset ) TO \'
SOMEFILE \' DELIMITER AS \' \' CSV HEADER

is there a way to copy the rows to different csv files without an iteration within one SQL command?

A: In 9.3 and above, you can COPY ... TO PROGRAM .... The program can be a script that filters the input and changes the output file on the fly. A simple tool like awk is suitable for this. It'll only work if the knowledge of the file name can be obtained using only the input data, without access to other parts of the database.
It is unfortunately not possible to COPY from a cursor, as that would be a good solution to your problem, allowing you to run multiple COPY commands with different destinations without having to use LIMIT and OFFSET. Unfortunately the FETCH command is not legal within a COPY query block. You could work around this with a PL/PgSQL function that fetched from the cursor and returned the results, but that's getting cumbersome fast.


text:
Q: opencv_traincascade.exe error, "Please empty the data folder"? I have been successful at training a classifier before but today I started getting errors.
Problem:
When I try to train a classifier using opencv_traincascade.exe I get the following message:
"Training parameters are loaded from the parameter file in data folder!
Please empty the data folder if you want to use your own set of parameters."
The trainer then stops midway in stage 0 with the following message:
===== TRAINING 0-stage =====
BEGIN
POS count : consumed   2 : 2
Train dataset for temp stage can not be filled. Branch training terminated.
Cascade classifier can't be trained. Check the used training parameters.
Here is how I got to the problem:
I had a parameters file inside the classifier folder where my trainer would usually train classifiers to. I forgot to delete this parameters file before running the traincascade.exe file. Even though I erased the parameter file I still got the same error.
Thanks for helping.

A: I solved it!
I downloaded opencv and all other required programs on another computer and tried running train classifier on another set of pictures. After I verified that it worked in the other computer I copied all files back to my computer and used them.


text:
Q: unable to use VlookUp on excel I am trying to do a vlook up here but unable to do it can some one please help me
Here is a Image on my problem if some one can help me fix this
it will be much appreciated thanks
EXCEL - IMAGE

A: Because of the FALSE parameter in your formula, excel looks for the exact lookup value. When it can't find it, it will return N/A. Just delete FALSE or replace it by TRUE, and the formula will look for the closest value that is smaller than the look-up value. The values in the first column of the look-up range, must be in ascending order.

A: Yes, you have found an incorrect formula. Let's move past that. =IFERROR(INDEX(your_array_guy, MATCH(value_in_question,array_you_look_up,false),2),INDEX(your_array_guy, MATCH(value_in_question,array_you_look_up,true),2)  -----You should trim your cells because your data isn't clean? Maybe provide the formula instead of an image? Asking questions correctly and politely will get you further


text:
Q: How to use JavaScript to display HTML? Okay, so basically I am using a JavaScript script to detect whether ad blocker is enabled on the visitor's browser or not. I successfully got it to popup an alert box, but that was just a basic test. Now, I'd like to replace the ad slot with an image the size of the ad that says my message about how it would be nice if they could allow ads. How would I achieve this using JavaScript?
Here is my code:

Any help is appreciated!

A:

<img id="myTopAd" src="sss.png" alt="TEXT"
<input type="button" onclick="changeLink()" value="Change link">

try this.

A: you can set a background-image to the ads parent element
function TestPage() {
  if ($('.myTopAd').height() == 0){
    $('.myTopAd-parent').css({background: "url(please.jpg) no-repeat 50% 50%", backgorundSize: "cover"});
  }
}

$(function(){ // DOM is now ready
   TestPage();
});

Or do the similar appending an image:
$('.myTopAd-parent').append("");

A: Inside your if, you can do something like this:
$('.myTopAd').prepend($('',{id:'ID-OF-IMG',src:'YOUR-IMAGE.jpg'}));

Or
$(".myTopAd").prepend("");

In src, put the path of your image.
This can be done on several ways, these are just some of them.
Prepend jQuery


text:
Q: mongodb facet with root Is there a way to push root documents to specific field on $facet without $group ? For example,
db.artwork.aggregate( [
  {
    $facet: {
      "categorizedByTags": [
        { $unwind: "$tags" },
        { $sortByCount: "$tags" }
      ],
      "items": [{$push: "$$ROOT"}] // I want to push all root document to `items`.
    }
  }])

A: Yes, just use an empty $match, like so:
db.artwork.aggregate( [
  {
    $facet: {
      "categorizedByTags": [
        { $unwind: "$tags" },
        { $sortByCount: "$tags" }
      ],
      "items": [{$match: {}}]
    }
  }])

A: You can use like this:
db.artwork.aggregate( [
{
 $facet: {
   items: [ { $match: {} } ],
  }
 }
])


text:
Q: WPF ComboBox, setting the background color of current item In my WPF application I need to set the background color of my combobox.
Example
As you can see in the file attached, I set thw background color to blue as (in code behind):
_combobox.Background = Brushes.DodgerBlue;

I have also set the triggers in order to handle the event while selecting the items (set style for both ComboBox and ComboBoxItem:
<Style x:Key="CmbStyleItem" TargetType="{x:Type ComboBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                <Border x:Name="gd" Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=Background}" Padding="4,6,2,2">
                    <ContentPresenter />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="ComboBoxItem.IsMouseOver" Value="True">
                        <Setter TargetName="gd" Property="Background" Value="#E7E2E2" />
                        <Setter TargetName="gd" Property="TextElement.Foreground" Value="#000000"/>
                    </Trigger>
                    <Trigger Property="ComboBoxItem.IsSelected" Value="True">
                        <Setter TargetName="gd" Property="Background" Value="#D6D6D6" />
                        <Setter TargetName="gd" Property="TextElement.Foreground" Value="#000000" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Width" Value="Auto" />
    <Setter Property="Height" Value="27" />
    <Setter Property="Padding" Value="4,6,2,2" />
    <Setter Property="FontFamily" Value="{StaticResource fntConsole}" />
    <Setter Property="Typography.Capitals" Value="AllSmallCaps"/>
    <Setter Property="FontSize" Value="13.55" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="ItemContainerStyle" Value="{DynamicResource CmbStyleItem}"/>
</Style>

Basically I'm not able to set the background color of selected item, for example in the attachment, the item "Tav1800x650x18". Any hints?

A: if i understant your problem, you want to modify the background color of combobox when no selecteditem :
so you have this line <Setter Property="Background" Value="Transparent" />
which gives the default background color
you have to set Value with the color you want.
Or i missunderstand you.....

A: Replace:
Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=Background}"
To: Background="{TemplateBinding Background}"


text:
Q: how do i check and uncheck input checkbox using immutable js I am trying to learn immutablejs with reactjs. I have a list of items with checkbox for each item. I want the functionality like when checkbox is clicked a checkmark should be shown and also some text like checked. I tried but when i check the first checkbox, second checkbox gets checked.
Here is my code
class AddRemoveCheckbox extends React.Component{
  constructor(){
    super();
    this.state = {
      checked: Immutable.List([])
    }
  }

  handleChange(e, key) {
    console.log('key', key);
    const { checked } = this.state;
    if (e.target.checked) {
      this.setState({
        checked: checked.push(key)
      })
    } else {
      this.setState({
        checked: checked.pop(key)
      })
    }
  }

  render() {
    console.log('items');
    const { checked } = this.state;
    console.log('checked', checked.has('0'));
    const items = this.props.items.map((item,key) => {
      return (

        <input
          type="checkbox"
          checked={checked.has(key)}
          onChange={(e)=>this.handleChange(e, key)}
        />
        {item}

        )
    })
    return (

      Items:
      {items}
      { checked.has('0') ? 'Checked' : 'Unchecked'}

    );
  }
}

ReactDOM.render(<AddRemoveCheckbox items={['item1', 'item2'] } />, document.getElementById('root'));

I have this code on jsbin too
http://jsbin.com/fusoxos/edit?js,console,output

A: I would recommend using an Immutable Set instead of List. This lets you deal purely with values instead of messing with indices.
Your original issue was that you were poping the last item from the list, no matter what it was. You were also checking indices of the list with has instead of values.
constructor:
this.state = {
  checked: Immutable.Set()
}

handleChange:
if (e.target.checked) {
  this.setState({
    checked: checked.add(key)
  })
} else {
  this.setState({
    checked: checked.remove(key)
  })
}

render:
checked={checked.includes(key)}

and
  { checked.contains(0) ? 'Checked' : 'Unchecked'}

I forked your JSBin.


text:
Q: Android Espresso: How to match text on custom spinner selected item layout? I have spinner with custom layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="60dp"
        android:layout_height="60dp" />
    <TextView
        android:id="@+id/tv_text"
        android:textColor="#FFFFFF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

And I need to check if value in R.id.tv_text of selected item match with specific text.
Is it possible to do this without implement custom Matcher class ?
My simple test:
@SmallTest
public class CategoryTest {

    public static final String TEXT_TO_MATCH = "Spinner item text";

    @Test
    public void testCreate() {
        ...
        onView(withId(R.id.spn_tt)).perform(click()); // open spinner
        onView(allOf(withId(R.id.tv_text), withText(TEXT_TO_MATCH))).perform(click()); // find item by text and click
        onView(withId(R.id.spn_tt)).check(matches(withTextInSpinnerSelectedView(TEXT_TO_MATCH))); // check if right item selected by text
    }

}

A: I have archieved that using a custom matcher too. But i have used a less verbose matcher, maybe it helps someone:
 onView(withId(R.id.spinner)).perform(click());
 onData(allOf(is(instanceOf(YourCustomClass.class)), withMyValue("Open"))).perform(click());

public static <T> Matcher<T> withMyValue(final String name) {
    return new BaseMatcher<T>() {
        @Override
        public boolean matches(Object item) {
            return item.toString().equals(name);
        }

        @Override
        public void describeTo(Description description) {

        }
    };
}

Then you must override toString() method on your custom class.

A: Really simple solution that worked out for me .....without using matcher
for CustomSpinner
onView(withId(R.id.custom_spinner)).perform(click());
onData(anything()).atPosition(1).perform(click());
onView(withId(R.id.custom_spinner)).check(matches(withSpinnerText(containsString("yourstring"))));

A: I haven't found more simple way than create custom matcher that looks for specific text in any TextView (or their heirs) of Spinner selected item. There is a my custom matcher: https://gist.github.com/igorokr/5f3db37f0b9eb8b2feae


text:
Q: python ziping lists of single element or tuples into list of tuples Assuming I have a colection of lists of the same size (same number of elements), where the elements are single elements (strings, numbers) or tuples:
a = ['AA', 'BB', 'CC']
b = [7,8,9]
d = [('TT', 'ZZ'),('UU', 'VV'),('JJ','KK')]
e = [('mm', 'nn'), ('bb', 'vv'), ('uu', 'oo')]

I would like a way of combining whatever two lists (ideally whatever number of lists) in a way that the result is a list of tuples
# none of this works:
print(list(zip(a,b))) # this ONLY works for the case in which a & b have single elements, not tuples
print(list(zip(b,*d)))
print(list(zip(*d,*e)))

Desired result:
pseudo code:
combination of a,b = [('AA', 7), ('BB', 8), ('CC', 9)]
combination of a,d = [('AA','TT', 'ZZ'),('BB', 'UU', 'VV'),('CC','JJ','KK')]
combination of d,e = [('TT', 'ZZ','mm', 'nn'),('UU', 'VV','bb', 'vv'),('JJ','KK','uu', 'oo')]

basically the method would get the elements of the input lists treat them as tuples (even if being of only one element) and add up all the values of the tuples of the corresponding same position.

A: Just flatten the output of zip, as below:
from collections.abc import Iterable

a = ['AA', 'BB', 'CC']
b = [7, 8, 9]
d = [('TT', 'ZZ'), ('UU', 'VV'), ('JJ', 'KK')]
e = [('mm', 'nn'), ('bb', 'vv'), ('uu', 'oo')]

def flatten(*e):
    for ei in e:
        yield from (ei,) if not (isinstance(ei, Iterable) or isinstance(ei, str)) else ei

print([list(flatten(ei)) for ei in zip(a, b)])
print([list(flatten(ei)) for ei in zip(a, d)])
print([list(flatten(ei)) for ei in zip(d, e)])

Output
[['AA', 7], ['BB', 8], ['CC', 9]]
[['AA', 'TT', 'ZZ'], ['BB', 'UU', 'VV'], ['CC', 'JJ', 'KK']]
[['TT', 'ZZ', 'mm', 'nn'], ['UU', 'VV', 'bb', 'vv'], ['JJ', 'KK', 'uu', 'oo']]

A: Conversion to a tuple wrt. string is cumbersome in python, you have to do it like this:
def to_tuple(s):
    if isinstance(s, str):
        return s,
    try:
        return tuple(s)
    except TypeError:
        return s,

Once this is done, the rest is easy:
a_plus_d = [to_tuple(x) + to_tuple(y)
            for x, y in zip(a, d)]

A: def foo(x, y):
    x = [x] if not isinstance(x, (tuple, list)) else x
    y = [y] if not isinstance(y, (tuple, list)) else y
    return [el for item in [x, y] for el in item]

[tuple(foo(el1, el2)) for el1, el2 in list(zip(a, d))]
# [('AA', 'TT', 'ZZ'), ('BB', 'UU', 'VV'), ('CC', 'JJ', 'KK')]

A: Another short approach using itertools.chain method:
import itertools

def combine_lists(*lists):
    return list(tuple(itertools.chain(*[i if isinstance(i, (list, tuple)) else (i,) for i in items]))
                for items in zip(*lists))

print(combine_lists(a, b, e))  # [('AA', 7, 'mm', 'nn'), ('BB', 8, 'bb', 'vv'), ('CC', 9, 'uu', 'oo')]


text:
Q: Facebook Error: (#100) The specified scheduled publish time is invalid I'm building a platform to create and organise Social Media posts and publish them to Facebook via Facebook Graph API. I have set up the logic to get the required access tokens and immediately publishing posts to a Facebook page works perfectly fine. However, if I try to schedule the posts I always get the error
"(#100) The specified scheduled publish time is invalid".
I use a POST request to https://graph.facebook.com/page_id/feed to query Facebook Graph API with the following params
access_token=...
message=Test
published=false
scheduled_publish_time=time

where I calculate the UNIX timestamp by
const minutes = 15;
const time = new Date().getTime() + minutes * 60 * 1000;

Given the fact that I schedule the post 15 minutes in the feature, I assume that I have taken all necessary requirements into account (https://developers.facebook.com/docs/graph-api/using-graph-api/common-scenarios#scheduledposts).
Edit
As pointed out by @04FS you need to give the timestamp in seconds NOT milliseconds. Hence the following solved my problem
const minutes = 15;
const time = Math.round((new Date().getTime() + minutes * 60 * 1000) / 1000);

A: const minutes = 15;
const time = new Date().getTime() + minutes * 60 * 1000;

JavaScript's Date object works in milliseconds, not seconds. Your JS code currently gives a value of around 1558015867708, and that would be the unix timestamp of 07/23/51341 @ 1:28am (UTC)
The API wants a proper unix timestamp in seconds, not milliseconds.


text:
Q: Whenever I try to install ChatterBot using the command pip install ChatterBot, I encounter the following error : I'm getting the following error:
Error: Could not find a version that satisfies the requirement chatterbot (from versions : none)
Error : No matching distribution found for chatterbot

I have a windows 10 , and I have python version 3.8 installed.
Can somebody please give a solution for this?

A: You can try
pip3 install chatterbot

It may not be supported for your version of python


text:
Q: Django App works in local server, but when pushed to heroku it only shows static html Thanks in advance. I am totally new to this and I am following the Django Girls tutorial for a blog app. Please let me know what else I should include to help answer the question!
The website just shows a static header "Django Girls Blog" with a font imported from google, and underneath it shows the post models we have created.  It all works perfectly when run from the local server, but when I deploy it to heroku it only shows the header in times new roman.
There are no errors when I deploy it.
Thanks again!


text:
Q: How to find last 7 working/week days in Oracle SQL? I have a table with dates populated from last 10 years & next 20 years.  I want to calculate if the date is in last 7 working (week) days with reference to today (sysdate) as shown in the sample table below (populate last column IsInLast7WorkingDays).
Assumption: Saturday & Sunday are non-working days.
TODAY       CAL_DATE  ISWEEKDAY   IsInLast7WorkingDays
8/12/2021   8/1/2021      N             N
8/12/2021   8/2/2021      Y             N
8/12/2021   8/3/2021      Y             Y
8/12/2021   8/4/2021      Y             Y
8/12/2021   8/5/2021      Y             Y
8/12/2021   8/6/2021      Y             Y
8/12/2021   8/7/2021      N             N
8/12/2021   8/8/2021      N             N
8/12/2021   8/9/2021      Y             Y
8/12/2021   8/10/2021     Y             Y
8/12/2021   8/11/2021     Y             Y
8/12/2021   8/12/2021     Y             N
8/12/2021   8/13/2021     Y             N
8/12/2021   8/14/2021     N             N
8/12/2021   8/15/2021     N             N
8/12/2021   8/16/2021     Y             N
8/12/2021   8/17/2021     Y             N
8/12/2021   8/18/2021     Y             N
8/12/2021   8/19/2021     Y             N
8/12/2021   8/20/2021     Y             N

TODAY       CAL_DATE  ISWEEKDAY   IsInLast7WorkingDays
8/14/2021   8/1/2021      N             N
8/14/2021   8/2/2021      Y             N
8/14/2021   8/3/2021      Y             N
8/14/2021   8/4/2021      Y             N
8/14/2021   8/5/2021      Y             Y
8/14/2021   8/6/2021      Y             Y
8/14/2021   8/7/2021      N             N
8/14/2021   8/8/2021      N             N
8/14/2021   8/9/2021      Y             Y
8/14/2021   8/10/2021     Y             Y
8/14/2021   8/11/2021     Y             Y
8/14/2021   8/12/2021     Y             Y
8/14/2021   8/13/2021     Y             Y
8/14/2021   8/14/2021     N             N
8/14/2021   8/15/2021     N             N
8/14/2021   8/16/2021     Y             N
8/14/2021   8/17/2021     Y             N
8/14/2021   8/18/2021     Y             N
8/14/2021   8/19/2021     Y             N
8/14/2021   8/20/2021     Y             N

Thanks in advance.
Edit: I guess I should have mentioned that I already have a table populated with dates and "isweekday".  Today is derived from sysdate in the below query.
select b.today, a.cal_date, a.isweekday
from DATE_SRK a, (select trunc(sysdate)+4 today from dual) b
order by a.cal_date;

A: If I understand correctly, you can use row_number() and case logic:
select t.*,
       (case when isweekday = 'N' then 'N'
             when cal_date > today then 'N'
             when row_number() over (partition by isweekday, (case when cal_date > today then 1 else 0 end)
                                     order by cal_date desc
                                    ) <= 7
             then 'Y'
             else 'N'
        end) as IsInLast7WorkingDays
from t;

The trick with row_number() is to only enumerate the rows that are 'Y' and less than or equal to today (the first two case conditions set the other rows to 'N').

A: Problem is the abstraction  of "workingDay" what about holidays?
I dont know of any way to get holidays in a database you would need a predefined table w/ those.
if you limited working day to is "Mon to Fri" then you could use recursive SQL to generate a table expression to get them.

A: Something like this expression might work in a query:
SELECT T_Dates.*,
IIf(Weekday([T_Dates]![TODAY],2)<6
And
IIf([T_Dates]![TODAY]>=DateAdd("d",-9,Now()),1,0)=1,1,0)
AS [Weekday & Last 7 Days]
FROM T_Dates;

In this example, T_Dates is a table with the data you showed earlier.
It will return 1 if the [TODAY] is a weekday within the last 9 days from the date of query run, 0 otherwise.


text:
Q: Automating internet option in IE 9 to open pop ups in new window through code asp or Jscript in asp coded page Please let me know if i can open a pop up window in a new browser instead of a new tab if the ie9 setting is default. My code is in ASP.

this is already present in the code but its not working.
Please help

A: Here is a sample code which might help you
<script type="text/javascript">
window.open('YourPageName.asp','','menubar=1, toolbar=0, scrollbars=1, status=1,resizable=1,width=650, height=500, top=10,left=100');
</script>

copy and paste this code where you want to open the popup window. Replace 'YourPageName' parameter with the name of the page you want to open in popup


text:
Q: Constrained optimization problem I'm having  problems with this assignment:
$$\begin{array}{rl}
\min & x^3 + 2xyz - z^2 \\
\text{subject to} & x^2 + y^2 + z^2 \leq 1 \\
\end{array}$$
Disregarding the constraint, find all points $(x,y,z)$ at which the gradient of the criterion function is zero. What is the criterion value at these points?
Provide an argument why all these points are neither (unconstrained) local minima nor local maxima, but saddle points.
My approach:
I calculated the gradient: $3 x^2+2 y z$; $2 x z$; $2 x y-2 z$
How can I find the values for $x,y$ and $z$ to let the elements be equal to zero?
Any help would be appreciated!

A: From $f_y=2xz=0$ it follows that (a) $x=0$ or (b) $z=0$. In case (a) from $f_z=2(xy-z)=0$ we deduce $z=0$, and $f_x=3x^2+2yz=0$ is then automatically fulfilled, and in case (b) from $f_x=0$ we deduce that $x=0$, and $f_z=0$ is then automatically fulfilled. All in all we conclude that the points $(x,y,z)\in{\mathbb R}^3$ with $\nabla f(x,y,z)=0$ are exactly the points $(0,y,0)$ with $y\in{\mathbb R}$ arbitrary. (These points were already found by superM.) The value of $f$ at such a point is $0$.
Keep $y_0\in{\mathbb R}$ fixed and consider now the straight line $x\ \mapsto\ (x,y_0,0)$ through the point $P_0:=(0,y_0,0)$. The corresponding  pullback of $f$ is given by
$$\phi(x)=f(x,y_0,0)=x^3$$
which indicates that the function $f$ assumes positive as well as negative values in the immediate neighborhood of $P_0$. Therefore $f$ has neither a local minimum nor a local maximum at $P_0$. Whether you want to call $P_0$ a "saddle point" is up to you; in any case the critical points $(0,y,0)$ of $f$  are so-called degenerate critical points (the determinant of the Hessian is $=0$ in these points), as otherwise they would form a discrete set.

A: from the third element in gradient we get z=xy. by substituting this value into the first element we can express y by x and obtain the following values:
x = 0, z = 0, y can have any value in its scope.


text:
Q: translate from PDO to MySQLI after a lot of hours troubleshooting i found that my hoster (hosting2go.nl) does not support PDO::mysql they just dont installd the driver so my Model.php in my MVC framework is screwed. I solved the problems with my database-conection. The problem is that i am completely new to mysqli and justr cant find out how to make my model.php (writen for PDO::mysql) writen for Mysqli (instead of PDO) i hope you guys can help me out...
My code:
|ORIGINAL PDO MODEL.PHP|
class Model
{
    function __construct()
    {
        $this->db = new Database;
        $this->data = $_POST;
    }

public function query( $data = array(), $query){
    try{
            $result = $this -> db -> prepare($query);
            $result->execute($data);
            $result = $result->fetchAll(PDO::FETCH_ASSOC);
            return $result;
    }catch(PDOException $e){
        echo $e;
    }
}

|My Database-connection|
class Database extends mysqli {
    public function __construct() {
        parent::__construct("localhost","root","","bartsite");

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

|This is what i made of my model.php FOR MYSQLI|
class Model
{
    function __construct()
    {
        $this->db = new Database;
        $this->data = $_POST;
    }
    public function query( $data = array(), $query){
        try{
                echo $query;
                $result = $this -> db -> prepare($query);
                $result = $this -> db -> query($data);
                $result->fetch_all();
//$result->execute($data);
//$result = $result->fetchAll(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            echo $e;
        }
    }
}

|usefull part f the controller|
public function index(){
    $data = $this->posts->getAllPosts();
    var_dump($data);
    $this->view->render("posts/index",$data);
    return true;
}

|posts.models.php|
class postsModel extends Model
{
function __construct()
{
    parent::__construct();
}

public function getAllPosts(){
    $result = $this->query(
        array(),
        "SELECT * FROM posts ORDER BY  id DESC"
    );
    return $result;
}

A:
I can't find out how to make my model.php writen for Mysqli

As a matter of fact, you can't do it without a LOT of pain. Mysqli neither have bindValue, not it can return you an array of arbitrary structure.
Nevertheless, your Model class is wrong.

*

*first, for some reason it has $data as first parameter, making you to write it always.

*next, you are catching an exception to echo it out, which is a big no-no

*finally, I hope you are creating only one instance of Model class as well as one of whatever Database class.

So, let me suggest you safeMysql instead, which is built upon mysqli but being more user friendly and safe than PDO.
Say, for postsModel
class postsModel {

    function __construct(safeMysql $db)
    {
        $this->db = $db;
    }

    public function getAllPosts(){
        return $this->db->getAll("SELECT * FROM posts ORDER BY id DESC")
    }
}

$db = new safeMysql();
$model = new postsModel($db);
$posts = $model->getAllPosts();

A: If you have in your mind to change hosting in future i suggest you to implement PDO interface by yourself. After your hoster add PDO or you change hoster you can switch to native PDO painless.
UPD:
Pros:
+ you can test your own PDO implementation to be compatible with canonical PDO
+ so you can easy migrate
Cons:
- a lot of work to do
Possible hack: implement PDO interface partly, only that stuff you really use
UPD-2
you can just get new hosting and forget about this one if it will be more cost-effective to you to do not mess with mysqli_* and other. Also it depends on your code base: there is no problem to change few methods or so, but not a huge cms or stuff like that. So the choice is up to you.
UPD-3
replace try-catch block in Model with this code
echo $query;
$stmnt = $this -> db -> prepare($query);
// bind params to statement from $data here
if (false === $stmnt->execute()) {
    // error
    echo $e;
    return;
}
$result = $stmt->get_result();


text:
Q: WEVTUtil export certain event I want to export only event id 4624 from Security
Code below exports all event from security (i want only 4624);
WEVTUtil query-events Security /rd:true /format:text > %~dp0Logins.txt /q:"<EventID>4624</EventID>"

When all 4624 events exported i want filter only events with:
<Data Name='LogonProcessName'>User32 </Data>

This will be RDP logs with IP, because logs in "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" dont have IP (only username) :( I heard this is because RDP connection is TLS secured...

A: I want to export only Event ID 4624 from Security

WEVTUtil query-events Security /rd:true /format:text > "%~dp0Logins.txt"<EventID>4624</EventID>"

You are using the wrong format for the /q option.
Use the following command line:
wevtutil qe Security "/q:*[System [(EventID=4648)]]" /rd:true /f:text > "%~dp0Logins.txt"

How do I restrict the filter to Event ID 4624 containing User32?

When all 4624 events exported I want filter only events with:
<Data Name='LogonProcessName'>User32 </Data>

Use the following command line:
wevtutil qe Security "/q:*[System [(EventID=4648)]]" /rd:true | findstr User32 >nul && wevtutil qe Security "/q:*[System [(EventID=4648)]]" /f:text /rd:true > "%~dp0Logins.txt"

Code based on the following source link.
Source How to use wevtutil command to get event details if it only comply with specific text or word

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*findstr - Search for strings in files.

*wevutil - Windows Events Command Line Utility.


text:
Q: Custom elements - hide an element before it can render Using custom elements, is it possible to have an element's display set to none (or in any other way) before it renders? Consider that I am using this particular one as a base class for other elements, so applying a global style won't work.
The element is simple
<my-element></my-element>

And it doesn't do much :)
class MyElement extends HTMLElement {}
customElements.define('my-element', MyElement);

But a lot of others extend it
<my-other-element></my-other-element>

class MyOtherElement extends MyElement {}
customElements.define('my-other-element', MyOtherElement);

This is why I could not have a global css rule
my-element {
  display:none;
}

I thought I got smart and added a shadow dom with a <style> and :host style but this just makes any other HTML I've placed inside my elements disappear.
Any ideas?

A: With the :defined pseudo class, which is part of the Web Components spec, you can apply styles whenever the custom element has been successfully defined.
my-element {
  display: none;
}

my-element:defined {
  display: block;
}


text:
Q: Database specific selection of data I have a database and one of tables has the following structure:
recordId, vehicleId, dateOfTireChange, expectedKmBeforeNextChange, tireType

I want to make such a selection from the table that i only get thouse rows that contain the most recent date for each vehicleId.
I tried this approach
SELECT vehicleid,
       Max(dateoftirechange) AS lastChange,
       expectedkmbeforenextchange,
       tiretype
FROM   vehicle_tires
GROUP  BY vehicleid

but it doesn't select the kilometers associated with the most recent date so it does not work.
Any idea how to make this selection?

A: There are several ways to get the desired result.
Correlated scalar subquery...
SELECT vt1.*
  FROM vehicle_tire vt1
 WHERE vt1.recordId = (SELECT vt2.recordId
                         FROM vehicle_tire vt2
                        WHERE vt2.vehicleId = vt1.vehicleId
                        ORDER BY vt2.dateOfTireChange DESC limit 1);

...or derived table...
 SELECT vt2.*
   FROM vehicle_tire vt2
   JOIN (SELECT vt1.vehicleId as vehicleId,
                MAX(vt1.dateOfTireChange) as maxDateOfTireChange
           FROM vehicle_tire vt1
          GROUP BY vt1.vehicleId) dt ON vt2.vehicleId = dt.vehicleId
                                    AND vt2.dateOfTireChange = dt.dateOfTireChange;

...are two that come to mind.
The reason GROUP BY is not correct when applied to the whole table is that any columns you do not GROUP BY and that are also not the subject of aggregate functions MIN() MAX() AVG() COUNT(), etc., are assumed by the server to be columns that you know to be identical in every row of the groups established by the GROUP BY clause.
If, for example, I'm doing a query like this...
SELECT p.id,
       p.full_name,
       p.date_of_birth,
       COUNT(c.id) AS number_of_children
  FROM parent p LEFT JOIN child c ON c.parent_id = p.id
 GROUP BY p.id;

The correct way to write this query would be GROUP BY p.id, p.full_name, p.date_of_birth, because none of those columns are part of the aggregate function COUNT().
The MySQL optimization allows you to exclude those columns that you know have to, by definition, be the same on each group from the GROUP BY, and the server will fill those columns with data from any row in the group.  Which row is not defined.  As you can see, in the example, the parent's full_name would be the same in all rows within a group-by parent.id, and that is a case when this optimization is legitimate.  The justification is that it allows the server to have to handle smaller values (fewer bytes) when executing the grouping... but in a query like yours where the ungrouped columns have different values within each group, you get an invalid result, by design.
The SQL_MODE ONLY_FULL_GROUP_BY disables this optimization.


text:
Q: prevent user from back after session is closed I'm trying to prevent user from back after session is closed. but its not working. any one suggest me how to do this.
In log out action class i wrote this code
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
            response.setDateHeader("Expires", 0);
            mySession.removeAttribute("user_id");
            mySession.invalidate();

            return mapping.findForward(SUCCESS);

so it redirects user to index page. while i'm pressing back button it going back and user is able to see all pages which are already visited.
how to prevent this.
in every jsp page i'm trying like this
       if (session.getAttribute("user_id") == null || session.getAttribute("user_id").equals(""))
          {
                  response.sendRedirect("index.do");
           }
           else
        {
             .........
        }

even though i'm not able to prevent user getting back. when ever user perform any action then only user redirects to index. help me out.

A: Better solution is using Filter, that proccess every request to your application.
http://www.coderanch.com/t/547172/Struts/filters-struts
example of using filter for validation user session.
public void doFilter(final ServletRequest request, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getSession().getAttribute("user_id") == null || req.getSession().getAttribute("user_id").equals("")) {
            HttpServletResponse response = (HttpServletResponse) res;
            response.addHeader("Location", "/SessionTimeoutAction.do");
            response.sendError(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        }

        chain.doFilter(request, res);
    }


text:
Q: Hibernate - could not initialize proxy - no Session I'm using spring-mvc and hibernate session-factory.
@Controller
    |
    ->  @Service (@Transactional)
            |
            -> @Repository

I have 2 entities, User and Address.
User has a List<Address> with FetchType=LAZY.
If I add an Addressobject via user, within a @Controller, I get failed to lazily initialize a collection of role - could not initialize proxy - no Session exception.
But If I do this inside the service layer which is wrapped with @Transactional, operation works nicely.
I found out about hibernate proxies,...etc.
My question is, why @Controller cannot change an entity object which is retried from @Service layer. Because @Controller has no idea whether it is a hibernate proxy or anything else. To the @Controller it is just an object. So why I'm getting an error, if I change an entity object inside the @Controller. This is only happening to entity properties which are marked as FetchType=LAZY.

A: When you choose a property to be lazily loaded, hibernate wraps those around a proxy having the session object in which the parent was fetched.
If you try to access the property after the session scope you will get this error.
Looks like your session is getting created and closed in service layer.
Implement  OpenSessionInView Filter provided by spring, it will close the session after response being send.


text:
Q: cxf-java2ws-plugin generates an input parameter in wsdl for no input parameter method in java I am using cxf-java2ws-plugin version 3.1.12.
The following method, which takes no input params,
    @WebMethod public @WebResult(name = "owner") Collection<Owner>
         getAllOwners();

Results in the following wsdl part:
.......
.......
    <wsdl:operation name="getAllOwners">
       <wsdl:input name="getAllOwners" message="tns:getAllOwners">
       </wsdl:input>
       <wsdl:output name="getAllOwnersResponse"
               message="tns:getAllOwnersResponse">
       </wsdl:output>
    </wsdl:operation>

.......
    <wsdl:message name="getAllOwners">
        <wsdl:part name="parameters" element="tns:getAllOwners">
        </wsdl:part>
    </wsdl:message>

.......
What can be done in order to generate the wsdl correctly (without input params)?


text:
Q: DJI Virtual Stick Controls are not properly applied I am building a drone application that will send flight commands for indoor flight. I am implementing DJI Mobile SDK's Virtual Sticks that are described here.
After experimenting with DJI's Simulator Tutorial found here, I implemented a trimmed-down, non-simulation version for my application. When I tested my application outdoors, the controls work consistently and correctly.
However, when I go indoors, the drone only performs 1 action regardless of the command sent: the drone flies in the direction of its back-left propeller. The drone will always fly in this direction even if the command is only to turn the drone.
Any ideas what could be happening? I'm not sure what code to post since my code works outdoors.
UPDATE #1
Here are my flight controller settings (implemented in Swift):
self.flightController = (DJISDKManager.product() as? DJIAircraft)?.flightController

self.flightController?.rollPitchControlMode = DJIVirtualStickRollPitchControlMode.velocity
self.flightController?.yawControlMode = DJIVirtualStickYawControlMode.angle
self.flightController?.rollPitchCoordinateSystem = DJIVirtualStickFlightCoordinateSystem.body

UPDATE #2
Code to change Yaw (with some hardcoded numbers). Basically is used to make the drone turn completely around.
private var turnTime = 0
private var turnTimer: Timer? = nil

func turn() {
    self.turnTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: (#selector(turnDroneCommand)), userInfo: nil, repeats: true)
}

@objc func turnDroneCommand() {
    self.turnTime += 1

    let data = DJIVirtualStickFlightControlData(pitch: 0, roll: 0, yaw: Float(180), verticalThrottle: 0)

    self.flightController.send(data, withCompletion: { (error) in
        if error != nil {
            // Fire custom error callback
        }
    })

    if self.turnTime >= 7 {
        self.turnTimer?.invalidate()
        self.turnTime = 0
        // Fire custom success callback
    }
}

I've implemented an almost identical method for changing the pitch. As stated perviously, the current outcome is no different for either command.

A: After a long back-and-forth with the devs at DJI, I can now offer a partial solution.
PARTIAL SOLUTION
If you look at the code provided in Update #2 of the question, you'll notice the following lines:
self.turnTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: (#selector(turnDroneCommand)), userInfo: nil, repeats: true)

and
self.turnTime += 1
...
if self.turnTime >= 7 {
    self.turnTimer?.invalidate()
    self.turnTime = 0
    // Fire custom success callback
}

The timeInterval parameter is set to 0.2 seconds. This means the commands are being sent at a frequency of 5Hz for less then 2 seconds. According to the developers at DJI, commands need to be sent at a frequency of 10Hz (or greater, but I have not verified this) for longer then 2 seconds.
OUTSTANDING ISSUE
The Matrice 100 (M100) still "drifts" towards the back left propeller before executing the virtual stick commands. The devs at DJI do not appear to have access to a M100 and cannot test it themselves. Since it appears (based on very, very limited testing) to be a problem unique to the M100, it may not be a problem with the Mobile SDK itself.
I am marking this as the answer in case someone stumbles on the "ignore command" problem with another DJI drone. If a solution for the drifting is found, I will update accordingly.

A: We had a similar problem with  virtual RC on the M100, it's a problem with the M100 firmware not the sdk. we are not using any SDK, we use direct serial commands direct to the the com port onboard  the M100. We abandoned trying to use virtual RC and now send velocity commands which work perfectly.


text:
Q: prestashop v 1.5.6.2 server/domain migration I've a problem with migration my prestashop system from old server & domain to new.
I've copied the full folder tree from old server and have done dump of DB, then pasted that to the new server and import DB to the new one. After that my problem occurs,  after complete those steps, when i call new url, system automatically redirect me to the old domain.
So i've changed in DB inside the table jr_shop_url, parameters domain and  domain_ssl to new ones, it returns me message: "my.domain.com is currently unable to handle this request".
Because of that problem i can't access admin panel either.
Any ideas what else i can do to make it works correctly or what have i done wrong ? :)
P.S. I'm using PrestaShop version 1.5.6.2

A: This problem was solved, it was problem with permissions and folder owner, after changing folder's owner by CHOWN -R user folder_path and setting permissions to 775 it is working now.


text:
Q: go channel deadlock issue I just began to learn golang and not fully understand how deadlock occurs. Here is an example adapted from golang playground tutorial:
 package main

import "fmt"

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case q:= <-quit:
            fmt.Println(q)
            return
        }
    }
}
func pp(c chan int, quit chan int){
   for i := 0; i < 10; i++ {
            fmt.Println(<-c)
        }
        quit <- 0
}

func main() {
    c := make(chan int)
    quit := make(chan int)
   // here it's good, no deadlock
     go pp(c,quit)
     fibonacci(c, quit)
   // but if change the order of above two line:
   // fibonacci(c,quit)
   // go pp(c,quit)
   // it will deadlock
}

Why the order of the two lines above are important?

A: You have two functions, which need to operate concurrently in order for the channel communications to work - one must be receiving at the same time the other is sending. In this case:
 go pp(c,quit)
 fibonacci(c, quit)

You start pp as a goroutine, it starts running, then you call fibonacci, so that both are running, and everything works. If you change it, as you suggested, to:
 fibonacci(c, quit)
 go pp(c,quit)

Then you call fibonacci as a regular function, not as a goroutine, which means the next line will not be executed until fibonacci returns. Because fibonacci is expecting something to be receiving from its channel, it blocks until that happens - which is never, because nothing is reading from it concurrently. Hence your deadlock.
The problem isn't the order of the functions, or channel buffering - the problem is that if you want to run two functions concurrently, whichever one you call first must be run as a goroutine (or both):
 go fibonacci(c, quit)
 pp(c,quit)

Would work fine, because it calls fibonacci concurrently, then calls pp which can run simultaneously. You can see it in action here: https://play.golang.org/p/4o3T0z5n40X
If you were using a WaitGroup, you could even run them both as goroutines and they would run concurrently:
 go fibonacci(c, quit, wg)
 go pp(c,quit, wg)

Though in your case this isn't necessary and adds complexity.

A: Channels make(chan int) has implicit size zero ( ref: https://golang.org/ref/spec#Making_slices_maps_and_channels)
A channel of size zero is unbuffered. A channel of specified size make(chan int, n) is buffered. See
http://golang.org/ref/spec#Send_statements for a discussion on buffered vs. unbuffered
channels. The example at http://play.golang.org/p/VZAiN1V8-P illustrates the difference.
Here, c := make(chan int) is unbuffered.
If change the order of these two line
 go pp(c,quit)
 fibonacci(c, quit)

To
fibonacci(c,quit)
go pp(c,quit)

it will cause program to deadlock. In fibonacci function, look at the select statement.
select {
    case c <- x:
        x, y = y, x+y
    case q:= <-quit:
        fmt.Println(q)
        return
}

select statement will remain blocked until one of the case is fullfilled. As go pp(c,quit) executed after fibonacci(c,quit), so there is no process to clear the channel c or send signal to quit channel. That's why function fibonacci(c,quit) will remain blocked.

A: If you call fibonnaci first it will send the value on the channel but the receiver is not ready. That is the reason behind the deadlock.
Note:

By default, sends and receives block until the other side is ready.
  This allows goroutines to synchronize without explicit locks or
  condition variables.

Still if you want to change the order of your program to see how can we avoid the deadlock.
package main

import "fmt"

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case q:= <-quit:
            fmt.Println(q)
            return
        }
    }
}

func pp(c chan int, quit chan int){
   for i := 0; i < 10; i++ {
            fmt.Println(<-c)
        }
        quit <- 0
}

func main() {
    c := make(chan int)
    quit := make(chan int)

    go func(){
       fibonacci(c, quit)
    }()
    pp(c,quit)
}

Working Code on Go playground
Always remember to wait for the go routine to finish in such situations. But when you call fibonnaci first it has sent the value but the receiver is not ready which leads to deadlock.
Edit:
Because even if you wait for the go routine to finish. It will still create a deadlock because the channels are not sync as:
package main
import (
    "fmt"
    "sync"
)

var wg sync.WaitGroup

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case q:= <-quit:
            fmt.Println(q)
            return
        }
    }
}

func pp(c chan int, quit chan int){
   defer wg.Done()
   for i := 0; i < 10; i++ {
            fmt.Println(<-c)
   }
   quit <- 0
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    fibonacci(c, quit)
    wg.Add(1)
    go pp(c,quit)
    wg.Wait()
}

Output:

fatal error: all goroutines are asleep - deadlock!
goroutine 1 [select]: main.fibonacci(0x434080, 0x4340c0)
    /tmp/sandbox779301309/main.go:13 +0xc0 main.main()
    /tmp/sandbox779301309/main.go:34 +0x80

If you change your code and create a default case in select of for loop. Then it will satisfy that case and return while your main will exit. Never ending loop let it to wait for return in the quit case for it to return. This will work:
package main

import (
    "fmt"
    "sync"
)

var wg sync.WaitGroup

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case q, ok := <-quit:
            if ok {
                fmt.Println(q)
            }
            return
        default:
            fmt.Println("No value in any of the channel")
            return
        }
    }
}

func pp(c chan int, quit chan int) {
    for i := 0; i < 10; i++ {
        if value, ok := <-c; ok {
            fmt.Println(value)
        }
    }
    quit <- 0
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    fibonacci(c, quit)
    go pp(c, quit)
}

Playground Example


text:
Q: Beacons, CoreLocation, BLE, and "Geo-Fencing" - definition of terms? I was hoping someone could spell out the relationship between iBeacon recognition, CoreLocation and CoreBluetooth, specifically in the context of what iOS considers "geo-fencing".
First off, I understand Apple's documentation on Using Regions to Monitor Boundary Crossings  and have seen other discussions around the topic, like iOS - CoreLocation and geofencing while app is closed (especially pertinent to our app since this is a background operation). However, I'm having a hard time finding Apple's explicit definition of geofencing and exactly which frameworks get categorized as such.
Consider:

*

*Beacons are based on BLE and yet they use the CoreLocation framework and not the CoreBluetooth framework. In fact, you do not need to add Bluetooth capabilities to the project settings in order to get them to work.

*Detecting beacon regions uses the same object and method calls: to register a region, you call the 'startMonitoringForRegion' method of 'CLLocationManager' object.

*It appears that once we added beacon recognition to our app, users have begun seeing "geo-fencing enabled" messages in their settings.
I thought geo-fencing was purely used in GPS- and Wifi-based location services? Not BLE services? The whole point of BLE beacons is to reduce the drain on the battery that geo-fencing produces.
On a higher level, is there any way to prove demonstrably that using beacon technology produces a much lower battery drain than other location-based geo-fencing? Using "geo-fencing" as an umbrella term for both (if that is indeed what is happening), muddies the waters significantly when making a business case for beacons.


text:
Q: what does it mean by "debug = require('debug')('api:server')" I was reading some code of a project to learn node.js then I found this line (debug = require('debug')('api:server')) which is enclosed in brackets. As I'm new to programming and when I don't know something I just search it on the web, but I couldn't find an answer for this one. If you are going to tell me to search on the web more aggressively then please tell me HOW too.

A: require returns the exports of some other module. Here, since debug is being passed into require, the debug module is being required. What this module does is:

debug exposes a function; simply pass this function the name of your module, and it will return a decorated version of console.error for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.

So
const debug = require('debug')('api:server');

where require('debug') resolves to a function, is like:
const debug = deccorateModule('api:server');

where decorateModule carries out the functionality described above. In this case, require acts as a higher-order function: a function which returns a function. (You may likely have a module named api:server)
This results in the debug variable holding the decorated version of console.error.


text:
Q: Properities of sine(and cosine) of Brownian Motion Suppose $(B_t, \mathcal{F}_t)_{t \geq 0}$ is a classical Brownian Motion (with the canonical filtration) and consider the process $X_t=\sin(B_t)$.
What properties does our new process share with a Brownian motion? Concretely: does it follow that $(X_t, \mathcal{F}_t)_{t \geq 0}$ is also a continous martingale?
It is definetively the case that $X_t$ also has stationary, independent increments, so that: $$\mathbb{E}[X_T|X_t] = \mathbb{E}[X_t + (X_T-X_t)|X_t] = X_t + \mathbb{E}[(X_T-X_t)|X_t] = X_t + \mathbb{E}[X_T-X_t] = X_t$$
Do you agree? Continuity also seems not difficult. On the other hand, the previous quick proof does not hold for $\cos(B_t)$ since $\mathbb{E}[X_T] \neq \mathbb{E}[X_t] \neq 0$.
Does this mean $\cos(B_t)$ is really not a martingale? I am using the results on this page by the way, for the expected values of $\sin(B_t)$ and $\cos(B_t)$.

A: Continuity is immediate as the composition of continuous functions is again continuous. However, $\sin (B_t)$ and $\cos (B_t)$ are not martingales.
Let $f(x) = \sin x$, so that $f_x(x) = \cos x$ and $f_{xx}(x) = -\sin x$.
Then, by Itô's lemma, $X_t$ satisfies the following stochastic differential equation:
$$dX_t = f_x(B_t) dB_t + \frac{1}{2}f_{xx}(B_t) dt = \cos (B_t)dB_t - \frac{1}{2} \sin (B_t)dt$$
In particular, $\sin B_t$ has a non-zero drift term, so that it cannot be a martingale. You may argue similarly for $\cos B_t$,


text:
Q: Click an enter button to create a new textbox How do I create a new TextBox by clicking an enter button? And how do I focus the cursor on the new textbox (the cursor focus on the last textbox every time the new textbox has been created)?
I has been tried this code:
"private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.Enter += new EventHandler(textBox1_Enter);
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            TextBox tb = new TextBox();

            tb.Size = new Size(100, 50);
            tb.Location = new Point(100, 100);

            Controls.Add(tb);
        }"

But it not create a new textbox when i press an enter button

A: When you load your form:
this.KeyDown += new KeyEventHandler(Form1_KeyDown);

then
void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        TextBox textbox = new TextBox();
        this.Controls.Add(textbox);
        textbox.Focus();
    }
}

Essentially, create the event that fires when a key is pressed.  If the key is the return key, create the textbox.
Your sample code doesn't really make sense because you are firing events from a textbox, when you want them fired from the form.

A:         TextBox myTextBox=new TextBox();

        myTextBox.Visible=true;

        myTextBox.Left=100;
        myTextBox.Top=200;

        myTextBox.Text="ABC";
                    this.Controls.Add(myTextBox);

As for moving the cursor:
        this.Cursor = new Cursor(Cursor.Current.Handle);
        Cursor.Position = new   Point(this.Left+myTextBox.Left+50,this.Top+myTextBox.Top+50);


text:
Q: Should I move from http to https? From what I understand good practices are now to use more and more https.
I was wondering if I can redirect all my websites from http to https, or are there cases where https cannot be used?


text:
Q: How to attach Chrome developer tools to the same window? I'm trying out the developer tools on Chrome for Mac OS and I'm finding a huge annoyance. I don't see an obvious method to make the tools window attach to the bottom of the page I'm inspecting like in Firebug and Safari

A: I know this question is a little bit old but I've just found out you just need to click in the most left icon in the bottom of developer tools window.

A: Ctrl Shift J to get a developer window and then use the bottom left button.

To be clear: I do not own a MAC so I can't test this but it does work on Chrome/Linux for sure.

A: I was able to dock the developer tools into the same window by clicking on the stoplight icon in the top right of the developer tools window.
You can then click on the appropriate icon to either open in a separate window, doc the developer tools on the bottom of the same window, or doc the developer tools on the right side of the same window.

A: As of this writing (Chrome 32 for the mac), the icon you're looking for is on the top right of the developer tools. It looks like a window pane.
Depending on your chrome theme, this button may blend in with the background, but it's there.

A: The Way to attach the Developer's tool to the same tab is simple..  Follow these Steps:-

*

*You open developer Tool By pressing ctrl+shift+i or Cntrl+shift+J  (supposing it opened in a new window)

*In the developer Tool Window, On the top right corner you'll see three vertical dots. click it, and on the top you'll see "Dock Side" option. From this option you can change the setting..  i.e. to open the developer tool in the same webpage..
Cheers!

A: *

*To Start:
Mac: Cmd + option + j
Windows: ctrl + shift + J

*Click on left side options, as highlighted


text:
Q: Machine-precision numbers cause loss of precision I am trying to use the Mod function as follows.
Table[
  Nest[Mod[2 #, 1] &, FractionalPart[Pi], n],
  {n, 100}] // N

Giving the following result:

{0.283185,0.566371,0.132741,0.265482,0.530965,0.0619298,0.12386,0.247719,0.495439,0.990877,0.981755,0.963509,0.927018,0.854036,0.708073,0.416146,0.832291,0.664583,0.329165,0.658331,0.316661,0.633322,0.266645,0.533289,0.0665783,0.133157,0.266313,0.532626,0.0652523,0.130505,0.261009,0.522018,0.0440369,0.0880737,0.176147,0.352295,0.70459,0.40918,0.818359,0.636719,0.273438,0.546875,0.09375,0.1875,0.375,0.75,0.5,0.,0.,0.,0.,0.,-1.,-2.,-4.,-8.,-17.,-35.,-70.,-141.,-282.,-564.,-1129.,-2259.,-4518.,-9036.,-18072.,-36145.,-72290.,-144580.,-289161.,-578323.,-1.15665*10^6,-2.31329*10^6,-4.62658*10^6,-9.25317*10^6,-1.85063*10^7,-3.70127*10^7,-7.40254*10^7,-1.48051*10^8,-2.96101*10^8,-5.92203*10^8,-1.18441*10^9,-2.36881*10^9,-4.73762*10^9,-9.47525*10^9,-1.89505*10^10,-3.7901*10^10,-7.5802*10^10,-1.51604*10^11,-3.03208*10^11,-6.06416*10^11,-1.21283*10^12,-2.42566*10^12,-4.85133*10^12,-9.70265*10^12,-1.94053*10^13,-3.88106*10^13,-7.76212*10^13,-1.55242*10^14}

Now when I do the following
ReleaseHold[
 Hold[Table[
   Nest[Mod[2. #1, 1.] &,
     FractionalPart[3.14159], n], {n, 100.}]]]

I get the following

{0.283185,0.566371,0.132741,0.265482,0.530965,0.0619298,0.12386,0.247719,0.495439,0.990877,0.981755,0.963509,0.927018,0.854036,0.708073,0.416146,0.832291,0.664583,0.329165,0.658331,0.316661,0.633322,0.266645,0.533289,0.0665783,0.133157,0.266313,0.532626,0.0652523,0.130505,0.261009,0.522018,0.0440369,0.0880737,0.176147,0.352295,0.70459,0.40918,0.818359,0.636719,0.273438,0.546875,0.09375,0.1875,0.375,0.75,0.5,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}```

Clearly something to do with working precision. But could you explain why this discrepancy ?

A: The machine-precision series
A machine precision number has the exact form $a \times 2^{-b}$, where $a$ and $b$ are integers.  [The exponent $-b$ is written with a minus sign for convenience in what follows.]  Multiplying by the machine precision number 2. is an exact operation (no round-off error).  If $a$ and $b$ are positive and $a$ has the binary expansion $+ a_{b}a_{b-1}\cdots a_{1}$, which would be the case if $a$ were the result of FractionalPart[] or Mod[x, 1.], then Mod[2. a, 1.] would result in
$$
a_{b-1}\cdots a_{1} \times 2^{-(b-1)}
$$
Note that the length of Mod[2. a, 1.] in bits and the exponent in $2^{-(b-1)}$ would be diminished by one.  After $b-1$ more iterations, the result will be zero.
Computational evidence
res = ReleaseHold[
   Hold[Table[
     Nest[Mod[2. #1, 1.] &, FractionalPart[3.14159], n], {n, 100.}]]];

Count[res, x_ /; x > 0.]

(*  49  <-- number of nonzero results *)

SetPrecision[FractionalPart[3.14159], Infinity]
Log2@ Denominator[%]

(*

  159416167809847/1125899906842624
  50  <-- on the 50th step, we should get 0.
*)

The exact series
The step in the iteration Mod[2 #, 1] & either (1) multiplies by 2 or (2) multiplies by 2 and subtracts 1. In the exact series, the result is never zero, so the effect is that we'll have a sequence of multiplying by 2 following by subtracting one. In short, the current result is multiplied by the smallest power of 2 to make the result between 1 and 2 and then 1 is subtracted. Here's the result after 13 iterations:
-1 + 2  (
 -1 + 2  (
  -1 + 32 (
   -1 + 8  (
    -1 + 8  *
       (-3 + Pi)))))

Applying N introduces a rounding error in approximating Pi - 3. The rounding error is propagated until 0. is reached as in the machine-precision series. At that point 0. is multiplied by a power of 2. and 1. is subtracted. And so forth.  The rounding error is larger than one might suspect because N[Pi - 3] seems to be computed as N[Pi] - N[3], and the subtractive cancellation yields a relative error of around 2^{-51} instead of 2^{-53}.  Coincidentally, the absolute error itself is 2^{53}:
N[Pi - 3] - N[Pi - 3, 16]
Log2[Abs@%]
(*
  -1.11022*10^-16
  -53.
*)

Consequently, after 53 iterations, the -1 shows up.  After that, multiplying by a power of 2 and subtracting one yields larger and larger negative results.


text:
Q: OWIN - Server Error in '/' Application OK, so I have this MVC5 website, using claims identity.
OWIN Throws this nasty error:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

If I manually delete everything in the 'bin' and 'obj' folders, the website works.
problem is that I also get this error, from time to time, on the deployment.
SQL Server is fine, working 100%.
It is something else from OWIN, causing this.
I remember I had this issue in the past, but I cannot recall what I did to fix it.
Here's the full Stack Trace:

[SqlException (0x80131904): A network-related or instance-specific
  error occurred while establishing a connection to SQL Server. The
  server was not found or was not accessible. Verify that the instance
  name is correct and that SQL Server is configured to allow remote
  connections. (provider: SQL Network Interfaces, error: 26 - Error
  Locating Server/Instance Specified)]
  System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
  identity, SqlConnectionString connectionOptions, SqlCredential
  credential, Object providerInfo, String newPassword, SecureString
  newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
  userConnectionOptions, SessionData reconnectSessionData,
  DbConnectionPool pool, String accessToken, Boolean
  applyTransientFaultHandling) +1385
  System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
  options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
  DbConnectionPool pool, DbConnection owningConnection,
  DbConnectionOptions userOptions) +1091
  System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool
  pool, DbConnection owningObject, DbConnectionOptions options,
  DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70
  System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
  owningObject, DbConnectionOptions userOptions, DbConnectionInternal
  oldConnection) +981
  System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
  owningObject, DbConnectionOptions userOptions, DbConnectionInternal
  oldConnection) +114
  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
  allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +1590
  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +156
  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
  owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
  connection) +268
  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions) +314
  System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1
  retry) +204
  System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
  retry) +245    System.Data.SqlClient.SqlConnection.Open() +130
  System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget
  target, Action2 operation, TInterceptionContext interceptionContext,
  Action3 executing, Action3 executed) +98
  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection
  connection, DbInterceptionContext interceptionContext) +509
  System.Data.Entity.SqlServer.<>c__DisplayClass33.<UsingConnection>b__32()
  +566    System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +15
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1
  operation) +237
  System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection
  sqlConnection, Action1 act) +913
  System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1
  commandTimeout, DbConnection sqlConnection, String
  createDatabaseScript) +117
  System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection
  connection, Nullable1 commandTimeout, StoreItemCollection
  storeItemCollection) +211
  System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection
  connection) +134
  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
  mustSucceedToKeepDatabase) +174
  System.Data.Entity.Migrations.DbMigrator.Update(String
  targetMigration) +116
  System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext
  internalContext, Func3 createMigrator, ObjectContext objectContext)
  +121    System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +292
  System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext
  context) +187
  System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
  action) +71
  System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
  +482    System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +174
  System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1
  action) +273
  System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
  entityType) +38
  System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +77
  System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
  +21    System.Data.Entity.Internal.Linq.InternalSet1.FindAsync(CancellationToken
  cancellationToken, Object[] keyValues) +69
  System.Data.Entity.DbSet1.FindAsync(CancellationToken
  cancellationToken, Object[] keyValues) +46
  System.Data.Entity.DbSet1.FindAsync(Object[] keyValues) +19
  Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext()
  +198    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62    Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult()
  +48    Microsoft.AspNet.Identity.Owin.<b__1>d__4.MoveNext()
  +828    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62
  Microsoft.Owin.Security.Cookies.d__2.MoveNext()
  +2534    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62
  Microsoft.Owin.Security.Infrastructure.d__0.MoveNext()
  +823    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62
  Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +333
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62    Microsoft.AspNet.Identity.Owin.d__0.MoveNext()
  +450    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62    Microsoft.AspNet.Identity.Owin.d__0.MoveNext()
  +450    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62    Microsoft.AspNet.Identity.Owin.d__0.MoveNext()
  +450    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62
  Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext()
  +203    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +62
  Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext()
  +193    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult
  ar) +119
  System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +365    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +134

A: You could try the following...
Edit the ApplicationHost.config usually found in C:\Windows\System32\inetsrv\config and change setProfileEnvironment to true.
<applicationPoolDefaults managedRuntimeVersion="v4.0">
    <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</applicationPoolDefaults>

A: I found the issue. These 3 lines in Startup.cs.
I have commented them out and now it works accordingly.
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);


text:
Q: Query varbinary bit field I am storing which lines in a source file are executed in a SQL server database. In my query I want to determine if two file's executions overlap; e.g.

Line Run1 Run2
1    x
2    x    x
3
4         x

Run1 executed lines 1 and 2, run2 lines 2 and 4. I can see by doing a (run1 & ! run2) that line 1 was executed in Run1 only.
If I store the runs as bit masks (varbinary) how can I compare runs in an SQL query?
create table runs columns filename varchar, runCoverage varbinary;
select filename, andNot(run, 1) from runs group by filename

This would compare a (selection of) run with the others run bit fields. Ideally I want to OR the bitfields of groups of records (line coverage data from one component) and then AND NOT with another group of records. I can count the 1 bits in the result, which would be the number of lines covered in one group of tests but not in another...

A: If the number of lines isn't too great, you could simply cast the varbinary to a bigint to do bitwise comparissons
to get all files that executed line 1:
where (cast(runCoverage as bigint) & 1) > 0

or all files that executed any line beside line 1
where (cast(runCoverage as bigint) & ~1) > 0

If the  number of lines is higher, some helper function could be made using substr to get the proper bits. Then again, perhaps I'm misunderstanding the question alltogether.


text:
Q: Book about a planet where the main character has to run away from the Sun I remember reading this book when I was 11 or 12, and it's killing me now - I just remember that the planet was really hot, and the character had to constantly run away from the Sun to stay alive.
Pretty vague but I'd be so happy if someone could identify, I remember really liking this when I was younger.

A: From your question I'm not sure if you're remembering a novel or a short story. On the off-chance that it was a short story, a possible candidate is Running from the Sun by William Forstchen. It deals with two young cadets from the "Moon Academy" assigned to an asteroid on an orbit near to the Sun. An accident destroys their shelter, and they have to keep running around the asteroid to always stay in the shade to avoid being cooked alive.
It was published in 1991 in Boy's Life. Isfdb doesn't seem to know about it, but a copy is available online at google books.