If $m<n$, show that there is a $1$-$1$ mapping $F:S_m\rightarrow S_n$ such that $F(fg)=F(f)F(g)$ for all $f,g\in S_m$

Question: question: If $m<n$, show that there is a $1$-$1$ mapping $F:S_m\rightarrow S_n$ such that $F(fg)=F(f)F(g)$ for all $f,g\in S_m$. Where $S_n$ stands for symmetric group of degree $n$
my approach:
First I was thinking how to construct the $F$. Because if I did this properly then the only work is left to show this is $1$-$1$ map.
So there are more elements in $S_n$ compare to $S_m$. I need to define $F$ in such a way that after covering all elements of $S_m$ I have to define it for other elements of $S_n$. Now here is my question arrive How to choose those elements and how to define $F$ when $S_m$ is covered?
Comment: This is a duplicate of [this](https://math.stackexchange.com/q/3699478/10513) question. Can you see why?
Answer: Define $F:S_m\rightarrow S_n$ by $F(\sigma)(j)=\sigma(j)$ if $1\leq j\leq m$, and $F(\sigma)(j)=j$ if $m<j\leq n$.
The question just wants you to show that $S_n$ contains an isomorphic copy of $S_m$ when $n>m$.
Comment: He mean that there is a subgroup of $S_n$ isomorphic to $S_m$ @NajmunNahar
Comment: Can you explain what you mean by **$S_n$ contains an isomorphic copy of  $S_m$**? @ilovebulbasaur
Answer: You have the wrong approach to this question. You cannot guarantee with your construction that $F$ is a homomorphism. Here is the correct answer,
If $\sigma:\{1,...,m \} \rightarrow \{1,...,m \}$ is a bijection we define $F(\sigma):\{1,...,n\} \rightarrow \{1,...,n\}$ as follows
$$F(\sigma)(x) = x \ \text{ if } \ x > m$$ and
$$F(\sigma)(x) = \sigma(x) \ \text{ if } \ x \leq m$$
Intuitively $F \sigma$ just fixes the elements which are not in $\sigma$'s domain.
Try and prove that $F$ is a homomorphism.
Comment: Isn't $F(\sigma):\{1,...,n\} \rightarrow \{1,...,n\}$ should be $F(\sigma):\{1,...,m\} \rightarrow \{1,...,n\}?$ @Noel Lundstrom
Comment: No, since $F(\sigma)$ has to be a permutation of $\{1,...,n \}$ by definition.
Answer: More generally, take any set $Y$ and $X\subseteq Y$. The map $\phi \colon S_X\to S_Y$, defined by $\phi(\sigma)_{\mid X}:=\sigma$ and $\phi(\sigma)_{\mid Y\setminus X}:=Id_{Y\setminus X}$, is:

"well defined": in fact, for every $\sigma\in S_X$, actually $\phi(\sigma)\in S_Y$;
injective: in fact, $\phi(\sigma)=\phi(\tau)\Longrightarrow$ $\phi(\sigma)_{\mid X}=\phi(\tau)_{\mid X}\Longrightarrow$ $\sigma =\tau$;
operation-preserving: in fact, for $x\in X$, $\phi(\sigma\tau)(x)=$ $(\sigma\tau)(x)=\sigma(\tau(x))=$ $\sigma(\phi(\tau)(x))\stackrel{\phi(\tau)(x)\in X}{=}$ $\phi(\sigma)(\phi(\tau)(x))=$ $(\phi(\sigma)\phi(\tau))(x)$; and, for $x\in Y\setminus X$, $\phi(\sigma\tau)(x)=$ $Id_{Y\setminus X}(x)\color{red}{=}$ $Id_{Y\setminus X}(Id_{Y\setminus X}(x))=$ $Id_{Y\setminus X}(\phi(\tau)(x))\stackrel{\phi(\tau)(x)\in Y\setminus X}{=}$ $\phi(\sigma)(\phi(\tau)(x))=$ $(\phi(\sigma)\phi(\tau))(x)$; therefore, $\phi(\sigma\tau)=\phi(\sigma)\phi(\tau)$.

Note that the equal sign in red holds only for the extension by the identity map of $Y\setminus X$; any other bijection on this set would fail the job.
So, $S_X\stackrel{\phi}{\hookrightarrow}S_Y$, and yours is just the particular case $Y=\{1,\dots,n\}$ and $X=\{1,\dots,m\}$.


Expansion of square root of a sum

Question: I know that $(a +  b)^2$ can be expanded as $(a + b) * (a + b) = a^2 + 2ab + b^2$.
Is there an equivalent expansion method for the square root of a sum, that is, $(a +  b)^{1/2}$?
If there's no method, how could one derive these equalities? $$(x + dx)^{1/2} = x^{1/2}(1 + \frac{dx}{x})^{1/2} = \sqrt{x} + \frac{1}{2}\frac{dx}{\sqrt{x}} ....$$
Attached is a screenshot for more information.
Comment: Where did you see such an expansion? Do you know Taylor's series?
Comment: See https://en.wikipedia.org/wiki/Binomial_series for a formula to expand $(1+t)^{\alpha}$ for arbitrary $\alpha \in \Bbb{C}$.
Comment: It's from a book called "Calculus Made Easy" by Silvanus Thompson. I think I heard of Taylor's series but I'm clueless about it. Is that a hint of the answer?
Answer: The Taylor series of $\sqrt{1+x}$ about $x = 0$ converges for $|x| ≤ 1$, and is given by
$$
{\displaystyle {\sqrt {1+x}}=\sum _{n=0}^{\infty }{\frac {(-1)^{n}(2n)!}{(1-2n)(n!)^{2}(4^{n})}}x^{n}=1+{\frac {1}{2}}x-{\frac {1}{8}}x^{2}+\cdots ,}
$$
This is where the formal identity $(1+\frac{dx}{x})^{1/2}$ from.

The first formal identity is nothing but
$$
(a+b)^{1/2}=[a(1+\frac{b}{a})]^{1/2}=a^{1/2}[1+\frac{b}{a}]^{1/2}
$$
assuming all the quantities are positive.
Comment: @CSquared: the definition of "binomial expansion" is from the Taylor series.
Comment: isn't there a binomial expansion formula for this as well?

Expansion of square root of a sum


How to get ansible playbook terminal output to show ansible_host jinja var from inventory file instead of literal jinja syntax

Question: Will do my best to explain my situation. Trying to figure out how to get the terminal output of a jinja expression for a var I have set when running the playbook at the command line. Specifically, getting the return line for changed:... to show the actual value instead of the literal jinja syntax that I have for ansible_host='{{ inventory_hostname }}.{{ host_domain }}':
Inventory file fragment (ce_campus_rtr_inventory_singular):
[all:vars]
ansible_connection=network_cli
host_domain=wfm.pvt
ansible_host='{{ inventory_hostname }}.{{ host_domain }}'

[CEASF]
CEASF-RTR

I am using Cisco ios config module and the ansible-playbook output snippet comes out like this:
changed: [CEASF-RTR -> {{ inventory_hostname }}.{{ host_domain }}] => (item=cowfm-tower-core) => {
But I need it to actually output the correct hostname and domain name, such as CEASF-RTR.wfm.pvt for example, because it makes debugging harder when it does not.
When running the playbook in verbose mode, I can see the correct var value outputted:
<CEASF-RTR.wfm.pvt> EXEC /bin/sh -c....
Same when I debug at the command line:
user$ ansible -i ce_campus_rtr_inventory_singular all -m debug -a "var=hostvars[inventory_hostname].ansible_host"

CEASF-RTR | SUCCESS => {
    "hostvars[inventory_hostname].ansible_host": "CEASF-RTR.wfm.pvt"
}

Do I have to define ansible_host per each host in my inventory file? Or is there some arg I need to pass when running ansible-playbook command to process the jinja expression in the inventory file so that the output is this:
changed: [CEASF-RTR -> CEASF-RTR.wfm.pvt] => (item=cowfm-tower-core) => {
instead of this..
changed: [CEASF-RTR -> {{ inventory_hostname }}.{{ host_domain }}] => (item=cowfm-tower-core) => {
Can I modify ansible return data going to stdout during execution perhaps? Looks like I would have to do something with a custom callback plugin.
Answer: I discovered that the default terminal output is set by the stdout callback plugin, specifically in my case, default.py.
Turns out, you can develop your own to tailor the output for what you want to see: Develop custom callback plugin


Bijection between sets of functions (proper subset)

Question: How can I construct a bijection between two sets of functions $\mathcal{F}(Im;\space Y) \rightarrow \mathcal{F}(X;\space Y)$, with $X$ and $Y$ finite such that $X \subsetneq Im$?
Notation: $Im = \left\{ {p \in \mathbb{N}};\space p \leqslant m \right\}  $ and
$\mathcal{F}(X;\space Y) = $ set of all functions $f: X \rightarrow Y$
Comment: As you stated it (or, at least, as I understood it), you cannot because there exists no bijection between the set of functions $Im\to Y$ to the set of functions $X\to Y$ unless $X=Im$.
Comment: Does it follow directly from the set of functions F(X;Y) being also finite?
Answer: If I understand the question correctly then $\mathrm{Im}$ is an arbitrary subset of $X$. Because $\mathrm{Im}$, $X$ and $Y$ are then all finite we have
$$
 |F(\mathrm{Im},Y)| = |Y|^{|\mathrm{Im}|}
 \quad\text{and}\quad
 |F(X,Y)| = |Y|^{|X|}.
$$
If $X = \mathrm{Im}$ then already $F(\mathrm{Im},Y) = F(X,Y)$.
IF $X \neq \mathrm{Im}$ then $\mathrm{Im} \subsetneq X$ and thus $|\mathrm{Im}| < |X|$ because $X$ is finite. For $|Y|^{|\mathrm{Im}|} = |Y|^{|X|}$ we then need that $|Y| = 1$ or $|Y| = 0$.
If $|Y| = 1$ then $|F(\mathrm{Im},Y)| = |F(X,Y)| = 1$, as both sets contain only the constant function, so the only map $F(\mathrm{Im},Y) \to F(X,Y)$ is a bijection.
If $|Y| = 0$ then $Y = \emptyset$. Because $\mathrm{Im} \subsetneq X$ we have $X \neq \emptyset$ and therefore $F(X,Y) = \emptyset$. For a bijection $F(\mathrm{Im},Y) \to F(X,Y)$ to exists we need $F(\mathrm{Im},Y) = \emptyset$, which is now equivalent to $\mathrm{Im} \neq \emptyset$. In this case $F(\mathrm{Im},Y) = \emptyset = F(X,Y)$.
Comment: Im is the set of the natural numbers that are less or equal to m. So it has cardinality equal to m.
Comment: I was proving that if the cardinality of X equals m and the cardinality of Y equals n, then F(X;Y) = n^m. I managed to prove it by induction and was trying to prove it in another way; so I put X = Im. Without assuming the cardinality of Im (supposing an arbitrary subset of X), if there is a bijection between F(Im;Y) and F(X;Y), then those sets have the same cardinality. This proves it. Thank you.
Answer: If $Y\ne\emptyset$ and $Im \subsetneqq X$, you can't, by a simple cardinality argument:
$$
\lvert F(Im; Y)\rvert = \lvert Y\rvert ^{\lvert Im\rvert}\tag{1}
$$
and similarly
$$
\lvert F(X; Y)\rvert = \lvert Y\rvert ^{\lvert X\rvert}.\tag{2}
$$
If $X$ is finite, then $Im \subsetneqq X$ implies $\lvert Im\rvert < \lvert X\rvert$, so if $Y\ne\emptyset$ then (1) is strictly less than (2).
You can construct an injection but not a bijection.


Rename specific columns with numbers with str+number

Question: I originally have r number of csv files.
I created one dataframe with 9 columns and r of them have numbers as headers.
I would like to target only them and change their name into ['Apple']+range(len(files)).
Example:
I have 3 csv files.
The current 3 targeted columns in my dataframe are:
            0       1       2
0       444.0   286.0   657.0
1      2103.0  2317.0  2577.0
2       157.0   200.0   161.0
3      4000.0  3363.0  4986.0
4      1042.0   541.0   872.0
5      1607.0  1294.0  3305.0

I would like:
       Apple1  Apple2    Apple3
0       444.0   286.0   657.0
1      2103.0  2317.0  2577.0
2       157.0   200.0   161.0
3      4000.0  3363.0  4986.0
4      1042.0   541.0   872.0
5      1607.0  1294.0  3305.0

Thank you
Answer: IIUC, you can initialise a itertools.count object and reset the columns in a list comprehension.
from itertools import count

cnt = count(1)
df.columns = ['Apple{}'.format(next(cnt)) if
       str(x).isdigit() else x for x in df.columns]

This will also work very well if the digits are not contiguous, but you want them to be renamed with a contiguous suffix:
print(df)
       1   Col1       5    Col2     500
0  1240.0  552.0  1238.0    52.0  1370.0
1   633.0  435.0   177.0  2201.0   185.0
2  1518.0  936.0   385.0   288.0   427.0
3   212.0  660.0   320.0   438.0  1403.0
4    15.0  556.0   501.0  1259.0  1298.0
5   177.0  718.0  1420.0   833.0   984.0

cnt = count(1)
df.columns = ['Apple{}'.format(next(cnt)) if
         str(x).isdigit() else x for x in df.columns]

print(df)
   Apple1   Col1  Apple2    Col2  Apple3
0  1240.0  552.0  1238.0    52.0  1370.0
1   633.0  435.0   177.0  2201.0   185.0
2  1518.0  936.0   385.0   288.0   427.0
3   212.0  660.0   320.0   438.0  1403.0
4    15.0  556.0   501.0  1259.0  1298.0
5   177.0  718.0  1420.0   833.0   984.0

Answer: You can use rename_axis:
df.rename_axis(lambda x: 'Apple{}'.format(int(x)+1) if str(x).isdigit() else x, axis="columns")
Out[9]:
   Apple1  Apple2  Apple3
0   444.0   286.0   657.0
1  2103.0  2317.0  2577.0
2   157.0   200.0   161.0
3  4000.0  3363.0  4986.0
4  1042.0   541.0   872.0
5  1607.0  1294.0  3305.0


Why does modifier order matter in SwiftUI?

Question: When applying modifiers to a view in SwiftUI, it appears that the order matters.
For example, this code:
HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}

..will produce this:

Change the order of the modifiers and things change. This code effectively 'breaks' the modifiers, as padding and corner radius are no longer applied:
HStack {
  Text("Hello world")
    .background(Color(UIColor.darkGray))
    .padding()
    .cornerRadius(20.0)
}

Why is this? I'm sure there's a logical explanation but I couldn't find any documentation or rationale for it.
Answer: A modifier is function that returns some View by wrapping the content View it modifies. For example .padding returns some View that implements a padding functionality and its content is the View it modifies, plus the padding:
So, conceptually:
HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}

is roughly equivalent to (names and params are made up):
HStack(content: {
   CornerRadiusView(20.0, content: {
      BackgroundView(Color(UIColor.darkGray), content: {
         PaddingView(content: {
            Text("Hello world")
         })
      })
   })
})

Hopefully, it's clear from the example how the order of the modifiers changes the view hierarchy.
Answer: New Dev's answer is correct. Here is also another good explanation what happens behind the scenes. It's just another point of view of the same concept:

Whenever we apply a modifier to a SwiftUI view, we actually create a
  new view with that change applied – we don't just modify the existing
  view in place. If you think about it, this behavior makes sense – our
  views only hold the exact properties we give them, so if we set the
  background color or font size there is no place to store that data.


Alto Saxophone: spit on sides of mouthpiece?

Question: I have been playing the alto sax for a few years now, and this problem has come up a lot recently.
Every time I play a long piece, spit starts foaming on the sides of my mouthpiece, right next to the reed. I have tried to adjust my mouth position, but no luck. Is there any way I can prevent this from happening?
If it helps, I use a vandoren size 3 reed.
Comment: Does your spit foam appear sooner if you play louder? Just trying to help diagnose your problem.
Comment: You say that this problem is recent. Were you doing something different before you started experiencing this? What has changed?
Comment: @Dekkadeci Yes.
Comment: @DavidBowling I don't really know. I mean, I switched to vandoren from rico royal a year back, but I don't think that makes a difference.
Answer: You need to have your teacher (you DO have one, right?) watch your playing.  It's pretty much guaranteed that your embouchure is out of whack, allowing air to escape (and saliva with it).
I'll note in passing that reeds are notoriously inconsistent, so the brand is irrelevant here.  The strength could be a problem: if you're using a stiffer reed than you can physically handle, your mouth/lip muscles will tire very quickly.  But I repeat: have your playing observed by a trained teacher or professional player.
Comment: What's wrong with that spit on the sides? I personally have a very large tip opening mouthpiece, and I've never seen it as a problem. The air escaping is what creates a "darker" sound.


Possible to provide full Domain Admin rights, but disallow creation of new Admin accounts?

Question: I would like to provide full administrative access to servers within the domain to another admin, with a single exception: the administrator should be unable to create new administrator accounts.
I have looked at the options available through control delegation, but am not quite sure how to do what I need, as control delegation appears to be OU-specific.
Answer: Add the user account for this user to the local Administrators group on the servers. You can do this with Group Policy Preferences in a domain linked GPO.


Solve equation for variable that's both in and out of exponent.

Question: I'm in the process of working on a spreadsheet for a track coach to calculate ASR. link
I managed to get to the point where, given time, I can solve for distance.
However, I'd like to be able to calculate the reverse as well, without having to find the nearest value on the spreadsheet and then referencing the time.
Here is the (manipulated) formula I came up with for time to distance.
$$d=t(r+a*e^(-0.013*t))$$
Can someone help me solve for t?
I know there's an $ln$ involved somewhere, but I don't know how to deal with a variable that's both inside and outside the exponent.
Wolfram Alpha suggests under 'roots' something that looks like t=, but I don't know if that's what I'm looking for.
(not sure on the linear algebra tag, but I guessed 'algebra' was what I'm looking for when it comes to 'solve this equation for this variable)
Comment: You cannot find an algebraic solution using 'normal' algebra. Since you are using a spreadsheet you could use goalseek to find t.
Comment: Thanks for the heads up on goalseek, I'll have to read up on that.
Answer: There is no closed-form solution to this equation.  Numerical solutions (for particular values of the constants) can be found, e.g. using Newton's method, and there can be series solutions. Thus if the $0.013$ is replaced by $s$, there is a series solution in powers of $s$:
$$ t = \frac{d}{a +r}+\frac{d^{2} a}{\left(a +r \right)^{3}} s + \frac{a d^{3} \left(3 a -r \right)}{2 \left(a +r \right)^{5}} s^{2}+ \frac{d^{4} a \left(16 a^{2}-13 a r +r^{2}\right)}{6 \left(a +r \right)^{7}} s^{3}+ \frac{a d^{5} \left(125 a^{3}-171 a^{2} r +39 a r^{2}-r^{3}\right)}{24 \left(a +r \right)^{9}} s^{4}+ \frac{d^{6} a \left(1296 a^{4}-2551 a^{3} r +1091 a^{2} r^{2}-101 a r^{3}+r^{4}\right)}{120\left(a +r \right)^{11}} s^{5}+\ldots
$$
which should converge to a solution for sufficiently small $s$.
Comment: That... looks really ugly... but thank you for the answer.
Answer: From a formal point of view, there is an analytical solution. Using the same notations as the ones used by @Robert Israel , we can write
$$e^{-st}=\frac{d-r t}{a t}$$ and the solution would be given in terms of the generalized Lambert function (have a look at equation $(4)$).
This being said, from a practical point of view, it is not very useful.
Under the same assumptions, what you could do for, at least, the generation of a "reasonable" estimate is to perform one iteration of Newton-like methods (Halley, Householder, ...). Depending on the order $n$ of the method, you would have things like
$$t_{(2)}=\frac{d}{a+r}$$
$$t_{(3)}=\frac{d (a+r)}{a^2-a d s+2 a r+r^2}$$
$$t_{(4)}=\frac{2 \left(a^2 d-a d^2 s+2 a d r+d r^2\right)}{2 a^3-4 a^2 d s+6 a^2 r+a d^2
   s^2-4 a d r s+6 a r^2+2 r^3}$$
Let me try with $s=0.013$, $a=\pi$, $r=e$ and $d=20$. The "exact" solution is $t=4.46864$. The above values would be
$$t_{(2)}=3.41304\qquad t_{(3)}=4.47832\qquad t_{(4)}=4.50790$$
Using $t_0=t_{(2)}$, Newton iterates would be
$$\left(
\begin{array}{cc}
n & t_n \\
 0 & 3.41304 \\
 1 & 4.41371 \\
 2 & 4.46850 \\
 3 & 4.46864
\end{array}
\right)$$


How/Where to set limits to avoid error container running beyond physical memory limits

Question: I know this type of question has been addressed in a few posts, but I cannot find an answer the provides the specific "how" or "where"
I am using CDH5.2, running an oozie workflow that executes a shell command. Each time I run it, nodemanager kills the job with the error:
Container [pid=6757,containerID=container_1424206993158_0001_01_000002] is running beyond physical memory limits. Current usage: 1.0 GB of 1 GB physical memory used; 2.3 GB of 2.1 GB virtual memory used. Killing container
Here are the relevant properties I have in my config files. I have clearly missed something though, so I am seeking direction on where specifically this setting must reside.
yarn-site.xml:
  <property>
    <name>yarn.scheduler.minimum-allocation-mb</name>
    <value>2048</value>
  </property>

  <property>
    <name>yarn.scheduler.maximum-allocation-mb</name>
    <value>8196</value>
  </property>

  <property>
    <name>yarn.nodemanager.resource.memory-mb</name>
    <value>8196</value>
  </property>

mapred-site.xml:
 <property>
    <name>mapreduce.map.memory.mb</name>
    <value>4096</value>
  </property>
  <property>
    <name>mapreduce.reduce.memory.mb</name>
    <value>8196</value>
  </property>
 <property>
    <name>mapreduce.map.java.opts</name>
    <value>-Xmx3072m</value>
  </property>
  <property>
    <name>mapreduce.reduce.java.opts</name>
    <value>-Xmx6144m</value>
  </property>

Comment: In CM these settings are under YARN > Configuration > [Gateway | ResourceManager | NodeManager] > Resource Management. Remember to restart the service and deploy client configurations (use the Actions button on the Configuration screen) after saving changes.
Comment: Are you using Cloudera Manager?
Comment: no cloudera manager, just editing configs under /etc manually. Though if you know where it would be in CM I'll checkpoint the VM and try it there.
Comment: Thanks, that did it. I'll incur the extra overhead from CM if it means I can set  the necessary configuration. If you post this as the answer, I'll accept & close it out.
Comment: Which OS are you using ?  have you tried setting yarn.nodemanager.vmem-check-enabled to false ?
Answer: In Cloudera Manager 5 you can modify these YARN resource settings in:
YARN > Configuration > Gateway > Resource Management
YARN > Configuration > ResourceManager > Resource Management
YARN > Configuration > NodeManager > Resource Management

Remember to restart the service and deploy client configurations (use the Actions button on the Configuration screen) after saving changes.
Comment: Cloudera Manager was causing a few problems (services failing to start, halting, etc so rolled back just prior to it, Someone pointed me towards the ozzie job properties, so I added these to it's xml, which also worked:
oozie.launcher.mapreduce.map.memory.mb
4096

oozie.launcher.mapreduce.map.java.opts
-Xmx3072m
Answer: I had the same problem and solved it increasing two memory assignment at:
YARN / Configuration / CATEGORY / Resource Management:

Map Task Memory:
mapreduce.map.memory.mb

Reduce Task Memory:
mapreduce.reduce.memory.mb


$T:U \to V$, $S: V\to W$, $P:W\to U$, Range($ST$)=nullspace($P$), nullspace($ST$)=range($P$), and rank($T$)=rank($S$)?

Question:
$Range($ST$)=nullspace($P$)$ $\rightarrow rank(ST)=dim(W)-rank(P)$
and
$nullspace(ST) = range(P) \rightarrow dim(U)-rank(ST)=rank(P)$
Combining above two, $dim(U)=dim(W)$
Clearly, option $(A)$ can't be always true since $dim(V)$ is not necessarily equal to $dim(U)$
$(b)$ is not correct.
I am unable to rule out between $(c)$ and $(d)$
Answer: You can find a counter example for (d) using slight variations of the identity. Suppose $U$ and $W$ have dimension 3, and $V$ has dimension 4. Then if $T$ 1-to-1, rank($T$) = 3. If rank($T$) = rank($S$), then rank($S) = 3$, so dim(NS($S$)) = 1. Set up NS($S$) in the right way and you'll have your answer.


Deploying block settings as an update script?

Question: I need to add a block to an existing Drupal site and would like to if possible automate the process using hook_update_N or something similar.
Specifically I'm referring to the position and region of the block relative to adjacent and following blocks. Is there a Drupal standard method to this process or do I simply need to use SQL to achieve this.
Is there a way to force a block in between others with some trick with the weights, or will I need to actively increment the weight of blocks below this in the same region?
Thanks for any advice!
Comment: You question is not clear for me, What kind of block you need to create and what is association with hook_update_N? Are you concerned about the position and region of any block or a specific block you want to create?
Comment: I have a contrib module that adds a block, so I am using `hook_update_N` and `module_enable` to enable that module when i run `update.php`. However there are block settings that I also want to apply such as the theme/region/weight as part of the update process. Forcefully setting the weight of the block however will make it clash with the weight of another block (since I want to insert it between 2 existing blocks).
Answer: You could do this if you like, but this is an unstable and hacky way of fixing your problem. The thing is that blocks can be rearranged at any time so using an update function to sort the block weights is not the best way to deal with this.
What you could do instead is to use the context module to deal with blocks. If offers a better interface to control blocks and allow you to display the same block in different regions. It also gives you a more advanced control of when blocks should be displayed, like display on all nodes of type x, or on these views etc.
In addition to all the nice features described above, contexts can be exported as features. This mean that you can with a click of a button create a module that have your block setup stored in code, including weights etc. If those blocks were to be rearranged, you could revert the feature back to the old state.


Password field is not arriving to php using ajax

Question: So i am having an issue debugging where the issue is. Could be Jquery or PHP issue. I have done quite a bit of alert testing and i believe the issue lies in the if statement of ajax, eg i am posting pass if the field is not disabled when posting. Because when doing a echo $_POST['pass'] and alert(data), i get nothing. So i believe the php is working fine please tell me where the issue lies and if you know also the remedy to this situation. Thanks Guys.
Ajax
$(document).on('submit', '#editaccsount', function(event) {
event.preventDefault();

myData = {
        contactname: $('input[name=contactname]').val(),
        business: $('input[name=business]').val(),
        email: $('input[name=email]').val(),
        code: $('input[name=code]').val(),
        phone: $('input[name=phone]').val(),
        priceband: $('input[name=priceband]').val(),
        address: $('input[name=address]').val(),
        active: $('input[name=active]').val(),
        mon: $('input[name=mon]').val(),
        tue: $('input[name=tue]').val(),
        wed: $('input[name=wed]').val(),
        thu: $('input[name=thu]').val(),
        fri: $('input[name=fri]').val(),
        sat: $('input[name=sat]').val(),
        sund: $('input[name=sund]').val(),
        adminname: $('input[name=adminname]').val(),
        accountid: $('input[name=accountid]').val(),
        isadmin: $('input[name=isadmin]').val(),
};

var isDisabled = $('input[name=pass]').prop('disabled');

if (isDisabled == false) {
        myData.pass = $('input[name=pass]').val();
}
$.ajax({
    url: 'php/editaccount.php',
    type: "POST",
    data: myData,
    success: function(data) {

        if ($('input[name=isadmin]').val() == 1) {
            $('input[name=accountsearch]').val($('input[name=email]').val());
            $('input[name=accountsearch]').submit();
        } else {
                $('input[name=accountsearch]').val($('input[name=business]').val());
            $('input[name=accountsearch]').submit();
        }

        alert(data);
    }
});
});

This is my PHP that does all the updating based on conditions:
<?php

require '../../core/init.php';

$auth = new Auth();

$accid = $_POST['accountid'];

echo $accid, '
';
echo 'Password is: ', $_POST['pass'], '
';
echo 'Is Admin: ', $_POST['isadmin'];

if (!empty($_POST['pass'])) {
    echo 'Pass Detected';
    echo 'Password: ', $_POST['pass'], "
";

    $salt = $auth->randomString();
    $newpass = $salt . $_POST['pass'];
    $newpass = $auth->hashData($newpass);

    if ($_POST['isadmin'] == 0) {

        $customer = DBPDO::getInstance()->update('customer', $accid, array(
                'businessName'      =>  $_POST['business'],
                'contactName'       =>  $_POST['contactname'],
                'email'             =>  $_POST['email'],
                'code'              =>  $_POST['code'],
                'phone'             =>  $_POST['phone'],
                'priceBand'         =>  $_POST['priceband'],
                'deliveryAddress'   =>  $_POST['address'],
                'is_active'         =>  $_POST['active'],
                'mon'               =>  $_POST['mon'],
                'tue'               =>  $_POST['tue'],
                'wed'               =>  $_POST['wed'],
                'thu'               =>  $_POST['thu'],
                'fri'               =>  $_POST['fri'],
                'sat'               =>  $_POST['sat'],
                'sun'               =>  $_POST['sund'],
                'password'          =>  $newpass,
                'user_salt'         =>  $salt
            ));
    } elseif ($_POST['isadmin'] == 1) {

        $admin = DBPDO::getInstance()->update('admin', $accid, array(
                'adminName'         =>  $_POST['adminname'],
                'email'             =>  $_POST['email'],
                'phone'             =>  $_POST['phone'],
                'password'          =>  $newpass,
                'user_salt'         =>  $salt
            ));
    }

} elseif (empty($_POST['pass'])) {
    echo 'Pass NOT detected';

    if ($_POST['isadmin'] == 0) {

        $customer = DBPDO::getInstance()->update('customer', $accid, array(
                'businessName'      =>  $_POST['business'],
                'contactName'       =>  $_POST['contactname'],
                'email'             =>  $_POST['email'],
                'code'              =>  $_POST['code'],
                'phone'             =>  $_POST['phone'],
                'priceBand'         =>  $_POST['priceband'],
                'deliveryAddress'   =>  $_POST['address'],
                'mon'               =>  $_POST['mon'],
                'tue'               =>  $_POST['tue'],
                'wed'               =>  $_POST['wed'],
                'thu'               =>  $_POST['thu'],
                'fri'               =>  $_POST['fri'],
                'sat'               =>  $_POST['sat'],
                'sun'               =>  $_POST['sund']
            ));
    } elseif ($_POST['isadmin'] == 1) {

        $admin = DBPDO::getInstance()->update('admin', $accid, array(
                'adminName'         =>  $_POST['adminname'],
                'email'             =>  $_POST['email'],
                'phone'             =>  $_POST['phone']
            ));
    }

}

What gets outputted as HTML:
<?php

require '../../core/init.php';
$data['result_1'] = '';
$searchquery = $_POST['accountsearch'];

if ($_POST['accounttype'] == 'Users') {

$customer = DBPDO::getInstance()->get('customer', array(
                array('businessName', '=', "'$searchquery'" )
            ));

foreach ($customer->results() as $row)
{
    $data['result_1'] .= '

            <input class="btn btn-lg btn-primary" type="button" name="editbtn" value="Edit Account">
            <input class="btn btn-lg btn-danger remove-btn" type="button" name="removebtn" value="Remove Account" uid="'.$row->id.'">

        <form id="editaccount" action="php/editaccount.php" method="POST">

General Details

                        Customer Name

                            <input type="text" disabled="disabled" name="contactname" class="form-control" value="'.$row->contactName.'">

                        Business

                            <input type="text" disabled="disabled" name="business" class="form-control" value="'.$row->businessName.'">

                        Email

                            <input type="email" disabled="disabled" name="email" class="form-control" value="'.$row->email.'">

                        Code

                            <input type="text" disabled="disabled" name="code" class="form-control" value="'.$row->code.'">

                        Phone

                            <input type="text" disabled="disabled" name="phone" class="form-control" value="'.$row->phone.'">

                        Price Band

                            <input type="text" disabled="disabled" name="priceband" class="form-control" value="'.$row->priceBand.'">

                        Delivery Address

                            <input type="text" disabled="disabled" name="address" class="form-control" value="'.$row->deliveryAddress.'">

                        Active

                            <input type="test" disabled="disabled" name="active" class="form-control" value="'.$row->is_active.'">

                        Password

                            <input type="password" disabled="disabled" name="userpass" class="form-control" value="'.$row->password.'">

                            <input id="editpasswordbtn" class="btn btn-sm btn-primary" type="button" value="Edit Password">

                Warning:  If you do NOT want to edit Password please click Cancel!

                <input type="button" class="btn btn-sm btn-danger" value="Cancel Password Change">

Standing Order Details

                        Monday

                            <input type="text" disabled="disabled" name="mon" class="form-control" value="'.$row->mon.'">

                        Tuesday

                            <input type="text" disabled="disabled" name="tue" class="form-control" value="'.$row->tue.'">

                        Wednesday

                            <input type="text" disabled="disabled" name="wed" class="form-control" value="'.$row->wed.'">

                        Thursday

                            <input type="text" disabled="disabled" name="thu" class="form-control" value="'.$row->thu.'">

                        Friday

                            <input type="text" disabled="disabled" name="fri" class="form-control" value="'.$row->fri.'">

                        Saturday

                            <input type="text" disabled="disabled" name="sat" class="form-control" value="'.$row->sat.'">

                        Sunday

                            <input type="text" disabled="disabled" name="sund" class="form-control" value="'.$row->sun.'">

                    <input type="hidden" name="accountid" value="'.$row->id.'">
                    <input type="hidden" name="isadmin" value="0">
                    <input class="btn btn-lg btn-rj" disabled="disabled" type="submit" name="editbtn" value="Send to Database">

        </form>
    ';
}
} elseif ($_POST['accounttype'] == 'Admins') {
$customer = DBPDO::getInstance()->get('admin', array(
                array('email', '=', "'$searchquery'" )
            ));

foreach ($customer->results() as $row)
{
    $data['result_1'] .= '

            <input class="btn btn-lg btn-primary" type="button"  name="editbtn" value="Edit Account">
            <input class="btn btn-lg btn-danger remove-btn adminremove-btn"  type="button" name="adminremovebtn" value="Remove Account" uid="'.$row->id.'">

        <form id="editaccount" action="php/editaccount.php" method="POST">

General Details

                        Admin Name

                            <input type="text" disabled="disabled" name="adminname" class="form-control" value="'.$row->adminName.'">

                        Email

                            <input type="text" disabled="disabled" name="email" class="form-control" value="'.$row->email.'">

                        Phone

                            <input type="text" disabled="disabled" name="phone" class="form-control" value="'.$row->phone.'">

                        Email

                            <input type="hidden" name="isadmin" value="1">
                            <input type="password" disabled="disabled" name="pass" class="form-control" value="'.$row->password.'">

                    <input type="hidden" name="accountid" value="'.$row- >id.'">
                    <input type="hidden" name="isadmin" value="1">
                    <input class="btn btn-lg btn-rj" disabled="disabled" type="submit" name="editbtn" value="Send to Database">

        </form>
    ';
}
}

echo json_encode($data);
exit;

?>

Comment: Have you checked that your isDisabled is set correctly and its getting into the if(isDisabled) statement?
Comment: Yes i have tried that using console, And it picks it up in console but its not sending to the php. So i am a little confused .
Comment: Does everything else get sent? I'm used to serializing the data before sending it usually. You can do $('myForm').serialize() and it will serialize the form for you as well, instead of doing all those .val's.
Comment: I havent ever tried serialize() not sure how it works, but yes the other data in the form does update using ajax. After trying various things, i still think its something to do with the ajax. I have another field on the page with the same name=pass. Would changing the query a little to select name=pass from nearest form would work?
Comment: Yes, if you have 2 then $('input[name=pass]') will return a collection like: ['', ''], so doing .val on that will not give you the result you want. You need to either take the one you want out of that collection or select more specifically. Take the form it is in and do $('form').find('input[name=pass]')
Comment: Are we able to open a chat somehow so i can show you my setup, and perhaps you might be able to see the issue.
Comment: Can you add the html to please?
Comment: HTML is long i am unsure if i am allowed to add alot of code here.
Comment: Can you post at least the part where the input pass is?
Answer: You are checking the property of disabled with:
var isDisabled = $('input[name=pass]').prop('disabled');

If I recall this will return a string empty or disabled as a way to use this would be:
$('input[name=pass]').prop('disabled', 'disabled');

If you're looking for a true/false maybe try with:
var isDisabled = $('input[name=pass]').is(':disabled');

and it will return true or false.
Comment: I will post my php up as well just in case, i tried this method but i still get no pass in php or field update in table.
Comment: I think it should work if you replace var isDisabled = $('input[name=pass]').prop('disabled'); with  var isDisabled = $('input[name=pass]').is(':disabled'); in your code as Fabrizio Mazzoni suggested.


Finding vertical asymptotes

Question: So I am trying to find the behaviour of this function around an asymptote at $x=0$.
$a>0$
$$y=\frac{(x-a)(x^2+a)}{x^2}$$
I know that as $x \to 0^+$, $y \to -\infty $ and $x \to 0^-$, $y \to -\infty $.
I've tried dividing the top and bottom of $y$ by $x^2$ and ended with:
$$x-a+\frac{a}{x}-\frac{a^2}{x^2}$$
Which does not help me as I end with $\infty -\infty$. Any help would be greatly appreciated.
Comment: $$\begin{eqnarray*}
\lim_{x\rightarrow 0}\frac{(x-a)(x^{2}+a)}{x^{2}} &=&\lim_{x\rightarrow 0}%
\frac{x^{3}-ax^{2}+ax-a^{2}}{x^{2}} \\
&=&-a^{2}\lim_{x\rightarrow 0}\frac{1}{x^{2}} \\
&=&-\infty
\end{eqnarray*}$$
Comment: Dividing the top and bottom by a power of $x$ is a method one uses to find a limit as $x \to \pm \infty$.  Tell me first how you arrive at the correct limit $y \to -\infty$.
Comment: My apologies. The question is framed around identifying the functions that match graphs of functions with asymptotes. There were three in total - I have successfully solved the first two. So I know the general behaviour of this function.
Comment: What description of the behavior are you looking for?  From your equation $y=x-a+\frac{a}{x}-\frac{a^2}{x^2}$ you can see that as $x$ approaches $0$ the last term will dominate.  The fact that the numerator of that term (including the leading sign) is negative supports your claim that it goes to $-\infty$ whichever side of $0\ \ x$ is on.
Answer: The fact that $x-a$ is negative when $x$ is near $0$ and $x^2 + a$ positive is positive when $x$ is near zero, and the denominator is positive, will mean that the function must approach $-\infty$ at the vertical asymptote, unless the numerator also approaches $0$, in which case you've got more work to do.  In this case the numerator approaches $-a^3$, which is not $0$, so that's it.
You're quite right about the fact that breaking it into $\infty-\infty$ won't help.  If you had that, I'd tell you to write it as a single fraction by using a common denominator.  That would take you to what you started with.
Answer: Expanding my comment above.

I know that as $x \to 0^+$, $y \to -\infty $ and $x \to 0^-$, $y \to
 -\infty $.

Only the first assertion is correct.
Since $\left( x-a\right) (x^{2}+a)=x^{3}-ax^{2}+ax-a^{2}$, we have
$$\begin{eqnarray*}
\lim_{x\rightarrow 0}\frac{\left( x-a\right) (x^{2}+a)}{x^{2}}
&=&\lim_{x\rightarrow 0}\left( x^{3}-ax^{2}+ax-a^{2}\right) \times
\lim_{x\rightarrow 0}\frac{1}{x^{2}} \\
&=&-a^{2}\times \lim_{x\rightarrow 0}\frac{1}{x^{2}}=-a^{2}\left( +\infty
\right) =-\infty, \qquad\text{    for }a\ne 0.
\end{eqnarray*}$$
So as $x$ approaches $0$, either from the left or from the right, $y\rightarrow -\infty $. The limit does not depend on the sign of $a$.
Plot of $y$ for $a=1$ (black) and $a=-1$ (green).

Finding vertical asymptotes


interface conversion: error is *errors.errorString, not validator.ValidationErrors

Question:
type BookInput struct {
  Title string `json:"title" binding:"required"`
  Price json.Number `json:"price" binding:"required,number"`
}

func PostBookHandler(ctx *gin.Context) {
  var bookInput book.BookInput

  err := ctx.ShouldBindJSON(&bookInput)

  if err != nil {
    errorMessages := []string{}

    for _, e := range err.(validator.ValidationErrors) {
        errorMessage := fmt.Sprintf("Error on filed %s, condition: %s", e.Field(), e.ActualTag())
        errorMessages = append(errorMessages, errorMessage)
    }

    ctx.JSON(http.StatusBadRequest, gin.H {
        "errors": errorMessages,
    })
    return
  }

  ctx.JSON(http.StatusOK, gin.H {
    "title": bookInput.Title,
    "price": bookInput.Price,
  })
}

I tried to validate the price input, but the results I got were unexpected. The code I wrote is like the one above, can someone help me?
Answer: The error returned in this case might not be a validator.ValidationErrors, it could be something else. For example if the body is invalid JSON, then the validation step isn't reached at all.
In your code you are performing an unchecked assertion range err.(validator.ValidationErrors) which could panic.
This is how you could conditionally handle the error:
err := ctx.ShouldBindJSON(&bookInput)
if err != nil {
    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
       // handle validator error
    }
    // handle non-validator error
    return
}

Answer: Maybe it can help:
type BookInput struct {
    Title string `json:"title" binding:"required"`

    Price interface{} `json:"price" binding:"required,number"`
}

func postBooksHandler(c *gin.Context) {
    var bookInput BookInput

    err := c.ShouldBindJSON(&bookInput)
    if err != nil {

        errorMessages := []string{}
        for _, e := range err.(validator.ValidationErrors) {
            errorMessage := fmt.Sprintf("Error on field %s, conditon: %s", e.Field(), e.ActualTag())
            errorMessages = append(errorMessages, errorMessage)

        }
        c.JSON(http.StatusBadRequest, gin.H{
            "error": errorMessages,
        })
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "title": bookInput.Title,
        "price": bookInput.Price,
    })

}

Answer: Need to create two conditions on error, because validator.ValidationErrors doesn't cover everything.
This my code:
if err != nil {
    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
        for _, e := range err.(validator.ValidationErrors) {
            c.JSON(http.StatusBadRequest, gin.H{
                "error":   true,
                "message": "" + e.Field() + " kosong",
            })
            return
        }
    }
    c.JSON(http.StatusBadRequest, gin.H{
        "error":   true,
        "message": err.Error(),
    })
}


