string vibrato: before/during/after beginning of sound production?

Question: I have heard from more than one string educator that in order to create a warm tone, it is helpful to begin vibrato motion in the left hand before producing sound with the bow.
However, I have also (less frequently) heard that doing so in a group can cause pitch issues. Here are two quotes from Wikipedia's Vibrato page for illustration:

"Wind and bowed instruments generally use vibratos with an extent of less than +/- half a semitone." (50 cents)
"Many contemporary string players vary the pitch from below, only up to the nominal note and not above it, although great violin pedagogues of the past such as Carl Flesch and Joseph Joachim explicitly referred to vibrato as a movement towards the bridge, meaning upwards in pitch..."

So suppose that we have two players, one who starts their vibrato up and one who starts down. Let's be conservative, and say that they only vibrate +/- 25 cents from the center of the ideal pitch. If they play the same note and begin vibrating BEFORE they play, there is a chance that their audience will not hear the same note, but rather two notes 50 cents apart. Unpleasant.
On the other hand, Wikipedia also cites a 1996 study by the Acoustical Society of America (with Wellesley and MIT) which found that the perceived pitch of a note with vibrato "is that of its mean", or the middle of the fluctuating pitch.
And so I ask you: When starting vibrato before creating sound with the right hand, does this cause pitch problems in the split second the sound is beginning to be pulled? Or does this idea of perceived vibrato pitch from the ASA mean that it doesn't matter where the initial pitch is placed so long as the vibrato is correctly centered? Does the fact that this pitch difference exists for a very small amount of time trivialize its magnitude?
Then again, the sine function spends most of its time near its maximum and minimum values; so we could say that, given similar but opposing vibrato speeds, the amount of time the pitch difference is heard is relatively large.
It seems to me that this pitch problem can be avoided if the vibrato is started (centered) in the exact instant (or shortly after) the sound begins to be pulled. But I can't tell if my concern is unfounded, nor can I necessarily articulate what starting with a centered vibrato, even after sound production, would do to fix my problem.
Comment: The mean is not  necessarily the mid point.  I think that distinction is critical to understanding how pitches with vibrato are perceived
Answer: I think you're definitely magnifying the problem beyond it's perceptibility, vibrato is generally much too fast for the instantaneous difference to be heard at all. In fact, it's generally much easier to be in tune with vibrato than without. The natural fuzziness of a vibrated pitch generally makes it blend more pleasingly and there's nothing more difficult than playing perfectly in tune during non vib sections. Vibrato speed, depth, onset and offset should vary throughout a piece based on musical considerations, and I don't think it's possible to reduce it to anything so concrete as the Wikipedia quote's focus on averages.
It's important to note that minute differences in pitch add depth and warmth to a sound—perfect intonation at the frequency level is impossible, but also undesirable. That's why most piano notes are produced by three strings (which can't possibly be tuned identically) and a section of cellos or violins sounds so much thicker and warmer than a solo. [that piano point I crossed out is incorrect, see David's comments below]
Edit to add: I can think of one exception. If you are entering quietly (loud attacks add noise partials that will obliterate any pitch differences) in unison (not octave probably, I mean literal unison) with one other instrument (3 or more players should mitigate most issues), then you might want to coördinate a bit more carefully. Such situations are rare, but they can be a real intonation nightmare.
Comment: Yes, forced resonance works only within a given tolerance.  It's actually a nuisance for tuners since it may mask the minute details of tuning.
Comment: Piano strings hold pitch rather well and are mechanically coupled, so of course forced resonance where all three strings vibrate synchronously is quite feasible even if the strings, when struck alone, would have minute pitch differences.
Comment: Hmmm, interesting. But then why, when a piano goes out of tune, do individual keys become 2– and 3–note clusters? Does the coupling only work within a certain tolerance?


Dictionary of words and their translation in JavaScript

Question: Consider the simple following HTML code:
<input id="dict_field" type="text"/>
<button id="translate_btn" type="button" class="btn">translate</button>

The user inputs something and clicking the button triggers a function that returns a translation.
And the JQuery code:
$(document).ready(function(){

  $('#translate_btn').click(function(){
    var word = $('#dict_field').val();
    var translation = "";
    translation = translate(word (, dictionary?));
    // For simplicity for now just display the result in the same input field
    $('#dict_field').val(translation)
  });

});

// pseudo code. How to implement this and build the dictionary I need?

function translate(word (, dictionary?)){
  if word in dictionary.keys() -> return dictionary[word]
  else return "no such word in dict"
}

Given the following:

The translation needs only to be one way (key to value).
The dictionary is custom made (meaning I have to build it, I cannot count on external API such as Google's).
I estimate the size of the dictionary keys could be of the order of thousands, say between 1 and 5000.
Not sure if related but eventually I'd like the translation to happen in real time (as soon as the user finishes the input without need of a button click). This for now is secondary.

What is a good way, "objectively", to build a map/dictionary {key:value} to implement a translation function/API? Any detail can be considered, such as speed, scalability, cost etc., keeping in view my above requirements.
I've little experience with this kind of things, but I have some thoughts, such as:

Use a very long js file containing the dictionary (might not be a good idea)
Store everything in a text file and read from there
Look at some database (but won't that be overkill?)

Appreciate valuable suggestions. Thanks for any help.
Comment: The dictionary would contain words only? And do you plan to add more description, helping material, links etc. along with translation?
Comment: Just use a JSON file with whatever structure suits you.
Comment: Good point. For now I think  words only should be fine (eg just a translate('foo') = 'bar'). Obviously the more flexible the better I guess should I in the future decide to add more to it.
Comment: Is the question still too broad after the kind edit by @TalhaAwan?
Comment: @Tommy, I don't know how and when on hold is removed after edit. I think the answer to the question will still be opinion based but it's really a good question. I wanted to answer that but I can't now. Maybe try another well-directed question. If you do so, tag me here. Thanks
Answer: Store it as a text file, e.g. CSV.
foo,bar
baz,quux

Then fetch it with ajax, and split it. You can optimize this, but not likely required.
var dict = text
  .split('\n')
  .map(function(x) { return x.split(',') })
  .reduce(function(acc, pair) { acc[pair[0]] = pair[1]; return acc }, {});

Then dict['bar'] === 'quux'.
Comment: @Tommy Accumulator
Comment: Thanks again for the answer. So I can fetch the dict right, but dict[key] returns undefined. Any ideas why?
Comment: Got it! I think it should be acc[pair[0]] = pair[1].
Comment: @Tommy yep, my mistake, updated.
Comment: No worries, it's good it actually forced me to understand what I was doing. :) one thing, forgive the silly question but what does "acc" stand for?
Comment: Makes sense. Thank you.
Answer: You can use an object {"key":"value"} or an array of arrays [["key", "value"]] or an array or array of objects [{"key":"value0"}, {"key":"value1"}]; where the latter two would allow more than one definition for the same word, to handle equivocal languages; and the ability to include metadata relating to the word or term within the array or object, for example an audio representation of the spoken word.


add js particule in header

Question: I tried to add the particle effect in javascript, on a project but I don't really know javascript
html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Леда</title>
    <link rel="stylesheet" href="style.css">

      ADVENTURE

About

Services

Support

Infos

Contact

css
* {
    margin: 0;
    padding: 0;
    text-decoration: none;
    list-style: none;
}

header {
    background-image: url('landscape.jpg');
}

header {
    height: 100vh;
    width: 100vw;
    background-size: cover;
}

.navbar {
    position: absolute;
    padding: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    box-sizing: border-box;
}

.navbar a {
    color: white;
}

.navbar .nav-links ul {
    display: flex;
}

.navbar .nav-links ul li {
    margin: 0 25px;
}

.navbar .nav-links ul li.active a {
    margin: 0 25px;
    font-weight: 600;
}

.navbar .menu-navbar{
    display: none;
    position: absolute;
    width: 35px;
}

@media screen and (max-width: 900px) {
    .navbar {
        padding: 0;
    }

    .navbar .logo {
        position: absolute;
        top: 37px;
        left: 50px;
    }

    .navbar .menu-navbar {
        display: block;
        top: 30px;
        right: 50px;
    }

    .nav-links {
        top: 0;
        left: 0;
        position: absolute;
        background-color: rgba(255, 255, 255, 0.233);
        width: 100%;
        height: 100vh;
        backdrop-filter: blur(7px);
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: -100%;
        transition: all 0.5s ease;
    }

    .nav-links.mobile-menu {
        margin-left: 0;
    }

    .nav-links ul {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .navbar .nav-links ul li {
        margin: 25px 0;
        font-size: 2em;
    }
}

#particle-canvas {
    width: 100%;
    height: 100%;
  }

js
const menuHamburger = document.querySelector(".menu-navbar")
const navLinks = document.querySelector(".nav-links")

menuHamburger.addEventListener('click', () => {
    navLinks.classList.toggle('mobile-menu')
});

!function (a) { var b = "object" == typeof self && self.self === self && self || "object" == typeof global && global.global === global && global; "function" == typeof define && define.amd ? define(["exports"], function (c) { b.ParticleNetwork = a(b, c) }) : "object" == typeof module && module.exports ? module.exports = a(b, {}) : b.ParticleNetwork = a(b, {}) }(function (a, b) { var c = function (a) { this.canvas = a.canvas, this.g = a.g, this.particleColor = a.options.particleColor, this.x = Math.random() * this.canvas.width, this.y = Math.random() * this.canvas.height, this.velocity = { x: (Math.random() - .5) * a.options.velocity, y: (Math.random() - .5) * a.options.velocity } }; return c.prototype.update = function () { (this.x > this.canvas.width + 20 || this.x < -20) && (this.velocity.x = -this.velocity.x), (this.y > this.canvas.height + 20 || this.y < -20) && (this.velocity.y = -this.velocity.y), this.x += this.velocity.x, this.y += this.velocity.y }, c.prototype.h = function () { this.g.beginPath(), this.g.fillStyle = this.particleColor, this.g.globalAlpha = .7, this.g.arc(this.x, this.y, 1.5, 0, 2 * Math.PI), this.g.fill() }, b = function (a, b) { this.i = a, this.i.size = { width: this.i.offsetWidth, height: this.i.offsetHeight }, b = void 0 !== b ? b : {}, this.options = { particleColor: void 0 !== b.particleColor ? b.particleColor : "#fff", background: void 0 !== b.background ? b.background : "#1a252f", interactive: void 0 !== b.interactive ? b.interactive : !0, velocity: this.setVelocity(b.speed), density: this.j(b.density) }, this.init() }, b.prototype.init = function () { if (this.k = document.createElement("div"), this.i.appendChild(this.k), this.l(this.k, { position: "absolute", top: 0, left: 0, bottom: 0, right: 0, "z-index": 1 }), /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(this.options.background)) this.l(this.k, { background: this.options.background }); else { if (!/\.(gif|jpg|jpeg|tiff|png)$/i.test(this.options.background)) return console.error("Please specify a valid background image or hexadecimal color"), !1; this.l(this.k, { background: 'url("' + this.options.background + '") no-repeat center', "background-size": "cover" }) } if (!/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(this.options.particleColor)) return console.error("Please specify a valid particleColor hexadecimal color"), !1; this.canvas = document.createElement("canvas"), this.i.appendChild(this.canvas), this.g = this.canvas.getContext("2d"), this.canvas.width = this.i.size.width, this.canvas.height = this.i.size.height, this.l(this.i, { position: "relative" }), this.l(this.canvas, { "z-index": "20", position: "relative" }), window.addEventListener("resize", function () { return this.i.offsetWidth === this.i.size.width && this.i.offsetHeight === this.i.size.height ? !1 : (this.canvas.width = this.i.size.width = this.i.offsetWidth, this.canvas.height = this.i.size.height = this.i.offsetHeight, clearTimeout(this.m), void (this.m = setTimeout(function () { this.o = []; for (var a = 0; a < this.canvas.width * this.canvas.height / this.options.density; a++)this.o.push(new c(this)); this.options.interactive && this.o.push(this.p), requestAnimationFrame(this.update.bind(this)) }.bind(this), 500))) }.bind(this)), this.o = []; for (var a = 0; a < this.canvas.width * this.canvas.height / this.options.density; a++)this.o.push(new c(this)); this.options.interactive && (this.p = new c(this), this.p.velocity = { x: 0, y: 0 }, this.o.push(this.p), this.canvas.addEventListener("mousemove", function (a) { this.p.x = a.clientX - this.canvas.offsetLeft, this.p.y = a.clientY - this.canvas.offsetTop }.bind(this)), this.canvas.addEventListener("mouseup", function (a) { this.p.velocity = { x: (Math.random() - .5) * this.options.velocity, y: (Math.random() - .5) * this.options.velocity }, this.p = new c(this), this.p.velocity = { x: 0, y: 0 }, this.o.push(this.p) }.bind(this))), requestAnimationFrame(this.update.bind(this)) }, b.prototype.update = function () { this.g.clearRect(0, 0, this.canvas.width, this.canvas.height), this.g.globalAlpha = 1; for (var a = 0; a < this.o.length; a++) { this.o[a].update(), this.o[a].h(); for (var b = this.o.length - 1; b > a; b--) { var c = Math.sqrt(Math.pow(this.o[a].x - this.o[b].x, 2) + Math.pow(this.o[a].y - this.o[b].y, 2)); c > 120 || (this.g.beginPath(), this.g.strokeStyle = this.options.particleColor, this.g.globalAlpha = (120 - c) / 120, this.g.lineWidth = .7, this.g.moveTo(this.o[a].x, this.o[a].y), this.g.lineTo(this.o[b].x, this.o[b].y), this.g.stroke()) } } 0 !== this.options.velocity && requestAnimationFrame(this.update.bind(this)) }, b.prototype.setVelocity = function (a) { return "fast" === a ? 1 : "slow" === a ? .33 : "none" === a ? 0 : .66 }, b.prototype.j = function (a) { return "high" === a ? 5e3 : "low" === a ? 2e4 : isNaN(parseInt(a, 10)) ? 1e4 : a }, b.prototype.l = function (a, b) { for (var c in b) a.style[c] = b[c] }, b });

// Initialisation

var canvasDiv = document.getElementById('particle-canvas');
var options = {
    particleColor: '#888',
    interactive: true,
    speed: 'medium',
    density: 'high'
};
var particleCanvas = new ParticleNetwork(canvasDiv, options);

I copied and pasted the entire code but it gave me a problem. It covered my image and the navbar in blue and I can't see anything except a blue page with the particles. What needs to change in the code so that we see the image and the navbar and that the click on the navbar works.
Answer: Everything seems to be working OK except your canvas with the particles on it is 'on top' of the other stuff.
If you make the canvas go back (in the z axis sense - that is the axis that is orthogonal to the screen) then the header is seen.
Make canvas have z-index: -1;

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Леда</title>
  <link rel="stylesheet" href="style.css">

      ADVENTURE

About

Services

Support

Infos

Contact

Comment: @A Haworth ok thanks i don't really know javascript what i need to change so that the canvas is transparent or leave this blue color ?
Comment: @A Haworth for leave this color   #1a252f because i have 3 files, style.css script.js and index.php when i copy past your code in file index.php i don't see the particules, and when i copy your code in my 3 files this don't change i dont see my pictures or when i click in navbar (in mobile version) it's not open the menu
Comment: Sorry, I am very confused by your comment. All I was suggesting that you do is alter the z-index of the canvas. Where exactly are you putting that?
Comment: @A Haworth check i have host check result
http://test11789456ttt.42web.io/?i=1# the canvas is above all the site but I would like it to be in the background. Because look when I put in mobile version we do not see the menu and the navbar
Comment: Plese use your browsers devtools inspect facility to see exactly what/where is putting the background on the various divs and what their z-indexs are. The scenario in your live site is slightly different from the snippet of code you provided.
Comment: @A Haworth
 in my computer do the same but ok

add js particule in header


When does Stinespring dilation yield a faithful representation?

Question: Let $A$ be a $C^*$-algebra, $H$ a Hilbert space, $\phi: A \to B(H)$ a completely positive map.  The Stinespring construction yields a triple $(K, V, \pi)$ where $K$ is a Hilbert space, $V: H \to K$ a bounded linear map with $\|V\|^2 = \|\phi(1)\|$, and $\pi: A \to B(K)$ a *-representation satisfying $V^* \pi(\cdot) V = \phi(\cdot)$.  The triple $(K, V, \pi)$ becomes unique up to unitary equivalence once we impose the minimality condition $\overline{\pi(A) VH} = K$.
I'm interested in what conditions on $\phi$ are equivalent to (or at least imply) the faithfulness of the representation $\pi$.  Here are a few observations:

Clearly, faithfulness of $\phi$ implies faithfulness of $\pi$, since any operator with a nonzero compression is perforce nonzero.
The converse fails; for instance, if $\phi$ is a vector state on $M_2(\mathbb{C})$ (so $H$ is one-dimensional), then $\phi$ is not faithful, but Stinespring (=GNS) yields the identity representation.
It is possible for $\pi$ not to be faithful.  For instance, if $A = C(X)$ for a compact Hausdorff space $X$, if $\phi$ is the state induced by a probability measure supported on a proper subset $E$ (so again $H$ is one-dimensional), and if $f \in A$ is supported on $X \setminus E$, then $\pi(f) = 0$.  Similarly, if $A = A_1 \oplus A_2$ and $\phi = \phi_1 \oplus 0$, then $\pi(0,a_2) = 0$.

In general, just by following through the details of the Stinespring construction, it looks like $\pi(a) = 0$ is equivalent to
$$
\forall b \in A: \, \phi(b^* a^* ab) = 0
$$
so that faithfulness of $\pi$ would be equivalent to the statement
$$
\forall a \in A:
\Big( \, \forall b \in A: \, \phi(b^* a^* ab) = 0 \Big) \Rightarrow a =0
$$
or equivalently, of course,
$$
\forall a \in A: \, a \neq 0 \Rightarrow \exists b \in A: \, \phi(b^* a^* ab) \neq 0.
$$
Is there a nicer way to say this, or a way to relate it to named/more easily understood properties of $\phi$?
Comment: You might want to rephrase you question to make it about a *minimal* Stinespring dilation. Otherwise, the same $\phi$ can have different $\pi$s with different properties.
Comment: Two comments: firstly, you form $K$ as the completion of $A\otimes H$ for a pre-inner product $(a\otimes\xi|b\otimes\eta) = (\phi(b^*a)\xi|\eta)$.  So I get a more complicated condition than the one you have.  Secondly-- can you give an answer when $\phi$ is just a state?  It strikes me that there is no particularly "nice" answer even in this case...
Comment: @MatthewDaws Silly me, forgetting about mixed tensors!   I think the formula I wrote down is correct for a state, so you're right, even in that case there may not be a simple answer.
Answer: If $A$ is a von Neumann algebra and $\phi$ is normal, we can define $\textrm{car}\phi$ to be the least projection such that $\phi(\textrm{car}\phi)=\phi(1)$. Note that $\phi$ is faithful if and only if $\textrm{car}\phi=1$.  Your condition is (in this case) equivalent to $C_{\textrm{car}\phi}=1$, where $C_{\textrm{car}\phi}$ is the least central projection above $\textrm{car} \phi$:

Proposition. If $\phi \colon A \to B$ is any completely positive map between von Neumann algebras, then
$$ \forall a \in A. \bigl(\forall b \in A. \phi(b^*a^*ab)=0\bigr) \Rightarrow a=0 \qquad\qquad (*)
 $$
  is equivalent to $C_{\textrm{car} \phi}=1$.

Proof. First some preparation. Write $p = \textrm{car} \phi$.  By Zorn's lemma, find a maximal family of orthogonal projections $(q_i)_{i \in I}$ from $A$, each Murray-von Neumann weaker than $p$.   Then $\sup_{i \in I} q_i = C_p$, see point 1 and 2 in proof of Theorem 28 of [1].  For each $q_i$ pick a $v_i$ such that $v_iv_i^*=q_i$ and $v_i^*v_i \leq p$.  (As an example, if $A=B(l^2(\mathbb{N}))$ and $p=\left|0\right>\!\!\left<0\right|$, then one can pick $I=\mathbb{N}$, $v_i=\left|i\right>\!\!\left<0\right|$ and $q_i=\left|i\right>\!\!\left<i\right|$.)
Assume $C_p=1$.  We will prove $(*)$.
To this end, assume for each $a \in A$ and for each $b \in A$
we have $\phi(b^*a^*ab)=0$.
In particular $\phi(v_i^* a^* a v_i)=0$. Without loss of generality, we may assume $a^*a \leq 1$ and then by the previous $v_i^* a^* a v_i \leq 1-p$.
So $q_i a^*a q_i = v_iv_i^* a^* a v_iv_i^* \leq v_i (1-p) v_i^* = v_iv_i^* - v_iv_i^*= 0$.  Hence $a^*a \leq 1-q_i$ for each $i \in I$.  So $a^*a \leq 1- \sup_i q_i=1-C_p=0$. By the C$^*$-identity, $a=0$.  Thus $(*)$ holds.
For the converse, assume $(*)$ holds.
Clearly for each $b \in A$,
we have
$$b^* (1- C_p) b= (1-C_p) b^*b (1-C_p) \leq \| b \|^2 (1- C_p) \leq \| b \|^2 (1-p)$$
and so $\phi(b^* (1-C_p)^*(1-C_p)b)=0$.  By $(*)$ now $1-C_p=0$ and so $C_p=1$, as desired. QED
[1] Paschke Dilations, Westerbaan & Westerbaan http://arxiv.org/pdf/1603.04353v1.pdf


Training a Bernoulli model using probabilities as inputs

Question: I'm using two methods to train a Bernoulli model, and am trying to understand why they are not yielding similar results. For both methods, I have a length $N$ array of probabilities $\{\hat{y}^{(n)}\}_{n=1}^{N}$, and I want to estimate the distribution of a length $N$ array of parameters $\{\theta^{(n)}\}_{n=1}^{N}$. In method (1), for each $\hat{y}^{(n)}$, I sample $M$ times from a Bernoulli distribution with probability $\hat{y}^{(n)}$, and use the resulting binary data as the input to my model. In method (2), I use $\hat{y}^{(n)}$ directly by incrementing the log joint density using the following update rule:
$
 \begin{equation*}
  \begin{split}
  \log p(\mathbf{y} \mid \boldsymbol{\theta}) &= \sum_{n=1}^{N} \log p(y^{(n)} \mid \theta^{(n)})\\
  &\approx \sum_{n=1}^{N} \frac{1}{M} \sum_{m=1}^{M} \log p(y^{(n)}_m \mid \theta^{(n)})\\
  &\approx \sum_{n=1}^{N} E_{y^{(n)}_m}[\log p(y^{(n)}_m \mid \theta^{(n)})]\\
  &= \sum_{n=1}^{N} E_{y^{(n)}_m}\left[\log({\theta^{(n)}}^{y^{(n)}_m} \cdot (1 - \theta^{(n)})^{1 - y^{(n)}_m})\right]\\
  &= \sum_{n=1}^{N} E_{y^{(n)}_m}\left[y^{(n)}_m \log(\theta^{(n)}) +  (1 - y^{(n)}_m) \log(1 - \theta^{(n)})\right]\\
  &= \sum_{n=1}^{N} \Pr(y^{(n)}_m = 1) \log(\theta^{(n)}) + \Pr(y^{(n)}_m = 0) \log(1 - \theta^{(n)})\\
  &= \sum_{n=1}^{N} \hat{y}^{(n)} \log(\theta^{(n)}) + (1 - \hat{y}^{(n)}) \log(1 - \theta^{(n)})
  \end{split}
 \end{equation*}
$
I'm using Stan, where you specify the log joint density incrementally using each data point. Pseudocode for these two methods looks like this:

I expect methods (1) and (2) to yield similar estimates for $\theta$ for large $M$, but I'm finding this to not be the case. I've reproduced this issue on a small toy problem using Stan, here is the code:
<code>import matplotlib.pyplot as plt
import numpy as np
import pystan

def get_theta_mean(fit):
    samples = fit.extract()
    theta = np.moveaxis(samples['theta'], 0, -1)
    return theta.mean(axis=1)

rng = np.random.RandomState(0)
N = 100
probs = rng.uniform(0, 1, N)

binary_model = '''
data {
    int<lower=0> N;
    int<lower=0> M;
    int<lower=0, upper=1> y[M, N];
}
parameters {
    real<lower=0, upper=1> theta[N];
}
model {
    for (m in 1:M) {
        y[m] ~ bernoulli(theta);
    }
}
'''
binary_sm = pystan.StanModel(model_code=binary_model)

M_list = [10, 100, 1000]
theta_means = {}

for M in M_list:
    y = np.full((M, N), np.nan)
    for m in range(M):
        for n in range(N):
            y[m, n] = rng.binomial(1, probs[n])
    y = y.astype(int)

    binary_fit = binary_sm.sampling(
        data={'N': N,
              'M': M,
              'y': y})

    theta_means[M] = get_theta_mean(binary_fit)

prob_model = '''
data {
    int<lower=0> N;
    real<lower=0, upper=1> yhat[N];
}
parameters {
    real<lower=0, upper=1> theta[N];
}
model {
    for (n in 1:N) {
        target += lmultiply(yhat[n], theta[n]) + lmultiply(1 - yhat[n], 1 - theta[n]);
    }
}
'''
prob_sm = pystan.StanModel(model_code=prob_model)
prob_fit = prob_sm.sampling(
    data={'N': N,
          'yhat': probs})

prob_theta_mean = get_theta_mean(prob_fit)

for M, theta_mean in theta_means.items():
    plt.scatter(theta_mean, probs, label=f'Method (1), M={M}')
plt.scatter(prob_theta_mean, probs, label='Method (2)')
plt.grid(True)
plt.xlabel(r'$E[\theta]$')
plt.ylabel('Probability')
plt.legend()
</code>
Here is a scatterplot of the results I get on the toy problem. (1) is supposed to better approximate (2) as $M$ is increased, eventually converging to $E[\theta^{(n)}] = \hat{y}^{(n)}$. (1) seems to follow this, but (2) is significantly off.

UPDATE:
I realized there is an error in line one of my derivation above, and that method (2) actually represents
$
 \begin{equation*}
   \begin{split}
   \log p(\vec{y} \mid \theta) &= \sum_{n=1}^{N} \log p(y^{(n)} \mid \theta^{(n)})\\
   &\approx \sum_{n=1}^{N} \log\left(\frac{1}{M} \sum_{m=1}^{M}  p(y^{(n)}_m \mid \theta^{(n)})\right)
   \end{split}
 \end{equation*}
$
I changed method (1) to reflect this, and now my results between method (1) and (2) are consistent, and neither of them satisfy $E[\theta \mid D] \approx \hat{y}$.
Comment: Hi. Please give more detail when you say you're ``finding this to not be the case''. What is your choice of $M$? Are you sharing information between each value of $\theta$ with a prior? If so what is that prior? I note also from step (1) in your pseudo code that you're not dividing by M at each increment. It seems like you should be.
Comment: @psboonstra I've attached a plot that shows the results of estimating $\theta$ using these two methods for various values of $M$. I am using a flat prior for $\theta$. I agree that the log densities are off by a constant amount based on there being $M$ times more data points in (1), but I wasn't sure whether this is a problem since (1) appears to recover $\theta$ more accurately for larger $M$ without any adjustments. (2) is supposed to be like (1) with $M = \inf$, but seems to be off systematically.
Comment: Thanks. Yes, I see now that failing to scale by M will artificially decrease your uncertainty intervals, since it is tantamount to making up data, but it will not impact your point estimates. Your plot shows posterior means (I believe) only. Second, according to your plot, the problem is with Method 2, or how it is coded. You are using a [continuous Bernoulli model](https://en.wikipedia.org/wiki/Continuous_Bernoulli_distribution), which is fine but a bit of an usual model for the data. I suggest to limit to one datapoint only for computational efficiency, and share the actual STAN model block
Comment: @psboonstra That's correct, the x-axis is the posterior mean. I added the code, including the Stan model block. binary_model is method (1), and prob_model corresponds to method (2). I tried running this code for small N, and I find it a bit difficult to visualize the issue this way, since the estimates for (2) seem correct for probabilities close to 0.5. I also tried modifying (2) to incorporate the $C(\lambda)$ constant in the continuous Bernoulli pdf that you shared. This seems to bring method (2) slightly closer to (1), but it's still not similar.
Comment: I actually think your first approximation was fine: for the continuous Bernoulli distribution, the log-density evaluates to $x\log(\theta) + (1-x) \log(1-\theta)$, and for the discrete Bernoulli distribution, the average of $M$ log-densities evaluates to $(1/M)\sum_m [x_m\log(\theta) + (1-x_m) \log(1-\theta)] = \bar x_M\log(\theta) + (1-\bar x_M) \log(1-\theta)$, $\bar x_M$ will approach $x$ in probability. As I argue in my answer, the issue is that you need to scale by $M$.
Answer: Update My original answer below applies to your original approximation. With respect to your modified approximation, which is different but also a sensible approximation, the issue of scaling by $M$ or not doesn't matter anymore, because then it just becomes a constant shift in the log-posterior (you are essentially deciding whether to add a constant $-\log (M)$). The results, which are the same between Method 1 and Method 2, don't match your intuition because of a shrinkage effect, which I discuss below.
Original answer
Method (2) is giving the expected results; Method (1) is coded incorrectly because it is not scaled by $M$. If you scale each added increment to the log-posterior by $M$, then you will get similar results for large $M$. In more detail:
Method (2) is using a model based upon the continuous Bernoulli distribution. The posterior means you are finding seem to be correct; the issue is that there is very little data and so the results are largely prior-driven. For example, I ran an adapted version of your code for $N=1$ and $\hat y=0.25$. Here is a histogram estimating the posterior distribution of $\theta$, with a red line indicating the value $\hat y = 0.25$:

The posterior mean of $\theta$ is a shrinkage estimator of the observed data $\hat y = 0.25$ and the prior mean 0.5 (things look 'correct' in that case when you have $\hat y = 0.5$ because the data are exactly equal to the prior mean). But the mode of the distribution is approximately at the place you would expect.
As your mathematical derivation suggests, Method (1) should yield approximately equal inferences for large enough $M$. However, by not scaling by $M$, you are artificially creating a great deal of data, which is having the effect of overwhelming the prior (In a comment, I suggested this shouldn't affect point estimates, but I misspoke). See below for two posterior histograms corresponding to Method (1) using $M = 500$, one which properly scales by $M$ and another which does not $M$. You'll observe that the lack of scaling by $M$ creates an extremely tight, and inappropriately confident, distribution around the observed data.
Comment: Thank you, so it turns out that (2) was actually working as intended, but my intuition was wrong. I'll need to rethink some of my choices, such as my priors.


how can i find my public facing ip from python program not proxy

Question: I want to find my public ip adress from python program.
So far this is the only site
http://www.whatismyip.com/
and
http://whatismyip.org/
which gives ip without proxy rest all give the proxy.
Now .org site is using image and first one writes ip across many span elements so i can't grab with urllib.
Any other idea or site so that i can get my ip
Comment: Did you try http://jsonip.com/. That will save you some html/xml parsing
Comment: What do you mean by "not proxy"? Only some proxies reveal your actual IP address.
Answer: I usually use http://httpbin.org/:
import requests

ip = requests.get('http://httpbin.org/ip').json()['origin']

Comment: i got 'dict' object is not callable
Comment: @user22: You're using an old version of requests. Upgrade or change `.json()` to `.json`.
Answer: Use lxml
import urllib
import lxml.html

u = urllib.urlopen('http://www.whatismyip.com/')
html = u.read()
u.close()

root = lxml.html.fromstring(html)
print ''.join(x.text for x in root.cssselect('#greenip *'))


Magical Record persistance issue

Question: I have following Problem:
First up... i use MagicalRecord for the whole CoreData thing

I have two Entities: A and B
They have a relation between each other
I create one instance of Entity A
I create several instances ob Entity B and set the relation
I don't call [[NSManagedObjectContext defaultContext] save];

It's fine
The relation is ok... I can check it using the findByAttribute method

If I call this save then the relation is destroyed...

the same check using findByAttribute does not find results any more

I have absolutely no clue what I am doing wrong or if it's a bug in CoreData / MagicalRecord...
I made a sample project showing the problem.
https://github.com/bliblablo/MagicalRecordsProblem
You can see the problem by following this steps:

click "create"
click "add"
click "check"
see the log output for results
click "save"
click "check" again and see the problem in the log :)

Any help is really appreciated!!!
Thanks a lot!
Comment: Where is the sample project? I can tell you with confidence that it won't be a bug in Core Data!
Comment: Sorry... I just updated my problem description. Here's the link: https://github.com/bliblablo/MagicalRecordsProblem
Answer: Sounds like the problem I was having with temporary ObjectID's not getting refreshed in the default context.
See my answer on NSPredicate not executed for details.
If you haven't already sorted it out, try checking the ObjectID of the NSManagedObject instances at various points.  Especially if you (or Magical Record) are using the object as part of an NSPredicate to do the later fetches.
Comment: Thank you Otto...
I worked around my problem by using a unique ID that I got from the webservice where the data comes from...
So instead of calling "fetch everything where the parent is this object", I now use "fetch everything where the parent.uniqueID is this objects uniquID".

This worked for me!
But thanks for your explanation! Really appreciate it!
Comment: This is rather a workaround than a real solution, I guess. What really bothers me is that if you perform a "reset" before fetching the data, even using the 'fetch everything where the parent is this object' will work. So, definitely a Core Data (or MagicalRecord) bug. I'd love to try to completely wipe out this helper and to have fun the old-fashioned way.
Comment: @FabianoFrancesconi I'm sure it's not a Magical Record but.  I'm reasonably sure it is actually a bug in Core Data.  I may still be misunderstanding what I'm supposed to be doing (listening for notifications, maybe?) but this works well enough. :)
Comment: Isn't it weird that only me and you have this kind of troubles? I mean, this is rather flashy bug. I think we are stucked in some sort of malpractice here.. I'm worried because the application seems to work now but it may happens that later in the future it may suddenly stop and we would have to go back and reconsider what we did.
Comment: There's at least 3 of us. :)  I am slightly worried, but I debugged it the first time, I can do it again.  I plan to make sure I'm on the latest Magical Record before shipping, just to be sure.
Comment: Best I can figure, maybe we're not giving Core Data enough credit and it would lazy load the whole NSSet that comes back from the association method.  But then I still don't have an NSFetchedResultsController.
Answer: I think this is not MR bug. It is a bug from core data. See this post.
http://wbyoung.tumblr.com/post/27851725562/core-data-growing-pains

Magical Record persistance issue


$\{(x_n, y_n)\}^\infty_\mathrm{n=1}$ in $(X \times Y, d_3)$ converges to a point $(\overline x, \overline y)$ in $(X \times Y)$

Question: Suppose that $(X, d_1)$ and $(Y, d_2)$ are metric spaces. We can then form the Cartesian product $X \times Y$, which is the set of all ordered pairs of the form (x,y) where $x\in X$ and $y\in Y$. We can also introduce a metric $d_3$ on $X \times Y$ by setting $(\forall x_1, x_2 \in X)(\forall y_1, y_2 \in Y)$ $$d_3((x_1,y_1)(x_2, y_2)) = d_1(x_1,x_2) + d_2(y_1,y_2)$$
I'm trying to prove that a sequence in $\{(x_n, y_n)\}^\infty_\mathrm{n=1}$ in $(X \times Y, d_3)$ converges to a point $(\overline x, \overline y)$ in $(X \times Y)$ if and only if:
(1) the sequence $\{x_n\}^\infty_\mathrm{n=1}$ converges to $\overline x$ in $X$
(2) the sequence $\{y_n\}^\infty_\mathrm{n=1}$ converges to $\overline y$ in $Y$
I don't think you would have to verify that $d_3$ is a metric, but I have no idea where to even begin.
Comment: It's not hard to prove that $d_3$ is a metric given that $d_1$ and $d_2$ are, but if this is an introductory real analysis class, that may be expected.
Comment: My point was that I don't think verifying $d_3$ is a metric space is useful (or necessary) because it can be assumed from given info, as you said. This is based on ideas from undergraduate real analysis texts, not any specific problem.
Comment: Can you more specifically describe what you are asking?
Comment: You have a sequence $(x_n, y_n)$ in the cartesian product space $ (X \times Y, d_3)$ that converges to a point $(\overline x, \overline y)$. I'm trying to prove that this can only be the case if $(x_n)$ converges to $\overline x$ in $X$ and $(y_n)$ converges to $\overline y$ in $Y$.
Answer: Suppose $ x_n \to \bar{x}$ and $ y_n \to \bar{y} $. Take your desired $ \varepsilon >0 $. By the two convergences there exist $ N_1, N_2 \in \mathbb{N}$ such that $$ \forall n > N_1 \quad d_1(x_n, \bar{x}) < \frac{\varepsilon}{2} \\ \forall n > N_2 \quad d_2(y_n, \bar{y}) < \frac{\varepsilon}{2} $$
taking $ N=\max\{N_1, N_2\} $, this means that we would have
$$ \forall n > N \quad  d_3\big((x_n,y_n), (\bar{x}, \bar{y})\big) = d_1(x_n, \bar{x}) + d_2(y_n, \bar{y}) < 2 \times \frac{\varepsilon}{2} $$
and therefore $ (x_n, y_n) \to  (\bar{x}, \bar{y}) $.
Conversely, suppose that one of the the two sequences doesn't converge to it's point, say $ \{x_n\} $ doesn't converge to $\bar{x}$. This means that there exists some $ \varepsilon_0>0 $ for which
$$ \forall N \quad \exists n > N \quad \mathrm{s.t.}  \quad d_1(x_n, \bar{x}) > \varepsilon_0 $$
but this means that we also have
$$ \forall N \quad \exists n > N  \quad d_3\big( (x_n,y_n), (\bar{x}, \bar{y}) \big) = d_1(x_n, \bar{x}) + d_2(y_n , \bar{y})> \varepsilon_0$$
since $ d_2(y_n , \bar{y}) $ is non-negative. And therefore $ (x_n, y_n) \not\to (\bar{x}, \bar{y})$.
Answer: Suppose the sequence $\{(x_n,y_n)\}$ converges to $(\bar{x},\bar{y})$ in  $(X\times Y, d_3)$. Then given $\varepsilon>0$, there exists a posituve integer $N$ such that
$$
d_3((x_n,y_n),(\bar{x},\bar{y})=d_1(x_n,\bar{x})+d_2(y_n,\bar{y})< \varepsilon \quad \forall n>N.
$$
It follows that
$$
d_1(x_n,\bar{x})< \varepsilon \quad \forall n>N,
$$
and
$$
d_2(y_n,\bar{y})< \varepsilon \quad \forall n>N,
$$
i.e. the sequence $\{x_n\}$ converges to $\bar{x}$ in  $(X, d_1)$ and the sequence $\{y_n\}$ converges to $\bar{y}$ in  $(Y, d_2)$.
Now, suppose $\{x_n\}$ converges to $\bar{x}$ in $X$ and  $\{y_n\}$ converges to $\bar{y}$ in $Y$. Given $\varepsilon>0$, there exist positive integers $N_1$ and $N_2$ such that
$$
d_1(x_n,\bar{x})< \frac{\varepsilon}{2} \quad \forall n > N_1
$$
and
$$
d_2(y_n,\bar{y})< \frac{\varepsilon}{2} \quad \forall n > N_2.
$$
Let $N=\max(N_1,N_2)$. For all $n>N$, we have
$\displaystyle d_1(x_n,\bar{x})< \frac{\varepsilon}{2} $ and  $\displaystyle d_2(y_n,\bar{y})< \frac{\varepsilon}{2} $, and
\begin{eqnarray}
d_3((c_n,y_n),(\bar{x},\bar{y}))&=&d_1(x_n,\bar{x})+d_2(y_n,\bar{y})\cr
&<&\frac{\varepsilon}{2}+\frac{\varepsilon}{2}\cr
&=&\varepsilon
\end{eqnarray}
i.e.
$$
d_3((c_n,y_n),(\bar{x},\bar{y}))<\varepsilon \quad \forall n>N
$$
meaning that $\{(x_n,y_n)\}$ converges to $(\bar{x},\bar{y})$ in $X\times Y$.


Powershell: reference an object property in another object property from within the same object?

Question: Evening folks, just a small question, if it a possibility.
I know I can do it by calling it as an empty object then adding properties one by one.
$Obj = New-Object PSObject
$Obj.name = "hello"
$Obj.type = $Obj.name '+' "world"

Is there a way to do this as one property line?
$Obj = New-Object PSObject -Property @{
Name = "hello"
Type = $Obj.name '+' "world"
}

Comment: You can do it with a class but what's the problem you're trying to solve? What is stopping you from doing just `Type = 'hello' + 'world'` in your example?
Comment: It's mainly a curiosity thing but. Specifically I have an object where I define the installer as getting the most recent file in the folder. And then I pull the installer version and instead of copying the code again for that property I'd like to just reference the property
Comment: Well you can do it with a class but it wouldn't look the same as you have. The argument would only be what you're using for `name`
Answer: This might help you accomplish what you're looking for using a PowerShell class:

Definition

class SomeClass {
    [string] $Name
    [string] $Type

    SomeClass() { }
    SomeClass([string] $Name, [string] $Type) {
        # ctor for custom Type
        $this.Name = $Name
        $this.Type = $Type
    }

    static [SomeClass] op_Explicit([string] $Name) {
        # explicit cast using only `Name`
        return [SomeClass]::new($Name, $Name + 'World')
    }
}

Now you can instantiate using a custom value for the Type:
PS ..\> [SomeClass]@{ Name = 'hello'; Type = 'myCustomType' }

Name  Type
----  ----
hello myCustomType

Or let the explicit operator handle the predefined value for the Type property based on the Name argument:
PS ..\> [SomeClass] 'hello'

Name  Type
----  ----
hello helloWorld

Comment: Thanks for the info! And something for me to give a look into. Appreciate it!
Answer:
Santiago Squarzon's helpful answer shows how to solve your problem via defining a class that creates a dedicated .NET type.
However, you can avoid creating a dedicated .NET class using the following workaround, which uses an auxiliary variable and the fact that enclosing a variable assignment in (...) passes an assignment's value through:
$obj = [pscustomobject] @{
  Name = ($name = 'hello')  # assign 'hello' to $name and pass the value through
  Type = $name + 'world'    # use the value assigned to $name above
}

Note: This relies on the order of property definitions: derived property values must be placed after the ones in which the aux. variables are defined.
Outputting $obj to the display prints:
Name  Type
----  ----
hello helloworld

See also:

GitHub issue #13782, which asks for a built-in mechanism for internally cross-referencing the entries of hashtable, which could equally apply to a custom-object literal.
Comment: Thanks a lot!, that's a great and simple workaround which is easy to maintain :-)


Connected sets and separations

Question: Respect to this Prove that a connected space cannot have more than one dispersion points. , I couldn't proof the first item:

Suppose that $p$ is a dispersion point of $X$. $X∖\{p\}$ is totally disconnected, so in particular it is not connected, and there is therefore a non-empty $H⫋X∖\{p\}$ such that $H$ is clopen in $X∖\{p\}$. Let $K=(X∖\{p\})∖H$, the other member of the separation of $X∖ \{p\}$.
Show that $H∪\{p\}$ is connected. HINT: If $A$ and $B$ are a separation of $H∪\{p\}$ with $p∈B$, what can you say about the sets $A$ and $K∪B$?

Ok. Since $A$ and $B$ are a separation of $H\cup\{p\}$, then, by defintion,

$A\cap B=\emptyset$.
$A=A_1\cap(H\cup\{p\})$ and $B=B_1\cap(H\cup\{p\})$, with $A_1,B_1$ open (or closed) in $X$, and
$H\cup\{p\}=A\cup B$\

Then, it is easy to show that $A\cup(K\cup B)=X$ and $A\cap(K\cup B)=\emptyset$. Now, since $p\in B$, then $K\cup B\neq\emptyset$. So, if $A$ and $K\cup B$ are open (or closed) in $X$, there would be a separation of the connected space $X$. Therefore $A=\emptyset$ and thus $H\cup\{p\}$ is connected. But I can't prove the fact that $A$ and $K\cup B$ are open (or closed) in $X$.
Any help or hint is welcome.
Answer: $H$ is open in $X\setminus\{p\}$, which is open in $X$, so $H$ is open in $X$. Similarly, $K$ is open in $X$, so $H\cup\{p\}$ is closed in $X$. $A$ is closed in $H\cup\{p\}$ so $A$ is closed in $X$. Finally,
$$A=A_1\cap\big(H\cup\{p\}\big)=A_1\cap H$$
is the intersection of two open sets in $X$ and so is open in $X$. Thus, $A$ is clopen in $X$, and you have your contradiction.
This argument does require that $\{p\}$ be closed in $X$. Since I tend to assume that all spaces under discussion are $T_1$ unless otherwise stated, I probably unconsciously made this assumption when I wrote my answer to the question to which you linked. However, it is possible with a bit more work to give a proof that does not require this assumption.

Lemma. Let $x\in X$ be arbitrary, let $Y=X\setminus\{x\}$, and suppose that $H\subseteq Y$ is clopen in $Y$; then $X\setminus H$ is connected.
Proof. Suppose that $X\setminus H=A\cup B$, where $A\cap B=\varnothing$, $A$ and $B$ are clopen in $X\setminus H$, and $x\in A$. Since $H$ is open in $Y$, there is an open $U$ in $X$ such that $H=U\cap Y=U\setminus\{x\}$; clearly $U=H$ or $U=H\cup\{x\}$. Similarly, there is a closed $C$ in $X$ such that $H=C\cap Y=C\setminus\{x\}$, so $C=H$ or $C=H\cup\{x\}$. Let $W_A$ be an open set in $X$ such that $A=W_A\cap(X\setminus H)$; $x\in W_A$, so
$$W_A\cup H=W_A\cup U\;,$$
which is open in $X$, and its complement
$$X\setminus(W_A\cup H)=(X\setminus W_A)\cap(X\setminus H)=(X\setminus H)\setminus W_A=B$$
is closed in $X$. On the other hand, there is an open $W_B$ in $X$ such that $B=W_B\cap(X\setminus H)$, and since $B\subseteq X\setminus C\subseteq X\setminus H$, we have
$$B=W_B\cap(X\setminus H)\cap W_B\cap(X\setminus H)\cap(X\setminus C)=W_B\cap(X\setminus C)\;,$$
which is open in $X$. Thus, $B$ is a proper clopen subset of $X$, so $B=\varnothing$, and $X\setminus H$ is indeed connected. $\dashv$

Now let $Y=X\setminus\{p\}$, and let $y\in Y$ be arbitrary. I'll show that $X\setminus\{y\}$ is connected, so that $y$ certainly cannot be a dispersion point of $X$. Suppose that $X\setminus\{y\}=H\cup K$, where $H\cap K=\varnothing$, $H$ and $K$ are clopen in $Y$, and $p\in H$. The lemma ensures that $X\setminus H$ is connected. However, $X\setminus H=K\cup\{y\}$, which is therefore a connected subset of $Y$ containing $y$. Since $Y$ is totally disconnected, we must have $K=\varnothing$, so that $X\setminus\{y\}$ is indeed connected, and $y$ is not a dispersion point of $X$.
Comment: @sinbadh: Depends on exactly how you define *totally disconnected*. If you define it to mean that the components are singletons, then yes, both points of any two-point space are dispersion points. If you add the requirement that the space not be connected, then neither is a dispersion point. But as I said, the whole question is pretty uninteresting for finite spaces.
Comment: Why the last part? If $\{p\}$ is open in X, which is the contradiction to connectedness of $X$?
Comment: @sinbadh: Oops! It appears that I was again unconsciously assuming that the space was $T_1$; it's a deeply ingrained habit. Ignore that part for now; I'll give it some more thought and either repair it or remove it.
Comment: @sinbadh: I don't see a way to remove the assumption that $\{p\}$ is closed from the argument that I sketched before, but I've produced a different argument that does not require it.
Comment: I added "open" to your def'n of $W_A$. Its omission was clearly a typo.
Comment: @user254665: It sure was; thanks!
Comment: @BrianM.Scott It's proved in a paper from around 2000 that cut points are always closed.
Comment: @BrianM.Scott please click chat at the bottom of the page and come to "special room"... I have some questions for you if you dont mind.
Comment: Why is $(X\backslash H)\backslash W_A=B$?
Comment: @sinbadh: $$(X\setminus H)\setminus W_A= (X\setminus H)\setminus\big((X\setminus H)\cap W_A\big) = (X\setminus H)\setminus A= B\;.$$
Comment: Thanks. I only have a question: where did you use that $X$ has at least three elements? Or the result is general for every $X$ with at least two elements?
Comment: @sinbadh: One doesn't normally even consider finite spaces in this context. In any case, if $X$ is a two-point space, then removing either point leaves a connected space, so $X$ has *no* dispersion point.
Comment: @sinbadh: You're welcome.

Connected sets and separations


PHP - Não consigo dar update na base de dados

Question: Não consigo dar update na base de dados, alguém me pode ajudar pfv?
<?php

$ligaBD = mysqli_connect("localhost", "root", "", "pap");

$tipo_autorizacao = $_POST['tipo_autorizacao'];
$autorizacao_obs = $_POST['autorizacao_obs'];

$linhaProposta = "INSERT INTO propostas () VALUES()";
$resultado = mysqli_query($ligaBD, $linhaProposta);

// Ir buscar o nproposta da proposta
$npropostaLinha = "SELECT nproposta FROM propostas ORDER BY nproposta DESC";
$resultado = mysqli_query($ligaBD, $npropostaLinha);
$nproposta = "";
printf($npropostaLinha);
$row = mysqli_fetch_array($resultado, MYSQLI_NUM);
printf("==> ");
print_r($row[0]);
$nproposta = $row[0];

$insertAutorizacao = "INSERT INTO autorizacao (nproposta,tipo_autorizacao,autorizacao_obs)
                    VALUES ($nproposta,'$tipo_autorizacao','$autorizacao_obs')";

$resultado = mysqli_query($ligaBD, $insertAutorizacao);
$selectAutorizacao = "SELECT autorizacao FROM propostas WHERE nproposta='$nproposta'";

$updateAutorizacao = mysqli_query($ligaBD, $selectAutorizacao);

if ($row["autorizacao"] == "autorizacao_sim") {
    $updateAutorizacao = "UPDATE propostas SET autorizacao='Autorizado' WHERE nproposta='$nproposta'";
} else if ($row["autorizacao"] == "autorizacao_nao") {
    $updateAutorizacao = "UPDATE propostas SET autorizacao='Nao Autorizado' WHERE nproposta='$nproposta'";
}

$resultado = mysqli_query($ligaBD, $updateAutorizacao);
header('Location: ./conselhoadmin.php');
mysqli_close($ligaBD);
?>

erro:
Comment: qual erro está acusando?
Comment: esqueci-me de meter, já editei. obrigado
Comment: O erro está aqui `$row["autorizacao"]` da onde saiu esse `$row`?
Answer: Achei o possível erro, faltava definir a variável $row, que contem o array trago pelo SELECT que vai definir a operação de UPDATE
    $resultado=mysqli_query($ligaBD, $insertAutorizacao);
    $selectAutorizacao = "SELECT autorizacao FROM propostas WHERE nproposta='$nproposta'";

    $updateAutorizacao = mysqli_query($ligaBD, $selectAutorizacao);

    //*********************************************************************
    // aqui está o que faltava

    $row = mysqli_fetch_assoc($updateAutorizacao);

    //*********************************************************************

    if($row["autorizacao"] == "autorizacao_sim") {

        $updateAutorizacao = "UPDATE propostas SET autorizacao='Autorizado' WHERE nproposta='$nproposta'";

    }else if ($row["autorizacao"] == "autorizacao_nao"){

        $updateAutorizacao = "UPDATE propostas SET autorizacao='Nao Autorizado' WHERE nproposta='$nproposta'";

    }
    $resultado=mysqli_query($ligaBD, $updateAutorizacao);
    if(!$resultado){
        echo("Error description: " . mysqli_error($ligaBD));
    }

Comment: desapareceram os dois primeiros erros, agora é só o erro do parameter 2.
obrigado por me estar a ajudar
Comment: Agora aparece este erro
http://prntscr.com/nah727
Comment: ja editei, é mysqli_fetch_assoc
Comment: reeditei a resposta, mas acredito que seja problema com `$row["autorizacao"]` acredito que a query não esteja sendo definida
Comment: vou tentar pesquisar mais um pouco, obrigado à mesma!
Comment: Faz um teste, da um `var_dump($row)` para certificar que está vindo o que vc queria
Comment: deu isso
http://prntscr.com/nahray
Comment: `$row["autorizacao"]='Por Autorizar'`, como no `if()` que vai definir qual `UPDATE` deverá ser feito não tem essa opção, ele não esta passando a `query` para o `mysqli_query`
Answer: fiz algumas modificações, funcionou aqui, levei em consideração que sua telabe tenha o modelo que coloquei no insert, qualuqer coisa e só modificar.

$ligaBD = mysqli_connect("localhost", "root", "", "pap");
$tipo_autorizacao = $_POST['tipo_autorizacao'];
$autorizacao_obs = $_POST['autorizacao_obs'];
$linhaProposta = "INSERT INTO propostas (nproposta, tipo_autorizacao, autorizacao_obs, autorizacao) VALUES ( '1234', '1234', '1234', 'autorizacao_sim');";
$resultado = mysqli_query($ligaBD, $linhaProposta);
// Ir buscar o nproposta da proposta
$npropostaLinha = "SELECT nproposta FROM propostas ORDER BY nproposta DESC";
$resultado = mysqli_query($ligaBD, $npropostaLinha);
$nproposta = "";
printf($npropostaLinha);
$row = mysqli_fetch_array($resultado, MYSQLI_NUM);
printf("==> ");
print_r($row[0]);
$nproposta = $row[0];
$insertAutorizacao = "INSERT INTO autorizacao (nproposta,tipo_autorizacao,autorizacao_obs)
                    VALUES ($nproposta,'$tipo_autorizacao','$autorizacao_obs')";
$resultado = mysqli_query($ligaBD, $insertAutorizacao);
$selectAutorizacao = "SELECT autorizacao FROM propostas WHERE nproposta='$nproposta'";
if ($result = mysqli_query($ligaBD, $selectAutorizacao)) {

/* fetch associative array */
while ($rowline = mysqli_fetch_assoc($result)) {

    if ($rowline["autorizacao"] == "autorizacao_sim") {
        $updateAutorizacao = "UPDATE propostas SET autorizacao='Autorizado' WHERE nproposta='$nproposta'";
    } else if ($rowline["autorizacao"] == "autorizacao_nao") {
        $updateAutorizacao = "UPDATE propostas SET autorizacao='Nao Autorizado' WHERE nproposta='$nproposta'";
    }
    if ($rowline["autorizacao"] != "Autorizado") {
        mysqli_query($ligaBD, $updateAutorizacao);
    }
}

/* free result set */
mysqli_free_result($result);}
Comment: Desde já obrigado pela resposta.
No entanto experimentei esse codigo e deu este erro http://prntscr.com/nak4ul
Comment: tenta trocar o codigo do if por esse;

if ($rowline["autorizacao"] == "autorizacao_sim" || $rowline["autorizacao"] == "autorizacao_nao" ) {

acredito que vai dá certo, tem algum valor em autorizacao que esta deixando passar assim resolve.
   mysqli_query($ligaBD, $updateAutorizacao);
  }
Comment: if ($rowline["autorizacao"] == "autorizacao_sim" || $rowline["autorizacao"] == "autorizacao_nao" ) {
   mysqli_query($ligaBD, $updateAutorizacao);
  }
Comment: já conseguir resolver, muito obrigado
Comment: De nada! qualuqer coisa e só falr.


Sequence such that $\lim\limits_{n\to \infty} \frac{x_1^2+x_2^2+...+x_n^2}{n}=0$

Question: Let $(x_n) _{n\ge 1}$ be a sequence of real numbers such that $\lim\limits_{n\to \infty} \frac{x_1^2+x_2^2+...+x_n^2}{n}=0$. Prove that $\lim\limits_{n\to \infty} \frac{x_1+x_2+...+x_n}{n}=0$.
I used the definition of the limit to conclude that $\exists N\in \mathbb{N} $ such that $|\frac{x_1^2+x_2^2+...+x_n^2}{n}|<\frac{1}{n^2}$, $\forall n\ge N$. Hence, we get that $|x_1^2+x_2^2+...+x_n^2|<\frac{1}{n}$.
Now here comes the part where I am not really sure. I think that this implies that $\sum_{n=1}^{\infty}x_n^2=0$, and as a result $x_n\to 0$,which solves the problem because if we use the Stolz-Cesaro lemma we get that $\lim\limits_{n\to \infty} \frac{x_1+x_2+...+x_n}{n}=\lim\limits_{n\to \infty} x_n=0$.
Comment: The definition of the limit does not allow you to conclude that $\exists N \in \mathbb{N}$ such that $ n \geq N \implies |\frac{x_1^2+x_2^2+...+x_n^2}{n}|<\frac{1}{n^2}$. It *does* allow you to say that for each $m>0$,  $\exists N \in \mathbb{N}$ such that $ n \geq N \implies |\frac{x_1^2+x_2^2+...+x_n^2}{n}|<\frac{1}{m^2}$, but this is a very different statement.
Answer: $\lim_{n\to \infty} \frac{x_1^2+x_2^2+...+x_n^2}{n}=0$
does not imply that $|\frac{x_1^2+x_2^2+...+x_n^2}{n}|<\frac{1}{n^2}$ for sufficiently large $n$. Also $\sum_{n=1}^{\infty}x_n^2=0$ would be true only if all $x_n$ are zero, so that approach cannot work, unfortunately.
But the Cauchy-Schwarz inequality gives
$$
\left |\sum_{k=1}^n 1\cdot x_k \right| \le \sqrt n \cdot \sqrt{\sum_{k=1}^n x_k^2}
$$
and therefore
$$
\left |\frac 1n \sum_{k=1}^n x_k \right| \le \sqrt{\frac 1n \sum_{k=1}^n x_k^2}
$$
This is also a special case of the Generalized mean inequality:
$$
\sqrt[p]{\frac 1n \sum_{k=1}^n x_k^p} \le \sqrt[q]{\frac 1n \sum_{k=1}^n x_k^q}
$$
for non-negative  real numbers $x_1, \ldots, x_n$ and $0 < p < q$.
Comment: Thank you! I know that $\lim \limits_{n\to \infty} a_n=l <=> \forall \epsilon>0 \exists N$ such that $|a_n-l|<\epsilon$, $\forall n\ge N$. Could you tell me what is the reason why I can't choose $\epsilon=\frac{1}{n^2}$?
Comment: @MathGuy: $N$ depends on $\epsilon$, but $\epsilon$ cannot vary with $n$. A simple example: $\frac 1n \to 0$,but $|\frac 1n| < \frac{1}{n^2}$ is never true.
Comment: Thank you for your clear explanation!
Answer: Alternatively, you can use Titu's lemma (and here)
$$\frac{x_1^2+x_2^2+...+x_n^2}{n}=
\frac{1}{n}\left(\sum\limits_{k=1}^n\frac{x_k^2}{1}\right)\ge
\frac{1}{n}\frac{\left(\sum\limits_{k=1}^nx_k\right)^2}{\sum\limits_{k=1}^n1}=\\
\left(\frac{x_1+x_2+...+x_n}{n}\right)^2$$

To the question of why $$\lim\limits_{n\rightarrow\infty} \frac{x_1^2+x_2^2+...+x_n^2}{n}=0 \ \nRightarrow \ \left|\frac{x_1^2+x_2^2+...+x_n^2}{n}\right|<\frac{1}{n^2}$$
Consider the case $x_n=\frac{1}{\sqrt{n}}$. Then $x_1^2+x_2^2+...+x_n^2=1+\frac{1}{2}+...+\frac{1}{n}$ which is the harmonic series, with
$$\ln{n}+1>1+\frac{1}{2}+...+\frac{1}{n}>\ln{(n+1)} \Rightarrow \lim\limits_{n\rightarrow\infty}\frac{1+\frac{1}{2}+...+\frac{1}{n}}{n}=0$$
but this also leads to
$$\frac{\ln{(n+1)}}{n}< \left|\frac{x_1^2+x_2^2+...+x_n^2}{n}\right|<\frac{1}{n^2}$$
which is wrong.
Comment: Titu's lemma *is* Cauchy-Schwarz in disguise :)
Comment: @MartinR in fact, some books use Titu's lemma to prove Cauchy-Schwarz (it's a $\iff$).
Comment: Thank you! I have also come up with this solution later on, but I am still curious why the other approach is wrong.
Comment: @MathGuy I just provided a counterexample ...


Premissions to access LDAP from a windows service

Question: I'm building a windows service that polls a windows file share location for a file containing members that may be found in LDAP. The windows service is running as a specific user on the domain to have access to the file share.  This user is in the Administrator group both on the server running the service and where LDAP is found.
The problem I have is that fetching the files works fine but then when accessing LDAP I get the following exception:

LDAPService.Program - Exception: An operations error occurred.
                          InnerEx:
=== STACKTRACE ===
  LDAPService.Program -    at
  System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
  at System.DirectoryServices.DirectoryEntry.Bind()    at
  System.DirectoryServices.DirectoryEntry.RefreshCache()
=== BASE EXC ===
  LDAPService.Program - System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operations error occurred.

Searching for this error there is a lot about ASP.NET and using Impersonate(). But that didn't help.
If I change the windows service to logon as Local System Account then I have no problems accessing LDAP (but I can't access the windows file share).
What other settings should I look at?
Comment: sounds like you need to have an admin setup your application with a system account this sounds like a permissions issue when you log in or run the application locally of course your network creds will be recognized if you are in AD or LDAP but LDAP knows nothing about the application when it's running on a different machine.. also do you have or use any Domain/User login with the application..? and I would actually stay away from `Impersonate` doesn't sound like a secure mechanism via the web..
Answer: I was using two different LDAP directories and forgot to provide the user/pass for the second one. Had only given it for the first one.
A classic example of what we call SBS here in Sweden (Skit Bakom Spakarna).


What does the term "receptive field size" in the MatConvNet library mean?

Question: I was reading MatConvNet's tutorial for (convolutional) deep learning and it said:

"...the receptive field size for the layer. This is the size (in
  pixels) of the local image region that affects a particular element in
  a feature map."

which makes sense with the traditional definition of a receptive field. Its usually thought as the number of pixels that affect a particular node in the feature map. However, when I went and do the exercise they have the following table:
<code>     layer|    0|    1|    2|    3|    4|         5|
      type|input| conv| relu| conv| relu|      conv|
      name|  n/a|conv1|relu1|conv2|relu2|prediction|
----------|-----|-----|-----|-----|-----|----------|
   support|  n/a|    3|    1|    3|    1|         3|
  filt dim|  n/a|    1|  n/a|   32|  n/a|        32|
 num filts|  n/a|   32|  n/a|   32|  n/a|         1|
    stride|  n/a|    1|    1|    1|    1|         1|
       pad|  n/a|    1|    0|    1|    0|         1|
----------|-----|-----|-----|-----|-----|----------|
   rf size|  n/a|    3|    3|    5|    5|         7|
</code>
where we can see that the convolution layer (layer 3) has a rf size (receptive field) of size 5. I was wondering, how did they get that number for the receptive field? I thought that the receptive field just referred to the size of the image size of the input to compute a feature map, i.e. the same size as the filter size of that convolution layer (Thought, I am aware the concept can extend to lower layers as explained on chapter 9 of Begnio, Goodfellow, Courville BGC deep learning book). Regardless, even aware of the extension definition, I am still unsure how to the number 5 was obtained on layer 3. Any ideas?
Answer: Receptive field refers to the pixels in the input image which contribute to a feature in any layer of a network.
Layer 1: Each point in the feature map comes from 3x3 pixels from input image, so RF is 3
Layer 3: Each point in the feature map comes from 3x3 patch of feature map
from layer 1 which in turn map to 3x3 pixels of input image, if you map it back you realize it maps to 5x5 patch of the input image.
Similarly for layer 5 you get a 7x7 patch.


Topological properties of cohomology rings

Question: I have read this question Is there anything to be learned from the spectrum of a cohomology ring?. But it seems more focused on the applications of $\mathrm{Spec}(H^*(X;R))$ rather than its topological properties. Which is why I am posting this as a separate question.
I was told that the Zariski topology for a $Z_2$ graded ring (like the cohomology ring defined with the cup product) is homeomorphic to the Zariski topology over its even graded (and so commutative) subring. I see how this should work by mapping primes in the whole ring to the intersection of it and the even graded subring.
With this we get $\mathrm{Spec}(H^*(X;R))\cong \mathrm{Spec}(\bigoplus_{k\text{ even}}H^k(X;R))$ which defines an affine scheme by definition so higher order cohomologies vanishes as shown here in the stacks project https://stacks.math.columbia.edu/tag/01XB.
I was wondering if this is enough to conclude $\mathrm{Spec}(H^*(X;R)\cong X$? (I'm just studying algebraic topology so I'm not familiar with sheafs,sheaf cohomology and the sort and I'm worried since stacks project seems to reference that maybe this step is wrong.)
Provided this is even right, is this a known result in literature? Where could I read more about this?
Comment: What does the symbol $\cong$ mean in your fourth paragraph? (Oh, and the `\bigotimes` should probably be `\bigoplus` in paragraph 3.)
Comment: Have you tried any examples? For instance, does Spec look different if $X=S^2$ vs. $X=S^4$?
Comment: Thanks for your comments Mariano my main question here seems totally wrong (too much wishful thinking I suppose) but I'll read up on the topics you mentioned they seem interesting.
Answer:
With this we get $\mathrm{Spec}(H^*(X;R))\cong \mathrm{Spec}(\bigotimes_{k\text{ even}}H^k(X;R))$

You need to take the direct sum here.

I was wondering if this is enough to conclude $\mathrm{Spec}(H^*(X;R)) \cong X$?

No, this is not even close to being true, for multiple reasons. For example if $X$ is any finite-dimensional connected manifold then $H^0(X, \mathbb{R}) \cong \mathbb{R}$ and the higher $H^i$ are nilpotent, so $\text{Spec } H^{\bullet}(X, \mathbb{R})$ consists of a single point. Generally speaking the cohomology ring is very far from being a complete invariant even up to homotopy, let alone up to homeomorphism.
Comment: Oh ok thanks your help. I really should have checked an example first


Monoids as Categories With One Object of Specific Type

Question: I was reading David Spivak's excellent book on category theory, where he uses a category to define a monoid. Another text by Tom Leinster defines monoids in the same way (I've only read through the "Motivation for Topologists"):
A monoid $\mathcal{M}$ is a category with a single object $@$, where the morphisms are the elements of $\mathcal{M}$ and the binary map is given by composition of morphisms. Leinster goes on to describe usage of monoids with this definition in Braid Theory and other parts of topology. I have only ever seen monoids defined in this way where the object $@$ is trivial, and the specific nature of the morphisms is usually quite vague.
Is there an example where the definition of $@$ in a monoid is rigorous and interesting, where $@$ is some algebraic object like a magma, group, or ring, and where the morphisms represent something quite literal outside of their use as objects of $\mathcal{M}$? Please do not give any examples where $@$ is only a set.
Comment: The main point is that the actual nature of @ doesn't matter at all, - the monoid structure lives in arrows and composition.
Comment: By the Yoneda lemma, you can take @ to be $M$ regarded as a right $M$-set. But @ is just an abstract entity; it's exactly like a vertex in a graph.
Answer: In algebra, a monoid is defined as a pair $(M, *)$ where $M$ is a set and $*$ is a binary operation on $M$ satisfying associativity and having an identity element.
A category with a single object, on the other hand, is given by a triple $(O, M, *)$ where $O$ is a set with a single element (the class of objects), $M$ is a set (the set of morphisms from the single object to itself is the only hom-set) and $*$ is a binary operation on $M$ satisfying associativity and having an identity element (the composition of morphisms turns out to be a binary operation because there is only one hom-set).
Notice that in the definition of a category with a single object there is no relationship between $O$ and $(M, *)$, because the properties that need to hold involve only $(M, *)$. Since those properties are exactly the same as those in the definition of monoid, we can say that a category with a single object consists of a monoid together with a set with a single element.
Therefore, if you want to get a monoid from a category with a single element, you just have to discard the useless set with a single element. Conversely, if you want to get a category with a single element from a monoid, you just have to come up with a set with a single element. Since that element won't play any role in the category, one usually puts a placeholder like $@$ to mean that any object will do.
Two categories with a single element are isomorphic (not just equivalent) whenever the corresponding monoids are isomorphic. Indeed, if $f\colon M \to M'$ is a monoid isomorphism, then the functor $F \colon \mathcal C \to \mathcal C'$ defined by $F(@)=@'$ and $F(m) = f(m)$ for any $m \in M$ (that is $m \colon @ \to @$ as a morphism) is clearly an isomorphism of categories, its inverse $F^{-1} \colon \mathcal C' \to \mathcal C$ being given by $F^{-1}(@') = @$ and $F^{-1}(m')=f^{-1}(m')$ for any $m' \in M'$ (i.e., $m' \colon @' \to @'$).
Now, if you still think that it makes more sense to define a monoid as a category with a single object, and that in order for a monoid defined in this way to be interesting its object should be some algebraic object as well, then you could consider the monoid of endomorphisms of a given algebraic object.
For example, if $(R, +, *)$ is a ring, then you could consider the full subcategory of the category of rings having $(R, +, *)$ as its only object. In this way there is indeed a relationship between the object and the morphisms, since the morphisms are precisely the ring homomorphism from $(R, +, *)$ to itself.
In fact, this construction can be applied to any category, not just a category of algebraic objects (e.g., you could also consider the full subcategory of the category of topological spaces having a given topological space as its only object, and so on).


Dynamic Header Titles with React

Question: I was wondering how I would go about being able to have different header titles using only 1 header file with React? I don't want to have to have a header for each component but want to have a title for each view that is changed. Any thoughts?
Comment: title as in `document.title`?
Comment: No, more of a title that I want to have for each document
Comment: Am new to react, how to render common header?
Answer: This is what props are for.
// Header.js
const Header = ({ title }) => (

{title}

);

Now you have a re-usable header component:

Comment: This works well while a having a simple header like that, but if you have a more complex header, would not be good to re-render it on every route/page change.
Comment: Optimising your renders is beyond the scope of the question. In any case, most of the page will typically re-render on a route change anyway.
Answer: { title } is the prop for the Header component, each view has a different title, e.g. Ofertas view: title='Ofertas'.

Dynamic Header Titles with React


How to configure the stylelint extension in vscode?

Question: I created a project using the create-react-app --template typescript. Now I wanted to try out the css linter stylelint. And, so I have installed the npm packages stylelint and  stylelint-config-standard as dev dependency using yarn.
I have also added a config file named .stylelintrc.js with below content
module.exports = {
  extends: "stylelint-config-standard",
  ignoreFiles: ["./build/**/*.css", "./node_modules/**/*.css", "**/*.js",
  "**/*.jsx"],
}

In my package.json, I have also added a script like
"css-lint": "stylelint '*/**/*.css'",

Now when I run yarn css-lint in the terminal, it works.
As for VS Code, I installed and enabled the extension. And as suggested, I have disabled the default css, less, sass linters. I have also restarted the VS code but no luck, the stylelint extension does not work or highlight any errors in VS code.
I am stuck. And any help will be appreciated.
Comment: Hi! I am a bit late, but maybe can help someone else. Check my answer here: https://stackoverflow.com/questions/69149058/why-the-stylelint-vscode-extension-is-not-working-on-my-computer/71817658#71817658
Answer: Add the language identifiers for the documents you want to validate to the extension's workspace or user settings using the stylelint.validate option. Troubleshoot vscode-stylelint with the output panel/channel.
//.vscode/settings.json
{
  "stylelint.validate": [
    "css",
    "scss",
    ...
  ],
}


how to remove forward slash generated from wordpress editor

Question: I have following html for a wordpress custom plugin which is loaded to a wordpress editor

But when its saved to a database its changes as follows

because of this slashes css styles are not getting reflecting. How to remove this slashes?. Please help
Comment: Try this stripslashes_deep.
Comment: Its working now. Thank you so much :)
Answer: Try this:

stripslashes_deep. <?php wp_editor( stripslashes($content), $editor-id ); ?>

Answer: Please try wp_kses_stripslashes function. This function changes the character sequence \" to just ".
<?php wp_kses_stripslashes( $string ) ?>


What to do after a chi-squared test for 2 way table?

Question: Suppose I have the following 2 way table and I perform a (Pearson) chi-squared test on it. With the null hypothesis: children's goals are independent of gender.
         gender
goal      boy girl
  grades  117 130
  popular  50  91
  sports   60  30

I get X-squared = 21.4553, df = 2, p-value = 2.193e-05, so I accept the alternative hypothesis that children's goals is dependent on gender.
For further analysis, how would I find what this dependence might be? Could I look at the column percentages, as in the following table?:
            gender
goal         boy   girl
  grades    51.5   51.8
  popular   22.0   36.3
  sports    26.4   12.0
  Total     99.9  100.1
  Count    227.0  251.0

I could say that 51.5 and 51.8 are fairly close and 117 and 130 provide relativity good support to say that. Boys and girls both closely equally represented when having grades as their goal. And similarly I could say that more girls have goals to be popular than boys but more boys have goals to be more sporty than girls.
Would I still be able to make the same statement about boys and girls goals for grades if say there was only 13 boys and 17 girls that have their goal as grades out of 1000 boys and girls total? I would then have a very low support, what conclusion can I then make about that? More importantly how big of a support would I need to be able to make such a conclusion about their goals?
Are there also other things I can do after I the chi-squared test?  (For example, if this was all the data I had, and no other variables to work with. I have got the individual responses as well in a data frame.)
Comment: Possible duplicate of [Understanding $\chi^{2}$ and Cramér's $V$ results](https://stats.stackexchange.com/questions/105795/understanding-chi2-and-cram%c3%a9rs-v-results)
Comment: Have you only got this data (the table as you show it), or have you got the detail of responses per participant, i.e. for each response a gender and a goal (or many goals if participants were allowed to select multiple goals)?
Comment: @ArthurSpoon Yes I have the responses in a data frame. There are only 3 goals and each boy or girl can only choose 1 goal that they think is most important to them.
Answer: There is a really good answer to your question right here, but just to expand a little bit on this and to make it specific to your problem:
In your case, you are dealing with gender which can be considered a grouping variable, when goal is much more a dependent variable as it is a response from your participant, so I would say that in your case, as in the answer I link to, Cramér's $V$ isn't what you want, so you will prefer going for one of the other measures listed in that answer.
What you were intuitively doing by comparing the column percentages was a risk difference.
Comment: That seems to work using risk difference or odds ratio. From another post I was recommended to try a post hoc test with Bonferroni Adjustment. Would you think that would be more suited as it uses statistical significance?
Comment: You could use Bonferroni correction as well, in which case what you want to do is run a $\chi^{2}$ on subsets of your data, and you need to decide in advance how many subtests you are running. In your case, I think you want one test for each row, so three tests in total, and your corrected $\alpha$ would be 0.017. However there are many reasons why you shouldn't be super keen on obtaining $p$-values and significant results (see e.g. [this](https://www.editage.com/insights/is-my-research-significant-why-you-shouldnt-rely-on-p-values)).


How can I detect if Dispatcher.DisableProcessing is active?

Question: An exception is raised if one tries to show a message box if the Dispatcher is suspended (Dispatcher.DisableProcessing() called).

InvalidOperationException: 'Dispatcher processing has been suspended' (see here).

Does anyone know how I can detect where the Dispatcher is suspended or not (so I know when to call BeginInvoke())?
Edit 1:
In reaction to the Application.DispatcherUnhandledException event I'm trying to show a MessageBox. However, if this unhandled Exception was thrown during DataBinding (i.e. ItemsControl.ItemsSource) the Dispatcher is suspended. Trying to show a MessageBox then fails. Always using Dispatcher.BeginInvoke() solves the problem, but I don't want to do that unless really necessary.
Edit 2:
Using Reflection to accomplish this works like this:
var dispatcherType = typeof(Dispatcher);
var countField = dispatcherType.GetField("_disableProcessingCount", BindingFlags.Instance | BindingFlags.NonPublic);
var count = (int)countField.GetValue(Dispatcher.CurrentDispatcher);
var suspended = count > 0;

Comment: I suggest you provide more details here, thus making the question complete in-place.
Answer: There is no public interface there so you don't have a legal way to say whether it's suspended or not. You still can use reflection, but generally speaking this indicates you are doing something totally wrong.
If you could give us more details we could suggest proper solution?
Comment: In reaction to the Application.DispatcherUnhandledException event I'm trying to show a MessageBox.

However, if this unhandled Exception was thrown during DataBinding (i.e. ItemsControl.ItemsSource) the Dispatcher is suspended. Trying to show a MessageBox then fails. Always using Dispatcher.BeginInvoke() solves the problem, but I don't want to do that unless really necessary.
Answer: try this:
if(currentDispatcher.Thread.ThreadState == System.Threading.ThreadState.Suspended)
{

}

Comment: This doesn't work.  The threadState is still "Running" during a DisableProcessing time period.


Usar findViewById na MapsActivity padrão do Android Studio

Question: Estou usando o modelo padrão de Maps disponível no Android Studio, e na activity_maps.xml adicionei um EditText com o id towhere.
Na classe MapsActivity apenas adicionei um setOnFocusChangeListener:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        if(mapFragment != null)
            mapFragment.getMapAsync(this);

        /* início da parte feita por mim */
        EditText towhere =  findViewById(R.id.towhere); //ERRO
        towhere.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    Intent findAddress = new Intent(MapsActivity.this, FindAddress.class);
                    startActivity(findAddress);
                }
            }
        });
        /* fim da parte feita por mim */
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }
}

