i want to validate date in javascript.can anyone help me in understandin this?

Question: var dcheck=/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/;/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/;

can anyone one help me in understanding this part
"/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/;/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/"

....can u please tell me how this checks the input also?
if(dcheck.test(dor)){
        document.getElementById('div_id').innerHTML="Correct Entry";
    }
else{
   document.getElementById('div_id').innerHTML="please check ";
  }

Thanks In Advance!!!
Comment: you can use this page to test your expression http://gskinner.com/RegExr/
Comment: If you enter the regular expression at http://gskinner.com/RegExr/ and hover over each piece of it, you'll get a tooltip that says what it does.
Comment: http://regex101.com/ will also provide explanation on what each part of your regex means.
Answer: /^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-{4}$/ is a regular expression, commonly used to match strings of various forms. Let's step through it bit by bit to figure out what it's doing.
/^(0?[1-9]|[12][0-9]|3[01])-:
Here, we check if the string starts with a certain two-digit string. The vertical bar here means or, so either we match 0?[1-9], [12][0-9], or 3[01]. The first means "It's a single digit day, and we don't care if you start with 0 or not." The "we don't care" is encoded by a question mark. The second is for a two-digit day where the second digit is unrestricted, and the third is saying that the date, if starting with 3, must be either 30 or 31. Finally, the - just means we end in a -, for this section.
(0?[1-9]|1[012])-:
Here, we do something similar. This part is of the form 0?[1-9] or 1[012]. Hopefully you can see, by referring to the previous paragraph, that this accepts months from 1 to 12, where single digits may start with a 0.
{4}
This is a new symbol we haven't seen. {n} just means "Accept an n-digit string".
So what we end up with is "Day-Month-Year", where the parentheses capture the day, month, and year, and stick them into variables.
Hope that helped!
Answer: Html Code:
<form name="frmSample" method="post" action="" onSubmit="return ValidateForm()">

Enter a Date (mm/dd/yyyy)
              :
              <input type="text" name="txtDate" maxlength="10" size="15">

              <input type="submit" name="Submit" value="Submit">

          </form>

javascript Code:

try this one. it may helpful to you.


Como reutilizar uma String em um outro Step do meu teste?

Question: estou com uma dúvida (talvez simples para a maioria) e precisava da ajuda de vocês...
Estou programando um Fluxo End-to-End de APIs utilizando Java, RestAssured e Cucumber (para definir meus steps).
Na minha primeira API é gerada um numero de proposta no retorno que é utilizada no body das outras APIs.
Como eu conseguiria capturar essa String em um Step do meu fluxo, e reutilizar nos demais Steps? alguem poderia me ajudar?
Sou grato pela ajuda desde já pessoal! :D
Answer: Caique Pena,
Tente o seguinte:
1- Crie uma variável global;
2- popule a variavel com o valor que deseja;
3- reutilize em outro método;
<code>public class Steps(){
    int idade;

    public void pegaIdade(){
         idade = 10;
    }

    public void reutilizaIdade(){
         int calculaSomaDeIdade = idade + 15;
    }
}
</code>
Abç.


Compilation gcc 4.6.2 (cannot compute suffix of object files)

Question: Problem when compiling gcc 4.6.2:
checking for avr-gcc... /data/data6/soft/src_build/gcc-4.6.2/host-x86_64-unknown-linux-gnu/gcc/xgcc -B/data/data6/soft/src_build/gcc-4.6.2/host-x86_64-unknown-linux-gnu/gcc/ -B/data/data6/soft/programming/gcc-avr/avr/bin/ -B/data/data6/soft/programming/gcc-avr/avr/lib/ -isystem /data/data6/soft/programming/gcc-avr/avr/include -isystem /data/data6/soft/programming/gcc-avr/avr/sys-include
checking for suffix of object files... configure: error: in `/data/data6/soft/src_build/gcc-4.6.2/avr/libgcc':
configure: error: cannot compute suffix of object files: cannot compile
See `config.log' for more details.

In my gcc-4.6.2/avr/libgcc/config.log I found:
configure:3268: /data/data6/soft/src_build/gcc-4.6.2/host-x86_64-unknown-linux-gnu/gcc/xgcc -B/data/data6/soft/src_build/gcc-4.6.2/host-x86_64-unknown-linux-gnu/gcc/ -B/data/data6/soft/programming/gcc-avr/avr/bin/ -B/data/data6/soft/programming/gcc-avr/avr/lib/ -isystem /data/data6/soft/programming/gcc-avr/avr/include -isystem /data/data6/soft/programming/gcc-avr/avr/sys-include -c -g -O2 conftest.c >&5
exec: 89: -o: not found
configure:3272: $? = 1
configure: failed program was:
| /* confdefs.h */
| #define PACKAGE_NAME "GNU C Runtime Library"
| #define PACKAGE_TARNAME "libgcc"
| #define PACKAGE_VERSION "1.0"
| #define PACKAGE_STRING "GNU C Runtime Library 1.0"
| #define PACKAGE_BUGREPORT ""
| /* end confdefs.h. */
|
| int
| main ()
| {
|
| ;
| return 0;
| }
configure:3286: error: in `/data/data6/soft/src_build/gcc-4.6.2/avr/libgcc':
configure:3289: error: cannot compute suffix of object files: cannot compile
See `config.log' for more details.

If this command run directly (after creating conftest.c) output will be same.
What is exec: 89: -o: not found? Which program write it? Where is 89 line?
Solutions like exporting LD_CONFIG_PATH or adding lines in /etc/ld.so.conf with path to GMP, MPFR, MPC not work for me.
Where find solution for this problem?
Update. It seems is configuration problem. Gcc has very good option -v :-) And i see that is assembler call from gcc, which fails. With option -save-temps i saved assembler source, and run assembler, but it doesnn't matter.
Instead of calling real assembler it calls shell-script wrapper, in my case /data/data6/soft/src_build/avr-gcc/gcc/as, which begins from:
ORIGINAL_AS_FOR_TARGET=""
ORIGINAL_LD_FOR_TARGET=""
ORIGINAL_PLUGIN_LD_FOR_TARGET=""
ORIGINAL_NM_FOR_TARGET=""

And when it form command-line call, we have this:
exec -o conftest.o conftest.s

which fails as described above.
Where is necessary fix this? To get call like this:
    exec as -o conftest.o conftest.s
Where good place to set variable ORIGINAL_AS_FOR_TARGET?
Comment: On Debian or Ubuntu: try first `aptitude build-dep gcc-avr binutils-avr; aptitude install gcc-avr binutils-avr`
Comment: What are your exact argument to `..../configure`? Did you pass a `CC` variable to it? Do you have a C compiler? Whch one? Which executable is it? Is it in your `PATH`? What is your host operating system? Are you sure you are building gcc outside of its source tree? What are your GCC source tree and build tree?  Did you *carefully* read http://gcc.gnu.org/install/ ?
Comment: Basile, thanks for reply. It is last ubuntu, build tree is OUTSIDE, compiler - gnu gcc 4.6.1 x86_64, target - avr. /data/data6/soft/src_build/avr-gcc - it is build tree, /data/data6/soft/src_build/gcc-4.6.2 - it is source tree.
Comment: I update post. May be it configuration problem?
Comment: aptitude build-dep gcc-avr binutils-avr; aptitude install gcc-avr binutils-avr - it work. Where to find information about this dependences?
Answer: I had the same problem cross-compiling for mips.
Step one:  Cross-compile the binutils for your target.  Install them somewhere sane.  I use /usr/local/[target]-gcc
Make sure you configure them with --program-prefix=[target]-
Something like (untested):
configure --prefix=/usr/local/avr-gcc --program-prefix=avr- --target=avr

Then you need to set up some environment variables so GCC can find them:
export AR_FOR_TARGET=/usr/local/avr-gcc/bin/avr-ar
export LD_FOR_TARGET=/usr/local/avr-gcc/bin/avr-ld
export OBJDUMP_FOR_TARGET=/usr/local/avr-gcc/bin/avr-objdump
export NM_FOR_TARGET=/usr/local/avr-gcc/bin/avr-nm
export RANLIB_FOR_TARGET=/usr/local/avr-gcc/bin/avr-ranlib
export READELF_FOR_TARGET=/usr/local/avr-gcc/bin/avr-readelf
export STRIP_FOR_TARGET=/usr/local/avr-gcc/bin/avr-strip
export AS_FOR_TARGET=/usr/local/avr-gcc/bin/avr-as

Now you can configure and compile GCC.  Ensure you start from a completely empty build directory, otherwise gcc/as etc won't get recreated.
Comment: **Ensure you start from a completely empty build directory, otherwise gcc/as etc won't get recreated.**

This should be the bolded top  comment.  I just wasted hours trying dozens of different things, only to realise that "make clean" wasn't enough to have it recreate this file, so all my experimentation was being wasted.
Answer: "*Building GCC is not trivial, but is not difficult if you follow the instructions carefully.
Many people rush into trying to build it without reading the installation docs properly and make one or more of these common mistakes:
1) do not run ./configure from gcc src dir (this is not supported) => you need to run configure from outside the gcc source directory
2) Note: if GCC links dynamically to the prerequisite libs (GMP/MPFR/MPC) then the shared libraries must be in the dynamic linker's path (LD_LIBRARY_PATH), both when building gcc and when using the installed compiler.*"
Simple example (without dynamic link to GMP/MPFR/MPC):
tar xzf gcc-4.8.0.tar.gz
cd gcc-4.8.0
./contrib/download_prerequisites
cd ..
mkdir objdir
cd objdir
$PWD/../gcc-4.8.0/configure --prefix=/opt/gcc-4.8.0
make
make install

Sources:
Advogato Doc -
GNU Doc


Regarding the union of certain affine Hyperplanes being closed

Question: Let $X$ be an open subset of $\mathbb{C}^n$. Let $F$ be the union of all affine hyperplanes $\Pi\subset\mathbb{C}^n\setminus X$. It is said that $F$ is a closed set.
The proof goes like this:
If $x_j\in F$ then we can find affine hyperplanes ${\Pi}_j\subset\mathbb{C}^n\setminus X$ such that $x_j\in{\Pi}_j$. If $x_j\longrightarrow x$ then we can choose a subsequence ${\Pi}_{jk}$ converging to an affine hyperplane $\Pi\subset\mathbb{C}^n\setminus X$, and since $x\in \Pi$, it follows that $F$ is closed.
My question is:

How are we getting this subsequence ${\Pi}_{jk}$ and how does ${\Pi}_{jk}$ converge to $\Pi$?

