I have a Windows 2008 R2 Amazon EC2 server, it can't ls via ftp client, what do I have to do to fix that?

Question: I have a Windows 2008 R2 Amazon EC2 and it needs to download a file from an external server via ftp.  The file name is different everyday so I have to ls and then get the newest file.  ls fails:
[REDACTED]:\[REDACTED]>ftp [REDACTED]
Connected to [REDACTED].
220 ProFTPD 1.3.3c Server ready.
User ([REDACTED]:(none)): [REDACTED]
331 Password required for [REDACTED]
Password:
230 User [REDACTED] logged in
ftp>ls
Connection closed by remote host.
ftp>

So it takes a while for it to say "Connection closed by remote host." this is what happens when I try on any non-Amazon EC2 Windows 2008 R2 server:
[REDACTED]:\[REDACTED]>ftp [REDACTED]
Connected to [REDACTED].
220 ProFTPD 1.3.3c Server ready.
User ([REDACTED]:(none)): [REDACTED]
331 Password required for [REDACTED]
Password:
230 User [REDACTED] logged in
ftp>ls
200 PORT command successful
150 Opening ASCII mode data connection for file list
photos
tmp
key
logs
customer
reversefeed
reviews
thesaurus
incoming
ad
226 Transfer complete
ftp: 144 bytes received in 0.01Seconds 18.00Kbytes/sec.
ftp>

So just to be clear I'm not running an FTP Server, I am trying to connect to one and download a file.  But it is unable to open the data transfer channel.  What do I need to change in the Amazon EC2 config for this to work?
Thanks in advance.
Answer: This is usually (in my experience) a problem caused by a firewall or filter/proxy on one end of the connection not properly handling PASV (passive) FTP connections.  First thing I'd try is using an active FTP connection, and then I'd try to remove the firewall(s) from the equation, which will give you a fairly exact indication of where the issue lies.
And, just as a general point of interest, SFTP (FTP over SSH) does not suffer from this active/passive problem (it's a single, "active" connection), in addition to being a secure, encrypted method of transferring files.  You should probably switch to it, if possible.  It will probably eliminate your problem, and wrap a layer of security around your file transfers at the same time.
Comment: @RobertLouisMurphy  Then you're limited to making sure there's no firewall or proxy/filter on your end blocking things, or trying to use an `ACTIVE` `FTP` connection.  Might also consider dumping those asshats too.  I'm pretty sure my current employer makes more than 8 million dollars profit **a week**, and I get tickets for `$externalcustomer` having issues connecting to `$oursystem` a fair bit.  If I told them I didn't care because we make so much money already, I'd be fired.  Time to maybe consider that these guys are small time asshats and your business is better given to a competitor.
Comment: I have no control over the server and must connect to them via the protocol they provide.  It is an $8 million profit a year company so they don't care if I am encountering issues.
Answer: Both FTP and FTPS use 2 or more ports in their connection protocol. You need to open at least 2 ports to make them work.   For FTP, its usually 21 and 20.  For FTPS its usually 989 and 990 I think.  So, I think most people prefer to use SFTP, which uses a single port tunnelled in a SSL channel, usually on port 22, which is the same port that SSH shells use.
You can verify ports using this batch script:
@echo off
cls
ECHO TCP ports that are listening...
ECHO.
ECHO   Prot   Local Address          Foreign Address        State           PID
ECHO.
netstat -an -o | find "LISTENING"
ECHO.
pause

Comment: Yes, that much is clear.  Really when it comes down to it, you just need to verify the servers ports are open (depending on protocol type) and also that the client is not being blocked on any of the ports outgoing either.  It isn't a hard thing to troubleshoot if you just look at it from a technical perspective...
Comment: You know I'm running a client, not a server right?  My issue is the the data stream.


How can I use feeds tamper to remove currency ($) sign when importing prices?

Question: I have an integer field that I am using for price info (not commerce) and I am importing from a csv. I need to strip out the $ sign and a blank space after. "$ ". How can I do this with feeds tamper?
Comment: Isn't it easier to update the .csv file?
Comment: No, these are automated, periodic imports and we don't have access to the source.
Answer: This is pretty easy.  You can use the "Find replace" tamper under "Text", and then user "$" as the search and "$ " as the replace.  If you want to be fancy you can use the "Find replace REGEX" tamper to make sure you only get the leading $.  IIRC, this needs to include the delimiters.  Using "/^\$/" as the search and "$ " as the replace should work (you need the ^ to anchor to the beginning and then escape the $.  Both of these plugins are part of the base feeds_tamper module.
Comment: I did try the find replace before posting but it didn't take. I assumed it was because of the blank space. I will try the regex way.


Why can complex numbers be written in exponential form? $z=r(\cos \theta+i\sin \theta)$ is $z=re^{i\theta}$.

Question: Why can complex numbers be written in exponential form? $z=r(\cos \theta+i\sin \theta)$ is $z=re^{i\theta}$.
I have studied that the exponential form of a complex number $z=r(\cos \theta+i\sin \theta)$ is $z=re^{i\theta}$.
Can someone explain why?
Comment: @A---B I am not sure "Why complex numbers are written in expoenential form?" is fine either (besides introducing a typo), because the question asks "I have studied that … can be written… can somebody explain why?", so it may be asking about why complex numbers _can_ be written in exponential form, rather than why they _are_.
Comment: @A---B: I have reverted the edit which changed the title of the question to "how to change from polar to exponential form…" — it does not seem to be what the question is asking, so changes the meaning of the question.
Comment: @ShreevatsaR Check now.
Comment: @ShreevatsaR Yes I think you are correct.
Comment: There is deeper justification for the equivalence of polar form and exponential form of a complex number (and this is beyond algebra). For an introduction to complex numbers this equivalence can be thought of a mnemonic to help remember rule for multiplication of complex numbers: multiply moduli and add argument.
Comment: https://math.stackexchange.com/questions/3510/how-to-prove-eulers-formula-eit-cos-t-i-sin-t
Answer: Here's a rather elegant proof.
The function $f : t\mapsto \cos t+i\sin t$ is differentiable and satisfies
\begin{align*}
f'(t) &= i\,f(t)  \\
f(0) &= 1
\end{align*}
Now let's solve it.
We have $f(0) = 1$ and
$$f'(t) = (\cos t+i\sin t)' = -\sin t+ i\cos t = i(\cos t+i\sin t) =if(t) $$
Now let us solve this differential equation
$$f'(t) = if(t)\Longleftrightarrow e^{-it}f'(t) -ie^{-it} f(t)=0 \Longleftrightarrow \frac{d}{dt}\left(e^{-it} f(t)\right)  = 0$$
That is
$$e^{-it} f(t) = c\Longleftrightarrow  f(t) = ce^{it}$$
But $f(0)=1 $ i.e $c=1$. Hence $f(t)=e^{it}$.
Comment: I don't understand what you are trying to prove here, and what is your definition of $e^{it}$ while you do it.
Comment: It's not clear what you mean by "$\ln(f(t))$". Someone wondering why $e^{it} = \cos t + i \sin t$ probably doesn't know what complex logarithm is; even worse, they may not even know that they don't know what it is! (And thus miss the fact that there's something nontrivial to say.)
Comment: Continuing Paramanand Singh's comment: if we don't know what $e^{it}$ is, how do we know what its derivative is? That is, how do we know that it satisfies $\frac{\mathrm{d}}{\mathrm{d}t}f(t)=i\,f(t)$?
Comment: When you use the power series definition of $e^z$ the result in question follows trivially from Taylor series for sine and cosine. So that part is easy. On the other hand how do you propose to analytically extend the definition of $e^{x} $? One of the ways of doing this is via power series. Other is to define $e^{x+iy} =e^{x} (\cos y+i\sin y) $ which again makes the question trivial. From your solution it appears that you assume that $g(t)=e^{it} $ satisfies the differential equation (in the beginning of your post). This makes it trivial as one can show that the equation has unique solution.
Comment: It is a little easier to show that $t \mapsto e^{-it} f(t)$ is a constant. Then the proof becomes a one liner.
Comment: +1 ugh, came here just to post a similar thing, but you beat me :) this is the most satisfying answer IMO.
Comment: @Mehrdad Thank you for editing this but I think we should be carefull to use logarithm together with complex. so I now propose an easier Proof.
Comment: @FedericoPoloni Maybe you check that edit now. Then ask further question if you still don't understand.
Comment: It would be better if you could supplement your answer with a specific definition of $e^{it} $.
Comment: @NajibIdrissi Please check the first edited proof it does not use complex logarithm. I arised this issues myself
Comment: @ParamanandSingh You are right this depend on with definition we are of $e^{it}$. Here Our definition of $e^z$ is just the analytical extension of the real exponential $e^x$. But if you want to use the definition $e^z=\sum_{n} \frac{z^n}{n!}$ the to solve we will need to use Picard iteration which is far a bite beyond the scope of this question
Comment: @NajibIdrissi, GuyFsone: You can just assume $i$ is an arbitrary constant (a real-valued one if you so desire) and then at the end just naturally extend the same definition to complex values by assuming $i = \sqrt{-1}$. It's quite intuitive that this is the only definition that would make sense, even if you've never heard the term "analytical extension" before. That's kind of what I was going for.
Comment: Thus your approach needs to be supplemented with the following: a proper definition of $e^{it} $ with $t$ being real. And using this definition prove that $(e^{it}) '=ie^{it} $ and further $e^{-it} e^{it} =1$.
Comment: @ParamanandSingh the writing $$e^{x+iy} = e^x(\cos y+i\sin y)$$ is what we means by analytics extension. and this extension carries also the properties of the extended function. Including the equation $y'=a y$
Comment: @GuyFsone: if by analytic extension you mean the definition $e^{x+iy} =e^{x} (\cos y+i\sin y) $ then by putting $x=0$ we are done.
Comment: One approach which I can suggest is to use the power series definition of $e^{z} $ and using it show that $(e^{it}) '=ie^{it} $ and also $e^{it} e^{-it} =1$ (these properties are very easily proved using power series) . Then your solution works and we get $e^{it} =\ cos t+i\sin t$ (this also gives Taylor series for since cosine for free).
Comment: Another approach is the use of definition $e^{z} =\lim_{n\to\infty} (1+(z/n))^{n}$ which @robjohn has handled in excellent manner in the linked answer.
Comment: Once you've set up the differential equation $\frac{dy}{dt} = i\,y$, the standard way of solving it is to move all the y expressions to one side, integrate with respect to $t$, which gives you $\ln y$ on the left; so you take the exponential of both sides. This avoids the aha factor of multiplying by $e^{-it}$.
Answer: Lets consider a function from $\mathbb R\to \mathbb C$
$z(\theta) = \cos \theta + i\sin \theta\\
z(\theta)z(\phi) = (\cos \theta + i\sin \theta)(\cos \phi + i\sin \phi) = \cos(\theta + \phi) + i\sin (\theta+\phi) = z(\theta + \phi)$
That is a property of an exponential function.  We do not know the base.
For some base:
$\exp (iy) = z(y) =\cos y + i\sin y$
and:
$\exp (x + iy) = \exp(x)\exp(iy) =\exp(x) (\cos y + i\sin y)$
And then you can define $e$ to be the required base.  In much of complex analysis, it does not matter that it is the same $e$ as you have learned to be Euler's constant.
However, if you have taken calculus, you should recognize these Taylor expansions.
$e^x = \sum_\limits{n=0}^{\infty} \frac {x^n}{n!}\\
\cos x = \sum_\limits{n=0}^{\infty} \frac {(-1)^nx^{2n}}{(2n)!}\\
\sin x = \sum_\limits{n=0}^{\infty} \frac {(-1)^nx^{2n+1}}{(2n+1)!}$
what is
$e^{ix}$ ?
$e^{ix} = \sum_\limits{n=0}^{\infty} \frac {{ix}^n}{n!}\\
1 + ix + \frac {(ix)^2}{2} + \frac {(ix)^3}{3!}+ \frac {(ix)^4}{4!} \cdots\\
1 + ix + \frac {-x^2}{2} + \frac {-ix^3}{3!} + \frac {x^4}{4!} \cdots$
collect the real terms and the imaginary terms
$(1 - \frac {x^2}{2} + \frac {x^4}{4!}\cdots )+ i( x  - \frac {x^3}{3!} + \frac {x^5}{5!}  \cdots)\\
e^{ix} = \cos x + i\sin x$
Without calculus.
we can define
$e = \lim_\limits{n\to\infty}(1+\frac {1}{n})^n\\
e^x =\lim_\limits{n\to\infty} (1+\frac {1}{n})^{nx} $
Make a substitution $m = nx$
$e^x =\lim_\limits{m\to\infty} (1+\frac {x}{m})^m $
Then look at what happens as $m = 1, 2,3, etc.$
We have already shown that multiplication of complex numbers multiplies the lengths and adds the angles.