Recebo o erro:

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.EditText.setOnFocusChangeListener(android.view.View$OnFocusChangeListener)'
  on a null object reference

O setContentView está definido antes do findViewById, mas não funciona.
Comment: Para te ajudar vai ser preciso mais código (MapsActivity e o activity_maps.xml)
Comment: poste mais parte do código
Comment: Postei toda a classe, já que só adicionei algumas linhas e ela é curta.
Answer: O problema estava no XML. Como eu estou rodando o emulador do Nexus, ele está obtendo o componente da pasta layout-v26 ao invés da layout, e os arquivos activity_maps.xml dessas duas pastas estavam diferentes, e por isso estava dando NullPointerException para o id requisitado em findViewById(R.id.towhere)


Can a dihedral group $D_2$ be a set of transformations of a line segment? If it can then what are the reflections?

Question:
Can a dihedral group $D_2$ be a set of transformations of a line segment? If it can then what are the reflections?

No matter how I think about reflecting it I always get either the identity or the result of one rotation.
Shouldn't the two reflections be something distinct to the identity and one rotation for it to be considered a dihedral group?
Comment: Please try to make the titles of your questions more informative. For example, *Why does $a<b$ imply $a+c<b+c$?* is much more useful for other users than *A question about inequality.* From [How can I ask a good question?](https://math.meta.stackexchange.com/a/589/): *Make your title as descriptive as possible. In many cases one can actually phrase the title as the question, at least in such a way so as to be comprehensible to an expert reader.* You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/).
Answer: If you want $D_2$ to be the set of symmetries of a line segment (a "regular $2$-gon"), then yes, it can be. But you have to take into account that flipping it over (the operation that has order $2$ in any dihedral group) is different from rotating it $180^\circ$ in the plane. So to truly generalize the case of $D_n$ being the group of symmetries of the regular $n$-gon, you have to see it as the set of symmetries of a line segment with an overside and an underside.
Comment: Precisely what I want to know is how is flipping it over different than rotating? If it is a vertical line segment and point $A$ is above and point $B$ is below then flipping or rotating would put the $B$ above, and $A$ below.
Comment: @MichaelMunta If you just draw a standard line segment, then the operations aren't different. But then $D_2$ isn't the symmetry group either, $C_2$ is. If you want $D_2$ to be the symmetry group, then your line segment has to be green on the overside (the side you see initially), and red on the underside (the side you see after flipping it). Or something similar. This is _precisely_ to make the flipping and the rotation distinct operations.
Comment: So in this case I can not think about the different symmetries as permutations of vertices? Like, for example, in triangle we have 6 different symmetries which correspond to 6 permutations of the set of vertices.
Comment: @MichaelMunta You can see yourself that that isn't enough. There are only two permutations on two vertices, but $D_2$ has four elements. The closest you can get is the group of symmetries on a rectangle.


Understanding homology groups and generators of a torus.

Question: It is mentioned here in 4x how for a torus $\mathbb{T}^2$ one has the homology groups of $H_0 \cong \mathbb{Z}$, $H_1 \cong \mathbb{Z}\oplus \mathbb{Z}$ WITH generators $\{a+b+c\}$ and $\{d+e+f\}$, as well as $H_2 \cong \mathbb{Z}$. I understand the basic idea behind homology, but I struggle understanding why these sets specifically form generators. Could someone explain this to me? Here's also the triangulation of the torus.
Comment: Did you try to actually compute $H_1$ by taking the quotient $\operatorname{ker}(\partial_1)/\operatorname{im}(\partial_2)$? This is what you need to do.
Comment: This is exactly what I am asking help with. I understand the procedure of computing a homology group, I am just struggling to do it here with the torus due to finding a basis for the given simplicial complex.
Comment: Then your question should include your efforts and point out where you get stuck in the computation.
Answer: I find the text a bit confusing. Usually the torus is presented as the quotient of the square by identifying parallel edges in a way to preserve orientations. This old question contains more material on such construction
$CW$ complex structure and intuitive construction of spaces
Here instead from what I see you have a triangulation on the starting square and you want to present the generators using the edges of the triangulation. The ending result is correct but the method is more convoluted of what it needs to be. I suppose such triangulation will be used later for exercises or applications.
I would suggest first to understand the situation without the presented triangulation, like in the question I linked. To see the boundary edges give the generators of $H_1(\mathbb{T}^2)$ you can use either Seifert-Van Kampen theorem and then the fact that $H_1(X)$ is the abelianization of $\pi_1(X)$ for $X$ a path connected space or use the Mayer-Vietoris sequence.
If you manage to do that it should be easy to understand the generators presented via this triangulation. It is basically like presenting the circle $S^1$ as the quotient $\mathbb{R}/3\mathbb{Z}$ instead of the usual $\mathbb{R}/\mathbb{Z}$.
Comment: It is a triangulation using a [simplicial complex](https://en.wikipedia.org/wiki/Simplicial_complex) instead of a cell complex. Using simplicial complexes this is the most simple triangulation you can get.
Comment: Yes, I understand what you mean. But as described by Christoph, I am trying to do this by the use of the simplicial complex rather than any other method.


VisualCode - Suggestion

Question: Estou iniciando um projeto utilizando JavaScript, no qual o suggestion (Ctrl + Space) não está funcionando completamente.
Ao colocar "." ou a apertar Ctrl + Space ele só mostra uma única opção (de forma resumida) e não vejo as demais propriedades que um objeto ou vetor pode ter. Parece que mostra de forma resumida.
Como configurar para mostrar todas opções de propriedades ao apertar a tecla?
Configuração do VSCode (setting.json)
"editor.quickSuggestions": true,
"editor.suggestOnTriggerCharacters": true,
"editor.wordBasedSuggestions": true,

Comment: isso ajuda? https://pt.stackoverflow.com/questions/232044/sugest%c3%b5es-de-comandos-no-vscode
Answer: Acesse a aba de plugins dentro do VSCode e procure por IntelliSense, esse varia de linguagem para linguagem... existem uns para PHP, Unity, JS, C# (E outros).
Tente procurar um de seu agrado, abra a configuração dos plugins estilo IntelliSense e lá você pode escolher a quantidade de resultados que o VS mostra!
Lembrando que aqui você pode baixar plugins para as linguagens que você for usar, isso ajuda o VS a reconhecer os codigos e snippets dessa linguagem.
Tente procurar por VS Code IntelliSense.

VisualCode - Suggestion


Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous

Question: I am using migrate module to transfer data from one site to another here is my query
<code>$query = Database::getConnection('db1', 'db1')
        ->select('users', 'u');
$query->leftjoin('field_data_field_user_insti_name', 'insti_name', 'insti_name.entity_id = u.uid and insti_name.bundle = \'user\'');
$query->leftjoin('users_roles', 'ur', 'ur.uid = u.uid');
$query->fields('u', array('uid', 'name', 'mail', 'pass', 'status'));
$query->fields('insti_name', array('field_user_insti_name_target_id'));
$query->condition('u.uid', '1', '>');
$query->condition('ur.rid', '6', '!=');
$query->distinct();
</code>
than I am getting this error

Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous

I found a solution for this problem that i have to add line
<code>$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));
</code>
After this error is solved, but don't know what this line do, is it safe to use this line
Comment: Refer this answer