Why does $x$ belong to $\Pi$?
Answer: Talking about hyperplanes that converge needs indeed a good definition. What you're reading seems loosy on this point. Here is a rigorous explanation .
Think of the affine hyperplane $\Pi_j \subset \mathbb{C}^n \setminus X $ as the hyperplane $\{ x_j + v \, | \, \langle v, v_j \rangle =0\}$ for a normed $1$ vector $v_j$. This is the hyperplane passing by $x_j$ and orthogonal to $v_j$.
Then $(v_j)$ is a sequence in the compact unit ball of $\mathbb{C}^n$ so there is a subsequence $v_{j_k}$ that converges to some $v_0$. Then take $\Pi$ to be the orthogonal of $v_0$ passing by $x$ : $\{ x+v \, | \, \langle v,v_0 \rangle \}$.
Using the openness of $X$, show that $\Pi$ is indeed in $\mathbb{C}^n \setminus X$. Basically, if $x+v$ were in $X$, there would be $x_{j_k} + w_k \in \Pi_{j_k}$ tending to $x+v$ and so would be in $X$.


Loading entity, set relation depth?

Question: Is it somehow possible to set a loading level for related entities? An example of related entities:
<code>Voucher
- has a Product
    - has a ProductGroup
</code>
A call like this
<code>$voucher->getProduct()->getProductGroup(),
</code>
causes multiple SQL queries by calling getProduct() and getProductGroup(). I know it is possible to load everything with a big join in querybuilder, but I am looking for a kind of configuration how deep the entities should be loaded by join or proxyobjects. I dont know for what I should search in google. :(
Comment: Nope.  QueryBuilder is really the only way to go for this sort of thing.
Comment: @Daniel: With lazy loading, only required data will be loaded, so you shouldn't worry about depth. As you said, you can use `join` in your repository to reduce the number of queries.
Answer: I think you're looking for this: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html
Comment: I am not sure if that really what I need. It is configured in my entity and the behaviour is allways the same, but I need something different. In another case I want to load it with all relations.

Maybe I need only the vouchers name, I want to load without relations.

Loading entity, set relation depth?


What is this mathematical expression?

Question: I am trying to figure out what the attached picture's mathematical expressions mean. We have a kernel function $k$ that takes in 2 vectors that are $\in \mathbb{R}^d$.
I don't understand what the subscripts in the sum mean, could someone explain? What do the $j_1,...,j_d$ stand for? I also do not understand what the big parenthesis means. Could someone explain this to me as well?
Comment: Thanks! I had a hard time searching because I did not know what the name of this expression is.
Comment: This may help you: https://en.wikipedia.org/wiki/Multinomial_theorem
Answer: It means $j_1, \ldots, j_d$ are nonnegative and sum to $p$.
and $$\binom{p}{j_1, \ldots, j_d} = \frac{p!}{j_1! j_2! \ldots j_d!}=\frac{p!}{\prod_{i=1}^d j_i!}$$
The multinomial coefficient.
Note that $$(u^Tv)^p = \left(\sum_{i=1}^d u^{(i)}v^{(i)} \right)^p$$
Comment: it didn't say that explicitly, but since I know the multinomial theorem...
Comment: they have to sum up to $p$, so nope.
Comment: Why does the sum subscripts mean the j's are non-negative?
Comment: Ohh. So does $j_1,\ldots,j_d$ take on the values of $1,\ldots,d$, respecitlvey?
Comment: for example if $d=3$, and $p=5$, some of the indices are $(5, 0,0), (1,2,2)$, $(3,0,2)$, and so on.
Comment: Ah okay. And is there a typo in your last edit? There shouldn't be a p on the RHS, or the LHS is missing a p.
Comment: you are right, thanks.
Comment: One more question. You gave the example for $d=3$ and $p=5$. So $j_1,\ldots,j_d$ the set of all indices that satisfy $j_1 + \ldots + j_d = p$?
Comment: yes, that is correct.
Comment: Is there a quick way to modify the multinomial expression for $(u^Tv)^p$ to $(u^Tv+1)^p$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/85160/discussion-between-siong-thye-goh-and-iamanon).

What is this mathematical expression?


Can every partially ordered set (POSET) take the form of a directed acyclic graph (DAG)?

Question: A POSET (Partially ordered set) is a set on the elements of which we have established a partial order relation ($\leq$), i.e. a relation which is:

reflexive: $x\leq x,$ for every x in S
anti-symmetric: $x \leq y \wedge y \leq x \Rightarrow x=y $
transitive: $x\leq y, y\leq x \Rightarrow x\leq z$

My question is if every POSET can take the form of a DAG (Directed Acyclic Graph) if we view its elements as the nodes and the relation itself as the edge set.
Comment: It's better than a DAG, it's a transitive DAG. If you represent the edges of the poset's [Hasse diagram](https://en.wikipedia.org/wiki/Hasse_diagram) as arcs in the upward direction, and take the [transitive closure](https://en.wikipedia.org/wiki/Transitive_closure) of the resulting (acyclic) digraph, you get the DAG of the poset.
Comment: @M.Vinay : the opposite operation is also interesting ? removing the maximum of edges without changing the binary relation by specifying it stays transitive. then the graph becomes ..
Comment: @user1952009 Then you'll get the Hasse diagram back. Edges now represent (the more restricted) "covering" relation rather the the whole relation.
Comment: ok thanks, and https://en.wikipedia.org/wiki/Transitive_reduction
Comment: Thank you very much all!! That's exactly what I wanted to verify plus a few more things I will try to learn about.
Comment: @user1952009 You might like to know that a [preorder](https://en.wikipedia.org/wiki/Preorder) (a reflexive and transitive relation) can also be a represented by a transitive digraph (not acyclic) in the same way. But now, you can define an equivalence relation on the vertex set by making any two vertices equivalent if each is related to the other. Then the equivalence classes form [strongly connected components](https://en.wikipedia.org/wiki/Strongly_connected_component), so that any cycle is contained entirely in exactly one strongly connected component or equivalence class.
Comment: Now construct a new digraph with each equivalence class of the earlier graph taken as a *single vertex*, such that there is an arc from one vertex to another if there is at least one arc between the corresponding equivalence classes in the original graph. Now the new graph is a transitive DAG and represents a partially ordered set.
Comment: You can do the same with no reference to graphs at all. You just define the same equivalence relation on the preordered set, and construct a new set with elements as the equivalence classes. Define a relation on this, with classes $[x]$ and $[y]$ being related as $[x] \le [y]$ if some $x' \in [x]$ (in the original preordered set) is related to some $y' \in [y]$. Then $\le$ is a partial order on the set of equivalence classes.
Comment: Thank you very much! This seems very interesting too.
Answer: YES. Every POSET can take the form of a DAG.
However, in order to obtain a less cluttered graph, you'd better avoid drawing every single edge. (see figure)
You can omit the edges that can be inferred from the reflexive and transitive properties.
Moreover you can arrange nodes in order to orient every edge upward and omit vector tips.
In this way you obtain a Hasse diagram: it is just a stripped down DAG.


Summation of $\sum\limits_{j=2}^n j = \frac{n(n+1)}{2} -1$

Question: I've know that
$\sum\limits_{i=1}^n k$ is $ \frac{n(n+1)}{2}$.
Then why
$\sum\limits_{j=2}^n j = \frac{n(n+1)}{2} -1$ ? I understand that i=1 $\neq$ j=2 is the key, but I can't get further.
from : Introduction to Algorithms (3rd edition) p. 27
Comment: Note $\sum\limits_{j=1}^n j = \frac{n(n+1)}{2} $ and $1+\sum\limits_{j=2}^n j=\sum\limits_{j=1}^n j $.
Comment: Of course. It was so obvious. I can't believe I couldn't see it. Thanks for the tip
Answer: $${n(n+1)\over 2}=\sum_{k=1}^n k = 1 + \sum_{k=2}^n k.$$
Comment: Vey clear thank you. It was so obvious!!!! Thanks for taking time to pointing it out! I got it !


How to find the minimum product of two or more quantities when their sum is given?

Question: Suppose we have been given $ \sum_1^n x_i = S $
How will we find $x_i $  such that  $  \prod_1^n x_i $ is minimum?
Any hints are appreciated. Thanks!
Edit : Sorry, my mistake. All $x_i$ are positive.
Comment: @Raghav:  As Mark Fischler says, the question does not make sense for a minimum.
Comment: Have you heard of the AM-GM inequality?
Comment: @TheSimpliFire Yes but I don't think that helps here.
Comment: Yes, it does.  The product of the number is the $n^{th}$ power of the geometric mean.
Comment: @RossMillikan That would give the upper bound of the product, not the lower bound.
Comment: @Raghav I don't think so. Just the minimum does not exist, See my post.
Comment: @MichaelRozenberg Yeah, I guess it doesn't make sense. It will be so close to 0 that it isn't worth it to find it.
Comment: @Raghav Which says that the minimum does not exist. In this the sense!
Comment: @MichaelRozenberg Yes.
Answer: I think you meant finding $x_i$ such that the product is maximum, not minimum, since for a minimum, just take one of the $x_i$ to be zero.  Also, the problem makes sense only if you restrict to non-negative $x_i$.
So for some fixed $S$ we are trying to find $x_i$ such that $\sum x_i = S$ and $\prod x_i$ is as large as it can be.
There is a theorem that the geometric mean of a set of numbers $GM(\{x_i\})$ is less than or equal to the arithmetic mean $AM(\{x_i\})$; it is sometimes called the AM-GM theorem.  The geometric mean is the $n$-th root of the product of the numbers: $GM(\{x_i\})=\left(\prod x_i)\right)^{1/n}$.
Then
$$ \left(\prod x_i)\right)^{1/n} \leq \frac1n \sum x_i = \frac{S}n \\
\prod x_i \leq \left( \frac{S}n \right)^n
$$
When each of the $x_i = \frac{S}n$, this bound is exactly achieved.  Therefore, the desired $\{x_i\}$ happens when they are all equal to $\frac{S}n$.
Comment: No, I do not mean maximum. I want to find the product such that it is minimum. I have mentioned that $x_i$ are positive.
Comment: In that case, you can get arbitrarily close to $0$ bby making one of the entries very close to $0$ and the others $S/(n-1)$.
Answer: There is no minimum of the products, but the infimum of the products is $0$.
Proof. By assumption all products are positive. Let an  $\epsilon\in\> ]0,S[\>$ be given, and put
$$x_1:=\epsilon,\qquad x_k:={S-\epsilon\over n-1}\quad(2\leq k\leq n)\ .$$
Then $\sum_{k=1}^n x_k=\epsilon+(n-1){S-\epsilon\over n-1}=S$, and
$$0<\prod_{k=1}^n x_k=\epsilon\left({S-\epsilon\over n-1}\right)^{n-1}\leq\epsilon\left({S\over n-1}\right)^n\ .$$
As $n$ and $S$ are fixed the RHS of $(1)$ can be made arbitrarily small by choosing $\epsilon$ small enough. This proves that
$$\inf\prod_{k=1}^n x_k=0\ .$$
Comment: Thanks for your answer. I have a doubt, wouldn't $\sum_1^n x_i $ get greater than S when I choose $\epsilon$ really small as I will have $S+ \frac{S}{2}$ for n=3.
Answer: Does not exist.
$\prod\limits_{k=1}^nx_k$ can be less than all positive number, but $\prod\limits_{k=1}^nx_k>0$.
Try $x_1=x_2=...=x_{n-1}\rightarrow0^+$ and $x_n\rightarrow S$.
Comment: sorry for wasting you wasting your time. I forgot to mention that all $x_i$ are positive. I've just edited it.
Comment: @Raghav I fixed my post. See now.
Answer: Mark Fischler does the general case, but it may be instructive just to consider the case of $n=2$.  Let the numbers be $a,b$.  We are given $S=a+b$ and asked to choose $a,b$ so the product is maximized.  The product $P=ab=a(S-a)=Sa-a^2$.  We can take the derivative and set to zero, getting
$$\frac {dP}{da}=\frac d{da}(Sa-a^2)=S-2a$$
If we set this to zero, we see $a=\frac S2$ and the second derivative test shows this is a maximum.
Now that we have it for two numbers, informally we should make any pair the same.  If we have $n$ numbers with two different, we can increase the product by changing each to the average of the two.  This needs some work to be a proof, but it should convince you.
Comment: As Mark Fischler says, you can get the product arbitrarily close to zero by taking one of the $x_i$ very small.  If you prohibit zero, there is no lower bound.
Comment: Thank you for taking your time to answer this, but I want to find the minimum product, not maximum.


bounding a sprite in cocos2d

Question: am making a canon to fire objects. back of the canon the plunger is attached. plunger acts for set speed and angle. canon rotates 0-90 degree and plunger moves front and back for adjust speed. when am rotates the canon by touches moved its working fine. when plunger is pull back by touches moved and it rotates means the plunger is bounds outside of the canon.
how to control this:-
my code for plunger and canon rotation on touches moved. ( para3 is the canon , para6 is my plunger):-
<code>    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
    oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
    oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];
    if (CGRectContainsPoint(CGRectMake(para6.position.x-para6.contentSize.width/2, para6.position.y-para6.contentSize.height/2, para6.contentSize.width, para6.contentSize.height), touchLocation) && (touchLocation.y-oldTouchLocation.y == 0))
    {
        CGPoint diff = ccpSub(touchLocation, oldTouchLocation);
        CGPoint currentpos = [para6 position];
        NSLog(@"%d",currentpos);
        CGPoint destination = ccpAdd(currentpos, diff);
        if (destination.x < 90 && destination.x >70)
        {
            [para6 setPosition:destination];
            speed = (70 + (90-destination.x))*3.5 ;
        }

    }