As $m$ increases hopefully you can see how that sequence of line segments begins to lie on the curve of the circle.
and when $m$ is very large comes to rest on $\cos x + i\sin x$
Answer: There are several reasons. Even without going into the technical details of why it's correct, here is a small list of reasons for why might be a good idea:

It's easy to use that form to read off the length and angle of your complex number
It's easy to recognize the form and see that it is indeed meant to convey length and angle as opposed to, for instance, the width and height we see in the $a+bi$ form.
The rules for complex multiplication means that hijacking the exponential notation and (mis)use the intuition you have from real exponentiation gives the correct results
Answer: In this answer, it is shown that
$$
\lim_{n\to\infty}\left(1+\frac{i\theta}n\right)^n=\cos(\theta)+i\sin(\theta)\tag1
$$
Therefore, we can say
$$
e^{i\theta}=\cos(\theta)+i\sin(\theta)\tag2
$$
We can also use the power series for $e^x$, $\cos(x)$, and $\sin(x)$ to derive $(2)$.
In any case, once we have $(2)$, any point on the unit circle in $\mathbb{C}$ can be represented as $e^{i\theta}$ for some $\theta\in\mathbb{R}/2\pi\mathbb{Z}$; $\theta$ is the argument of that point.
Furthermore, using $(2)$, we can write any point in $\mathbb{C}$ as
$$
\begin{align}
x+iy
&=\overbrace{r\cos(\theta)}^x+i\,\overbrace{r\sin(\theta)}^y\\
&=re^{i\theta}\tag3
\end{align}
$$
One important identity is
$$
\begin{align}
e^{i\theta}e^{i\phi}
&=(\cos(\theta)+i\sin(\theta))(\cos(\phi)+i\sin(\phi))\\
&=(\cos(\theta)\cos(\phi)-\sin(\theta)\sin(\phi))+i(\sin(\theta)\cos(\phi)+\cos(\theta)\sin(\phi))\\
&=\cos(\theta+\phi)+i\sin(\theta+\phi)\\
&=e^{i(\theta+\phi)}\tag4
\end{align}
$$
Equation $(4)$ tells us that we can combine imaginary exponents like we do real ones.
Answer: If $z=0$ it is clear that we can take $r=0$ and any value for $\theta$.
Note that any number on the complex unit circle can be written as $\cos t + i \sin t$ for some $t$.
Note that any non zero complex number $z$ can be written as $z= |z| {z \over |z|}$ and ${z \over |z|}$ lies on the complex unit circle.
If we let $r=|z|$, then we see that there is some $t$ such that $z = r (\cos t + i \sin t)$.
As to why $e^{it} = \cos t + i \sin t$, let
$\phi(t) = e^{it} - ( \cos t + i \sin t ) $, note that $\phi(0) = 0$ and $\phi'(t) = i\phi(t)$. Hence $e^{-it} \phi(t)$ is a constant from which it follows that $\phi(t) = 0$ for all $t$.
Answer: It's a definition.
As to why it's a good definition, the answer comes from the fact that the Taylor series for exp(x) stays the same when we let $x \in \mathbb{C}$.


Expo/React Native Background/Sleep Mode Timer

Question: I'm currently trying to get a timer to work in Expo/React Native. I want that my timer is still running in the background when the user for example locks his phone screen or he just puts the app in the background. Is this somehow manageable with react native?
I need this functionality to send a notification when the timer is finished, even when it's in background as mentioned.
Answer: not sure, background timer stops about an hour after phone idle. location can't really do background timer as its background services is only triggered when other apps are actively requestion location such as google maps.
Comment: So there is no possibility to achieve my request?


Does a homomorphism send a subgroup to itself?

Question: Let $P$ be a normal $p$-Sylow subgroup of a finite group G and let $\phi:G \to G$ be a homomorphism. Is it necessarily true that the elements of $P$ will also get mapped within the subgroup, $\phi: P \to P$? That is, can we say that for any element $p \in P, \phi(p) \in P$, too?
As a note, I'm aware that in the end it does turn out that $\phi(P) \subseteq P$. I'm wondering if we need to argue that thoroughly or if we can just say that the image of $P$ is a subset of $P$ because by definition of a homomorphism the elements will be mapped back to the subset.
Answer: If $P$ is a normal $p$-Sylow subgroup, then you know it is the unique maximal $p$-subgroup of $G$ (because $p$-Sylow subgroups are conjugate to one another). Since any $p$-subgroup of $G$ is contained in a $p$-Sylow subgroup, we get that any $p$-subgroup of $G$ is contained in $P$.
So, let $\phi$ be an endomorphism of $G$. Then $\phi(P)$ is the homomorphic image of a $p$-group, hence it is a $p$-subgroup of $G$.
Comment: This makes a lot of sense. So I think I understand why $\phi(P) \subseteq P$, but I want to make sure that that is as much as we know. For instance, we cannot say that if $s \in P, \phi(s) = s \in P$, correct? Like $\phi$ isn't given to be any sort of identity mapping so no definition of a homomorphism would imply that any element is necessarily mapped back to itself, right?
Comment: @Bryyo357 If $\phi$ is an automorphism, you can infer $\phi(P)=P$ for cardinality reasons. But just considering the trivial homomorphism $\phi(g)=1$, for all $g\in G$, tells you that not much more can be said. The fact that $P$ is self-conjugated doesn't mean that its elements are self-conjugate, so the elements of $P$ need not be fixed even by inner automorphisms.
Answer: Yes, but in general only if $P$ is unique (i.e. if it is normal).
That's because in general $\operatorname{ord}(\phi(g)) \mid \operatorname{ord}(g)$ for every $g \in G$. Since for every $\pi \in P$ we have $\operatorname{ord}(\pi) = p^n$ for some $n \geq 0$, it follows that $\operatorname{ord}(\phi(\pi)) = p^m$ for some $0 \leq m \leq n$. Thus $\operatorname{ord}(\phi(\pi))$ lies in some $p$-Sylow subgroup, but we can't guarantee in which one unless it is unique.


Prove $\sin \left(1/n\right)$ tends to $0$ as $n$ tends to infinity.

