Terms in a geometric sequence

Question: Find the maximum number of terms in a strictly increasing geometric sequence, where each term is an integer between $100$ and $1000$ (inclusive). I tried making many cases but it didn't help.
Comment: $a_0=2^7=128$ and $r=\dfrac32=1.5$
Answer: Proof there is no sequence of length $7$:
Let $\frac{p}{q}$ be the ratio with $(p,q)=1$ and $a_0=b$ . Then $a_6=\frac{bp^6}{q^6}$ Hence $q^6|b$.
Since the only numbers in $[100,1000]$ which are divisible by a sixth power are $2^7,2^8,2^9$ We must have that $b$ is equal to one of these. And therefore $q$ must be a power of $2$. However if $q=2^k$ with $k\geq 2 $ then $(2^{k})^6=2^{6k}$ will not divide $b$. So if we want for the sequence to have more than six terms we must have $q=2$.
From here $p\geq 3$ and therefore $a_6\geq 2^7\frac{3^6}{2^6}=2\cdot3^6>1000$.
Therefore no sucession of length $7$ exists and $6$ is indeed the max.
Comment: Nice. Was in the process of editing my answer with the almost same proof I finally found; looks like you posted it before me.
Answer: While trying to optimize number of terms in sequence you desire by keeping the common ratio quite small, as well as keep all of the terms an integer between 100 and 1000, you need a first term which is quite small, and which will result in only integer values between 100 and 1000. I can just think of r=3/2 and starting term to be 128, as $2^7 = 128$, meaning it will only result in integer values between 100 and 1000 (As it has 7 twos in its prime factorisation).
So I think 128, 192, 288, 432, 648, 972 is the longest geometric sequence; 6 terms
In fact, since 2 is the smallest integer factor besides one, the starting term $2^7$ will yield most terms for the common ratio (Which again has 3/2, smallest integer factors for denominator and numerator respectively (Because we wish to optimise the number of terms in the sequence and keep the denominator a factor capable of resulting in only integer values between 100 and 1000)). So I have more assurance now that this is the correct answer...

Terms in a geometric sequence


Prove that: $\lim\limits_{x\to\infty}\sum_{n=1}^\infty \frac{2x}{x^2+n^2}=\pi$

Question: Find the limit $$\lim_{x\to\infty}\sum_{n=1}^\infty \frac{2x}{x^2+n^2}$$
My attempt, I can prove $\sum_{n=1}^\infty \frac{2x}{x^2+n^2}$ is not uniformly convergent on $[a,\infty)$, hence I can't switch the limit and series. Then I choose to compute the series first,
$$\sum_{n=1}^\infty \frac{1}{x^2+n^2}=\frac\pi{2x}\coth(\pi x)-\frac1{2x^2}$$
then compute the limit
$$\lim_{x\to\infty}\sum_{n=1}^\infty \frac{2x}{x^2+n^2}=\lim_{x\to\infty}\left(\pi\coth(\pi x)-\frac1{x}\right)=\pi$$
My question is, how to compute this limit without computing the closed form for the series? It seems also difficult to prove the limit is convergent before getting a closed form for the series.
Comment: My guess: $\sum_{n=1}^\infty \frac{2x}{x^2+n^2} = \frac 1x \sum_{n=1}^\infty \frac{2}{1+(n/x)^2}$ approximates $\int_0^\infty \frac{2}{1+t^2} dt$.
Comment: Wolframalpha confirms that
 Limit[Sum[2 (x/(x^2 + n^2)), {n, 1, Infinity}], x -> Infinity] = Pi
Answer: Fix $q>1$
$$\sum_{n=1}^\infty \frac{2x}{x^2+n^2}=\sum_{n=1}^{q\lfloor x\rfloor} \frac{2x}{x^2+n^2}+\sum_{n=q\lfloor x\rfloor+1}^\infty \frac{2x}{x^2+n^2}$$
where
$$\lim_{x\to\infty}\sum_{n=1}^{q\lfloor x\rfloor} \frac{2x}{x^2+n^2}=\lim_{x\to\infty}\sum_{n=1}^{q\lfloor x\rfloor} \frac{2}{1+\left(\frac nx\right)^2}\cdot \frac1x=\int_0^q\frac{2}{1+t^2}dt=2\arctan q\tag{1}$$
For tail part, let $k=n-q\lfloor x\rfloor$
$$\sum_{n=q\lfloor x\rfloor+1}^\infty \frac{2x}{x^2+n^2}=\sum_{k=1}^\infty \frac{2x}{x^2+(qx+k)^2}\le \sum_{k=1}^\infty \frac{2x}{(qx)^2+k^2}=\frac1q \sum_{k=1}^\infty \frac{2qx}{(qx)^2+k^2}$$
Let $p=qx$
$$\frac1q\sum_{k=1}^\infty \frac{2p}{p^2+k^2}\approx \frac1q\int_0^\infty \frac{2p}{p^2+k^2}dk=\frac{2\arctan p}q\le \frac\pi q$$
since $q$ is arbitrary, let $q\to\infty$, then the tail part
$$\sum_{n=q\lfloor x\rfloor+1}^\infty \frac{2x}{x^2+n^2}\le\frac\pi q\to 0$$
and (1) goes to $2\arctan q\to \pi$, hence
$$\lim_{x\to\infty}\sum_{n=1}^\infty \frac{2x}{x^2+n^2}=\pi$$


Is it possible to force your module's update hook to run?

Question: I am the author of the Date iCal module, and the new major version I'm working on (3.x) requires a two-part schema update for users who had 2.x installed. I've written the update hook that makes these changes, but if one of my users fails to run the database update script, they will get an error message relating to their iCal feeds importers.
The right solution is for them to run the update script... but if they just go in and manually change their importers to get rid of the message, their importers will remain permanently broken (because the second part of the schema update won't have been executed).
So is there any way to display a message to users who haven't run the update? Or somehow forcibly execute the update hook the first time a page load occurs when 3.x gets installed overtop of 2.x?
Comment: I would imagine you could do a `variable_set()` in your update function that sets a variable when it was successfully run that you could look at inside a `_preprocess_page()` but you'd be looking at it every time so not sure how performance friendly this would be.
Answer: There are few ways of forcing module update.

Calling the update function directly.
$sandbox = [];
module_load_include('install', 'FOO');
FOO_update_7001($sandbox);

Resetting the schema version to the point of interest and run the updates again as usual.
drupal_set_installed_schema_version('module_name', '7000');

Or reset to re-run only the latest update schema:
drupal_set_installed_schema_version('foo', drupal_get_installed_schema_version('foo') - 1);

Notes:

This can be placed in hook_install, so during the update process all sequent update hooks would be executed.
In order to use this function outside of the installation file, you've to include Drupal install.inc first and installation file of the module, e.g.
require_once DRUPAL_ROOT . '/includes/install.inc';
module_load_include('install', 'foo');

Consider adding ini_set('max_execution_time', 0); for longer installation updates to prevent PHP timeouts.

Using drush. Find below few examples:

drush eval 'module_load_include('install', 'foo'); $s = []; foo_update_7001($s);'
drush sqlq "UPDATE system SET schema_version = 7000 WHERE name = 'foo'" && drush -y updb
Comment: Oh nice, I didn't know about `drupal_set_installed_schema_version()`. That'd be super handy for debugging update hooks!
Comment: So the main problem with putting it into `hook_install()` is running long batched (sandboxed) updates.
In ideal situation, there should be a way to trigger updates in the same way as `update.php` does with restarting PHP thread to prevent timeouts.
Ant ideas how to do that?
Comment: @Alex.Designworks You can add `ini_set('max_execution_time', 0);` before triggering the updates.
Comment: Just want to add the this drush command example was clutch! Still works great on Drupal 9.3.x! `drush eval 'module_load_include('install', 'foo'); $s = []; foo_update_7001($s);'`
Answer: extending on comment from Jimajamma:

do a variable_set() in your update function that sets a variable when it was successfully run that you could look at inside a _preprocess_page()

and instead of checking this on every page load do it only if browsing the admin area and if the installed version is 3.0 (3.1, 3.2, kill that check if you stop supporting the old version as an upgrade path).
Additionally make use of hook_requirements to provide feedback on the status report page:

Check installation requirements and do status reporting.
  (...)
  The 'runtime' phase is not limited to pure installation requirements but can also be used for more general status information like maintenance tasks and security issues.
Answer: You could "SELECT schema_version FROM system" to detect whether an update has been performed. If not, then refuse to run (with an error message).
Comment: Please reword your answer, and try to give a usage example.
Comment: I'm afraid that won't work, because the functionality in question is a plugin for another module, and I can't prevent that module from letting users mess with their importers.
Comment: You cannot check the schema version of the module which you intend to monitor for updates?
Answer: I agree with the above suggestions - my only addition would be to investigate "Triggers and Actions" also - it seems that you need an action (notify user or run update) to occur when a trigger (user checks admin page, etc) is pulled. For use examples see the Examples module, there are both action and trigger example code. :)
Answer: function MYMODULE_install() {
  $functions = get_defined_functions();
  foreach ($functions['user'] as $function) {
    if (strpos($function, 'MYMODULE_update_') === 0) {
      call_user_func($function);
    }
  }
}
Answer: Using Drush you can force your hook to run
ddev drush eval 'module_load_include('install', 'module_name'); $s = []; module_hook_9001($s);'


Count possible traversals in an undirected graph