if(CGRectIntersectsRect((CGRectMake(para6.position.x-para6.contentSize.width/8, (para6.position.y+30)-para6.contentSize.height/10, para6.contentSize.width, para6.contentSize.height/10)),(CGRectMake(para3.position.x-para3.contentSize.width/2, para3.position.y-para3.contentSize.height/2, para3.contentSize.width, para3.contentSize.height))))

            {

        [para3 runAction:[CCSequence actions:
                          [CCRotateTo actionWithDuration:rotateDuration angle:rotateDiff],
                          nil]];
        CGFloat plungrot = (rotateDiff);
        CCRotateTo *rot = [CCRotateTo actionWithDuration:rotateDuration angle:plungrot];
        [para6 runAction:rot];
    }
}
</code>
Answer: how about u do this that you use the [CCMoveTo actionWithDuration: position:] method??
Through this method you can easily control the speed by the "actionWithDuration" argument which takes integer values of time in seconds, while direction can be adjusted through "position" argument which takes ccp(x,y) as the values to the point you want your plunger to move to.
You can use it like this....
<code>    CCSprite *plunger = [[CCSprite alloc] initWithFile:@"plunger.png"];
    plunger.position = ccp(240,240);
    [self addChild:plunger z:10];
    [plunger release];

    id = [CCMoveTo actionWithDuration:3 position:ccp(300,240)];
</code>
The values given are of my choice. You may use them to your accordance.
Hope it helps you....
Answer: I hope i understood the question correctly:
if the problem is, that the cannon and plunger both rotate around their own center points, but you want them to rotate together, then the solution should be to make the plunger a child sprite of the cannon (this also makes the plugers position relative to the cannon) i.e.
<code>[para3 addChild:para6]
</code>
then you only need to rotate the cannon and the plunger will be rotatet with it.
if i got your question totally wrong, maybe you could post a screenshot :-)
Comment: i added as a child. still its bounding the sprite ( plunger bounds the cannon)  when touches ended method it will working correctly. in touches moved still it bounds after adding child.

bounding a sprite in cocos2d


Excel Unable to remove Em dash and replace with En dash

Question: Anyone know an excel formula or a VBA code for excel to replace Em dash with En dash. I just cant figure it out. My VLookup formula is not working for cell A1 which contains value 'WARSAW - ICSD RED – EB' as there is a long dash in text.
I've already tried excel formula =SUBSTITUTE(A1,"—","–")
Also below VBA code:
Range("A:A").EntireColumn.Replace What:="—", Replacement:="–", lookat:=xlPart
Answer: Here you go:
=SUBSTITUTE(A1;CHAR(151);CHAR(150))

Comment: Nah that doesn't work unfortunately. Im getting an error. I Also changed the formula to =SUBSTITUTE(A1,CHAR(151),CHAR(150)) but it just returns same vakue thats in cell A1
Answer: With the string: "WARSAW - ICSD RED – EB"
by me this code works:
Sub changer()
    Dim str As String
    str = Cells(1, 1).Value
    str = Replace(str, "–", "-")
    Cells(2, 1) = str
End Sub


How to perform lasso on a wide matrix?

Question: I have a Matrix with almost 1000 samples (rows) and for each of this I have gene expression data for more than 16000 genes. I was trying to perform lasso with the glmnet algorithm but I always get the "cannot allocate vector of size ...Mb" error when I use the function model.matrix to prepare the data. I already tried to increase memory limit, cleaning the environment, deleting useless data and so on. I'm asking if there is another method instead of model.matrix and if this problem is due to RAM problems or something else. Thank you!
Comment: Is there any reason to believe the whole 16000 gene are dependent?
Comment: Using a full stop instead of a comma every now and then can be a good idea :)
Answer: The error message indeed suggests that you don't have enough RAM.
However, this answer suggests that glmnet should be able to handle this amount of data, and suggests h2o for situations where glmnet does give up.
Anyway, if, even after reading this linked answer, you can't make glmnet do the job, maybe speedglm will help.
And yet another powerful library being able to handle large amounts of data would be the python module scanpy.

How to perform lasso on a wide matrix?


Not getting expected output when using bash OR '||'

Question: I'm trying to write a simple bash script that checks the string if value is not "rpm" or "jar". But it seems to always be evaluating to true. I'm not sure what I'm missing.
#!/bin/bash
FILE_EXTENSION="rpm"

if [ "$FILE_EXTENSION" != "jar" ] || [ "$FILE_EXTENSION" != "rpm" ];
then
    echo "File type is NOT rpm or jar";
else
    echo "File type is rpm or jar";
fi

echo "Debug: FILE_EXTENSION value is $FILE_EXTENSION"

Running it on my local gets below output. It evaluates to true even though FILE_EXTENSION variable is set as "rpm"
$ ./check3.sh
File type is NOT rpm or jar
Debug: FILE_EXTENSION value is rpm
$

Answer: You are confused about the logic. a OR b is true if a is true and you don't care about b; and it is true when b is true and then you don't need to care about the value of a.  The trivial fix for your problem is to switch to && which is apparently what you wanted to check for.
I would in fact also prefer a case statement, as it is easier on the eyes (once you get past the syntax of the case statement itself, which can be unsettling if you are unfamiliar with it).
case $file_extension in
  rpm | jar) echo "File type is rpm or jar";;
  *) echo "File type is not rpm or jar";;
esac

See also Correct Bash and shell script variable capitalization; I switched to lower case for this reason.
Answer: That's because you're using or (||) instead of an and (&&). Currently you're checking if:
rpm != jar -> True
rpm != rpm -> False
True or False => True and you get "File type is NOT rpm or jar"


Could not found FtpWebRequest in windows phone

Question: I am uploading one XML file to web server using FTP
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("test.xml", FileMode.Append, myIsolatedStorage))
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri"ftp://" + IPServer + "/" + isoStream.Name));
                reqFTP.UsePassive = true;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential("uname", "pass");
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];

                Stream uploadStream = reqFTP.GetRequestStream();
                int contentLength = isoStream.Read(buffer, 0, bufferLength);

                while (contentLength != 0)
                {
                    uploadStream.Write(buffer, 0, bufferLength);
                    contentLength = isoStream.Read(buffer, 0, bufferLength);
                }
            }

But I could not found FtpWebRequest. I have also added assembly System.Net. I am not getting What is the issue ? Can anyone help me to solve this? Can I upload the file by using FtpWebRequest in windows phone ? Is my code is correct to upload a file or not ?
Answer: There is no FtpWebRequest in Windows Phone as of right now.
The same question asked elsewhere caused people to mention using a service that wraps FTP calls in HTTP. That appears to be your only option right now unless you find some third-party component to use.
Comment: Hey Tim, Thank you for reply. Then how can I upload file on ftp server?
Comment: I edited my answer with a bit more info. Sorry I don't have much in the way of help. Just doesn't seem too easy right now.
Comment: Ok I will try by using HTTP


Redirect request to an external IP to localhost (emulate a server)

Question: I got an application (no source code) calling a server (hard coded IP) and expecting an answer before starting (a kind of login).
Cause the server is down half of the time, I want to create a dummy server which will emulate the behavior of the official server.
My problem:
How can I redirect the traffic to my local machine?
I want all the request send to IP w.x.y.z to be re-routed to localhost (where my dummy server is running)
More info:

my dummy server is an apache/php
solution.
I tried to edit the hard coded IP in the application with an hex
editor, but some checksum fail when I
start the application.
cause the IP is hard coded in the application, I cannot use the hosts
file.
I'm running win xp.