Question: I'm sure there is an easy solution to this but my mind has gone blank! Any help on proving that $\sin( \frac{1}{n})\longrightarrow0$ as $n\longrightarrow\infty$ would be much appreciated.
This question was set on a course before continuity was introduced, just using basic sequence facts. I should have phrased it as:
Find an $N$ such that for all $n > N$ $|\sin(1/n)| < \varepsilon$
Comment: It is useful to know that $|\sin x|\leq |x|$ for every $x\in\mathbb{R}$. Proof: MVT.
Comment: I assume you do not want a solution that uses facts about continuity, let alone differentiability, the mean value theorem, or Taylor series.  Right?
Answer: $$\lim\limits_{n\to\infty}\sin\left(\frac{1}{n}\right)=\lim\limits_{n\to\infty}\frac{\sin\left(\frac{1}{n}\right)}{\left(\frac{1}{n}\right)}\left(\frac{1}{n}\right)=\left(\lim\limits_{n\to\infty}\frac{\sin\left(\frac{1}{n}\right)}{\left(\frac{1}{n}\right)}\right)\left(\lim\limits_{n\to\infty}\frac{1}{n}\right)=1\times0=0$$
Answer: Because $\sin$ is continuous, we can take:
$$\lim\limits_{n\to\infty}\sin\left(\frac{1}{n}\right)=\sin\left(\lim\limits_{n\to\infty}\frac{1}{n}\right)=\sin{(0)}=0$$
To answer the new question:
For each $\epsilon>0$ we need to find how big $n$ (for $N>0$, $n>N$) must be to ensure that $|\sin\left(\frac{1}{n}\right)-0|<\epsilon$. Thus we have:
$$|\sin\left(\frac{1}{n}\right)|<\epsilon$$
Let's only consider positive instances of $\sin1/n$ as negative ones will always be less than $\epsilon$. Then:
$$\frac{1}{\arcsin\epsilon}<n$$
So we put $N=1/\arcsin\epsilon$.
Then, formally:
Let $\epsilon>0$ and let $N=1/\arcsin\epsilon$. Then $n>N$ implies $n>1/\arcsin\epsilon$, hence $\arcsin\epsilon>\frac{1}{n}$, hence $\epsilon>\sin1/n$, hence $|\sin1/n|<\epsilon$. Finally, we have $|\sin1/n-0|<\epsilon$ which proves that the limit is 0.
Comment: Yes, I can see this now, although I've made an edit to the original question. I should have specified I was looking for an argument not based on continuity. Thanks!
Comment: @Wooster I've updated the answer with a different solution.
Answer: Hint
$$\quad0 \leq\sin\left(\frac{1}{n}\right)\leq \frac{1}{n}$$
Answer: Hint: $\sin$ is a continuous function.
Edit: Since $\dfrac{1}{n}\longrightarrow 0$ the statement below is true: $$(\forall \delta>0)(\exists M\in \Bbb N)(\forall n\in \Bbb N)\left(n\ge M\implies \left\vert \dfrac{1}{n}\right\vert<\delta\right)$$
Using $M$ from above and the fact that $\left \vert \sin\left(\dfrac{1}{n}\right)\right \vert<\left \vert \dfrac{1}{n}\right \vert$ for all $n\in \Bbb N$ try to find a suitable $N$.
Comment: And also, look at a *graph* of the sine function. If $x < y$, and $y$ is "close" to zero, can $\sin(x)$ be larger than $\sin(y)$ in absolute value?
Answer: Consider the Taylor series expansion of $\sin(1/n)$, then
$$ \frac{1}{n}- \frac{1}{n^3} \leq\sin \left(\frac{1}{n}\right) \leq \frac{1}{n}. $$


Why is ddebug_backtrace coming up blank?

Question: I've been using the Devel module for a couple of years now but every time I try to get a backtrace I run into issues.  I remember getting it working once, but I don't remember how.
It seems like using dpm(ddebug_backtrace()); should do the trick.  I have tried it with no argument, TRUE, and FALSE, and I have also tried removing the dpm function it's wrapped in.
I have dpm calls directly above and below this code that print variables appropriately, but the most I get out of dpm(ddebug_backtrace()); is a blank line in the Krumo output.
Suggestions mightily appreciated.
Comment: `dpm(ddebug_backtrace());` works fine for me (I just tried it). Does `die(ddebug_backtrace());` work for you?
Answer: For me the command had to be called without the extra d
dpm(debug_backtrace());
Comment: This worked for me.  I'm on D7.
Answer: If you see the source, you can see that ddebug_backtrace() only returns values if the variable error_level is set to 1 or greater.
// Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
// (This is Drupal's error_level, which is different from $error_level,
// and we purposely ignore the difference between _SOME and _ALL,
// see #970688!)
if (variable_get('error_level', 1) >= 1) {

So one of the ways to make it return values is by either changing the error_level from admin/config/development/logging, or change it temporarily in the code like so:
variable_set('error_level', 1);
dpm(ddebug_backtrace(TRUE));
variable_set('error_level', 1);

As Ian Bullock says, debug_backtrace() would return values because it ignores the variable and the content is essentially the same. But ddebug_backtrace() returns a more readable output.
Comment: Thank you very much for the explanation, this actually answers the question.
Answer: In the instances where I've been like, "WTF! Where's my dpm output at?", it's either been:

A permissions issue with an impersonated user not having access devel information perm.
A theme page that isn't outputting the $messages var.

Hope that helps.
Comment: Thanks shawn, gets a vote because it's good advice, sadly I've already been through that.  As I said, dpm is outputting fine but not when used with `ddebug_backtrace()`.


Get the node ID from the "node/add" menu item and hook_form_alter()

Question: I want to set a unique 7-digit code to a custom content type and display it in a disabled textfield when a node is created. I created a CCK textfield and set it to disabled in hook_form_alter, great.
I think that a good way to make this unique ID is just to use the node id and fill it out to the required length (eg. 0000012). It doesn't look like $nid is available at the node/add form though. How can I set this ID field to default to the $nid? Can I access the hook_form_alter() as the content is created (on form submission)?
Answer: You're right, the nid is not available at this point, it's assigned only after the the node is saved.
The easiest solution is most probably to use hook_node_insert and resave the node after having added the value to the field you have created.
Answer: Implement a field in PHP.
It can keep its own serial counter in a variable, and auto-fill itself with that. You can create formatters for all the different use cases yourself.
Field example code here: http://drupal.org/project/examples
Also I made a UUID field you could hack on: http://drupal.org/sandbox/Mile23/1326218
Answer: Looking at the code of node_save(), which the function used to save a node, the hooks that are invoked after drupal_write_record(), which is the function used to set the node ID, are the following ones (when the node is created):

hook_node_insert()
hook_entity_insert()

// Call the node specific callback (if any). This can be
// node_invoke($node, 'insert') or
// node_invoke($node, 'update').
node_invoke($node, $op);

// Save fields.
$function = "field_attach_$op";
$function('node', $node);

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

Can I access the hook_form_alter() as the content is created (on form submission)?

hook_form_alter() is invoked for a node edit form whenever the node is being created, or the node is being updated. You can add a custom submission handler from hook_form_alter(), which then is able to alter the node being saved.
The hooks I have reported should be sufficient for what you want to do, though.


I want to change language in a select list and whole site changes to selected language(All content)

Question: I want to have four languages Catalan, Spanish , French and English. English language will be default.If i change language to be spanish,i want the whole site to change to spanish or if i change to french the whole site should changed to french.
Example site. I want to know how this would have been done ?
Any help really appreciated :)
Answer: I don't believe you need Internationalization module, core's Locale module will already do the job. It makes content translatable, so yes you need to translate it manually. When you enable Locale and edit a node, the option to enter a translation will appear.
Comment: So i need to manually enter each content for each language. A node in english, correspondingly i need to create three more nodes for same content for other languages. Is that what you meant manually ?
Answer: if i where you i would use google translate for websites its very easy ......go to google webmaster tools choose  google translate for site take add your site domain and generate the code ...then take the first code and put it in the page.tpl.php in the header section
and take the second code and put it after the  directly and at then you should have 52 language on your site all the site is translated to your selected language and you could limit it to any no of languges from the webmaster tool before generate the code  and inject it to your page.tpl.php
Comment: google translate doesn't do the translation properly.


Showing markers on Google Maps (React)

Question: I'm having trouble showing markers on my app.
I am trying to show markers using @react-google-maps/api for each property that a user owns. The map is rendering but markers are not appearing on the map for some reason.
When I console.log(markers) in Map component, it prints values from the markers array correctly.
When I add empty space or any change to the Map component and saves it, the markers show on the map so code itself works but I think it's to do with the timing of the rendering/ the Map receiving the markers list from PropertyPage component. Navigating to other pages also won't fix it. I tried creating state for markers, using useEffect in PropertyPage (causes infinite re-rendering) and useEffect in Map component and map doesn't render at all.
Below are my codes for the PropertyPage and the Map components.
If you could spot any issue, I would very much appreciate it! Thank you in advance!!
/// PropertyPage
import React from 'react'
import PropertyCard from './PropertyCard'
import RingLoader from 'react-spinners/RingLoader';
import Map from './Map';
import { Grid, Button, Image } from 'semantic-ui-react'
import { Link } from 'react-router-dom';
import { useLoadScript } from '@react-google-maps/api'
import { getGeocode, getLatLng } from 'use-places-autocomplete';
import { useGetPropertiesQuery } from '../../app/services/propertiesAPI'

const libraries = ['places']

const PropertyPage = () => {
    const { data: properties = [], isLoading, isError, error, isSuccess } = useGetPropertiesQuery()
    const { isLoaded } = useLoadScript({
        googleMapsApiKey: process.env.REACT_APP_GOOGLEMAPS_KEY,
        libraries,
    });
    let markers = [];

    if (!isLoaded) {
        return
Map is loading...

    }

    let content

    const generateLatLng = async (address) => {
        try {
            const results = await getGeocode({ address });
            if (results.length === 0) {
             return;
            } else {
                const { lat, lng } = await getLatLng(results[0]);
                if (lat && lng) {
                    markers.push({ lat, lng });
                }
            }
        } catch (error) {
            console.error('Error while generating lat and lng:', error);
        }
    };

    if (isLoading) {
        content =
Loading...

    } else if (isError) {
        content =
{error.toString()}

    }

    if (isSuccess && properties.length > 0) {
            content = properties.map((property) => <PropertyCard key={property.id} property={property}/>)
            properties.map(property => generateLatLng(property.address))
    }

    const noPropertiesYetMessage = (

You have no properties yet.

            <Button as={Link} to='/properties/add-new'>
                Add More
            </Button>

            <Image fluid style={{ width: '100%', height: '100%', objectFit: 'cover' }} src='https://www.bhg.com/thmb/TXKtfIyA_UUCOWtMsLXetN5Wvb8=/1493x0/filters:no_upscale():strip_icc()/gray-exterior-white-trim-path-09767f9e-83bad323e9d2473b90e69add9165c12f.jpg' alt='building entrance'/>

    )

    return (

            <RingLoader color={'#F5A623'} loading={isLoading} />

                { properties && properties.length > 0 ?
                <Grid Columns={3}>
                    <Grid.Column width={2}>
                    <Button as={Link} to='/properties/add-new' style={{ marginTop: '10px' }}>
                        Add More
                    </Button>
                    <Image src='https://wdy.h-cdn.co/assets/16/05/480x480/square-1454612525-baby-pandas.jpg' size='tiny' circular style={{ marginTop: '10px' }}/>
                    </Grid.Column>
                    { content }
                </Grid> : (noPropertiesYetMessage)}
                <Grid.Row style={{width: '100vw', height: '100vh', paddingTop: '15px'}}>
                    <Map markers={markers}/>
                </Grid.Row>

    )
}

export default PropertyPage

/// Map component
import { GoogleMap, Marker } from '@react-google-maps/api';

const Map = ({ markers }) => {
    return (
        <GoogleMap zoom={10} center={{lat: 47.6062, lng: -122.3321}} mapContainerStyle={{ width: '80%', height: '80%' }}>
            {markers.map(marker => (
            <Marker key={marker.lat + marker.lng} position={marker}/>)
            )}
        </GoogleMap>

    );

};