Cisco Networking fiber to fiber

Question: I have a cisco 892 router and a cisco catalyst 2960 switch; both have the SFP fiber module.  The plan is to extend the network to the switch using the fiber ports. (Two buildings are connected by fiber)  No routing is needed, just to connect the switch to the router via the fiber ports. I tried to set  the sfp interface to switchport access, but it gives an error – I think it may only support WAN connectivity.
So in a nutshell. I am trying to connect one building to another over fiber. The Cisco routers do not have a fiber port so I had to use a sfp interface to convert the fiber to ethernet. I am trying to get the switch in building A to talk to the router in building B.   I think the problem is I am using the SFP module and it is in an expansion slot on the router and switch and not actually plugged into one of the ports on the switch and router. All I am trying to do is bridge the connections so building A can be apart of building Bs network.
Comment: Are you saying you want to turn the router into a bridge?
Comment: You say it gives an error - what's the error. It's best if you provide complete data.
Answer: Let me see if I understand this correctly. You already have a network in place in building #1 and want to extend it to building #2 via fiber.
I'm assuming you have a 1000base-T switch in building #1 and it is lacking sfp-ports. To mitigate this problem you want to use an 892 you have laying around as a bridge to gain a fiber connectivity in building #1.
Unless the interface with the SFP module accepts the "switchport" command, it can't be done.
I would suggest you toss the 892 and use a media convert instead, e.g http://www.planet.com.tw/en/product/product.php?id=43643
Either that or buy a switch for building #1 with SFP support.