http://drupal.stackexchange.com/questions/51091/migrate-failure-on-clause-is-ambiguous
Answer: You have to add alias in MigrateSQLMap
<code>$this->map = new MigrateSQLMap($this->machineName,
   array(
       'uid' => array(
           'type' => 'int',
           'not null' => TRUE,
           'alias' => 'u',
       )
   ),
) ;
</code>


crontab ifconfig outputting nothing

Question: /home/myname/bin/script:
#!/bin/bash
ifconfig > /home/myname/foo

Crontab:
* * * * * /home/myname/bin/script

...waits 1 minute...
@@ 11:35:51 [myname@comp - ~]$ ls foo
-rw-r--r-- 1 myname myname 0 Jul  7 11:35 foo
@@ 11:35:55 [myname@comp - ~]$

I can't figure out why foo would end up empty. Running the ifconfig command on the command line works exactly as you'd expect, dumping its output into a file just like normal.  For reference, I'm running Ubuntu 8.04.
Comment: I'm just going to say that, in the intervening five years, one thing I constantly have to remind myself of about crons is that they don't run with the same environment (path, aliases, etc.) that I'm used to on the shell, and this continually trips me up.
Answer: try using the full path to the ifconfig executable in your script.
which ifconfig will give you the path.
I don't know what ipconfig does in ubuntu. :)
Comment: Sorry, it's ifconfig in the script, I typo'd it in the question.
Comment: I figured. I do that from time to time too. Cron usually just wants the full path so let us know how things turn out.
Comment: ...but yes, it was a path problem.  ifconfig is under /sbin, which is not in the default bash path.  Thanks.
Comment: ah makes sense, see I always overlook something when writing scripts, nice spot egorgry
Answer: In a cron job you probably want to redirect both stdout and stderr to the file.  Change your script to this:
#!/bin/bash
ifconfig &> /home/myname/foo