export default Map

Answer: I was able to figure this out. Instead of converting address to latitude and longitude every time the page renders, I convert when the property instance is created/updated and save the latitude and longitude values in properties tables. That way, when the property page is rendered, I just need to get those values from the properties data like other variables and it solved the issue of non-rendering when using variable/ infinite re-rendering when using state. I hope this helps!!

Showing markers on Google Maps (React)


Progress Bar with process

Question: When i click my command button it takes a few seconds to complete the process which could make the end users think the program is lagging, then i thought of the progress bar. so how can make the progress bar work while the process is running so that the users will not think that the program is lagging, i'm new to vb.net, i research quiet some time now and still can't get how it works nor how will i start.
thanks for the help in advance
this is my command button process.
        Private Sub LoginBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoginBTN.Click
    Using ClientDashboardx As New ClientDashboard
        Try

            cn = New ADODB.Connection
            conDB()
            cn.Open()

            rs = New ADODB.Recordset
            rs.Open("SELECT * FROM tb_registration", cn, 0, 3)

            If txtuserid.Text = "" Or txtuserpass.Text = "" Then
                MsgBox("Value Null")
                Exit Sub
            Else
                Do While Not rs.EOF
                    Dim strLogin = txtin.Text
                    Dim strLogout = txtout.Text
                    If rs("st_acc_number").Value = txtuserid.Text And rs("st_password").Value = txtuserpass.Text And rs("st_log").Value = strLogin Then
                        MsgBox("Account in use")
                        Exit Sub
                    ElseIf rs("st_acc_number").Value = txtuserid.Text And rs("st_password").Value = txtuserpass.Text And rs("st_log").Value = strLogout Then
                        Dim strID = rs("st_acc_number").Value
                        Dim strUserName = rs("st_fname").Value & " " & rs("st_lname").Value
                        Dim strTotalTime = rs("st_totaltimeleft").Value
                        rs.Close()
                        SaveAccNumber.Text = strID
                        SaveUserName.Text = strUserName
                        SaveTotalTime.Text = strTotalTime

                        cn.BeginTrans()
                        cn.Execute("UPDATE tb_registration SET st_log='in' where st_acc_number='" & SaveAccNumber.Text & "'")
                        cn.CommitTrans()
                        cn.Close()

                        ClientDashboardx.id_lbl.Text = SaveAccNumber.Text
                        ClientDashboardx.iduser_lbl.Text = SaveUserName.Text
                        ClientDashboardx.UserTotalTime.Text = SaveTotalTime.Text
                        ClientDashboardx.AutoUpdate_Button.Enabled = True
                        Me.Hide()
                        ClientDashboardx.ShowDialog()
                        Me.Show()
                        Exit Sub
                    Else
                        rs.MoveNext()
                    End If
                Loop
                MsgBox("User/Pass Mismatch")
                Exit Sub
            End If
        Catch ex As Exception
            MsgBox("Server Offline", MsgBoxStyle.Critical, "")
        End Try
    End Using
End Sub

Answer: You should perform your long running process in a separate thread or background worker.
Here is how to use the background worker:
Add a BackgroundWorker and ProgressBar to your Form
Add a private variable to hold your result
Private _success As Boolean

Add code to show the ProgressBar and Start the worker in Form_Load
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    _success = False
    ProgressBar1.Style = ProgressBarStyle.Marquee
    ProgressBar1.Visible = True
    BackgroundWorker1.RunWorkerAsync()
End Sub

Perform your long running operation here
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    'perform your db access here and set the result in _success
End Sub

When the worker has finished hide the progress bar and depending on the result perform some action
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    ProgressBar1.Visible = False
    If _success Then
        Me.Hide()
        ClientDashboardx.ShowDialog()
        Me.Show()
    Else
        MsgBox("User/Pass Mismatch")
    End If
End Sub

Comment: Thank you so much, a straight forward guide. this will save me so much time. cheers
Comment: I Have encountered an error, here

            SaveAccNumber.Text = strID
            SaveUserName.Text = strUserName
            SaveTotalTime.Text = strTotalTime

This is the error "Cross-thread operation not valid: Control 'Client' accessed from a thread other than the thread it was created on." what should I do? this is the first time I saw an error like this.
Comment: You can't set the Text values of TextBoxes inside a background worker without using a delegate as it runs on a different thread (hence the error). Set values in variables and then use these variables to populate the textboxes in the RunWorkerCompleted event.
Comment: I've search about the error. and i found this. System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
is this a good code? seemed to work, but BackgroundWorker1_RunWorkerCompleted doesn't seem to work.
so i put me.hide() clientdashboardx.showdialog() me.show in the DoWork. and it work.

Progress Bar with process


How to prove binomial coefficient is asymptotic big theta of two to the power n?

Question: I am stuck at this problem. I think it is equivalent to show 2m choose m is big theta of 4 to the power n, but still find difficult to prove it.

Thanks of @LutzL's suggestion. I thought of stirling's approximation before.
Answer: The O-part should be easy. Choosing exactly n/2 elements out of n is a special case of choosing arbitrary combinations out of n elements, i.e. deciding for each of these n elements whether to choose it or not.
The Ω-part is harder. In fact, plotting 4n / binomial(2 n, n) for moderately large n I see no indication that this would flatten to stay below some constant. Speaking intuitively, the larger n is, the more special is the case when you take a random pick from n elements and coincidentially happen to choose exactly n/2 of them. That probability should tend to zero as n increases, meaning that 2n should always grow faster than n choose n/2. Are you certain you understood this part of your task correctly?
Comment: Per Stirling formula, one can see that `binom{2n}{n}=Theta(4^n/sqrt(n))`. The square root factor makes the requested lower bound impossible. As you can test via WA http://www.wolframalpha.com/input/?i=plot+4^n+%2F+sqrt%28n%29+%2F+binomial%282*n,+n%29+for+n+from+0+to+1000
Comment: Thanks for your opinion. To be honest, I am not sure the lower bound of 2^n is correct. Is there a lower bound that you can think of ?
Comment: But I saw the bound of 2m choose m, which seems to have higher and lower bound of constant times 4^n.
Answer: It's not -- it's Theta(2^n/sqrt(n)), and in fact choose(n, n/2) ~ 2^n/sqrt(pi * (n/2)) as n->infinity). See https://en.wikipedia.org/wiki/Central_binomial_coefficient
Answer: You could use Stirlings formula for the factorials.
n! = sqrt(2*pi*(n+theta)) * (n/e)^n

where theta is between 0 and 1, with a strong tendency towards 0.
Comment: @xxx_yyyy Note that this is *equality*.  So `theta == 0` is a lower bound, and `theta == 1` is an upper bound.
Comment: You can not prove the lower bound since it is wrong. As you already found out, it has to be in terms of `2^n/sqrt(n)`.
Comment: Thanks, but with Stirling's formula, I still can not prove the lower bound. Any  suggestion?


Property setters for compound assignment?

Question: Consider the following simple example class, which has a property that exposes a modified version of some internal data when called:
class Foo(object):
    def __init__(self, value, offset=0):
        self._value = value
        self.offset = offset

    @property
    def value(self):
        return self._value + self.offset

    @value.setter
    def value(self, value):
        self._value = value
The value.setter works fine for regular assignment, but of course breaks down for compound assignment:
>>> x = Foo(3, 2)
>>> x.value
5
>>> x.value = 2
>>> x.value
4
>>> x.value += 5
>>> x.value
11
The desired behavior is that x.value += 5 should be equivalent to x.value = x._value + 5, as opposed to x.value = x.value + 5. Is there any way to achieve this (with the property interface) purely within the Foo class?
Comment: I recommend against adding magical numeric behavior from the beginning to a property, otherwise you break symmetry – as you've noticed – with the standard mathematical operators. Defining `offsetValue()` makes the intention far more obvious to the reader; in particular, should `x.value += 5` add to `_value` or `offset`?
Comment: I tried something with `if 'INPLACE_ADD' in [dis.opname[ord(op)] for op in inspect.stack()[1][0].f_code.co_code]:` before realizing that the `setter` behavior overall is flawed. I'd been working with it so long it didn't occur to me to just revisit that.
Comment: It seems to work ok without that offset.  I agree with ezod that it is doing something odd attempting to assign the results of the add to the computed property.  With the offset it gives unexpected results.  Without it it doesn't.  Hmm.
Answer: @ezod, there is no direct way to do what you're asking for, even with the descriptors protocol.
That kind behaviour of value property totally breaks the semantics of += operator.
Comment: I'm not sure I understand. How does it break `+=` semantics? Externally, it would work exactly as expected. The "offset" functionality (which is trivial in this example but rather involved in my actual application) is hidden from the user, but the user should still be able to intuitively access and modify the exposed value using all the functionality of its class (including `__iadd__`) without these weird effects.
Comment: On further reflection I think I see what you mean -- `x += y` should equate to `x = x + y`, which is not true in my case. Fair enough.
Comment: Consider this: y = x.value; x.value += 5; y += 5; At this point, a programmer expects that x == y.
Answer: Override the __iadd__ magic method.
You need to do that because += means "take the value and add five, then set that as the result". If you want it to know that the value isn't really the value, you need to change the semantics of the += operator.
Comment: Overriding `__iadd__` in `Foo` will not work, as I am not adding to `Foo`, I am adding to its member. Even if I have access to the class of `value` and there is no polymorphism, it has no knowledge of `Foo` internals, so I can't override `__iadd__` there either.
Comment: `__iadd__` is also only called on mutable types, otherwise `__add__` is called. Also, try writing semantics by which this works, by sublcassing the value passed -- you'll end up recursing no matter what you do.
Answer: I was confronted with the same problem and solved it with the following method:
class Foo(object):
    def __init__(self):
        self._y = 0

    @property
    def y(self):
        return self._y + 5

    @y.setter
    def y(self, value):
        value -= 5
        self._y = value

>>> f = Foo()
>>> f.y
5
>>> f.y += 1
>>> f._y
1
>>> f.y
6

Could this be a solution? Have I overlooked something?
Answer:
The desired behavior is that x.value += 5 should be equivalent to
  x.value = x._value + 5