Cisco Networking fiber to fiber


Modelagem de base de dados

Question: Criei a seguinte modelagem:

Gostaria de saber o que pode ser melhorado? levando em considerações boas práticas para banco de dados?
Explicação:
Na TBLogin uma pessoa irá criar um login, podendo ser do tipo PessoaFisica ou PessoaJuridica. OBS: Neste caso uma PessoaJuridica = Empresa
Na TBPessoas coloquei os campos que são comuns para ambos os tipo de pessoa.
TBEndereco TBCidades TBEstados são para armazenar a localização.
TBVagas relacionada com a TBPessoaJuridica(Empresa). Seria as vagas que essa pessoa/empresa cadastrariam para divulgar.
TBCurriculos Toda PessoaFisica pode ter apenas um currículo. O currículo é composto pela TBIdiomas que no caso seria os idiomas que a pessoa fala, podendo haver + de 1.
TBEmpregos É um histórico profissional de onde a pessoa já trabalhou.
TBFormacoes São as formações que um pessoa tem.(Colégio/Faculdade/Cursos)
TBTiposFormacoes são os tipos de formação. Ex: (graduação / pos-graduação / mestrado / doutorado / ensino médio / etc)
OBS: Não sou muito bom com modelagens, tenho pouco conhecimento de relacionamentos de tabelas e essa coisas.
Answer:
A resposta foi invalidada pela edição da pergunta, mas fica aqui quem quiser ver em cima da original.