and you'll see the error message in your output file.
See All About Redirection in the Bash Programming How To for more info.
Answer: crontab does not use user path variable.
You have to place command with full path to it. i.e. /sbin/ifconfig. Then this will be working.
Other way to solve this problem is to add PATH variable to your script and export it then your script will be able to use standard commands with out adding full path every time. You can check path typing echo $PATH in terminal.
Answer:
You probably need the full path to ipconfig in your script, or did you mean ifconfig?  Either way, you should use the full path.
You capture stdout in /home/myname/foo, but not stderr which probably gets the clue that you're missing here.  Check your email for the output of the cronjob.
Answer: have you tried manually running your script?
cd in to /home/myname/bin/
./script
does it make the foo with contents as expected?
is the script executable?
I know that might sound like simple things but sometimes that is what is overlooked, especially when I make a script
Comment: Yes, and yes. The script executes normally when run by hand, and it is executable.

crontab ifconfig outputting nothing


LOAD DATA LOCAL INFILE Manipulate Some Date Columns

Question: I have a csv with 3 date columns but each is formatted dd/mm/yyyy H:i:s i.e 27/05/2019 20:25:00
I am trying to manipulate these to insert using LOAD DATA INFILE without any success:
My state looks like this:
 LOAD DATA LOCAL INFILE '/file.csv'
    INTO TABLE db_table FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
    IGNORE 1 LINES
    SET promotion_starts = str_to_date(@column7, '%d/%m/%Y %H:%i:%s'),
    promotion_ends = str_to_date(@column8, '%d/%m/%Y %H:%i:%s'),
    date_added = str_to_date(@column17, '%d/%m/%Y %H:%:%i:%s')

