To find $P(XY>z)$ for $\operatorname{Pareto}(a)$ IIDs $X,\,Y$

Question:
Let $X$ and $Y$ be i.i.d $\operatorname{Pareto}(a)$, i.e. each of them has PDF $f(x)=ax^{-a-1}1_{[1,\,\infty)}(x)$ for some $a>0$. Calculate $P(XY>z)$ for $z\ge1$.

I tried converting from Pareto distribution to exponential such that $P(\ln X+\ln Y>\ln z)$
But don't know what to do further.
What I can infer is that it is essentially P((gamma(2,alpha)>log Z).
However how do I calculate the same...in order to obtain a closed form.
I would kindly ask for an answer in order to enable me to understand as I am unable to evaluate the expression using the CDF of the gamma distribution.
Hope my argument is clear.
Comment: You're welcome. You can prove your Gamma-distribution claim with convolutions or characteristic functions (or, which is similar, moment-generating functions). If we know which methods are allowed at your level, we can help you.
Comment: That's what it reduces to, yes. Make sure any course details you clarify are edited into the question, rather than placed in comments, which are ideally ephemeral.
Comment: Do you know the sum of two $\operatorname{Exp}(\lambda)$ IIDs is distributed? Failing that, which methods do you know for computing the distribution of the sum of IIDs?
Comment: Well it is given that the Paretos are i.i.d distributed now..I know that log(Pareto) is exponential so I transformed it to P(X_1+Y_1>=logZ) where X_1 and Y_1 are exponetially.
Comment: I have an idea...that sum of exponetially distributed i.i.ds follow gamma distribution.
Comment: And thank you for editing the question @J.G...thanks a lot
Comment: Ya,that has been discussed in our course..however I have a question that the problem essentially reduces to P(Gamma(alpha,2))>logZ..
Comment: I have added the issue at which I am stuck at in the main question body ....@J.G.
Answer: Since as you've realized $W:=\ln(XY)$ has PDF $a^2we^{-2aw}1_{[0,\,\infty)}(w)$,$$P(W>\ln z)\stackrel{t:=2aw}{=}\frac12a\int_{2a\ln z}^\infty\frac12ate^{-t}dt=[(-1-t)e^{-t}]_{2a\ln z}^\infty,$$which I leave you to simplify.
Comment: I did not quite understand the  1st line...the PDF mentioned by you in the answer it is which distribution PDF.
Comment: I am actually unable to connect whether that is the PDF of the Gamma distribution...as I knew it in a different form @J.G.
Comment: @Mathtome Edit your knowledge of the Gamma distribution of $\ln X+\ln Y$ into the question.


Error: Call to undefined function execute()

Question: this my html and php coding

          Room Size:
          <select class="form-control" required>
            <option value=""> -Sila Pilih- </option>

     <?php

       $sql1    = "SELECT * FROM room_type ORDER BY code ASC";
       $query1  = $conn -> prepare($sql1);
       $query1  = execute();

       while($data1   = $query1 -> fetch(PDO::FETCH_OBJ)):
       echo '<option value= "'.$data1->code.'" > '.$data1->title.' </option>';

     endwhile;

     ?>

          </select>

Fatal error:  Uncaught Error: Call to undefined function execute() in /opt/lampp/htdocs/php/Kelas/room.php:124
Stack trace:
  0 {main}
    thrown in /opt/lampp/htdocs/php/Kelas/room.php on line 124
Comment: Use it like `$query1->execute()` Read http://php.net/manual/en/pdostatement.execute.php
Comment: change to `$query1->execute();`
Comment: This could help you: http://php.net/manual/en/pdostatement.execute.php
Answer: You should call execute() method on $query1 object which is PDOStatement instance.
Try:
$query1->execute();

instead of:
$query1  = execute();

Here's PDOStatement's doc page with examples
Answer: Change the portion of your code
$query1  = execute();

to
$query1->execute();

execute() method should be called on PDOStatement object $query1
Check PDOStatement::execute for detailed explanation.


Is there a proof for this or we should accept that?

Question: Why are two independent parameters necessary and enough for determining position of a point with respect to a reference point in a plane?
In other words, I want to address a point from another reference point in a plane. How many independent parameters are necessary and enough for that aim? And why?
Comment: If you view the plane as the Cartesian product of two axes, then this ought to be obvious enough: A Cartesian product is a set of ordered pairs, and the two data points correspond to each part of the pair. If you're thinking of the plane as something else, then you'll need to explain.
Comment: Since you talking about 2-dimensional space, you need some basis of the space (which includes 2 elements) to represent each variable in that space as a linear sum of the basis elements.
Comment: Whether it is something to prove, or something to accept as given, depends on how you define a plane. It certainly doesn't follow just from the fact that there's only one line passing through two points, because the latter is true also in space, where two numbers are not sufficient to specify a point.
Comment: You shouldn't say "with respect to a reference point in a plane", as this boils down to telling the distance to the reference point, which requires a single independent parameter, not two.
Comment: @T.Bongers Thanks! I want to address a point from another reference point in a plane. How many independent parameters are necessary and enough for that aim? And why?
Comment: @YvesDaoust Thanks! But there are infinite point (on a circle) in a constant distance from a point.
Comment: @celtschk Thanks! You are right it doesn't follow just that fact. I was mistaken.
Comment: @lucas You talk about how many parameters are necessary and in theory you only need on parameter, since you can identify the line and the plane with a bijection.
Comment: @lucas: anyway your formulation is wrong; all points on the circle are at the same distance and have the same "position wrt the reference" and are equivalent in this respect. You should ask for "the poition of a point in a plane", full stop.
Comment: @YvesDaoust But each coordinate system needs an origin, doesn't it?
Comment: I think you have to be more specific about what you mean. There **are** space filling curves so each point can very well be specified with a single parameter. In addition (I think) one could construct mappings of the plane which require three parameters to identify a point.
Comment: A single point doesn't define a coordinate system. Saying "with respect to a point" is either too few or too much.
Answer: To show the sufficient condition, you can reason as follows:

choose three points in the plane forming a non-degenerate triangle and choose two sides;
for any point, there are two unique lines parallel to the respective sides that pass through it;
the intersection points of the parallels with the sides can be unambiguously located by means of the ratio of lengths.

Conversely, two ratios define two non-parallel lines, that have a single intersection point.
By this method any point can be unambiguously designated by two real numbers.
Comment: Sorry, I cannot get your meaning. But I am sure that the problem is from me not your answer. Thank you very much because of your time and attention.
Comment: Well! But how about other coordinate systems? Polar, path, etc. For example, in polar coordinate system we determine the position of a point by a distance and an angle.
Comment: @lucas This answers and closes the question "two parameters are enough", constructively.
Comment: My main question was: How many [degrees of freedom](https://en.wikipedia.org/wiki/Degrees_of_freedom_(mechanics)) does a point have in a plane (with proof). But I was afraid that it gets closed because of being off-topic.
Comment: @lucas: why this comment ? My answer is about $DOF\le2$.
Comment: I am not mathematician and I am not familiar with technical definitions. I wanted to ask my question in an on-topic form. But it seems that my question has technically mistakes.
Comment: But the answer is $DOF=2$
Comment: @lucas, hem $DOF=2\implies DOF\le 2$, doesn't it ?
Comment: But $DOF\le 2$ means that $DOF$ can be $1$ or $0$ also.
Comment: $2$ independent parameters are **necessary** and **enough**.
Comment: @lucas: for the last time, isn't it clear that my answer is about the "sufficient" requirement ($DOF\le2$), not about the "necessary" one ($DOF\ge2$) ?
Comment: @lucas: you shouldn't accept my answer as it's only partial.


Rahn Atonal Prime Form Confusion

Question: A review via the mark I eyeball of the prime form tables in "Basic Atonal
Theory" (Rahn, 1980) versus modern software calculations of the prime
form yields some differences; are these errors in publication, the
software, or something else?
7-Z18  0, 1, 2, 3, 5, 8, 9      # BAT
       0, 1, 4, 5, 6, 7, 9      # software

7-20   0, 1, 2, 4, 7, 8, 9      # BAT
       0, 1, 2, 5, 6, 7, 9      # software

8-26   0, 1, 2, 4, 5, 7, 9, 10  # BAT
       0, 1, 3, 4, 5, 7, 8, 10  # software

For 7-Z18 and 7-20 Rahn is in agreement with what Forte published,
but not software that uses the Rahn method? 8-26 I've no idea.
Answer: They are both right and here's why.
There are two different algorithms for determining the prime form which are Forte's and Rahn's. In most cases they are the same, however there are a handful that are not the same. The one's you've noted are not the same with both algorithms. The breakdown of them are as follows:

Pitch Class Set     Forte Prime           Rahn Prime
7-Z18              (0,1,2,3,5,8,9)      (0,1,4,5,6,7,9)
7-20               (0,1,2,4,7,8,9)      (0,1,2,5,6,7,9)
8-26             (0,1,2,4,5,7,9,10)    (0,1,3,4,5,7,8,10)

You can even try it out yourself on this calculator.
Here's a more in depth explanation of why this is and what the actual difference is bewteen the two from the What is this? button next to the two algorithms.

There are two algorithms for computing the prime form of a Pitch Class
  Set. The first was introduced by Allen Forte in The Structure of
  Atonal Music and the second is used by John Rahn in his book Basic
  Atonal Theory and is also used by Joseph N. Straus in his Introduction
  to Post-Tonal Theory.
The difference between the two algorithms is apparent when examining
  Pitch Class Set 6-31. The Prime Form using the Forte algorithm is
  (0,1,3,5,8,9), and the prime form using the Rahn algorithm is
  (0,1,4,5,7,9). As you can see, the Forte algorithm puts a priority on
  making the small numbers smaller (i.e. 3 instead of 4), whereas the
  Rahn algorithm wants the larger numbers to be smaller (i.e. 7 instead
  of 8).
Which is better? Well, it depends on who you ask. Computer programmers
  and computer music people will typically prefer the Rahn algorithm
  because it is computationally more elegant. However, the Forte
  algorithm has the more established pedigree, and so it tends to be
  preferred by academics.
Comment: So why is the Rahn book using Forte-algorithm derived prime forms for three of its entries? The rest of the prime forms in the Rahn book agree with the Rahn algo.
Comment: Hmm, David H. Smyth in "Perspectives of New Music" Vol 22 No 1/2 (Autumn, 1983 - Summer 1984) pp. 549-555 reviews "Basic Atonal Theory" and points out errata and food for folks implementing code to do this sort of thing.
Comment: @thrig The software's output is showing Rahn's results. The book on those three is not which may be considered a typo, but there're not wrong in a sense of prime form since it's valid for Forte's.

Rahn Atonal Prime Form Confusion


Are all stopped Brownian motions integrable?

Question: Let $(W_t)_{t\in[0,\infty)}$ be a standard Brownian motion and let $\tau$ be a stopping time that is finite almost everywhere, but otherwise arbitrary—it need not be a hitting time, in particular.

I am wondering whether the random variable $\omega\mapsto W_{\tau(\omega)}({\omega})$ is integrable for all such stopping times or whether a counterexample can be constructed.

Intuitively, the expected value of $|W_t(\omega)|$ for a fixed $t\geq0$ is proportional to $\sqrt{t}$, which tends to make it less likely that $\omega\mapsto W_{\tau(\omega)}({\omega})$ is integrable if one can make $\tau$ take on large values with sufficiently high probabilities. On the other hand, the probability of $\tau$ being "large enough" is small (given that $\tau$ is finite almost everywhere), which tends to favor integrability.
I cannot see whether a counterexample can be constructed making the first of these two effects "win" against the second, yielding $$\int_{\omega\in\Omega}|W_{\tau(\omega)}(\omega)|\,\mathrm d\mathbb P(\omega)=+\infty.$$

Any hints and comments would be much appreciated.
Answer: Using the idea in your answer we can prove something stronger.

For any cumulative distribution function $F$ on $\mathbb{R}$, there is an a.s. finite stopping time such that $W_\tau$ has the distribution $F$.

In particular we can choose an $F$ with infinite first moment.
Recall the following lemma which is fairly standard and not hard to prove:

For any cdf $F$, define $F^{\leftarrow} : (0,1) \to \mathbb{R}$ by $F^{\leftarrow}(y) = \sup\{x : F(x) < y\}$.  If $U$ is a random variable with a uniform(0,1) distribution, then $F^{\leftarrow}(U)$ has the distribution $F$.

Note that if $F$ is continuous and strictly increasing then $F^{\leftarrow} = F^{-1}$.
Next let $\Phi$ be the standard normal cdf.  If $Z$ has a standard normal distribution, then $\Phi(Z)$ has a uniform(0,1) distribution.  In particular this is true for $\Phi(W_1)$.  So let $g = F^{\leftarrow} \circ \Phi$; then $g(W_1)$ has the distribution $F$.
Now let
$$\tau = \inf\{t \ge 1 : W_t = g(W_1)\}.$$
As in your answer, by the strong Markov property, $X_s = W_{s+1} - W_1$ is a Brownian motion independent of $W_1$.  Brownian motion is recurrent, so for any $x$, $X_s$ hits the value $x$ almost surely.  Since $\{X_s\}$ is independent of $W_1$, this implies that $X_s$ hits the value $g(W_1) - W_1$ almost surely.  This happens when $W_t$ hits the value $g(W_1)$, so $\tau < \infty$ almost surely.  And it is clear that $W_\tau = g(W_1)$, so $W_\tau$ has the distribution $F$.
It's worth mentioning here the Skorohod embedding theorem, which says that if $F$ has zero mean and finite variance, then we can find an integrable stopping time $\tau$ such that $W_\tau \sim F$.  You can find a proof in Brownian Motion by Mörters and  Peres.  The assumption of zero mean and finite variance is necessary here, since it follows from the Wald lemmas that if $\tau$ is integrable then $E[W_\tau] = 0$ and $E[W_\tau^2] = E[\tau]$.
Comment: @triple_sec: Strictly speaking you are right.  However, it doesn't really make any difference.  It's common to use a definition of stopping time that allows an infinitesimal peek into the future; i.e. the event $\tau = 1$ need only be $\mathcal{F}_{1+}$-measurable.  It is also commonly assumed that the filtration is complete, so you can do whatever you want on events of probability 0.  And there are many ways to see that the event you are worried about has probability 0.
Comment: First, please accept my apologies for the belated reply. Thank you very much for your answer, this is very nice. In fact, this question came into my mind while I was consulting a proof of Skorohod's embedding theorem, so it is not a coincidence you thought it was relevant. One minor thing: I think the strict inequality $t>1$ in the definition of $\tau$ should be weak: $t\geq 1$. This is because if the inequality is weak, then $\tau=1$ is easily seen to be the same event as $W_1=g(W_1)$ by continuity. However, if you insist on the strict inequality, [continued below]
Comment: [continued] then $W_1=g(W_1)$ does _not_ imply that $\tau=1$: it may happen that $W_t$ just hits $g(W_1)$ at $t=1$, and it does not hit it again for a long time (or ever). The point is that, intuitively, the event $\tau=1$ should not depend (even on zero-probability sets) on what values the motion takes on for $t>1$, since a stopping time is not supposed to "look into the future." But if the inequality is strict, then the event $\tau=1$ is determined by values of the Brownian motion just a little bit _later_ than $t=1$; the knowledge of $W_1$ alone is not sufficient to decide whether $\tau=1$.
Comment: I was not aware that some versions of the definition of stopping times would allow instantaneous forward-looking. And, indeed, the probability of the event affected by this minor point vanishes (or at least the affected sample points sit within a zero-probability set if the underlying space is not complete), so that the ultimate distribution is unaffected. Thank you for the clarification and, again, for the brilliant answer!
Comment: Actually, the "instantaneous forward-looking" is usually built into the filtration - it's common to assume the filtration is right continuous, so that $\mathcal{F}_t = \mathcal{F}_{t+}$.  This and completeness are called the "usual conditions".
Answer: Here is a (somewhat contrived) counterexample. The idea is this: wait until the period $t=1$. Then, decide when to stop based solely on the value of $W_1$. In particular, choose for each realization of $W_1(\omega)$ such an extremely late time of eventual stopping that makes the first effect mentioned above "win" against the second, rendering an infinite expected absolute value of the stopped process.

For each $n\in\mathbb N$, define
\begin{align*}
p_n\equiv&\;\mathbb P\big(\{\omega\in\Omega\,|\,n-1\leq|W_1(\omega)|<n\}\big),\\
t_n\equiv&\;\frac{\pi}{2p_n^2}+1.
\end{align*}
Since $W_1$ has the standard normal distribution, the sequence $(p_n)_{n\in\mathbb N}$ of probabilities is strictly positive, strictly decreasing, and converges to $0$. Correspondingly, the sequence $(t_n)_{n\in\mathbb N}$ is well-defined, strictly increasing, always greater than $1$, and diverges to $+\infty$.
Now, define $$\tau(\omega)\equiv t_n\quad\text{if $n-1\leq|W_1(\omega)|<n$.}$$
It is not difficult to verify that $\tau$ is a stopping time that is everywhere finite-valued.
The following argument [which exploits the facts that for any $t>1$, (i) $W_1$ and $W_t-W_1$ are independent; and (ii) $W_t-W_1$ has the normal distribution of mean $0$ and variance $t-1$] establishes that $W_{\tau}-W_1$ is not integrable, which implies that $W_{\tau}$ is not integrable, either:
\begin{align*}
&\;\int_{\omega\in\Omega}|W_{\tau(\omega)}(\omega)-W_1(\omega)|\,\mathrm d\mathbb P(\omega)=\sum_{n=1}^{\infty}\int_{\{\omega\in\Omega\,|\,\tau(\omega)=t_n\}}|W_{t_n}(\omega)-W_1(\omega)|\,\mathrm d\mathbb P(\omega)\\
=&\;\sum_{n=1}^{\infty}\int_{\{\omega\in\Omega\,|\,n-1\leq|W_1(\omega)|<n\}}|W_{t_n}(\omega)-W_1(\omega)|\,\mathrm d\mathbb P(\omega)\\
=&\;\sum_{n=1}^{\infty}\mathbb P\big(\{\omega\in\Omega\,|\,n-1\leq|W_1(\omega)|<n\}\big)\times\mathbb E(|W_{t_n}-W_1|)=\sum_{n=1}^{\infty}p_n\times\sqrt{\frac{2}{\pi}\times(t_n-1)}\\
=&\;\sum_{n=1}^{\infty}1=+\infty.
\end{align*}


Why is plexiglas(perspex) sometimes placed in front of guitar amplifiers at live shows?

Question: Something I've noticed at several live shows (especially blues and jazz) is these short plexiglass walls placed in front of the guitar amplifiers.  Why would they do that?  What are they for?
Answer: They are used to manage the on-stage volume levels while still allowing the amplifiers to be cranked up for tone.  These shields limit the amount of sound directly hitting the on-stage performers.  You will also see them around drummers.
This type of shielding will also reduce cross-talk, e.g. preventing the drum sounds getting captured by the guitar microphones, but I haven't heard of this being the primary driver for on live shows; but they have been used in studio situations to reduce bleed.
Comment: You can also see sound shields on stage in orchestra. Usually to protect the players that are in front of the trombones.
Comment: @Édouard accurate. Source: am trombonist :-)


Insert html into a div based on select box value

Question: I'm trying to get a button to insert html into a div based on a select box value. It is not working. When I press the button, nothing happens. Not sure if I'm missing something? From what I can tell the code should work, but it doesn't, so that means I'm definitely not in the right waters.

KMVCSS Newsletters

2014 - 2017

<form acion="post" action="">
<select id="nbox" name="newsletters">
<option value="2017">Newsletter 2017</option>

</select>
<button id="nbutton" type="button" onclick="displayNewsletter();">Get Newsletter Link</button>
</form>

Javascript


D3 Zoom scales Map, not points

Question: I am zooming in on a map upon click but the latitude longitude points do not scale. They are rendered as circles and I would like them to move with the map. I am following the D3 template here: http://bl.ocks.org/mbostock/2206590
<code>  var map_width = 960,
  map_height = 500,
  jsonRoot = '/static/d3/json/',
  centered;

 var projection = d3.geo.albersUsa()
.scale(1070)
.translate([map_width / 2, map_height / 2]); // default projection type for d3.geo.path
 var urls = {
    counties: jsonRoot + "us-counties.json",
    states: jsonRoot + "us-states.json"
}
, margin = { top: 0, right: 0, bottom: 0, left: 0 }
, width = 960 - margin.right - margin.left
, height = 500
, path = d3.geo.path().projection(projection)
, map;

var q = queue()
  .defer(d3.json, jsonRoot + "us-counties.json")
  .defer(d3.json, jsonRoot + "us-states.json")
  .await(ready);

function ready(error, countylines, statelines) {
window.error = error;
window.countylines = countylines;
window.statelines = statelines;

if (error){
  throw error;
}

var stateIds = {};
statelines.features.forEach(function(d) {
    stateIds[d.id] = d.properties.name;
});

countylines.features.forEach(function(d) {
    d.properties.state = stateIds[d.id.slice(0,2)];
})

// remove the loading text
d3.select('.loading').remove();

map = d3.select('#map').append('svg')
    .style('width', width)
    .style('height', height);

counties = map.append('g')
    .attr('class', 'counties')
  .selectAll('path')
    .data(countylines.features)
  .enter().append('path')
    .attr('d', path);

counties.on('mouseover', showCaption)
    .on('mousemove', showCaption)
    .on('mouseout', function() {
      caption.html(starter);
    })
    .on('click', clicked);

states = map.append('g')
    .attr('class', 'states')
  .selectAll('path')
    .data(statelines.features)
  .enter().append('path')
    .attr('d', path);

// Captions
var caption = d3.select('#caption')
  , starter = caption.html();

function showCaption(d, i) {
      var name = [d.properties.name, d.properties.state].join(', ');
  caption.html(name);
}

var systemSuccess = function(result){
  console.log(result);
}

    var site = map.append("circle")
      .attr("r",5)
      .classed("system", true)
      .attr("latitude",37.77521)
      .attr("longitude",-122.42854)
      .attr("transform", function() {
      return "translate(" + projection([-122.42854,37.77521]) + ")";
    });

  });
})
};