É sempre difícil sem conhecer os reais requisitos. O que pode ser certo em uma caso pode ser errado em outro.
Não achei nenhum erro grave como se costuma ver em muitos modelos. De uma maneira geral gostei de tudo, até dos detalhes, exceto por prefixar as tabelas com TB e nomear as tabelas no plural. Claro que as informações são escassas. As tabelas possuem poucas colunas. O que eu vejo é que cadastros reais costumam possuir mais dados. Mas pode não ser o seu caso. Pode ser que pretende ampliar depois. Aí o modelo pode começar ficar errado. Mas só posso falar do que estou vendo agora.
O que eu não gosto mas não posso afirmar que está errado sem saber dos detalhes:

Ter uma tabela de relacionamento de pessoas com endereços dependendo se é física ou jurídica. Faz algo sentido fazer assim mas eu não faria. Acho que é duplicação de esforço na maioria dos casos.
Acho estranho turno estar vinculado a currículo, mas vai saber se tem algum motivo. Talvez seja qual o turno de interesse da pessoa. Ela pode ter vários, certo? Pensou nisto?
Obviamente há um simplificação e rigidez do que pode haver em um currículo mas não posso discutir isto no caso concreto. Inclusive dependendo do cargo é provável que tabelas específicas podem ser necessárias para informar sobre certos tipos de habilidades. Mas é só especulação minha. Dá para ser criativo aqui.