Question: A graph of $n$ nodes is given. We have to visit each node twice. How many such traversals are there?
It's a complete graph and it's not possible to visit the nodes in a consecutive order.
Example: we have $4$ nodes, $A$, $B$, $C$ and $D$.
One possible path would be: $A B A C D B D C$
Path $A A B C D B C D$ would be invalid, since we visited the node A in a consecutive order.
I reckon there are $(2n)! / (2!)^n$ possibilities to traverse such a graph, but how do I exclude the consecutive visits ("$AA$" or "$BB$")?
Comment: For some basic information about writing math at this site see e.g. [here](http://meta.math.stackexchange.com/questions/5020/), [here](http://meta.stackexchange.com/a/70559/155238), [here](http://meta.math.stackexchange.com/questions/1773/) and [here](http://math.stackexchange.com/editing-help#latex).
Answer: You can do it with an inclusion-exclusion argument. Let $S$ be a set of $k$ of the vertices. Then there are $$\binom{2n-k}k\cdot k!\cdot\frac{(2n-2k)!}{2^{n-k}}=\frac{(2n-k)!}{2^{n-k}}$$ traversals that visit each of the $k$ vertices in $S$ (and possibly some other vertices as well) twice in succession: there are $\binom{2n-k}k$ ways to choose where in the traversal the $k$ vertices in $S$ will come, $k!$ ways to permute the vertices in $S$ amongst those positions, and $\frac{(2n-2k)!}{2^{n-k}}$ ways to arrange the rest of the traversal. Since there are $\binom{n}k$ sets of $k$ vertices, the number of traversals that do not visit any vertex twice in succession is
$$f(n)=\sum_{k=0}^n(-1)^k\binom{n}k\frac{(2n-k)!}{2^{n-k}}\;.\tag{1}$$
The first few values are $f(1)=0,f(2)=2,f(3)=30$, and $f(4)=864$; these are enough to identify the sequence as OEIS A114938, described as the number of permutations of the multiset $\{1,1,2,2,\dots,n,n\}$ with no two consecutive terms equal. The formula given there is $$f(n)=\sum_{k=0}^n(-1)^{n-k}\binom{n}k\frac{(n+k)!}{2^k}\;,$$ which is simply $(1)$ with $k$ replaced by $n-k$. There does not appear to be a nice closed form.


hover não funciona

Question:

.csgo-player {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.csgo-player-link {
  width: 40%;
  position: relative;
}

.csgo-player-info {
  padding: 10px;
  height: 200px;
  width: 100%;
  background-color: green;
  position: absolute;
  display: none;
}

.csgo-player-link:hover .csgo-player-info {
  display: block;
  position: absolute;
  z-index: -1;
}

arT

        Andrei Piovezan - IGL

        Download CFG

Quero que quando der um hover no .csgo-player-link, o .csgo-player-info apareça... Alguém pode me ajudar?
Answer: Resumidamente, o problema é que seu HTML está muito mal estruturado.

O código inicia com um
 avulso;

Aqui podemos até considerar que você omitiu o resto do código, mas é apenas uma suposição.

Você tem uma âncora  que não é uma âncora;

Âncoras são elementos que provem navegação, mas você está usando apenas para ter um hover.

Você tem elementos filhos dentro de uma âncora que não fazem sentido;

Lista como filho de âncora? Faz sentido eu clicar sobre a lista e ser redirecionado à outra página? Parece que não é o caso.
E o problema principal: uma âncora como filha de outra âncora? Isso não faz o menor sentido.

Reduzindo o seu código ao mínimo verificável você basicamente possui:

    Clique aqui

Se eu clicar em "Clique aqui", irei para a página "//url_A" ou "//url_B"?

  Clique aqui

Ao inspecionar a página, verá:

É exatamente esse conflito que quebra o seu código. Basta inspecionar a sua página para avaliar qual é o HTML que o navegador processou:

Perceba que tem nada a ver com o código que você originalmente escreveu.
Para resolver o problema, você terá que corrigir a estrutura do seu HTML para algo que faça sentido, principalmente corrigindo essa âncora que não é âncora.

.csgo-player {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.csgo-player-link {
  width: 40%;
  position: relative;
}

.csgo-player-info {
  padding: 10px;
  height: 200px;
  width: 100%;
  background-color: green;
  position: absolute;
  display: none;
}

.csgo-player-link:hover .csgo-player-info {
  display: block;
  position: absolute;
  z-index: -1;
}

arT

      Andrei Piovezan - IGL

      Download CFG

Answer: Pelas especificações HTML, é incorreto usar elemento  dentro de outro  como está fazendo. Ao fazer isso, o navegador irá automaticamente fechar o primeiro , fazendo com que o segundo  se torne um elemento separado do primeiro , como mostra o print:

Com isso, o seletor .csgo-player-link:hover .csgo-player-info se
  torna inválido.

Neste caso, utilize uma div em vez de , e coloque na classe .csgo-player-link a propriedade cursor: pointer para alterar o cursor do mouse na div para que o usuário perceba que ali há alguma interação:

.csgo-player {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.csgo-player-link {
  width: 40%;
  position: relative;
  cursor: pointer; /*ALTERA O CURSOR*/
}

.csgo-player-info {
  padding: 10px;
  height: 200px;
  width: 100%;
  background-color: green;
  position: absolute;
  display: none;
}

.csgo-player-link:hover .csgo-player-info {
  display: block;
  position: absolute;
  z-index: 0;
}

arT

           Andrei Piovezan - IGL

           Download CFG

Answer: Troca o a por div; acredito que a não tenha características que permitam fazer isso como a div. Eu vi isso aqui http://jsfiddle.net/zEJVK/6/
.cp-thumb:hover .cp-hover { display:block; }

.csgo-player {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.csgo-player-link {
  width: 40%;
  position: relative;
}

.csgo-player-info {
  padding: 10px;
  height: 200px;
  width: 100%;
  background-color: green;
  position: absolute;
  display: none;
}

.csgo-player-link:hover .csgo-player-info {
  display: block;
  position: absolute;
  z-index: -1;
}

arT

        Andrei Piovezan - IGL

        Download CFG

Comment: No exemplo que postou pelo JSFiddle, ao substituir todas as `div.cp-thumb` por âncoras `a.cp-thumb` [funcionará normalmente](http://jsfiddle.net/tp7q04Le/), o que mostra que sua premissa, de que com `` não funciona está equivocada.
Comment: Obrigado pelo exemplo! Eu troquei no código de exemplo da pergunta e funcionou. Nesse cenário específico não funcionou com a e com div sim. Não estudei a fundo o porquê da diferença.
Comment: Se puder por favor tentar fazer funcionar com  meu código que está funcionando com  na resposta, ficaria grato de entender.
Comment: Leonardo, coloquei a explicação em forma de resposta
Answer: É só vc colocar um target para o hover, assim: .csgo-player-link:hover .csgo-player-info{
display:block;}Por padrão o target é o proprio elemento.
Comment: E não está exatamente assim no código da pergunta?
Comment: AAh sim , desculpe. Já tentou usar !important ?

hover não funciona


Prove if $f$ is continuous at a and $g$ is discontinuous at a, then $f + g$ is discontinuous at a

Question: Hello I want to prove: if $f$ is continuous at $a$ and $g$ is discontinuous at $a$, then $f + g$ is discontinuous at $a$. But with the $\epsilon - \delta$ definition of continuity and discontinuity (I see that the far more concise way of proving this would be to assume to the contrary that $f+g$ is continuous and then finding a contradiction from $g = (f + g) - f$).
So far I have:
Let $\epsilon > 0$ be given. Then since $f$ is continuous at $a$, there exists $\delta_{1} > 0$, such that
$$|x - a| < \delta_{1} \implies |f(x) - f(a)| < \epsilon.$$
And since $g$ is discontinuous at $a$, there exists $\epsilon_{0} > 0$ such that for all $\delta_{2} > 0$,
$$|x - a|<\delta_{2} \land |g(x) - g(a)| \ge \epsilon_{0}.$$
Now I want to show that there exists an $\epsilon_{1} > 0$ such that for any $\delta > 0$,
$$|x - a| < \delta \land |f(x) + g(x) - (f(a) + g(a))| \ge \epsilon_{1}.$$
So now I need to find an appropriate $\epsilon_{1}$ and I think I should use the reverse triangle inequality to try to show this inequality holds
$$0 < \epsilon_{1} \le ... \le |g(x) - g(a)| - |f(x) - f(a)| \le |g(x) - g(a) + f(x) - f(a)|$$
What seems problematic is the $|f(x) - f(a)|$ since there doesn't seem to be a way to bound it since $\delta$ can be any positive real number. I'm kind of wondering if this will even work or if another route needs to be taken. Any help would be much appreciated, thanks!
Answer: I'm not sure if your post is indicating that you know this, but there is a quick proof using a relatively well known fact: the sum of two continuous functions is continuous. Assume $f+g$ is continuous. Then since $f$ is continuous, $-f$ is continuous. Therefore $(f+g)+(-f)=g$ is continuous, contradiction.
If you don't know this fact already, I would recommend trying to prove it for yourself. The crucial step is to consider $\delta=\max{(\delta_f,\delta_g)}$.
You can actually use the proof of the above statement to prove your question by contradiction. As you've noted, the fact that $\delta$ can be any real number can be problematic. However, you do have a statement that is true for all $\delta$, namely
$$\exists\epsilon_g\forall\delta_g\exists x_g\text{ such that }|x_g-a|<\delta_g\wedge |g(x_g)-g(a)|>\epsilon_g$$
This fact is the one that you want to leverage to get your result. I think by contradiction would be the best way to proceed. So, you assume $$(\forall\epsilon)(\exists\delta)(\forall x)(|x-a|<\delta\Rightarrow|f(x)+g(x)-f(a)+g(a)|<\epsilon)$$ and you have that $$(\forall\epsilon')(\exists\delta')(\forall x)(|x-a|<\delta'\Rightarrow|f(x)-f(a)|<\epsilon')$$ so therefore $$|g(x)-g(a)|=|f(x)+g(x)-(f(a)+g(a))-(f(x)-f(a))|\leq \epsilon+\epsilon'$$ by the triangle inequality, which contradicts that $g$ is discontinuous once you do a bit of tweaking of $\delta$'s and $\epsilon$'s.
Comment: Thanks! That is really helpful. Going for a contradiction in the end seems like the best way. And just to see if I got the remaining details, I would just choose $\delta$ for $g$ to be $min\{\delta, \delta'\}$.
Comment: Yes I know of this proof for this, and it is a far more sensible proof of this. I was just wondering if there was a way with using $\epsilon$ - $\delta$, to see if I could make the inequalities work out, but I seem to be a bit stuck.
Comment: @user330531 I edited it to include a proof with $\delta$ and $\epsilon$
Comment: @user330531 you also have to talk about how the $\epsilon$'s relate, but I think if you sit down and try to write it it'll all pop out.
Answer: You could use the sequential characterization of continuity, which says that $f$ is cts at $a$, if and only if for every sequence $x_n$ converging to $a$, we have that $f(x_n)$ converges to $f(a)$.
Now, let some arbitrary sequence converge to your point $a$.
We have that $(f+g)(x_n)$ = $f(x_n) + g(x_n)$, which does not converge to $f(a) + g(a)$ = $(f+g)(a)$, by assumption, since $g$ is known to be discts at $a$.
This shows that the function $f+g$ is discts at $a$, as required.
Answer: The direct approach will work. Remember that if $g$ is discontinuous at $a$, then there exists $\varepsilon_g>0$ such that for every $\delta>0$ there exists an $x$ within $\delta$ of $a$ such that $|g(x)-g(a)|\ge \varepsilon_g$. (Your solution left out the "there exists an $x$" part.)
Proof continues as follows. Since $f$ is continuous at $a$, there exists $\delta_f>0$ such that $|x-a|<\delta_f$ implies $|f(x)-f(a)|<\varepsilon_g/2$.
We'll show that $h:=f+g$ is discontinuous at $a$, with $\varepsilon_g/2$ as the magic value. So let $\delta>0$. Since $g$ is discontinuous at $a$, there exists $x$ such that $|x-a|<\min(\delta, \delta_f)$ and $|g(x)-g(a)|\ge\varepsilon_g$. For this $x$ we have
$$|h(x)-h(a)|\stackrel{(1)}\ge|g(x)-g(a)|-|f(x)-f(a)|\stackrel{(2)}\ge\varepsilon_g-\varepsilon_g/2=\varepsilon_g/2.$$
Step (1) is the reverse triangle inequality, as you've done. In step (2) we use the fact that $|x-a|<\delta$ (so that $|g(x)-g(a)|\ge\varepsilon_g$), and the fact that $|x-a|<\delta_f$ (so that $|f(x)-f(a)|<\varepsilon/2$).
Comment: Thanks, this is what I was trying to think of. I do have a question, why is it possible to choose $|x-a| < min(\delta, \delta_{f})$? It seems to me that this goes against the 'for any $\delta > 0$' part of the definition of discontinuity. Not sure if the question I'm trying to articulate makes sense.
Comment: The key is that given the original $\delta$ (the one in the "So let $\delta>0$"), the number $\delta_2:=\min(\delta,\delta_f)$ is another delta, and apply the definition of discontinuity to *that* delta. By def, there exists $x$ within $\delta_2$ of $a$ such that...


Preferred INNER JOIN linking sequence

Question: I am linking three tables from the FDA's MedWatch system that have a common Individual Safety Report, or ISR, field. The three tables are Demographics (unique record), Drugs (unique record, but linked to the Demographics record) and Reactions (one or more records, each linked to either the Drugs or the Demographics record).
My question is that since the Reactions.ISR can be INNER JOINed to either the Drugs or the Demographics table, is there a preferred way?
E.g. can be:
SELECT Demographics.Case, Demographics.ISR, Drugs.DrugName, Reactions.PT
  FROM (Reactions INNER JOIN Drugs ON Reactions.ISR = Drugs.ISR)
    INNER JOIN Demographics ON Drugs.ISR = Demographics.ISR

which links in a Demographics <- Drugs <- Reactions hierarchy
or:
SELECT Demographics.Case, Demographics.ISR, Drugs.DrugName, Reactions.PT
  FROM Reactions INNER JOIN (Drugs INNER JOIN Demographics ON Drugs.ISR = Demographics.ISR)
    ON Reactions.ISR = Demographics.ISR

which independently links the Drugs record and the Reactions record(s) to the Demographics record.
Both return the same recordset, but I wondered if one method was preferred over the other as a best practice, perhaps making the query execute faster. i.e. is it possible to improve the query performance by altering the JOIN sequence?
Answer: To compare the performance of two queries you should look at their execution plans. For instance in this case you might find that you get identical plans in which case that proves that it doesn't matter.
Answer: How a query is optimized depends on the database.
In terms of inner joins (and where clauses) its often best to start from the most restrictive table (or condition) first and then link out to the "wider" joins/conditions.
Given that these joins aren't that restrictive - i.e. there aren't any further conditions applied then they'll probably be equivalent - look at the query plans of the two approaches to check.

Preferred INNER JOIN linking sequence


Remote Database Connection Setup in Netbeans

Question: I'm totally junior in this area :)
I have JAVA version 7 on my PC.

I want to connect my PostgreSQL database to NetBeans.
Based on my search I found that I should get JDBC driver. so I downloaded JDBC41 Postgresql Driver, Version 9.3-1100 jar files from here.
then based on what I found for connection remote Mysql, did similar changes to connect to my PostgreSQL database.

As you can see in the image, connection couldn't established.
Based on what my host says, I added my IP address to "Remote PostgreSQL Database Access" page of my host.
I'm not sure my host name is correct. I used Dedicated IP Address of my site.
Any suggestion would be appreciated. Thanks
Answer: My fault was entering wrong user name and pass instead of using user name and password of database :(


Estimating the likelihood of an observed path for a continuous state space Markov process

Question: Problem statement
Let $\mathbb{X} \subset \mathbb{R}^{k}$ and let
$p:\mathbb{X}\times\mathbb{X}\rightarrow\mathbb{R}$ be a density kernel on
$\mathbb{X}$. We assume the following model for the stochastic process
\begin{equation}
  X_{t+1}\sim p(X_t, y)dy \quad (t\geq1),
\end{equation}
which defines a discrete time Markov process ${(X_t)}_{t\geq1}$ on $\mathbb{X}$. Let $X_0$ be a given initial state, and let $(y_i)_{i=1}^{T}$ be an observation, or realization, of that Markov process.
Furthermore, assume that we have observed another $n$ independent paths ${(x_{i}^{j})}_{i=1}^{T}$, where $j=1,\dots, n$, from the discrete time Markov process.
Would anyone be able to tell me what can be said about the equation
\begin{equation}
\frac{1}{n}\sum_{j=1}^{n}\prod_{i=1}^{T}p(x_{i-1}^{j}, y_i),
\end{equation}
and in particular what happens in the limit as $n\rightarrow\infty$?
This has been proposed to me as a way of estimating the likelihood, or density, of the observed path $(y_i)_{i=1}^{T}$ for the assumed model of the stochastic process, with the motivation that it propagates the uncertainties of the model, but I have been unsuccessful in understanding the equation.
I hope that this is clear enough to at least give a hint which may lead me down the proper path.
Insights (update)
I have found a paper by Stachurski et. al (2008), which give some insight for the problem.
The marginal distribution of $y$ at time $t$,
$\mathbb{P}(X_t = y)$, can be written (assuming a given initial condition) as
\begin{equation}
  \psi_{t}(y) = \int p(x,y)\psi_{t-1}(x)dx,
\end{equation}
and we define an estimate of this as
\begin{equation}
  \psi_{t}^{n}(y) \equiv \frac{1}{n}\sum_{i=1}^{n}p(x_{t-1}^{i}, y),
\end{equation}
where ${(x_{t}^{i})}_{i=1}^{n}$ are $n$ i.i.d realizations, or observations, of the Markov process
at time $t$.
By the law of large numbers we get
\begin{equation}
  \frac{1}{n}\sum_{i=1}^{n}p(x_{t-1}^{i}, y) \rightarrow
  \mathbb{E}p(x_{t-1}^{i}, y) = \int p(x,y)\psi_{t-1}(x)dx = \psi_t(y),
\end{equation}
as $n\rightarrow\infty$ (Stachurski, 2008).
However, this only helps us get insight into estimates of the marginal probability distributions of the discrete time Markov process, and not the joint probability distributions.
We could make the assumption that ${(X_t)}_{t\geq1}$ are i.i.d (which is incorrect by the definition of the model, but lets see what happens), which would allow me to write
\begin{equation}
\label{eq:likelihood_1}
  \mathbb{P}(X_1=x_1, \dots, X_T=x_T) \approx \prod_{i=1}^{T} \psi_{i}^{n}(x_i)
  = \prod_{i=1}^{T} \frac{1}{n}\sum_{j=1}^{n}p(x_{t-1}^{j}, x_t),
\end{equation}
which looks very similar to the equation I have an interest in, the major two differences being that the product is in a different place and the way we draw ${(x_{t}^{i})}_{i=1}^{n}$.
While this helps give some insight into the problem, I am still unable to understand the equation of interest. Namely,
\begin{equation}
\frac{1}{n}\sum_{j=1}^{n}\prod_{i=1}^{T}p(x_{i-1}^{j}, y_i).
\end{equation}
Answer: Sounds like you are you looking for the partition function for a given path and then a functional integral across those paths in the denominator to determine the probability of a given path.
Comment: You know have enough rep to comment anywhere. Congratulations. This is rather a comment than an answer.
Comment: Thank you for your answer. I am sure that you are correct, however, my foremost interest is in understanding the equation suggested. I need to understand the interpretation of it in this context, and if there is no reasonable interpretation (the equation is not meaningful) why that is.

Maybe I would get further insights into the problem if you could elaborate on how to write down a partition function for the given path and a functional integral across those paths? (I do not have the proper background in physics) Keep in mind that I need to be able to make an estimate by computation.


Comparison $\sum_{k=0}^{\infty} a_k$, $\sum_{k=0}^{\infty} a_{n_k}$ with $\lim_{k\rightarrow\infty}\frac{n_k}{k}=l<\infty$

Question: We all know the Limit comparison test:

Suppose that we have two series $\sum_{k=0}^{\infty} a_k$, $\sum_{k=0}^{\infty} b_{k}$ with  $a_k, b_k \geq 0$  for all  $k$.
  Then if  $\lim_{k \to \infty} \frac{a_k}{b_k} = c$ with  $0 < c < \infty$  then either both series converge or both series diverge.

Now, we suppose that there exists a sequence $n_k$ such that $\lim_{k\rightarrow\infty}\frac{n_k}{k}=l<\infty$. Then, can we conclude that either both series converge or both series diverge? Is it an equivalent form of the Limit comparison test?
Comment: Your question is not clear. Suppose there is a sequence $n_k$ with some property. What is the relation of $n_k$ with $a_k$ and/or $b_k$?
Answer: If $\sum a_k$ (with all $a_k\ge 0$) converges then so does $\sum a_{n_k}$, but we cannot conclude inthe other direction. For example let $n_k=2k$, $a_k=1-(-1)^k$.
Comment: Thanks. Can you get a proof please for direction from $\sum a_k$ to $\sum a_{n_k}$?
Comment: @Mark there are counterexamples even for the other direction: consider $a_k=(-1)^n/n$ and $n_k=2k$.
Comment: @Hagen Von Eitzen see my comment above
Comment: @Norbert Oh, I was assuming that the condition $a_k\ge 0$ from the quoted comparison test was assumed for the conjectured test as well ...
Answer: This looks close to the Cauchy condensation test. For it to work, you would need the sequence $(a_k)$ monotonically decresing towards zero as well.
Then
$\sum_k (n_k-n_{k-1})a_{n_k}\le \sum_k a_k\le\sum_k (n_{k+1}-n_k)a_{n_k}$
However, it is not clear to me if the size of $(n_{k+1}-n_k)$ can be meaningfully bounded by $l$.


Conditional homoskedasticity vs heteroskedasticity

Question: From Econometrics, by Fumio Hayashi (Chpt 1):
Unconditional Homoskedasticity:

The second moment of the error terms E(εᵢ²) is constant across the observations
The functional form E(εᵢ²|xi) is constant across the observations

Conditional Homoskedasticity:

The restriction that the second moment of the error terms E(εᵢ²) is constant across the observations is lifted

Thus the conditional second moment E(εᵢ²|xi) can differ across the observations through possible dependence on xᵢ.

So then, my question:
How does Conditional Homoskedasticity differ from Heteroskedasticity?
My understanding is that there is heteroskedasticity when the second moment differs across observations (xᵢ).
Comment: Maybe this will help: http://www2.econ.iastate.edu/classes/econ674/falk/Lecture%2016_conditional_heterosked_I.pdf
Comment: @Henry It is difficult to tell from the present question which definitions are accurate and which ones not--some of them do not seem to make sense out of the context of the textbook.  Some clarification would be welcome.
Comment: There a slight issue in that the lecture says "Therefore, conditional homoskedasticity implies unconditional homoskedasticity" in contradiction to the Econometrics book.  They seem to be conditioning on different things.
Answer: I will begin by just quoting from Hayashi to help anybody else who would like to comment.  I have tried to preserve formatting and original equation numbers.
Begin quote from Hayashi page 126, section 2.6:
Conditional versus Unconditional Homoskedasticity
The conditional homoskedasticity assumption is:
Assumption 2.7 (conditional homoskedasticity):
\begin{align*}
\tag{2.6.1} E(\epsilon_i^2|\mathbf{x}_i)=\sigma^2>0.
\end{align*}
This assumption implies that the unconditional second moment $E(\epsilon_i^2)$ equals $\sigma^2$ by the Law of Total Expectations.  To be clear about the distinction between unconditional and conditional homoskedasticity, consider the following example [Example 2.6 (unconditionally homoskedastic but conditionally heteroskedastic errors)...]
End quote.
Some relevant equations from Hayashi pages 11-14 (Section 1.1):
\begin{align*}
\tag{1.1.12} E(\epsilon_i^2|\mathbf{X})=\sigma^2>0 \quad (i=1,2,\ldots,n) \\\
\tag{1.1.17} E(\epsilon_i^2|\mathbf x_i)=\sigma^2>0 \quad (i=1,2,.\ldots,n).
\end{align*}
The subsection "The Classical Regression Model for Random Samples" on page 12 discusses the implications of a sample being iid.  Quoting from Hayashi pages 12-13: "The implication of the identical distribution aspect of a random sample is that the joint distribution of $(\epsilon_i,\mathbf x_i)$ does not depend on $i$.  So the unconditional second moment $E(\epsilon_i^2)$ is constant across $i$ (this is referred to as unconditional homoskedasticity) and the functional form of the conditional second moment $E(\epsilon_i^2|\mathbf x_i)$ is the same across $i$.  However Assumption 1.4---that the value of the conditional second moment is the same across $i$---does not follow.  Therefore, Assumption 1.4 remains restrictive for the case of a random sample; without it, the conditional second moment $E(\epsilon_i^2|\mathbf x_i)$ can differ across $i$ through its possible dependence on $\mathbf x_i$.  To emphasize the distinction, the restrictions on the conditional second moments, (1.1.12) and (1.1.17), are referred to as conditional homoskedasticity."
[No further quotes from Hayashi, just my understanding after this point.]
I assume the original question was about the above discussion on pages 12-13.  In that case, I think the first bullet under "Conditional Homoskedasticity" isn't technically correct (though I understand what you mean): Hayashi says (1.1.17) is "conditional homoskedasticity," and if $E(\epsilon_i^2|\mathbf x_i)=\sigma^2$, then $E(\epsilon_i^2)=E[E(\epsilon_i^2|\mathbf x_i)]=E[\sigma^2]=\sigma^2$, as Hayashi notes on page 126 (that conditional homoskedasticity implies unconditional homoskedasticity by the Law of Total Expectations).
So I think part of the issue may be the interpretation of Hayashi's statements.  Conditional homoskedasticity says (1.1.17) even for different $\mathbf x_i$, the variance of $\epsilon_i$ is the same constant $\sigma^2$.  Unconditional homoskedasticity is a weaker statement, in that you could have $E(\epsilon_i^2)=\sigma^2$ but $E(\epsilon_i^2|\mathbf x_i)\ne\sigma^2$; Examples 2.6 (page 127) illustrates this.  It also perhaps answers the question of the overlap between homo- and heteroskedasticity: it gives an example where there is unconditional homoskedasticity as well as conditional heteroskedasticity.
These are confusing concepts, especially without a lot of experience with conditional expectations/distributions, but hopefully this adds some clarity (and source material for any future discussions).
Comment: It might help to summarize those examples here to more fully clarify the distinction between these confusing concepts.


read epub file page by page using epublib

Question: i'm working on an application in which i want to read epub file page by page using epublib and  show in a app , i am able to get all contents of book chapter wise  , now i want to get contents page wise , plz answer if you have any idea , thanks in advance
here is code that i used for getting contents of book chapter wise
<code>    public String getText(String filepath) {

    String linez = "";
    File f = new File(filepath);

    InputStream epubInputStream = null;
    try {
        epubInputStream = new FileInputStream(f);
    } catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    Book book = null;
    try {
        book = (new EpubReader()).readEpub(epubInputStream);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Spine spine = book.getSpine();
    List<SpineReference> spineList = spine.getSpineReferences();
    int count = spineList.size();
    txtpages.setText("Size:" + Integer.toString(count) + "\n");
    StringBuilder string = new StringBuilder();
    for (int i = 0; count > i; i++) {
        Resource res = spine.getResource(i);

        try {
            InputStream is = res.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is));
            try {
                while ((line = reader.readLine()) != null) {
                    linez = string.append(line + "\n").toString();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            // do something with stream
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //webView.loadData(linez, "text/html", "utf-8");

    return linez;
}
</code>
Comment: You need to clarify what you mean by "now i want to get contents page wise". Do you mean that you want to paginate each XHTML file of the  of your EPUB? If so, you need to inject your own CSS and load CSS+XHTML into the WebView, or you need to split the XHTML contents within your Java code.
Comment: yes i want to paginate each xhtml
Comment: were you able to find an answer how to paginate it.
Comment: @ArunavhKrishnan Krishnan i didn't find the solution
Comment: try this http://stackoverflow.com/a/41122252/7235539
Answer: You may able to seperate an epub file page by page by using EpubParser. Even though it still has some issues it does its job.


Como buscar diferentes extensões de arquivos

Question: Estou procurando uns arquivos com o final .jar, .py e .sh, porém só quando coloco um deles o código roda.
finded = re.findall(r'\w*.jar\b'|'\w*.sh\b'|'\w*.py\b', text)
Mensagem de erro:

TypeError: unsupported operand type(s) for |: 'str' and 'str'
Comment: Dica: a conjugação de _to find_ no pretérito é _found_ e não _finded_.
Answer: Não é necessário repetir a regex inteira. No caso do seu código nem faz sentido, porque você está tentando "combinar" várias strings com o operador | e Python não aceita este tipo de construção até onde eu sei.
O que você precisa é usar estes operadores para combinar diferentes padrões aceitos na regex.
Uma regex que funciona seria: \w*\.(jar|sh|py)\b, onde:

\w: Qualquer caracter
*: Zero ou mais do padrão anterior
\.: Encontra o literal para ponto
(jar|sh|py): Encontra um dos literais (jar ou sh ou py)

import re
found = re.findall(r'(\w*\.(jar|sh|py)\b)', 'teste.jar script.sh program.exe script.bat')
print(found) # [('teste.jar', 'jar'), ('script.sh', 'sh')]

Veja funcionando no Repl.it
Answer: Primeiro veja bem o que você fez. Você criou três strings e colocou | entre elas:
     finded = re.findall(r'\w*.jar\b'|'\w*.sh\b'|'\w*.py\b', text)
#                         ^         ^ ^        ^ ^        ^
     #                    |         | |        | |        |
     #                    |         | |        | |        |
# aqui começa a           |         | |        | |        \__ aqui termina a terceira string
# primeira string ________/         | |        | |
     #                              | |        | |
     #                              | |        | |
     #                              | |        | \__ aqui começa a terceira string
     #                              | |        |
     #                              | |        \__ aqui termina a segunda string
     #                              | |
# aqui termina a primeira string ___/ \___ aqui começa a segunda string

Ou seja, você está tentando fazer string | outra_string | e_mais_outra_string. Só que o | não é um operador válido para strings, daí o erro.
Para resolver bastaria eliminar as aspas do meio, deixando tudo em uma única string:
re.findall(r'\w*.jar\b|\w*.sh\b|\w*.py\b', text)

Mas tem muita redundância aí. Você pode fazer como a outra resposta ((\w*.(jar|sh|py)\b)), mas eu sugiro algumas alterações:

\w* significa "zero ou mais letras, dígitos ou _". Isso quer dizer que se o nome do arquivo for apenas .jar, será aceito (pois tem zero caracteres antes do ponto). Você pode trocar para \w+ (uma ou mais ocorrências), pois aí garante que deve ter pelo menos um caractere antes do ponto (a menos, é claro, que você queira mesmo pegar nomes como .jar)
O ponto corresponde a qualquer caractere (exceto quebras de linha), então se quiser somente o caractere ., tem que ser \.
os parênteses formam grupos de captura, e quando estes estão presentes, findall retorna todos os grupos. No caso, a extensão está em um grupo, então além do nome do arquivo, será retornado também a extensão separadamente. Mas se quer apenas os nomes dos arquivos, pode trocar para grupos de não-captura, usando (?: em vez de apenas (

Ou seja:
import re

text = 'abc.txt def.jar g123.sh aaa.c xyz.py'
arquivos = re.findall(r'\w+\.(?:jar|sh|py)\b', text)
print(arquivos) # ['def.jar', 'g123.sh', 'xyz.py']

Indo um pouco além, nomes de arquivos não se resumem a letras, números e _ (que é o que o \w reconhece). Podemos ter nomes como abc-def-1.0.15.tar.gz e até mesmo nomes com espaços. Neste caso, o \w não é suficiente, e teria que ser algo assim:
import re

# o nome com espaços tem \ antes do espaço para diferenciar do espaço que separa dois arquivos
text = r'abc-def-1.0.15.jar nome\ com\ espaços.sh'
arquivos = re.findall(r'\b(?:[\w\-.]|\\ )+\.(?:jar|sh|py)\b', text)
print(arquivos) # encontra os dois arquivos

Ou seja, agora antes da extensão o nome pode ter \w (letras, números e _), hífen e ponto, além de espaços (desde que seja escapado por \).
Mas enfim, já estamos indo além da pergunta, foi só para mostrar que regex não é algo "mágico", e que quanto mais complicados os casos, pior ela vai ficando.
Por fim, se estiver fazendo a busca no sistema de arquivos (pois não é dito de onde vem o text), tem maneiras melhores de resolver.
Answer: consegui alterando dessa forma:
found = re.findall(r'\w*.jar\b|\w*.sh\b|\w*.py\b', text)
já estou aprendendo inglês junto, troquei o nome da variável tb!
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How to include [] in python regex code?

Question: I am using python 2.7.8 to write a small python code that reads a rule in a form A ==> B by using regex and return it in a form of 'A, B'.
This is my code:
import re

def fixp1(s):
    pattern = re.compile("(?P<g1>([A-Z0-9a-z]|\?)*):(?P<g2>([A-Z0-9a-z]|\?)*)")
    return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))

x = "[ABCD:NP, [PQR:?TAG1]] ==> [XXX:?P]"

def readrule(r):
    r.split("==>")
    return [fixp1(r[0].strip()), fixp1(r[1].strip())]

When I test this code:
>>> readrule(x)

I got the following error message:
readrule(y)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File ".../patterns.py", line 12, in readrule
        return [fixp1(r[0].strip()), fixp1(r[1].strip())]
    File ".../patterns.py", line 5, in fixp1
        return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))
    File "<string>", line 1
        [
        ^
SyntaxError: unexpected EOF while parsing
>>>

I think this problem happened because I couldn't add '[' and ']' in here
([A-Z0-9a-z]|\?)

If that's right, how to do it? if not; where is my mistake?
Answer: Remove the eval command, the RegEx.sub returns a string which is your match with the replacements applied, you cannot evaluate the string. This yields the SyntaxError you are seeing.
If you want to include [] in your patterns, you need to escape them with \:
 pattern = re.compile(r'[\[\]0-9]+')

would match strings like '[1234]'.
Comment: Yes, you'd need to do something like `left, right = r.split('==>')` to get the left and right hand side of the rule.
Comment: I need 'eval' as I need the output as a list not a string. But I follow what you said , the results was quite weird:
>>> readrule(x)
readrule(x)
['[', 'A']
>>>

So, it might be not this is my problem.
Comment: That seems to give me r[0] the first character '[' and r[1] the second 'A'. I tried to do 'eval' after separating the rule

    def readrule(r):
        r.split("==>")
        n = eval(r)
        return [fixp1(n[0].strip()), fixp1(n[1].strip())]

But this gave me another problem (invalid syntax)
Comment: Ok, I did some changes an it worked , I changes eval place to the end.

    def readrule(r):
    n = r.split("==>")
    return [eval(fixp1(n[0].strip())), eval(fixp1(n[1].strip()))]

How to include [] in python regex code?


Calculating number of three consecutive values above a threshold (in raster stack)

Question: I need to compute number of three consecutive days when value of each pixel in a raster stack (x) is above a given threshold (defined by another raster y). I tried using rle for the purpose with calc as follows after stacking x and y together into new raster a:
library(raster)
fn<-function(a) with(rle(a), sum(lengths>=3 & values>a[[nlayers(a)]]))
calc(b,fn)

However, I am getting the error:

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
  cannot use this function

Reproducible sample:
x1 <- raster(nrows=10, ncols=10)
 x2=x3=x4=x5=x6=x1
 x1[]= runif(ncell(x1))
 x2[]= runif(ncell(x1))
 x3[]= runif(ncell(x1))
 x4[]= runif(ncell(x1))
 x5[]= runif(ncell(x1))
 x6[]= runif(ncell(x1))
 x=stack(x1,x2,x3,x4,x5,x6)
 y=x1
 y[]= runif(ncell(x1))
 a<-stack(x,y)

Can someone please help.
Comment: Please give a reproducible example (you need to `dput()` some sample data). Hover your pointer over the `r` tag for more info.
Comment: @Hack-R I have edited the question accordingly.
Answer: Based on Lorenzo's answer I modified the code and this is exactly what I was looking for.
# create data
x1 <- raster(nrows=2, ncols=2)
x2=x3=x4=x5=x6=x1
x1[]= runif(ncell(x1))
x2[]= runif(ncell(x1))
x3[]= runif(ncell(x1))
x4[]= runif(ncell(x1))
x5[]= runif(ncell(x1))
x6[]= runif(ncell(x1))
x=stack(x1,x2,x3,x4,x5,x6)*4
y=x1
y[]= runif(ncell(x1))*2

#Overlay to get greater than values raster (in form of TRUE and FALSE)
a<-overlay(x,y,fun=function(x,y){x>y})
# function for finding total number of 3 consecutive days when condition is TRUE
fn<-function(a) {
      seq <- rle(a)
      n=sum(seq$lengths[seq$lengths>=3 & seq$values==TRUE])
      return(n)
    }
    calc(a,fn)

But since my solution is based on your answer, so I accept your answer Lorenzo. Thanks!
Answer: You could try this:
 x1 <- raster(nrows=10, ncols=10)
 x2=x3=x4=x5=x6=x1
 x1[]= runif(ncell(x1))
 x2[]= runif(ncell(x1))
 x3[]= runif(ncell(x1))
 x4[]= runif(ncell(x1))
 x5[]= runif(ncell(x1))
 x6[]= runif(ncell(x1))
 x=stack(x1,x2,x3,x4,x5,x6)*4
 y=x1
 y[]= runif(ncell(x1))*2
 a<-stack(x,y)

 library(raster)

fn<-function(x) {
  seq <- rle(as.numeric(x)>as.numeric(x)[[nlayers(a)]])
  n = length(seq$lengths > 3 & seq$values == TRUE)
  return(n)
}
calc(a,fn)

class       : RasterLayer
dimensions  : 10, 10, 100  (nrow, ncol, ncell)
resolution  : 36, 18  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names       : layer
values      : 1, 7  (min, max)

(note that I modified the example dataset to get some good sequences)
HTH !
Comment: Hey thanks! This code works very well. But when I use this function on my original data I just get 1 as the value for all pixels :(
Comment: don't know.... on the test dataset I think the code was doing what it was supposed to do... Do you have NAs in your input data, by any chance ?


Numeric value in file name causing OnAction error

Question: I'm using the following code to assign a new macro to a button:
ActiveSheet.Shapes("ButtonI").OnAction = AName & "!Import_to_Master"

where the AName is a filename in the format: "Tool - IP1.xls"
Currently it throws up:

Run-time error '1004': Cannot run the macro 'Tool - IP1.xls!Import_to_Master'.

There is no error if there is no numeric value in the filename i.e. if the filename is "Tool - IP.xls".
How can this be solved so that you can use numbers in the filename?
Answer: You're missing the ' needed when using workbooks/sheets with spaces in it:
ActiveSheet.Shapes("ButtonI").OnAction = "'" & AName & "'!Import_to_Master"

assuming AName is "Tool - IP.xls" and is open.
Comment: This did fix the problem, however I don't understand why the same problem didn't occur with other AName that didn't have numbers in them.


Class not dynamically loaded in custom module

Question: I have a very simple Drupal 7 module in which I want to load a custom class. I'm not able to load the class and I get the following error when I enable the module:
Fatal error: Class 'Drupal\testmodule\TestClass' not found in www/sites/all/modules/testmodule/testmodule.module on line 4

Here are the contents of my module files:
testmodule.info
name = "Test Module"
core = 7.x
files[] = src/TestClass.php

testmodule.module
<?php

function testmodule_init() {
  Drupal\testmodule\TestClass::go();
}

src/TestClass.php
<?php

namespace Drupal\testmodule;

class TestClass {
  function go() {
    print 'Foo!';
  }
}

Please could anyone help me understand why Drupal 7's dynamic-loading code registry is not working as documented here: https://www.drupal.org/docs/7/creating-custom-modules/writing-module-info-files-drupal-7x#files ?
Answer: To use namespaced classes in Drupal 7, you can use one of these modules:

https://drupal.org/project/xautoload
https://drupal.org/project/registry_autoload

One reason for choosing one or the other may be if you have other modules that also depend on one of those modules.
Otherwise I guess it is largely a matter of taste.
One difference is that xautoload is more convenient during development, because newly created PSR-4 classes are immediately available without rebuilding the class registry.
On the other hand, it does a lot of things which you probably don't need right now, and the code looks complex.
Of course you could do some profiling to find out which is faster, but as always you would need to be careful what you measure and what you compare. I currently cannot tell you which one is faster, or better for memory.
There is also the alternatives module that can help to have only one of those enabled, instead of both.
Disclaimer: I am the author of one of these modules, and I am subscribed to the autoload tag on drupal.stackexchange.com.
Answer: I believe the reason is that Drupal 7's class loader doesn't account for namespaces, so it would find \TestClass but \Drupal\testmodule\TestClass is not found.
There are two ways around this: don't use namespaces (may not be possible), or include your own class loader as one of the files mentioned in your .info file.
There are examples of trivial autoloaders on this page:
http://php.net/manual/en/language.oop5.autoload.php
Comment: Thank you @rivimey. Removing the namespaces does indeed work. I removed the namespace line from src/TestClass.php and called the go() method in testmodule.module with just

`TestClass::go();`

I've realised this is a duplicate of [https://drupal.stackexchange.com/questions/60830/modules-and-namespaces](this issue)


React if user's text changes in existing node are major

Question: I would like to ask about some ideas about following issue:
I have a content type - answer, that can be created and edited (not deleted) by users. From time to time, for any reason an user can delete all text inside node, thus completely destroying it.
I do not want to be informed about every subtle change in node, but I certainly want to be alerted and possibly approve, if there is a major change in node's content.
So the requirements are:

detect negative change + restrict user to publish changes + alert admin for approval

Solutions?:
1) Count words in node and compare it to word count in node's revision. The word count may be saved inside a field in node and after compared by rules.
2) As suggested by @T-34, use custom module
I found some modules but none of them gives the ability to figure out the difference percentage and use it with rules:
https://drupal.org/project/diff
https://drupal.org/project/rules_diff
https://drupal.org/project/trevi - suggested by @T-34 gives me an error + it seem s to work only on node edit page.
Thank you for ideas.
Answer: I would use Diff and implement hook_entity_diff() (see diff.api.php), which allows modules to provide a comparison about entity properties.
Here you go:
<code>function MYMODULE_entity_diff($old_entity, $new_entity, $context) {
  if ($context['entity_type'] == 'node') {
    $old_body = $old_entity->body[LANGUAGE_NONE][0]['value'];
    $new_body = $new_entity->body[LANGUAGE_NONE][0]['value'];
    $matching = similar_text($old_body, $new_body, $percent);
    $results['line'] = array(
      '#name' => t('Body'),
      '#old' => 'Number of matching chars: ' . $matching,
      '#new' => 'Percentage difference: ' . $percent,
    );
    return $results;
  }
}
</code>
Comment: I edited question a bit. Thank you for code, I need drupal to react somehow based on the number. Best would be rules. This module gives a message with percentage number right?
Comment: Then you just need to add rules implementation. If you are not a programmer, you can hire someone to write this functionality for you - it will take not much time.
Comment: With code above you can see percentage number on page node/NID/revisions by clicking "compare" button, provided by [Diff](https://drupal.org/project/diff).
Answer: After I wrote my first answer, I found module https://drupal.org/project/trevi. It seems to be unsupported, but description says that this module has Difference percentage review method. You can try this module too.
Comment: Hi, I tried this module before but it seems to work only on node edit page.


Is creating CASArray important in Exchange 2010?

Question: I have question here: is creating CASArray in Exchange server important?
If we we don't create CASArray what will be the effect on a server with only one domain and with 20 email accounts.
Thanks
Answer: Unless you have multiple CAS servers in a single site, you don't need to create an array. You wouldn't need multiple CAS servers to handle the load of 20 users. The only other reason to have multiple CAS servers in one site would be to provide high availability. If that's the case, you also need either dedicated CAS servers (no hub transport roles assigned) or a hardware load balancer in order to get the benefit of a CAS array.


How can I authenticate to IBM MQ using XMS .NET Core app running in Linux Docker?

Question: Per my understanding XMS .NET will authenticate with the credentials of the logged in user, which is what our app is doing now running on a Windows server.  But we have been asked to move this app into a Linux Docker container and I am unsure of how XMS .NET is now trying to authenticate.  The process is running under root, so I'm assuming it is trying to authenticate with that and is failing.
Comment: The MQ version that is running your queue managers MUST be MQ V8.0 or higher to perform authentication or you need to use a 3rd party solution (i.e. security exit) like Capitalware's [MQAUSX](https://capitalware.com/mqausx_overview.html) that works with all releases of MQ.
Comment: What version of XMS/MQ are you at? There is XMSC.USERID and XMSC.PASSWORD connection factory properties that can be used specify your own userid and password which will be used to authenticate with queue manager.
Comment: What version of MQ is the queue manager?
Comment: There is a lot of reading between the lines of your question.It will make the task of answering your question easier if we are not having to make assumptions. It currently reads as though you have already tried to migrate the code, so I guess it is already using .net core. But the migrated code is failing to authenticate. Is this correct? If so what error are you seeing?
Comment: @Shashi we are at IBM MQ 7 and from what I have read and tried, XMS tries to use the account of the person running the process, so in the case and Windows account.  The XMSC.USERID is ignored, right?  https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_8.0.0/com.ibm.mq.msc.doc/prx_userid.htm
Comment: @chughts so yes, this .net core process is already in production on a Windows server, but we have been asked to migrate it to a Linux Docker container.  Basically, how to authenticate a client running on Linux to the Queue Manager running on a Windows server.  I have been able to get it to work by creating the same service account in the Linux container that we use in the Windows domain and run it using that account, but it is an ugly work around.  I keep seeing something about security exits?
Comment: @Roger, this issue has come back up.  I do not see that MQ V8.0 or higher offers any more solution to this.  Per IBM the XMSC_USERID has to match that of the currently logged on user (https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_8.0.0/com.ibm.mq.msc.doc/prx_userid.htm).  Security exist seems like the only solution.
Comment: Hi, MQ v8 (which is out of support now) added CONNAUTH, this allows you to pass a userid and password from .NET to MQ to be authenticated on the server.  What you describe working when it runs on windows is no authentication at all, it means the queue manager is accepting the ID your process is running under on windows, but it is not authenticating it.  As you saw in docker you just created that ID and worked, but that same example anyone that can connect to the IP and port of your queue manager can do the same.
Comment: Using CONNAUTH you send both a username and password and MQ will authenticate it against either the OS or LDAP depending on how the MQ admin configures it.  The other option is to present a cert to the queue manger and have the queue manager validate the DN value of the cert you present and map you to a specific MCAUSER on the channel.  Both of these allow your client to prove to the queue manager that you are authorized to connect.
Answer: So sorry I did not post the solution to my question earlier, but basically, the IBM MQ server has a service account in a Windows domain which we need to authenticate as.  If you run the XMS .NET client using Windows impersonation you can connect to the MQ as that service account.  We put this XMS .NET client in a Linux Docker container, created this service account in the Linux container, and it runs under that account.  IBM allows this as "cross domain" authentication.  Violla!
Comment: See my comments on your question, for what you setup there is no authentication going on.   Anyone that has network access to your windows queue manager can do the same thing you did and connect.   Enabling CONNAUTH on the queue manager and having the client send both a username and a password will actually authenticate and you would not need to worry about creating the user in the Docker container.
Comment: "IBM allows this as "cross domain" authentication." is a false statement.
Comment: I will have to talk to my Dev Ops guys who set up the Queue Manager about using CONNAUTH.  Currently, you do have to be running a client under a specific service account in order to get access to the Queue, but technically I agree you are not being authenticated by the Queue Manager.  IBM does seem to "allow" this.
Comment: It only allows this if you do not configure it to require authentication which is possible and recommended.
Comment: Did you mean "not recommended?"  My understanding is that this is the "out of the box" setting, so I can see how DevOps people may have not changed this default behavior.  I am obviously an IBM MQ noob and depend on my IBM MQ administrator to know more than I do.  I do read considerable documentation before asking questions here so I really appreciate your input.
Comment: I mean configuring it to require authentication is recommended,  but I can see now I wasn't very clear . In my opinion out of the box is not restrictive enough so I agree it can be difficult for those new to MQ administration.


Views and node_access

Question: I have a D7 installation with about 2k "project" nodes, which have a multi-entry field "team members" used to control view and edit access.
So far, I have my (pretty complex) logic inside node_access, and it works fine. But views (e.g. a "new projects" feed) don't respect node_access. The mymod_node_access hook is called (I see it with dpm()), but the nodes still appear in the view result.
Obviously I could simply hide the elements using a view field template, but that breaks the paging system (e.g. user selects "10 projects per page", but sees only four).
How can I make the Views module respect node_access as a filter?
Comment: hook_node_access only gets invoked for individual nodes. What you could do, that will also repsect the pagination is add a view filter to filter only projects where the current user is a member of (if that's what you want to achieve) You'll probably need to do it with a contextual filter.
Comment: Problem is that it's not just the "team member" field that controls access, there are also rules based on role membership and other factors, so it isn't really possible to use ordinary views filters - and I wouldn't like to duplicate the logic in node_access to avoid a code split or risk a mismatch between the filter and node_access.
Comment: @Skynet Would you be interested in suggestion for a possible alterrnative (a module you may not be aware of) that you could use to replace your entire "access" implementation (your special field, and the node access module)? PS: is this D7 or D8?
Comment: Why not? As long as I can replace node_access AND drupal filters with one solution, I'm fine. Btw, I'm on D7.
Answer: If you are willing to give it a try to "replace node_access AND drupal filters with one solution" (as per one of your comments), then have a look at the Group module (commonly perceived as an alternative for Organic Groups).
Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.
Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site).
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Views and node_access


Send personalized email to a particular role

Question: I want to send a PERSONALIZED email to all users of a particular role on my site starting with for example: Hello [first_name] [surname],
I have tried using the Rules module but was not successful.
Please is there a way to use Rules module to achieve this or is there another way?
Thanks in anticipation.
Answer: Try using the views_send module instead. This powerful module acts like views_bulk_operations in that it lets you create a view to execute an action using Drupal's batch API for processing. For your case (roughly following the directions on the project page):

Create a view of users and add the user email field to the list
Add the field 'Global: Send e-mail' to activate the Views Send functionality
Add any other fields that you want to include in your customized email as fields in the view (ex. User: First Name, User: Last Name)
Finally, add a filter to filter by the particular role(s) you want to filter on.
You probably also want to secure the views permissions so non-authorized users can't use the view to send to your users.

If that's all setup then when you visit your page, you will see a list of all users in that role with the option to send an email to them. When you select your users and are ready to send your email, you will then see on the next page the option to use any of the fields you've selected above as tokens in your email (thus the customizable option):


Convert images to compressed video

Question: I have video steam that i convert to images to make some image analyzing.
After my image analyzing - I want to convert the same images ( after i did the image analyze ) compressed video.
Is it possible do to it ( using hardware/software encoder ) ?
Answer: The easiest way to accomplish to make a video from images is probably ffmpeg.
<code>ffmpeg -i yourimage1 -i yourimage2 -i yourimage3 -vcodec libx264 -an output.mp4
</code>
Add additional "-i" elements for each image.

Convert images to compressed video


Entidade Endereco Compatilhada

Question: Modelando um projeto associei uma entidade Endereco na Raiz de Agregação Cliente. Até aí tudo bem. Contudo, verifiquei posteriormente que outras entidades ou raízes de agregação como Empresa e Fornecedor também precisam de endereço na sua composição. Sendo assim, a dúvida que tenho é como utilizar a mesma entidade Endereço para atender a todas entidades que necessitem dela?
Obs: a modelagem que estou fazendo é baseada nos conceitos de DDD.
Comment: Qual linguagem você esta utilizando? Como está seu código?
Answer: tl;dr
Você modelou a entidade Endereço como entidade filha de Cliente, porém ela é apenas uma entidade relacionada.
Entendendo o que é um endereço
Normalmente, quando estou desenhando um conceito, sinto a necessidade de ser cético sobre ele, ou seja, por em dúvida aquilo que conheço dele. Assim, geralmente acabo descobrindo algo novo que muda o design.
Dito isto, o melhor a se fazer é compreender como  os Correios identificam um endereço. O que reproduzo abaixo para fins históricos:

Nome do destinatário
Nome do logradouro (uma rua ou avenida), número da residência, complemento (geralmente um número de apartamento)
Nome do bairro (opcional)
Nome da cidade e nome do estado
CEP.
Latitude e Longitude

O item 1 nós normalmente atribuímos a outra entidade, como, no seu caso, Cliente, Empresa e Fornecedor. Já o item 6 é imutável porque uma latitude e longitude diferentes representam um endereço/local diferente.
Com relação aos itens que vão de 2 a 5, todos podem ser alterados. Exemplos:

O nome de um logradouro (que foi escrito incorretamente no sistema ou que foi alterado pela prefeitura)
Um bairro que foi criado
Um distrito que se tornou uma nova cidade
O formato do CEP, que foi alterado em 1992.

Em qualquer um dois exemplos acima nós, desenvolvedores e usuários, queremos que, uma vez que um atributo tenha sido alterado, o novo valor seja aplicado para todos que utilizam aquele atributo. Ou seja, se uma rua trocou de nome, o desejável é que o novo nome seja aplicado a todos os clientes e fornecedores que residam lá.
Isso nos mostra que um endereço tem um ciclo de vida e que, se um de seus atributos mudar, ele ainda pode ser o mesmo endereço. Logo, endereço é uma entidade, não um objeto de valor.
Entidades filhas e entidades relacionadas
Entidades filhas são aquelas cujo ciclo de vida está diretamente ligado ao da entidade pai, como, por exemplo, um projeto e uma tarefa (task). Uma terefa existe apenas dentro de um projeto e, quando um projeto é deletado, a tarefa também é.
Entidades relacionadas são aquelas que estão ligadas a outras entidades mas tem um ciclo de vida independente, como, por exemplo, endereços.
Referência
Por fim, um agregado pode conter entidade pai, entidades filhas e objetos de valor. Um agregado não deve conter entidades relacionadas.
Comment: Olá Tobias, na verdade eu tenho no banco de dados apenas uma tabela chamada Endereco e na aplicação a sua modelagem. Acho que me expressei mal quando disse "...como utilizar a mesma entidade Endereço para atender a todas entidades". Eu gostaria de ter uma só tabela  no banco e nela guardar endereços vindo de todos os lugares possíveis (contudo cada endereço pertencente a um dono que pode ser uma empresa, um cliente, um fornecedor, etc)... meu raciocínio é adequado ou tem uma foma mais elegante de normalizar esse cenário?...
Comment: @MarceloAlmeida está tudo certo, o que você comentou agora é o mesmo que eu havia compreendido da sua pergunta inicial. O seu caso de uso é o que eu descrevi no terceiro paragrafo da minha resposta.
O banco de dados está certo, o que precisa mudar é a arquitetura do seu código: coloque a entidade Endereço no mesmo nível hierarquico de Cliente e acesse Endereço através do repository de Cliente (i.e. não utilize seu ORM para acessar Endereço diretamente de Cliente, caso seu ORM seja Active Record)
Comment: @MarceloAlmeida editei a resposta para dexá-la mais clara. Veja se tens alguma dúvida.
Answer: Pode sim, a classe endereço irá usar a convenção de ValueObject em um diretório dentro do seu domínio. Porém seria correto você persistir (banco de dados) em tabelas separadas e relacionadas em seu respectivos domínios ou até mesmo utilizar as tabelas da entidades principais da agregação. O ValueObject é imutável, então por exemplo, ao adicionar um novo endereço você deverá remover o atual e adicionar o novo, para isso é "permitido" criar comportamentos que lhe auxiliam nesse cenário e os mesmos só podem ser acessados da entidade root da agregação que a utiliza.
Material para conhecimento:

https://deviq.com/value-object/
https://docs.microsoft.com/pt-br/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects
https://martinfowler.com/bliki/ValueObject.html

Entidade Endereco Compatilhada


Open set in $\Bbb{R}^2$ Topology

Question: Consider $\Bbb{R}^2$ with the usual topology. Let $X$ be a subset of $\Bbb{R}^2$. If for every $a \in X$ and $v \in \Bbb R^2$ there exists a d>0, such that $a+vt\in X$, for every $0\leq t<d$, then X is open.
I suppose this theorem is wrong as the choice of the radius of the open ball $d$ is dependent from choice of the vector $v$. However, I am looking for a counter-example to disprove that.
Comment: I think it's saying that, once a specific $a$ and $v$ have been chosen, a $d$ can be found.
Comment: @KajHansen You are right, the radius is not $d$. However, I still don't think this would give me an open ball.
Comment: @PrzemysławScherwentke yes is edited.
Answer: For a single point $a$, you may be able to manufacture a sequence $d_n$ depending on $v_n$ such that $d_n$ converges to zero. For that point $a$ there would not be ball around a completely contained within the set because you can always find a smaller $d_n$ than the radius of that ball. The set would probably look sort of like a circle with a shrinking radius.
$$
X = \{(x,y) = (r\cos(\theta),r\sin(\theta)), \theta \in (0,2\pi] : x^2 + y^2 < \theta\}
$$
For the point $a=(0,0)$, take any $v=r_v(\cos(\phi),sin(\phi))$ then $d=\frac{r_v \phi}{2}$ so $a + tv < a + dv=dv=\frac{\phi}{2}(\cos(\phi),\sin(\phi))$ and so is in the set.
For any other point this also follows and is the centre of a ball contained in $X$
Suppose $X$ is open, that there is a ball of radius $p$ around $(0,0)$ contained in $X$, well there is some $\theta<p$ such that the point $\frac{p+\theta}{2}(\cos(\theta),\sin(\theta))$ is not in the set $X$ but is in the ball, so the set $X$ is not open.
Answer: In the present formulation...
Let us fix $a=(0,0)$, $X=\{(x,y):x^2+y^2\leq 1\}$. Let $v$ be any unit vector. Your condition is valid for $d=1$, but $X$ is not open.
Comment: But the condition has to be true for every $a\in X$.
Comment: @quallenjager I don't think rescaling would solve it. For example, if I take $a$ on the boundary of the unit disk $X$ and $v$ a point outside of $X$, then there is no $d$.

Open set in $\Bbb{R}^2$ Topology


Mailer Error on sending mail with Flutter

Question: I'm actually developping a mobile app with Flutter and I wish I could send an email from it. To do so, i tried to use the Mailer plugin with the following code :
import 'package:flutter/material.dart';
import 'package:mailer2/mailer.dart';

main() {

    var options = new GmailSmtpOptions()
      ..username = 'firstname.lastname@example.com'
      ..password = '*******';

    var emailTransport = new SmtpTransport(options);

    // Create our mail/envelope.
    var envelope = new Envelope()
      ..from = 'email@example.com'
      ..recipients.add('*******@*****.fr')
      ..subject = 'Testing the Dart Mailer library'
      ..text = 'This is a cool email message. Whats up? 語'
      ..html = '
Test

Hey!
';

    // Email it.
    emailTransport.send(envelope)
        .then((envelope) => print('Email sent!'))
        .catchError((e) => print('Error occurred: $e'));
}

However, i have the following error:
I/flutter (22531): Error occurred: type '_AsBroadcastStream<dynamic>' is not a subtype of type 'Stream<Envelope>' where
I/flutter (22531):   _AsBroadcastStream is from dart:async
I/flutter (22531):   Stream is from dart:async
I/flutter (22531):   Envelope is from package:mailer/mailer.dart

Can someone help me ? Thanks in advance !
Comment: Please check if mailer plugin is updated after flutter got updated.. could be that the plugin is old and is not compatible with new flutter.
Comment: Looks like it's a known Dart 2 issue. https://github.com/kaisellgren/mailer/issues/42 From the Dart command line it works unless you set `--preview-dart-2`. Flutter sets that flag.
Answer: In this file

mailer-1.1.4/lib/src/smtp/smtp_client.dart

Update lines 49 & 50 by add "cast()" method to be:

    onIdle = _onIdleController.stream.asBroadcastStream().cast();
    onSend = _onSendController.stream.asBroadcastStream().cast();


Show that $\frac{\alpha}{(k+1)^{1-\alpha}}\leq (k+1)^{\alpha}-(k)^{\alpha} \leq \frac{\alpha}{k^{1-\alpha}}$

Question: Let $\alpha \in ]0,1[$. Show for every positive integer $k \geq 1$ we have
$$
\frac{\alpha}{(k+1)^{1-\alpha}}
\leq (k+1)^{\alpha}-(k)^{\alpha}
\leq \frac{\alpha}{k^{1-\alpha}}
$$
I need some hint for this. I was thinking  we consider the function $f(x)=(1+x)^{\alpha}$.
Answer: HINT: consider $f(x)=x^{\alpha}$ on the interval $[a,b]$ for some $0<a<b$. Then for every $x,y\in[a,b]$
$$
f(y)-f(x)=f'(\xi)(y-x)
$$
hold for some $\xi\in[a,b]$. In your case $x=a=k$ and $y=b=k+1$, so it is enough to find max and min of $f'$ on $[k,k+1]$.
Comment: You are welcome
Comment: OMG  I forgot Mean value theorem . Thank you
Answer: Another way: Use Bernoulli inequality.
The right inequality is written as
$$\left(\frac{k+1}{k}\right)^\alpha - 1 \le \frac{\alpha}{k}.$$
The left inequality is written as
$$\frac{\alpha}{k + 1} \le 1 - \left(\frac{k}{k+1}\right)^\alpha.$$
Both inequalities are true by the Bernoulli inequality
$$(1 + x)^r \le 1 + rx, \quad \forall x > -1, \, 0 \le r \le 1.$$
Indeed, for the right inequality, let $x = \frac{1}{k}$ and $r = \alpha$, and for the left inequality, let $x = -\frac{1}{k + 1}$ and $r = \alpha$.


strip dashes or any special characters at the end of the string

Question: I convert any special characters to dashes in my string except for alphanumerics using this:
return preg_replace("![^a-z0-9]+!i", "-", $str);

However, in some case I have this strings:
$str = "Hello there chubby!";

which will result to:
Hello-there-chubby-

The dash on the end of word is what makes me think of a solution on how to remove that.
Answer: return trim(preg_replace("![^a-z0-9]+!i", "-", $str), '-');

will strip leading and trailing dashes.
Answer: You can try
rtrim("Hello-there-chubby-", "-");.
or
preg_replace("#[^a-z0-9]+$#ims", "", "Hello-there-chubby-");
for removing the last special character.


Assign Domain to IP Address which has a path

Question: In my DNS settings, I want to point this website domain - www.websiteA.example to the following IP address which has a path http://xxx.xxx.xxx.xxx/pathA (this is a VPS, if it makes any difference)
Is this possible?
If so can you please provide more information on how I can achieve this?
Comment: If you want to avoid a lot of pain in the future, avoid using IP addresses in URLs. Specially for HTTPS ones, but even for HTTP one.
Answer: That's not possible, DNS only handles mappings between host or domain names and IP addresses; the path only makes sense for web sites, it's managed by the web server and DNS has nothing to do with it.

A possible solution is to put something (f.e. a minimal webserver) at www.websiteA.com that performs a HTTP redirect to http://xxx.xxx.xxx.xxx/pathA.
Comment: Thanks for the response.
Answer: TL;DR
No you can't.
The bigger picture
DNS only maps names to addresses using A records when it comes to IPv4 and AAAA records when you're dealing with IPv6.
I'm assuming that you have a web server that shall serve different documents for two distinct domains. If I'm right, then I suggest you look into the concept of virtual hosts/servers. As an example, here is the documentation for Apache httpd's virtual host configuration. The basic idea is, that you set up multiple A/AAAA entries with the same address, but different names in your DNS pointing to your web server. Web servers can - since the HTTP protocol carries that information - find out with which name a request was made with and decide what documents to serve accordingly.
Comment: Thanks for the response.
Comment: You're very welcome, I hope it helped. Please consider selecting one of the answers as your accepted answer as well if your question has been sufficiently answered. This way it doesn't get listed as open anymore.


Set column order in alembic when adding a new column

Question: I'm struggling to find a clean way (without raw SQL) to set the column order in alembic. For example, I would like to put a new column called 'name' after the 'id' column, something like this:
from alembic import op
import sqlalchemy as sa

...

op.add_column(
    'people',
    sa.Column(
        'name',
        sa.String(),
        nullable=False
    ),
    after='id'
)

But of course, alembic does not have the 'after' parameter, therefore this code fails and I have not found an equivalent to this 'after' parameter in the docs. I'm only able to append the column at the end of the table.
Can anybody suggest how to achieve in alembic/sqlalchemy what I want? Is it possible without raw SQL?
Comment: You cannot specify the position of the new column: https://dba.stackexchange.com/questions/3276/how-can-i-specify-the-position-for-a-new-column-in-postgresql. This is a limitation in Postgres.
Comment: What about MySQL?
Comment: @dbatten No, but according to https://dev.mysql.com/doc/refman/5.6/en/alter-table.html it's possible with raw SQL command (with `[FIRST | AFTER col_name]` )
Comment: What DB are you using?
Comment: PostgreSQL version 9.6
Answer: alembic version 1.4.0 or higher supports this feature.
use the batch operation to achieve it.
from alembic import op
import sqlalchemy as sa

with op.batch_alter_table("people") as batch_op:
  batch_op.add_column(
    Column("name", sa.String(50)),
    insert_after="id"
  )

Reference: https://alembic.sqlalchemy.org/en/latest/ops.html?highlight=insert_after#alembic.operations.BatchOperations.add_column
Answer: Slice them into separate nested lists, ending at the column before the inserted column ( so in this case, create a one nested list that ends at the "id" column.
Let's call that variable id_col
Now, you can either use the "extend" built-in or "append" to add the "name" column right after the id column.
You can also add the nested lists to end up with a final single data structure that has what you're looking for.
The emphasis, here, being, that you do not have to be constrained by exclusively using your SQL table format. You can convert it into a a nested list and then once combined using list methods, reconvert them back into your desired SQL table.


How to match encoded diacritical marks in MYSQL?

Question: In a project that is almost a decade in the past we encoded diacitical marks in a MYSQL database with html entities. All of that seemes bizzare today but be it as it may. The application that uses this database implements a search function and my problem is that the search does not work correctly when the string searched for contains a diacritical mark. Like in: "für"
The simplified MySQL query looks like this:
SELECT kunstwerk. * , kategorie.published, kategorie.bezeichnung
FROM kunstwerk
LEFT JOIN kategorie ON SUBSTRING( kategorie, 1, 7 ) = kategorie_Nr
WHERE published = 'true'
AND published_veto <> 'false'
AND MATCH (titel_DE)
AGAINST (
  '+für '
  IN BOOLEAN MODE
)
ORDER BY kategorie

My problem is that it matches anything that contains "ü" regardless of the surrounding characters in "für".
What is the reason for that?
Comment: Can  you try wrapping the term in in quotes? `'+"für" '`
Comment: @Pekka perfect, that does it. Make this an answer please.
Answer: I'm not 100% sure what happens here, but mySQL is clearly choking on the & and ; control characters. (my suspicion it's ultimately searching only for the uuml part).
Anyway, wrapping the term in quotes will help:
AGAINST (
  '+"für" '
  IN BOOLEAN MODE
)


Void pointers in C used in stacks

Question: I am writing a program that implements a stack in c.  I want each node to take any type of data(ie int char struct etc) if I declare my node struct as
    typedef struct node{
           void *data;
           struct node *next;
   }Node;

Does that allow my void pointer data to point to any type of memory?
Answer: Yes, but there are some caveats involving dereferencing your void pointer to access the data inside.
Basically, say you have a node:
Node *node;

And you have some Point structure:
typedef struct Point {
    int x;
    int y;
} Point;

And you put a point in a node:
Point *p = malloc(sizeof(Point));
p->x = 0;
p->y = 3;
node->data = p;

In order to access the members of the point, you have to use a typecast:
printf("%d\n", ((Point *)node->data)->x);

Or you can assign a pointer of the correct type and copy the void pointer:
Point *p = node->data;
printf("%d\n", p->x);

Because this won't work:
printf("%d\n", node->data->x);

That's because a void pointer contains no type information for the compiler to make sense of what's being pointed to by a void pointer.
And that's pretty much all you need to know about how to use void pointers.
Answer:
Does that allow my void pointer data to point to any type of memory?

Yes.
Answer: Succinctly, yes.  It means you'll store a pointer to the int, etc, so that takes up space.  You also need to ensure that you know how to handle different types if you do not have homogeneous types in the list.
Answer: Yes its possible what you wanna to achieve but you need to take care of dereferencing the the void pointer.,what i am alluding is you have to type caste void pointer to appropriate type while dereferencing.

Void pointers in C used in stacks


Standard error of the mean of a non-normal distribution

Question: It seems like a basic question, but I haven't find an answer yet.
How do you calculate the standard error of the mean when you have a discrete non-normal distribution?
Actually, I have a discrete distribution that I represent as a box plot because it is non-normal and has outliers. Therefore, I display the median, IQR, etc. In this case, what is the equivalent of the standard error of the mean that we employ with normal distributions?
Answer: Per the central limit theorem, the sample mean is asymptotically normally distributed even for non-normal sampled distributions under some quite weak assumptions, which can in practice usually be assumed to hold. And the asymptotics kick in even with quite small $n$. So you can estimate the SEM in the standard way, no need for the underlying distribution to be normal (or even continuous).
For additional peace of mind, consider bootstrapping the mean and calculating the standard deviation of the bootstrapped means.
As an illustration, assume we have a sample containing $0$ fourteen times and $1$ six times. It doesn't get much more non-normal than that. We have $\bar\mu=0.3$ with SEM $0.105$. Bootstrapping the mean 1,000 times yields a standard deviation of the bootstrapped means of $0.103$. The difference is minuscule. Also, here is a histogram of the bootstrapped means:

R code:
<code>> foo <- c(rep(1,6),rep(0,14))
> sd(foo)/sqrt(length(foo))
[1] 0.1051315
>
> set.seed(1)# for reproducibility
> bb <- boot::boot(foo,statistic=function(xx,index)mean(xx[index]),R=1000)
> sd(bb$t[,1])
[1] 0.1034599
>
> hist(bb$t[,1],main="Bootstrapped means",xlab="")
</code>
Comment: Central limit theorem applies only to independent random samples so that it cannot be applied to samples which are not randomly sampled, having the same variances, or independent (i.e. having zero covariances). https://www.linkedin.com/pulse/standard-error-stephen-senn?fbclid=IwAR1BKUsy0QwxmU6ePUCQ6tDpnqu3DkTSKocYEnkK8tS9-h_K_ZAK-ChZYC4


Using ajax with selectPDF

Question: I have the following ajax call:
$.ajax({
    url: 'WebService.asmx/ConvertPDF',
    data: "{'section':'Ajax html'}",
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'JSON',
    async: false,
    success: function (response) {
        // proceed
    },
    error: function () {
        // fail code
    }
});

and the webservice
[WebMethod(EnableSession = true)]
public void ConvertPDF(string section) {
    HtmlToPdf convertor = new HtmlToPdf();
    string _html = "
this is a test
</html";

    string size = "A4", orientation = "Portrait";
    PdfPageSize pdfSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), size, true);
    PdfPageOrientation pdfOrientation = (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation), orientation, true);
    convertor.Options.PdfPageSize = pdfSize;
    convertor.Options.PdfPageOrientation = pdfOrientation;
    convertor.Options.WebPageWidth = 1024;
    convertor.Options.MinPageLoadTime = 2;
    convertor.Options.WebPageHeight = 0;

    PdfDocument doc = convertor.ConvertHtmlString(_html, "");
    doc.Save(HttpContext.Current.Response, false, "Sample.pdf");
    doc.Close();
}

Running the service method natively it works fine but when I do it through the JS button to call the ajax, I get 'Thread was being aborted'.
Any ideas on how to get round it? Basically the button grabs html from sections on the page, and will (eventually) pass it to the method to output to PDF, essentially replacing the _html variable with what is in the section parameter.
Thanks
Comment: already got that
Comment: ok let me try this code and try to solve it
Answer: // Post method to convert Html to pdf using selectpdf
[HttpPost]
    public ActionResult ConvertDocument(MyDocumentDTO model)
    {

        HtmlToPdf converter = new HtmlToPdf();

        PdfDocument doc = converter.ConvertHtmlString(model.Context);
        // save pdf document
        byte[] pdf = doc.Save();

        string handle= Guid.NewGuid().ToString();
        TempData[handle] = pdf;
        return Json(handle, JsonRequestBehavior.AllowGet);

    }

Ajax call
        $.ajax({
            url: '/document/ConvertDocument',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: ko.toJSON(document),
            success: function (data) {
                window.location = 'download?fileGuid=' + data;
            },

// Get request to download file
    [HttpGet]
    public ActionResult Download(string fileGuid)
    {
        byte[] pdf = TempData[fileGuid] as byte[];
        FileResult fileResult = new FileContentResult(pdf, "application/pdf");
        fileResult.FileDownloadName = "Document.pdf";
        return fileResult;
    }

Using ajax with selectPDF


uniformity in quantifier elimination

Question: Let $T_0$ be a consistent theory. Let ${\cal T}$ be the set of all complete theories that contain $T_0$.
Is it true that if each $T\in{\cal T}$ eliminates quantifiers so does $T_0$?
Note. The point is about uniformity. Assume for every formula $\varphi$ there is a quantifier-free formula $\psi_T$ such that $T\vdash \varphi\leftrightarrow\psi_T$. Is it possible to conclude that $\psi_T$ does not depend on $T$?
Edit. The case when $T_0$ has no finite models, is particularly interesting.
Answer: No, it is not. Every completion of the empty theory in the empty language has quantifier elimination, but the empty theory itself doesn't.
Why? Well, note that the only data missing from the empty theory is the size of the universe: a completion of the empty theory either is generated by some sentence of the form "there are exactly $n$ many elements," or is generated by the set of sentences "there are at least $n$ distinct elements" for all $n$. Either way, in any model of $T$ the type of a tuple is determined completely by the atomic theory of the tuple (= which coordinates are equal to which others, in this case) so every extension of $T$ has quantifier elimination, but $T$ itself doesn't prove or disprove the quantifier-free sentence $\eta=$"$\exists x\exists y(x\not=y)$", and sinec the only quantifier-free sentences in the empty language are (equivalent to one of) $\perp$ and $\top$, this means that the empty theory doesn't eliminate quantifiers from $\eta$.

Note, however, that by Konig's lemma for any such $T_0$ and any formula $\psi(\overline{x})$, there is a finite set of formulas $\{\theta_1, ..., \theta_n\}$ such that $T_0$ proves $$\bigvee_{1\le i\le n}\forall \overline{x}(\psi(\overline{x})\iff\theta_i(\overline{x})).$$ (This is a good exercise. HINT: consider the usual tree of consistent extensions of $T_0$, and look at the subtree of consistent extensions which do not yet eliminate quantifiers from $\psi$. If that subtree is finite we're done; otherwise, think about what a path through that subtree entails . . .)

EDIT: This can easily be tweaked to avoid finite models. Consider the language consisting of a single unary relation symbol $U$, and the theory $T_0$ consisting only of the axioms asserting that the universe is infinite. A completion of $T_0$ consists of data telling us the size of $U$ and of $\neg U$; it's easy to check that each of these satisfies quantifier elimination, but $T_0$ does not eliminate quantifiers from e.g. the sentence "$\forall x(U(x))$."
This might seem cheap, since a model of $T_0$ basically consists of two models of the theory above placed "side by side," at least one of which is infinite. However, we can produce plenty more examples.
The failure of quantifier elimination in $T_0$ is guaranteed when $T_0$ is complete for quantifier-free sentences but is not complete (since then $T_0$ can't eliminate quantifiers for any sentence it doesn't decide), and this trivially holds if $T_0$ is in a relational language (since then it has no nontrivial quantifier-free sentences); more vaguely, the fact that quantifier elimination holds in all completions of $T_0$ is guaranteed by completions of $T_0$ being generated (over $T_0$) by a "simple" decision, and models of the theory being "combinatorially simple." With this in mind, we can construct many more examples:

The theory of dense linear orders possibly with endpoints.
The theory of $\overline{\mathbb{Q}}$-vector spaces of unspecified dimension. (Here in order to make linear independence first-order definable, the vector space is construed as a two-sorted structure, with scalars and vectors; if we replaced $\overline{\mathbb{Q}}$ with a finite field, it wouldn't matter how we presented it.)

And so forth.
Another approach is to consider the disjunction of two complete theories which eliminate quantifiers. Given theories $T_1$ and $T_2$ in the same language, let $$T_{1\vee 2}=\{\varphi\vee\psi: \varphi\in T_1, \psi\in T_2\}.$$ Any model of $T_{1\vee 2}$ is either a model of $T_1$ or a model of $T_2$ (suppose not; let $\varphi$ and $\psi$ witness this, and think about $\varphi\vee\psi$ . . .), hence $T_{1\vee 2}$ has exactly two completions, each of which eliminate quantifiers, but in general $T_{1\vee 2}$ itself won't.
For example, work in the language with a single binary relation symbol $R$, let $T_1$ be the theory of the random graph, and $T_2$ be the theory of the dense linear order without endpoints. Then $T_{1\vee 2}$ doesn't decide, and hence (since its only quantifier-free sentences up to semantic equivalence are $\top$ and $\perp$) doesn't eliminate quantifiers from, the sentence "$\exists x, y, z(xRy\wedge yRz\wedge \neg xRz)$".
Comment: You *would* appeal to Konig's Lemma instead of the compactness theorem!
Comment: +1 For the example. I forgot about the existence of finite models :( and I have edited my question.
Comment: @Escherica Avoiding finite models doesn't help things, see my edit.
Comment: @AlexKruckman Haha, wow, why *did* I do that?
Comment: @NoahSchweber You give some great examples, but one isn't right. Transcendence degree is not first order (ACF_p is already complete with QE).
Comment: @AlexKruckman Derp, of course - I got ACFs and vector spaces mixed up. Fixed!
Comment: The same comment applies to vector spaces! When the field K is forced, you can only express linear independence if K is finite.
Comment: @AlexKruckman I might be having a stupid moment, but if you include the scalars explicitly as a separate sort (as I indicated we must do) then it seems you **can** express linear dependence - e.g. "$\exists a_1, a_2(\neg(a_1=a_2=0)\wedge a_1\cdot v_1+a_2\cdot v_2=0)$." Am I missing something?
Comment: That's true, but you said $\mathbb{Q}$-vector spaces, so I assumed you meant the one sorted language with a fixed field. If you want QE in the two-sorted language, you'd better make the field algebraically closed, and then you still don't have QE in the natural vector space language - for example, you need to add relations for linear independence.
Comment: @AlexKruckman I did explicitly state that I was doing the two-sorted version. As to algebraic closure, that was a typo - I meant to write "$\overline{\mathbb{Q}}$" instead of "$\mathbb{Q}$," and just botched it. Fixed! (Although why I didn't just use "$\mathbb{C}$" escapes me . . .)
Comment: Oops, sorry, I missed that! So yeah, that example works, if you state it in an expanded language where the completions have QE.
Answer: This is an addendum to @NoahSchweber'a answer.
The answer is positive in some particular cases (e.g. for $T_0=$ACF and similar cases).
Suppose all completions of $T_0$ are of the form $T_0\cup S$ where $S$ is a set of quantifier-free sentences. Then, if all completion of $T_0$ have quantifier elimination, so does $T_0$.
By compactness (or Köning's lemma), there are finitely many quantifier-free sentences $\sigma_i$ and quantifier-free formulas $\psi_i(x)$ such that
$\displaystyle\qquad\sigma_i\vdash\varphi(x)\leftrightarrow\psi_i(x)$,
$\qquad\displaystyle T_0\vdash\bigvee^n_{i=1}\sigma_i$, $\qquad\sigma_i\vdash\neg\sigma_j$ for $i\neq j$.
then
$\displaystyle\quad T_0\vdash\varphi(x)\leftrightarrow\bigvee^n_{i=1}\sigma_i\wedge\psi_i(x)$.

uniformity in quantifier elimination


Commerce Order Total Tax line via EntityMetadataWrapper

Question: I need the final tax amount for an order found on the commerce order total. when using dpm and entity metadata wrapper i can't seem to break it out in order to grab the value.
<code>$order = entity_metadata_wrapper('commerce_order', 3);
dpm($order->commerce_order_total->getPropertyInfo());
</code>
Answer: the most thorough insight on getting access to the tax line and individual subtotals. found via: https://gist.github.com/BBGuy/3e1f624eaee2088d8eee
<code>// order total object
$order_total_obj = $order_wrapper->commerce_order_total->value();
// Order total (cents).
$order_total = $order_total_obj['amount'];
// order currency code
$currency_code = $order_wrapper->commerce_order_total->currency_code->value();
// subtotal without vat
$total_ex_vat = commerce_price_component_total($order_total , 'base_price');
// total tax (in this case vat 20%)
$total_vat = commerce_price_component_total($order_total , 'tax|vat_20');
// subtotal with vat
$sub_total = $total_ex_vat['amount'] + $total_vat['amount'];
// formatted price string with currency sign
$sub_total = commerce_currency_format($sub_total, $currency_code);
</code>
Answer: To get the final tax amount for an order from the commerce_order_total field, you can use the following code:
<code>$order = entity_metadata_wrapper('commerce_order', 3);
$order_total = $order->commerce_order_total->value();
$tax_amount = $order_total['tax_amount'];
</code>
The commerce_order_total field is an entity_reference_revisions field, which means that it stores a reference to a revision of a tax total entity. The tax total entity stores the total tax amount in the tax_amount field.
You can also use the commerce_price Twig filter to format the tax amount as a price:
<code>{# Format the tax amount as a price #}
{{ tax_amount|commerce_price }}
</code>


Pandas with flask getting Nonetype for search array

Question: I'm getting this error:

AttributeError: 'NoneType' object has no attribute 'replace'

Which I believe is because the search array is empty when the page loads, but adding a 'is not None' check before hand doesn't fix it.
search = []
if search is not None:
    search = request.values.get('searchinput').replace(" ","").split(',')
    return render_template('drugsafety.html', tables=[filtered.to_html(classes='data')], titles=['na', 'Drug List'])

Why wont this escape the NoneType error?
edit
Updated from answer below
searchterms = []

    search = request.values.get('searchinput')
    if search is not None:
        searchterms = search.replace(" ","").split(',')
    else:
        searchterms == ""

    filtered = df.query ('BP.str.contains(@searchterms, na=False)', engine='python')
    return render_template('drugsafety.html', tables=[filtered.to_html(classes='data')], titles=['na', 'Drug List'])

This now gives

TypeError: unhashable type: 'list'
Answer: You set search to the empty list. That makes it not None. So it goes into the code below the if There you write
search = request.values.get('searchinput').replace(" ","").split(',')

This returns the searchinput value is there is one. If there is no such value it returns None. So your values have no searchinput.
You do not specify how the request is sent, using POST or GET method. If it is post, your form should have a text input with id searchinput, if it is get, the same applies or you can have a url argument named searchinput
Solution:
First get the value of the search input, second if it is not None, replace comma's and split.
Btw, for a string a check like this is preferred:
if search: # True if search is not none and not the empty string

Comment: Thankyou for the answer what you have put makes sense I'm just struggling to write it. I have updated my question. In my messing about with the code it seemed to work then on restart of the page it gave 'unhashable type: List' error.
Comment: That is a completely different issue. Please create a new question for that.