function clicked(d) {
var x, y, k;

if (d && centered !== d) {
  var centroid = path.centroid(d);
  x = centroid[0];
  y = centroid[1];
  k = 4;
  centered = d;
} else {
  x = width / 2;
  y = height / 2;
  k = 1;
  centered = null;
}

counties.selectAll("path")
.classed("active", centered && function(d) { return d === centered; });

counties.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");

states.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");

map.selectAll(".system")
.attr("transform", function(d) { return "translate(" + projection([-122.42854, 37.77521 ]) + ")" });
}
});
</code>
The map scales appropriately. But not the points.
All help is appreciated!
Comment: It looks like you're appending only a single circle with fixed coordinates. How are you creating the points you are talking about?
Comment: And it doesn't seem like you're doing anything - the `.system` translation is the same on creation and click...
Comment: Right, how would "reproject" those coordinates to a zoomed map?
Comment: To simplify, I've hardcoded the point coordinates. My intention is to be able to project them onto the zoomed map such that they are correct relative to the zoomed map
Comment: Right, so you change the projection/transformation of the points in the same way as for the paths.
Comment: I see, thanks. Could you link to any documentation with such transformations or some more information about projection/transformation in same way for paths?  Thanks
Answer: As Lars suggested, you could do the following.
<code>//Same projection and transformation as applicable to the path elements.
d3.selectAll("circle")
.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
</code>
I am not sure if the above code would work correctly...although I have used a similar premise through the "zoom" d3 behavior.
If you want your points to retain their size, but be at the right position; you could try semantic zooming
OR
you could keep the resize the circle's radius based on the scale like this:
<code>d3.selectAll("circle")
.attr("r", 5/k);
</code>