related:
How to redirect traffic to one IP to a different IP on Windows Server 2008
Answer: This would be a total hack, but you could try assigning the IP of the server in question as an additional IP on you local interface, instructions here
Comment: Precision: Adding a 2sd IP to my NIC got a side effect; all IP in the same external subred are redirected to my NIC. ie: when adding IP 22.214.171.124, IP 220.127.116.11 is not reachable anymore. This is caused by the route 220.127.116.11 and the route 18.104.22.168. Workaround: add route 22.214.171.124 -> normal gateway.
Comment: This really rocks ! working great, very easy solution. thanks !
Comment: This looks great !. but I cannot try it now, (my internet is down, I'm tethering on 3G..). I give you some feedback at the end of next week.
Comment: Sweet, glad to hear it :)
Comment: the link is broken
Answer: Well, you could try the following:
Set up a specific route for that IP address, which will use the dummy server as gateway, like this:
route add -host w.x.y.z/32 gw dummy-server-ip
For this you will need either access to the main router for your network, or you have to do it on the machine that is sending the requests. This effectively sends the TCP packets with the w.x.y.z IP address to the MAC address of the dummy-server. So now you need to make sure the dummy server knows what to do with them.
Then add the w.x.y.z IP address as a secondary address to the dummy server.
Finally update the apache config on the dummy server to ensure it also listens on the w.x.y.z address, and make sure that the vhost on the dummy server accepts incoming requests for both the IP address and the domain name.
Please note that this will only work if there are no other routers between the requesting machine and the dummy-server. And if there are any firewalls involved, they also need updating.
Comment: There is a route command available for Windows:

route ADD w.x.y.z MASK 255.255.255.255 127.0.0.1

This will point the route back onto your own machine. You might have to open the firewall for incoming requests on the w.x.y.z address.
Comment: Thanks for the answer it's look exactly like what I want to do.

but, I got problem implementing it.

I will prefer to not touch the router, also because, the solution should be exclusive for my machine.

The command you put me as an example does not work on my win xp. I also tried "route add w.x.y.z 127.0.0.1" without success.

I do not have firewall/router between the application and the dummy server. they both run on the same machine. (But, I do have a software firewall:kaspersky)

I will really appreciate some help about how to set this route.
Comment: I did try to add a route using this command with no success. don't know why.
Comment: "route add 184.108.40.206 mask 255.255.255.255 127.0.0.1"
The error message say : "error adding the route: incorrect parameter" (translated from ES)
Comment: Hmm, maybe you need to replace 127.0.0.1 with the actual LAN IP address of that interface. I have never tried anything like this before, so there is a little guesswork involved.
Comment: I could add the route ! (I will have sweared I did try with the local IP without succes. Weird.). Thanks a lot for the guidance. Anyway, even with the route, I cannot open my web server from the local browser using the external IP.
Answer: You could probably bang something together with iptables.  Here's something I once used but am no longer doing to give you a toehold:
<code>*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A PREROUTING -d 172.16.25.202 -i eth0 -p tcp -m tcp --dport 25 -j DNAT --to 172.16.27.59:8025
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
</code>
NB: I did this a long time ago, there may be mistakes in there
The only thing I see that might be an issue is that it's specific to the interface.  I think that the eth0 is only for the inbound part, so using an ip on the lo interface (127.0.0.1) as the target might still work...
Comment: That'd be a great answer...but he's running Windows XP.
Comment: Doh!  I think I saw "apache/php" and stopped reading.  Even after you pointed it out I scanned three times before I saw it.  Oh well, I'll leave it, maybe it'll help someone somewhere somewhen.
Comment: I'm thinkering with Vagrant, busybox and iptables to create a selective VPN. I want to be able to tell my system that only a few known IP addresses belongs to the VPN so traffic to somewhere else won't go through the VPN. My idea is to use a very lightweight Linux as busybox to connect to the VPN, and then using iptables, or hosts file, or something similar, redirect the requests of the known IP addresses to the guest Vagrant VM so that it will handle the VPN. This iptables rules might give me some help :)


using map with filter array JavaScript

Question: i have a json and need to extract data to array.
const data = [{
  "week": 1,
  "lost": 10,
  "recovery_timespan": [{
    "week": 2,
    "count": 1
  }, {
    "week": 3,
    "count": 0
  }],
   "netLost": 10,
  "netReturned": 20
}, {
  "week": 2,
  "lost": 7,
  "recovery_timespan": [{
    "week": 3,
    "count": 1
  }],
  "netLost": 30,
  "netReturned": 200
}, {
  "week": 3,
  "lost": 8,
  "recovery_timespan":"",
  "netLost": 50,
  "netReturned": 40
}];

Expected output: lost,count in recovery_timespan,netLost , netReturned.
[ [ 10, 1, 0, 10, 20 ], [ 7, 1, 30, 200 ], [ 8, 50, 40 ] ]

As you can see expected output,  last recovery_timespan does not contain any data and it just shows as "".so i need to ignore it.
My approach:
const result = data.map(({lost, recovery_timespan,netLost,netReturned}) => [
  lost,
  ...recovery_timespan.map(({count}) => count),
  netLost,netReturned
]);

My code breaks when "recovery_timespan" is "". How can i add a filter along with map to filter that part and make my code work?
Comment: Want to skip records when `recovery_timespan` is empty?
Comment: yes, my code breaks when there is "" for recovery_timespan.
Answer: It's just a matter of checking if it's string or not, but you can short circuit
const result = data.map(({lost, recovery_timespan,netLost,netReturned}) => [
  lost,
  ...(recovery_timespan || []).map(({count}) => count),
  netLost,netReturned
]);

Comment: it's a classic (although not necessarily precise) shortcut because OR expressions are evaluated left to right and in a lazy way. That means if `recovery_timespan` is `truthy` then it won't even get to evaluate the `[]` part. However, if `recovery_timespan` is `falsy` then the second part of the expression will evaluate to return the result `[]`. `falsy` is 0, "", false etc
Comment: this works. Can you please explain `recovery_timespan || [ ]` part?

using map with filter array JavaScript


Expressão Regular para clonar um valor em um campo

Question: Tenho os seguintes valores:
PRO|00000001|GASOLINA ADITIVADA|0101001|27101259|

Gostaria de uma expressão que mudasse os valores e ficassem assim:
PRO|00000001|GASOLINA ADITIVADA|00000001|27101259|

Eu já tenho mais ou menos uma ideia de como será:
(^PRO\|)(\d*)(.\w*.)

Mas o problema é que ela só ta pegando até:
PRO|00000001|GASOLINA

E não estou conseguindo pegar o valor restante do ADITIVADA|.
Comment: Sempre vai ter "PRO" e "GASOLINA ADITIVADA" ou pode ter outros textos? Que linguagem vc está usando?
Comment: vai ter outros textos, PRO é nome de produto, sempre vai ser PRO.. agora GASOLINA ADITIVADA é um exemplo.. poderia ser LUB SELENIA API SN15W40 SEMI-SINT1L
Answer: Eu acho mais fácil você fazer um split, separando os campos por | e em seguida concatenando o que você precisa, mas se quer usar regex, vamos lá.

Se as suas entradas sempre são separadas por | e estão sempre nesta ordem, você pode ser mais específico, dizendo exatamente o que quer e o que não quer.
Se você só quer as linhas que começam com "PRO" e possuem "GASOLINA ADITIVADA", pode usar estes textos explicitamente. Senão, você pode usar [^|], que significa "qualquer coisa que não seja |".
Usar o ponto (.) é abrangente demais, pois significa "qualquer caractere". Usando explicitamente | para o separador dos campos e [^|] para "qualquer coisa que não seja o separador", a regex fica mais específica para o seu caso.
Outro detalhe é decidir se vai usar + em vez de *. Isso porque * significa "zero ou mais ocorrências", ou seja, se não tiver nada, também é válido. Já o + significa "uma ou mais ocorrências", ou seja, o campo não pode ser vazio.
O mesmo vale para os números, pois \d* vai aceitar o campo vazio. O melhor é usar \d+, que verifica se tem pelo menos um dígito. Ou, se você sabe a quantidade exata, use por exemplo \d{8} para exatamente 8 dígitos, ou \d{8,} para "8 ou mais dígitos" ou ainda \d{8,20} para "entre 8 e 20 dígitos". Escolha o que se encaixar melhor nos seus casos de uso e adapte as quantidades de acordo com o que você precisa.
Enfim, uma opção de regex seria:
^PRO\|\d+\|[^|]+\|\d+\|.*$

Repare que o | deve ser escapado e escrito como \|, já que somente um | significa alternância (ou seja, PRO|\d+ significa "PRO" ou dígitos). Com isso temos:

^PRO\|: começa com "PRO", seguido de |
\d+\|: dígitos, seguido de |
[^|]+\|: um ou mais caracteres que não são |, seguido de |
\d+\|: dígitos, seguido de |
.*$: zero ou mais caracteres, até o final da string ($)

Já para fazer a substituição, depende da linguagem que você está usando, pois cada uma tem suas próprias funções para substituição de strings com regex.
De qualquer forma, para isso geralmente usam-se parênteses para agrupar as partes que você quer capturar, então a regex ficaria assim:
^(PRO\|)(\d+\|)([^|]+\|)\d+\|(.*)$

O primeiro par de parênteses é (PRO\|), então este será o primeiro grupo, o segundo par de parênteses é (\d+\|) (os dígitos mais o |), então este será o segundo grupo e assim por diante.
Para fazer a substituição, você usa a sintaxe $1 para se referir ao primeiro grupo, $2 para o segundo etc. Dependendo da linguagem/engine, a sintaxe é \1, \2, etc. Sendo assim, o resultado seria $1$2$3$2$4 (o grupo 2 se repete no lugar do quarto campo). Veja aqui um exemplo.


Script to open a webpage many times to test a server

Question: I would like to test my websocket sever to see home many open connections it can handle at the same time.
To do that I can open many webpages manually and see if the server crashes or not. However, I am looking for an automatic way. Like a simple script that can loop through opening the URL many times.
Is there any simple way to do this?
Answer: Try looking for web server stress testing tools.
Jmeter is a simple free tool that can do some performance/functional testing.
Answer: If you are running an Apache server you could use the Apache benchmark command-line tool.
So let's say for this instance that your server is running on localhost(127.0.0.1), port 8000. If we want to know whether the concurrent connections can be handled by the server we'd have to have a script that executes for a set amount of (mili)seconds and take the average of that.
So let's create a JavaScript function for your server that does a 1 second timeout like this:
<code>setTimeout(function() {
console.log("Executed")
}, 1000)
</code>
With the Apache command-line tools installed run the following command

ab -n 100 -c 100 http://127.0.0.1:8000

If all goes well you should see the average time it has taken to execute a single script. The results should be somewhere between 1 and 1.1 seconds.
I would assume that you are using NodeJS? If not I would definitely recommend looking into it. Mostly because of it's non-blocking awesomeness.