Why should Python know how you property is implemented (i.e. that setter assigns its value exactly to _x)?
Protocol of property gives you a possibility assign different actions (get, set, delete) to one name.  And this protocol doesn't care about a way of implementation of these actions.
So it would be quite confusable if Python make some assumptions about your code and try to modify strait forward code logic.
Comment: I'm not suggesting that Python should know this. More along the lines of `setter` being able to introspect how it was called (i.e. via `=`, `+=`, etc.) and behave accordingly.


How Do We Find Points On A Circle Equidistant from each other?

Question: I'm a programmer and I saw this question on stackoverflow which exactly does my job:
https://stackoverflow.com/questions/13608186/trying-to-plot-coordinates-around-the-edge-of-a-circle.
In this, the answer says that:
var items = 10; // say there are 10 points to be plotted.
var x0 = 40;
var y0 = 40;

// Remember top left pixel of computer screen is (0,0) and both axis go positive from left to right and top to bottom.

for(var i = 0; i < items; i++) {
    var x = x0 + r * Math.cos(2 * Math.PI * i / items); // WHAT IS HAPPENING HERE?
    var y = y0 + r * Math.sin(2 * Math.PI * i / items); // WHAT IS HAPPENING HERE?
}

I'm just undone about the code above. How is that happening. Why are we adding the x0 and y0 (coordinates of center of circle). How does it gives us exact points exactly equidistant from each other? Please explain how this math is working.
For e.g., the above code gives us like this:

That's what I want to do. The points generated is the variable items.
Comment: I am of reminded of $N^{th}$ roots of unity.  That is, for a circle centered at the origin and unit radius, the $N^{th}$ roots of unity are equally spaced around the *unit circle*.
Comment: Could you please explain it in a better way? Check the edit I posted @Integrator
Comment: For circles centred at (0,0), (rcosθ, rsinθ), represents a point on the circle subtending an angle θ at the origin with the +ve x-axis.
Comment: Since the centre of the circle in your case is off-centre, we add the +ve offset to the centres of thee circle.
Answer: I am reminded of $N^{th}$ roots of unity.  That is, for a circle centered at the origin and unit radius, the $N^{th}$ roots of unity are equally spaced around the unit circle.
Answer: for(var i = 0; i < items; i++){
var x = x0 + r * Math.cos(2 * Math.PI * i / items);
var y = y0 + r * Math.sin(2 * Math.PI * i / items);}

The equations translated:
$$x(n)=x(0)+r\cos\left(2\pi\frac{n}{N}\right)\\
y(n)=y(0)+r\sin\left(2\pi\frac{n}{N}\right)\\$$
Remember points on a circle with centre at $x_0,y_0$ with radius $r$ at an angle $\theta$ are:
$$(x,y)\equiv(x_0+r\cos\theta,y_0+r\sin\theta)$$
The $360^\circ\equiv2\pi$ radians has been divided into $N$ parts and thus the angle between two adjacent points will be $2\pi/N$, I hope you can understand the rest.
Comment: Is there any kind of name for these equations?


Callback method after a new object is initialized but not after find

Question: I have a Secret model that has attribute token. I need to generate this token after the object is initialized for the first time, i.e., after Secret.new, but not after Secret.find
I couldn't find any callback that fits my purpose. It seems that after_initialize excluding after_find would have work.
How should I deal with this situation? Am I doing something smelly that Rails wasn't prepared for?
Answer: In the after_initialize callback you could check to see if the record is new or not via secret.new_record?  Then, only generate your token for new records.


JSF2.0 internationalization not working on server

Question: I am using JSF 2.0 and Spring 3.0.2 and tomcat 22.214.171.124 as server. I have an issue with changing language of my site. All the codes are working well in my local server. But when I deploy on server, Language changes does not effect. Its automatically select Italy as a default language. when I click on another language,nothing is changes.
Here is my bean code:
<code>            @ManagedBean(name="language")
           @SessionScoped
          public class LanguageBean implements Serializable{

private static final long serialVersionUID = 1L;

private String localeCode;

private static Map<String,Object> countries;
    static{
    countries = new LinkedHashMap<String,Object>();
    countries.put("English", Locale.ENGLISH); //label, value

            countries.put("Italian", Locale.ITALIAN);
}

public LanguageBean() {
    countries = new LinkedHashMap<String,Object>();

            countries.put("English", Locale.ENGLISH); //label, value
            countries.put("Italian", Locale.ITALIAN);

}

public Map<String, Object> getCountriesInMap() {
    return countries;
}

public String getLocaleCode() {
    return localeCode;
}

public void setLocaleCode(String localeCode) {
    this.localeCode = localeCode;
}

    public void countryLocaleCodeChanged(ValueChangeEvent e){

    String newLocaleValue = e.getNewValue().toString();

    for (Map.Entry<String, Object> entry : countries.entrySet()) {
            System.out.println("newLocaleValue "+newLocaleValue+"\n entry.getValue().toString()"+entry.getValue().toString());
        if(entry.getValue().toString().equals(newLocaleValue)){

            FacesContext.getCurrentInstance()
                .getViewRoot().setLocale((Locale)entry.getValue());
                    FacesContext context = FacesContext.getCurrentInstance();
                    System.out.println("Default : "+context.getApplication().getDefaultLocale());

                    context.getApplication().setDefaultLocale((Locale)entry.getValue());

        }
    }

}
</code>
And this is the config.xml::
<code>    <locale-config>
        <default-locale>en</default-locale>
    </locale-config>
    <resource-bundle>
        <base-name>com.mad_u.welcome</base-name>
        <var>msg</var>
    </resource-bundle>
</code>
Please give me some idea. Thanks in advance.
Comment: this [thread1](http://stackoverflow.com/questions/4830588/jsf-locale-is-set-per-request-not-for-session), [thread2](http://www.coderanch.com/t/447920/JSF/java/JSF-Locale) will help you.
Answer: I had the same problem. My properties files were like this:

message_en_US.properties
message_es_ES.properties
message_eu_ES.properties

It was working in my local server but uploading the web to my server the language change didn't work, so I changed this:
<code>        countries.put("Castellano", new Locale("es"));
        countries.put("Euskara", new Locale("eu"));
        countries.put("English", new Locale("en"));

<locale-config>
            <default-locale>es</default-locale>
            <supported-locale>es</supported-locale>
            <supported-locale>eu</supported-locale>
            <supported-locale>en</supported-locale>
        </locale-config>
</code>
and

message_en.properties
message_es.properties
message_eu.properties


$V=V_1\cap...\cap V_n$ neighbourhood of a point?

Question:
Theorem: Let $n\in\mathbb{N}$ and $(Y,d_1),...,(Y,d_n)$metric spaces. Consider in $Y=(Y_1\times Y_n)$ one of the product metric $\delta_j(j=1,2,\infty)$.
Let $(X,d)$ be another metric space. An application
$f:(X,d)\to(Y,\delta_j),x\to(f_1(x),...,f_n(x))$
is continuous in a point $a=(a_1,...,a_n)\in X$ if and only if each $i\in\{1,...,n\}$ a function $f_i:(X_i,d_i)\to Y,x\to f_i(x)$ is continuous in $a_i$.

Proof: As the product metrics $\delta_1,\delta_2$ and $\delta_\infty$ are equivalent, it suffices to show that the proposition holds in the metric $\delta_\infty$.
Let $B$ be a open of $(Y,\delta_{\infty})$. Suppose that each of the functions $f_i$ is is continuous in $a$. Let $V_i$ be an neighbourhood of $f_i(a)$ on $Y_i$. So $V=V_1\cap...\cap V_n$ is a neighbourhood of $f(a)$ in $X$. As $f^{-1}(V)=f^{-1}(V_1)\cap...\cap f^{-1}(V_n)$ and $f^{-1}_i(V_i)$ is the neighbourhood of $a$, therefore $f^{-1}(V)$ is in the neighbourhood of $a$. So, $f$ is continuous in $a$.
Notes: Metrics:$\delta_1=\sum_\limits{i=1}^{n}d_i(x_i,y_i),\:\:\:\delta_2=(\sum_\limits{i=1}^{n}(d_i(x_i,y_i))^2)^{\frac{1}{2}}\:\:\:,\delta_\infty=\max\{d_i(x_i,y_i):1\leqslant j\leqslant n\}$
Questions:
I am not understanding certain anspects of this proof:
1) Why does the author writes $V=V_1\cap...\cap V_n$ as the neighbourhood of $f(a)$? If we think on $\mathbb{R}^3$ the neighbourhood of each axis does not intersect with neigborhood on the other axis given a point on $\mathbb{R}^3$
Did not the author mean instead $V=V_1\cup...\cup V_n$?
2) The author writes "$f^{-1}(V)=f^{-1}(V_1)\cap...\cap f^{-1}(V_n)$". Did he not mean instead $f^{-1}(V)=f_1^{-1}(V_1)\cap...\cap f_n^{-1}(V_n)$?
Thanks in advance!
Answer: I think the biggest confusion here comes from the fact that the author writes the $V_i$ as elements of the topology of $Y$ without saying how this is done. (I guess he writes about it earlier). But when constructing the product topology you take the projections $\pi_i: Y \to Y_i$ and look at the inverse images of open sets as a basis of the topology. Therefore $V_i$ in $Y$ is the preimage of the set $V_i \subset Y_i$ under $\pi_i$, so it is $(Y_1,\dots,V_i,\dots,Y_n)$. Thats why you take the intersection of all these neighbourhoods to get another one.
This should (hopefully) answer both of your questions.


Collect Map.Entry first value into map

Question: I have following map :
private static Map<String, String[]> createMap(){
    Map<String, String[]> map = new HashMap<>();
    map.put("A", new String[]{null});
    map.put("B", new String[]{"Banana"});
    map.put("C", new String[]{""});
    map.put("D", new String[]{"Duck"});
    return map;
}

I want to convert this map into Map<String, String>
Needed Output :

Key :B Value : Banana
Key :D Value : Duck

I want to do this using Java 8 Stream APIs and and one of the solution that I tried is
final Map<String, String[]> collect = createMap().entrySet().stream()
        .filter(e -> e.getValue()[0] != null && !"".equals(e.getValue()[0]))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

collect.forEach((key, value) -> System.out.println("Key :" + key + " Value :" + Arrays.toString(value)));

But this is giving me Map<String, String[]> and output is

Key :B Value :[Banana]
Key :D Value :[Duck]