D3 Zoom scales Map, not points


Problemas com automação web em VBA - Radio Button

Question: Olá, Sou novo por Aqui,
Estou enfrentando um problema com meu código VBA, estou tentando uma interação usando a internet explore, preciso que faça os seguintes passos

acesse o site: https://www.bcb.gov.br/estabilidadefinanceira/historicocotacoes
selecione o radio button 2 <"Cotações de fechamento de todas as moedas em uma data.">
clique em pesquisar.

porém, quando tento lecionar o radio button, ele aparece um erro. abaixo está o meu código.
<code>    Sub buscador()

    Set ie = CreateObject("InternetExplorer.application")

    ie.navigate "https://www.bcb.gov.br/estabilidadefinanceira/historicocotacoes"
    ie.Visible = True

    Do While ie.Busy And ie.readyState <> ""
    DoEvents
    Loop

    ie.document.getElementById("RadOpcao").Item(1).Click

    ie.document.getElementsByClassName("fundoPadraoBClaro3").Item(0).getElementsByTagName("input").Item(1).Click

    End Sub

</code>
HTML que estou pegando as class
Imagem do codigo em html
Comment: `getElementById` como diz o nome do método pega um elemento, então não precisa do `.Item` pq não vai ter retornar um array mas um único objeto
Comment: @RicardoPontual testei com a seguinte expressão ie.document.getElementsByTagName("RadOpcao")(0).Click  porem não deu certo, deu erro 91
Comment: acredito que não conhece muito de html, acho que precisa dar uma olhada sobre :)  `getElementsByTagName`  vai procurar uma tag como o nome do método diz, eu não conheço uma tag "RadOpcao" no html  :) esse método se usa para "input", "button", "div", etc
Answer: A URL que está tentando interpretar através do InternetExplorer.application possui um iframe (basicamente uma página dentro de outra página, veja mais aqui).
Os iframes limitam as seleções e execuções, inclusive as rotinas definidas pelo VBA.
A solução é buscar o acesso diretamente nessa página que está incorporada na página principal. Ao inspecionar a página é possível chegar até ela (URL base), veja:

Agora podemos ajustar o código VBA com essa URL. Ainda, alterei as linhas de busca e clique, utilizando querySelector a partir do value, que aparentemente é um valor único em cada elemento (o ID dos elementos HTML estão repetidos, o que não é recomendado, podendo gerar algum erro):
<code>Sub buscador()

Set ie = CreateObject("InternetExplorer.application")

ie.navigate "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?method=exibeFormularioConsultaBoletim"
ie.Visible = True

Do While ie.Busy And ie.readyState <> ""
DoEvents
Loop

ie.document.querySelector("input[value='2']").Click
ie.document.querySelector("input[value='Pesquisar']").Click

End Sub
</code>
Comment: perfeito amigo, deu certo!!
Comment: agora eu estou na parte de "baixar" o arquivo. Vou tentando aqui. Muito obrigado.
Comment: Ótimo. Sinaliza como resposta adequada, pode ajudar mais pessoas. Se surgir novos problemas, crie uma nova pergunta para não misturar os temas.


Taylor series for arctan(x)

Question: I am having a serious problem with the following example:
$$f(x) = \arctan(x).$$
The task is to calculate the taylor polynom of the third grade. This is easy and I solved it.
The second task is to get the lagrange error for  $$ x \le \frac{1}{10} .$$
I know that the equation for the error is $$ R(f,x,x_0) = \frac{1}{(n+1)!} \cdot f^{n+1}(\xi) \cdot (x-x_0)^{n+1} $$ and that, applied to this specific example, can be written as:
$$ R(f,x,0) = \frac{1}{4!} \cdot f''''(\xi) \cdot x^4 .$$
I also found the fourth derivation, which is $$\frac{24x-24x^3}{(x^2+1)^4}.$$ I can also set $x = \frac{1}{10}$ to get the "worst case", but how can I find a good $ \xi ?$
I would be happy if you could help me.
Thanks!
Answer: You probably should not really be thinking of finding some particular $\xi$ but rather, estimating how big $|f''''(x)|$ can be (BTW note the absolute value signs).  The more thought you put into this the better estimate you can get (maybe), but probably a rather crude estimate will be good enough, so it's best just to go with fairly simple ideas.  Here is one possibility.
Since $|x|<\frac1{10}$ we have
$$|x|>|x^3|$$
and so
$$|24x-24x^3|<|24x|+|24x|<\frac{48}{10}\ ;$$
also
$$|x^2+1|\ge1\ .$$
Therefore
$$\left|\frac{24x-24x^3}{(x^2+1)^4}\right|<\frac{48/10}{1^4}=4.8\ .$$
Hope this helps!
BTW I am assuming that $x_0=0$: you didn't say so but from your working that's what it looks like.
Comment: Thank you so much! This really helps, but why can you say $$|24x - 24x^3| < |24x| + |24x|$$?
Comment: Triangle inequality, $|a-b|\le|a|+|b|$.
Comment: Oh thank you so much. Your solution is absolutely clear but do you have an idea to get a better estimation?
Comment: Not too hard: $|x-x^3|=|x||1-x^2|\le|x|$, and so $|24x-24x^3|\le\frac{24}{10}$, slightly better than above.  Anything better than this, I suspect, could be very difficult.

Taylor series for arctan(x)


I have to Export around 50 page pdf in node js which module i have to use?

Question: Currently I am using pdfmake module in my sails app to export pdf.But,when size of pdf increase it is taking too much time to export pdf,Ihave to export pdf of around 50 pages.So,Which module i can use to export pdf ? or any way to decrease load time in pdfmake module.
Thank you,
Answer: It can be an issue with the performance of your server. Is it VPS, dedicated or somehow shared?
Try to use html-pdf
https://www.npmjs.com/package/html-pdf


Estou com um problema com meu código não consigo trazer os dados de uma função para outra!