Ah, o posicionamento do diagrama poderia dar mais ênfase para as tabelas mais importantes e deixar mais claro como satélites as menos importantes, secundárias, complementares. Mas nada que afete o modelo, claro.
Coloquei no GitHub para referência futura.
Comment: Marginal para sua pergunta, mas seguindo a dica do bigown sobre organização do diagrama: procure por raiz agregada, que é um conceito que aborda a determinação dos 'galhos ' principais'. Mais voltado para quando implementar as regras de negócio que vão manipular seus dados, mas obviamente ajuda a organizar o diagrama.
Comment: Atualizei o esquema. e tentei explicar mais ou menos como é que funciona.
Comment: Na prática, quanto mais simples melhor. Tanto para entender a dinâmica como para trazer os relacionamentos dos dados. procure sempre adotar a ideia de que toda o MER sempre pode ser melhorado, e que no futuro, ele deve poder ser expandido, então seja o mais abstrato possível, nunca crie tabelas desnecessárias só para o intuito de expandir sua arquitetura, seja objetivo. No geral, dá pra melhorar... Enxugue o máximo que poder. Quer saber como melhorar, comece fazendo um caso de uso primeiro...
Answer: Do meu ponto de vista o modelo esta praticamente correto.
A única alteração que eu faria seria a seguinte:
Pessoa -> Endereco (1..N)
Pessoa -> PessoaFisica (1..1)
Pessoa -> PessoaJuridica (1..1)

Assim eliminando as tabelas :
- TBPessoasFisicas_has_TBEndereco.
- TBPessoaasJuridicas_has_TBEndereco.
Afinal, pessoa tem endereço, não importa se é jurídica ou física.
Assim criando TBPessoa_has_TBEndereco.
Eu não compreendi a tabela de Vagas, relacionada com pessoa jurídica, afinal você esta identificando a pessoa, Vagas estaria melhor relacionada com uma tabela de Empresa, pois a empresa tem vagas.
Comment: Neste caso `PessoaJuridica` = 'Empresa'

Modelagem de base de dados


Why is custom domain for Github pages not serving pages for other repositories?

Question: Github's About custom domains and GitHub Pages forum reads,

After you configure a custom domain for a user or organization site, the custom domain will replace the <user>.github.io or <organization>.github.io portion of the URL for any project sites owned by the account that do not have a custom domain configured. For example, if the custom domain for your user site is www.octocat.com, and you have a project site with no custom domain configured that is published from a repository called octo-project, the GitHub Pages site for that repository will be available at www.octocat.com/octo-project.

This is exactly what I want. I made a home repository <user>.github.io (with a basic static html website) for my custom domain and set the custom domain xyz.com and www.xyz.com to direct to <user>.github.io as explained in Managing a custom domain for your GitHub Pages site. Here is how it looks.

I also added a file CNAME in xyz-repo with contents xyz.com. Now www.xyz.com and xyz.com both point to the html in xyz-rep, perfect.
Here is the issue though, I have another repository with Github pages that I can access by <user>.github.io/other-repo-name but not by xyz.com/other-repo-name or www.xyz.com/other-repo-name.
Any help?
Answer: It sounds like you manually created the CNAME file. From the docs at https://help.github.com/en/github/working-with-github-pages/managing-a-custom-domain-for-your-github-pages-site,

Under "Custom domain", type your custom domain, then click Save. This
  will create a commit that adds a CNAME file in the root of your
  publishing source.

I believe Github's system adds the CNAME commit for you: not sure if it will work if you do it? Or maybe there's a specific branch it has to live in? I'd try removing your manually created CNAME file and using the configuration UI.
Comment: I actually deleted the repository and records and did them again, this seems to have fixed it.


Function series - pointwise/ uniform converges?

Question:
Let the function series:$$S(x) = \sum_{n=1}^\infty \frac{x^2}{(1+x^2)^n}$$  study it's converges (point-wise/uniform) in $\mathbb{R}$.

So we have: $$S(x) = x^2 \sum_{n=1}^\infty \frac{1}{(1+x^2)^n}$$
Now, if I showed that for sufficiently large $n$-s for a given $x$:
$$\frac{1}{(x^2+1)^n} < \frac{1}{n^2}$$ then we're done.
For uniform converges, I think we can use dini's theorem but for that we need to know that $S(x)$ is a continuous function too.
Answer: Assuming $x\in\mathbb{R}$:
$$\sum_{n=1}^{\infty}\space\frac{x^2}{(x^2+1)^n}=\lim_{m\to\infty}\sum_{n=1}^{m}\space\frac{x^2}{(x^2+1)^n}=$$
$$\lim_{m\to\infty}\space\left(1-\frac{1}{\left(x^2+1\right)^m}\right)=1-\lim_{m\to\infty}\frac{1}{\left(x^2+1\right)^m}=$$
$$1-\lim_{m\to\infty}\left(x^2+1\right)^{-m}=1-\lim_{m\to\infty}\exp\left(\ln\left(\left(x^2+1\right)^{-m}\right)\right)=$$
$$1-\lim_{m\to\infty}\exp\left(-m\ln\left(x^2+1\right)\right)=1-\exp\left(-\ln\left(x^2+1\right)\lim_{m\to\infty}m\right)=$$
$$1-\exp\left(-\ln\left(x^2+1\right)\lim_{m\to\infty}m\right)=1-0=1$$
So it equals $1$ when: $\frac{1}{|x^2+1|}<1$

With some strange notations (because $\infty$ isn't a number):
$$1-\exp\left(-\ln\left(x^2+1\right)\lim_{m\to\infty}m\right)=$$
$$1-\exp\left(-\ln\left(x^2+1\right)\cdot\infty\right)=$$
$$1-\exp\left(-\infty\right)=1-e^{-\infty}=1-\frac{1}{e^{\infty}}=1-0=1$$
Comment: @Elimination You're welcome! If you know that $x$ is real you can find: $\frac{x^2}{\left(x^2+1\right)^n}=x^2\left(\left(x^2+1\right)^2\right)^{-\frac{n}{2}}$
Comment: @Elimination You're welcome (again)!


Assign random numbers avoiding blocked numbers from a range in JavaScript

Question: I have a game where users can win an extra prize if they select a specific a number from the board.
The Game Master chooses a range for the game and the extra prizes are randomly allocated to a number.
However, the extra prizes cannot be allocated:

to a "blocked number"
or the same number as another prize

I have a crude way of making sure the first prize doesn't match.
How can this code be extended to cover all 5 extra prizes?  I am concerned if I just copy the function 5 times it could loop forever?
Would it be better to create to the game range in an array and then remove the values for each prize as they are generated?
var gameMinNum = 10;
var gameMaxNum = 125;
var gameBlockedNum = [5,12,66,97,124,129,165,200]

var extraPrizeNum1 = 0;
var extraPrizeNum2 = 0;
var extraPrizeNum3 = 0;
var extraPrizeNum4 = 0;
var extraPrizeNum5 = 0;

function randomGenerator(xUpper,xLower)
{
  return Math.floor(Math.random()*(xUpper-xLower+1)+xLower);
}

function PrizeNum1() {

  extraPrizeNum1 = randomGenerator(gameMaxNum,gameMinNum);
  if (gameBlockedNum.includes(extraPrizeNum1)) {
    PrizeNum1();
  }
}

Comment: Why do you store the "extra prices" in separate variables (and not in an array like the "blocked numbers")?
Comment: In the game code, if the selected number matches one of the prizes it will trigger a different congratulations message etc... and I also store additional details in the array.   I tried to simplify describing my problem with the code above.
Answer: You could take a Set for used values and take an array for all prices.

function randomGenerator(xUpper, xLower) {
    return function () {
        return Math.floor(Math.random() * (xUpper - xLower + 1) + xLower);
    };
}

function getExtraPrices(randomFn, length, blocked) {
    var selected = new Set(blocked);
    return Array.from({ length }, () => {
        var number;
        while (selected.has(number = randomFn())) ;
        selected.add(number);
        return number;
    });
}

var gameMinNum = 10,
    gameMaxNum = 125,
    gameBlockedNum = [5, 12, 66, 97, 124, 129, 165, 200],
    extraPricesCount = 5,
    random = randomGenerator(gameMaxNum, gameMinNum),
    extraPrices = getExtraPrices(random, extraPricesCount, gameBlockedNum);

console.log(extraPrices);


What can be the most efficient way to remove first 10 elements from tuple?(every elements)

Question: THE PROBLEM
Hi, I am currently learning python and opencv. I want to get only name of the dog species from the above pic, which removing the first 10 strings and numbers after the dog species.
For example:
[('n00000000-Maltese_dog', 252')] to 'Maltese_dog'.
I would appreciated if you can provide me any information of removing 'n' elements from tuple, or any help.
Thank you! Hope yall have a great day
Comment: Don't post images of code. Put the actual data (or a minimal representation of it) in the question and then format it by indenting 4 spaces.
Comment: Use string slicing.  `mytuple[0] = mytuple[0][10:]`
Answer: Don't think of it in terms of removing items, think of extracting the data you want.
For each tuple, t,  in the list take the first item t[0] and then take a slice of the string t[0][10:]. You can use a list comprehension to make a new list of all the strings:
l = [
    ('n00000000-Maltese_dog', '252'),
    ('n10030000-Australian terrier', '252')
]

[t[0][10:] for t in l]
# ['Maltese_dog', 'Australian terrier']


Parameter in expectation subscript

Question: There are a few questions/answers out there about subscripts involving a random variable ($E_X[...]$) or a density ($E_{f(X)}[...]$) in expectations.  I like this one.
But today I ran into a subscript involving a parameter of a density, and there is a point that confuses me.
The book of A. A. Tsiatis defines m-estimators $\hat{\theta}_n$ as the solution of:
$\sum_{i=1}^nm(Z_i, \hat{\theta}_n)=0$
where $Z_1,...,Z_n$ is an iid sample from $p_Z(z,\theta)$, $\theta$ is $p$-dimensional and, by definition, $E_{\theta}[m(Z, \theta)]=0^{p \times 1}$. When I first saw that zero-expectation condition I thought:
$\int m(Z, \theta)p_\theta(\theta)d\theta$
which is not weird in a Bayesian context, where parameters have distributions. But then I remembered that the likelihood in MLE is $L(\theta;z)\equiv p_Z(z,\theta)$, so I figured the $E_{\theta}[\quad ]$ was shorthand for:
$\int m(Z, \theta)p_Z(z,\theta)d\theta$
However, at the bottom of page 32 he says that this zero-expectation condition is equivalent to:
$\int m(Z, \theta)p_Z(z,\theta)d\nu(z)=0 \quad \text{for all } \theta$
where $\nu(z)$ is the dominating measure.
I would like to understand (1) what that subscript $\theta$ means in the expectation and (2) why the expectation is equivalent to this last integral + the "for all $\theta$" condition.
Comment: The expectation is parameterized by $\theta$; it is taken with respect to the distribution given the parameter value $=\theta$.  This is important because you want to make sure that the $\theta$ in $m(Z,\theta)$ has the same value as the parameter that's in $p_Z(z;\theta)$, and it's that latter $\theta$ that the subscript refers to.
Comment: I think I understand what you're saying and it seems to also answer my second question. If you post it as an answer I will accept it.
Answer: In this case, the subscript means "the expectation is parameterized by $\theta$"; it is taken with respect to the distribution $p$ given $p$'s parameter value $= \theta$. This is important in this context because you want to make sure that the reader understands that $\theta$ in $m(Z,\theta$) has the same value as the parameter that's in $p_Z(z;\theta)$, and it's that latter $\theta$ that the subscript refers to.
It is a little confusing, as often the subscript on the expectation operator refers to what the expectation is taken with respect to, not what the parameters of the relevant probability distribution are.

Parameter in expectation subscript


Estrutura de banco de dados para sistema de enquete

Question: Tenho um projeto para desenvolver um sistema de enquete online. Estou preocupado na forma que eu vou buscar as respostas das questões para mostrar em um gráfico. Cada gráfico é cada questão a ser analisada. Vejamos, se eu possuo uma questão que possui 4 respostas diferentes, e que cada pergunta, somente pode ser marcado uma só resposta. Basicamente, a estrutura seria:
1) pergunta um
   a) questao um
   b) questao dois
   c) questao tres
   d) questao quatro
   e) questao cinco