Why do graphing calculators plot this function wrong? Wolfram Mathematica example.

Question: Wrong graph of the function f(x)=-1^x
The function in question is $f(x)=-1^x$ and the plot example is from Wolfram Mathematica. The graph is supposed to show a zig-zag otherwise known as the triangle waveform. This problem happened on Microsoft Mathematics, Desmos online graphing calculator, another graphing calculator online, everywhere except Microsoft Excel so far.
Wolfram Language code for the graph linked is simply: Plot[-1^x, {x, -100, 100}]
Comment: Do you maybe mean to plot $(-1)^x$ instead?  Exponentiation is carried out first, and $1^x$ is uniformly equal to $1$, so $-1^x = -1$ for all values of $x$.
Comment: PEMDAS: http://www.wolframalpha.com/input/?i=plot+(-1)%5Ex
Comment: I'm curious. Does Microsoft Excel really get this wrong?
Comment: Microsoft Excel is the only one that gets it right, but shows a triangle, not a sine.
Comment: No no, $-1^x = -(1^x) = -(1) = -1$ is right. So there should be no oscillation of any kind.
Comment: Example code from Excel: "-C2^B2 " shows oscillation, however I now tried "Plot[(-1)^x, {x, -100, 100}]" in Wolfram Mathematica and I don't get the oscillation :(
Comment: (-1)^x is not understood by desmos.com either...
Comment: How do you define $(-1)^x$ for $x$ real?
Comment: I just did the above code. Not even Microsoft Mathematics accepts the correction the correction $(-1)^x$
Comment: I think I understand now... $(-1)^x$ can produce imaginary numbers when the domain is set to all real numbers, for example $(-1)^\frac{1}{2}=\sqrt[2]{ -1^1}=\sqrt[2]{-1}=i$ ,  $(-1)^\frac{3}{2}=\sqrt[2]{(-1)^3}=\sqrt[2]{-1}=i$, etc.
Answer: What you wrote according to order of operations is $-1^x=-1$. You meant $(-1)^x$ probably. See:
http://m.wolframalpha.com/input/?i=%28-1%29%5Ex&x=0&y=0
Answer: The problem I encountered was twofold:
1) $f(x)=-1^x$, won't show oscillatory motion
because
$=-1^x=-(1^x)-(1)=-1$
2) $f(x)=(-1)^x$, won't plot
because
if $\{x|x \in \mathbb R\} \land x=a/2b$ where $b \in \mathbb N$
"$x$ is in the domain of all real numbers and $x=a/$some even number"
where
$a \neq 2b \lor a \notin \mathbb Q \lor a=2n+1$ where $n \in \mathbb N$
"the numerator $a$ is not equal to the divisor or is irrational or odd"
then
$ (-1)^x \in \mathbb C \land (-1)^x=i=\sqrt[2n]{-1}, n\in \mathbb N$
"$(-1)^x$ is in the domain of all complex numbers and equal to the even root of -1."
In layman terms, when $-(1)$ is elevated to a power other than an integer then the imaginary number $i$ (which is not plottable over a range of real numbers) tend to appear over the range of $(-1)^x$.
The solution:
$f(x)=(-1)^x$, will plot if $\{x|x\in \mathbb Z\}$
"$x$ is in the domain of all integers"
Sample MATLAB code:
x=-100:1:100; %Domain in increments of 1 plots the set of all integers
y=(-1)^.x;
plot(x,y)
The result is the graph of a triangle waveform or "zig-zag."
A new problem arised in Wolfram Mathematica for me. The plot function Plot[] is in the format Plot[expression,{var,varmin,varmax}] with no option for setting the increment of the domain to any desired value. In the case of $(-1)^x$ to 1. Any help with this?
Comment: If you want a triangle wave, you could use $(-1)^{\text{floor}(x)}(2x-2\text{floor}(x)-1)$.


Isomorphism of rings implies isomorphism of vector spaces?

Question: Let $A$ and $B$ be isomorphic unitary rings. Suppose that both of them admit a structure of (maybe finite dimensional) vector space over some field $k$. I would like to know if then $A$ and $B$ are isomorphic as vector spaces over $k$ (if they are forced to have the same dimension). Notice that in general I am not requiring $A$ and $B$ to be $k$-algebras, i.e. I am not requiring any kind of compatibility between the multiplicative structure and the product with scalars from the field. My guess is that in this generality the answer is no, but I can't provide nor find any example.
Here I gather some things I can prove:
1) if the field is $k=\mathbb{Q}$ and $A$ and $B$ are $k$-algebras, then the answer is yes.
2) if the field is $k=\mathbb{R}$, $A$ and $B$ are $k$-algebras and they are fields, then the answer is yes again.
3) if $A$ and $B$ are finite $k$-algebras (and so $k$ is finite too) the answer is yes again.
Unfortunately these rule out most of the examples from a first course in ring theory, so I suspect the answer would be more exotic than this, but I can't find anything. Maybe the answer is yes even in the general setting (or maybe just for $k$-algebras), and in this case I'd like to see a proof.
Thanks in advance.
Comment: Just to clarify your question: it is easy to find isomorphism of rings that are not isomorphism of $k$-vector spaces. For instance, the Frobenius mapping $x\mapsto x^p$ is an automorphism of $\overline{\Bbb F}_p$ which is not ${\Bbb F}_{p^2}$-linear. Yet, this doesn't answer "no" to your question.
Comment: By the way, "finite $k$-algebra" conventionally means a $k$-algebra that is finitely-generated as a $k$-module – in particular it doesn't have to have finitely many elements! (This is the same convention as "finite field extension".)
Comment: @AndreaMori : thanks for this nice example!!
Comment: @ZhenLin : you're right of course; in the question I mean "with finitely many elements".
Answer: I assume you want both the ring and the vector space structures to share the same abelian group structure. $A = B = \mathbb{R}$. Give $A$ the structure of $\mathbb{R}^n$ and give $B$ the structure of $\mathbb{R}^m$, $n \neq m$. You can do it because $\mathbb{R}^n \cong \mathbb{R}^m$ as vector spaces over $\mathbb{Q}$ and thus as abelian groups, given the axiom of choice.
To prove this, consider a Hamel basis $X$ of $\mathbb{R}$ over $\mathbb{Q}$. $\operatorname{card} X = \mathfrak{c}$, thus $X^m \cong X \cong X^n$ as sets, which induces the isomorphism of $\mathbb{R}^m \cong \mathbb{R} \cong \mathbb{R}^n$.
Edit: to the downvoters: please provide a reason.
Comment: @ZhenLin: Both $A$ and $B$ are isomorphic to $\Bbb R$ as *rings*. It's only as $\Bbb R$-vector spaces that they are different.
Comment: @ZhenLin But I'm not using the ring structure of $\mathbb{R}^n$ :)
Comment: @ZhenLin Read the question again.
Comment: Huh, OK. That's a less interesting question than I thought.
Comment: Thank you for your answer. Of course I want the same underlying group. I'm not familiar with infinite extensions, so please let me get this right:  you are saying that $\mathbb{R} \cong \mathbb{R}^m \cong \mathbb{R}^n$ as abelian groups and as (infinite dimensional) $\mathbb{Q}$-spaces. In my notations, the field $k$ is $\mathbb{R}$, right? So you are taking $\mathbb{R}$ as ring and you put on it two non isomorphic structures of $\mathbb{R}$-space, right?
Comment: @YACP It's strange, I saw the score climb up to two and then drop back to zero.
Comment: @Lor yeah, pretty much it.


I can't run cqlengine on centos

Question: I installed python 2.7 and django 1.5 on centos server. I installed cqlengine too but when I want to run my project
This error happen:
can not import model cqlengine
CAn any one help me what shoud I do..
Thanks
Comment: could you post the traceback?
Comment: These are the erroes:
Comment: python2.6 manage.py runserver 0.0.0.0:8000
Validating models...

Unhandled exception in thread started by >
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/core/management/commands/runserver.py", line 92, in inner_run
    self.validate(display_num_errors=True)
Comment: File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/core/management/base.py", line 280, in validate
    num_errors = get_validation_errors(s, app)
  File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/core/management/validation.py", line 35, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/db/models/loading.py", line 166, in get_app_errors
    self._populate()
Comment: File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
  File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/db/models/loading.py", line 96, in load_app
    models = import_module('.models', app_name)
  File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/utils/importlib.py", line 35, in import_module
Comment: File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/db/models/loading.py", line 96, in load_app
    models = import_module('.models', app_name)
  File "/usr/lib/python2.6/site-packages/Django-1.5.1-py2.6.egg/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/srv/www/Viral360/MainApp/models.py", line 1, in
    from cqlengine import columns
  File "/usr/lib/python2.6/site-packages/cqlengine-0.5.2-py2.6.egg/cqlengine/__init__.py", line 3, in
    from cqlengine.columns import *
Comment: File "/usr/lib/python2.6/site-packages/cqlengine-0.5.2-py2.6.egg/cqlengine/__init__.py", line 3, in
    from cqlengine.columns import *
  File "/usr/lib/python2.6/site-packages/cqlengine-0.5.2-py2.6.egg/cqlengine/columns.py", line 501
    return {self.value_col.validate(envy) for v in val}
Answer: You need to upgrade python on your centos box. It looks like you're using python 2.6 on your centos box. Set comprehensions (what's happening in the cqlengine file) were not introduced until python 2.7. That's most likely your problem.

I can't run cqlengine on centos


Count Pageviews in MVC and log in Database

Question: First let me thank everyone who has contributed in my education, it has helped a great deal and I have learned a lot in 7 months.
I have been requested to count every pageview when someone visits a details page.
I updated my database to add a pageview column but I am unsure of how to do anything else.  I think I should put the code on my details ActionResult on my controller since that is the page I want to be tracked.  If this is wrong please correct me.
 public ActionResult Details(int id, int? yearId)
        {
            var dbTest = _testRepository.Id(id);
            var year = yearId == null ? dbTest.LastYear : dbTest.Date.Single(i => i.Id == yearId);
            var vm = new DetailsVM
            {
                Test = _mapper.Map<TestVM>(year)
            };

            return View(vm);
        }

Above is my action result. What it does is collects everything from the database and displays it on a details cshtml page.  This code works.  How do I get each pageview to count and log into my database using the column name pageview.  Please explain your methods so I can learn from it.
Edit:
I have looked into Google Analytics and it isn't what I am looking for. I just want something to use for organization.
I have also included my database model which hopefully provides more information.
public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public ICollection<TestYear> Years { get; set; }
        [NotMapped]
        public TestYear LastYear {
            get {
                return this.Years.OrderByDescending(i => i.Year).FirstOrDefault();
            }
        }
        public int PageViews { get; set; }
    }