How can I tell Collector to only extract the first value from Map.Entry values ?
Comment: how about an input `"A", new String[]{null, "Apple"}`? Is this possible? If yes, what is the expected output?
Comment: As only first element should be considered, this input should be skipped.
Answer: You can do:
map.entrySet().stream()
          .filter(entry -> Stream.of(entry.getValue()[0])
                                .anyMatch(s -> s != null && !s.isEmpty()))
          .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue()[0]))

by your code:
Map<String, String> collect = map.entrySet().stream()
            .filter(e -> e.getValue()[0] != null && !e.getValue()[0].isEmpty())
            .collect(Collectors.toMap(Map.Entry::getKey, entry->entry.getValue()[0]));

Comment: I don't see the advantage of turning the test for the first array element into an `allMatch` that would test other unrelated elements when there are some. But turning `"".equals(e.getValue()[0])` into `e.getValue()[0].isEmpty()` is a good idea.
Comment: @Holger, You are right, OP solution with the changes that you pointed out is better.

Collect Map.Entry first value into map


How to create such an element in Flutter?

Question: I want to create such an element. But I'm still new to flutter. Can there be something similar?
I need the button and the text box (I don't know what it's called) to have States depending on which it changed color and the plus button turned on and off. The text changes in the first and second text boxes so they should stretch.
*The button and text box still need to be moved to the right side
Answer: here is a working code, you can further change size and colors to satisfy your requirements
<code>class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _numberCounter = 0;
  var _clickCounter = 0;
  var _changeColor = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Material(
            elevation: 6.0,
            child: Row(children: <Widget>[
              Container(
                padding: EdgeInsets.all(8),
                child: Text(
                  '$_numberCounter',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 20.0),
                ),
              ),
              Container(
                color: _changeColor ? Colors.green : Colors.grey,
                padding: const EdgeInsets.all(8.0),
                child: GestureDetector(
                    onTap: () => setState(() {
                          _changeColor = !_changeColor;
                          _numberCounter++;
                          _clickCounter++;
                        }),
                    child: Icon(Icons.add), color: Colors.white),
              ),
              Expanded(
                child: Text(
                  '$_clickCounter per click',
                  style: TextStyle(fontSize: 20.0),
                  textAlign: TextAlign.center,
                ),
              )
            ]),
          ),
        ),
      ),
    );
  }
}
</code>
Comment: 2 days of torment with this fairly simple thing. Thank you very much you really helped me out! God grant you all the best, if you are of course a believer, and if not, I just wish you all the best ;)


iOS adding huge number of products through In-App Purchase

Question: I'm working on in iphone application for my company, they want to sell huge number of products using in-app-purchase ...
but the problem is to use iap we have to add for each product a record on app store contains meta data and its price about this product, and as I said before we have huge data.
So what I'm thinking about is to add a number of virtual products each one with a different tier price and when a user buy a product form my store I map this product with one of the virtual product on app store (depending on the price tier) and I send an identifier through SKMutableProduct.requestData and receive it with the transaction to know which product the user has bought.
In this way if I have millions of products with 5 tires price I can add just 5 products to app store, But I don't if apple will accept that ... is that regular ? what do you think ?
if not what can I do with huge number of products?
Answer: Application Loader provides the ability to bulk upload IAP product information from a flat file.
Go to iTunes Connect->Manage Your Applications, then scroll to the bottom and download the app loader (if you haven't already) and select "View Guide".    You'll want to look at the "Creating a Package from a File" section.
Answer: No that isn't regular and Apple would not allow this. It's important to have an entry per product in iTunes Connect. The way you are proposing would not work if the user restored purchases.
Also the nature of non consumable products is that they are purchased once and forever owned, this would not work with how you are suggesting because you can't purchases a non consumable twice.
Answer: With the Application Loader on OS X and a CSV upload in the Google Play Developer console you have the possibility to upload multiple In-App-Pruchasing-Products in one go. To streamline the process I made a small tool that helps you generate these files. If you need more customizing it is also be a good starting point to teach you all the ins and outs.
You can check the whole thing out here: http://niklausgerber.typed.com/blog/an-easy-way-to-generate-batch-upload-files-for-in-app-purchase-items-for-itunes-connect-and-google-play-developer-console


Pass data from a hook to (be used in another hook)

Question: So in a hook hook_commerce_cart_order_refresh() I make some calculations that I would later like to use in a different hook hook_form_alter, how can I pass these data/object and use later on?
In that first hook, I have a EntityMetadataWrapper but it seems I can only give it data that actually is persisted, and mine should only exist for the request.
Again, I could use $_SESSION but that storage is used for persistent storage through multiple requests. And I'm not looking for that.
Any suggestions?
Comment: the above is a slight variation, same answer as @Clive, except Clive created a function to retrieve the drupal static stuff.
Answer: You can't, there's no mechanism to pass data from one arbitrary function to another (which is what two separate hooks essentially are). You'll have to make the data available another way.
Drupal uses a pattern like this all over the place:
function MYMODULE_get_data() {
  $data = &drupal_static(__FUNCTION__, NULL);

  if (!$data) {
    $data = some_function_to_build_data();
  }

  return $data;
}

function MYMODULE_commerce_cart_order_refresh(...) {
  // Get the data, populating it if it doesn't already exist.
  $data = MYMODULE_get_data();
}

function MYMODULE_form_alter(...) {
  // Retrieve the data.
  $data = MYMODULE_get_data();
}

That's a contrived example, it'll make more sense when you plug your own requirements into it.
Comment: `drupal_static()` is the first thing I can think of as well....


Adding READ_PHONE_STATE permission to AndroidManifest.xml is not enough to permit the call of a getprop function

Question: I was trying to add a segment to my Android application, which would gather information about the device (like the serial number for example) and use it for digital signing of data, later on.
I was planning on using the output of the getprop function, paired with adequate parameters, for instance getprop ro.serialno.
Googling this issue had me on a path of enabling proper permissions, for this to work.
I am having issues with enabling the READ_PHONE_STATE permission on my device. Adding it to the AndroidManifest.xml file does absolutely nothing. After I reused an already working piece of code to request the user's permission after launching, my app started crashing.
App crashes with:
    --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.strujomeri, PID: 17563
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.strujomeri/com.strujomeri.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

All permissions from AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Code that requests permission. Works for other permission but only crashes here:
ActivityCompat.requestPermissions(MainActivity.this,
        new String[]{Manifest.permission.READ_PHONE_STATE},
        STATE_REQUEST);

if (requestCode == STATE_REQUEST) {
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "State request granted", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "State request granted", Toast.LENGTH_SHORT).show();
    }
}

EDIT: This is the error message I get when trying to read the serial number of the phone:
E/libc: Access denied finding property "ro.serialno"

Any ideas on how to get this type of information ? Other methods besides getprop can be useful as well. Thank you
I was looking to enable the READ_PHONE_STATE permission on my Android device, which I need for executing some system calls in my code, but I am experiencing a blockade in enabling this permission and suspect that there is theory underneath this issue which I don't already know.
Answer: seem you are edited your code before show here.
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

Problem cause is your permission array.
To easy check permission :
    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    // Forward results to EasyPermissions
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}

@AfterPermissionGranted(RC_PHONE)
private void methodRequiresTwoPermission() {
String[] perms = {Manifest.permission.READ_PHONE_STATE , Any more permission in your manifest};
if (EasyPermissions.hasPermissions(this, perms)) {
    // Already have permission, do the thing
    // ...
} else {
    // Do not have permissions, request
}
}

if you don't want the lib above
prive boolean checkPermission(String [] perms){
for(String perm : perms){
    if(ActivityCompat.checkSelfPermission(getApplicationContext(),perm) !=PackageManager.PERMISSION_GRANTED){
        return false;
    }
}
return true;

}
-use
if (!checkPerms(new String[]{
         // //your permissions in manifest

    })){
        requestPermissions(new String[]{
             //your permissions in manifest

        }, REQUEST_CODE);
    }

Comment: Sorry but no, I did not edit my code before pasting, it's exactly from the terminal.
Your solution did eliminate the crash, but I still did not get the READ_PHONE_STATE permission approved. This is the error I get when I try to read the serial number:

E/libc: Access denied finding property "ro.serialno"
Comment: So if you're using Samsung device there is a certain bug with them. This is worth to be tried [link](https://stackoverflow.com/a/44138687/5648093)


Improving Unextended Chords