2)
   a) questao um
   b) questao dois
   c) questao tres

Eu preciso de ajudar para definir qual o melhor critério para armazenar essas respostas no banco de dados. Basicamente, preciso saber quantas vezes na pergunta 1, a, b, c, d, e, foi selecionado para ser mostrado o gráfico da pergunta um. Se eu tivesse uma tabela na seguinda estrutura:
id_usuario 2
respostas ac

Nesse caso o usuário id 2, teria respondido a questão 1,letra a e questão 2, letra c.
Mas a questão seria, se eu tratasse isso na programação seria muito trabalhoso para mim. Gostaria de saber qual a melhor forma de desenvolver esse sistema seguindo esses critérios.
Answer:
Nesse caso você precisar configurar no banco (opcao_id, resposta_id, usuario_id) como um índice único ou tratar com PHP no momento da inserção.


Drive cloning dd or rsync/sync via KVM

Question: I've got a crash and the system won't boot correctly. I am getting errors like:
ata3.00: status: { DRDY }
ata3.00: status: { UNC }

What would be the best way to save the main drive to make the system boot again?
I am looking at:
Using DD for disk cloning
I read that using DD to clone a live system is bad. But does booting in via KVM mean just as bad?
Answer: You don't want to do a block level copy of a drive when any of the filesystems are mounted (which also means that you can't be running the OS installed on the drive). Either boot a live CD/USB (I like RIPLinux) or connect the drive to another machine.
In terms of getting data off a dodgy drive, rather use ddrescue (the GNU version, sometimes called gddrescue). It won't stop as soon as it encounters a bad sector like dd will, and can resume copies. Make sure to specify a log file:
ddrescue /dev/sda /mnt/sdb1/sda.img /mnt/sdb1/sda.log

Comment: Is using KVM considered being mounted to the filesystems of the main drive? doesn't this CL run DD even if it does get errors? dd if=/dev/sda of=/dev/sdb bs=32M conv=noerror,sync
Comment: @ThompsonSmith Depends how you are using KVM. If KVM is booting off an OS stored on the bad drive then that's still a problem. `noerror` will make it continue, but `ddrescue` is still better for this.
Comment: So KVM Would need to boot off a disk with a fresh OS Install? Isn't DDRescue a lot slower? I've used it once. I know data centers typically use DD. Does it depend more on the state of the drive?
Comment: @ThompsonSmith: ddrescue will go back and retry blocks that fail on the first try, so it's much better than dd for cloning flaky drives. (This also makes it slower, precisely because it doesn't just give up right away on errors.)

Drive cloning dd or rsync/sync via KVM


Problem with Tail Recursion in g++

Question: I'm was messing around with tail-recursive functions in C++, and I've run into a bit of  a snag with the g++ compiler.
The following code results in a stack overflow when numbers[] is over a couple hundred integers in size. Examining the assembly code generated by g++ for the following reveals that twoSum_Helper is executing a recursive call instruction to itself.
The question is which of the following is causing this?

A mistake in the following that I am overlooking which prevents tail-recursion.
A mistake with my usage of g++.
A flaw in the detection of tail-recursive functions within the g++ compiler.

I am compiling with g++ -O3 -Wall -fno-stack-protector test.c on Windows Vista x64 via MinGW with g++ 4.5.0.
struct result
{
    int i;
    int j;
    bool found;
};

struct result gen_Result(int i, int j, bool found)
{
    struct result r;
    r.i = i;
    r.j = j;
    r.found = found;
    return r;
}

// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i, int j)
{
    if (numbers[i] + numbers[j] == target)
        return gen_Result(i, j, true);
    if (i >= (size - 1))
        return gen_Result(i, j, false);
    if (j >= size)
        return twoSum_Helper(numbers, size, target, i + 1, i + 2);
    else
        return twoSum_Helper(numbers, size, target, i, j + 1);
}

Comment: Did you already try to do the conditional increments separately and do the recursive call only once with the incremented parameters?  It is less nice than your example, but it might shed some light on your problem.
Comment: Does it work if you use a single statement ala `return twoSum_Helper(numbers, size, target, i + j_ge_size, j_ge_size ? i + 2 : j + 1)` where `j_ge_size` is `bool j >= size`?  (suit yourself re implicit conversion from bool).
Comment: Tom makes an interesting observation in http://stackoverflow.com/questions/34125 - his tail recursion needed the function to be static...?
Comment: @stefaanv Yes, to no avail. It appears that the call is occuring on the else statement, but no amount of tweaking will cause it to use a jmp instead of a call.
Comment: @Tony Assembly still has a call to itself for what equates to the else clause above.
Comment: @Tony: Tom doesn't say this, and it's wrong. Tom said that if you change the function linkage to `extern` TCO will no longer apply – which is completely different. Extern linkage will effectively defer the call resolution to link time and since GCC by default performs only very limited link-time optimization TCO no longer applies. But a function doesn't need to be `static` for this to apply.
Answer: Tail call optimization in C or C++ is extremely limited, and pretty much a lost cause. The reason is that there generally is no safe way to tail-call from a function that passes a pointer or reference to any local variable (as an argument to the call in question, or in fact any other call in the same function) -- which of course is happening all over the place in C/C++ land, and is almost impossible to live without.
The problem you are seeing is probably related: GCC likely compiles returning a struct by actually passing the address of a hidden variable allocated on the caller's stack into which the callee copies it -- which makes it fall into the above scenario.
Answer: Try compilling with -O2 instead of -O3.
How do I check if gcc is performing tail-recursion optimization?

well, it doesn't work with O2 anyway. The only thing that seems to work is returning the result object into a reference that is given as a parameter.
but really, it's much easier to just remove the Tail call and use a loop instead. TCO is here to optimize tail call that are found when inlining or when performing agressive unrolling, but you shouldn't attempt to use recursion when handling large values anyway.
Comment: If you're curious, the flag for optimizing tail recursion is -foptimize-sibling-calls, and is included in -O2, -O3, and -Os.
Comment: Well, the answer i'm linking to presents a case where O2 works, but not O3.
Answer: I can't get g++ 4.4.0 (under mingw) to perform tail recursion, even on this simple function:
static void f (int x)
  {
  if (x == 0) return ;
  printf ("%p\n", &x) ; // or cout in C++, if you prefer
  f (x - 1) ;
  }

I've tried -O3, -O2, -fno-stack-protector, C and C++ variants. No tail recursion.
Answer: I would look at 2 things.

The return call in the if statement is going to have a branch target for the else in the stack frame for the current run of the function that needs to be resolved post call (which would mean any TCO attempt would not be able overwrite the executing stack frame thus negating the TCO)
The numbers[] array argument is a variable length data structure which could also prevent TCO because in TCO the same stack frame is used in one way or another.  If the call is self referencing (like yours) then it will overwrite the stack defined variables (or locally defined) with the values/references of the new call.  If the tail call is to another function then it will overwrite the entire stack frame with the new function (in a case where TCO can be done in A => B => C, TCO could make this look like A => C in memory during execution).  I would try a pointer.

It has been a couple months since I have built anything in C++ so I didn't run any tests, but I think one/both of those are preventing the optimization.
Comment: There is no "numbers[] array argument", that's misleading (and it certainly isn't of variable length). There is only a *pointer* argument, the stack frame is always used identically, and that's almost certainly not the cause here. And if-else isn't the cause either. **Every** recursion needs a base case, and hence a conditional statement.
Comment: Has been a while since C++, I get that it is a pointer, thnx. I do think the conditional is the source though, recursion does need a base case, but Tail Call optimization means that there is no instruction left on the stack except return after the recursive call has been made, in order for the compiler to optimize, the recursive call needs to be the last statement in the frame, the 2nd IF still has a branch target for the ELSE after it in the execution stack.  It is the logical last statement but not the physical (when the assembly is in memory).
Comment: And I did mean the 3rd IF (the one that decides the next self referencing recursive call)
Answer: Try changing your code to:
// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i, int j)
{
    if (numbers[i] + numbers[j] == target)
        return gen_Result(i, j, true);
    if (i >= (size - 1))
        return gen_Result(i, j, false);

    if(j >= size)
        i++; //call by value, changing i here does not matter
    return twoSum_Helper(numbers, size, target, i, i + 1);
}

edit: removed unnecessary parameter as per comment from asker
// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i)
{
    if (numbers[i] + numbers[i+1] == target || i >= (size - 1))
        return gen_Result(i, i+1, true);

    if(i+1 >= size)
        i++; //call by value, changing i here does not matter
    return twoSum_Helper(numbers, size, target, i);
}