Question: Estou com um problema com meu código não consigo trazer os dados de uma função para outra!!
no caso da Função somar não consigo imprimi-la na função imprimir.
Alguém pode me ajudar
1 - Inserir em um vetor
2 - Somar valores do vetor
3 - Imprimir valores e soma
4 - Sair
A qualquer momento pode solicitar impressão dos dados, não imprima lixo de memória
A qualquer momento pode solicitar a soma, não some valores não lidos ainda
<code>
#include <stdio.h>
#define TAM 5
int vetor[TAM];
int menu(){
    int opcao;
    printf("1 - Inserir\n");
    printf("2 - Somar valores\n");
    printf("3 - Imprimir\n");
    printf("4 - Sair\n");
    scanf("%d", &opcao);
    return opcao;
}
//----------------------------------------------------INSERINDO OS DADOS
int inserir(int i){
    int vt;
    for (i = 0; i < TAM; i++){
        scanf("%d", &vetor[i]);
    }
    return vt;
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------SOMAR
int somar(int i){
    int soma=0, total;
    for (i=0; i<TAM; i++){
        soma=soma+vetor[i];
    }
    total = soma;
    printf("\n");
    return total;
}
//-----------------------------------------------------------------------

//----------------------------------------------------IMPRIMINDO OS DADOS
void imprimir(int i){
    printf("Imprimindo elementos\n");
    for (int i=0; i<TAM; i++){
        printf("   %d   ", vetor[i]);
    }

    printf("%d\n", total);   //IMPRIMIR DADO DA SOMA <----------------
    printf("\n");
}
//-----------------------------------------------------------------------

int main(){
    int op = 0, i=0;
    i++;
    while(op != 4){
        op = menu();
        switch (op){
            case 1:
                inserir(i);
                break;
            case 2:
                somar(i);
                break;
            case 3:
                imprimir(i);
                break;
            case 4:
                printf("Saindo");
                break;
        }
    }
    return 0;
}

</code>
Answer: No seu código eu achei 2 erros, que foram:

Não chamar a função somar dentro da função imprimir
Não declarar a variável TOTAL

As correções foram basicamente isso que citei acima e seu código funcionou
<code>    void imprimir(int i){
    int total;
    printf("Imprimindo elementos\n");
    for (int i=0; i<TAM; i++){
        printf("   %d   ", vetor[i]);
    }
    total = somar(i);
    printf("%d\n", total);   //IMPRIMIR DADO DA SOMA <----------------
    printf("\n");
}
</code>
Como não havia uma troca do valor entre a função somar e a função imprimir, sempre era impresso lixo de memória. Logo, chamando a função, passando por parâmetro qualquer coisa, ele retornou a soma corretamente.
Comment: Perfeitamente, mil perdões
Comment: Mario se quiser deixar uma mensagem disponibilizando-se para ajuda use os comentários.


QMAKE_POST_LINK in windows 10 issue

Question:
I have an Qt project wherein I build a lib and then use it in my main
  project. For that purpose in the library's .pro file I need to copy the
  generated libs to a certain folder. And for that purpose I am using
  QMAKE_POST_LINK. The ones I have doesn't seem to work.

QML_INSTALL_PATH = C:\Qt\Qt5.7.0\5.7\mingw53_32\qml\Plot
QMAKE_DIR_SEP = "\\"

WDIR = $$replace(PWD, /, $$QMAKE_DIR_SEP)
QMAKE_POST_LINK += copy /y ..\Plot\*.*  $$QML_INSTALL_PATH &
QMAKE_POST_LINK += copy /y $$WDIR\*.qml $$QML_INSTALL_PATH

Comment: it works but only if I rebuild the project everytime. Is there any setting to change that?
Answer:
it works but only if I rebuild the project everytime

Since the library has been already linked, there's no need to copy it again. It only will get copied when it gets linked. That's the meaning of QMAKE_POST_LINK. It literally is "do this after you link", so when you don't link, it doesn't get done.
If you're removing the copy and want it auto-regenerated, you need to add a custom target.
Answer: Try using $$QMAKE_COPY, and $$quote() around the arguments. I.e.
QMAKE_POST_LINK += $$QMAKE_COPY $$quote(../Plot/*.*) $$quote($$QML_INSTALL_PATH) & $$QMAKE_COPY $$quote($$WDIR/*.qml) $$quote($$QML_INSTALL_PATH)

Comment: the one that I have used and yours works but only if I rebuild the project. It doesn't work simply when I build the project.

QMAKE_POST_LINK in windows 10 issue


Best way to run admin side mySQL based sessions (without modifying php code)

Question: I'd like to set up mysql sessions in my hosting environment that works for all of my clients across the board for my load balanced environment.  After some googling, it sounds like most people's solutions involve overriding their session handlers with php code.  Since I am not the web admin for all of the sites I host, I'd rather not touch the PHP code itself.
Is there a way through Apache or PHP config to add PHP code that gets processed for all pages?
Or is there a preferred mysql session handler that people use?
the only one I've found is http://websupport.sk/~stanojr/projects/session_mysql/
which seems a little less documented and supported than I'd like for a production environment.
Thanks
Answer: It isn't quite clear in your question, but I am going to presume you are asking how to handle PHP sessions in a (load balanced) server cluster.
Traditional PHP sessions are stored in flat files - the location and details of which are configured in php.ini. The problem with this and a server cluster is, of course, that a session file created on one server is not available on any other server.
There are a number of solutions to this problem, each with their own advantages and disadvantages.
Sticky sessions:
Have your load balancer hash the requesting IP and always send the same user to the same server. This may work for dealing with sessions, but it scales poorly, doesn't handle failed nodes well, and doesn't allow for more efficient (i.e. load based) load balancing.
Clustered File Systems:
By using a distributed file system, you can replicate your sessions across multiple nodes, and each node can have access to the sessions equally. A typical two node setup might include DRBD and OCFS2 - but you do encounter some difficulty setting up heartbeat and failover. A more resilient system might use GlusterFS, but adds considerable overhead. Both of these approaches may encounter some problems with file locking, although GlusterFS should work fairly well (it supports flock()).
RDBMs:
As you mention, it is possible to store sessions in MySQL (and PgSQL). Databases tend to be already installed, and available to multiple nodes, and support locking for atomic transactions. However, the feature set of a relational database is not really necessary for storing flat files, and may add some amount of unnecessary overhead. (PHP used to bundle the msession extension which, I believe, is no longer maintained).
NoSQL:
Recent key-value stores are well suited to storing PHP sessions. Previously, there may have been some difficulty with locking, and authentication but I believe most of these have been addressed. Examples in this category might include MongoDB and CouchDB.
Volatile Storage:
Some memory caches are well established and commonly used in distributed systems (e.g. Memcached, Redis). These key-value stores offer most of what is needed for session management, and memcached in particular is very easy to setup as a session store. However, these tend to have two major drawbacks - a) if the server storing the sessions goes down or needs to be restarted, the session data is lost, since it is stored in memory and b) as session data grows, the memory usage grows, which may result in old objects being removed from the cache.
A proposed solution:
Most of the good solutions will combine a cache with some persistent storage - to avoid excessive database load, but protect against loss of data. Unfortunately, these solutions do often require modifying PHP code to include a custom session_save_handler.
One good solution though, that does not require modifying PHP code is MemBase. It runs on the same protocol as memcached - making it easily configured for use as a session handler, but also provides persistence.
Essentially, the setup entails:

Download and install the MemBase application (binaries available in .deb and .rpm)
Configure the server (it has a web interface - not ideal, but it does the job)
Install the php5-memcached extension (but don't install memcached as it conflicts with MemBase)
Change your session.save_handler and session.save_path in php.ini to point to the MemBase server
Restart your web server, php-fpm, etc.
(a quick search finds this guide, which seems reasonable)

The approach should scale fairly well, you have control over the amount of memory used, the data is persistent, performance is good with minimal overhead, the setup is easy, and it does not require the alteration of any PHP code (just changing some php.ini settings).
Comment: Thanks for the response.  Rereading my original question, I think I left out some key things(question updated).  Yeah, I have a load balanced environment (EC2 based), and am trying to get my sessions to store in mySQL.  Right now I have sticky sessions in place, but obviously this creates problems whenever a server has to go down for any reason.  I'd like to be able to restart/stop/upgrade/crash/etc servers at any time without affecting the sites at all.  I'll check out MemBase.  It sounds like a good option.
Comment: @Talik: I think MemBase is a good solution - it can be built into clusters as well, but setting up automatic failover is a bit more of a challenge (but with a replicated cluster, shouldn't be as big of a concern) - manual failover is very easy to setup on it. I also quite like GlusterFS - especially in an environment where you also need the files to be available to all nodes, using a distributed file system caters to multiple purposes.
Answer: For anyone else interested in this, it looks like PHP has a setting that can be set through the ini file called auto_prepend_file.  This can be used to create a session handling script that will run for all websites without any modification to the site code itself.


jquery masonry/isotope like plugin that grows / shrinks elements based on importance

Question: Does anyone know of a jquery plugin that would stack elements like masonry or isotope and displays bigger / smaller elements based on importance? Could not find a way to do this with either of these mentioned plugins. Is there any plugin out there that does this ?
edit:
tried to make an image of what i need, numbers represent different weights that would make the rectangles fill more of less of their parent container.
Answer: I don't know of a plugin that does this out of the box, but you could take a tagcloud plugin and modify the CSS to make boxes bigger and smaller, rather than just the font size.
The drop that into a 960 grid system or any other masonry, and it will flow columns decently well. Everything might not line up on the right edge though.
To line things up on the right edge would take some more complex math than simply making things bigger and smaller. Currently the question does not specify how you want things to line up or display. Simply stacking elements is way easier than doing what isotope does.
Please clarify.
[Edit]
Oh, yeah, there is totally a plugin for that: http://bl.ocks.org/mbostock/4063582
"A treemap recursively subdivides area into rectangles; the area of any node in the tree corresponds to its value. This example uses color to encode different packages of the Flare visualization toolkit. Treemap design invented by Ben Shneiderman. Squarified algorithm by Bruls, Huizing and van Wijk. Data courtesy Jeff Heer."
Not the easiest thing to build, but this one was made with D3: https://github.com/mbostock/d3/wiki/Gallery
Comment: added an image that illustrates what i need. Your idea is actually cool, although, like you mentioned, it could be hard to line up stuff. When i say stack, i mean doing what isotope does, not with floats.
Comment: Thanks m8, thats exactly what i needed, only down side is that it depends on d3, but it's doable.


How can I setup RD Gateway on the same server as TMG?

Question: I have used the following guides with no luck:
http://www.rayheffer.com/953/building-a-remote-desktop-gateway-rdg-rd-gateway-server/
http://www.isaserver.org/tutorials/Microsoft-Forefront-TMG-Publishing-RD-Web-Access-RD-Gateway-Part2.html
We have MS TMG 2010 on Server 2008 R2 Standard. All we would like to do is allow home users (who have an AD account at work) connect to their own workstation at work over RDP. Essentially they would be using mstsc.exe from their home computer to do this.
We have to go over port 443 due to filtering of port 3389 on the ISP side. We don't want to use SSTP as Windows XP users won't be able to connect. So I decided to install RD Gateway on the server. We do want to use the same server as where TMG is on.
But even using the guides above, when we try to connect from home, we get:

Your computer can't connect to the remote computer because the remote desktop gateway server is temporarily unavailable.

We are getting so confused with setting this up and have spent weeks on it.
Sometimes we get:

Your computer can't connect to the remote computer because the Remote Desktop Gateway server address requested and the certificate subject name do not match. Contact your network administrator for assistance.

I have only installed the Remote Desktop Gateway role, not the Web Access one as we only want to use mstsc.exe from home.
Answer: Well, first of all don't use port 443, that's the default SSL port.  If you use a different port for RDP (your explanation doesn't ring true with me - I've never seen an ISP that filters port 3389, but I suppose anything's possible), then you should at least use a port that's not also in use by a common protocol or service.
Second of all, TMG lets you configure a Remote Access VPN.  This is what you probably should be doing instead of, or in addition to setting up a Remote Desktop Gateway.
Third, sounds like you'd benefit from hiring an experienced Windows SA to set this up for you, even if only on a contract or consultant basis.
Comment: Thanks. It does appear to be a 443 conflict. If I have ONLY the RD Gateway role installed, and not the RD Web role,  do I still need IIS 7 installed for RD Gateway functionality - assuming the client will only use mstsc.exe?
Comment: @name No.  IIS is not required for RD Gateway.
Comment: Thanks. This is so strange. I have IIS disabled completely. Only the RD Gateway role is installed. We have TMG on the same box. We have a 2nd external IP address assigned to the ext. interface. A TMG rule and listener are made, listening on that IP. When we connect from outside and specify the gateway in mstsc.exe, all that keeps happening is it keeps asking for our credentials over and over. Any ideas where I may be going wrong? Ta
Answer: You have to configure the MSTSC client for the RD Gateway. The easiest thing to do would be creating Connection Files for each Workstation and providing them for the end users. Asking them to configure a Gateway on their own is a bit much for typical users. Once you have the file configured it should be easy to copy it, edit it with notepad and change the workstation it's connecting to.


Rules: How to check one field against same field on all other nodes of that contenttype?

Question: Using Rules I would like to check the values of some fields.
I have a content type 'A' which has a custom field called 'address'. All nodes of content type 'A' are imported through Feeds.
I would like to create a rule where each node that is imported is checked, to verify if the value of field 'address' is equal to the value of field 'address' on any of my other nodes of type A.
I have read about 'Entity has field' as a Rules Condition. However I understand that this only checks several fields in the same node, while I want to check one field against all other nodes.
How can I accomplish this with Rules or any other method?
Comment: even if you could it in Rules (which I don't think you can), it would be much slower than writing a custom module to handle this
Comment: Would a custom module be better then a custom rule?
Comment: that really depends on how good you are at writing either :)  I don't think from a practical stand point either is 'better', a stand-alone module isn't reliant on Rules, but a custom Rule might be easier to write - efficiency really depends on your coding skill
Comment: @Pierre.Vriens Nope. A comment is just that, a comment based on what I knew at the time. Going back to make sure every piece of content is correct based on current information is pointless and indicative of severe OCD. Besides, I don't say it isn't possible, I just didn't think it was, hence a comment, and not an answer. It's still a valid comment.
Comment: @Geoff OK, good enough. Based on that, and combined with my answer to this question, it seems that we *disagree* then, since I think (actually I'm sure) you can ... even already from when this question was posted.
Comment: @Pierre.Vriens to continue this pointless conversation, I fail to see how we disagree - my original comment was almost 3 years ago. I never said I concur with my then comment, now. Only that there is little point in deleting it, since it can no longer be revised, and at the time, it was valid based on what I knew - I care not about what you know now or knew then, I'm sure lots of people knew more about it than me at the time, but that doesn't change my comment as written, when it was written
Answer: You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed below.
In what follows, I'm assuming that the machine name of your field is field_address (change to whatever fits).
Step 1 - Create a VBO view
Use the Views Bulk Operations (VBO) module to create a view of all relevant nodes, in which you should:

Add a VBO field to it.
Add a contextual filter for the field_address field for which you want to check that its value is unique. Make sure to correctly configure this contextual filter, similar to what is mentioned in this answer to "How to have a field that counts the nodes submitted by the current user?" (credits to Niall Murphy, merci!).

Include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.
Here is an export of such VBO view:
$view = new view();
$view->name = 'relevant_nodes';
$view->description = 'Produce a list of node ids that satisfy a specific filter';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Relevant nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Relevant nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Address */
$handler->display->display_options['fields']['field_address']['id'] = 'field_address';
$handler->display->display_options['fields']['field_address']['table'] = 'field_data_field_address';
$handler->display->display_options['fields']['field_address']['field'] = 'field_address';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Contextual filter: Content: Address (field_address) */
$handler->display->display_options['arguments']['field_address_value']['id'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['table'] = 'field_data_field_address';
$handler->display->display_options['arguments']['field_address_value']['field'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_address_value']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['field_address_value']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_address_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_address_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'relevant-nodes';

Step 2 - Create a Rule
Create a rule like so:

Rules Event: something like "Before saving content of type Article" seems most appropriate, though you can use any variation that fits.
Rules Condition: "Check number of results returned by a VBO view". And select the VBO view created in the previous step. In doing so, you will be asked to "specify arguments to pass to the view, one per line. You may use token replacement patterns.". The token to be entered there is node:field-address. If the number of results is 1 or more, then you know the value already exists. So within Minimum number of results you should enter the value 1.
Rules Action: this is pretty much up to your own imagination (your question doesn't specify what should happen ...). For example if the Rules Condition is TRUE, you could use "Set a data value", to set the value of that field to whatever fits. Maybe also display an appropriate message, such as (when trying to set the value to HomeIsWhereMyStellaIs):

The value "HomeIsWhereMyStellaIs" has already been used in at least 1 other node ...

Here is an export of a Rule that does (without such "Set a value" though) what is described above (if you have the Rules UI enabled, and a field with the machine name field_address, you should be able to just import this rule):
{ "rules_prevent_multiple_nodes_with_same_field_value" : {
    "LABEL" : "Prevent multiple nodes with same field value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "views_bulk_operations_condition_result_count" : {
          "view" : "relevant_nodes|page",
          "args" : [ "node:field-address" ],
          "minimum" : "1"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "The value \u0022[node:field-address]\u0022 has already been used in at least 1 other node ...",
          "type" : "error"
        }
      }
    ]
  }
}

Note that my Rules Event is limited to "Article" (change to whatever fits), and replace (prior to trying to import this rule) the machine name of field_address to whatever other machine name your field.
Done!
PS: I'm assuming this is about D7.


Is every quotient algebra of a Boolean algebra isomorphic to a subalgebra?

Question: Is every (non-trivial) quotient of a Boolean algebra isomorphic to a subalgebra of that Boolean algebra? And conversely is every subalgebra isomorphic to a quotient algebra?
Answer: For the first question, the answer is no, there are quotient algebras that cannot be embedded as subalgebras. Let's take $\newcommand{\powerset}{\mathcal{P}}\newcommand{\N}{\mathbb{N}}A = \powerset(\N)$, the ideal $I \subseteq A$ to be the set of finite subsets, and $B = A/I$. We need to show that $B$ is not a subalgebra of $A$.
We start by observing that $A$ has what is known as the countable chain condition, which is that if $(S_i)_{i \in I}$ is a pairwise disjoint family of non-zero elements of $A$, then $I$ is countable. This follows from the countability of $\N$.
We can therefore show that $B$ is not a subalgebra of $A$ by finding an uncountable pairwise disjoint family in $B$. We do this as follows. For each $n \in \N$, we write $\mathbf{digits}(n)$ for the finite sequence expressing $n$ in binary. For each infinite binary sequence $a \in 2^\N$, define $S_a \subseteq \N$ as:
$$
S_a = \{ n \in \N \mid \mathbf{digits}(n) \text{ is a prefix of } a\}
$$
As is well known, $2^\N$ is uncountable. Each $S_a$ is infinite, because each finite prefix of $a$ comes from some $n \in \N$, so the equivalence class $[S_a]$ is non-zero in $B$. Finally, if $a \neq b$ are elements of $2^\N$, they have only finitely many prefixes that are the same, so $S_a \cap S_b$ is finite, so the equivalence classes $[S_a]$ and $[S_b]$ are disjoint in $B$. So we have shown that $([S_a])_{a \in 2^\N}$ is an uncountable disjoint family in $B$, which would be a contradiction if $B$ could be embedded as a subalgebra of $A$.

For your second question, the answer is also no, there are subalgebras that are not isomorphic to any quotient. However, I was not able to make this example as elementary as the other one, so I will be using Stone duality and a bit of general topology.
Let's start again with $A = \powerset(\N)$, and define the subalgebra $B$ to consist of finite sets and cofinite sets, i.e. complements of finite sets. Assume for a contradiction that $B$ is representable as a quotient of $A$, so there is a surjective Boolean homomorphism $f : A \rightarrow B$. The Stone space of $A$ is $\beta \N$, the Stone-Čech compactification of $\N$, and the Stone space of $B$ is the "free convergent sequence", i.e. it is homeomorphic to the subspace $S = \{ 0, 1, \frac{1}{2}, \cdots, \frac{1}{n}, \cdots \} \subseteq \mathbb{R}$. The Stone dual of $f$ is a continuous injective map $g : S \rightarrow \beta(X)$. But as $\beta(X)$ is extremally disconnected, every convergent sequence is eventually constant, which is a contradiction.
Comment: Thanks, that was very helpful. (By the way, shouldn't it be called the countable *anti*chain condition? Is that standard terminology?)
Comment: The standard terminology is "countable chain condition" or "c.c.c.", even though it's about antichains (and therefore can mislead the newcomer). From time to time some people try to change it to "countable antichain condition" or "c.a.c." but this never seems to catch on.
Answer: This question gets right to the inner workings of Boolean algebras so I'm surprised nobody has answered it. I don't know the answer in general and would love to see a proof of a positive answer, or a counterexample!
For what it's worth I think I can show the answer is "yes" in both directions for finite Boolean algebras, and that something stronger than isomorphism holds. If $A$ is a Boolean algebra, and $Q$ is a quotient algebra of $A$ by some ideal, and $S$ is a subalgebra of $A$, let us say, for lack of a better word, that $Q$ "subsumes" $S$ when each $Q$-element (which is of course an equivalence class of $A$-elements) has exactly one element from $S$. If $Q$ subsumes $S$, the map taking each $Q$-member to its respective $S$-member is a (boolean) isomorphism onto $S$.
Claim: when $A$ is finite, every quotient algebra $Q$ subsumes some subalgebra $S$, and conversely every $S$ is subsumed by some $Q$.
First note that any finite boolean algebra $A$ is isomorphic to the power set of its atoms: the function mapping each $p \in A$ to the set of atoms $\leq p$ is a bijection, and the boolean operations on $A$ agree respectively with union, intersection, and complement on the power set of $A$'s atoms. Thus the finite boolean algebras can be characterized up to isomorphism as $\mathcal{P}(\{1, ..., n\})$ where $n$ can be any natural number $> 0$. (I am ignoring the one-element "degenerate" algebra.)
Second, note that a subalgebra of $\mathcal{P}(\{1,...,n\})$ is uniquely determined by its atoms, which together necessarily form a partition of $\{1,...,n\}$; and any such partition can serve as atoms for a subalgebra. A quotient of $\mathcal{P}(\{1,...,n\})$ by a nontrivial ideal is uniquely determined by that ideal's greatest element, which can be any nonempty subset of $\{1,...,n\}$.
Now let $Q$ be the quotient of $\mathcal{P}(\{1,...,n\})$ by some given ideal, which by the preceding paragraph must have a greatest element which can by any  nonempty subset $X \subseteq \{1,...,n\}$. Let $Z$ be any partition of $\{1,...,n\}$ such that each $e \in Z$ has exactly one member that is not in $X$. Then I think it should be easy to show that $Z$ is the set of atoms of a subalgebra $S$ that is subsumed by $Q$. Note that since $Z$ need not be unique in general for a given $Q$, $S$ need not be unique in general.
Conversely, when $S$ is any subalgebra of $\mathcal{P}(\{1,...,n\})$, and $Z$ is its set of atoms (which again can be any partition of $\{1,...,n\}$), let $X$ be any subset of $\{1,...,n\}$ such that for all $e \in Z$, $|X \cap e| = |e| - 1$. Then when $Q$ is the quotient by the ideal whose greatest element is $X$, $Q$ subsumes $S$.


How do i remove main menu title once it's in sidebar,

Question: Why is so dang difficult to style the main menu once you put in the sidebar in Drupal 7?!?
i also want to remove those annoying leaf classes!  first leaf, leaf, last leaf etc.
on the page template file i see the main nav code and where it spits out title, but in the same file,
all the side bar code is in one variable. how do i access that?,
i don't mind  php coding. can someone please advise how to do this?
big thanks in advance
Comment: Did you place it in the side bar via a Block?
Comment: yes i placed in SideBar
Comment: you can override a block's title by explicitly giving it a title of  . As for the classes, I believe you would need to override a hook as webkenny suggested.
Answer: Welcome to the wild world of theme functions, friend. You're going to need to do some overriding of the main menu in a file called "template.php" which should be included in whatever base theme you're using. Create a function in that file that looks something like this:
<code>function MYTHEMENAME_menu_link($variables){ // Code here }
</code>
Use this link as reference to understand how to change what's there: https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7
And for a real brain buster on everything you want to know about how to theme menus, check out this answer by Sheena, who's basically a genius: Advanced menu theming in Drupal 7


Why do I get two different mean values with two different methods for the same sample?

Question: I have this dataframe where I created the 3rd column using the first two columns. Both ${Y}$ and ${X}$  are independent random variables.

$\bar{Y}$
$\bar{X}$
$\bar{Z} = 100\frac{\bar{X}-\bar{Y}}{\bar{Y}}$

13435
13502
0.4987

21847
22354
2.3207

15584
18014
15.5929

17121
16738
-2.2370

18758
19664
4.8299

18994
22234
17.0580

22864
23555
3.0222

30365
31452
3.5798

29850
34808
16.6097

38674
38791
0.3025

47803
39717
-16.9153

88777
91756
3.3556

When I manually calculate the expectation of $\bar{Z}$ using the data in the 3rd column (in the above table) and pass it statistics.mean() function in Python, I get $E[Z] = 0.04.$
On the other hand, I know that I can calculate $E[Z]$  also as follows:
$E[Z] = E[100\frac{X-Y}{Y}] = 100E[\frac{X}{Y}-1] =100E[\frac{X}{Y}]-100 =100E[X]E[\frac{1}{Y}] -100 $ (as according to this link https://en.wikipedia.org/wiki/Ratio_distribution I can write $E[\frac{X}{Y}] =E[X]E[\frac{1}{Y}]$ )
but then I get $E[Z] = 33.75$ (since the mean of $\bar{X}$ and $\frac{1}{\bar{Y}}$ are $E[\bar{X}] =31048.75 $ and  $E[\frac{1}{\bar{Y}}] = 0.000043$, respectively.)
Apparently I get two very different mean values for $\bar{Z}$. When I do the same process for standart deviation, I again get very different values. So which approach should I use? Manually calculating using the 3rd row (by using Python's statistics library mean() and stdev() functions) or using the derivation formula?
In this study http://www.statistics.du.se/essays/D09_Zhang%20Ling%20&%20Han%20Kun.pdf, as far as I understood, they straightaway calculated mean and standard deviation by using the data in Percentage and Absolute columns.
I am really looking forward to some informative answers!
Thank you!
Answer: There are a couple of issues that can be addressed here.
First,
In general, the expected value of the product of two random variables does not need to be equal to the product of their expectation. This means that
$$ E(XY) \neq E(X)E(Y) $$
The equality only holds when the random variables are independent. But... This links directly to the second issue.
Second
Do not mix random variables with samples. The above property holds for independent random variables, but it is very much likely that the samples you display here are actually correlated, so you can't use above property on your samples.
Conclusion
For this reason, the correct result would be to compute the third column and then obtain the mean of that column. Or, if you want to use an alternative derivation, you could go as far as this:
$$E(z) = E(100\frac{x-y}{y}) = 100 E(\frac{x}{y}-\frac{y}{y})=100E(\frac{x}{y})-100$$
But $E(\dfrac{x}{y})\neq E(x)E(\dfrac{1}{y})$
Comment: If the samples were independent then both methods should provide exactly the same result. For this, I recommend you to always use the 3rd column approach and forget about the other way. It keeps things simpler. And yes, you should use the 3rd column also for the standard dev.
Comment: Also to calculate the standard error, again, the best I can do is calculating the 3rd row and computing the standard error of that row?
Comment: Thanks for the answer! Yes my samples are highly correlated such that I get 0.986014 and 0.98846 for spearman and pearson coefficient, respectively. So if my two samples were independent then I could always say ()=()(1/). Then which method would give me a better result?


Interchangability of expected value and integral only when $\mathbb E|X(t)| < \infty$ for a stochastic process $\{ X(t) \}$?

Question: In my textbook of Stochastic Process (in Chinese), I found a theorem as follows:

Theorem: If a stochastic process $\{ X(t), t \ge 0 \}$ has $\mathbb E|X(t)| < \infty$ and $\mathrm{var} X(t) < \infty$, then
$$\mathbb E \left[ \int_0^t X(s) \, ds \right] = \int_0^t \mathbb E [ X(s) ] \, ds, \\ \mathbb E\left[ \int_0^s \int_0^t X(v) X(u) \, du dv \right] = \int_0^s \int_0^t \mathbb E[X(v)X(u)] \, du dv$$

My textbook says this can be simply proved by applying Fubini's theorem.
But I am confused. To apply Fubini's theorem, we seem to need a condition like $\int_0^t \mathbb E |X(t)| < \infty$ as in this. Only $\mathbb E|X(t)| < \infty$ is really enough?
I doubt this, but I have no idea how to construct a counterexample. So I ask here, thanks for any help!
Comment: The argument would be valid if $X:[0,t]\times\Omega\rightarrow\mathbb{C}$ is jointly measurable
Comment: @OliverDíaz I am curious how does one apply Fubini here? Can you please provide a proof or at least some hint?
Comment: If $X$ is jointly measurable, then the proof is as you mentioned, an application of Fubini's theorem. Your textbook may be referring to a process that has some nice properties (cad lag process for instance) that make $X)t$ to be progressively measurable and so jointly measurable when restricted to $\Omega\timesp0,T]$
Comment: @OliverDíaz Yeah, joint measurability is needed and I think joint integrability is also needed, i.e., $\int_0^t \mathbb E|X(t)| < \infty$. Otherwise, I could give a counterexample (see my answer below).
Answer: If $X(s) \geq 0$ for all $s$ and jointly measurable then the conclusion is true. You can indeed swap the integral and expectation by Tonelli's theorem.
Further if $\int_{0}^t E(|X(s)|) <\infty$ (OR) $E \int_{0}^t |X(s)| <\infty$ then also the conclusion is true by Fubini-Tonelli's theorem.
https://en.wikipedia.org/wiki/Fubini%27s_theorem#:~:text=Fubini's%20theorem%20implies%20that%20two,one%20integrable%20over%20their%20domains.
See the above link for other versions.
Answer: The "theorem" is not correct. Here I could give a counterexample.
First, we can construct a discrete stochastic process $\{ Y_n, n \ge 1 \}$.
We consider $$\mathbb{P}(A) := \sum_{k \in A} 2^{-k}, A \subseteq \mathbb{N}^+$$ as the probability measure.
And define $$Y_n(k) := \left\{ \begin{array}{ll} 2^k, & k = n \\ -2^k, & k = n - 1 \\ 0, & \text{otherwise} \end{array} \right.$$
We could verify that $\{ Y_n, n \ge 1 \}$ satisfies the conditions in the "theorem": $$\mathbb E|Y_n| \le 2^k 2^{-k} + 2^k 2^{-k} = 2 < \infty$$ $$\mathrm{var} Y_n \le \mathbb E Y_n^2 \le 2^{2n} 2^{-n} + 2^{2n - 2} 2^{-(n - 1)} < 2^{n + 1} < \infty$$
However, $$\mathbb E \left[ \sum_{n = 1}^\infty Y_n \right] = \mathbb E \left[ k \mapsto Y_n(k) + Y_{n + 1}(k) \right] = \mathbb E [0] = 0$$
$$\sum_{n = 1}^\infty \mathbb{E}[Y_n] = 1 + \sum_{n = 2}^\infty \left( 2^k 2^{-k} - 2^{k - 1} 2^{-(k - 1)} \right) = 1 \not= \mathbb E \left[ \sum_{n = 1}^\infty Y_n \right]$$
$$\mathbb E\left[ \sum_{n = 1}^\infty \sum_{m = 1}^\infty Y_n Y_m \right] = \sum_{k = 1}^\infty (Y_k(k)Y_k(k) + Y_{k + 1}(k)Y_k(k) + Y_k(k)Y_{k+1}(k) + Y_{k + 1}(k)Y_{k + 1}(k)) \mathbb P(k) = 0$$
$$\sum_{n = 1}^\infty \sum_{m = 1}^\infty \mathbb E [ Y_n Y_m ] = \mathbb E [Y_1Y_2] + \mathbb E[Y_1Y_2] + \sum_{n = 2}^\infty (\mathbb E[Y_nY_{n - 1}] + \mathbb E[Y_nY_n] + \mathbb E[Y_nY_{n + 1}]) = -\frac{1}{2} \not= \mathbb E\left[ \sum_{n = 1}^\infty \sum_{m = 1}^\infty Y_n Y_m \right]$$
Second, we can show that it is possible to generalize this construction to the continuous stochastic process.
Define $$X(t) := \left\{ \begin{array}{ll} 0, & t = 0 \\ n(n + 1)Y_n, & t \in (\frac{1}{n + 1}, \frac{1}{n}] \end{array} \right.$$
Under this definition, $$\mathbb{E}|X(t)| \le \mathbb{E} \left| \frac{1}{t}\left(\frac{1}{t} + 1\right)Y_n \right| \le \frac{2(t + 1)}{t^2} < \infty$$ $$\mathrm{var} [X(t)] \le \mathbb E X^2(t) \le \mathbb E \left[ \left(\frac{t + 1}{t}\right)^2 Y_n^2 \right] < \left( \frac{t + 1}{t} \right)^2 2^\frac{t + 1}{t} < \infty$$
However,
$$\mathbb E \left[ \int_0^1 X(s) \, ds \right] = \mathbb E \left[ \sum_{n = 1}^\infty n(n + 1)Y_n \left( \frac{1}{n}
 - \frac{1}{n + 1} \right) \right] = \mathbb E \left[ \sum_{n = 1}^\infty Y_n \right] = 0$$
$$\int_0^1 \mathbb E [X(s)] \, ds = \sum_{n = 1}^\infty \mathbb E[n(n + 1)Y_n] \left( \frac{1}{n} - \frac{1}{n + 1} \right) = \sum_{n = 1}^\infty \mathbb E Y_n = 1 \not= \mathbb E \left[ \int_0^1 X(s) \, ds \right]$$
$$0 = \mathbb E \left[ \sum_{n = 1}^\infty \sum_{m = 1}^\infty Y_n Y_m \right] = \mathbb E \left[ \int_0^1 \int_0^1 X(v) X(u) dudv \right] \not= \int_0^1 \int_0^1 \mathbb E [X(v)X(u)] dudv = \sum_{n = 1}^\infty \sum_{m = 1}^\infty \mathbb E[Y_nY_m] = -\frac{1}{2}$$


$n \text{th}$ derivative of $f(x)$?

Question: Let $ \ f(x) \ = \ x^4  e^x \ $ .
Determine the nth derivative of $ \ f \ $ at $ \ x \ = \ 0 \ $.
I know by working it out that the first, second, and third derivative will be 1. The fourth, fifth, and onward derivatives will be 0.
However, the textbook answer is n(n-1)(n-2)(n-3).
I'm having difficulty understanding this, because according to that formula, the first, second, and third derivative will all equal zero, or am I misinterpreting it somehow?
Comment: I had to withdraw my earlier comment.  The first few derivatives equal zero at  $ \ x \ = \ 0 \ $ , but this does not continue to be the case.
Comment: Hint: Maclaurin Series.
Comment: Ah, in that case, I'm going to withdraw my previous comment to make myself look like less of an idiot haha
Comment: The power series approach is efficient, but is this a first- or second-semester calculus course?
Comment: Um, I'm not taking a course - I'm studying by working through this study manual ACTEX (P) By Broverman. This is just one question I didn't get in the first problem set. T_T I have a long way to go
Answer: How much calculus do you know?  The Taylor series of $e^x$ is $$\sum_{n=0}^\infty \frac{1}{n!} x^n$$ and the Taylor series of $x^4 e^x$ is thus $$\sum_{n=0}^\infty \frac{1}{n!} x^{n+4} = \sum_{n=4}^\infty \frac{1}{(n-4)!}x^n = \sum_{n=4}^\infty \frac{n(n-1)(n-2)(n-3)}{n!} x^n.$$
Since the first four coefficients of the Taylor series are zero, you have $$f(0) = f'(0) = f''(0) = f'''(0) = 0.$$ The remaining derivatives are given by he numerator in the Taylor expansion: $$f^{(n)}(0) = n(n-1)(n-2)(n-3).$$
Comment: I've taken up to Calc 3 - I didn't work too much with Taylor series so I had forgotten that you could do what you did in that second step. Is there a topic name or something I could look up on Pauls Online notes to get a refresher?
Comment: The relevant section of Paul's is in his Calculus II notes: http://tutorial.math.lamar.edu/Classes/CalcII/SeriesIntro.aspx  , in particular starting from "Power Series" -- http://tutorial.math.lamar.edu/Classes/CalcII/PowerSeries.aspx
Comment: Thank you RecklessReckoner!
Answer: Hint :Notice that $f(x)=x^{4}e^{x}=\sum\limits_{n=0}^{\infty}\frac{x^{n+4}}{n!}=\sum\limits_{n=4}^{\infty}\frac{x^{n}}{(n-4)!}$
Comment: Thank you! This makes sense to me after reading Umberto's post.
Answer: Note that you are only finding the derivative of $f$ at the point $x=0$. You will find that these derivatives have some $x$ term multiplying it for the first three derivatives, so it makes sense that the derivative is $x$ at $0$.
Comment: Oh, okay! Thank you, this makes sense to me now.

$n \text{th}$ derivative of $f(x)$?


reading 512 bytes at a time from a file and checking what's inside?

Question: I have a large file that contains a lot of jpegs inside. All jpegs need to be extracted one by one. Here are my first steps at  approaching this problem:
1) define "block" variable and allocate 512 bytes of storage to it
2) open file that contains all jpegs and loop through it until eof
3) grab first block (512 bytes) and see what's inside
Currently my code doesn't compile. Here are my errors:
 recover.c:27:19: error: implicitly declaring C library function
 'malloc' with type 'void *(unsigned int)' [-Werror]
     char* block = malloc(BYTE * 512);
                   ^ recover.c:27:19: note: please include the header <stdlib.h> or explicitly provide a declaration for 'malloc'
 recover.c:27:26: error: unexpected type name 'BYTE': expected
 expression
     char* block = malloc(BYTE * 512);
                          ^ recover.c:45:18: error: conversion specifies type 'int' but the argument has type 'char *'
 [-Werror,-Wformat]
         printf("%c", block);
                 ~^   ~~~~~
                 %s

This is my code so far:
#include <stdio.h>
#include <stdint.h>

typedef uint8_t BYTE;

//SOI - 0xFF 0xD8
//EOI - 0xFF 0xD9
//APPn - 0xFF 0xEn
int main(void)
{
    //FAT - 512 bytes per block
    char* block = malloc(BYTE * 512);

    //open file containing pictures
    FILE* fh = fopen("card.raw", "rd");

    //make sure the file opened without errors
    if (fh == NULL)
    {
        printf("something went wrong and file could not be opened");
        return 1;
    }

    while (!feof(fh))
    {
        setbuf(fh, block);
        printf("%c", block);
    }

    fclose(fh);
return 0;
}

What am I doing wrong? Why isn't char* block = malloc(BYTE * 512); allocating 512 bytes, but throws an error instead?
Also, since I can't even compile this piece yet, am I reading 512 bytes correctly? If not, how can I go about accomplishing this?
Thanks.
Comment: The first thing you do is include stdlib.h so there is a proper prototype for malloc() in scope.   Then, check the return value from malloc() to make sure it succeeds.  That should get you started on the proper path at least.
Comment: The error message tells you the exact problem; you need to `#include `.
Comment: There's no need to use `malloc()` at all in this code. Just declare `char block[512]`;
Answer: You want to:
#include <stdlib.h>

To get the definition of malloc().
char* block = malloc(BYTE * 512);

Should be (because malloc takes the argument in terms of bytes already; sizeof(BYTE) would return 1):
char* block = malloc(512);

And:
printf("%c", block);

Should be:
printf("%s", block);

And like EJP said in a comment, while this isn't an error, there isn't a real need for dynamically allocating the buffer with malloc(). You already know you will need 512 bytes for what you're doing, so you can replace that line with:
char block[512];

I take it you're using clang as your compiler, which as you can see is really helpful with it's error messages, it basically tells you how to fix it.
Comment: Thank you! No idea how I missed what compiler told me.


Are Magento Extensions off-topic?

Question: I have asked a couple of questions about Magento Extensions (specifically the Google API Content for Shopping one) and they keep getting put on hold / closed with a note saying the following:

This question appears to be off-topic because it is about a third party extension
This question does not appear to be about the Magento e-Commerce platform within the scope defined in the help center.

However, when I check the scope, it says:

Magento Stack Exchange is for users of and developers working with the Magento e-Commerce platform. Questions which involve custom code or extensions should include relevant code and, where applicable, an indication that the custom coder or extension vendor has been contacted for support.

This says to me that Extensions can be talked about.
I have tried adding comments to the answers, but I never get clarification. So can someone please explain to me what I am doing wrong?
Answer: With reference to the answer from Flyingmana (it won't let me post a comment for some reason!):

The extension was there not so long ago; I only installed it a few weeks ago. It must have been removed very recently.
I did do a search, and I couldn't find anything relating to my problem. Although it is the right product, your link doesn't relate to the error message I receive.

Re 1.9 compatibility, the answer didn't say it definitely did not work, just that "if the Module is not override any core functionality then It will work in 1.8 as well as 1.9."
I think I'm going to come at this from another direction...
Comment: thats probably because of not enough reputation...(upvote)
I referred to this question because of the answer "A new version of Content API was introduced on June 6th http://googleadsdeveloper.blogspot.co.uk/2014/06/the-new-improved-content-api-for.html "
Answer: I think one reason for closing all those extension related questins was one way to filter the massive amount of questions after the forums got closed.
The other is that for some extensions it is indeed impossible to answer for third party developers without studying the code first. So in this case it would heavily depends on how specific the question is and if all required code snippets and the version information are part of the question, and if the extension author was contacted first.
Maybe policy will change again once some new forum thing is online as promised.
Comment: It does seem a bit odd to close extension-related questions when this forum is supposed to support them!

Also, my question wasn't about solving a problem with the code. I just didn't know how to use it! I also confirmed that I contacted the extension author - Magento themselves - who have ignored my request for help. Considering I am using a very popular extension - Google API Content for Shopping - I am somewhat disappointed that this semi-official support forum are not only not willing to provide help, but are actively stopping me from getting it!
Answer: I looked into the question about "Google Content API for Shopping" Magento Extension
First: I dont even find this extension anywhere, so no idea how to validate your problem
Second: you did not even try to use the search before, did you?
Google Content API for Shopping not adding all products
Also in another question you already found out, that the module is not supported for anything newer then 1.7

Are Magento Extensions off-topic?


How to create service accounts in Snowflake

Question: How can a service account be created in snowflake?
What parameters of a user can tell whether an account is a service account or not in snowflake?
Comment: You may look at the following article which details how the service account is used in Snowflake and how to secure them :
The following 3 blog articles would give details on this as :
https://www.snowflake.com/blog/snowflake-service-account-security-part-3
Answer: One way is to use a standard naming convention for service users and create these users so that they utilize key pair authentication using the RSA_PUBLIC_KEY parameter.


Powershell DSC File copy - Workgroup machines

Question: I've got a machine that I need to copy files to from a network share (on domain) for a deployment from a machine that's off domain.
Currently I have the following code;

Configuration deployWebsite
{
  param
  (
  [string[]] $MachineName = "localhost"
  )

  Node $MachineName
  {

    File Test {
      SourcePath = "\\buildserver\mywebsite"
      DestinationPath = "C:\deployments"
      Recurse = $true
      Type = "Directory"

    }
  }
}
deployWebsite -MachineName "at-test-2012"

I run this and I'm able to generate a MOF file which is fine.
The error I get is as follows;

PS C:\dsc> Start-DscConfiguration -Path .\deployWebsite -CimSession $sess -Wait -Verbose -Force
VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsof
t/Windows/DesiredStateConfiguration'.
VERBOSE: An LCM method call arrived from computer AT-TEST-2012 with user sid S-1-5-21-77344112-180879520-4075690869-1002.
VERBOSE: [AT-TEST-2012]: LCM:  [ Start  Set      ]
VERBOSE: [AT-TEST-2012]: LCM:  [ Start  Resource ]  [[File]Test]
VERBOSE: [AT-TEST-2012]: LCM:  [ Start  Test     ]  [[File]Test]
VERBOSE: [AT-TEST-2012]:                            [[File]Test] Access is denied.
VERBOSE: [AT-TEST-2012]:                            [[File]Test] The related file/directory is: \\buildserver\mywebsite.
VERBOSE: [AT-TEST-2012]:                            [[File]Test] The path cannot point to the root directory or to the root of a net share.
VERBOSE: [AT-TEST-2012]:                            [[File]Test] The related file/directory is: \\buildserver\mywebsite.
VERBOSE: [AT-TEST-2012]:                            [[File]Test] SourcePath must be specified if you want to configure the destination directory recursively. Make sure that SourcePath is a di
rectory and that it is accessible.
SourcePath must be specified if you want to configure the destination directory recursively. Make sure that SourcePath is a directory and that it is accessible.
    + CategoryInfo          : InvalidArgument: (:) [], CimException
    + FullyQualifiedErrorId : MI RESULT 4
    + PSComputerName        : at-test-2012

The SendConfigurationApply function did not succeed.
    + CategoryInfo          : InvalidArgument: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : MI RESULT 4
    + PSComputerName        : at-test-2012

VERBOSE: Operation 'Invoke CimMethod' complete.
VERBOSE: Time taken for configuration job to complete is 3.979 seconds

The CIM session seemed to be setup fine.

PS C:\dsc> Get-CimSession

Id           : 1
Name         : CimSession1
InstanceId   : 7ae9cd9b-fc65-4879-94c1-ec9805479500
ComputerName : at-test-2012
Protocol     : WSMAN

It was created with the following code;

$sess = New-CIMSession -cn at-test-2012 -Authentication Credssp -Credential $cred

And it was passed credentials for a user that is local admin over the workgroup machine and is a local user on the domain machine its trying to pull files from.
If I try another test by creating a PSSession, and trying to copy the files then it works fine and I see the files appear on the workgroup machine.

$cred = Get-Credential -Credential deployuser
$sess = New-PSSession -cn at-test-2012 -Authentication Credssp -Credential $cred

Invoke-Command -Session $sess -ScriptBlock {Copy-Item -Path '\\buildserver\mywebsite' -Destination 'C:\deployments'}

The problem being that Start-DscConfiguration doesn't appear to support PSSessions, only CIMSessions.
So, any pointers on what to try next? I think my CIMsession is setup correctly and I think I have all the necessary settings on the fileshare, workgroup machine all set correctly as the PSSession works fine.
Cheers,
Andy
Comment: The error send to indicate that a file test source path can't be the root of a network share.  \\buildserver\mywebsite would seen to qualify.
Comment: Even if i specify the full path to a folder or file it generates the same error. It still seems to be more of a permissions error as it generates an "access denied" message. What is unclear though is why the script doesn't appear to be using the credentials supplied to it.
Comment: Try adding both server names to the cimsession
Comment: Just to ensure that the cimsession works can you try the following command:    Get-DscLocalConfigurationManager -CimSession $sess
Answer: Typically I approach a problem like this in one of three ways:

Create a scheduled task on the remote machine with explicit
credential, to do the Start-DscConfiguration locally.  It will run
exactly as local user for purposes of the next hop in remoting.
Consider creating and using a JEA endpoint.  This is more
complicated, but heads you down the path towards simplifying
the ongoing credential management of managing remote machines.
You may be able to create a mapped drive to the remote share with
explicit creds using something like a Script resource

Beware doing remote Start-DscConfiguration if you have additional configurations that may do network affecting changes.
For instance, creating the previously mentioned JEA endpoints via the JustEnoughAdministration resource can reset WinRM and prematurely interrupt both local and remote Start-DscConfiguration calls that -Wait.
The scheduled task is immune to both network affecting issues within the Configuration, as well as simple network flakiness from other environment factors.  The big trick is if you need to then monitor for the stabilization of the configuration, which is an exercise for the reader (or a future question/answer.)


Webfrom : Having two textfield boxes inline .

Question: What I need to do is have two input boxes next to each other.  As it's to except data that comes in two parts.  I can do this with CSS but using inline errors causes me problems. Has anyone done this or have any ideas on a solution.

Drupal 7 - webfrom 7.x-4.9+2-dev
Comment: Not really sure what your error is. If you define the two wrapping containers to be displayed inline, flexbox or via float (using css) it will not cause any errors with the processing itself. You also don't need to define your css inline, I would have it in a seperate stylesheet. However, there is a module called Field Groups where you can create a fieldset, div etc. to place the fields in. This makes putting two containers into one row, relatively easy as you isolate them from other input field containers.
Answer: You can easily accomplish this using the Webform Layout module.
This module allows you to arrange fields into rows or columns.


When is null useful?

Question: Nowadays we have Guava's Optional and builder pattern. Every book/blog says to avoid nulls. We have to use them when dealing with legacy code or protocols that explicitly require it. But are there any other use cases when it's useful or when it's the best option?
Comment: Worth noting that Java 8 has its own [`Optional`](http://download.java.net/jdk8/docs/api/java/util/Optional.html).
Answer: It is useful for uninitialised variables.  Whether it is useful as a valid value is another question which depends on your programming model.  For example, if you have a model where you aim to produce little or no garbage, Optional is not an option and null produces no garbage.
In extreme cases, your target might be to produce 1 GB/hour or as low as 1 GB per day of garbage.  This allows you to run for a day or a week without a minor collection.
In "normal" Java programming, a lack of use of one of these wrappers it likely to be due to laziness.  It is more effort, for little perceived gain (as I never intend to write NPE into my code)  What would be useful is tools like your IDE filling in this code for you. e.g. IntelliJ will tell you if you have a value which could be null and cn introduce runtime checks.
Comment: I like _`Optional` is not an option_. P.S. the Java 8 `Optional` produces less garbage.

When is null useful?


NGINX Rewrite subdomain with multiple . as -

Question: On my NGINX server, I am rewriting usernames as a subdomain. However, the server that I inherited, the initial names have a "." to separate out two names.
For example: http://foo.com/john.smith is being rewritten as http://john.smith.foo.com.
Due to the wildcard ssl certificate, it's causing havoc displaying images or returning a certificate error due to the multiple "."
How do I rewrite john.smith.foo.com as john-smith.foo.com? Here's the beginning of the subdomain rewrite
server {
listen 443 ssl;
server_name ~^(.*)\.<%=rootdomain.replace(".", "\\.")%>$;
set $subdomain  $1;

Answer: You can construct a server block to match domain names with an embedded ..
For example:
server {
    listen 443 ssl;
    server_name  "~^(?<prefix>.+)\.(?<suffix>.+)\.example\.com$";
    return 301 $prefix-$suffix.example.com$request_uri;
}

But this will still cause trust errors if the wildcard certificate is not valid for the original domain name.


Difference between Univariate Linear Regression and Simple Linear Regression?

Question: Is there any difference between Univariate Linear Regression and Simple Linear Regression? If so, what is the difference exactly? It seems both of them are exactly same. I would appreciate if anyone could cite a scientific paper that defines Univariate Linear Regression.
Comment: Uni means one, simple regression refers to examining the relationship of one explanatory variable on one dependent variable. Both univariate and simple linear are the same.
Comment: [This google books search gives many book hits ](https://www.google.com/search?tbm=bks&q=%22Univariate+Linear+Regression%22++) for "https://www.google.com/search?tbm=bks&q=%22Univariate+Linear+Regression%22++"
Answer: A good start (I hope uncontentious) on this is simply to note that univariate, bivariate and multivariate denote focus on one, two or many variables respectively. (Other words such as trivariate can be found but seem much more rarely used and rarely needed.)
Then it might follow that univariate techniques are those for which only one variable is needed (e.g. calculating mean or median, drawing a histogram); bivariate techniques are those which two variables are needed (e.g. correlation); while multivariate techniques are those for which many variables are needed, or (similarly if not identically) those which can be applied to many variables at once. Many and two sometimes overlap as when principal component analysis could be applied to two variables, not just many. (Or even one...)
I'd say that regression without qualification implies just one outcome or response variable, whereas multivariate regression implies two or more outcome or response variables (although regression with one predictor could naturally be seen as a special case).
Historically multiple regression has been used to refer to any set-up with several predictor variables and in contrast simple regression can be used when only one predictor is used. I'd assert, as a mixture of personal impressions from reading and personal opinions about good terminology, that references to multiple regression are fading slowly (it's routine in many fields, scientifically, statistically and computationally, and long since not very special) and that neither term, multiple or simple, fills an important gap.
A clear distinction in literature between multiple and multivariate regression doesn't stop multivariate being misused for multiple, a common confusion often seen on this site.
So much context, now the question:
The expression univariate regression seems to have crept into informal discussions fairly recently. Can anyone cite a good textbook reference? (*) I'd presume that it could only mean one outcome, one predictor. So it's at best redundant or a term for the simplest kind of regression. It's also at odds with the idea that such regression is a bivariate technique.
(*) The original question over 5 years ago as I write asked for scientific paper references, which no-one seems to have provided. I don't have one either.
Comment: +1. I've increasingly seen the word "multivariable" used instead of "multiple" in papers describing a regression model with more than one predictor variable. As you state, the incorrect "multivariate" is used quite frequently as well.
Comment: @COOLSerdash Indeed; I should have mentioned that too, but no matter given your spot-on comment.
Answer: Purist view: In general, there is clear difference between those two terms.
Univariate might have e.g. two explanatory variables (or five etc.) but always just one response variable. But it can also have just one expl. variable. In that scenario it is a simple linear regression as well.
Now, the question remains whether simple linear regression can have multiple response variables. According to Wikipedia (citing multiple text books), no, although not stated explicitly. (Subquestion: Can regression have more response than explanatory variables?)
Practical view: If you have one response variable (univariate) and multiple explanatory ones, you should call it (univariate) multiple regression. Wherever you have more than one variable, you need to be explicit about it. Otherwise one variable is expected, thus the term univariate is redundant.
In conclusion, univariate r. and simple linear regression describe (most likely) the same kind of regression, but in most cases it will not make sense to use the former term. (The opposite is only true when you contrast it with multivariate regression.)
Answer: Simple Linear Regression is defined in as model with a single explanatory variable (i.e., the independent variable).
According to this answer,, Univariate Linear Regression refers to a model with a single response variable (i.e., the dependent variable). This answer corroborates the theory.
Now, here is a claim that says Simple regression necessarily has a single dependent variable too, but I cannot verify the claim. A model with one explanatory variable and more than one response variable will still be called simple (and multivariate), I think.
I have seen the terms 'Simple' and 'Univariate' used interchangeably, and was under the impression that there is no difference. But I reckon it is best to keep that distinction.
Comment: thanks. If both of them are exactly same, then I can use scientific paper which defines the simple linear regression.
Comment: I have made an edit to the post, after finding evidence that went against my original belief.
Answer: Univariate Model :

Simple :  1 DV & 1 IV

Multiple: 1 DV & many IV

Multivariate Model:

Simple Multivariate: many DV & 1 IV
Multiple Multivariate: many DV & many IV


It's possible to pass a variable on attach_library in a template on Drupal 8?

Question: I need to pass a variable to a library called on a Twig template, is this possible?
<code>{{ attach_library('theme/some-library') }}
</code>
Comment: You want a variable that will be read as Javascript in the client's browser? You could print a script tag with the variable. And the library would read it from the DOM.
Comment: You could also do this from a preprocess hook.
Comment: Right, I was wondering if there was a more fancy way of doing it.
Answer: .module
<code>/**
 * Implements hook_ENTITY_TYPE_load()
 */

function my_module_node_load($nodes) {
    foreach ($nodes as $node) {
      if ($node->getType() == 'article') { // is of article content type
        $data_passer = &drupal_static('my_module_node_field_name');
        // use &drupal_static to pass value between hooks.
        $data_passer = $node->field_name->value;
      }
    }
}

/**
 * Implements hook_page_attachments()
 */
function my_module_page_attachments(array &$attachments) {
    if (!empty(&drupal_static('my_module_node_field_name'))) {
      $data_passer = &drupal_static('my_module_node_field_name');
      $node_field_name = $data_passer;
      $attachments['#attached']['drupalSettings']['my_variable'] = $node_field_name;
    }
  }
}
</code>
.js
<code>(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_behaviour = {
    attach: function (context, settings) {

      alert(drupalSettings.my_variable); //alerts passed in node field_name

    }
  };
})(jQuery, Drupal, drupalSettings);
</code>
Comment: Thanks, but I was wondering if there is a way of doing it directly from the template, although I ended up using a preprocess hook.
Comment: @Flupkear from template file there isn't, unless you print the value in an attribute and then pick it up with jQuery. Ex: ` {{ content.field_some_field }} ` and in jQuery `var variable = $('.something').attr('variable');`
Answer: I have passed my variable in twig like this:
<code>{{ attach_library('theme/library' ~ variable ) }}
</code>