All other data inserts fine but the date columns are all null
Comment: Where do you set `@column7`, etc.?
Answer: You're missing the line of the query that specifies how the fields of the CSV file correspond to table columns, and defines @column7 and @column8.
 LOAD DATA LOCAL INFILE '/file.csv'
    INTO TABLE db_table FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
    IGNORE 1 LINES
    (foo, bar, baz, xxx, yyy, zzz, @column7, @column8, aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, @column17, iii, jjj)
    SET promotion_starts = str_to_date(@column7, '%d/%m/%Y %H:%i:%s'),
    promotion_ends = str_to_date(@column8, '%d/%m/%Y %H:%i:%s'),
    date_added = str_to_date(@column17, '%d/%m/%Y %H:%:%i:%s')

Replace all the column names I made up with the actual column names in your table that correspond to the CSV fields.


How do I make a standalone application exported from Eclipse (more info inside)?

Question: Here is a brief summary:
I have a large project on Eclipse with numerous classes and Maven dependencies. This java class is part of a script I plan to make. Basically, this collection of classes will be called by the script using java and javac, or whatnot, and in turn, the program will output many JSON files to be interpreted by an HTML file.
What is the best way to do this? I tried using JARS and running them independently, but for some reason, the Maven dependencies were not included, so some of the classes, like JSONObject, did not work.
As you can probably tell, I am a relatively beginner to development, so I'd appreciate any help. Thanks in advance.
Answer: Maven gives you tool to build executable jars with dependencies. You just need to configure your POM file accordingly.
Maven: Packaging dependencies alongside project JAR?
Above URL can explain you details for configuring POM.
EDIT
If you want your own JAR configuration without MAVEN, then you need to learn about Manifest file.
JAR files support a wide range of functionality, including electronic signing, version control, package sealing, and others. What gives a JAR file this versatility? The answer is the JAR file's manifest.
The manifest is a special file that can contain information about the files packaged in a JAR file. By tailoring this "meta" information that the manifest contains, you enable the JAR file to serve a variety of purposes.
Details can be found at location below :
http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
Comment: Sorry if my question wasn't clear enough, but the main purpose wasn't Maven. I mean for my project in general, how do I make sure my JAR works properly, beucase I get numerous errors when trying it. Also, what's the best way to run a main method in a class located within the JAR?
Comment: I have added custom jar related details in answer. Please go through it.