Comment: This will probably work, but unfortunately it defeats the general idea of what I was testing.
Comment: Also, j is not necessarily always going to be i+1 on every recursive call.
Comment: @Swiss I just rewrote the bottom lines of zour code and kept the function signature, but since zou asked for it I changed the singature and shortened it a bit.
Comment: @Swiss Also what would be the problem if this would work, this would mean that the problem is likely that you have two points from which you recurse. As the example shows this can easily be rewritten (like recursion could also be removed by using loops, I think there is a theorem for that, since I could not google it quick enough there is a [section in wikipedia](http://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Expressive_power) wich hints to this)
Answer: Support of Tail Call Optimization (TCO) is limited in C/C++.
So, if the code relies on TCO to avoid stack overflow it may be better to rewrite it with a loop. Otherwise some auto test is needed to be sure that the code is optimized.
Typically TCO may be suppressed by:

passing pointers to objects on stack of recursive function to external functions (in case of C++ also passing such object by reference);
local object with non-trivial destructor even if the tail recursion is valid (the destructor is called before the tail return statement), for example Why isn't g++ tail call optimizing while gcc is?

Here TCO is confused by returning structure by value.
It can be fixed if the result of all recursive calls will be written to the same memory address allocated in other function twoSum (similarly to the answer https://stackoverflow.com/a/30090390/4023446 to Tail-recursion not happening)
struct result
{
    int i;
    int j;
    bool found;
};

struct result gen_Result(int i, int j, bool found)
{
    struct result r;
    r.i = i;
    r.j = j;
    r.found = found;
    return r;
}

struct result* twoSum_Helper(int numbers[], int size, int target,
    int i, int j, struct result* res_)
{
    if (i >= (size - 1)) {
        *res_ = gen_Result(i, j, false);
        return res_;
    }
    if (numbers[i] + numbers[j] == target) {
        *res_ = gen_Result(i, j, true);
        return res_;
    }
    if (j >= size)
        return twoSum_Helper(numbers, size, target, i + 1, i + 2, res_);
    else
        return twoSum_Helper(numbers, size, target, i, j + 1, res_);
}

// Return 2 indexes from numbers that sum up to target.
struct result twoSum(int numbers[], int size, int target)
{
    struct result r;
    return *twoSum_Helper(numbers, size, target, 0, 1, &r);
}

The value of res_ pointer is constant for all recursive calls of twoSum_Helper.
It can be seen in the assembly output (the -S flag) that the twoSum_Helper tail recursion is optimized as a loop even with two recursive exit points.
Compile options: g++ -O2 -S (g++ version 4.7.2).
Answer: I have heard others complain, that tail recursion is only optimized with gcc and not g++.
Could you try using gcc.
Answer: Since the code of twoSum_Helper is calling itself it shouldn't come as a surprise that the assembly shows exactly that happening. That's the whole point of a recursion :-) So this hasn't got anything to do with g++.
Every recursion creates a new stack frame, and stack space is limited by default. You can increase the stack size (don't know how to do that on Windows, on UNIX the ulimit command is used), but that only defers the crash.
The real solution is to get rid of the recursion. See for example this question and this question.
Comment: Tail recursive functions are unique because it is theoretically possible to optimize their recursion from a call instruction to a jmp instruction. This changes the stack requirement of the function from O(n) to O(1). In practice it's not so simple, because it relies on the compiler to make the distinction and utilize the optimization.
Comment: Sorry, I've missed that there's an optimization which is not applied since this wasn't mentioned in the question. Still, it's a bit dangerous to rely on a specific compiler optimization, no ?
Comment: @Swiss: that's a C++ problem (or in general a language-specific problem). There are languages which guarantee that tail recursion is done. For people experimenting with their own compilers, the easiest way to start is by adding an explicit `tailcall %1` instruction.
Comment: This doesn't answer the question: tail recursion should elide the call and prevent the stack from overflowing, but the optimisation is not being applied, and the OP wants to know why.
Comment: @DarkDust I'm starting to feel that way about tail-recursion. It's nice in theory, but can go terribly wrong with no real warnings.
Comment: @Dark: that depends. In principle, tail recursion is very well known, a relatively common case and it's well established that all modern compilers *do* support it. So many people argue (and I include myself here) that you *should* be able to rely on this optimization. It's indeed baffling that g++ doesn't do this here, and arguably an optimization *bug*.

Problem with Tail Recursion in g++


When does a morphism of varieties preserve codimension of points?

Question: The context of this question is my attempt to generalise the Hurwitz theorem to varieties that aren't necessarily curves. In the case of curves, we have that a closed point always maps to a closed point because we are generally only dealing with finite morphisms. So we get a morphism from a prime divisor to a prime divisor, which we can extend linearly with ramification indices.
But as soon as we leave the world of curves this seems more difficult. The situation I am in is if we have a normal variety $Y$ with a projective birational morphism from a smooth variety $\pi: X \rightarrow Y$. Now if $p \in X$ is the generic point of a codimension $1$ subset, then why should it be true that $f(p)$ also has codimension $1$?
My attempt so far is to notice that since the morphism is dominant we have an injective morphism on local rings $\mathcal{O}_{Y, f(p)} \rightarrow \mathcal{O}_{X, p}$ from which we get that $\dim \mathcal{O}_{Y, f(p)} \leq \dim \mathcal{O}_{X, p}$. But to obtain equality we would normally want the extension of local rings to be integral. Is there any way to deduce integrality from the fact that the morphism $\pi$ is proper? If it were affine I think we could, because we would have a univerally closed morphism of affine schemes. But in this case it doesn't seem so obvious. Is it even true?
Comment: This is false for any dimension bigger than 1: take $f: X \rightarrow Y$ to be the blowup of a smooth point, and $p$ the generic point of the exceptional divisor.
Comment: @LazzaroCampeotti that looks like an answer to me - would you care to record it below?
Answer: This is false for any dimension bigger than 1: take $f:X \rightarrow Y$ to be the blowup of a smooth point, and $p$ the generic point of the exceptional divisor.
On the other hand, you say you are interested in the situation when $f: X \rightarrow Y$ is a birational morphism to a normal variety. Understanding the relationship between the canonical divisors of $X$ and $Y$ in this case is a fundamental issue in minimal model theory. Under suitable assumptions, there is a formula
$$K_X = f^* K_Y + \sum_i a_i E_i$$
where the sum is over all prime divisors on $X$ contracted by $f$, and the coefficients $a_i$ is a rational number called the discrepancy of $E_i$. The values of the $a_i$ depend on the singularities of $Y$, and imposing various bounds on the $a_i$ defines important classes of singularities such as terminal, canonical, and log canonical.
More details can be found in various texts such as those of Koll'ar--Mori, Matsuki, Debarre...
Comment: Thank you @Lazzaro, in fact my question was noticed by studying some introductory lectures for the minimal model program where I had seen this formula. I have done some thinking in the meantime and I was wondering what exactly those suitable assumptions are. Intuitively it seems like we need the morphism to be sufficiently "nice" outside of a pure codimension $1$ set. What exactly is "nice"? And am I wrong to think that formula is a kind of generalized Hurwitz formula, or am I missing the point entirely?
Comment: Dear Luke, the terminology "Riemann--Hurwitz" is usually reserved for _finite_ morphisms. In this context there is indeed a higher-dimensional version of the formula for curves: see for example Theorem 2.14 of http://math.mit.edu/~mckernan/Teaching/07-08/Autumn/18.735/l_2.pdf
Comment: As for the suitable assumptions, I suggest you consult one of the references I gave above. They can give a more accurate and enlightening explanation than I can.


Moment-generating function (MGF) of non-central chi-squared distribution

Question: I need to compute the moment-generating function of the non-central chi-squared distribution, but I have no idea where to begin.
Answer: Let $Z$ have a standard normal distribution, with mean $0$ and variance $1$, then $(Z+\mu)^2$ has a noncentral chi-squared distribution with one degree of freedom. The moment-generating function of $(Z+\mu)^2$ then is
\begin{equation}
 E[e^{t(Z+\mu)^2}] = \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} f_Z(z) \text{d}z
\end{equation}
with $f_Z(z) = \frac{1}{\sqrt{2\pi}}e^{-z^2/2}$ the density of $Z$. Then,
\begin{align*}
 E[e^{t(Z+\mu)^2}] & =  \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} e^{-z^2/2}\text{d}z\\
 & = \frac{1}{\sqrt{2\pi}} \int \exp[-(\frac{1}{2}-t)z^2+2\mu t z +\mu^2 t] \text{d} z\\
 & = \frac{1}{\sqrt{2\pi}} \int \exp[-(\frac{1}{2}-t) (z-Q)^2+\mu^2 t + \frac{2\mu^2 t^2}{1-2t}] \text{d} z \qquad\text{with } Q=\frac{2\mu t}{1-2t}\\
 & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] \frac{1}{\sqrt{2\pi}} \int \exp[-\frac{(z-Q)^2}{2(1-2t)^{-1}}] \text{d}z\\
& = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] (1-2t)^{-1/2} \times \frac{1}{\sqrt{2\pi}(1-2t)^{-1/2}} \int \exp[-\frac{(z-Q)^2}{2(1-2t)^{-1}}] \text{d}z\\
& = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] (1-2t)^{-1/2} \times 1\\
& = \exp[\frac{\mu^2 t}{1-2t} ] (1-2t)^{-1/2}
\end{align*}
By definition, a noncentral chi-squared distributed random variable $\chi^2_{n,\lambda}$ with $n$ df and parameter $\lambda=\sum_{i=1}^n \mu_i^2$ is the sum of the squares of $n$ independent normal variables $X_i=Z_i+\mu_i$, $i=1,\ldots,n$. That is,
\begin{equation*}
\chi^2_{n,\lambda} = \sum_{i=1}^n X_i^2 = \sum_{i=1}^n (Z_i+\mu_i)^2
\end{equation*}
Because all terms are jointly independent and using the above result, we have
\begin{align*}
 E[e^{t\chi^2_{n,\lambda}}] & = E[\prod_i \exp[t(Z_i+\mu_i)^2]]\\
 & = \prod_i E[\exp[t(Z_i+\mu_i)^2]]\\
 & = \prod_i (1-2t)^{-1/2} \exp[\frac{\mu_i^2t}{1-2t}]\\
 & = (1-2t)^{-n/2} \exp[\frac{t}{1-2t}\sum_i \mu_i^2]\\
 & = (1-2t)^{-n/2} \exp[\frac{\lambda t}{1-2t}]\\
\end{align*}
Comment: Hi Stijn, I don't understand how you have $E[e^{t(Z+\mu)^2}] = \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} f_Z(z)$, with $f_Z(z) = \dfrac{1}{\sqrt{2\pi}}e^-{z^2/2}.$ $X = (Z+\mu)^2$ has a noncentral $\chi^2$ distribution, so shouldn't we have a moment generating function of the form $E[e^{t(Z + \mu)^2}] = \int e^{t(Z + \mu)^2} f_X(x)dx$, where $f_X(x)$ is the probability density function of the noncentral $\chi^2$ distribution?
Comment: @titusAdam: No. The correct formula for the expectation of a function $g(Z)$ of a (continuous) random variable $Z$ with density function $f_Z(z)$ is $\text{E}[g(Z)]=\int g(z) f_Z(z)\text{d}z$.
In our case here we have $\text{E}[e^{tX}]=\int e^{tx}f_X(x)\text{d}x=\text{E}[e^{t(Z+\mu)^2}]=\int e^{t(z+\mu)^2}f_Z(z)\text{d}z$. So either you integrate over $x$ or over $z$, but not something in between.


String com maior e menor número de caracteres

Question: Desejo retornar a maior e a menor string.
Vejam:
nl=str(input('Digite uma string'))

String=[]
string.append(nl)

while caractere != 'pare':
    caractere = str(input("Digite uma letra ou número "))
    string.append(caractere)

Dentre as entradas que o usuário escrever, eu gostaria de pegar a maior e a menor string e imprimi-las na tela.
Comment: Mas o usuário irá entrar com uma letra, número ou um texto?
Comment: qualquer tipo de string, as strings de menor e maior caracteres seriam impressas. Ex:

23123
asd
da
as
.

A saída seria:
menor  = .
maior = 23123
Answer: Basta você criar uma lista, de forma bem semelhante ao que já fez:
textos = []
while True:
    texto = input("Entre com um texto:")
    if texto == 'pare':
        break
    textos.append(texto)

Depois, para encontrar o menor e maior texto, basta utilizar as funções nativas min e max, fazendo uso do parâmetro key passando a função len. Desta forma, você obterá o menor e maior texto em relação ao retorno da função len e não somente do conteúdo do texto.
menor = min(textos, key=len)
maior = max(textos, key=len)

Comment: Muito Obrigado, funcionou perfeito^^


Evaluating $\int_0^3|3x-1|\,dx$.