Question: As a jazz-head piano/electronic composer, I tend to end up stacking huge amounts of extensions on my chords. Whenever I use standard non-extended triads they sound sorta empty and boring, but sometimes I end up using so many extra notes that my chords become more a wall of sound than a harmonic progression.
What I'm asking is, how do I get more "oomph" out of standard triads and make them feel "fuller"?
Answer: Well, if we can't add extra notes, we still have some options.
The biggest potential change is the voicing of the chords. Some will sound small and thin, and others will sound large and resonant. To my ears, big open fifths can fall into the latter category. I'd recommend sitting down in front of a piano/keyboard, and experimenting. Don't add any extensions! Another option is to study sheet music for more voicing ideas. Another word to look out for here is inversion. Different inversions are basically different voicings of the chord.
On a related subject, the range in which you play the chord will have a big impact. Low octaves are great for imparting power, but they're easy to overuse. Experiment here as well.
It's also worth saying that sometimes less is more. I know it's a cliche, but there's a reason for that. If you're always playing loads of notes, you'll tire your listeners, and they will lose their impact. You do not have to play lots of notes and complicated harmonies to make good music. For me, it takes conscious effort to play less, but I'm almost always happier with the results.
If you feel like cheating a little, seconds (or ninths) are wonderful things. You can sneak them into all sorts of basic triads without anybody getting too upset. Minor sevenths can also be slipped in here and there. Sure, they are extensions, but they're certainly not jazzy.
Moving further into this territory, you could also experiment with different bass notes. A common technique to build tension is to use a constant bass note under moving chords. For example, there's a song I play that has the following bridge progression: G F G Dm7 G F G F. Nothing special. On the second repeat, I play G F/G G Dm7/G G F/G G F. The resolution of tension created by the final F and subsequent chorus chord (C, the tonic) makes this second repeat sound much bigger.
Comment: I suppose this is a particular type of voicing, but I instantly thought of inversions. You might add that idea to the section about voicings, which overall is the best answer. +1
Answer: I would recommend looking into guitar approaches a bit, as well as some voice leading.
When guitar players play triads, they are usually hitting the same note a few times, such as an E major in open position: EBEG#BE.  Three Es in there and two Bs.  Focusing on doubling the root and fifth of the chord brings a lot of depth and support to the "smaller" sound that a triad has compared to one with Jazzy extensions and alterations.  Lots of Rock music uses Power Chords (Root, 5, octave) and a lot of distortion, which makes the chords very thick.  This of course leaves out the major/minor aspect but it is typically easily determined in the context of all of the chords taken together, included in the melody, or just plain not necessary for the style.
Voice leading can also be very important, depending on what you're going for.  The idea of voice leading comes from the concept of Counterpoint, which is the idea of having different Lines or Voices all playing their own part, with the goal of maintaining independence for each part.  Basic voice leading includes not using parallel fifths or octaves from chord to chord, eg, if you're going from G to D, you wouldn't want to have two voices playing the note G and both move up to the note A.  Parallel fifths and octaves basically destroy the independence of the voices, so if you have a four part harmony and have parallel fifths between two chords, it will sound like you've lost a voice when you arrive at the second chord.  I'm not 100% sure but I believe this has to do with overtones.  Since fifths and octaves are the first two overtones, they are very closely related, so it's easy for the higher voice to "disappear" into the lower voice because it blends in and sounds like it's just an overtone.  Using Contrapuntal voice leading can allow you to have fuller sounding harmonies by maintaining this voice independence.  It's important to note the difference between parallel octaves and doubling.  If you listen to orchestral works, you will very often hear instruments doubling each other in octaves, which would not be breaking these "rules".  The idea is that those two instruments are actually playing the same voice and just adding texture and depth to the harmony, so they're not actually supposed to have the independence that the "rules" are meant to maintain.
These voice leading approaches often lead to solutions that involve inversions and, as others have mentioned, inversions can bring a lot of texture to your chords, sometimes feeling like they've completely changed to another chord.  In my experience as a bass player, it can be touchy to use inversions sometimes and it's easy to over use them.  It took me a little while to "mature" and understand that there are times that inversions are just not appropriate for the style of music I'm playing, whatever that style may be at the time.
You can also look at some guitar stuff to see patterns of voice leading embedded.  You would be looking for songs that have mostly open chord voicings.  A lot of progressions that use the standard open voicings follow pretty good voice leading rules and lead to fuller sounding harmonies.
As others have mentioned, exploring range is also valuable.  Having strong bass notes adds a lot of depth to your harmony.  It's also worth mentioning that the further apart your voices are, the less they sound as though they are working together.  The Classical approach within a four part harmony is to have no more than two octaves between your bass and soprano voices (lowest and highest voices).  This shouldn't be considered a rule by any stretch but working out parts within a couple octaves of each other may help you hear the cohesiveness that it can offer.  From there, you can basically move things up and down and further apart as you wish and hear how it impacts the cohesiveness and stability of your harmony.  Rock music is often using the bass player to double the root of each chord an octave below the guitar which adds a lot of depth, so that can help a lot as well.
There's also a lot to be said for context and texture change.  We often hear pieces that include a smaller sounding arrangement for an introduction, then the next section will include a larger arrangement, such as guitar only intro/verse with band entering at the first chorus.  This can make the larger arrangement sound bigger than it actually is because of where it is coming from.  I've used a similar tool in my writing where I will play all of my bass notes an octave up from what you might expect a bass player to be doing, then toward the end of the song at some critical juncture, I'll drop down that octave and everything sounds huge for that important part of the song, furthering the climax.
There are certainly a lot of possibilities as to what may help you achieve your goals here, so it's definitely a good idea to try a lot of them.  I also recommend finding some songs to learn that are mostly triadic and try to determine what it is about their approach that works better than what you've been able to do up to now.
Answer: It may be obvious to you but it might be worth remembering that triads don't have to be your "basic unit" of arrangement - you can write music that never plays two notes together at the same time and still has a full sense of harmonic progression. Then there's the 'bassline + melody' model, which is full of options, or playing dyads (two notes) instead of triads.
You might think it odd to suggest playing fewer notes if you want a fuller sound, but often more open arrangements give you more room for interesting dissonances and can be very 'nimble' - you can change the whole harmony with just one note. They also mean that when you do throw in a triad, it will sound full in comparison!
When it comes to actual triads, endorph has mentioned them but they're so good I'll say it again : the sus2 chord as a colour in its own right (not as an actual suspension) is very useful and is an important part of pop music vocabulary. It also works well as a base for further extension.
'less is more' can also work when thinking about extensions - you don't have to play all those extra notes at once! When playing in C minor, I might hit a little not cluster of C, D, and E♭ - I'm sort of thinking of it as a Cm9 (no 5 no 7) but playing it as something much simpler. So if you really want to play triads, playing triads that are reductions of extensions can work. You could think of the sus2 chord is an inversion of a 9 (no 3 no 7) chord.
Finally, if you're an electronic composer, you presumably play synths sometimes and you know how a single, steady note on an analogue synth with interesting filter modulation can be a harmonic adventure in its own right; try playing three notes in different octaves with a PWM sound and filter resonance just breaking ito oscillation, then sweep the keytrack - I think your neighbours will agree you can get quite a full sound with just three notes :)
Comment: I've definitely seen plenty of times where pop notation doesn't align with most other theory but I've also seen plenty of times where Classical and Jazz disagree with each other, which are arguably the most academically formalized sets of theory.  A friend of mine has been putting out some youtube videos to teach piano/theory and I was just watching his on sus chords yesterday and it was more in line with topo's answer.  It's kind of like how a Gsus would not include a suspension that's intended to be resolved, it's just a type of chord whose name disagrees with its use.
Comment: Would that sus2 without a suspension be better called 'add2' or 'add9' , as it's a suspension of the 3rd as 'sus', but with 3rd kept as 'add' ?
Comment: @Tim the chord I mean is where the third *isn't* kept - e.g. Csus2 = C, D, G. Is there a better name for it? When I say 'without a suspension' I mean that the second doesn't resolve back to the third.
Comment: That makes sense - without resolution - which normally happens.I don't think there's a separate name for it - unlike the 11th which is similar (sus4 with 3, but also b7). Sounds like it needs a name, as its function is different from a 'normal' sus2. Do we see another question?!
Comment: @Tim could it be more correctly seen as an inversion of *5 (add 9)*? I think I am used to just seeing it notated as 'sus2' in pop transcriptions, but maybe that's my own habit clouding my memory.
Comment: Never seen 5add9, but that would do it - in C - C,G,D. Sometimes the pop stuff takes liberties (sometimes?...), and is somewhat lax, I seem to find.

Improving Unextended Chords


Is it possible to Mock and ignore properties

Question: I'm changing our identity strategy and we're using an ID that is generated before the Entity is written to the database. This change is causing some of our tests to fail due to the way we're mocking some service calls.
TimeLog timeLog = buildTimeLog('123456', mockEmployeeId);
TimeLog mockTimeLog = buildTimeLog('123456', mockEmployeeId);
when(this.timeLogService.save(mockTimeLog)).thenReturn(timeLog);

When the test makes the call to the Controller, the bound entity in the Controller gets a different ID than the mock that is expected because the Entity generates the ID. Whereas before, the database generated the ID so the mocks worked.
If there is a way to tell Mockito to ignore a property in the expectation? That would solve the problem and the test would still be valid. Otherwise, other approaches are welcome.
Answer: You can't tell mockito to ignore a property in an expectation because it's using the java "equals" method... You can define an equals method in TimeLog that igonres ID but I suspect that won't give you what you want. The other approach is, instead of trying to tell mockito what not to verify, define explicitly what it is to verify using a hamcrest matcher. Define a hamcrest matcher which just matches the fields you want to verify i.e. all fields other than ID. So something like:
private class TimeLogMatcher extends TypeSafeMatcher<TimeLog> {
    private final EmployeeId employeeId;

    public TimeLogMatcher(EmployeeId employeeId) {
        this.employeeId = employeeId;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("TimeLog with employeeId=" + employeeId);
    }

    @Override
    public boolean matchesSafely(TimeLog item) {
        return employeeId.equals(item.getEmployeeId());
    }
}

And then instead of calling whatever your "buildTimeLog" method is doing call into the mockito Matchers class like:
TimeLog timeLog = Matchers.argThat(new TimeLogMatcher(mockEmployeeId));