Comunicar Checkbox com Python

Question: Tenho um botão do tipo "checkbox" com um evento JS, os eventos JS estão funcionado normalmente, porem eu gostaria que meu código JS executasse um arquivo .py quando o checkbox estiver marcado. Como posso fazer isso?
esse é o codigo html

    <input id="switch-shadow" class="switch switch--shadow" type="checkbox"name="field[]" value="1">

esse é o codigo JS:
var checkbox = $("#switch-shadow[type='checkbox']");

checkbox.change(function(event) {
    var checkbox = event.target;

    if (checkbox.checked) {
        setTimeout(function(){

            alert("Luz do quarto Acessa")

        }, 1000);
    }

    else {
        setTimeout(function(){

            alert("Luz do quarto Desligado")

        }, 1000);
    }

});

Tem mais, o meu back-end é em python. Esse é o código:
import RPi.GPIO as GPIO
import time
import cgi, cgitb

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(5)
print "LED off"
GPIO.output(18,GPIO.LOW)

Comment: Você tem um backend? Em qual linguagem?
Comment: python, esse é o codigo python:

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(5)
print "LED off"
GPIO.output(18,GPIO.LOW)
Comment: Não seria o caso de fazer um ajax quando ele selecionasse o checkbox?
Comment: sim, exatamente mas nao estou conseguindo estrutula-lo no meu JS
Answer: Para resolver, basta utilizar o fetch para resolver seu problema da seguinte forma:
checkbox.change(function(event) {
    const checkbox = event.target;
    fetch(`http://www.example.com/?status=${checkbox.checked}`)
    .then(function(response) {
        alert(response.data);
    });

}

Daí o seu backend ficaria encarregado de alterar o estado da luz, baseado no que foi enviado pra ele através do GET e dar o retorno de se foi acendida ou apagada e se houve ou não algum erro.
Comment: ok, vou testar, e te dou um retorno

Comunicar Checkbox com Python


How to show that for any initial probability this Markov chain has the same distribution as $n \rightarrow \infty$?

Question: I'm currently trying to solve this problem about Markov chains.

Let a Markov chain have the transition probability matrix:
$$
P =
\begin{bmatrix}
1 - \alpha & \alpha \\
\beta & 1 - \beta
\end{bmatrix}
$$
where $|1 - \alpha - \beta| \lt 1$.
1) Find the $n$-step transition matrix $P^n$ as $n \rightarrow \infty$.
2) Show that for any initial probability the Markov chain has the same probability distribution as $n \rightarrow \infty$.