Comment: If what you really care about is how are customers using my site then you most likely want to look into Google Analytics or a similar service. And if you really want to do using your own code the use global action filters
Comment: I have read about using Google Analytics but haven't found a good tutorial or explanation/example on HOW to use it. Or where.
Comment: Have a look on [this](https://www.google.com/analytics/#/section-quote) And [this](http://stackoverflow.com/questions/21832711/implementing-google-analytics-in-mvc4-c)
Comment: I have google analytics on my application.  However, how do you pull a number from analytics.  I need to use the stored number.  So if a page as 500 page views on google I need it in the code for example: data-views="google analytics generated number here"
Comment: I don't think google analytics is going to work for me
Comment: Valid point, but think you can also do that with Google-analytics. **How?** read [here](https://developers.google.com/analytics/devguides/config/mgmt/v2/mgmtFeedReference?csw=1#profileFeed).
Comment: I think you should search on more about this, and look at [here](http://stackoverflow.com/questions/6033392/google-analytics-api-display-page-views)
Answer: I ended up just making a method in my repository to add a counter to the page-views column in my database every time an id was hit.
public void AddView(int id)
    {
        var view = _context.Tests.Single(i => i.Id == id);
        view.PageViews++;
        _context.SaveChanges();
    }


problemas com o __dirname no electron js

Question: eu estou fazendo um curso que usa electron 5.0.13, e esta dando esse erro no terminal da minha aplicação em electron
Uncaught ReferenceError: __dirname is not defined
at eval (index.js?bdb9:4)
at Object../node_modules/electron/index.js (chunk-vendors.js:2080)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Home.vue?vue&type=script&lang=js&:2)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Home.vue?vue&type=script&lang=js& (app.js:950)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (Home.vue?59e2:1)
at Module../src/components/Home.vue?vue&type=script&lang=js& (app.js:1113)

eu estava usando electron 9.0 e me deparei com esse erro
no curso teve alguem que perguntou e o professor respondeu que era para colocar o electron 5.0.13, foi o que eu fiz, mas n resolveu, ja removi o yarn-lock e o node_modules varias vezes e não resolveu.
ta aqui o codigo

<template>
    <v-content fluid>
        <v-form>
            <v-file-input multiple chips v-model="files" append-icon="mdi-send"
            label="Selecione um Legenda" prepend-icon="mdi-message-text"
            @click:append="processSubtitles"/>
        </v-form>

            <Pill v-for="word in groupedWords" :key="word.name"
            :name="word.name" :amount="word.amount"/>

    </v-content>
</template>

Comment: Provavelmente, é esse o problema. Quando você cria o BrowserWindow, precisa setar esta flag para true, pois o erro aparentemente está no Vue. Porém, antes de setar essa flag, recomendo ler a documentação e avaliar se a sua aplicação não terá nenhum risco de segurança.
Comment: Quando você criou o BrowserWindow, você setou a flag webPreferences.nodeIntegration para true?
Comment: não setei não, só fui fazendo
Answer: Cria um arquivo chamado vue.config.js na raiz do projeto, e coloca isso dentro para habilitar a integração do Node.
module.exports = {
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true
    }
  }
}

Creditos:
https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/683#issuecomment-600179004
Comment: Não é recomendado utilizar `nodeIntegration: true`, tanto que ele vem desativado por padrão. Uma alternativa melhor envolve o uso do _preload_, por exemplo.
Answer: Tenta usar a solução que tem nessa publicação do SOen utilizando preload.js e window:
Dessa forma dá pra chamar o método abaixo dentro dos arquivos vue
window.ipcRenderer.send(channel, args...) .

Só tenha certeza de configurar o arquivo preload.js no vue.config.js:
// vue.config.js - project root
module.exports = {
  pluginOptions: {
    electronBuilder: {
       preload: 'src/preload.js'  //adicione essa linha
    }
  }
}

O arquivo preload.js:
// src/preload.js

import { contextBridge, ipcRenderer } from 'electron'

contextBridge.exposeInMainWorld('ipcRenderer', {
  send: (channel, data) => {
    let validChannels = ['nameOfClientChannel'] // <-- Array of all
    ipcRenderer Channels used in the client
    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data)
    }
  },
  receive: (channel, func) => {
    let validChannels = ['nameOfElectronChannel'] // <-- Array of all
    ipcMain Channels used in the electron
    if (validChannels.includes(channel)) {
      // Deliberately strip event as it includes `sender`
      ipcRenderer.on(channel, (event, ...args) => func(...args))
    }
  }
})

Outra solução pode ser encontrada nesse artigo:
Ela usa um parâmetro __static ao invés __dirname para se referenciar ao arquivo preload.js e não configura no vue.config.js. Para ter certeza que funciona precisa desabilitar o warning do es-lint para o preload.js dentro do construtor do BrowserWindow:
// eslint-disable-next-line no-undef
preload: path.resolve(__static, 'preload.js')

E tenha certeza que adicionou o arquivo preload.js dentro da pasta /public


Show and hide based on user role in rails

Question: I have the following code in my home.html.erb file;

<% if user_signed_in? %>

want to work on this?

<% else %>
are you a guru? want to work on this? Sign up.
<% end %>

Now as you can see I'm trying to have Seeker as a user role. Depending if that type of user with that type of role is signed in or not, different content is shown.
I have Devise + CanCan installed. Now very new to this and I've looked all over to see how to do this. I will have "Users" with normal roles of users and "Seekers" with seeker role. Using the above code only shows when a user is signed in, but not a seeker.
Is it as simple as seekers_signed_in? that I should be using? compare to user_signed_in? I've generated the Devise views for both Users and Seekers and Admins. Admins will be able to delete, update, etc. for users and seekers. Users post items and Seekers grab them.
Can anyone help?
Answer: You don't have to create Users& Seekers (two devise models), instead you can create only one model as common and call it User, then add as many roles as you need.
I recommend using this gem for easy roles configuration,
Then in your home.html.erb you simply do the following:

<% if user_signed_in? && current_user.is_seeker? %>

want to work on this?

<% else if !user_signed_in?%>
are you a guru? want to work on this? Sign up.
<% else%>
You are not a seeker, you need to be a seeker!
<% end %>

CanCan is used at Controller level, so the above approach is easy and direct for your case.
I hope this will help.
Comment: Hi, will that also work with an approach where Seekers and Users have different views ?? rather then just a simple home.html.erb page? -Thanks!
Comment: Because you can access user_signed_in? && current_user from any view, you will be able to check in any view wither the current_user is a seeker or not .. remember that its one User model, used in all your app, did you check the easy role gem?


Is there a common underdispersed discrete distribution with unbounded support for general mean and variance?

Question: I have a mean $\mu$ and a variance $\sigma^2$ with underdispersion, i.e., $\sigma^2<\mu$. Is there a standard discrete distribution with these moments and unbounded-on-the-right support, i.e., support on $\{0, 1, \dots\}$?
Bonus points if it is implemented in R.