Question: The definite integral I have to evaluate is
$$
\int_0^3|3x-1|\,dx.
$$
The answer I got was $13.5$ only because I solved for the area after where the graph of the function starts to increase after decreasing. I'm not sure how to find the area of the function where it is decreasing since it's a very small portion of the graph. Thanks in advance.
Comment: Hint: Break up the interval $[0,3]$ into two pieces, one where $3x-1$ is positive and the other where $3x-1$ is negative.
Comment: Can you show where you got 13.5 from?  It doesn't agree with my calculations.
Comment: I got the area of a rectangle plus the area of a triangle on the side where the function is increasing: (3*1)+(1/2)*3*7
Comment: [Helpful graph](http://i.stack.imgur.com/LiYme.jpg) (Desmos app)
Answer: Consider the following:
\begin{align}
\int_0^3|3x-1|\,dx &= \frac{1}{3}\int_{-1}^{8}|u|\,du\tag{$u=3x-1; du = 3\,dx$}\\[1em]
&= \frac{1}{3}\left|\int_{-1}^{0}u\,du\right|+\frac{1}{3}\left|\int_0^8 u\,du\right|\tag{split up regions}\\[1em]
&= \frac{1}{3}\left(\left.\frac{u^2}{2}\right|_{-1}^0 + \left.\frac{u^2}{2}\right|_0^8\right)\tag{FTC}\\[1em]
&= \frac{1}{3}\left(\frac{1}{2}+32\right)\\[1em]
&= \frac{65}{6}
\end{align}
Your integral may be visually interpreted by the following picture:
$\color{white}{\text{center me please I dare}}$
Answer: hint: $I = \displaystyle \int_{0}^{\frac{1}{3}} + \displaystyle \int_{\frac{1}{3}}^{3}$
Answer: $$\text{Hint: }\int_0^a|ax-1| dx = \int_0^{\frac1a}1 - ax \ dx + \int_{\frac1a}^a ax - 1\ dx$$

Evaluating $\int_0^3|3x-1|\,dx$.


Adding data to node object

Question: Is there a hook responsible for generating the node object's data?
I want to add some custom data to specific node objects to help with the functionality of a very complex website.
Can anyone help, please?
Comment: does't fields allow that? or are you looking at something different?
Answer: hook_node_load() is exactly what you're looking for

Act on arbitrary nodes being loaded from the database.
This hook should be used to add information that is not in the node or node revisions table, not to replace information that is in these tables (which could interfere with the entity cache). For performance reasons, information for all available nodes should be loaded in a single query where possible.

The code example from the docs page is actually very good for your use case so I'll include it here too:
function hook_node_load($nodes, $types) {
  // Decide whether any of $types are relevant to our purposes.
  if (count(array_intersect($types_we_want_to_process, $types))) {
    // Gather our extra data for each of these nodes.
    $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
    // Add our extra data to the node objects.
    foreach ($result as $record) {
      $nodes[$record->nid]->foo = $record->foo;
    }
  }
}

Comment: Then you're after [`hook_node_presave()`](http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7) :) If you need to mae changes _after_ the node has saved then you want `hook_node_update()` and `hook_node_insert()`
Comment: Thanks for your very helpful answer. I was looking for a way of adding to the node object data at the point creation or being editted

Adding data to node object


What's the best server infrastructure for real-time games?

Question: I'm developing a Real-Time game which should hold thousands of players in real-time.
What would be the best server structure for this?
My idea was using 2 server clusters - one for the Server End (all the computing side) and one for the Database end, where a load balancer is "responsible" for each of the clusters.
One main server will receive the requests from the users and send back the IP address of the relevant server that the user can work this.
The database cluster will use database replication for consistency between the databases.
I'm using .NET + MSSQL for the game.
Comment: This would kind of depend in part on how decoupled your design is, too. And where your servers will be vs. where your players are...great decoupling and optimization of systems won't translate into great performance if your servers are in NY and your players are in Lithuania.
Comment: I agree - we are planning on geographical load balancing as well, where as a player in Germany will get the closest local load balancer to him, which in turn will return the IP of a server from it's server cluster. The question is - is the design right and scalable?
Comment: Please don't use the term cluster as it is related to the term failover cluster which is a High Availability Cluster where only one of the nodes is active with the SQL Server...
Answer: Latency will be your biggest enemy for gaming.  Gamers don't tolerate lag, so you must keep it to a minimum.
There are some interesting articles on game server infrastructure in which you may be interested:
http://www.eveonline.com/devblog.asp?a=blog&bid=769
http://wiki.eveonline.com/en/wiki/RAMSAN
http://www.datacenterknowledge.com/archives/2009/11/25/wows-back-end-10-data-centers-75000-cores/
https://stackoverflow.com/questions/1418749/how-are-massively-multiplayer-online-rpgs-built


Add custom next slide button to Unslider script

Question: I use the unslider.js slider script.
By the way I can recommend it to everyone.
I'm trying to add an 'to next slide' button inside a slide.
First I added the same class to the button as the class from the next arrow link. But it doesn't work.
Is there a possibility to do this?
Thank you
**JS**
            var unslider = $('.banner').unslider({

        complete: function() {},
        keys: true,
        dots: false,
        fluid: false,
        nav: false
    });

    $('.unslider-arrow').click(function() {
        var fn = this.className.split(' ')[1];

        unslider.data('unslider')[fn]();
    });

**HTML snippet**

To next slide

http://jsfiddle.net/qATC9/45/
Answer: first you need to set an href like this:
To next slide

to prevent navigation. Then in jQuery
$('.unslider-arrow').click(function() {
    unslider.data('unslider').next();
});

see updated FIDDLE
Answer: May be this will help you
just use this code

  To next slide

 To next slide

 To next slide

            ←
            →

Check it here on FIDDLE


Como transformar uma saída de uma query já em xml no Informix?

Question: É possivel pegar uma saída qualquer de uma query direto do banco e
trazer o resultado já formatado em texto XML  ?
Isso utilizando banco de dados IBM Informix v11.50 e de modo nativo no banco de dados.
Onde ao invés do banco retornar um dataset com cada campo em seu formato irá retornar um TXT em XML.
Answer: A partir da vesão 11.10 do banco é possivel sim.
Para saber qual versão do banco você está utilizando, execute este SQL:
select dbinfo('version', 'full') from systables where tabid = 1;

Existem algumas funções especificas para isso, porém há limitações que para contorna-las pode ser um pouco trabalhoso e até depender de certas configurações no banco (SMARTBLOB spaces).
A função básica para isso é a genxml() onde ela vai retornar em apenas 1 linha todos os registros da query. Como esta função retorna uma LVARCHAR ela é limitada em 32kbytes o que pouco para um XML, portanto tem que tomar cuidado como vai selecionar muitos dados senão terá o erro 8368 (veja no final do exemplo abaixo), para contornar este problema você ter que utilizar outras funções .
Uma lista das funções existentes (que você irá encontrar detalhes nos links dos manual abaixo): genxml, genxmlelem, genxmlschema, genxmlquery, genxmlqueryhdr,  extract, extractvalueclob, existsnode, idsxmlparse.
Para referencia em uma versão mais antiga do banco consulte este linkda versão 11.50
Para referencia na versão mais atual do banco consulte este link da versão 12.10
Exemplo de um sql executado no dbaccess.
database sysmaster;
Database selected.

select genxml(systables, "tabela") from systables where tabid = 1 ;
genxml  <tabela tabname="systables" owner="informix                        " pa
        rtnum="1048800" tabid="1" rowsize="497" ncols="24" nindexes="2" nrows="
        245.0000000000000000" created="21/11/2011" version="65539" tabtype="T"
        locklevel="R" npused="9.0000000000000000" fextsize="32" nextsize="32" f
        lags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11
        :23:13.00000" secpolicyid="0" protgranularity=" "/>
1 row(s) retrieved.

select genxmlclob(systables, "tabela") from systables where tabid = 1 ;
genxmlclob
<tabela tabname="systables" owner="informix                        " partnum="1048800" tabid="1" rowsize="497" ncols="24" nindexes="2" nrows="245.0000000000000000" created="21/11/2011" version="65539" tabtype="T" locklevel="R" npused="9.0000000000000000" fextsize="32" nextsize="32" flags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11:23:13.00000" secpolicyid="0" protgranularity=" "/>
1 row(s) retrieved.

select genxmlclob(systables, "tabela") from systables where tabid <=5 ;
genxmlclob
<tabela tabname="systables" owner="informix                        " partnum="1048800" tabid="1" rowsize="497" ncols="24" nindexes="2" nrows="245.0000000000000000" created="21/11/2011" version="65539" tabtype="T" locklevel="R" npused="9.0000000000000000" fextsize="32" nextsize="32" flags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11:23:13.00000" secpolicyid="0" protgranularity=" "/>
<tabela tabname="syscolumns" owner="informix                        " partnum="1048801" tabid="2" rowsize="157" ncols="10" nindexes="2" nrows="2778.0000000000000000" created="21/11/2011" version="65539" tabtype="T" locklevel="R" npused="30.0000000000000000" fextsize="32" nextsize="32" flags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11:23:13.00000" secpolicyid="0" protgranularity=" "/>
<tabela tabname="sysindices" owner="informix                        " partnum="1048802" tabid="3" rowsize="3323" ncols="15" nindexes="2" nrows="192.0000000000000000" created="21/11/2011" version="65539" tabtype="T" locklevel="R" npused="11.0000000000000000" fextsize="32" nextsize="32" flags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11:23:13.00000" secpolicyid="0" protgranularity=" "/>
<tabela tabname="systabauth" owner="informix                        " partnum="1048803" tabid="4" rowsize="77" ncols="4" nindexes="2" nrows="262.0000000000000000" created="21/11/2011" version="65539" tabtype="T" locklevel="R" npused="6.0000000000000000" fextsize="32" nextsize="32" flags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11:23:13.00000" secpolicyid="0" protgranularity=" "/>
<tabela tabname="syscolauth" owner="informix                        " partnum="1048804" tabid="5" rowsize="73" ncols="5" nindexes="2" nrows="109.0000000000000000" created="21/11/2011" version="65539" tabtype="T" locklevel="R" npused="3.0000000000000000" fextsize="32" nextsize="32" flags="0" type_xid="0" am_id="0" pagesize="4096" ustlowts="2011-11-21 11:23:13.00000" secpolicyid="0" protgranularity=" "/>
1 row(s) retrieved.

select genxml(systables, "tabela") from systables ;
 8368: Function (genxml) Buffer size exceeds maximum size.
Error in line 2
Near character position 49

Database closed.


My container moves up into the header when a file is downloaded in Chrome. Not sure how to fix it

Question: I have a container and as I've been previewing it in the Chrome browser. I noticed that when I downloaded a file, and the download appeared at the bottom of the browser, the container in my website preview moved up into the header section of the webpage. I'm teaching myself HTML and CSS and I can't figure it out. Here is my CSS code:
.container {
    background-color: #FFF;
    padding-left: 30px;
    padding-right: 30px;
    border-radius: 10px;
    -moz-border-radius: 10px;   /*So the border is visible in Mozilla*/
    -webkit-border-radius: 10px; /*So the border is visible for browsers using webkit */
    position: fixed;
    left: 65%;
    width: 24em;
    top: 55%;
    transform: translate(-50%,-50%);
}

Here is the HTML:

Connect with Facebook

Connect with Twitter

            <input type="text" id="firstname" class="input" required pattern=.*\S.* />
            First Name

            <input type="text" id="lastname" class="input" required pattern=.*\S.* />
            Last Name

            <input type="text" id="email" class="input" required pattern=.*\S.* />
            Email

            <input type="password" id="password" class="input" required pattern=.*\S.* />
            Password

            <input type="password" id="password2" class="input" required pattern=.*\S.* />
            Password (again)

By creating an account, you agree to our Terms and Conditions.

          <button class="btn">Sign-Up</button>

The position is fixed and not float. Any ideas? Thanks in advance.
Comment: we need more info to reproduce the problem, please post the relevant html and css
Comment: @cocoa Just added the HTML code
Comment: Does the same happen when you reduce the height of the window?
Comment: @Shomz Yes, when I adjust the size of the webpage the container doesn't become smaller or larger, it remains the same size and just floats on the page. It doesn't stay in a fixed position.
Comment: Understood, the percentages are the same, but their actual values change because the window size changes (for example: 50% of 200px and 50% of 180px are not the same)... I explained it in my answer.
Comment: Thanks a lot for your help, seriously! I'll try it out and mark your answer. Thanks! @Shomz
Comment: You're welcome, @Kayla! Just calculate those vertical offsets in pixels, and you'll be good to go. Or, if you can, completely drop the fixed positioning and simply lay block elements one on top of another, as they work by default.
Comment: No problem. Hmmm, it's because of the fixed position and top offset. It's used to achieve that effect. Don't use it if you want elements to behave normally (you'd probably have to remove the transform rule as well.
Comment: Thanks again! I fixed it by removing the fixed position and replaced it with `float: right;` I adjusted the margins as needed. You're an awesome guy! Thanks @Shomz
Comment: Awesome! Haha, thank you, @Kayla, I'm glad I could help! :)
Answer: Observe the following two rules for your container:
top: 55%;
transform: translate(-50%,-50%);

It's a vertical positioning "hack" that relies on the window height (unless you have a relatively positioned parent, those rules are in relation to the window). What happens when you download a file is that you lose a little piece of the window height, because of that little Chrome's download box.
Not sure how exactly it looks like, but the way to fix it is to use pixels for both top and the vertical component of transform: translate rules.
Generally, you should avoid using percentages for fixed elements, not only because of Chrome's download box, but because different users will have different website experiences unless they all have the identical window height (which you can never count on).