Or alternatively you could always use an Answer object:
when(this.timeLogService.save(any(TimeLog.class)).thenAnswer(new Answer<TimeLog> {
    public TimeLog answer(InvocationOnMock invocation) throws Throwable {
        TimeLog receivedTimeLog = invocation.getArgumentAt(0, TimeLog.class);
        assertThat(receivedTimeLog.getEmployeeId(), equalTo(mockEmployeeId));
        return timeLog;
    }
});

Does that all make sense?
Comment: Makes perfect sense. I had headed down this path but wasn't quite getting there. This helps. Thanks!


Can anyone recommend a current, effective captcha solution?

Question: I have a site with a simple form response. A few months ago I started getting  bogus submissions from Russia -- 4 or 5 a day. I have tried several solution to no avail:

I added reCaptcha, which worked for a few days, then the spam started again (a quick Google search suggested that reCaptcha had been hacked in 2010!).
Next I switched to a simple javascript snippet "What is two plus three?" That too was hacked after a few days.
Then I switched to SecureImage (PHP image captcha). Next day, more spam.
Then I added a "Title" field to my form and hid it with CSS. My form handler (a php script) rejected the form if the title field was filled in (presumably by a bot). Spammed.
Today I modified my javascript to ask different questions. Spammed within the hour.

The logs shows the submissions are coming from different IPs every time. Those with a whois entry are from Russia. Any suggestions how I can deal with this? I'd rather not implement email verification or anything else that might annoy users.
Comment: Maybe someone is simply manually tricking you?
Comment: And you are absolutely sure that the spam comes from that specific form which you're trying to protect?
Comment: @Tom that's a good point. Captchas are made to deter bots (and mildly annoy humans). If the spammer is a determined and/or deranged human who's targeted this site for some reason, then automated solutions aren't going to help.
Comment: It seems unlikely that they'd be human-generated. How can I tell? They're all from different IPs? The logs suggest they are coming from the form page. Is there a way to tell if they're spoofs?
Comment: Am I the only one who thinks this belongs on webmasters?
Answer: Captchas are speed bumps, not roadblocks. They will never be a 100% solution.
There are even web services (with APIs!) that have humans solve captchas, for fractions of a cent.
I've also seen a fun implementation where spammers run a "submit this captcha to view the porn gallery" site. They present your captcha to the people looking for photos of naked people, and pass their response along to your form.
Comment: I agree, captchas suck. But I have to figure out a way to filter these submissions. The submissions are supposed to be emailed to a fulfillment house, and I don't want the fulfillment guys shipping samples to Russia. One or two a month I can absorb. 4 or 5 a day is too much.
Comment: The simplest solution may be a non-technical one. "Don't ship any to Russia, guys."
Answer: Honestly, they are getting better and better each day and there is no sure-fire way of completely stopping SPAM. The best solution is to incorporate a little bit of both. reCAPTCHA is good, but when you combine it with say a mathematical equation, it could do very well. Also, you want to keep in mind not to make SPAM catchers too difficult because they might do well to keep away the spam bots, but they are also good at deterring real users as well.
Also, if you don't want any customer's from Russia, or you know you won't get any real business from anybody other there, then why not just block Russia IP's?
Comment: This is probably a stupid question, but how do you block all Russian IPs?
Comment: Obviously there are ways around it, say if they might be using a proxy, but this site provides a good reference: [link](http://www.cyberciti.biz/faq/block-entier-country-using-iptables/)
Comment: Simple google search came up with this: http://www.countryipblocks.net/ There are dozens more. I've searched for "Russia IP range"
Comment: Most web servers offer an option to block by country via the headers as well, so that's always an option, but it's the easiest one to get past as well.
Comment: Well, you said Russia, but how sure are you that they are actually from Russia? Try blocking any non-North American countries.
Comment: Yes, I am also curious about how he would go about this. Sounds like it would be a great solution for him.
Comment: Thanks Nick. I knew I could block by IP, but not by country. I'll check into that.
Comment: Quick update: I found 2 sources online that let me download lists of Russian IPs for an htaccess deny block. NONE of the Russian IPs from my server logs were on the downloaded lists :( Not very encouraging.
Comment: Hmm, that might work. It makes me nervous though, since IPs are being added daily. It would probably require constant maintenance to keep current. Maybe I could point non-North American IPs to an alternate form, which DOES require email verification - just so someone doesn't accidently fall through the cracks.
Answer: I don't want to boast because it'll be hacked tonight if I link to it, but I made one that seems to work quite well. In essence (and I'll let you work out the details for yourself) I have a dozen simple photos - cat, dog, car, plane, bird etc. - and I show them alongside a form field with a randomised name (something like MD5( rand(1,10000) ) ). To complete the form the user has to write dog or cat or whatever in the text field.
Comment: So a botmaster only needs to visit your site multiple times, download all the images and label them manually once, then his bots can compare to his already written database against his images, and write correct values each time.
Comment: The proof of the pudding's in the eating. It's worked for a couple of years while everything else I've tried has failed. Most of my clients don't want this method because they don't want the silly little pictures of cats and dogs. The hack you suggest might not work because of the form field having a different name every time. I'm not going to fight it out with you - it's just a suggestion.
Comment: A captcha solution working for a long time isn't necessarily an indication that it's a good captcha. It could just be that you don't get enough traffic to write a custom solution for.
Comment: You're right. And the spam comes in spates. Sometimes you get thousands a day and then you get none for months. No solution is perfect, that's certain. Changing the name of fields does help - making some fields blank (i.e. bin the response if this field is filled) also seems to help.
Comment: The different name will not deter bots from filling it, they can and will read the direct HTML source EVERY TIME, the name doesn't matter for them. Maybe if you had several such fields, all with random and changing names, with their order scrambled (with JavaScript, also done randomly) and all of them are hidden except for one, it might confuse the bot about which one to fill out (because if all of them are field the PHP should reject it).
Comment: Crossed in the post there. An interesting discussion though.
Answer: I came across NuCaptcha on Slashdot, it uses video instead of pictures to make it much harder for the bots to read but easy for you and I as it does not have to be crazy scrambled. its works very well so far but i agree with ceejayoz. If anything, just to kick the tires and see what you think of it.
<code>http://www.nucaptcha.com/
</code>
Comment: This is not an effective solution considering it uses Flash. If they converted to canvas/HTMl5 elements, it might be better.
Comment: @NickGeorge I didn't realize it used flash, i agree with you 100%
Comment: @NickGeorge Let's sidestep the issue of flash on mobile devices 'cos it always results in arguments :) Frankly, I wish everyone would hurry up and upgrade - I only managed to drop support for IE6 about 6 months ago (Public sector clients)
Comment: @NickGeorge and Drewedin: The problem is that although HTML5 is preferable long-term, there are an awful lot of users out there whose browsers don't support it. Much as I hate Flash, it's still got a huge install base so it is a viable option. Of course, the ideal is HTML5 with a fallback to Flash...
Comment: @Basic, but the same can be said with Flash. An ever growing support for non-flash applications is needed with the mobile market booming.


Solr and Zookeeper with a single node

Question: I have the setup of Solr cloud running in my local machine with the internal Zookeeper (i.e) Zookeeper that is being internally used by Solr with the single node.
My query is that while I move my Solr to the production environment, Is it recommended to run the Zookeeper in a isolated/separate/external instance or is it better to go with the internal instance of Zookeeper that comes along with the Solr?
Answer: The use solr internal zookeeper is discouraged for the production environments. This is even stated in SolrCloud documentation.

Although Solr comes bundled with Apache ZooKeeper, you should consider yourself discouraged from using this internal ZooKeeper in production, because shutting down a redundant Solr instance will also shut down its ZooKeeper server, which might not be quite so redundant. Because a ZooKeeper ensemble must have a quorum of more than half its servers running at any given time, this can be a problem.

The solution to this problem is to set up an external ZooKeeper ensemble. You should create this ensemble on a different machine so that if any of the solr machine goes down it will not impact the zookeeper and rest of the solr instances. I know currently you are going with one solr instance.
Comment: Yes am going with the internal instance of Solr(Zookeeper). Thanks for your suggestion.
Comment: I have hosted the SOLR in a separate machine and database(datasource) in a different machine. Then while indexing takes too long time.
Is there any configuration needs to be changes either in the database machine or in SOLR side?
Both machines is on same LAN.
Comment: Please have a look at the last comment @YoungHobbit
Answer: As mentioned, for production is not a good idea to have the internal Zookeeper inside Solr but for development is entirely OK and very practical and for that you just need to add this lines to your /etc/default/solr.in.sh file:
SOLR_MODE=solrcloud
ZK_CREATE_CHROOT=true

As an alternative, you can also start Solr manually with the command $SOLR_HOME_DIR/bin/solr start -c

Tested with Apache Solr 9 on a Debian based Linux

Solr and Zookeeper with a single node


4 UIlabel with equal space on iphone5 and iphone6

Question: Currently, I am working a app with UITableview. In each cell, there are 4 labels are showing data and value. However, the UI is working fine on iphone 5 simulator. When I use iphone 6 or 6s simulators, there is a space area at right hand side. I would like to have result that is 4 labels with equal space no matter it shows on iphone5 or iphone6. I know that I must use UI constaint to make it possible. However, I Google it but I cannot find similiar case. Please give me some hints or tutorial link to do so. Thank you.

Regards,
Tommy
Comment: post your error log or problem image
Comment: Try this [link](https://www.packtpub.com/books/content/evenly-spaced-views-auto-layout-ios)
Comment: add leading and trailing constraint from labels to superview.
Comment: Gentlemen - Thank you for your reply. The post had been updated. I had added the picture for your reference. I just want to get the result of iPhone 4.7 and 5.5 inch with like 4 inch screen.
Comment: You can use equalWidth constraints between your parent view and labels. Set multiplier to 0.2 or something that fit for you. Give leading and trailing constraints between them. It should work for you.
Comment: Dear all experts - I am newbie on it. Would you give me more hints or examples? I had tried to do, but I cannot get the equal width. Please help.
Comment: This video helps you. https://www.youtube.com/watch?v=WTMpJJ9Ofm8 &&
http://stackoverflow.com/questions/13075415/evenly-space-multiple-views-within-a-container-view
Answer: The way I find easiest to accomplish this is by creating a UIView for each of the UILabels. Then Make them all have equals widths and heights and add constraints for up, down, left and right.
Also dont forgot 3.5 inch as you still have to support that for iOS 8 and 9 :)


How to bridge two lan but keeping their clients using/choosing their own wan?

Question: this is my first question here so please bear with me if I haven't made it super clear
So I have 2 piece of Cisco RV180W router hardware.
The office is moderately big and one single Wifi router is not sufficient to cover them all. So that's why I got two of these routers.
We also have 2 WAN connections so that we don't have a single ISP point of failure. Currently each router is connected to one WAN.
We also have some shared network resources like a Wifi printer, and a NAS.
Current situation is that each router broadcasts their own SSID, so it's like two entirely separate network.
Pro: users could pick their own SSID to switch between ISP.
Con: They have to switch SSID in order to print or use NAS, because the two thing are associated with one of the router only.
So what I am looking for is:

Merge the two SSID into one
Merge the two network into one (so only 1 DHCP server) so that printers/nas can be shared
Users could by some means still pick their own WAN connection (via VPN? some VLAN magic?)

So far I could only achieve 1+2, but not 3.
The way I do 1+2 is simply put one of the router as AP (simply by disabling DHCP on that router and plug a cable between the LAN ports of the two routers; and then set the same SSID and password)
Is there any pro tips on how I could achieve 3 as well?
Although not strictly required, but I would like to keep the amount of additional hardware/server at minimal - best if it can be done just with that two router or maybe the NAS (since it came with also VPN server and DHCP server that I could enable)
I have only little knowledge in VLAN so any newbie-friendly, overly-detailed explanation are more than welcome.
Answer:
Users could by some means still pick their own WAN connection

Depends on how you understand "some means". You can assign different gateways via DHCP configuration. You could offer an internal web page which the users can use for selecting the gateway. This page would trigger a script that makes the respective changes to the DHCP configuration file. Ask your favorite search engine for [dhcp multiple gateways].
Comment: Originally I was hoping to look for solutions that doesn't require the admin to do any programming (thus "via VPN? some VLAN magic?"). But this answer definitely is a workable solution somehow. Deserves acceptance.