I looked at the binomial-distribution, but that is only defined if the size parameter $\frac{\mu}{1-\frac{\sigma^2}{\mu}}$ is an integer.
The binomial and binomial compounds like the beta-binomial have bounded support.
So does the Generalized Poisson distribution (Consul & Jain, 1973) in the case of underdispersion, plus it can only handle underdispersion to a certain degree (note that Consul & Jain require $|\lambda_2|<1$ in formula (3.1)). The Generalized Poisson is Joseph Hilbe's main recommendation in this answer of his. His other recommendations might be useful, but he gives no details on them, and searching for the names is not very successful.
Sampling from under/over-dispersed count data in R is related but does not have a helpful answer.
Quasi-Poisson models sound like they may be useful (e.g., here), but I haven't been able to find anything helpful outside the context of a regression.
Comment: Hilbe's answer to this question https://stats.stackexchange.com/questions/67385/what-is-the-appropriate-model-for-underdispersed-count-data might be helpful.
Comment: The Conway-Maxwell-Poisson distribution has unbounded support and R packages, including one for regression, so may fit your requirements: https://en.wikipedia.org/wiki/Conway%E2%80%93Maxwell%E2%80%93Poisson_distribution.  When I looked at it some years ago, computation was very slow, but it looks like much faster algorithms have been developed since then.
Comment: @jbowman: Hilbe's main suggestion is the Generalized Poisson, which has bounded support if underdispersed. (I did find his answer when writing this question, upvoted it and looked through his *Negative Binomial Regression*.) His other suggestions might be helpful if there were just a few pointers to literature.
Comment: There are many possible answers. The most trivial is to add a sufficiently large integer to any lattice variable, thereby increasing $\mu$ without changing $\sigma^2.$  Even restricting distributions to those implemented in `R`, you could (for instance) reduce the dispersion by using $\lfloor X/k \rfloor$ for $k\gt 1$ with $X$ any non-negative variable (discrete or not).  As in almost all such cases, it's likely more constructive to articulate the *statistical* problem you are trying to solve so that a suitable choice of distribution (family) can be made.
Comment: Not familiar with applications of this, but how about $\sqrt{X},$ where $X \sim \mathsf{Pois}(\lambda)?$  `set.seed(1017); x=rpois(10^5,3); mean(sqrt(x)); var(sqrt(x))` returns $1.62883 > 0.3404474.$ Round or take floor if you need integers.
Comment: @BruceET: thanks, but that presupposes a very specific relationship between the mean and the variance, and I'd like for something that works for general moments.
Comment: @jbowman: thanks, that looks very helpful indeed! Do you want to post your comment as an answer?
Comment: @Stephan 1. When you say "unbounded" do you mean unbounded on both the left and right, or only on the right? I'd have thought you meant the first but several aspects of your question/comments suggest otherwise.  2. If you want an actual exponential-family quasi-Poisson distribution then I think it's just a scaled-Poisson. If that's underdispersed, it will be discrete but can't be restricted to be on the integers.
Comment: @Glen_b: 1. Only on the right. (I'd be interested in which of my comments suggest otherwise. Am I confused?) I edited the question to clarify. 2. I don't need an actual exponential family distribution, anything is fine.
Comment: @Stephan I initially interpreted "unbounded support" to imply unbounded in both directions (and likely would again in the same circumstances, unless there were other information); your comments and some aspects of your question suggested otherwise (i.e. that it was more like a count, and bounded on one side, rather than simply discrete and completely without bounds). I'm not criticizing the question, simply trying to be sure I understood the intent properly.
Comment: @whuber: I am (was) modeling retail sales. These are low volume count data, often intermittent (i.e., many zeros). The majority of such time series is overdispersed, and a negative binomial distribution makes sense. Sometimes, they turn out to be underdispersed, and I wonder what distribution would reasonably describe them. I have played around a bit with the Conway-Maxwell-Poisson per jbowman's answer, but if there is anything else, I would be interested.
Comment: The start of any effective search for a distribution to model your data ought to be with an analysis of the empirical distribution of those data (which may, and ideally ought, to include any information gleaned from an understanding of what those data mean and how they were generated).  Without any such information as a guide, there's nothing to say beyond outlining the purely mathematical description of the set of all such distributions.
Answer: The Conway-Maxwell-Poisson distribution (https://en.wikipedia.org/wiki/Conway%E2%80%93Maxwell%E2%80%93Poisson_distribution) has unbounded support (on the right) and can model both under- and over-dispersion (relative to the Poisson) seamlessly through the use of a single parameter.  The Poisson is a special case.  It can't handle any amount of underdispersion, though, and it is relatively computationally intensive.  It is a member of the exponential family of distributions.
R packages exist for both estimation and regression:
https://cran.r-project.org/web/packages/CompGLM/CompGLM.pdf
https://cran.r-project.org/web/packages/COMPoissonReg/COMPoissonReg.pdf
https://cran.r-project.org/web/packages/compoisson/compoisson.pdf
although I haven't used them so cannot make any helpful comments about their relative quality / usefulness!
Comment: From my recent experience, Generalized Poisson regression is not well supported in R,  CompPoissonReg is well established and good and DGLMExtPois (https://cran.r-project.org/web/packages/DGLMExtPois/index.html) is useful because it has the mean parametrized CMP, i.e. results are comparable to those from a regular GLM.


What are the effects of the shape of a bend in a brass instrument slide?

Question: Some brass instrument manufacturers make a feature of the shape of the various slides - some have a semi-circular wrap, other more semi-elliptical. Some have a tight wrap (the two legs of the slide are close together) or an open wrap (legs further apart).
My question is - what effect do the shape and tightness of the tubing wrap have on the sound and instrument playing response?
I'm asking because some manufacturer claims sound like voodoo to me - I'm wondering whether there are good physics reasons for choosing the shape of an instrument, or whether the choice of shape is mostly based on cosmetics and having an instrument that isn't tiring to hold, e.g. the centre of gravity is in a place where the instrument doesn't tip forward or backward when you're playing it.
Comment: You're not asking about trombone slides - they're round in section - so is it the tuning slides on trumpets, (also round?) or what?
Comment: Tuning slides are not semi-circular on every trumpet - there's considerable variety of curvature between models and manufacturers. All brass tubes are circular in cross-section - I'm asking about the shape after the straight tube has been bent into a slide.
Comment: Likewise, the U at the end of the trombone movable slide is not always semi-circular. It varies between manufacturers.
Comment: You can even have different shapes in the same instrument, see french horn in [wikipedia](https://en.wikipedia.org/wiki/French_horn#/media/File:French_horn_front.png). Both parts beneath the mouth piece can be removed for cleaning, as well as the parts at 10 o'clock and 8 o'clock positions.
Answer: Looks like you're asking two things: 1) the equation of the curve for the bent section at the end, 2) the variation in sound, if any, due to spacing between the 'out' and 'in' sections of the slide.
In any case, the answer is that there's next to no effect from the curve selection or the spacing.  The most likely effect might come from the choice of location of the stabilizer bar (welded in place perpendicular to the slide tubes), as that could affect harmonic vibration transfer.
Comment: Yep.  Given a constant circular cross section (which is the case here), it doesn't matter what the shape of the curve is acoustically.


Recursive Representation of Markov Process

Question: Let $(e_{t})_{t=0}^{\infty}$ be a sequence of $\mathbb{R}$ valued random variables defined on a common probability space $(\Omega, \Sigma, P)$; assume $(e_{t})_{t=0}^{\infty}$ is a Markov process with kernal $Q$ and initial distribution $\psi$.
We know the process $(e_{t})_{t=0}^{\infty}$  has a recursive representation. That is, there exists a measurable function $G\colon \mathbb{R}\times [0,1]\rightarrow \mathbb{R}$ such that the process defined by
\begin{equation}
\tilde{e}_{t+1} = G(\tilde{e}_{t}, \eta_{t})
\end{equation}
has the same distribution as $(e_{t})_{t=0}^{\infty}$ on $\mathbb{R}$. Where $(\eta_{t})_{t=0}^{\infty}$ is a sequence of i.i.d random variables uniformly distributed on $[0,1]$.
My question is, can we define $(\eta_{t})_{t=0}^{\infty}$ on the probability space $(\Omega, \Sigma, P)$? That is if I start with $(\Omega, \Sigma, P)$, fix it, have a Markov process $(e_{t})_{t=0}^{\infty}$ on $(\Omega, \Sigma, P)$, can $(e_{t})_{t=0}^{\infty}$ be written recursively on $(\Omega, \Sigma, P)$? Or do we have to construct a new space for $(\eta_{t})_{t=0}^{\infty}$ to be defined on?
My initial solution: we know how to construct $G$. Let $F^{-1}_{x}$ be the inverse of $Q(x, (-\infty, \cdot))$ for each $x$ and let $G(x,y)\colon = F^{-1}_{x}(y)$. (see Borokov, Probability Theory, p508). So I thought about defining $\eta_{t}(\omega) \colon = F_{e_{t}(\omega)}(e_{t+1}(\omega))$. Clearly we have $e_{t+1} = G(e_{t}, \eta_{t})$. However  I am lost to show that $(\eta_{t})_{t=0}^{\infty}$ is an i.i.d sequence on $(\Omega, \Sigma, P)$!
Answer:
Summary: The sequence $(\eta_t)$ that you suggest, is not independent in general.

We first rephrase the question, then we exhibit a setting where $(\eta_t)$ is indeed independent, finally we show that, in general, $(\eta_t)$ may not be independent.
In the post below, "increasing" means strictly increasing.
1. Rephrasing the question. Assume without loss of generality that, for every $t$, $$e_{t+1}=h(e_t,z_t)$$ for some measurable function $h$ and some i.i.d. sequence $(z_t)_{t\geqslant0}$ uniform on $[0,1]$ and independent of $e_0$. Let $\bar z$ denote yet again another random variable uniform on $[0,1]$ and independent of everything else. Also assume, again without loss of generality, that for every $x$, the function $h(x,\cdot)$ is nondecreasing on $[0,1]$.
Then, for every $(x,y)$, $F_x(y)=P(e_{t+1}\leqslant y\mid e_t=x)=P(h(x,\bar z)\leqslant y)$ and the question is whether the sequence  $\eta_t=F_{e_t}(e_{t+1})$ is independent.
2. In a specific case, the answer is positive. To show that indeed $(\eta_t)$ may be independent, consider the case when, for every $x$, the function $h(x,\cdot)$ is increasing on $[0,1]$.
Then each function $h(x,\cdot)$ is invertible hence $z_t$ is $\sigma(e_t,e_{t+1})$-measurable since $z_t=h(e_t,\cdot)^{-1}(e_{t+1})$.
Thus, $$\eta_t=P(h(e_t,\bar z)\leqslant e_{t+1}\mid e_t,e_{t+1})=P(h(e_t,\bar z)\leqslant h(e_t,z_t)\mid e_t,z_t)=P(\bar z\leqslant z_t\mid e_t,z_t)=z_t$$ which proves that in this case $(\eta_t)$ is indeed independent.
3. But in the general case... One can only assume that for every $x$, the function $h(x,\cdot)$ is nondecreasing on $[0,1]$, and then things can turn differently.
For a specific example, consider the case when $e_0=0$ and $$h(x,z)=(x+z)\,\mathbf1_{x\leqslant1}$$
Then $F_x(y)=P(x+\bar z\leqslant y)=P(\bar z\leqslant y-x)$ if $x\leqslant1$, and $F_x(y)=\mathbf 1_{y\geqslant0}$ if $x>1$. Thus, $\eta_t=z_t$ if $e_t\leqslant1$ and $\eta_t=1$ if $e_t>1$.
In particular, $[\eta_t=1]=[e_t>1]=[e_{t+1}=0]\subseteq[\eta_{t+1}=z_{t+1}]$ hence $[\eta_t=\eta_{t+1}=1]=\varnothing$ but one can check that, for every $t\geqslant2$, $P(\eta_t=1)>0$ since, again, $[\eta_t=1]=[e_t>1]$. Thus, $(\eta_t)$ is not independent.
Comment: I wonder if there is another sequence that is independent? That is can we still define $(e_{t})_{t}^{\infty}$ recursively on the original prob space?


Como fazer validação de checkbox no Ruby on Rails?

Question: Eu estou estudando ruby on rails e pouco tempo, e um dos exercicios que estou tentando fazer é um checkbox e um botão submit em uma página haml, o objetivo é que o botão submit só funcione caso o checkbox esteja marcado, caso não apenas dê uma mensagem genérica como "Complete os campos", como posso fazer isso?
Answer: O Rails tem um validador chamado acceptance_of. É utilizado quando você tem um booleano e quer verificar se esse valor é verdadeiro.
class Person < ApplicationRecord
  validates :terms_of_service, acceptance: true
end

Veja mais validações do Rails na documentação.
Quando você chamar model.save, verifique o seguinte:
if person.save
  # successo!
else
  # erro :(
  person.errors.full_messages
  # => [ { terms_of_service: "must be accepted" }]
end

Comment: No botão do submit em si eu preciso passar o valor do acceptance? ou no checkbox? Só precisa do model e controller? Ainda não peguei muito bem o jeito do haml
Comment: @dfop02 no model


What is wrong in my LOAD DATA INFILE Syntax?

Question: I'm trying to import a CSV file into MySQL database but it didn't work.
I have 5 columns in my database:

id , userID, movieID, rate, timestamp

And in my CSV file I have only 4 columns separated by two colons '::'.
This is the sample data:

1::1193::5::978300760

This is my query

$query = "LOAD DATA INFILE '$uploadfile'          INTO TABLE rating_table
            FIELDS TERMINATED BY '::'           LINES TERMINATED BY '\n'            (
  userID, movieID, rate, timestamp)";

And I'm using PDO_MySQL this is the additional code so that you can understand.
$stmt = $dbh->prepare($query);

try{
        if($stmt->execute()){
                echo "Sucessful importing of CSV file into the MySQL database!";
            }

    }
catch (PDOException $e) {
    echo "Error importing of CSV file into the MySQL database!";
    echo "Error!: " . $e->getMessage() . "
";
    die();
}
echo "
";

I've tried many times but when I've checked in my database, it is still empty.
I can't seem to figure out what is wrong, can you help me? Thanks!
This is the error I've got.

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while
  other unbuffered queries are active. Consider using
  PDOStatement::fetchAll(). Alternatively, if your code is only ever
  going to run against mysql, you may enable query buffering by setting
  the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.' in
  C:\xampp\htdocs\movie\php\upload_file.php:57 Stack trace: #0
  C:\xampp\htdocs\movie\php\upload_file.php(57): PDOStatement->execute()
  1 {main} thrown in C:\xampp\htdocs\movie\php\upload_file.php on line 57

This is my connection settings:

$dbh = new PDO('mysql:host=localhost;dbname=movie','root', '',
      array(
          PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8",
          PDO::ATTR_EMULATE_PREPARES => FALSE,
          PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,      PDO::MYSQL_ATTR_LOCAL_INFILE => TRUE
          ));
Comment: You have 5 fields in your SQL, but only 4 columns in the file.
Comment: Are you getting an error?
Comment: @Barmar, That's my problem, I don't get any error.
Comment: Can you run the statement by hand in a mysql session and get it to work with a local file?
Comment: @Barmar, Yes Sir do you think that is causing the problem?
Comment: It could be. What are you trying to set `@count` to?
Comment: Hmm, what happened to `@count` in your question?
Comment: @Harvey, please take a look at my answer, you might need additional inits, like `PDO::MYSQL_ATTR_LOCAL_INFILE => TRUE`, post an error output after setting `PDO::ATTR_ERRMODE`.
Comment: @Barmar, Sir sorry, I've already edited my post. Thanks!
Answer: In order to see error messages on your output, just initialize your PDO with PDO::ERRMODE_EXCEPTION, something like this:
$db = new PDO('mysql:host=' . $config['db_host'] . ';dbname=' . $config['db_name'], $config['db_username'], $config['db_password'],
    array(
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8",
        PDO::ATTR_EMULATE_PREPARES => FALSE,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ));

Afterwards you will be able to see the error. Post it in an update and I/we will be able to help you out!
EDIT 1:
Take a look at the manual on PDO_MYSQL.
You might also need:
PDO::MYSQL_ATTR_LOCAL_INFILE => TRUE

Note, this constant can only be used in the driver_options array when
  constructing a new database handle.

EDIT 2:
According to MySQL Manual, MySQL must be compiled with --enable-local-infile:

You MUST have compiled PHP using the full path to MySQL, otherwise it
  will use it's internal handlers, which don't work with the "new" LOAD
  DATA.
--with-mysql=/usr/local/mysql (assuming your MySQL is located here)
You MUST start the MySQL daemon with the option '--local-infile=1'

Or enabling it, by adding to your /etc/my.cnf:
[mysql]
local-infile=1

[mysqld]
local-infile=1

Restart mysqld afterwards, by running service mysqld restart.
EDIT 3:
Quotes are for string literals, back-ticks for columns and tables names. Escape a variable properly. Change your query to:
$query = "LOAD DATA INFILE ' . $uploadfile . ' INTO TABLE `rating_table` FIELDS TERMINATED BY '::' LINES TERMINATED BY '\n' ( `userID`, `movieID`, `rate`, `timestamp`)";

EDIT 4:
This error is normally caused when you have multiple queries open at the same time. For example, you call fetch(), but you don't call it until it's finished, and then you try to execute a second query.
Normally, the solution to this problem is to call closeCursor() PHP: PDOStatement::closeCursor - Manual.  Try calling that:
/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();

/* Now we can execute the second statement */
$otherStmt->execute();

and see if that changes anything for you.
EDIT 5:
Try using other syntax for escaping variable. Use the following:
$stmt = $dbh->prepare("
       LOAD DATA INFILE
          '" . $uploadfile . "'
       INTO TABLE
          `rating_table`
       FIELDS TERMINATED BY
          '::'
       LINES TERMINATED BY
          '\n' ( `userID`, `movieID`, `rate`, `timestamp`)
");
$stmt->execute();

EDIT 6:
PDO placeholders can only be used for values, and not database, table or column names! I think the error is coming from using '::'. Change your data delimiter in your files from '::' to, let's say '.'.
As quick workaround for checking you could use your query directly without prepare:
$stmt = $dbh->query("
       LOAD DATA INFILE
          '" . $uploadfile . "'
       INTO TABLE
          `rating_table`
       FIELDS TERMINATED BY
          '::'
       LINES TERMINATED BY
          '\n' ( `userID`, `movieID`, `rate`, `timestamp`)
");

If it doesn't work try changing data delimiter or try escaping your existing delemiter (::) somehow.
Comment: Sir, I've already edited my post and include there the error. Thanks!
Comment: What about setting `PDO::MYSQL_ATTR_LOCAL_INFILE => TRUE`, have you tried that?
Comment: Sir, I have edited the error in my post and I think I'm close enough in solving it.
Comment: @Harvey, please take a look at `EDIT 3`, this might solve you problem! If it doesn't work try removing `' . . '` completely.
Comment: I tried to insert single-quote in `$uploadfile` So it becomes like this `$query = "LOAD DATA INFILE '$uploadfile' INTO TABLE `rating_table` FIELDS TERMINATED BY '::' LINES TERMINATED BY '\n' ( userID, movieID, rate, timestamp)"; . It gives a different error from the one that I've posted above.
Comment: Here's the error. `Error importing of CSV file into the MySQL database!Error!: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.`
Comment: What do you use after `$query`?
Comment: This line `$stmt = $dbh->prepare($query);` comes after the query.
Comment: And then..? And then..?
Comment: Sir, I've only one statement. This is my only statement `$stmt = $dbh->prepare($query);` following the query. After that the `try catch` statement.
Comment: That is wired as you don't execute your query? No wonder you get an error. Run either instead `$stmt = $dbh->query($query);` or better add afterwards `$stmt->execute();`
Comment: Yes Sir I have this on the try, `  if($stmt->execute()){
    echo "Sucessful importing of CSV file into the MySQL database!";
   }`
Comment: Try removing that `try` and `catch` stuff. Just run it normally. You don't need it in every query. You don't need it at all, I think!
Comment: Take a look at `EDIT 5` and post what happens when you `echo $uploadfile`, please!
Comment: Sorry for the late reply. Ahm Sir I've tried your EDIT 5 and I echoed the `uploadfile`. This is the output of `uploadfile`-> `C:\xampp\htdocs\movie\uploads\movieratings.dat` and below is the error, and the same error Sir.
Comment: This is the error:
`Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.' in C:\xampp\htdocs\movie\php\upload_file.php:67 Stack trace: #0 C:\xampp\htdocs\movie\php\upload_file.php(67): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\movie\php\upload_file.php on line 67`
Comment: Sure, I see! What do you get if you do: `echo readfile($uploadfile);`
Comment: It returns the content of the file. Like this -> `1::1193::5::978300760 1::661::3::978302109 1::914::3::978301968 1::3408::4::978300275 1::2355::5::978824291 1::1197::3::978302268 1::1287::5::978302039 1::2804::5::978300719 1::594::4::978302268 ...`
Comment: Okay...but how will I be able to change the delimiter on my files? I've only downloaded it on the movielens dataset.
Comment: You can go with `$data  = str_replace('::', '.', file_get_contents($uploadfile));`
Comment: I've done EDIT 6, replace the '::' with '.'and use query directly without prepare but the same error.
Comment: You could try `"::"` but I'm not sure! Double check your query! Try to re-saving your file to make sure the encoding is set correctly on the file. It's hard to debug without access to executable code! It could be anything!
Comment: Okay I understand. I think what can I do now is to look for other ways in saving CSV file or importing it into MySQL. Thank you for your help Sir. I appreciate it. :)
Comment: You're welcome! Pay attention to reading http://dev.mysql.com/doc/refman/5.7/en/load-data.html carefully.
Answer: You are probably missing LOCAL keyword in your LOAD DATA INFILE statement.
LOCAL means that the file you are loading from is located on the client and not on the server. When I just tried this, with your table and file, it worked fine.
> cat infile.csv
1::1193::5::978300760

> mysql
mysql > create table ratings (
    id int primary key auto_increment,
    userID int,
    movieID int,
    rate int,
    ts long);
Query OK, 0 rows affected (0.06 sec)

mysql > LOAD DATA LOCAL INFILE 'infile.csv' INTO TABLE ratings FIELDS TERMINATED BY '::' LINES TERMINATED BY '\n' ( userID, movieID, rate, ts);
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql > select * from ratings;
+----+--------+---------+------+-----------+
| id | userID | movieID | rate | ts        |
+----+--------+---------+------+-----------+
|  1 |      1 |    1193 |    5 | 978300760 |
+----+--------+---------+------+-----------+
1 row in set (0.00 sec)

Comment: Try to put it somewhere simple, like c:\testfile.csv, to start with. That way you can eliminate problems you do in php or problems with mysql. Also try to run the command using normal mysql client.
Comment: I've added the `LOCAL` keyword but I think your close. Ahm to elaborate I have this code `$uploaddir = 'C:\xampp\htdocs\movie\uploads\movie';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);` and I used `$uploadfile` in my query. Is this the correct way of doing it?
Comment: @Harvey did you confirm that your $uploadfile actually exists at that location with file_exists?
Comment: @eis, Yes Sir, I've verified, checked it using `file_exists` and Yes it existed.
Comment: I tried what you've said put it in my local disk C, and modified the path to be able to read it in the local disk C but the same error I've got Sir.


Alternative to AIC for feature selection in classification

Question: I want to know what are the most common methods for feature selection in classification problems (binary and mutli-class).
I see in Chapter 6 of Zumel and Mount that they use AIC before they train classification algorithms (trees, logistic regression, kNN) on a classification problem with both categorical and numerical features. They compute AIC as $2\,\left(\log L- \log L_{base}\right)-2^S$ for categorical variables, and  $2\,\left(\log L- \log L_{base}\right)-1$ for numeric variables ($L$ is likelihood, $L_{base}$ is likelihood of the saturated model, $S$ is entropy). They keep features with AIC above a certain threshold, which presumably can be modified to improve algorithm performance.
What are the alternatives, and when should I consider using them? In specific, how should I do feature selection if I plan to train with a boosting algorithm (adaboost or gbm)? Are there any dangers in throwing all the noisy variables (without any feature selection) to adaboost or gbm, as they seem to not be perfectly immune to overfitting?
Answer: James et al. (2013), An Introduction to Statistical Learning strongly focus on cross-validation (CV) as a means to prevent overfitting. See also Hastie et al. (2009), The Elements of Statistical Learning.
Under certain circumstances, AIC and CV essentially do the same thing, but there are important cases where CV is more flexible.
The link links to the free e-version of the book, so I hope you bear with me if I do not rehash their explanations here in what could only be an inferior way of doing so.
Comment: No problem with not repeating material from the books. I'll wait a couple of days in case someone else weighs in, before accepting an answer. Thanks!