For the first problem, I was able to find that the transition matrix is:
$$
P^n =
\begin{bmatrix}
\dfrac{\alpha + \beta(1 - \alpha - \beta)^n}{\alpha + \beta} & \dfrac{\alpha - \alpha(1 - \alpha - \beta)^n}{\alpha + \beta} \\
\dfrac{\beta - \beta(1 - \alpha - \beta)^n}{\alpha + \beta} & \dfrac{\beta + \alpha(1 - \alpha - \beta)^n}{\alpha + \beta}
\end{bmatrix}
$$
and so for $n \rightarrow \infty$ we have:
$$
P^{n \rightarrow \infty} =
\begin{bmatrix}
\dfrac{\alpha}{\alpha + \beta} & \dfrac{\alpha}{\alpha + \beta} \\
\dfrac{\beta}{\alpha + \beta} & \dfrac{\beta}{\alpha + \beta}
\end{bmatrix}
$$
If I'm incorrect, please let me know.
What's confusing me is the second problem. To be completely frank, I don't recall learning this in the course I'm taking and I'm having trouble finding resources online, which led me to ask a question here. How would I solve this problem? I'm having trouble from where to begin.
Any tips or feedback are appreciated. Thanks in advance!
Comment: Let $\pi$ be the initial distribution, let $Q$ be your limit matrix.  You have to show that $\pi Q$ does not depend on $\pi$.
Answer: Let $Q = \lim_{n\to\infty} P^n$. For any initial distribution $\alpha=(\alpha_0,\alpha_1)$, we have
$$
\alpha Q=\begin{pmatrix}\alpha_0&\alpha_1\end{pmatrix}\left(
\large\begin{array}{cc}
 \frac{\alpha }{\alpha +\beta } & \frac{\alpha }{\alpha +\beta } \\
 \frac{\beta }{\alpha +\beta } & \frac{\beta }{\alpha +\beta } \\
\end{array}
\right)
= \left(
\Large\begin{array}{cc}
 \frac{\alpha  \alpha _0}{\alpha +\beta }+\frac{\beta  \alpha _1}{\alpha +\beta } & \frac{\alpha  \alpha _0}{\alpha +\beta }+\frac{\beta  \alpha _1}{\alpha +\beta } \\
\end{array}
\right)
$$
which shows that $\lim_{n\to\infty}\mathbb P(X_n=j\mid X_0=i)$ is independent of $i$.